How do I add memoization to this problem? Problem
Starting in the top left corner of a 22 grid, there are 6 routes (without backtracking) to the bottom right corner.

How many routes are there through a 2020 grid?

Solution
Here is my solution

    def step(i,j):
    if(i==20 or j==20):
        return 1
    return step(i+1,j)+step(i,j+1)
print step(0,0)

But this takes too long to run, how can this be optimized?

Finally my memoization technique worked and the result appears in less than a sec

    cache = []
for i in range(20):
    cache.append([])
    for j in range(20):
        cache[i].append(0)

def step(i,j):
    if(i==2 or j==2):
        return 1
    if(cache[i][j]>0):
        return cache[i][j]
    cache[i][j] = step(i+1,j)+step(i,j+1)
    return cache[i][j]
print step(0,0)

Another optimization I have added (since step(i,j) is same as step(j,i))

    cache = []
for i in range(20):
    cache.append([])
    for j in range(20):
        cache[i].append(0)

def step(i,j):
    if(i==20 or j==20):
        return 1
    if(cache[i][j]>0):
        return cache[i][j]
    cache[i][j] = step(i+1,j)+step(i,j+1)
    cache[j][i] = cache[i][j]
    return cache[i][j]
print step(0,0)


Projecting future positions My code takes a starting position (which must be completed) and a list of updates (each element of which is optional). It then projects future positions, using the appropriate value from each update, if present, or using a formula otherwise.

I'm looking for ways to reduce code duplication, especially as the real data structures will be substantially larger.

In particular:

Is there a better way for the type system to express the fact that ResultForDate is the same structure as InputForDate but with all option values replaced by the underlying types?
Can the duplication be removed from the repetitive code which checks for the existance of an input, uses it if possible and uses a formula otherwise? Perhaps using a monad?

module Demo

open System

type InputForDate = { Date: DateTime; AssetValue: option<float>; InterestRate: option<float> }
type ResultForDate = { Date: DateTime; AssetValue: float; InterestRate: float }

let projection (startingInput: ResultForDate) (futureInputs: InputForDate list) =
    let project (previousYear: ResultForDate) (input: InputForDate) : ResultForDate =
        {
            Date = input.Date;
            AssetValue =
                match input.AssetValue with
                | Some x -> x
                | None -> previousYear.AssetValue * (1.0 + previousYear.InterestRate) ;
            InterestRate =
                match input.InterestRate with
                | Some x -> x
                | None -> previousYear.InterestRate
        }
    List.scan project startingInput futureInputs

// example of use

let startingInput = { ResultForDate.Date = new DateTime(2012, 12, 31); AssetValue = 100.0; InterestRate = 0.05 };

let futureInputs = [
    { InputForDate.Date = new DateTime(2013, 12, 31); AssetValue = Some 110.0; InterestRate = Some 0.04 };
    { Date = new DateTime(2014, 12, 31); AssetValue = None; InterestRate = Some 0.03 };
    { Date = new DateTime(2015, 12, 31); AssetValue = None; InterestRate = None } ]

let result = projection startingInput futureInputs

The code duplication problem can be solve using Operators.defaultArgs, which does pretty much what you're trying to do

AssetValue =
    match input.AssetValue with
    | Some x -> x
    | None -> previousYear.AssetValue * (1.0 + previousYear.InterestRate) ;
InterestRate =
    match input.InterestRate with
    | Some x -> x
    | None -> previousYear.InterestRate

to

AssetValue = defaultArg input.AssetValue <| previousYear.AssetValue * (1.0 + previousYear.InterestRate)

InterestRate = defaultArg input.InterestRate previousYear.InterestRate

I don't really have an idea for your data type. You both of your type doesn't have the same fields types, so you can't really inherit. And since both of your fields are optional, you can't really compose with another record.


Device limitation rule for user I've created a simple application for mobile users, they can login using provided API but must have limitation on the devices, so the requirement is simple :

  User cannot login using more than 2 devices

I'm building the API using laravel for mobile apps, so I've created the function and it works correctly and wrote test and it works fine you can find the full code here.

But I would like to know what are you guys think of this code :

public function isLoginValid2($user_id,$device_id){

        $deviceLimit = 2;

        //retrive device or create new one if doesnt exist
        $params = [
            'user_id' => $user_id,
            'device_id' => $device_id
        ];

        $device = Device::where($params)->first();

        if (!$device) {

            // check if not exceed limit
            if (Device::where(['user_id'=>$user_id, 'is_banned'=>false])->count() <= $deviceLimit) {
                return true;
            }else{
                // the device is above llmit
                return false;
            }

        }else {
            // check if banned
            if ($device->is_banned) {
                // the device is banned user is not pemmitted to login
                return false;
            }else{
                return true;
            }
        }

    }

As for the code above if we take a look there are some code line that we can modify or move to create another function.

The reason why I did it because I can make a unit test case on every function and make sure everything is work. so the code above I've modified it and become like this :

public function isLoginValid2Refactored($user_id,$device_id){
        if($this->isDeviceExistWithUser($user_id,$device_id)){
            //device is exist check if its banned
            if($this->isDeviceBanned($device_id)){
                return false;
            }else{
                return true;
            }
        }else{
            //device is not exits check device limit
            if($this->isUserReachLimitDevice($user_id)){
                //user reach limit device
                return false;
            }else{
                return true;
            }
        }
    }

So from here I created another function called isDeviceExistWithUser and isUserReachLimitDevice any better idea to write testable?  Or any better improvement so I others can read it easily?

$device = Device::where($params)->first(); will either return an instance of eloquent or null.

You have if (!$device) {...}else{...}.

This translates to if the device is not found aka the else part then $device->is_banned which will results in a trying to get property of non-object fatal error.

if ($condition) {
    return false;
}else{
    return true;
}

The else is not necessary since return will immediately end the execution of the function and return the result.

if ($condition) {
    return false;
}
return true;

Works just the same and I personally find it more visually pleasant.

$this->isDeviceExistWithUser($user_id,$device_id)

Syntax heavy naming. You could simple call it deviceForUser or something like that. is usually suggests a boolean, as in isDevice, isSmall, isLarge etc etc.

$this->isDeviceBanned($device_id)

Nitpick but a simple isBanned will do here since you passing in $device_id, clearly a device is the scope here.

isLoginValid2Refactored

Again really heavy name here. It's not something inherently wrong with it, but the lighter the better. Fluent and easy to understand goes a long way.


Try-catch flow to handle two failing services We need to create a car with apiCar and log in two places CosmosDB and the logger, whether there is an error or not. Except if the error happens in Cosmos, in that case we only log in the logger. Finally, if there is an exception, any exception, we need rethrow it so the "MyFunction" caller can handle it.
This is my best shot that works but I don't like it. Is there any way to improve it?
public async Task MyFunction(Car car)
{
    try
    {
        var apiCar = await _APIService.CreateAsync(car);
        car.Status = CarStatus.Created;

        _logger.LogInformation("Created apiCar for car: {carId}", car.Id);
    }
    catch (ApiErrorException exception)
    {
        _logger.LogError(exception, "API exception for car: {carId}", car.Id);
        car.Status = CarStatus.Error;
        car.ErrorMessage = exception.Body.Error.Message;
    }
    catch (Exception exception)
    {
        _logger.LogError(exception, "Exception for car: {carId}", car.Id);
        car.Status = CarStatus.Error;
        car.ErrorMessage = exception.Message;
    }

    try
    {
        await _cosmosService.UpdateItemAsync(car);
    }
    catch (CosmosException exception)
    {
        _logger.LogError(exception, "Cosmos exception for car: {carId}", car.Id);

        throw;
    }

    if (car.Status == CarStatus.Error)
    {
        throw new Exception();
    }
}

First, any async function should end with Async, ie MyFunctionAsync. You can see examples of this in the other async functions you're calling throughout your code.
As to your requirements, the exception you throw at the end is devoid of any useful information. It has no exception origination information (line number etc) and no correct stack trace. Either save the exception you're handling in the top try when it happens, or even better rethrow it on the spot.
I very much question your updating the item even though the first part errored out, so rethrowing the first set of exceptions on the spot is what I'd do, but if you want to update it even in an error case, bring the update function with you in the catch and then rethrow.
The second part is fine, you're rethrowing as you should.


Simplify Raphael JS code: display text in DIV on click event I've been working with the RaphaelJS 'australia map' example that displays text in a DIV when a state is clicked on. However I'm having difficulty working with it to create different events and functions.

I want to be able to duplicate the 'display text' function for two different element onClick events (i.e. have two different buttons (elements) that do the same thing). But the current code is a bit too complicated for me. Can somebody please help me simplify the code that displays the text in a DIV when an element is clicked on.

Any help would be much appreciated - this is what I'm currently working with jsfiddle.

 window.onload = function () {
    var R = Raphael("paper", 532, 500);
    var attr = {
        fill: "#0B0",
        stroke: "#fff",
        "stroke-width": 3,
    };
    var ctx = {};
    ctx.btn_1 = R.path("M 180,130 L 340,130, L 392,212, L 128,212 z").attr(attr);
    ctx.btn_2 = R.path("M 128,212 L 392,212, L 435,280, L 85,280 z").attr(attr);

    var current = null;
    for (var state in ctx) {
        (function (st, state) {
            st[0].style.cursor = "pointer";
            st[0].onmousedown = function () {
                current && (document.getElementById(current).style.display = "");
                st.toFront();
                R.safari();
                document.getElementById(state).style.display = "block";
                current = state;
            };
        })(ctx[state], state);
    }
 };

I agree with tiffon it's better to extract a function, but I don't agree with the rest of their edits, so here's what I would have done (I also kept the style intact).

var initPath = (function () {
    var currentEl;

    function init(el, path) {
        path.attr({
            fill: "#0B0",
            stroke: "#fff",
            "stroke-width": 3,
        });

        path[0].style.cursor = "pointer";
        path[0].onmousedown = function () {
            currentEl && (currentEl.style.display = "");

            path.toFront();
            path.paper.safari();

            el.style.display = "block";
            currentEl = el;
        };
    }

    return init;
})();

window.onload = function () {
    var R = Raphael("paper", 532, 500);
    var paths = {
        'btn_1': R.path("M 180,130 L 340,130, L 392,212, L 128,212 z"),
        'btn_2': R.path("M 128,212 L 392,212, L 435,280, L 85,280 z")
    };

    for (var id in paths) {
        initPath(document.getElementById(id), paths[id]);
    }
};

Firstly, I think st and state were confusing names, so I changed them to be path and id, respectively, and then changed id to el to avoid additional lookups.

I separated the infrastructure (current and initPath) from the usage (R, paths and the loop).

I also think an object literal looks better than a series of assignments, so I changed that.

Finally, I like it better if I move initPath and currentEl into a closure of their own—after all, they don't depend on window.onload anymore.

I left the inner init a named function so it is named in a stack trace, if there is an error.


Accessing Data inside Presentation Layer from API: Laravel 5.2.27 I wrote the code to fetch the JSON Data. For that I tried to do this in 2 projects.

  First Laravel project which has API code for database interaction only.

Sample code in API controller

class CountryAPI extends Controller
{
    public function AllCountries() {
        return response()->json(['CountryList' => \App\Models\CountryModel::all()]);
    }
}

  Second Laravel project which is a Presentation Layer that has code to access data from an API. So, Database is not exposed directly in this
  layer, instead a URL is being used to access data.

Sample code in the Presentation Layer

class CountryController extends Controller {

    public function AllCountries() {
        $url = "http://localhost/API/public/Countries";
        $json = file_get_contents($url);
        $json_data = json_decode($json, true);
        return view('Country.List', array("Countries" => $json_data["CountryList"]));
    }
}

Then inside the View it is like below.

@foreach($Countries as $Country)

        {{$Country["Country"]}}
        {{$Country["CountryCode"]}}

@endforeach

This is just a beginning to learn how to isolate the database code from Presentation Layer.

Question: Is there problem in below points?

  Code Quality
  Approach to fetch data in Presentation layer from API.
  As website users will send request to website and then website will send request to Database server through an API. So each requests will have one in direct additional request. Is that good?

Reason I asked this because Data has to be accessed from Android as well as from Website

This looks like a good place to use a shared repository. If you used a repository that was shared between your android api server app and your web server app you could avoid the need for inter-server communications and translating to and from json. You'd get better performance and the repository would function as the middle tier of your 3-tier architecture.

Repositories in Laravel are a fairly large topic so I'll just point you at Laracasts for that. For using a shared model in more than one project, this thread gives an example of doing it via composer:

https://laracasts.com/discuss/channels/general-discussion/share-models-between-two-laravel-projects?page=1

That's not to say there is anything particularly wrong with the architecture you're describing. It shouldn't have too much of a performance hit but it will have a hit from the communications aspect and the translation to and from json aspect. Both of which are small as long as you stay within your local LAN. You seem to be accessing localhost for the API so it shouldn't be a problem.


Monty Hall simulator in Python 3.x I've been working on Python for the past few weeks trying to get my head around it's syntax/naming conventions/style/etc. I decided to make a monty hall sim to see how it looks in python. For those who don't know what the Monty Hall problem is, check the second paragraph here.

I've verified the code is fully functional and gives the right results. It IS indeed best to swap every time. After spending time getting rid of duplicated effort, overly wordy statements, and many logic errors, I'd like to know how to improve my code readability and efficiency (both here and in general).

Specific to this code, here's what I'd like to know (mostly #1):

If possible, how could I make this more efficient?
Is having a function call in the first for loop a good idea? If not, where do I put it?
I keep feeling like this is longer than needed. Are there still places I can cut out code?

import random

def setup():
    # Basic greeting/explaining what to do.
    print("\n\nThere are 3 doors. One is a winner. The computer")
    print("will try guess the right one. After the first ")
    print("guess, one door is shown to be a loser. The computer ")
    print("can then change it's choice to the remaining door.\n")

    # Display choices and get input
    change_choice = input("Should the computer always change it's choice? y/n\n:> ")
    runs = int(input("How many times should this run?\n:> "))
    run(change_choice, runs)

def run(change_choice, times_to_run):
    wins = 0 #Correct door choices

    # Loop through calling the function with switching enabled or not
    for i in range(times_to_run):
        if change_choice == 'y' or change_choice == 'Y':
            wins = wins + setupDoors(True)
        else:
            wins = wins + setupDoors(False)

    # Display amount of times won/percentage of games won
    statistics(wins, times_to_run)

def setupDoors(always_change_choice):
    # Set up the winning door
    winning_door = random.randint(1,3)
    print("\nThe winning door is "+str(winning_door))

    # Get the computer's guessed door
    computer_guess = random.randint(1,3)
    print("the computer guessed door number "+str(computer_guess))
    return playGame(winning_door, computer_guess, always_change_choice)

def playGame(winning_door, computer_guess, always_change_choice ):

    # Get the right door to open.
    # Can't be the computer's door OR the winning door
    opened_door = getAvailableDoor(computer_guess, winning_door)
    print("Door number "+str(opened_door)+" was opened and shown not to be a winning door.")

    #Swap the computer's choice to last door if that was desired
    if always_change_choice:
        computer_guess = getAvailableDoor(computer_guess, opened_door)
        print("The computer changed it's guess to door number "+str(computer_guess))

    # Return a win or a loss.
    if computer_guess == winning_door:
        print("The computer won!")
        return 1
    else:
        print("The computer lost!")
        return 0

def getAvailableDoor(computer_guess, unavailable_door):
    # List of doors to choose from
    Doors = [1,2,3]

    for i in range(3):
        if Doors[i] == computer_guess or Doors[i] == unavailable_door:
            continue
        else:
            break
    return Doors[i]

def statistics(wins, times_to_run):
    print("\nThe computer won "+str(wins)+" times")
    print("This means the computer won "+str((wins/times_to_run)*100)+"% of the time")

setup()

Readability:

you should have 2 newlines after each function definition
you should use augumented assignments where possible
you should define each method in a logical order (e.g: if you're calling a function inside another function, the later should be defined first). That's rather a personal preference because you can't do this everytime.
you should have a space around operators and delimiters
you should make your print() statements more compact
variable names should be snake_cased. The same goes for method names.
at the beginning of each function you should define a docstring

Now, let's dig into each function:

in def statistics() you should use format() and join those two prints into a single one:

def statistics(wins, times_to_run):
    """Print the statistics"""
    print("The computer won {} times"
          "This means the computer won {} % of the time".format(wins, (wins / times_to_run) * 100))

as mentioned above:

def setup_doors(always_change_choice):
    """Set up the winning door"""
    winning_door = random.randint(1, 3)
    computer_guess = random.randint(1, 3)

    print("The winning door is {}.\n"
          "The computer guessed door number {}".format(winning_door, computer_guess))

    return play_game(winning_door, computer_guess, always_change_choice)

in def run(change_choice, times_to_run) you should avoid that multiple condition by using the lower function. You can also use the enumerate() to get rid off that variable definition, and replace i by _ as you don't use it:

def run(change_choice, times_to_run):
    """Some description here"""
    for wins, _ in enumerate(range(times_to_run)):
        if change_choice.lower() == 'y':
            wins += setup_doors(True)
        else:
            wins += setup_doors(False)

    # Display amount of times won/percentage of games won
    statistics(wins, times_to_run)

in def setup() I'd just join the print statements:

def setup():
    """Basic greeting/explaining what to do."""
    print("\n\n"
          "There are 3 doors. One is a winner. The computer \n"
          "will try guess the right one. After the first \n"
          "guess, one door is shown to be a loser. The computer \n"
          "can then change it's choice to the remaining door.\n")

    # Display choices and get input
    change_choice = input("Should the computer always change it's choice? y/n\n:> ")
    runs = int(input("How many times should this run?\n:> "))
    run(change_choice, runs)

// To be continued. I have to leave the office.


Inserting into a linked list I know that this is very very basic, but now I am starting from group up after getting frustrated with my coding practices and knowledge of standard idioms out there and elegant way of coding corner cases. The problem is to insert into tail of a linked list.

void insertattail (struct node *head, int data)
{
  //First construct the node in newp
  struct node *newp;
  struct node *p;
  newp = malloc (sizeof (struct node));
  newp -> data = data;
  newp -> next = NULL;

  // Standard name for node pointers only used for traversal? p? q? tmp?
  // if more than 1 kind of nodes?
  // Then what about temp pointers for swapping etc but not exactly for traversal?

  if (head == NULL)  // is there more elegant way of dealing with this? any idiom?
  {
    head = newp;
    return;
  }

  for (p=head; p->next != NULL; p++)
    ;
  p->next=newp;
}

if(head == NULL)  // is there more elegant way of dealing with this? any idiom?
{
head=newp;
return;
}

head is a local variable in this function. Modifying it will not change the variable that was passed into the function. As a result, the new node you create isn't attached to anything that the caller can access. If you want to modify a variable being passed in you need to use a pointer. If you want to modify a pointer, you need to use a pointer to a pointer.

Here is a version which reduces the amount of code, but for those who don't think in pointers naturally it may be hard to follow.

// I take a pointer to a pointer so that I can modify it if need be.
void insertattail(struct node **head,int data)
{
    // advance the pointer until it reaches NULL
    // because its a pointer to a pointer I can modify it
    while(*head != NULL) head = &(*head)->next;

    // replace that NULL with a new node
    *head = malloc(sizeof(struct node));
    // fill up the node
    (*head)->data = data;
    (*head)->next = NULL;
}


Check if a given string can be a palindrome by altering some character without using a library function I was asked in an interview to write code to check if a given string is a palindrome or can be a palindrome by altering some character without using library function.

My logic is to:

Compare 1st char with remaining chars. If it exists, remove both from array using removeElement().
If it does not exist in the char array, then use removeFirstElement() to remove the first element 1 time only.
chackPotentialPalindrom() returns true if a String can be a palindrome, otherwise false.

package package1;

import java.util.Scanner;

public class Palindrom {
    static int  temp=0;
    static char[] cArr;
        static boolean chackPotentialPalindrom(char[] cAr){
            cArr=cAr;
            if(cArr!=null){
                char current=cArr[0];
                for(int i=1;i<cArr.length;i++){
                    if(current==cArr[i]){
                        cArr=removeElement(i);
                        chackPotentialPalindrom(cArr);
                        break;
                    }
                    }
                if(cAr.length==2){
                if(cAr[0]==cAr[1]){
                    cArr=null;
                }}
                if(temp==0 && cArr!=null){
                    temp=1;
                    cArr=removeFirstElement(cArr);
                    chackPotentialPalindrom(cArr);
                    }
                }
            if(cArr==null){
                return true;
            }else{
                return false;
            }
        }
        static char[] removeFirstElement(char[] cAr){
            cArr=cAr;
            if(cArr!=null){
            if(cArr.length >1){
            char[] cArrnew=new char[cArr.length-1];
            for(int j=1,k=0;j<cArr.length;j++,k++){
                cArrnew[k]=cArr[j];
            }
            return cArrnew;
            } else {
                return null;
            }
                } else {
                    return null;
                }
        }
        static char[] removeElement(int i){
            if(cArr.length>2){
            char[] cArrnew=new char[cArr.length-2];
            for(int j=1,k=0;j<cArr.length;j++,k++){
                if(i!=j){
                    cArrnew[k]=cArr[j];
                }else{
                    k-=1;
                }
            }
            return cArrnew;}
            else{
                return null;
            }
        }
        public static void main(String[] args) {
            Scanner scn=new Scanner(System.in);
            while(true){
                temp=0;
            String s=scn.next();
            char[] arr=s.toCharArray();
            System.out.println(chackPotentialPalindrom(arr));
            }
        }
    }

Any tips to optimize this code?
I could not write this in an interview as they have given a pen and paper to code.
It took 3 hrs for me to write this. Can I be a developer?

The above looks to be more work than is necessary. Assuming that we are working with all lower case chars, the following should work.

We match the chars at each end, moving inwards on each cycle. Normally, if any do not match, we consider it a fail and break out. If we are allowed a one pair mismatch (i.e. change one character), then we need to keep track of the count of mismatches and if we have 0 or 1 (less than 2) we consider it to be a palindrome.

private static boolean isAlmostPalindrome(String str){
    int diffCount = 0;
    int left = 0;
    int right = str.length() -1;

    while(right>left){
        if (str.charAt(right--)!= str.charAt(left++)){
            diffCount++;
        }
    }
    return diffCount <2;
}


Multiplying/Dividing before Adding/Subtracting I'm working on a calculator for educational purposes and was asked to include a rule that multiplies/divides before it adds/subtracts.

Let's assume I have the following equation:

2 + 2 * 2

Windows built-in calculator would return 8, since it just goes down the line without parantheses.

The correct answer however would be 6.

So my code first splits the entire equation into a List<string>:

string equation = "2 + 2 * 2"
List<string> equationList = equation.Split(' ').ToList();
//Result:
//2
//+
//2
//*
//2

Then it checks if equationList contains an asterisk or slash:

if (equationList.Contains("*")) equationList = PunktVorStrich("*", equationList);
if (equationList.Contains("/")) equationList = PunktVorStrich("/", equationList);

This automatically calls the following function PunktVorStrich:

private List<string> PunktVorStrich(string symbol, List<string> equationList)
{
    while (equationList.Contains(symbol))
    {//loops in case there are multiple instances of the given symbol
        int position = equationList.IndexOf(symbol); //position of the symbol
        int before = int.Parse(equationList.ElementAt(position - 1)); //position of the number before the symbol
        int after = int.Parse(equationList.ElementAt(position + 1)); //position of the number after the symbol
        equationList.RemoveAt(position - 1);
        equationList.RemoveAt(position - 1);
        equationList.RemoveAt(position - 1);//Remove all 3 elements
        //finally calculate and "replace" the equation-part with the result
        if(symbol == "*")
        {
            equationList.Insert(position - 1, (before * after).ToString());
        }else if(symbol == "/")
        {
            equationList.Insert(position - 1, (before / after).ToString());
        }
    }
    return equationList;
    //equationList =
    //2
    //+
    //4
}

And finally the program loops through the remaining equation:

bool number = true; //This ensures that the equation is split between operators and values
int total = 0; //Sum of the current equation
string lastOperator = String.Empty; //Stores the last operator

foreach (string term in equationList)
{
    if (number)
    {
        if (lastOperator == "") total = int.Parse(term);
        if (lastOperator == "+") total = total + int.Parse(term);
        if (lastOperator == "-") total = total - int.Parse(term);
    }
    number= !number;
    lastOperator = term;
}

Finally I can return the equation with

MessageBox.Show(total.ToString());

I'm however not exactly happy with this solution, since I personally think that took a few steps too much to achieve my goal. Is there anything I can do better?

Review

The calculator requires a very specific syntax and depends on whitespace delimiters. As a consumer it is really easy to make a mistake in using the calculator.
I would expect a basic calculator to include parentheses parsing as well as the basic operators +-/*.
You split the input in a series of string tokens List<string> equationList. String is hard to work with once you start extending the calculator. Invest in a custom class Token that has at least a Value (string) and a Type (Operator, Operand, Parenthesis, Whitespace, ..)
Method PunktVorStrich return the same list as provided in the parameters. It could be made void if you allow the provided list to get changed in the method body.
I would not perform the multiplication/division evaluation in the preprocessor. It should be done in a later phase.

Limitations

You have created a preprocessor function that transforms any input string into one that only uses addition and subtraction.

"1 + 1 * 3"

comes out as

"1 + 3"

Since the expression still remains to be evaluated, you'd have to go over the expression again, this time only dealing with the basic operators. I would not use a function like PunktVorStrich in the preprocessing phase, I would include it in the expression evaluator. This would gain performance, by only iterating the expression once.

By the way, how would you evaluate this expression? There is no consensus in math.

"2 / 3 * 4"

If you want to extend your calculator, you'll notice it would get harder to maintain the evaluator, since you have a fixed format <number><whitespace><operator>.. and evaluate left to right. As you noticed, a simple multiplication and division already are special cases to this left to right scanner. The following simple expressions can currently not be parsed.

"1+1"
"(1 + 1) + 1"

Expression Tree Evaluator

What you could do, is tokenize the input, build an expression tree and evaluate the tree. For instance "(1 + 1) + 1" could have a syntax tree:

//             add
//     add          1
//  1       1

You should read more about evaluating expressions using lexers and parsers. Try refactoring the simple evaluator with only +-/* to this structure.


Binary Tree Inversion I solved this problem.

  Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

  To this

     4
   /   \
  7     2
 / \   / \
9   6 3   1

This problem looked a lot harder at first and then I was able to come up with a recursive solution to this.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if((root == NULL) || (root->left == NULL && root->right == NULL) )
        {
            return root;
        }
        TreeNode *temp = root->left;
        root->left = root->right;
        root->right = temp;
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

When I submitted this solution, I found that my submission ran faster than just 0.2 % of other submission for this problem.

Is there a better and faster approach to this, maybe an iterative one?

It's hard to say exactly how much it'll affect execution speed, but your code isn't written how I'd write it.

First, I'd try to minimize the complexity of the initial condition. I'd only return if root was a null pointer. Unless the tree is tiny, you're probably going to gain more from a minimal test than from being able to skip a level of recursion.

Second, when you need to swap things, it's better to use swap to do the job. One of the interesting points of swap is that it's fairly common to specialize it, so you don't want to call std::swap directly. Rather, you typically want a using declaration to bring std::swap into scope, followed by a call to swap with an unqualified name, so if the namespace of the objects being swapped contains a swap, that'll be found via ADL, and otherwise lookup will fall back to std::swap.

using std::swap;
swap(root->left, root->right);
invertTree(left);
invertTree(right);

This may or may not improve speed for your particular case, but it certainly can in some cases (often enough that you usually want to follow this basic pattern for swapping items in C++).


Customer segmentation using RFM analysis Currently, my code works perfectly well but i would like to make it cleaner for other users by removing the duplicate and similar lines of code into functions or for loops. Because I am still new learning Python, I still did not get a hang of functions and for loops. My data frame rfm includes 5 columns:

Max Date (latest transaction)
Id (unique identifier)
Recency (today's date minus Latest Transaction Date)
Frequency (total # of transactions per Id since its subscription)
Monetary (total amount of $ spent by Id since its subscription)

Separating the main data frame into 3 different df because the sort differs for each cumulative sum column. Frequency and Monetary dfs have identical calculations:

rfm_recency = rfm[['Max_Date', 'Id', 'Member_id', 'Recency']].copy()
rfm_recency = rfm_recency.sort_values(['Recency'], ascending=True)

rfm_frequency = rfm[['Id', 'Member_id', 'Frequency']].copy()
rfm_frequency = rfm_frequency.sort_values(['Frequency'], ascending=False)
rfm_frequency['cum_sum'] = rfm_frequency['Frequency'].cumsum()
rfm_frequency['cum_sum_perc'] = rfm_frequency['cum_sum'] / rfm_frequency['Frequency'].sum()

rfm_monetary = rfm[['Id', 'Member_id', 'Monetary']].copy()
rfm_monetary = rfm_monetary.sort_values(['Monetary'], ascending=False)
rfm_monetary['cum_sum'] = rfm_monetary['Monetary'].cumsum()
rfm_monetary['cum_sum_perc'] = rfm_monetary['cum_sum'] / rfm_monetary['Monetary'].sum()

def scorefm(x):
    """Function for separating data into 5 bins for Frequency & Monetary df """
    if x <= 0.20:
        return 5
    elif x <= 0.40:
        return 4
    elif x <= 0.60:
        return 3
    elif x <= 0.80:
        return 2
    else:
        return 1

# Divide the Recency df into equal quantiles
rfm_recency['r_score'] = 5 - pd.qcut(rfm_recency['Recency'], q=5, labels=False)

# Create scores from cum_sum_perc for Frequency and Monetary
rfm_frequency['f_score'] = rfm_frequency['cum_sum_perc'].apply(scorefm)
rfm_monetary['m_score'] = rfm_monetary['cum_sum_perc'].apply(scorefm)

# Resorting data frames by ID to merge
rfm_recency = rfm_recency.sort_values('Id')
rfm_frequency = rfm_frequency.sort_values('Id')
rfm_monetary = rfm_monetary.sort_values('Id')

# Merging data frames together
result = rfm_recency.copy(['Recency', 'r_score'])
result = result.join(rfm_frequency[['Frequency', 'f_score']])
result = result.join(rfm_monetary[['Monetary', 'm_score']])

# Create an FM and RFM score based on the individual R, F, M scores.
result['FM'] = (result['f_score'] + result['m_score']) / 2
result['RFM_Score'] = result['r_score'] * 10 + result['FM']

Fiddle Data:

import pandas as pd

col_names = ['Max_Date', 'Id', 'Member_id', 'Recency', 'Frequency', 'Monetary'] # 6 columns
data =[['2019-01-21',456,'dwfv84',23,261,4221],
['2019-02-10',123,'qwbe78',3,83,9251],
['2019-01-25',789,'adqw87',19,478,19195],
['2018-01-04',988,'afdi25',40,321,3753],
['2018-03-19',784,'asdf48',331,413,8551],
['2018-04-15',445,'asfv41',304,246,10215],
['2018-04-10',589,'sdqw88',309,80,19569],
['2018-05-20',741,'dsdg46',269,282,3108],
['2018-06-30',852,'cvgo87',228,261,5975],
['2019-01-19',963,'ewgs45',25,357,4405],
['2019-01-12',369,'fbbr54',32,197,1019],
['2019-01-18',258,'fwgs77',26,132,18100],
['2019-02-10',147,'jkyu87',3,32,8678],
['2019-02-05',753,'yukh20',8,132,19871]]

rfm = pd.DataFrame(data=data, columns=col_names,)
rfm ['Max_Date'] = pd.to_datetime(rfm ['Max_Date'])

This can be done a lot simpler.

Since all of rfm returns in result, you can do a copy. To make sure that even if you reorder things, they appear at the correct place, you use an index. Since Id is unique in the DataFrame, let's use this

result2 = datas.set_index("Id")

r_score

There is no use for the intermediate rfm_recency, or it's sorting, so including the r_score can be as simple as:

result2["r_score"] = 5 - pd.qcut(result2["Recency"], q=5, labels=False)

Doing this immediately in this result2 DataFrame instead of joining several intermediary DataFrames together.

f_score and m_score

The f_score and m_score are both linear interpolations, so can be done with this formula, instead of applying the scorefm method on each row individually

def fm_score(series):
    return (
        6 - series.sort_values(ascending=False).cumsum() / series.sum() * 5
    ).astype(int)

result2["f_score"] = fm_score(result2["Frequency"])
result2["m_score"] = fm_score(result2["Monetary"])

FM and RFM_Score

These are simple calculations, so can be done like this:

result2["FM"] = (result2["f_score"] + result2["m_score"]) / 2
result2["RFM_Score"] = result2["r_score"] * 10 + result2["FM"]

This can be all you need. If the shape needs to be exactly as the original result, a reset_index, sort and reindex can help:

result2 = result2.sort_index().reset_index().reindex(columns=result.columns)

where instead of result.columns you manually give a list of the columns in order

    Max_Date    Id  Member_id   Recency r_score Frequency   f_score Monetary    m_score FM  RFM_Score
0   2019-02-10  123 qwbe78  3   5   83  1   9251    2   1.5 51.5
1   2019-02-10  147 jkyu87  3   5   32  1   8678    2   1.5 51.5
2   2019-01-18  258 fwgs77  26  3   132 1   18100   3   2.0 32.0
3   2019-01-12  369 fbbr54  32  3   197 1   1019    1   1.0 31.0
4   2018-04-15  445 asfv41  304 1   246 2   10215   2   2.0 12.0
5   2019-01-21  456 dwfv84  23  4   261 2   4221    1   1.5 41.5
6   2018-04-10  589 sdqw88  309 1   80  1   19569   4   2.5 12.5
7   2018-05-20  741 dsdg46  269 2   282 3   3108    1   2.0 22.0
8   2019-02-05  753 yukh20  8   5   132 1   19871   5   3.0 53.0
9   2018-03-19  784 asdf48  331 1   413 4   8551    1   2.5 12.5
10  2019-01-25  789 adqw87  19  4   478 5   19195   3   4.0 44.0
11  2018-06-30  852 cvgo87  228 2   261 2   5975    1   1.5 21.5
12  2019-01-19  963 ewgs45  25  4   357 4   4405    1   2.5 42.5
13  2018-01-04  988 afdi25  40  2   321 3   3753    1   2.0 22.0


Proper and elegant way of Building a XML Document I need to build the following XML document

<?xml version="1.0"?>
<SFDocument>
    <TableID>5415</TableID>
    <PageSize>1</PageSize>
    <PageIndex>1</PageIndex>
    <MultiCompany>No</MultiCompany>
    <Language>1033</Language>
    <Fields>
        <Field>Operation No.</Field>
        <Field>Line No.</Field>
        <Field>Date</Field>
        <Field>Comment</Field>
    </Fields>
    <TableFilters>
        <TableFilter>
            <Field>Status</Field>
            <Filter>3</Filter>
        </TableFilter>
        <TableFilter>
            <Field>Prod. Order No.</Field>
            <Filter>101006</Filter>
        </TableFilter>
    </TableFilters>
    <Key>
        <Field>Routing Reference No</Field>
        <Field>10000</Field>
    </Key>
</SFDocument>

using the following code, it works but is it the proper way of doing it.

internal class Field
{
    public string Name { get; set; }
    public  const string FieldName = "Field";
}
internal class Key
{
    public string Field { get; set; }
    public  const string FieldName = "Field";
}

internal class TableFilter
{
    public string Field { get; set; }
    public string Filter { get; set; }
    public const string FieldName = "Field";
    public const string FilterName = "FilterName";
}

void Main()
{
    //this part is just for the example, obviously, this would be passed as parameter
    var tableId = 5415;
    var pageSize = 1;
    var pageIndex = 1;
    var multiCompany = "No";
    var language = 1033;

    var fields = new List<Field>();
    fields.Add(new Field() {Name = "Operation No."});
    fields.Add(new Field() {Name = "Line No."});
    fields.Add(new Field() {Name = "Date"});
    fields.Add(new Field() {Name = "Comment"});

    var tableFilters = new List<TableFilter>();
    tableFilters.Add(new TableFilter() {Field = "Status", Filter = "3"});
    tableFilters.Add(new TableFilter() {Field = "Prod. Order No.", Filter = "101006"});

    var keys = new List<Key>();
    keys.Add(new Key() {Field = "Routing Reference No"});
    keys.Add(new Key() {Field = "10000"});

    //End of setup

    XDocument doc = new XDocument(new XElement("SFDocument",
                                      new XElement("TableId", tableId),
                                      new XElement("PageSize", pageSize),
                                      new XElement("PageIndex", pageIndex),
                                      new XElement("MultiCompany", multiCompany),
                                      new XElement("Language", language),
                                      new XElement("Fields"),
                                        new XElement("TableFilters"),
                                        new XElement("Key")
                                        )
    );

    var xFields = doc.Element("SFDocument").Element("Fields");

    foreach (Field field in fields)
    {
        xFields.Add(new XElement(Field.FieldName, field.Name));
    }

    var xTableFilters = doc.Element("SFDocument").Element("TableFilters");

    foreach (TableFilter tableFilter in tableFilters)
    {
        var tf = new XElement("TableFilter");
        tf.Add(new XElement(TableFilter.FieldName, tableFilter.Field));
        tf.Add(new XElement(TableFilter.FilterName, tableFilter.Filter  ));
        xTableFilters.Add(tf);
    }

    var xKey = doc.Element("SFDocument").Element("Key");

    foreach (Key key in keys)
    {
        xKey.Add(new XElement(Key.FieldName, key.Field));
    }
    doc.Dump();  //Using LinqPad
}

I ended up changing my approach and went with a serialize method:

public static class SerializationHelper
{
    internal static string SerializeObject<T>(this T toSerialize)
    {
        var xmlSerializer = new XmlSerializer(toSerialize.GetType());
        var textWriter = new StringWriter();
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}
[Serializable]
public class SFDocument
{
    public int TableId { get; set; }
    public int PageSize { get; set; }
    public int PageIndex { get; set; }
    public string MultiCompany { get; set; }
    public int Language { get; set; }

        [XmlArrayItem("Field")]
        public List<string> Fields { get; set; }

        public List<TableFilter> TableFilters { get; set; }

        [XmlArrayItem("Field")]
        public List<string> Key { get; set; }
        public SFDocument(): this(5415, 1, 1, "No", 1033){}

        public SFDocument(int tableId, int pageSize, int pageIndex, string multiCompany, int language)
        {
            TableId = tableId;
            PageSize = pageSize;
            PageIndex = pageIndex;
            MultiCompany = multiCompany;
            Language = language;

            Fields = new List<string>();
            Key = new List<string>();
            TableFilters  = new List<TableFilter>();
        }
}

[Serializable]
public class TableFilter
{
    public string Field { get; set; }
    public string Filter { get; set; }

    public TableFilter() {}

    public TableFilter(string field, string filter)
    {
        Field = field;
        Filter = filter;
    }
}

void Main()
{
    var sfd = new SFDocument();
    sfd.Fields.Add("Field1");
    sfd.Fields.Add("Field2");
    sfd.Fields.Add("Field3");
    sfd.Fields.Add("Field4");

    sfd.Key.Add("Key1");
    sfd.Key.Add("Key2");
    sfd.Key.Add("Key3");

    sfd.TableFilters.Add(new TableFilter("field1", "filter1"));
    sfd.TableFilters.Add(new TableFilter("field2", "filter2"));
    sfd.TableFilters.Add(new TableFilter("field3", "filter3"));
    sfd.SerializeObject().Dump();
}


Categorization algorithm for discrete variables I am trying to categorize some data. For that I check the distribution of the data. Then I split based on the number of appearance of each value.
The algorithm I have is working so far but really slow. I am looking to improve the speed.
The speed is important on this one because I treat a lot of different data using the same structure and the data is a bit large (140k rows)

def RamsesIdCategory(data):
    # handling Ramses Id:
    print('Starting Ramses Id')
    valueRamses = data['Ramses Trade Id'].unique()
    countRamses = data['Ramses Trade Id'].value_counts()
    for value in valueRamses:
        if countRamses.get(value) < 2:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id'] == value] = 1
        elif 2 <= countRamses.get(value) < 5:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id'] == value] = 2
        elif 5 <= countRamses.get(value) < 10:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id'] == value] = 3
        elif 10 <= countRamses.get(value) < 20:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id']== value] = 4
        elif 20 <= countRamses.get(value) < 32:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id']== value] = 5
        else:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id'] == value] = 6
    print('finished Ramses Id')
    return data

EDIT : I reworked my code as I knew there was the problem with the loop doing too much iterations over my rows. Here is the new version :

def RamsesIdCategory(data):
    # handling Ramses Id:
    print('Starting Ramses Id')
    valueRamses= data['Ramses Trade Id'].value_counts()
    for i in data.index:
        if valueRamses.get(data.get_value(i,'Ramses Trade Id'))<2:
            data.set_value(i,'Ramses Trade Id',1)
        elif 2<=valueRamses.get(data.get_value(i,'Ramses Trade Id'))<5:
            data.set_value(i, 'Ramses Trade Id', 2)
        elif 5 <= valueRamses.get(data.get_value(i, 'Ramses Trade Id')) < 10:
            data.set_value(i, 'Ramses Trade Id', 3)
        elif 10<= valueRamses.get(data.get_value(i, 'Ramses Trade Id')) < 20:
            data.set_value(i, 'Ramses Trade Id', 4)
        elif 20 <= valueRamses.get(data.get_value(i, 'Ramses Trade Id')) < 32:
            data.set_value(i, 'Ramses Trade Id', 5)
        else:
            data.set_value(i, 'Ramses Trade Id', 6)
     return(data)

I iterrate over my whole dataset once and do a single select and modification instead of trying to do a multiple modification on the entire dataframe for each different value. It is 100 time faster as it ran in few sec vs 50min

The code can be largely simplified using apply. But first, you need a better way to test your values and assign them an id:

def convert_count_to_id(count, limits=(2, 5, 10, 20, 32)):
    for id, limit in enumerate(limits, 1):
        if count < limit:
            return id
    return id + 1

This is equivalent to your elifs chain but harder to get wrong.

Now your function can become:

def ramses_id_category(data):
    serie_name = 'Ramses Trade Id'
    value_ramses = data[serie_name].value_counts()
    id_ramses = values_ramses.apply(convert_count_to_id)
    data[serie_name] = data[serie_name].apply(id_ramses.get)

Note that I removed the return data at the end. Since you are mutating the parameter in place, there is no need to return it back since the caller will already be able to see the changes on the reference they hold when calling this function.


Area calculator in Python I'm pretty new with programming in general.  I'm using Python 2 right now as it seems most of the courses are teaching Python 2 and not 3.  I built this area calculator that will calculate square, rectangle, triangle, circle or trapezoid.  I'm a little concerned about how I used the functions as well as my else statement when an "invalid" input is given.

import math

##formulas for each geometric figure

def calc_square(a_side):
    square_area = a_side ** 2
    return square_area

def calc_rectangle(w_side, l_side):
    rect_area = l_side * w_side
    return rect_area

def calc_triangle(base, height):
    triangle_area = (base * height) / 2
    return triangle_area

def calc_circle(radius):
    circle_area = math.pi * radius ** 2
    return circle_area

def calc_trapezoid(short_base, long_base, height):
    trapezoid_area = ((short_base + long_base) / 2 ) * height
    return trapezoid_area

##function determining which formula to calculate

def area_calc_logic(user_calc):
    if user_calc == "square":
        a_side = float(raw_input("Give length of side: "))
        print calc_square(a_side)
    elif user_calc == "rectangle":
        l_side = float(raw_input("Give the length: "))
        w_side = float(raw_input("Give the width: "))
        print calc_rectangle(w_side, l_side)
    elif user_calc == "triangle":
        base = float(raw_input("Give the length of base: "))
        height = float(raw_input("Give the height: "))
        print calc_triangle(base, height)
    elif user_calc == "circle":
        radius = float(raw_input("Give the radius: "))
        print calc_circle(radius)
    elif user_calc == "trapezoid":
        short_base = float(raw_input("Give the length of the short base: "))
        long_base = float(raw_input("Give the length of the long base: "))
        height = float(raw_input("Give the height: "))
        print calc_trapezoid(short_base, long_base, height)
    else:
        area_calc_logic(raw_input("Error, Re-enter input: "))

print "This program will calculate/narea of some geometric shapes for you"
print "Shapes available are squares, triangles, circles, and trapezoid"
print "Enter square, rectangle, triangle, circle, or trapezoid"
area_calc_logic(raw_input("What area would you like to calculate? "))

Overall this seems pretty good. The calculations look correct (given sensible input) and the code is easy to follow.

Here are some suggestions for making this even better:

Cope with the user entering an empty string.

If I select a shape, and then press “enter” immediately when asked for a dimension, I get a nasty traceback printed to the console:

This program will calculate/narea of some geometric shapes for you
Shapes available are squares, triangles, circles, and trapezoid
Enter square, rectangle, triangle, circle, or trapezoid
What area would you like to calculate? square
Give length of side:
Traceback (most recent call last):
  File "areas.py", line 54, in <module>
    area_calc_logic(raw_input("What area would you like to calculate? "))
  File "areas.py", line 29, in area_calc_logic
    a_side = float(raw_input("Give length of side: "))
ValueError: could not convert string to float:

If you add a bit of debugging code around that, you see it’s trying to process float('') and choking. You should probably ask the user for the dimension again.
Handle negative dimensions.

For example, if I tell you my triangle has base -5 and height 14, you tell me that the area is -35. That seems a bit odd – isn’t area always positive?

It’s not immediately obvious how you should handle negative quantities from the user – perhaps just call abs() on their input? – but the current approach isn’t very good.
Move the area_user_logic into an if __name__ == '__main__' block.

This just means tweaking the end of the program as follows:

if __name__ == '__main__':
    print "This program will calculate/narea of some geometric shapes for you"
    print "Shapes available are squares, triangles, circles, and trapezoid"
    print "Enter square, rectangle, triangle, circle, or trapezoid"
    area_calc_logic(raw_input("What area would you like to calculate? "))

This means that the interactive session only runs when you call the script directly. If I import the file into another file, I don’t get the interactive session, just the functions you’ve defined.

This helps make your code more reusable. See What does if __name__ == '__main' do? on SO for more details.
Cope with weirdly cased input.

I claim my intention is perfectly clear here, but your program rejects it:

This program will calculate/narea of some geometric shapes for you
Shapes available are squares, triangles, circles, and trapezoid
Enter square, rectangle, triangle, circle, or trapezoid
What area would you like to calculate? Triangle
Error, Re-enter input:

It would be good to lowercase user input before checking – that makes it a bit more friendly to malformed user input.
Print an integer area if possible.

Here’s a sample run from your program:

This program will calculate/narea of some geometric shapes for you
Shapes available are squares, triangles, circles, and trapezoid
Enter square, rectangle, triangle, circle, or trapezoid
What area would you like to calculate? square
Give length of side: 3
9.0

From my perspective, I’ve entered an integer, and numerically the area is an integer. It’s a bit odd that you returned it as a float. You could use the float.is_integer method to detect if an area has integral value, and print a slightly cleaner output.
The else branch could cause a recursion bug.

If somebody enters bogus input 999 times, they’ll hit Python’s max recursion depth. Admittedly they’d need to be quite patient – I tried it, and got bored holding down “Enter” – but hey, would be nice to avoid.

You could refactor the code into a while True: loop. Something like (pseudo-code):

while True:
    ask_for_shape_name()
    if shape_name_is_valid():
        ask_for_dimensions()
        print_area_given_shape_and_dimensions()
    else:
        error_message()

as a bonus, this approach could allow me to calculate many areas at once, rather than restarting the script every time.
Python 3 support isn’t tricky for this script.

There are only two changes that affect this code:

print is a function, not a statement. That means you write print("hello world") instead of print "hello world". If you want to use this in Python 2 – which will help you write scripts than run under 2 or 3 – add this line to the top of your script:

from __future__ import print_function

It forces your Python 2 scripts to use print() as a function.
In Python 2, there’s a distinction between raw_input(), which returns user input as a string, and input(), which eval()'s the input first.

The latter is quite dangerous, so in Python 3 raw_input() was renamed to input(), and the old input() was dropped. To get the old behaviour, you have to do eval(input()), which makes the danger more explicit.


Mean of integers, ignoring the largest and smallest values The code returns the mean of a list of integers, except ignoring the largest and smallest values in the list. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value.  Assume that the list is length 3 or more.

For this problem, as part of my learning, I’ve defined my own functions. Please comment on my variable names, docstrings, readability of code etc. and let me know how you would do it.

from typing import Sequence

def find_length(seq: Sequence) -> int:
    """ Return the number of elements in a sequence.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_length(numbers)
    6
    """

    count = 0
    for _ in seq:
        count += 1

    return count

def find_min(numbers: Sequence) -> int:
    """ Return the smallest number in a sequence.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_min(numbers)
    -10
    """

    min_number = numbers[0]

    for number in numbers:
        if number < min_number:
            min_number = number

    return min_number

def find_max(numbers: Sequence) -> int:
    """ Return the biggest number in a sequence.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_max(numbers)
    0
    """

    max_number = numbers[0]

    for number in numbers:
        if number > max_number:
            max_number = number

    return max_number

def find_sum(numbers: Sequence) -> int:
    """ Return sum of the numbers in a sequence.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_sum(numbers)
    -22
    """

    total = 0

    for number in numbers:
        total += number

    return total

def find_centered_average(numbers: Sequence) -> int:
    """ Return the centered average of a list of numbers.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_centered_average(numbers)
    -3
    """

    max_number = find_max(numbers)
    min_number = find_min(numbers)
    total = find_sum(numbers) - max_number - min_number
    centered_average = total // (find_length(numbers) - 2)

    return centered_average

All of that can be accomplished with either:

(sum(numbers) - max(numbers) - min(numbers)) // (len(numbers) - 2)

Or,

centered_numbers = sorted(numbers)[1:-1]
sum(centered_numbers) // len(centered_numbers))

There must be a number of other ways to do it.

Well, whenever you want to know which function is better, you should test them.

First, your custom functions are just re-inventing the wheel, so you should only use them if you have to (either because it is mandated or they are actually faster, more secure, more memory-friendly, more whatever).

When running your functions with growing number of numbers, this is what I get:

Here, Input is the length of the numbers list, generated with numpy.random.random_integers(-10, 10, size=n), with \$n\in [10, 10000]\$.

So, for larger lists, the difference between your own function and the sorting function is negligible. The sorting should be \$\mathcal{O}(n\log n)\$, but I don't see why your function seems to show a similar behavior.

The sum/min/max function should be \$\mathcal{O}(3n)\$, so wins for large lists.

For smaller sizes, the two simple implementations perform similarly and your functions slightly slower:

This is for numpy.random.random_integers(-100, 100, size=n), with \$n\in [10, 100]\$.

All measurements were done in Python 2.7.13. I put your last two snippets into functions:

def centered_average_sum(numbers):
    return (sum(numbers) - max(numbers) - min(numbers)) // (len(numbers) - 2)

def centered_average_sort(numbers):
    centered_numbers = sorted(numbers)[1:-1]
    return sum(centered_numbers) // len(centered_numbers)

Note that I fixed a superfluous closing bracket on the second function.


Finding "lucky numbers" This code is for a problem in which I'm to find the total number of numbers that exist between A and B, of which sum of digits and sum of square of digits are prime.

How can I make this optimal?

import java.util.Scanner;
public class LuckyNumbers {
    static int T,ans[];
    static long A,B;
    public static void main(String ar[]){
        Scanner scan=new Scanner(System.in);
        T=scan.nextInt();
        ans=new int[T];
        for(int i=0;i<T;i++){
            A=scan.nextLong();
            B=scan.nextLong();
            for(long j=A;j<=B;j++){
                if(getLucky(j)){
                    ans[i]++;
                }
            }
        }
        for(int i=0;i<T;i++){
            System.out.println(ans[i]);
        }
    }
    public static boolean getLucky(long j){
        boolean lucky=false;
        long rem,sum=0,sum1=0;
        while(j>0){
            rem=j%10;
            sum=sum+rem;
            sum1=sum1+(rem*rem);
            j=j/10;
        }
        if(isPrime(sum)&&isPrime(sum1)){
            lucky=true;
        }
        return lucky;
    }
    public static boolean isPrime(long sum){
        boolean status=true;
        if(sum!=1){
            for (int i=2; i < sum ;i++ ){
              long n =sum % i;
              if (n==0){
                    status=false;
                    break;
              }
            }
        }else{
            status=false;
        }
        return status;
    }
}

Some thoughts on speed:

Start caching results in isPrime.
Print things as soon as you calculate them, no need to store them back into an array. (This makes debugging easier, too.)

As Leonid pointed out, storing things may be a good idea.  I would keep it an array in that case, not a linked list, as that costs less time.
However, I would simply disable output when profiling, and keep my suggestion for debugging.
On a similar note, consider splitting both the main algorithm and the output into separate functions so that you can easily disable both.  That makes it much easier to check how much each stage of the algorithm (parsing, processing, printing) is taking.

You could try caching rem*rem, as you know there's only ten possibilities.  May be faster, may be slower.
You should take a look at the input you'll be dealing with and figure out what values your program needs to have that could be given beforehand.  What values can the numbers you're checking for primality be?  (I would guess you need up to around 2000, but I'm not sure.)

Some general thoughts:

Add some comments.  What is a lucky number?
Add some blank lines.
Rename getLucky to isLucky or checkIsLucky.  I'd go for the first, but some people will tell you that functions need a verb other than "is".  If Java supports it, you could make it an extension method and then do arr[i].isLucky().
Don't make variables static unless they have to be.  Both T and ans can be local to main.
Make your variable names more meaningful.  In particular, replacing T with numberOfInputPairs (or numInputPairs, at least) would improve matters.
Don't use the same name for two variables, with one letter difference.  Why do you have sum and sum1?  What's the difference between them?
Use the += operator when possible.  sum1 += rem*rem is easier to read than what you have.

To address the question of numberOfInputPairs being too long: let's reformat the code a little and change the name appropriately:

public static void main(String ar[]){
    Scanner scan = new Scanner(System.in);
    int numberOfInputPairs = scan.nextInt();
    int ans[] = new int[numberOfInputPairs];

    for (int i = 0; i < numberOfInputPairs; i++){
        A = scan.nextLong();
        B = scan.nextLong();
        for (long j = A; j <= B; j++) {
            if (getLucky(j)) {
                ans[i]++;
            }
        }
    }

    for (int i = 0; i < numberOfInputPairs; i++) {
        System.out.println(ans[i]);
    }
}

Yes, if no whitespace is added, the longer variable names make a wall of text a bigger wall of text, and convey very little meaning.  However, with just a slight increase in the amount of whitespace, I find that the longer variable name is no less clear and makes it clear what is being done.

(By the way, I think this is partially a language problem: as things are, it is used three times, while a proper for-each loop would mean it would only need to be used once.)

I do not agree with n or T offering that clarity; numPairs would do, too, and is down to personal preference.


Refactor PHP | Laravel Code, Optimisation needed to make code clean I have made some notification preferences in which there are 4 major preferences

SMS
PUSH
FAX
EMAIL

And then there are some specific templates such as booking-accepted and within booking accepted there are again these 4 notifications.

So what I have to do I need to check 1st priority notification preferences first that if SMS is on then I have to check regarding specific templates that SMS is on in booking-accepted and then I'll send the notification or will just unset the recipient.

The object on notification preferences is as follows

{
    "sendSms": "1",
    "sendFax": "1",
    "sendEmail": "1",
    "sendPush": "0",
    "specific-templates": [
        {
            "update-video-physical-address": [
                {
                    "sendPush": "1",
                    "sendSms": "0",
                    "sendEmail": "0"
                }
            ],
            "booking-denied": [
                {
                    "sendPush": "1",
                    "sendSms": "0"
                }
            ]
        }
    ],
}

And The code I did for this is given below which is bit messy and unclean.

 foreach ($recipients as $recipient) {
            $user = $userRepository->findByParams([
                'email' => $recipient->getUser()->email
            ]);
            if (!is_null($user->userNotificationPreference) && array_key_exists($sendMethod, $user->userNotificationPreference->preferences)
                && $user->userNotificationPreference->preferences[$sendMethod] == true) {
                if (array_key_exists($notification->getTemplateCode(), $user->userNotificationPreference->preferences['specific-templates'][0])) {
                    if (array_key_exists($notification->getTemplateCode(), $user->userNotificationPreference->preferences['specific-templates'][0])
                        && array_key_exists($sendMethod, $user->userNotificationPreference->preferences['specific-templates'][0][$notification->getTemplateCode()][0])) {
                        if ($user->userNotificationPreference->preferences['specific-templates'][0][$notification->getTemplateCode()][0][$sendMethod] == false) {
                            $key = array_search($recipient, $recipients->toArray());
                            unset($recipients[$key]);
                        }
                    }
                }
            } elseif (!is_null($user->userNotificationPreference) && array_key_exists($sendMethod, $user->userNotificationPreference->preferences)
                && $user->userNotificationPreference->preferences[$sendMethod] == false) {

                $key = array_search($recipient, $recipients->toArray());
                unset($recipients[$key]);

            }
        }

        return $recipients;

getTemplateCode() will return the template code i.e booking-accepted
$sendMethod is method i.e sendSms, sendPush

Please help me with writing this mode more clean and efficient way such as reducing IFs and any other approach

You could exploit Laravel collections to achieve what you need.

Most of your code is checking for the presence/absence of props on your arrays. Laravel internally exposes and uses the Illuminate\Support\Arr class that contains a lot of useful methods to work with arrays without the hassles of checking for key existance.
It also allows you to use dot notation to get nested properties in a really simple way.

Laravel collection methods (documentation)  use this class where needed. Therefore, the refactored code would become really intuitive and should look like this (it may need a little bit of tweaking based on your userNotificationPreference and preferences arrays and how you retrieve them from the model:

$recipients->map->getUser()
    ->where("userNotificationPreference.preferences.{$sendMethod}", true)
    ->where("userNotificationPreference.preferences.specific-templates.0.{$notification->getTemplateCode()}.0.{$sendMethod}", true);

Note that I used ->map->getUser() that would be equivalent to:

$recipients->map(function ($recipient) {
    return $recipient->getUser();
})

However, if you really need to pluck the user instance through the user repository then you can do:

$recipients->map(function ($recipient) use ($userRepository) {
    return $userRepository->findByParams([
        'email' => $recipient->getUser()->email
    ]);
})->where(...);

and chain the where calls after that.

If any part of my code is unclear or doesn't work, let me know in the comments and I'll explain/fix it.


Python class assignment simplification for d&d character creator As some of you may know, part of creating, or leveling up a character in almost any game is ability score increases. In this example, the character has six abilities with preassigned scores: strength, dexterity, intelligence, wisdom, charisma, and constitution. Users of the code have the option of choosing to level up one score by 2 points, or two different scores by one each.

The code I have works, and it works well, however, I realize that it's bulky, ugly, and probably a sin for python to be running it. Can you help me simplify/streamline it? Thank you

def ability(self):
    choice = raw_input("leveling up: do you want to increase 'one' score by two, or 'two' scores by one each?")
    if choice == "one":
        score = raw_input("which ability do you want to increase by two?")
        if score == "strength":
            self.strength = self.strength + 2
        elif score == "dexterity":
            self.dexterity = self.dexterity + 2
        elif score == "intelligence":
            self.intelligence = self.intelligence + 2
        elif score == "wisdom":
            self.wisdom = self.wisdom + 2
        elif score == "charisma":
            self.charisma = self.charisma + 2
        else:
            self.constitution = self.constitution + 2
    else:
        score = raw_input("which ability do you want to increase by one?")
        if score == "strength":
            self.strength = self.strength + 1
        elif score == "dexterity":
            self.dexterity = self.dexterity + 1
        elif score == "intelligence":
            self.intelligence = self.intelligence + 1
        elif score == "wisdom":
            self.wisdom = self.wisdom + 1
        elif score == "charisma":
            self.charisma = self.charisma + 1
        else:
            self.constitution = self.constitution + 1
        score_two = raw_input("which second ability do you want to increase?")
        if score_two == "strength":
            self.strength = self.strength + 1
        elif score_two == "dexterity":
            self.dexterity = self.dexterity + 1
        elif score_two == "intelligence":
            self.intelligence = self.intelligence + 1
        elif score_two == "wisdom":
            self.wisdom = self.wisdom + 1
        elif score_two == "charisma":
            self.charisma = self.charisma + 1
        else:
            self.constitution = self.constitution + 1

Duplicate code is almost always better replaced with a function. Consider a class method which alters an ability by a given value. This can be achieved (most cleanly, I believe) with getattr and setattr. Calling getattr(x,'spam') will return the value x.spam, and similarly setattr(x,'spam',n) will set the value of x.spam to n.

This, combined with a helpful message when the user enters something unexpected, would yield code like that below:

def ability(self):
    choice = raw_input("Leveling up: do you want to increase 'one' score by two, or 'two' scores by one each?")
    while True:
        if choice == "one":
            stat = raw_input("Which ability do you want to increase by two?")
            self.alter_stat(self, stat, 2)

            break
        elif choice == "two":
            first_stat = raw_input("Which first ability do you want to increase by one?")
            self.alter_stat(self, first_stat, 1)
            second_stat = raw_input("Which second ability do you want to increase?")
            self.alter_stat(self, second_stat, 1)

            break
        else:
            print("Hmm, I don't understand. Enter 'one' or 'two' next time!")

def alter_stat(self, stat, alteration):
    assert stat in ['charisma', 'constitution', 'dexterity', 'intelligence', 'strength', 'wisdom'], "That's not a valid ability!"
    old_value = getattr(self, stat)
    setattr(self, stat, old_value + alteration)


Determine if subset in int array adds up to a given input integer Given a set of non-negative integers, and a value sum, determine if there is a subset
of the given set with sum equal to given sum. On similar lines, Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of
elements in both subsets is same.

Complexity:

\$O(n \times m)\$, \$n\$ is the array length and \$m\$ is the sum.

Looking for code-review, optimizations and best practices.

public final class SubSetSum {

    private SubSetSum() {}

    /**
     * Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of
     * elements in both subsets is same.
     *
     * A negative value in array would case unpredicatable results.
     *
     * Examples
     *
     *  arr[] = {1, 5, 11, 5}
     *   Output: true
     *   The array can be partitioned as {1, 5, 5} and {11}
     *
     * arr[] = {1, 5, 3}
     * Output: false
     *   The array cannot be partitioned into equal sum sets.
     *
     * @param a     the input array
     * @return      true if array can be partitioned into subsets, else false.
     */
    public static boolean canPartition(int[] a) {
        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum  = sum + a[i];
        }
        if ((sum % 2) == 1) return false;

        return subsetSum(a, sum % 2);
    }

    /**
     * Given a set of non-negative integers, and a value sum, determine if there is a subset
     * of the given set with sum equal to given sum.
     *
     *  Examples: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
     *  Output:  True  //There is a subset (4, 5) with sum 9.
     *
     *  A negative value in array would case unpredicatable results.
     *
     * @param a     the input array
     * @param sum   the input sum
     * @return      true if some subset of elements add up to the sum.
     */
    public static boolean subsetSum(int[] a, int sum) {

        boolean[][] m = new boolean[sum + 1][a.length + 1];
        for (int j = 0; j < m[0].length; j++) {
            m[0][j] = true;
        }

        for (int i = 1; i < m.length; i++) {
            for (int j = 1; j < m[0].length; j++) {
                m[i][j] = m[i][j - 1];
                if (i >= a[j - 1]) {
                    m[i][j] = m[i][j - 1] || m[i - a[j-1]][j-1];
                }
            }
        }

        return m[sum][a.length];
    }
}

public class SubSetSumTest {

    @Test
    public void testCanPartition() {
        int[] a1 = {1, 2, 3, 4};
        assertTrue(SubSetSum.canPartition(a1));

        int[] a2 = {1, 2, 3, 4, 5};
        assertFalse(SubSetSum.canPartition(a2));

        int[] a3 = {1, 2, 3, 4, 5, 6};
        assertFalse(SubSetSum.canPartition(a3));

        int[] a4 = {1, 2, 3, 4, 5, 7};
        assertTrue(SubSetSum.canPartition(a4));
    }

    @Test
    public void testSubsetSum() {
        int[] a = {1, 3, 8, 9};
        assertTrue(SubSetSum.subsetSum(a,  1));
        assertFalse(SubSetSum.subsetSum(a,  2));
        assertTrue(SubSetSum.subsetSum(a,  3));
        assertTrue(SubSetSum.subsetSum(a,  4));
        assertFalse(SubSetSum.subsetSum(a,  5));
        assertFalse(SubSetSum.subsetSum(a,  6));
        assertFalse(SubSetSum.subsetSum(a,  7));
        assertTrue(SubSetSum.subsetSum(a,  8));
        assertTrue(SubSetSum.subsetSum(a,  9));
        assertTrue(SubSetSum.subsetSum(a, 10));
        assertTrue(SubSetSum.subsetSum(a, 11));
        assertTrue(SubSetSum.subsetSum(a, 12));
        assertTrue(SubSetSum.subsetSum(a, 12));
        assertTrue(SubSetSum.subsetSum(a, 13));
        assertFalse(SubSetSum.subsetSum(a, 14));
        assertFalse(SubSetSum.subsetSum(a, 15));
        assertFalse(SubSetSum.subsetSum(a, 16));
        assertTrue(SubSetSum.subsetSum(a, 17));
        assertTrue(SubSetSum.subsetSum(a, 18));
        assertFalse(SubSetSum.subsetSum(a, 19));
        assertTrue(SubSetSum.subsetSum(a, 20));
        assertTrue(SubSetSum.subsetSum(a, 21));
    }

}

This solution is very dependant on m for the space complexity.

I worry that, with the inputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2000000000]

and the target sum 2000000002 that your program will run out of memory (it will do: boolean[][] m = new boolean[sum + 1][a.length + 1]; which will create an array of about 20GB or more.... actually, it will be worse... about 80GB.

Additionally, you have labelled this as a 'dynamic programming' problem, but there is no recursion here, and no memoization/re-use....

In a review, I would challenge this solution's scalability, and assumptions.


Arranging numbers in a circle such that the sums of neighbors and sums of diametric opposites are prime I need to create a circle with numbers from 1 to n , however it is necessary to respect some rules:

  All numbers from 1 to n are used in the circle only once.
  The sum of two consecutive numbers is a prime number
  The sum of a number with what is diametrically opposite it is also a prime number

So I need to create an algorithm that receives an integer n
and determines whether there is a circle of size n, if it exists.

For example:

Program response: 1 6 7 16 15 8 5 12 11 18 13 10 3 4 9 14 17 2

I managed to get the expected result, but I do not know if I made the faster way, or if there is something badly written.

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JOptionPane;

public class QuintoDesafio {

    private static int j;
    private static int k;

    private static Vector primes  = new Vector();

    public static void main(String[] args)
    {

        long start = System.currentTimeMillis();

        ArrayList list = new ArrayList();

        primes.add( new Integer( 2 ) );
        primes.add( new Integer( 3 ) );
        primes.add( new Integer( 5 ) );
        primes.add( new Integer( 7 ) );
        primes.add( new Integer( 11 ) );
        primes.add( new Integer( 13 ) );
        primes.add( new Integer( 17 ) );
        primes.add( new Integer( 19 ) );
        primes.add( new Integer( 23 ) );
        primes.add( new Integer( 31 ) );
        primes.add( new Integer( 37 ) );
        primes.add( new Integer( 41 ) );

        String n = JOptionPane.showInputDialog( "Input n (even) ");
        int ene = Integer.parseInt( n );

        for ( int i=1; i <= ene; i++ ) {
            list.add( new Integer(i) );
        }
        exchange(list, 0);

        long end  = System.currentTimeMillis();
        System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end - start)));
    }

    static void exchange(ArrayList arr, int k){
        boolean passed = true;

        for(int i = k; i < arr.size(); i++){
            java.util.Collections.swap(arr, i, k);
            exchange(arr, k+1);
            java.util.Collections.swap(arr, k, i);
        }
        if (k == arr.size() -1){
            int half = arr.size()/2;

            for ( int j=0; j<arr.size(); j++ ) {
                int one = (int) arr.get(j);
                int two;
                if ( j+1 == arr.size() ) {
                    two = (int) arr.get(0);
                } else {
                    two = (int) arr.get(j+1);
                }
                Integer number_test = new Integer( one+two );
                if ( !primes.contains( number_test )) {
                    passed = false;
                }
            }

            for ( int j=0; j<half; j++ ) {
                int one = (int) arr.get(j);
                int two = (int) arr.get(j+half);
                Integer number_test = new Integer( one+two );
                if ( !primes.contains( number_test )) {
                    passed = false;
                }
            }
            if ( passed ) {
                System.out.println(java.util.Arrays.toString(arr.toArray()));
            }
        }
    }
}
```

First, Vector shouldn't be used here. It's essentially a synchronized ArrayList, and you don't need any synchronization in this case. Just change it to an ArrayList.

This has the potential to be a little faster.

Second, you're using a raw ArrayList which isn't typesafe:

list.add("Some nonsense"); // Doesn't cause an error

and is necessitating your (int) type-casts later on. Specify that the list is holding integers using generics, and it will be typesafe. Read the < > as "of" here:

// Note how we specify what the list can hold
// An ArrayList of Integers
ArrayList<Integer> list = new ArrayList<>();

list.add("Some nonsense") // This causes an error now at compile time

You're also doing odd stuff with the Integer constructor. You don't need to manually cast unboxed integers like Integer(2). 2 will be "auto-boxed" into its object wrapper as necessary implicitly.

You're calling Integer/parseInt outside of a try; which is risky. If the user enters bad input, your whole program with crash. Wrap it up and handle failure (yes, users will enter bad input):

try {
    int ene = Integer.parseInt(n);
    // Code using "ene"

} catch (NumberFormatException e) {
    // Just an example. You'll need to do something more involved, like re-asking for input
    System.out.println("Parse failed");
}

Just as an example of what I mentioned earlier:

static void exchange(ArrayList arr, int k){
    ...
    int one = (int) arr.get(j);
    int two = (int) arr.get(j + half);
    Integer number_test = new Integer(one + two);

Make the parameter generic, and do away with the casts and boxing. Just write:

static void exchange(ArrayList<Integer> arr, int k){
    ...
    int one = arr.get(j);
    int two = arr.get(j + half);
    int number_test = one + two;

And then similarly below that.

Also, Java prefers camelCase, not snake_case. It's best to stick to the conventions of the language you're using.

import java.sql.Date;

is a little worrying. You shouldn't really be raiding a SQL library just to make use of some date object. Java has a java.time package for this purpose.

Just as a tip,

int two;
if (j + 1 == arr.size()) {
    two = arr.get(0);

} else {
    two = arr.get(j + 1);
}

Can also be written as:

int two = j + 1 == arr.size() ? arr.get(0) : arr.get(j + 1);

or, alternatively:

int two = arr.get(j + 1 == arr.size() ? 0 : j + 1);

Depending on how much duplication you can tolerate. The ? : part is known as the "ternary operator"/a "conditional expression".

if (!primes.contains(number_test)) {

This is quite expensive when done on a List like an ArrayList. If you need to use contains, you should probably be using a Set like a HashSet. Membership lookups are much faster using sets. The time difference will become increasingly noticeable as primes grows.


Bash functions to run/manage MySQL, Redis, Sidekiq, Rails server I'm working with a Rails app that requires a few layers of infrastructure to run: MySQL, Redis, Sidekiq, and (of course) the Rails server. I wrote some functions to help me manage the various servers (start/stop/check and one to kill the rails server when it gets hung up and decides to eat all my memory rather than shutting down).

I'm still new to Bash scripting, and looking for all the feedback/criticism I can get, so please, don't hold back. I'm particularly interested in how I can further DRY up this code.

Generic helpers to check if a named process is running and get its pid:

function running {
  pgrep -f "$1" &> /dev/null
}

function rpid {
  pgrep -f "$1" 2> /dev/null
}

MySQL server:

function msta {
  if ! running mysql; then
    mysql.server start
  else
    echo "MySQL already running"
  fi
}

function msto {
  if running mysql; then
    mysql.server stop
  else
    echo "MySQL not running"
  fi
}

function mstat {
  if running mysql; then
    echo "MySQL running"
  else
    echo "MySQL not running"
  fi
}

Redis server:

function resta {
  if ! running redis; then
    redis-server ~/.redis/redis.conf
    until running redis; do
      sleep 1
    done
    echo "Redis daemon started"
  else
    echo "Redis daemon already running"
  fi
}

function resto {
  if running redis; then
    kill $(rpid redis)
    while running redis; do
      sleep 1
    done
    echo "Redis daemon stopped"
  else
    echo "Redis daemon not running"
  fi
}

function restat {
  if running redis; then
    echo "Redis daemon running"
  else
    echo "Redis daemon not running"
  fi
}

Sidekiq:

function sksta {
  if ! running sidekiq; then
    sidekiq -d
    until running sidekiq; do
      sleep 1
    done
    echo "Sidekiq daemon started"
  else
    echo "Sidekiq daemon already running"
  fi
}

function sksto {
  if running sidekiq; then
    kill $(rpid sidekiq)
    while running sidekiq; do
      sleep 1
    done
    echo "Sidekiq daemon stopped"
  else
    echo "Sidekiq daemon not running"
  fi
}

function skstat {
  if running sidekiq; then
    echo "Sidekiq daemon running"
  else
    echo "Sidekiq daemon not running"
  fi
}

Rails server:

# kill the Rails server
function krs {
  if running 'rails s'; then
    kill $1 $(rpid 'rails s')
    for i in 1 2; do
      if ! running 'rails s'; then
        break
      else
        sleep 1
      fi
    done
    reportkill
  else
    echo "Rails server not running"
  fi
}

function reportkill {
  if ! running 'rails s'; then
    echo "Rails server killed"
  else
    echo "Rails server survived (pid $(rpid 'rails s'))"
  fi
}

# when a `kill -9` is required
function krs9 {
  krs '-9'
}

function rastat {
  if running 'rails s'; then
    echo "Rails server running"
  else
    echo "Rails server not running"
  fi
}

MySQL + Redis + Sidekiq

function asta {
  msta && resta && sksta
}

function asto {
  sksto && resto && msto
}

function astat {
  mstat && restat && skstat
}

Pretty nicely written! In fact, if you want to DRY this up, I'm pretty sure you could do it yourself if you seriously tried... But here you go anyway ;-)

Non-standard features

The function keyword is non-standard:

function rpid {
    pgrep -f "$1" 2> /dev/null
}

Write it this way instead:

rpid() {
    pgrep -f "$1" 2> /dev/null
}

DRY-ing up

You could write running in terms of rpid:

running() {
    rpid "$1" > /dev/null
}

rpid() {
    pgrep -f "$1" 2> /dev/null
}

This way, the pgrep logic is only in one place. If you need to change something, you could do it in one place. Just remember that the caller (running) expects the correct exit code of success / failure, and no output on stderr.

The start / stop / status commands have the common elements of checking if the process is running or not. You could create helper functions to reduce the duplication:

start() {
    procname=$1; shift
    name=$1; shift
    if ! running "$procname"; then
        "$@"
    else
        echo "$name already running"
    fi
}

stop() {
    procname=$1; shift
    name=$1; shift
    if running "$procname"; then
        "$@"
    else
        echo "$name not running"
    fi
}

status() {
    procname=$1
    name=$2
    if running "$procname"; then
        echo "$name running"
    else
        echo "$name not running"
    fi
}

Then you can simplify the MySQL functions using these helpers:

msta() {
    start mysql MySQL mysql.server start
}

msto() {
    stop mysql MySQL mysql.server stop
}

mstat() {
    status mysql MySQL
}

Similarly for redis:

redis_start() {
    redis-server ~/.redis/redis.conf
    until running redis; do
      sleep 1
    done
}

redis_stop() {
    kill $(rpid redis)
    while running redis; do
      sleep 1
    done
}

resta() {
    start redis "Redis daemon" redis_start
}

resto() {
    stop redis "Redis daemon" redis_stop
}

restat() {
    status redis "Redis daemon"
}

And I left the rest for you as exercise:

rastat can be simplified using status
krs can be simplified similar to the way I did redis above
You can leave reportkill as it is, as it's a different pattern from the others

There remains still some duplication in the start, stop, status helpers, but trying to reduce that might hurt readability. I think the current form is the "sweet spot", trying to optimize further will have diminishing returns.

shellcheck.net

This site is really awesome for checking your shell scripts for common mistakes:

http://www.shellcheck.net/#


Asynchronous dispatch queue Background:
This is supposed to be the sole worker thread to carry out long-lasting jobs in a GUI application. The GUI thread should be able to schedule tasks in a non-blocking manner and the tasks should que-up until the thread gets around executing them. I tried my best to make it exception safe.
Code:
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <utility>

class WorkerThread final {
 public:
  using Task = std::function<void(void)>;

 private:
  /* this mutex must be locked before
   * modifying state of this class */
  std::mutex _mutex;

  /* list of tasks to be executed */
  std::queue<Task> _toDo;

  /* The thread waits for this signal when
   * there are no tasks to be executed.
   * `notify_one` should be called to
   * wake up the thread and have it go
   * through the tasks. */
  std::condition_variable _signal;

  /* This flag is checked by the thread
   * before going to sleep. If it's set,
   * thread exits the event loop and terminates. */
  bool _stop = false;

  /* the thread is constructed at the
   * end so everything is ready by
   * the time it executes. */
  std::thread _thread;

 private:
  /* entry point for the thread */
  void ThreadMain() noexcept {
    /* Main event loop. */
    while (true) {
      /* not locked yet */
      std::unique_lock lock{_mutex, std::defer_lock_t{}};  // noexcept

      /* Consume all tasks */
      while (true) {
        /* locked while we see if
         * there are any tasks left */
        lock.lock();  // won't throw

        if (_toDo.empty()) {  // noexcept
          // Finished tasks. Mutex stays locked
          break;
        }

        // Pop the front task
        // move shouldn't throw
        auto const task = std::move(_toDo.front());
        _toDo.pop();

        // Allow other tasks to
        // be added while we're executing one
        lock.unlock();  // won't throw

        try {
          // execute task
          task();  // May throw. Will be caught.
        } catch (...) {
          // log if throws
        }
      }

      // queue is empty (and mutex is still locked)

      /* if `_stop` is set, unlock
       * mutex (in lock destructor)
       * and stop the thread */
      if (_stop) return;

      // wait for further notice (and unlock the mutex)
      _signal.wait(lock);  // won't throw
    }
  }

 public:
  template <class Func>
  void Schedule(Func&& func) {
    // lock the mutex so we can add a new task
    std::lock_guard<std::mutex> guard{_mutex};

    // push the task
    // May throw. RAII lock will be unlocked. State is valid
    _toDo.push(std::forward<Func>(func));

    // notify the worker thread in case it's sleeping
    _signal.notify_one();
  }

  WorkerThread() : _thread(&WorkerThread::ThreadMain, this) {}

  ~WorkerThread() {
    std::unique_lock lock{_mutex};  // won't throw
    // tell the thread to finish up
    _stop = true;

    // wake up the thread in case it's sleeping
    _signal.notify_one();  // noexcept

    lock.unlock();  // won't throw

    // wait for the thread to finish up
    _thread.join();  // won't throw since ThreadMain is noexcept
  }

  WorkerThread(WorkerThread const&) = delete;
  WorkerThread& operator=(WorkerThread const&) = delete;
  WorkerThread(WorkerThread&&) = delete;
  WorkerThread& operator=(WorkerThread&&) = delete;
};

// Example driver code

#include <chrono>
#include <iostream>

int main() {
  using namespace std::chrono_literals;

  int constexpr sz = 100;

  int vars[sz];

  {
    WorkerThread thread;
    for (int i = 0; i < sz; ++i) {
      thread.Schedule([&vars, i] {
        std::this_thread::sleep_for(1ms);
        vars[i] = i;
      });
    }
  }

  for (auto const var : vars) std::cout << var << '\n';
}

The parts marked with // won't throw are parts I believe won't possibly throw even though aren't marked with noexcept.

Remove redundant comments
You added a lot of comments to the code, but many of them are not very useful. Comments should be used to explain what the code does if this is not clear from reading the code itself. But for example:
std::queue<Task> _toDo;

I can see just from this line of code that this is a queue of tasks to be done, so the comment you wrote doesn't add any new information to this. Adding unnecessary comments just increases the noise to signal ratio, and actually makes the code less readable.
Avoid starting names with underscores
The C++ standard reserves some names starting with underscores. Unless you want to learn the exact rules, I recommend you don't start any names with an underscore, but instead use the prefix m_ or a single underscore as a suffix.
Avoid manually locking and unlocking mutexes
I recommed you just use a lock guard without std::defer_lock_t to lock those regions of code that need exclusive access to the data structures. So in MainThread(), I would write:
while (true) {
    std::function<void(void)> task;

    {
        std::unique_lock lock{_mutex};
        _signal.wait_for(lock, []{ return _stop || !_toDo.empty(); });

        if (_stop && _toDo.empty())
            break;

        task = std::move(_toDo.front());
        _toDo.pop();
    }

    task();
}

Notify without the lock held
While your code is correct, it is slightly more efficient to call notify_one() if you don't hold the lock. So for example, in the destructor you can write:
~WorkerThread() {
    {
        std::unique_lock lock{_mutex};
        _stop = true;
    }

    _signal.notify_one();
    _thread.join();
}


Split an array of items into several arrays, given a condition The question is very simple : I have an array of items, that all have a date. According to the date, I would like to split this array into several arrays.

In my case, I would like to split the array into 3 arrays : one that contains result of the last 24h, the other 48h, then the last one on the week.

Here is a minimal reproduction of the case, with the final solution.

const now = Date.now();
const day = 1000 * 3600 * 24;

const todayTime = now - day;
const yesterdayTime = now - day * 2;
const weekTime = now - day * 7;

const arr = [
  { id: 1, date: todayTime + 100 },
  { id: 2, date: yesterdayTime + 100 },
  { id: 3, date: weekTime + 100 },
];

const today = arr.filter(item => item.date - todayTime > 0);
const yesterday = arr.filter(item => item.date - yesterdayTime > 0 && item.date - todayTime < 0);
const week = arr.filter(item => item.date - weekTime > 0 && item.date - yesterdayTime < 0);

console.log(today, yesterday, week);

Is there a way to make it more concise ? I'm talking about code length : I would like to reduce it to the maximum, especially the definition of the 3 arrays. I tried with reduce, but the syntax is pretty ugly.

Any ideas ?

Always create a function
Its not really code if its not a function, you may as well just output the 3 arrays directly. (my personal view on global inline code).
You may say, "This is just an example". No it can not be just an example, a function has special powers and is written differently than inline code. Plus examples are boarder line off topic here, this question may get closed.
Part of a functions power is that it makes you think about how you solve the problem differently from inline code.
Look for change
When you write a function you look for the parts of the logic and data that change. You pass that to the function as arguments. The function uses these argument to process the data and return the desired results.
In this case you have

the array of items to split.
The number of days old to split the data, eg 1,2,and 7 days.

Thus we can have something like the following. The function is declared inside another so that all it needs is safely encapsulated and outside of unrelated scopes.
const splitByDaysOld = (() => {
    const MS_IN_DAY = 8.64e7;
    const sorter = (a, b) => a - b;
    return function(array, periods) {
        const now = Date.now();
        var start = 0;
        return periods.sort(sorter).map(day => {
            const res = array.filter(item => {
                const daysOld = (item.date - now) / MS_IN_DAY;
                return daysOld >= start && daysOld < day;
            });
            start = day;
            return res;
        });
    };
})();

It returns an array of arrays, one for each period.
Example below has 3 periods  0 to < 1, 1 to < 2, and 2 to < 7 days old.
const [today, yesterday, week] = splitByDaysOld(arr, [1, 2, 7]);

Note that the periods array is sorted from most recent to oldest and that the result will be in the same order


Counting words from stored .md files The following searches recursively for all the mark down files - i. ending with the extension .md - inside a folder. It then stores the text of the files in an array. Finally, it sums their word count using a wordCount() function (from the compromise package).
import nlp from 'compromise'
import fs from 'fs'
import path from 'path'

const filePaths = searchRecursive(`${__dirname}/test`, '.md')

const fileTexts = filePaths.map((filePath: string) => {
    return fs.readFileSync(filePath, 'utf-8')
}) // -> ['one two', 'one two three']

let totalWordCount = 0

fileTexts.forEach((fileText: string) => {
    totalWordCount += nlp(fileText).wordCount()
})

console.log(totalWordCount) // -> 5

function searchRecursive (dir: string, pattern: string) {
    ...
}

I've heard that forEach shouldn't be used in functional programming. How can I modify this code so it doesn't use forEach?

How to modify this code, so it doesn't use forEach?

One way to achieve this is using Array.prototype.reduce():
const totalWordCount = fileTexts.reduce((big: sum, fileText: string) => {
    return sum + nlp(fileText).wordCount()
}, 0)

Notice that totalWordCount is assigned once so const can be used which helps avoid accidental re-assignment and other bugs.
If fileTexts is only used to calculate totalWordCount then the two loops could be combined into a single loop (e.g. with reduce()).
To learn more about functional techniques try these functional exercises.