texts:
This Flask app, which makes use of SQLAlchemy, a MySQL server which is only reachable via SSH and Flask-Login, is the base on which I want to write an application which has login protected pages.

Registering users is a feature that I still have to write in a better way, but it works for now and testing purposes.

I'm posting this here because I want to be a 100% sure that my application is safe. I'm really curious to hear where I can improve, or if my application is reasonably safe. Cheers!

from flask import Flask, render_template, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_login import login_required, login_user, current_user, UserMixin, logout_user
from pathlib import Path
from sshtunnel import SSHTunnelForwarder
import re
import paramiko
import bcrypt

SSH_IP = "example.com"
SSH_PORT = 32452
SSH_USER = "ssh_user_here"
SSH_KEY = paramiko.RSAKey.from_private_key_file(Path(r'filepath\key.key'))
SSH_REMOTE_BIND_IP = "127.0.0.1"
SSH_REMOTE_BIND_PORT = 3306

DB_IP = "127.0.0.1"
DB_USER = "db_username"
DB_PASSWORD = "db_password"

app = Flask(__name__)
app.secret_key = 'randomly generated string'
wsgi_app = app.wsgi_app

login_manager = LoginManager()
login_manager.init_app(app)
#Defines to which page the user is redirected when it's trying to reach a protected page
login_manager.login_view = 'Login'

#Start SSH tunnel so app is able to connect to database
tunnel = SSHTunnelForwarder(
    (SSH_IP, SSH_PORT),
    ssh_username=SSH_USER,
    ssh_pkey=SSH_KEY,
    remote_bind_address=(SSH_REMOTE_BIND_IP, SSH_REMOTE_BIND_PORT))
tunnel.start()
#Connect to the actual database
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://' + DB_USER + ':' + DB_PASSWORD + '@' + DB_IP +':' + str(tunnel.local_bind_port)+'/' + "database name"
db = SQLAlchemy(app)

class User(UserMixin, db.Model):
    __tablename__ = 'Login'
    email = db.Column(db.String(200), unique=True, nullable=False, primary_key=True)
    password = db.Column(db.String(500))

    def get_id(self):
        return str(self.email)

    def check_password(self, password):
        return bcrypt.checkpw(password.encode('utf-8'), self.password.encode('utf-8'))

@login_manager.user_loader
def load_user(email):
    return User.query.filter_by(email=email).first()

def create_user(email, password):
    password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    password = password.decode('utf-8')
    new_user = User(email=email, password=password)
    db.session.add(new_user)
    db.session.commit()
    return

@app.route('/')
@login_required
def index():
    return render_template('index.html', current_user=current_user.email)

@app.route('/login', methods=['GET', 'POST'])
def login():
    #create_user("test@test.com", "testpassword123")

    # If the user is already logged in, redirect to index
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    # Check if all the fields are filled in
    if request.method == 'POST' and 'email' in request.form and 'password' in request.form:
        email = request.form['email']
        password = request.form['password']

        # Check if email is valid.
        if re.match(r'[^@]+@[^@]+\.[^@]+', email):

            user = User.query.filter_by(email=email).first()

            if user and user.check_password(password):
                login_user(user)
                return redirect(url_for('index'))
            else:
                return render_template('login.html', msg="Unknown email//password combination entered!")
        else:
            return render_template('login.html', msg='Please enter a valid e-mail address' )
    else:
        return render_template('login.html', msg='Please fill in the form!')
    return render_template('login.html', msg="")

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)


texts: Data structure for a list of radial coordinates

texts:
I have a loop that's updating a dictionary's values a large amount of time (by adding the new value to the old. Each value for each dictionary key is actually a list of 3 number, and so for each dictionary value the data structures that I thought of using are:

Python Lists:
The problem is that lists are inefficient at modifying numbers inside of them, and require indexing.
Numpy Arrays:
The problem is that numpy arrays are immutable and are taking a huge amount of time to do this.
Python tuples:
The worst of each world

My code looks like this:

class ModelErrors():

    def __init__(self):
        self.fwhm = 0.7 #arcsec
        self.sigma = self.fwhm/(2*np.sqrt(2*np.log(2)))
        self.TrM = 2*self.sigma**2
        self.PSF.TrM = self.TrM
        self.STAR.TrM = self.TrM
        self.survey_area = (np.radians(200),np.radians(50)) # in radians
        stars_X = np.random.rand(int(2000))*self.survey_area[0]
        Y = 0.77*np.random.rand(int(2000))/2 + 0.5
        stars_Y = np.arccos(2*Y-1) - np.pi/2 # random points on a sphere
        stars = np.array((stars_X,stars_Y))
        self.stars = stars.swapaxes(1,0)
        self.DELTA.M = defaultdict(list)
        self.STAR.M = defaultdict(list)
        self.PSF.M = defaultdict(list)
        self.n = defaultdict(int)

    def getModels(self, positions):
        '''calls one of the model methods to create an overly simplified model,
        or (N/A yet) imports one
        '''
        for i in range(len(positions)):
            self.radial_pattern(position_num=i)

    def radial_pattern(self,position_num):
        ''' method to create a radial pattern (one of the overly simplified models),
            e = 0.05* distance from origin
        '''
        from angles import r2d, r2arcs, d2arcs
        center = self.positions[position_num]
        stars = self.stars[np.where(((self.stars[:,0]-center[0])**2+(self.stars[:,1]-center[1])**2)<np.radians(1.2))[0]]
        rel_X, rel_Y = stars[:,0] - center[0], stars[:,1] - center[1]
        r = np.sqrt(rel_X**2+rel_Y**2)
        theta = np.arctan((rel_Y)/(rel_X))
        stare1 = r*np.cos(2*theta)*5
        stare2 = r*np.sin(2*theta)*5
        psfe1 = stare1/1.1
        psfe2 = stare2/1.1
        starMxx = 0.5*self.STAR.TrM*(stare1+1)
        starMxy = 0.5*self.STAR.TrM*stare2
        starMyy = 0.5*self.STAR.TrM*(-stare1+1)
        psfMxx = 0.5*self.PSF.TrM*(psfe1+1)
        psfMxy = 0.5*self.PSF.TrM*psfe2
        psfMyy = 0.5*self.PSF.TrM*(-psfe1+1)

        # populate new defaultdict with star/psf M[pos]=(Mxx,Mxy,Myy)
        for ind in range(len(psfMxx)):
            if (stars[ind][0],stars[ind][1]) in self.STAR.M.keys():
                self.n[(stars[ind][0],stars[ind][1])]+=1
            self.STAR.M[(stars[ind][0],stars[ind][1])]+=[starMxx[ind],starMxy[ind],starMyy[ind]]
            self.PSF.M[(stars[ind][0],stars[ind][1])]+=[psfMxx[ind],psfMxy[ind],psfMyy[ind]]

and then I call:

instance = ModelErrors()
instance.getModels(positions)

Is there a better data structure/more efficient way to do this?


texts:
This macro is made to randomly draw specific number of civilization choices for a specific number of Civ V players. It is based on a list of 43 possibilities and the for loop in the while loop checks for already picked civilizations. Constant cell references point to values obtained with scroll-bars in the worksheet. The variable based cell references are made to structure the results in a two-column design.

Are there any smart ways to make my code better from both an aesthetic as well as functional view?

Sub CIV_draw()
Range("K2:M50").ClearContents
Dim x As Integer
x = Cells(3, 3).Value
For i = 1 To x
    Cells(3 + (Cells(3, 7).Value + 2) * (i - 1), 11).Value = "Player " & i
    For j = 1 To Cells(3, 7).Value
        Dim Rand_CIV As String
        Dim RandNum As Integer
        Dim checkVal As Boolean
        checkVal = False
        While checkVal = False
            RandNum = CInt(Int(43 * Rnd())) + 1
            Rand_CIV = Cells(RandNum, 16).Value & " (" & Cells(RandNum, 15).Value & ")"
            For Z = 1 To 50
                If Cells(Z, 12) = Rand_CIV Then
                    Exit For
                End If
                If Z = 50 Then
                    checkVal = True
                End If
            Next Z
        Wend

        Cells((Cells(3, 7).Value + 2) * (i - 1) + (j + 3), 12).Value = Rand_CIV
    Next j
Next i
End Sub

I know for example that my duplicate check isn't optimal, and I would like to get suggestions for alternative solutions.


texts: Maintaining state while walking a tree structure

texts:
The following code creates a simple tree structure and then walks through the tree looking for node with the value 9 that appears after we have seen a node with the value 1 and a node with the value 4 (order of the 1 and 4 don't matter).
type N = Value of int  | Children of N list
type S = {oneFound:bool; fourFound:bool}

let walk () =
    let mutable state = {oneFound = false; fourFound = false}
    let rec walkImpl curNode =
        match curNode with
        | Value n ->    match n with
                        | 1 -> state <- {state with oneFound = true }
                        | 4 -> state <- {state with fourFound = true }
                        | 9 -> if state.oneFound && state.fourFound then
                                printfn "Found a good 9"
                               else
                                printfn "Found a bad 9"
                        | _ -> ()
                        printfn "Node value %d" n
        | Children c -> c |> List.iter (fun n -> walkImpl n)
    walkImpl (Children [Value 1; Value 2 ; Children [Value 9; Children [Value 4; Value 5]; Value 9]])

walk ()

When I run it produces the correct output:
Node value 1
Node value 2
Found a bad 9
Node value 9
Node value 4
Node value 5
Found a good 9
Node value 9

Is there a method to do this that threads the state through the recursive function calls rather than making it a mutable variable?  The mutability is confined to my function but I keep thinking there must be a way to structure this that makes it unnecessary.
In real life the tree structure will be much larger, several thousand nodes and 10 levels deep, while the  code has not run into any recursion limits yet are there improvements that would make this less likely?


texts:
Loosely basing myself on this blog post, I implemented an ordered dictionary. In essence, it's a wrapper struct for a list of tuples with some initialisers and some functions (map, filter, toArray, ...) added to it.

struct OrderedDictionary<KeyType: Hashable, ValueType>: SequenceType
{
    typealias KeyValueType = (key:KeyType, value:ValueType)

    private var tuples: [KeyValueType] = []

    init() {}

    init(_ tupleArgs: KeyValueType...)
    {
        self.init(tupleArgs)
    }

    init(_ tupleArgs: [KeyValueType])
    {
        tuples = tupleArgs
    }

    subscript(key:KeyType) -> ValueType?
    {
        get
        {
            return tuples.filter({ $0.key == key })[0].value
        }

        set(newValue)
        {
            if let val = newValue
            {
                if tuples.contains({ $0.key == key })
                {
                    tuples = tuples.map({ $0.key == key ? ($0.key, val) : $0 })
                }
                else
                {
                    tuples.append((key, val))
                }
            }
            else
            {
                tuples = tuples.filter({ $0.key != key })
            }
        }
    }

    func generate() -> AnyGenerator<KeyValueType>
    {
        var nextIndex = 0
        return anyGenerator({
            if nextIndex >= self.tuples.count
            {
                return nil
            }
            else
            {
                return self.tuples[nextIndex++]
            }
        })
    }

    mutating func insert(tuple: KeyValueType, atIndex index: Int)
    {
        tuples = tuples.filter({ $0.key != tuple.key })
        tuples.insert(tuple, atIndex: index)
    }

    func map<NewKeyType:Hashable, NewValueType>(transform: (KeyValueType) -> (key:NewKeyType, value:NewValueType)) -> OrderedDictionary<NewKeyType, NewValueType>
    {
        return OrderedDictionary<NewKeyType, NewValueType>(tuples.map(transform))
    }

    func filter(includeElement: (KeyValueType) -> Bool) -> OrderedDictionary<KeyType, ValueType>
    {
        return OrderedDictionary(tuples.filter(includeElement))
    }

    func sort(isOrderedBefore: (KeyValueType, KeyValueType) -> Bool) -> OrderedDictionary<KeyType, ValueType>
    {
        return OrderedDictionary(tuples.sort(isOrderedBefore))
    }

    func reverse() -> OrderedDictionary<KeyType, ValueType>
    {
        return OrderedDictionary(tuples.reverse())
    }

    func toArray<T>(transform:((KeyValueType) -> T)) -> [T]
    {
        return tuples.map(transform)
    }

    func toArray() -> [KeyValueType]
    {
        return tuples
    }

    func toDict() -> [KeyType:ValueType]
    {
        var dict: [KeyType:ValueType] = [:]
        for tuple in tuples
        {
            dict[tuple.key] = tuple.value
        }
        return dict
    }
}

Does this look okay? Is it Swift-y enough and are there no major performance issues? I'm a bit worried about the filter, map, reverse and sort functions, but I'm not sure why. I'm also not confident about my use of map in the subscript setter.


texts:
The problem I am facing is:
I need to interate through a bunch of lists, and there are separated conditions which needs to be satisfied by the list. conditons are not independent.

I care about the situation when all the conditions are matched.

The solutions I come up is nested interations mixed with conditions on each level, but it is rather ugly and not easy to maintain.

Is there a way for me to improve this code?

[1, 2, 3].each do |n1|
  if n1 == 1
    [1, 2, 3].each do |n2|
      if n2 == 2
        [1, 2, 3].each do |n3|
          if n3 == 3
            [1, 2, 3].each do |n4|
              if n4 == n3 # conditions are dependent
                print n1, n2, n3, n4
              end
            end
          end
        end
      end
    end
  end
end


texts:
This query executes very slowly and I wonder if it can be improved?

We have an Access database split to front end / back end with around 50 users. BE is in a network folder and FE is on users' hard drives.

Data entered into the FE is stored in FE tables until the user has finished inputting all the required data for a record. They then click a button to send the data to the BE in one go, to  identical tables as in the FE. In the sql below the BE table is suffixed with '_Share'.

The table contains 2 keys: QuoteID and OptionID. There is a one-to-many between the two e.g.:

QuoteID   OptionID

1234      1
1234      2

3333      1
3333      2
3333      3

As they user works they are creating data for new Options to go with existing Quotes. What the code is doing is to check whether a QuoteID on the BE already has an OptionID created by the user on the FE, if not then the data for that OptionID is appended to the BE.

INSERT INTO T_Option_Category_Benefits_Share
SELECT T_Option_Category_Benefits.*, *
FROM T_Option_Category_Benefits
WHERE (((T_Option_Category_Benefits.QuoteID)=1971)
AND ((T_Option_Category_Benefits.OptionID)
NOT IN (SELECT T_Option_Category_Benefits_Share.OptionID FROM T_Option_Category_Benefits_Share WHERE T_Option_Category_Benefits_Share.QuoteID=1971)));

The key fields are not indexed. The BE table contains 18 columns with around 100k rows. The network is generally quite slow at busy times but time of day doesn't have much effect. Amount of rows to append is only around 300 on average. We're using Office 365 on Windows 10.


texts: Point distance program written without a framework

texts:
I have been developing a cross-platform game based on open C libraries (mainly glfw) with a direct focus on Windows development. The beginning of my programming career taught me familiarity in Objective-C, however I've been using pure C for the past few years in embedded applications.

Now that I'm trying to return to proper desktop program development, I'm wondering if it's a good idea to transfer my Objective-C skills to Windows in order to tidy up my C code. My current way of programming is creating a struct for data that I need and then creating functions around those structs: struct Point {int x, int y}; and then float Point_calculateDistance(struct Point *obj1, struct Point *obj2). This approach to me seemed very redundant and too object-oriented to write all in C. It would make more sense to me to write an Objective-C class to do this where everything can be more encapsulated.

I prefer not to use any framework for my code to increase the portability. I'm currently using VS Code and MSYS2 (mingw64) with GCC 8.3.0. I threw together a working example that demonstrates how I attempt to build a simple class. Does my code look reasonable? Am I performing any bad habits (within reason considering that I'm not using a framework)? Does this currently leak memory? Let me know what you think.

#include <objc/objc.h>
#include <objc/runtime.h>
#include <objc/Object.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

@interface Point : Object {
    float x;
    float y;
}

@property float x;
@property float y;

-(id)initWithX: (float)xval AndY: (float)yval;
-(float)calculateDistance: (Point *)other;

@end

@implementation Point

@synthesize x;
@synthesize y;

+(id)alloc {
    id obj = malloc(class_getInstanceSize(self));
    object_setClass(obj, self);
    return obj;
}

-(void)dealloc {
    free(self);
}

-(id)init {
    x = 0.0;
    y = 0.0;
    return self;
}

-(id)initWithX: (float)xval AndY: (float)yval {
    x = xval;
    y = yval;
    return self;
}

-(float)calculateDistance: (Point *)other {
    return sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));
}

@end

int main(int argc, char **argv) {
    Point *point1 = [[Point alloc] init];
    Point *point2 = [[Point alloc] initWithX: 1.5 AndY: 1.5];

    printf("Distance is %f.\n", [point1 calculateDistance: point2]);

    [point1 dealloc];
    [point2 dealloc];
    return EXIT_SUCCESS;
}


texts:
Tried to make a binary search algorithm, how did I do?

def homogeneous_type(list1):
    i_list = iter(list1)
    listtype = type(next(i_list))
    return True if all(isinstance(x, listtype) for x in i_list) else False

def binSearch(list1, value):

    if not list1:
        raise ValueError("list is empty")
    if not homogeneous_type(list1):
        raise ValueError("list must be one type")

    left = 0
    right = len(list1) - 1
    list1 = sorted(list1)

    while left <= right:

        midIndex, mod = divmod(left + right, 2)
        midIndex = midIndex + 1 if mod else midIndex

        if list1[midIndex] == value:
            return midIndex
        elif list1[midIndex] < value:
            left = midIndex + 1
        elif list1[midIndex] > value:
            right = midIndex - 1

    raise ValueError("value not in List")


texts: `sfinae` proposal... useful or unnecessary?

texts:
I am trying to learn what SFINAE is. I believe I understand it quite well; however, I do not have a lot of practice in the subject. I mean I would find it difficult to list all the cases in which SFINAE should or could be used, or it would be difficult for me to immediately understand what a given sample of an SFINAE code should do. However, I believe I understand the core concept well enough to use it effectively.

Nonetheless looking through examples of SFINAE usage I came to the few conclusions.

One of which is: it is extremely pointless to use a chain of std::enable_if_t, std::void_t, std::is_same, etc, etc, etc, to define a single type using type = int *. IMHO (of a "newbie" with untrained eyes) such chains make the code less (extremely less) readable.

The second conclusion was: wouldn't it be useful to have the ability to check few conditions at the same time?

So I created this alias: (well "created" is waaay too big word... I just wrote 4 lines of code...)

template<typename T, typename ...>
using sfinae = T;

template<typename T, typename ...>
using SFINAE = T;

Usage examples

// 1) within class declaration:
template <typename T,
    sfinae<bool,
        std::enable_if_t<std::is_integral_v<T>>,
        std::enable_if_t<std::is_arithmetic_v<T>>
    > = true /* provide default option, bc reasons */>
class foo;

// 2) within function declaration:
template <typename T,
    sfinae<bool,
        std::enable_if_t<std::is_integral_v<T>>,
        std::enable_if_t<std::is_arithmetic_v<T>>
    > = true /* provide default option, bc reasons */>
void foo;

// 3) as a function return type:
template <typename T>
sfinae<T,
    std::enable_if_t<std::is_integral_v<T>>,
    std::enable_if_t<std::is_arithmetic_v<T>>
> const & foo(T const & val);

// 4) To define other SFINAE-conditions as aliases:
template <typename T>
using check_xyz = sfinae<void,
    std::enable_if_t<std::is_integral_v<T>>,
    std::enable_if_t<std::is_arithmetic_v<T>>
>;

template <typename T, typename = check_xyz<T>>
class foo;

And my main concern/question is: would a professional c++ developer deem sfinae</*...*/> (as I proposed it) useful or extremely unnecessary? Are there any changes that could be introduced to the idea?


texts:
I made a shader to display a YUYV surface (data arranged as: Y0 U0 Y1 V0). It's working, but I don't know anything about shaders, or openGL, or anything graphic related as a matter of fact. I feel more like a mad scientist patching random bits of code together than a programmer. Thus, I would appreciate if anyone could look it up and tell me what I could improve, performance-wise, logic-wise or syntax-wise. I also have some questions:

What desktop hardware will that work on? Is there any restriction, or will it work on any  10 years old desktop?
Would that work on an android tablet?
Will any interpolation of pixel be performed, if my rendering surface is the same size as the texture? Is it possible to have interpolation (with some flag, not by implementing it)?

I load my YUYV texture as RGBA texture of width/2 by height. The rest should be self-explanatory:

#version 330 core
uniform sampler2D tex;
uniform mat4 convMat; /* Color conversion matrix */
uniform vec2 dim; /* Width and height of image */
in vec2 UV;
out vec3 color;

void main(){
    vec4 yuv;
    ivec2 iUV = ivec2(UV*dim*vec2(0.5, 1)); /* Absolute coordinate of desired pixel in texture */

    yuv = texelFetch(texy, iUV, 0);
    if (int(UV.x*dim.x) % 2 == 1){
        /* There are 2 Y in a texture RGBA pixel, choose the right one based on absolute pixel coordinate */
        yuv.x = yuv.z;
    };
    yuv.z = yuv.w;
    yuv.w = 1;
    color = (convMat*yuv).rgb;
};


texts: Calculating the ranks of classmates' exam grades

texts:
The questions from hackerearth:

  Geeko is in worry now because an exam is coming up and he has to know
  what rank he can get on exams. So he goes back into the the school records
  and finds the amazing pattern.

  He finds that if a student is having a current rank \$n\$, then his rank on
  the final exam will be the count positive numbers between in the range
  \$[1,n]\$ which are relatively prime to \$n\$.

  As being a geek, he became curious now and wants to calculate the rank of
  all his classmates on the final exam.  But he finds this task a bit hard,
  so he asks you programmers to solve this task for him.

  Input: The first line of each test file contains a integer \$t\$ denoting
  the number of test case.  Each test case contains a numbers \$n\$
  representing the current rank of each student

  Output: for each test case output single integer the rank of student
  in final exam in new line.

  Constraints:

  \$1 <= t <= 2000\$

  \$1 <= n < 10^6\$

My solution:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;

class relative {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        ArrayList<Integer> input = new ArrayList<Integer>();

        ArrayList<Integer> result = new ArrayList<Integer>();
        // int input[] = new int[t];
        // int result[] = new int[t];
        for (int i = 0; i < t; i++) {
            int count = 1;
            int in;
            input.add(in = Integer.parseInt(br.readLine()));
            for (int j = 2; j < in; j++) {
                if (in % j == 0)
                    continue;
                else if (checkRelativePrime(j, in))
                    count++;
            }
            result.add(count);
        }
        for (int i : result)
            System.out.println(i);
    }

    static boolean checkRelativePrime(int a, int b) {
        int i = 2;
        while (a > 1) {
            if (a % i == 0) {
                {
                    if (b % i == 0)
                        return false;
                }
                a = a / i;
            } else
                i++;
        }

        return true;
    }
}


texts:
The context is Weekend Challenge #2 (Poker hand evaluation).

Hand.prototype.isStraight = function()
{
  for( var i = 1 ; i < this.cards.length ; i++ )
    if( this.cards[i].value + 1 != this.cards[i-1].value )
      return false;
  return true;
}

cards is an array with card objects { suit : "x" , value : "0->12" }.  The cards are sorted during the creation of the hand.

My approach to detect straightness seems like the hard way.  Can anyone suggest something else?

Okay, Poker is tough.  I will revise this question once I have my new isStraight.


texts: Generate ISO 8601 Duration String from Two Date Objects

texts:
I've written a function which should generate an ISO 8601 duration string, given two Dates as input.

import {
  differenceInYears,
  differenceInMonths,
  differenceInWeeks,
  differenceInDays,
  getDaysInYear,
  eachYearOfInterval,
} from 'date-fns/esm'; // v2.11.0

/**
 * Given a start Date and an end Date, returns an ISO 8601 duration string
 * Only supports Year, Month, Week, and Day. Does not support Hour or smaller.
 * @param  {Date} start
 * @param  {Date} end
 * @return {string} ISO 8601 Duration
 * @example
 * ```js
 * toISODurationString(new Date('2020'), new Date('2021'));
 * // => PY1
 * ```
 */
export function toISODurationString(start, end) {
  const differenceInDaysOverYears =
    eachYearOfInterval({ start, end })
      .map(getDaysInYear)
      .map(days => days % 365)
      .reduce(add) - 365;

  const Y = differenceInYears(end, start);
  const M = differenceInMonths(end, start) - 12;
  const W = differenceInWeeks(end, start) - 52;
  const D = differenceInDays(end, start) - (365 + differenceInDaysOverYears);

  return Object.entries({ Y, M, W, D })
    .reduce((s, [c, v]) => `${s}${v !== 0 ? c + v : ''}`, 'P');
}

I'm concerned about the differenceInDaysOverYears part. Is this code reliable? Specifically, will it robustly handle any Date you give it?


texts:
I am using code like this everywhere. How can I reduce such this code so that my Ruby code looks a lot cleaner?

Fabricate(:tl, :when =>Date.yesterday.to_s,:work => 266,:type => "fast" )
Fabricate(:tl, :when =>Date.yesterday.to_s,:work => 100,:type => "super_fast" )
Fabricate(:tl, :when =>Date.yesterday.to_s,:work => 50,:type => "ludicrous" )
Fabricate(:tl, :when =>Date.yesterday.to_s,:work => 900,:type => "budget" )


texts:
I find this code quite ugly, but in fact, I can't find a finer way of achieving the goal.

private static final String TABLE_NAME = "table_name";
private static final String[] allNeededColumns = {"col_id","col_one","col_two"};

public int[] getItemIds(int category_id) {
    ArrayList<Integer> ids = new ArrayList<Integer>();
    Cursor c = getDatabase().query(TABLE_NAME, allNeededColumns, CATEGORY_ID + "=" + category_id, null, null, null, null);
    c.moveToFirst();
    while(!c.isAfterLast()){
        ids.add(Integer.valueOf(c.getInt(2)));
        c.moveToNext();
    }
    return convertIntegers(ids);
}

public static int[] convertIntegers(ArrayList<Integer> integers)
{
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
    {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}

The purpose is to get out of table int array, where IDs are item IDs from category bycategory_id`.

The problem is, I need some kind of expandable collection to add DB result ID to, and return primitives array, and I find it prettier than creating new int[] variable for each iteration on Cursor.

Can you think of a prettier solution?


texts:
What do you think of this implementation of an LRU cache? I'm trying to migrate to modern C++, so it would be fantastic if you could give me any tips here. I've heard it's not desired to use raw pointers, right? What about only internally, as in the example?

Also, since I can't return a nullptr value in the get() method, what is the best alternative for this? Default value as in the example?

#ifndef __LRU_HPP__
#define __LRU_HPP__
#include <map>
#include<iostream>
#include<assert.h>

template<class T>
struct Default {
  T value;
  Default():value(){}
};

template<class K, class V>
struct node {
  K key;
  V value;
  node<K,V>* next;
  node<K,V>* prev;
  explicit node(K key, V value);
};

template<class K, class V>
class lru {
private:
  node<K,V>* head;
  node<K,V>* tail;
  std::map<K,node<K,V>*> map;
  std::size_t capacity;
  void replace(node<K,V>*);
public:
  explicit lru(std::size_t);
  void put(K key, V value);
  V get(K key);
};

template<class K, class V>
inline node<K,V>::node(K key, V value) {
  this->key = key;
  this->value = value;
}

template<class K, class V>
inline lru<K,V>::lru(std::size_t capacity) {
  assert(capacity > 1);
  this->capacity = capacity;
  this->head = tail = nullptr;
}

template<class K, class V>
void lru<K,V>::put(K key, V value) {
  auto it = map.find(key);
  if (it != map.end()) {
    node<K,V>* temp = it->second;
    temp->value = value;
    replace(temp);
    return;
  }
  if(capacity == map.size()) {
    tail->prev->next = tail->next;
    node<K,V>* target = tail;
    map.erase(target->key);
    tail = tail->prev;
    delete tail;
  }
  node<K,V>* temp = new node<K,V>(key, value);
  temp->prev = nullptr;
  temp->next = head;
  if(head != nullptr)
    head->prev = temp;
  else
    tail = temp;
  head = temp;
  map.insert(std::pair<K,node<K,V>*> {key, temp});
}

template<class K, class V>
V lru<K,V>::get(K key) {
  auto it = map.find(key);
  if(it != map.end()) {
    replace(it->second);
    return it->second->value;
  }
  return Default<V>().value;
}

template<class K, class V>
void lru<K,V>::replace(node<K,V>* temp) {
  if (temp->prev != nullptr)
    temp->prev->next = temp->next;
  if (temp->next != nullptr)
    temp->next->prev = temp->prev;
  if (tail == temp)
    tail = temp->prev != nullptr ? temp->prev : temp;
  if (head != temp) {
    head->prev = temp;
    temp->next = head;
    head = temp;
  }
}
#endif


texts:
UPDATE

New regex - covers escaped slashes and uses lazy qualifiers:

/(?>(')(?>(?>\\\\)|\\'|.)*')|(?>(")(?>(\\\\)|(?>\\")|.)*")|(?>((?>\/\/|#)).*^)|(?>(\/\*).*\*\/)/msU

Here are the different parts:

Single quotes: (?>(')(?>(?>\\\\)|\\'|.)*')

Double quotes: (?>(")(?>(\\\\)|(?>\\")|.)*")

Single line comments: (?>((?>\/\/|#)).*^)

Multiline comments: (?>(\/\*).*\*\/)

I moved the html comments to a different regex because html will be handled differently.

Here's an example of what it does: (The matched parts are bold)

//single line comment

random text ... #another comment

Multiline comments:

/* this is a multiline comment

matches the whole thing
*/

Quotes:

"also matches strings with \" escaped quotes or 'the other kind of quotation marks in it' "

'matches the end quote because it it not escaped \\'

This is the original post:

I'm working on making syntax highlighting on my blog, and I created a regex to match strings and comments (I'm going to make a callback function to format each differently)

Here's my regex:

(?>(")(?>[^"]|(?>(?<=\\)"))*")|(?>(')(?>[^']|(?<=\\)')*')|(?>((?>\/\/|#))[^\n\r]*)|(?>(\/\*)(?>.(?!\*\\))*\*\/)|(?>(<!--)(?>.(?!-->))*.-->)

I tested it and it seemed to work, but is there anything I'm missing or an easier  way to do it? It currently matches strings ("...", '...') and takes into account escaped chars and strings within other strings. It also matches comments (//..., #..., /*...*/, <!--...-->).

Here's what I'm using each part of the regex for:

Part 1: (?>(")(?>[^"]|(?>(?<=\\)"))*"): Match strings quoted with "

Part 2: (?>(')(?>[^']|(?<=\\)')*'): Match strings quoted with '

Part 3: (?>((?>\/\/|#))[^\n\r]*): Match single line comments # or //

Part 4: (?>(\/\*)(?>.(?!\*\\))*\*\/): Match multiline comments /*...*/

Part 5: (?>(<!--)(?>.(?!-->))*.-->): Match html comments <!--...-->


texts:
I have a program that specifies when an alarm should be active (say, 10AM to 8PM). Part of my program then checks if the alarm is active right now. The "is it active" checker needs to deal with alarm ranges that cross the midnight boundary into tomorrow (say, 8PM to 10AM alarm).

I am currently handling this with redundant functions that are identical, except for AND vs OR comparison. What is the better way, please? (Of course, any other review comments are also most welcome.)

import datetime as dt

def check_alarm_bounds_on_same_date(time_now, time_of_day_bounds):
    time_start_of_current_day = dt.datetime.combine(time_now.date(), dt.datetime.min.time())
    if ( time_now >= (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[0])) and #<< AND
         time_now < (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[1])) ):
        return True
    return False

def check_alarm_bounds_on_different_dates(time_now, time_of_day_bounds):
    time_start_of_current_day = dt.datetime.combine(time_now.date(), dt.datetime.min.time())
    if ( time_now >= (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[0])) or #<< OR
         time_now < (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[1])) ):
        return True
    return False

def is_alarm_live(time_current, time_of_day_bounds):
    alarm_start_time = time_of_day_bounds[0]
    alarm_end_time = time_of_day_bounds[1]
    if alarm_end_time <= alarm_start_time:
        return check_alarm_bounds_on_different_dates(time_current, time_of_day_bounds)
    else:
        return check_alarm_bounds_on_same_date(time_current, time_of_day_bounds)

# specify two alarm periods (#1 @ 10AM-8PM; #2 @ 8PM-10AM next day)
alarms = [(10,20),(20,10)]
for hour in range(0,24):
    # test all hours in a sample day, and output which alarm is active
    print 'hour %i: ' % hour,
    time_test = dt.datetime(2017,01,22,hour,10,30)
    for alarm in alarms:
        print is_alarm_live(time_test, alarm),
    print ''


texts: Simulate sliding range selector with string values

texts:
I need to have a range selector that accepts string values instead of integer value.
This is not possible with standard HTML, so I needed to simulate one by using (hidden) radio buttons that are coupled with the range selector and change the label of the range selector accordingly.
My code is a bit of a mess, though. Could you help me clean it up?

{
  "use strict";
  console.clear()
  const selector = 'input[type="radio"][data-range-selector]'

  let radios = Array.from(document.querySelectorAll(selector)).reduce((acc, el) => {
    acc[el.name] = acc[el.name] || {form: el.form, elements: []}
    acc[el.name].elements.push({
      'element': el,
      'value': el.dataset.rangeValue,
      'selector': el.dataset.rangeSelector,
    })
    el.dataset.rangeValue = acc[el.name].elements.length - 1
    return acc
  }, {})

  const getRadio = el => {
    return el.form.querySelector(`input[type="radio"][data-range-value="${el.value}"]`)
  }

  const getLabelForInput = el => {
    return el.form.querySelector(`label[for="${el.id}"]`)
  }

  const getRangeSelector = el => {
    return el.form.querySelector(el.dataset.rangeSelector)
  }

  Object.keys(radios).forEach(key => {
    var rangeSelector = getRangeSelector(radios[key].elements[0].element)
    rangeSelector.setAttribute('max', radios[key].elements.length - 1);
    rangeSelector.dataset.key = key

    radios[key].form.addEventListener('input', function(e) {
      if (e.target.matches('input[type="range"][data-key]')) {
        getLabelForInput(e.target).innerHTML = getLabelForInput(getRadio(e.target)).innerHTML
        getRadio(e.target).checked = true
        // getRangeSelector(e.target).value = e.target.dataset.rangeValue
      }
    })
  })

  // document.addEventListener('change', e => console.log(e.target.form))
}
[data-range-selector], [data-range-selector] + label {
  display: none;
}

Simulate a sliding range selector with string values

<form>
  <input type="radio" name="evil" value="" id="evil" data-range-selector="#evil-range" />Choose
  <input type="radio" name="evil" value="one" id="evil-one" data-range-selector="#evil-range"  />One
  <input type="radio" name="evil" value="twin" id="evil-twin" / data-range-selector="#evil-range"  >Twin
  <input type="radio" name="evil" value="six" id="evil-six" data-range-selector="#evil-range"  />Six
  <input type="radio" name="evil" value="666" id="evil-666" data-range-selector="#evil-range"  />666
  <input type="range" id="evil-range" min="0" value="0">Choose
</form>

<form>
  <input type="radio" name="good" value="" id="good" data-range-selector="#good-range" data-range-value="0" />Choose
  <input type="radio" name="good" value="one" id="good-one" data-range-selector="#good-range" data-range-value="1" />One
  <input type="radio" name="good" value="twin" id="good-twin" / data-range-selector="#good-range" data-range-value="2" >Twin
  <input type="radio" name="good" value="six" id="good-three" data-range-selector="#good-range" data-range-value="3" />Tree

  <input type="range" id="good-range" min="0" value="0">Choose
</form>


texts:
I just recently started reading the python.org documents and it looked like a really interesting language. Now, since Visual Studio 2017 supports Python, I decided to finally actually start learning it. My friend challenged me to write a program that checks if a number is an Armstrong number.

import sys

def isArmstrong(number):
    arr = str(number)
    count = len(arr)
    res = 0
    for x in range(0, count):
        res += int(arr[x]) ** count
    return res == number

if len(sys.argv) > 1:
    arg = sys.argv[1]
    print(arg + " is an armstrong number: " + str(isArmstrong(int(arg))))
else:
    print("No arguments passed! :-(");

Now this is the first solution that I could come up with. As you can see, it converts the number to a string to determine the amount of digits, and then handle them individually. Is this the smartest way to do it, or can it be done without converting to a string? If not: Is there anything I can do to improve this code performance-wise?


texts: How can this simple coroutine implementation be improved?

texts:
This is a quick and dirty implementation of coroutines that implements yield by saving and restoring the stack to and from the heap. Here's an earlier version, which does the most naive possible thing, and just allocates enough space on the stack for every possible coroutine. The relevant bits from the current code are below, and the whole thing is here.

I'm open to feedback both on pretty much anything: completely different approaches, how to restructure this approach, bugs, idiomatic C style pointers, etc.

An obvious performance improvement would be to use ucontext, but that seems to be deprecated and somewhat broken on Mac OS X (although it works fine on the linux distros I've tried). I'm not sure what the next step is to make this 'better'.

typedef void (*coroutine_cb)();

static void scheduler(coroutine_cb);
static int spawn(coroutine_cb);
static void yield(int);

jmp_buf scheduler_jmp;
void *scheduler_rbp;
int coro_pid;

coroutine_cb scheduler_next_coro;

#define MAX_COROS 100

struct {
  jmp_buf jmp;
  void *stack;
  long stack_sz;
} coroutines[MAX_COROS];

static void scheduler(coroutine_cb coro)
{
  printf("starting the scheduler...\n");
  static int max_pid = 1;

  // we move down 0x1000 to give scheduler space to call functions and allocate stack variables without having them get
  // overwritten by the memcpy below. Before we did this, we had to manually copy memory instead of using memcpy
  // because we would overwrite memcpy's stack
  scheduler_rbp = __builtin_frame_address(0) - 0x1000;
  scheduler_next_coro = coro;
  int value = setjmp(scheduler_jmp);
  // value == 0 means just starting
  // value == -1 means spawning new coroutine
  // value positive means hop back to a specific pid
  if (value == 0 || value == -1)
  {
    coro_pid = max_pid++;
    printf("about to run coro %d...\n", coro_pid);
    char *buf = alloca(0x2000); // was 0x1000 when we didn't allocate extra space for scheduler stack
    asm volatile("" :: "m" (buf));
    scheduler_next_coro();
    assert(0);
  }
  else
  {
    printf("jumped back to scheduler (pid --> %d) (coro_pid --> %d)...\n", value, coro_pid);
    // restore coroutine marked by value (pid)
    coro_pid = value;

    int stack_sz;
    stack_sz = coroutines[coro_pid].stack_sz;
    memcpy(scheduler_rbp - stack_sz, coroutines[coro_pid].stack, stack_sz);
    longjmp(coroutines[coro_pid].jmp, 1);
    assert(0);
  }
}

static void yield(int pid)
{
  // take current rbp
  void *rbp = __builtin_frame_address(0);
  void *fudgy_rsp = (char *)rbp - 0x100;
  assert(scheduler_rbp > rbp);

  long stack_sz = (char *)scheduler_rbp - (char *)fudgy_rsp;
  void *stack = malloc(stack_sz);

  /*
   * Marek: check how overflowing stack actually works, because
   * we're actually copying data beyond our stack frame.
   */
  memcpy(stack, fudgy_rsp, stack_sz);
  coroutines[coro_pid].stack = stack;
  coroutines[coro_pid].stack_sz = stack_sz;

  if (!setjmp(coroutines[coro_pid].jmp))
  {
    longjmp(scheduler_jmp, pid);
    assert(0);
  }
  else
  {
    // our stack is already good to go at this point
    return;
  }
}

/*
 *
 */
static int spawn(coroutine_cb coro)
{
  scheduler_next_coro = coro;
  yield(-1);
  return 0; // need to get pid
}

int main()
{
  scheduler(f);
  assert(0);
  return 0;
}


texts:
I have this piece of code in Python 2.7:
As you can see is very hard to read the SQL query, what is the best way to re-write it?

    try:
        if title and url:
            sql_query = "INSERT INTO news (title, author, description, " \
                        "content, url, url_to_image, source_id, source, " \
                        "campaign, published_at, score, magnitude, sentiment, " \
                        "inserted_at ) VALUES ('%s','%s','%s','%s'," \
                        "'%s','%s','%s','%s','%s','%s', %s, %s, '%s', '%s')" \
                        % ( title.replace("'", "''"),
                            author.replace("'", "''"),
                            description.replace("'", "''"),
                            content[:settings.content_size].replace("'", "''"),
                            url,
                            url_to_image,
                            source_id,
                            source,
                            campaign,
                            published_at,
                            score,
                            magnitude,
                            sentiment,
                            DB_NOW)
            db = Db.Db()
            db.initialize(dsn=settings.SQLALCHEMY_DSN)
            return db.insert_content(sql_query, 'news_id')
    except psycopg2.ProgrammingError as exception:
        log.exception(exception)`enter code here`


texts: Scraping the full content from a lazy-loading webpage

texts:
I've written a script in python in combination with selenium which is able to scrape 1000 links from a webpage in which lazy-loading method is applied for that reason it displays it's content 20 at a time and full content can only be seen when it is made to scroll downmost. However, my script can scroll the webpage to the end. After collecting the 1000 links from main page, it then gets to each individual link to scrape the Name of CEO and Web address of that organization. It is working great now. I tried to make the whole thing accordingly. Here is the full code:

from selenium import webdriver
import time

def get_links(driver):

    driver.get('http://fortune.com/fortune500/list/')

    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(3)

        links = [posts.get_attribute("href") for posts in driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]//a")]
        if (len(links) == 1000):
                break

    for link in links:
        process_links(driver, link)

def process_links(driver, sub_links):

    driver.get(sub_links)

    for items in driver.find_elements_by_xpath('//div[contains(@class,"company-info-card-table")]'):
        Name = items.find_element_by_xpath('.//div[contains(@class,"small-7")]/p[@class="remove-bottom-margin"]')
        Web = items.find_element_by_xpath('.//div[contains(@class,"small-9")]/a')

        print(Name.text, Web.get_attribute("href"))

if __name__ == '__main__':

    driver = webdriver.Chrome()
    try:
        get_links(driver)
    finally:
        driver.quit()


texts:
I am currently working on creating a tree (this is my learning process of creating a minimax tree and am starting towards minimax tree from here) with multiple nodes recursively.

Can anyone please determine if the algorithm is correct? From my perspective and couple of test (using print, count and gdb), I think I am creating the tree that I want, which looks like this:

The code for this tree:

#include <iostream>
#include <vector>
#define SIZE 3 //  this is number of child nodes a node will have

using namespace std;

struct Node{

    std::vector<Node*> v_node;
    std::vector<int> my_vec;
    int val;
};

class Tree{

    Node *root;
    int size;
    int count;

    void create_tree(Node *n, int size){
        if(size == 0) return;

        count++;
        for(int i = 0; i < SIZE; i++){
            Node * node = new Node;
            node->v_node.resize(SIZE, nullptr);
            node->my_vec.resize((size-1), n->my_vec[0]-1); // decrease val of vector by 1 in each level
            node->val   = i;
            n->v_node[i] = node;
            create_tree(node, size-1); // recursively call
        }
    }

public:

    Tree(int s){
        size = s;
        root = new Node;
        root->v_node.resize(SIZE, nullptr);
        root->my_vec.resize(s, 36);
        root->val = 0;
        count = 0;
    }
    void ct(){
        create_tree(root, size);
    }
    int get_node_count(){
        return count;
    }
};

int main(){

    Tree t(4); //
    t.ct();

    std::cout << "Node count = " << t.get_node_count() << std::endl;

}

My core questions are:

Do you think using for loop inside recursive function a good idea?
I know that recursion have limits. When I do ulimit -s it gives me around 8000. This means that if I am using minimax for complex games like chess this might cause stack overflow. This gives me hint that this algorithm that I wrote is not good. Can you comment on this?
I know I need to do the delete for releasing the resource, and for that I am planning to use unique_pointer later.


texts:
Boost 1.58 has new library spreadsort, so I tried it out.
I wrote simple sample for sorting vector of pairs of int:

#include <chrono>
#include <iomanip>

#include <boost/sort/sort.hpp>

// based on http://www.boost.org/doc/libs/develop/libs/sort/doc/html/sort/sort_hpp/string_sort.html

struct lessthan
{
  inline bool operator()(const std::pair<int, int> &x, const std::pair<int, int> &y) const
  {
    return x < y;
  }
};

struct bracket
{
  inline unsigned char operator()(const std::pair<int, int> &x, size_t offset) const
  {
    if (offset < sizeof(int))
      return get_char(x.first, offset);

    return get_char(x.second, offset - sizeof(int));
  }

private:
  inline unsigned char get_char(int x, size_t offset) const
  {
    static const boost::uint64_t base_mask = 0xff;

    const int bit_shift = 8 * (sizeof(int) - offset - 1);
    unsigned char result = (x & (base_mask << bit_shift)) >> bit_shift;
    if (offset == 0)
      return result ^ 128;

    return result;
  }
};

struct getsize
{
  inline size_t operator()(const std::pair<int, int> &) const
  {
    return 2 * sizeof(int);
  }
};

bool verify_sorted(const std::vector<std::pair<int, int>> & a)
{
  lessthan ls;
  for (size_t i = 0; i + 1 < a.size(); i++)
  {
    if (ls(a[i + 1], a[i]))
      return false;
  }

  return true;
}

int main()
{
  std::vector<std::pair<int, int>> r;

  srand(12345);
  for (size_t i = 0; i < 10000000; i++)
    r.push_back(std::make_pair(rand(), rand()));

  {
    std::vector<std::pair<int, int>> a = r;

    auto t_start = std::chrono::high_resolution_clock::now();
    std::sort(a.begin(), a.end());
    auto t_end = std::chrono::high_resolution_clock::now();

    std::cout << std::fixed << std::setprecision(2) << "CPU time used (std::sort): "
      << std::chrono::duration<double, std::milli>(t_end - t_start).count()
      << " ms\n";

    std::cout << (verify_sorted(a) ? "OK." : "FAIL!") << std::endl;
  }

  {
    std::vector<std::pair<int, int>> a = r;

    auto t_start = std::chrono::high_resolution_clock::now();
    boost::sort::spreadsort::string_sort(a.begin(), a.end(), bracket(), getsize(), lessthan());
    auto t_end = std::chrono::high_resolution_clock::now();

    std::cout << std::fixed << std::setprecision(2) << "CPU time used (boost::sort::spreadsort::string_sort): "
      << std::chrono::duration<double, std::milli>(t_end - t_start).count()
      << " ms\n";

    std::cout << (verify_sorted(a) ? "OK." : "FAIL!") << std::endl;
  }
}

It's faster then std::sort, but it's seems to me this implementation is to heavyweight and ugly for such a simple task.
Can anyone propose better one?


texts: Switch case implementation in Java for an integer pair combination

texts:
I have following Python code:

def get_subject_from_stream_id_and_subject_id(stream_id, subject_id):
    #(stream_id, subject_id): ("subject_name")
    return {
        (1, 1): "Accounts",
        (1, 2): "English",
        (1, 3): "Organization of Commerce",
        (2, 1): "Physics",
        (2, 2): "English",
        (2, 3): "Biology"
    }.get((stream_id, subject_id), "None")

In this code, I want to get subject name from the integer pair combination i.e. stream_id, subject_id e.g. (1, 2) is for English. It was implemented using a Python tuple.

I want to implement the same piece of code in Java.

Could someone write this in a better way in Java?

public String getSubjectFromStreamIdAndSubjectId(int streamId, int subjectId) {
  switch (streamId) {
    case 1:
        switch (subjectId) {
        case 1:
            return "Accounts";
        case 2:
            return "English";
        case 3:
            return "Organization of Commerce";
        default:
            return null;
        }

    case 2:
        switch (subjectId) {
        case 1:
            return "Physics";
        case 2:
            return "English";
        case 3:
            return "Biology";
        default:
            return null;
        }
    default:
        return null;
   }
}


texts:
My task is to compute average half spread in percentages on a stream of market. This is part of the coding assignment that I have received.

namespace CodingAssignment
{
    public interface IMarketDataFeed
    {
        string StockName { get; }
        event Action<MarketDataUpdate> Update;
    }

    public interface IIndicator
    {
        event Action<double> IndicatorUpdate;
    }

    /// <summary>
    /// Computes the average half spread (ie bid to mid) in percentage on a stream of market data updates
    /// </summary>

    public class AverageHalfSpreadIndicator
    {
        private List<MarketDataUpdate> _lastUpdates;

        public AverageHalfSpreadIndicator(IMarketDataFeed marketDataFeed)
        {
            marketDataFeed.Update += OnMarketDataUpdate;
        }

        private void OnMarketDataUpdate(MarketDataUpdate updates)
        {
            _lastUpdates.Add(updates);
            if (_lastUpdates.Count == 20)
            {
                _lastUpdates.RemoveAt(0);
            }

            var start = DateTime.Now;
            var spreads = _lastUpdates.Select(x => 100 * (x.Mid - x.Bid) / x.Bid);
            Console.WriteLine("Time to compute spreads: "+(DateTime.Now - start).TotalMilliseconds+" ms");

            var averageSpread = spreads.Average();
            Console.WriteLine("Total time:" + (DateTime.Now - start).TotalMilliseconds + " ms");

            IndicatorUpdate(averageSpread);
        }

        public event Action<double> IndicatorUpdate;
    }

    public class MarketDataUpdate
    {
        public double Bid { get; set; }
        public double Ask { get; set; }
        public double Last { get; set; }

        public double Mid
        {
            get { return (Bid + Ask) / 2; }

        }
    }
}

C# is a fairly new language for me, so there might be some best practises that I may have missed. I am also wondering how this would behave in a multi-threaded environment.


texts:
Having coded in Java and C# for quite some years, I'm currently learning Ruby. I'm working my way through the Ruby Koans tutorial. At some point, you are to implement a method that calculates the game-score of a dice-game called Greed.

I came up with this recursive Java/C#-like method. It passes all the supplied unit tests, so technically it's correct.

Now I'm wondering: Is this good Ruby code? If not, how would a "Rubyist" write this method? And possibly: Why? I'm also not so happy about the amount of duplicate code but can't think
of a better Rubyish way.

def score(dice)   #dice is an array of numbers, i.e. [3,4,5,3,3]
  return 0 if(dice == [] || dice == nil)

  dice.sort!

  return 1000 + score(dice[3..-1]) if(dice[0..2] == [1,1,1])
  return 600 + score(dice[3..-1]) if(dice[0..2] == [6,6,6])
  return 500 + score(dice[3..-1]) if(dice[0..2] == [5,5,5])
  return 400 + score(dice[3..-1]) if(dice[0..2] == [4,4,4])
  return 300 + score(dice[3..-1]) if(dice[0..2] == [3,3,3])
  return 200 + score(dice[3..-1]) if(dice[0..2] == [2,2,2])
  return 100 + score(dice[1..-1]) if(dice[0] == 1)
  return 50 + score(dice[1..-1]) if(dice[0] == 5)
  return 0 + score(dice[1..-1]);
end

Some background (if needed)

# Greed is a dice game where you roll up to five dice to accumulate
# points. A greed roll is scored as follows:
#
# * A set of three ones is 1000 points
#
# * A set of three numbers (other than ones) is worth 100 times the
#   number. (e.g. three fours is 400 points).
#
# * A one (that is not part of a set of three) is worth 100 points.
#
# * A five (that is not part of a set of three) is worth 50 points.
#
# * Everything else is worth 0 points.
#
#
# Examples:
#
# score([1,1,1,5,1]) => 1150 points
# score([2,3,4,6,2]) => 0 points
# score([3,4,5,3,3]) => 350 points
# score([1,5,1,2,4]) => 250 points
#
# More scoring examples are given in the tests below:

class AboutScoringProject < EdgeCase::Koan
  def test_score_of_an_empty_list_is_zero
    assert_equal 0, score([])
  end

  def test_score_of_a_single_roll_of_5_is_50
    assert_equal 50, score([5])
  end

  def test_score_of_a_single_roll_of_1_is_100
    assert_equal 100, score([1])
  end

  def test_score_of_a_single_roll_of_1_is_100
    assert_equal 200, score([1,1])
  end

  def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores
    assert_equal 300, score([1,5,5,1])
  end

  def test_score_of_single_2s_3s_4s_and_6s_are_zero
    assert_equal 0, score([2,3,4,6])
  end

  def test_score_of_a_triple_1_is_1000
    assert_equal 1000, score([1,1,1])
  end

  def test_score_of_other_triples_is_100x
    assert_equal 200, score([2,2,2])
    assert_equal 300, score([3,3,3])
    assert_equal 400, score([4,4,4])
    assert_equal 500, score([5,5,5])
    assert_equal 600, score([6,6,6])
  end

  def test_score_of_mixed_is_sum
    assert_equal 250, score([2,5,2,2,3])
    assert_equal 550, score([5,5,5,5])
  end

  def test_score_of_a_triple_1_is_1000A
    assert_equal 1150, score([1,1,1,5,1])
  end

  def test_score_of_a_triple_1_is_1000B
    assert_equal 350, score([3,4,5,3,3])
  end

  def test_score_of_a_triple_1_is_1000C
    assert_equal 250, score([1,5,1,2,4])
  end
end


texts: Business Access Layer and Data Access Layer for a database application

texts:
Would like to get your opinion and any advice regarding my current approach of creating database applications. Below find my current approach. Counting on your opinion and comments including examples ideas to improve the way I do. Is there something wrong with the way I do or maybe better way to do so. Most of the cases i create project for BAL (Business Layer) where I create blueprint for classes then I prepare for each of them classes in separate project (DAL) Data Access Layer. How do you do on daily business? Would like to see any other "better ways" or something to imporve my current knowledge and approach.

Within project called BAL (Bussiness Layer):
Blueprint for Kategorie class:

Public Class Kategorie
    Inherits Base

#Region "Properties"
    Property Name As String
    Property Erstellungsdatum As Date
#End Region

#Region "Constructors"
    Sub New()
        MyBase.New(New DataLayer.DALKategorie)
    End Sub
    Sub New(pId As Integer)
        MyBase.New(New DataLayer.DALKategorie)
        Id = pId
    End Sub
    Sub New(pName As String)
        MyBase.New(New DataLayer.DALKategorie)
        Name = pName
    End Sub
#End Region
    Public Overloads Function Add(pName As String, pDate As Date) As Boolean
        Dim dlsubkategorie As New DataLayer.DALKategorie
        Return dlsubkategorie.Add(pName, pDate)
    End Function
End Class

This and other classes inheriting from class Base which is as follows:

Blueprint for base class:

Public Class Base
    Implements IGetInformation
    Public Property DAL As DataLayer.IDAL
    Property Id As Integer
    Protected Sub New()
    End Sub
    Protected Sub New(dal As DataLayer.IDAL)
        Me.DAL = dal
    End Sub
    Protected Sub New(pId As Integer)
        _Id = pId
    End Sub
    Public Overridable Function IsExist(name As String) As Boolean Implements IGetInformation.IsExist
        Return DAL.isExist(name)
    End Function
    Public Overridable Function GetNameById(pId As Integer) As String Implements IGetInformation.GetNameById
        Return DAL.GetNameById(pId)
    End Function
End Class

Base class implements interface

Public Interface IGetInformation
    Function IsExist(name As String) As Boolean
    Function GetNameById(pId As Integer) As String
End Interface

Within project called DAL(Data Access Layer):
Blueprint for DAL (Data Access Layer) class for Kategorie class:

Option Strict On

Imports System.Configuration
Imports System.Data.SqlClient

Public Class DALKategorie
    Implements IDAL

    Private strcon As String = New AppSettingsReader().GetValue("ConnectionString", GetType(System.String)).ToString()

    Public Function isExist(name As String) As Boolean Implements IDAL.isExist
        Dim result As Boolean
        Using con As New SqlConnection(strcon)
            Using cmd As New SqlCommand("SELECT count(*) FROM T_Kategorie WHERE Name = @name", con)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@name", name)
                con.Open()
                Dim o As Integer = CInt(cmd.ExecuteScalar())
                If o > 0 Then
                    result = True
                Else
                    result = False
                End If
                con.Close()
            End Using
        End Using
        Return result
    End Function

    Public Function GetNameById(id As Integer) As String Implements IDAL.GetNameById
        Dim result As String
        Using con As New SqlConnection(strcon)
            Using cmd As New SqlCommand("SELECT Name FROM T_Kategorie WHERE ID=@katID", con)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@katID", id)
                con.Open()
                result = Convert.ToString(cmd.ExecuteScalar())
                con.Close()
            End Using
        End Using
        Return result
    End Function
End Class

DALKategorie implements IDAL interface:

Public Interface IDAL
    Function isExist(name As String) As Boolean
    Function GetNameById(id As Integer) As String
End Interface


texts:
Hello am a new to Python and my programming concept is catching up to me.
I just created my first ever project. I did not look else where for an answer, and it took me 6 hours to write.
How can I improve this code? Is their a way to use for loop to check the if player1 beats player2.
Please don't recomend using functions.
choice = ['r', 'p', 's']
player = ['1', '2']
user_Ply = []
ply_round = 0
draw = 0

print("--------------------------------------------------------------------")
print(r"""THIS IS A GAME OF ROCK, PAPER AND SICSSORS TO PLAY EITHER ENTER
R FOR "ROCK" P FOR "PAPER" AND "S" FOR SCISSORS """)

 while True:
        ply_round += 1
        win = ''
        active_player = player[0]
        isPlayer1_TheActive_Player = True
        if isPlayer1_TheActive_Player:
            for i, players in enumerate(player):
                if active_player == player[i]:
                    print('------------------------------------------')
                    print('Player One it your Turn')
                    ply_1 = input('Enter "Rock","Paper","Scissors :" ')
                    user_Ply.append(ply_1)
                    for j, v in enumerate(choice):
                        if choice[j] in ply_1:
                            print(f'you choose {choice[j]}')
                else:
                    print('------------------------------------------')
                    print('Player Two it your Turn')
                    ply_2 = input('Enter "Rock","Paper","Scissors :" ')
                    user_Ply.append(ply_2)
                    for j, v in enumerate(choice):
                        if choice[j] in ply_2:
                            print(f'you choose {choice[j]}')
                            isPlayer1_TheActive_Player = False

        if ((user_Ply[0] == choice[-1] and user_Ply[1] == choice[-1]) or (user_Ply[0] == choice[1] and user_Ply[1] == choice[1]) or (user_Ply[0] == choice[0] and user_Ply[1] == choice[0])):
            print(fr'The result of round {ply_round} is a draw')
            draw += 1
            user_Ply.clear()
        elif (user_Ply[0] == choice[0] and user_Ply[1] == choice[-1]):
            print(fr'The result of round {ply_round} is a win for P1')
            user_Ply.clear()
        elif (user_Ply[1] == choice[0] and user_Ply[0] == choice[-1]):
            print(fr'The result of round {ply_round} is a win for P2')
            user_Ply.clear()
        elif (user_Ply[0] == choice[-1] and user_Ply[0] == choice[1]):
            print(fr'The result of round {ply_round} is a win for P1')
            user_Ply.clear()
        elif (user_Ply[1] == choice[1] and user_Ply[0] == choice[-1]):
            print(fr'The result of round {ply_round} is a win for P2')
            user_Ply.clear()
        elif (user_Ply[0] == choice[1] and user_Ply[0] == choice[0]):
            print(fr'The result of round {ply_round} is a win for P1')
            user_Ply.clear()
        elif (user_Ply[1] == choice[0] and user_Ply[0] == choice[1]):
            print(fr'The result of round {ply_round} is a win for P2')
            user_Ply.clear()
        else:
            user_Ply.clear()
        if ply_round == 5:
            break
    print('------------------------------')
    print('Game over')
    print()


texts:
I am trying to learn C and I came across the ROT13 scrambling system used to store some passwords.

Assuming the user types everything in correctly (uses 1 argument, uses a string not an int, etc.) would this be correct/safe to use? Or is there anything at all that I am doing wrong you can point out to me (techniques, indentation, anything at all)?

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

int main(int argc, char** argv)
{
    char* word = argv[1];
    int key = 13;

    // all the letters in the first argument
    for (int n = 0, len = strlen(word); n < len; n++)
    {
        int currentLetter = word[n];

        char cipher = currentLetter + key;

        // make sure the next letter isn't over 26 or it isn't a ascii letter
        // if it is, do %26
        if ((currentLetter - 'a') + key > 26)
        {
            key = (currentLetter - 'a') + key) % 26;
            cipher = 'a' + key;
        }

        printf("%c", cipher);
        // reset the key and do the next letter
        key = 13;
        }
    }
    printf("\n");
    return 0;
}


texts: LeetCode 894: All Possible Full Binary Trees

texts:
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem

A full binary tree is a binary tree where each node has exactly 0 or 2
children.
Return a list of all possible full binary trees with N nodes.  Each
element of the answer is the root node of one possible tree.
Each node of each tree in the answer must have node.val = 0.
You may return the final list of trees in any order.
Example 1:
Input: 7
Output: [
            [0,0,0,null,null,0,0,null,null,0,0],
            [0,0,0,null,null,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,null,null,null,null,0,0],
            [0,0,0,0,0,null,null,0,0]
        ]

Note:
1 <= N <= 20

Code
#include <vector>

class Solution {
public:
    static TreeNode *clone_tree(const TreeNode *node) {
        TreeNode *root = new TreeNode(0);
        root->left = (node->left) ? clone_tree(node->left) : nullptr;
        root->right = (node->right) ? clone_tree(node->right) : nullptr;
        return root;
    }

    static std::vector<TreeNode *> allPossibleFBT(const size_t n) {
        std::vector<TreeNode *> full_binary_trees;

        if (n == 1) {
            // full_binary_trees.push_back(new TreeNode(0));
            full_binary_trees.emplace_back(new TreeNode(0));

        } else if (n & 1) {
            for (size_t index = 2; index <= n; index += 2) {
                const auto left = allPossibleFBT(index - 1);
                const auto right = allPossibleFBT(n - index);

                for (size_t left_index = 0; left_index < left.size(); left_index++) {
                    for (size_t right_index = 0; right_index < right.size(); right_index++) {
                        full_binary_trees.emplace_back(new TreeNode(0));

                        if (right_index == right.size() - 1) {
                            full_binary_trees.back()->left = left[left_index];
                        } else {
                            full_binary_trees.back()->left = clone_tree(left[left_index]);
                        }

                        if (left_index == left.size() - 1) {
                            full_binary_trees.back()->right = right[right_index];
                        } else {
                            full_binary_trees.back()->right = clone_tree(right[right_index]);
                        }
                    }
                }
            }

        }

        return full_binary_trees;
    }
};

Problem

Solution

Discuss


texts:
I'm working on this little text based game. Up to this point, I've gotten it to work, however I've heard I shouldn't be using global like I am. I have this set up to modify the global variables because I want the player to revisit a place and all the events have still been triggered.

I've just started programming, so I don't have knowledge of lots of concepts. The tutorials I've been reading include Learning Python the Hard Way.

print "You are a lone adventurer with the bounty to clear out the crypt."
print "You come with nothing but your sword and a compass."
print "You enter the crypt."
print "To the north you have a gated portaculas and rooms to the west and east."
print "What do you do?"

gate = False
lever = False
def entrance():
    global gate

    while True:
        choice = raw_input('> ')

        if choice == 'west':
            guard_shack()
        elif choice == 'east':
            lever_rm()
        elif choice == 'north' and gate == False:
            print "The gate is still closed and locked."
            entrance()
        elif choice == 'north' and gate == True:
            fountain_rm()
        else:
            entrance(gate)

def lever_rm():
    global lever
    global gate

    print "You enter the room."
    print "What do you do"

    while True:
        choice = raw_input('> ')

        if 'search' in choice:
            print "You look around the room and notice a lever on the opposite wall."
        elif "pull lever" in choice:
            print "You pull the lever."
            lever = True
            gate = True
        elif choice == 'west':
            entrance()
        else:
            print '> '

def fountain_rm():
    print "you're in the lever room!"
entrance()


texts: Showing links to Contributor Breakdown on Stackoverflow Docs

texts:
So Stackoverflow Documentation has added "Contributor Breakdown". For any given topic (and example) people can display who contributed in which way.

That page is only available if you know the link though. And it's not linked publicly in any way. Since I like these hidden pages, but I keep forgetting the correct URLs to use, I wrote a short userscript to insert these links where relevant:

// ==UserScript==
// @name         Documentation contributor links
// @namespace    http://github.com/Vogel612/mini-se-userscripts/documentation-contributor-breakdown
// @version      0.1
// @description  Add links to the contributor breakdown for topics and examples on stackoverflow documentation.
// @author       Vogel612
// @include      /https?:\/\/stackoverflow\.com\/documentation\/.*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    // these are in here for debugging purposes
    document.addLinks = addLinks;
    document.addContributorLink = addContributorLink;
})();
// because the page is modified on SE side after loading. 2 secs should be enough to wait
setTimeout(addLinks, 2000);

function addLinks() {
    'use strict';
    let topicLink = document.querySelectorAll("a.doc-topic-link")[0];
    let topicMenuContainer = document.querySelector("div.docs-menu.topic-menu");
    addContributorLink("topic", topicLink.href.split('/')[5], topicMenuContainer);

    let exampleLinks = document.querySelectorAll(".example-link a.doc-example-link");
    let exampleMenus = document.querySelectorAll(".example-link div.example-menu.docs-menu");
    for (var i = 0; i < exampleLinks.length; i++) {
        let currentLink = exampleLinks[i];
        let currentMenuContainer = exampleMenus[i];
        addContributorLink("example", currentLink.href.split('/')[7], currentMenuContainer);
    }
}

function addContributorLink(section, linkId, menu) {
    'use strict';
    let href = `/documentation/contributors/${section}/${linkId}`;
    let elem = document.createElement("A");
    elem.href = href;
    elem.innerHTML = "CB";
    elem.title = "Contributor Breakdown";
    menu.insertBefore(elem, menu.children[0]);
}

Note that the documentation pages are modified by StackOverflow after loading and that removes the link, if I add it before the page is completely built. That's why I run addLinks() with a 2 second delay.

Any and all aspects are up for critique, as always :)


texts: dplyr -- tidyverse, pipes, correlation, same variable across time "a" "b"

texts:
Have a look at this dataset. The"a" and "b" are used to make possible differentiate when the same variable was measured. In this case X1a and X1b access the same variable, but "a" was (suppose..) in the last year and "b" was this year.

I just want to correlate "a" and "b" and plot it. Simple like that and I really imagine the following code can be improved.

The final plot will be this one:

The data is fake, but it's virtually equal as the original dataset I'm working on.

 all_items <- data.frame("1a" = sample(1:5),
                            "2a" = sample(1:5),
                            "3a" = sample(1:5),
                            "1b" = sample(1:5),
                            "2b" = sample(1:5),
                            "3b" = rep(sample(1:5),10))

    #matrix with correlation
    all_correlation <- cor(all_items, method = "spearman") %>%
      as.data.frame()

    #filter
    all_correlation <- all_correlation %>% select(-c(ends_with("a"))) #columns

    #create a colum with the now name
    all_correlation <- all_correlation %>%
      mutate(item = row.names(.)) %>% select(item, everything())

    #supress some rows
    all_correlation <- all_correlation %>%  filter(!grepl("b", item))

    #filter(stringr::str_detect(row.names(.), "b"))
    #get only the diagonal
    all_correlation <- data.frame(item=1:3,Result=diag(as.matrix(all_correlation[, -1])))

    #P Value
    all_correlation_p_value <- Hmisc::rcorr(as.matrix(all_items))$P %>% as.data.frame()

    #filter
    all_correlation_p_value <- all_correlation_p_value %>% select(-c(ends_with("a")))
    all_correlation_p_value <- all_correlation_p_value %>% mutate(item = row.names(.)) %>% select(item, everything())
    all_correlation_p_value <- all_correlation_p_value %>%  filter(!grepl("b", item))
    all_correlation_p_value <- data.frame(item=1:3,P_Valor=diag(as.matrix(all_correlation_p_value[, -1])))

    #General table with the correlation  results
    all_correlation <- right_join(all_correlation,all_correlation_p_value, by = "item")

#Plot
ggplot(all_correlation, aes(x=item, y=Result)) +
  geom_point(aes(color=Result)) +
  geom_line() +
  annotate("text", x = all_correlation$item,
           y=all_correlation$Result,
           label = paste("P-value =",round(all_correlation$P_Valor,3)), hjust = -0.1, colour = "red") +
  scale_x_continuous(breaks = seq(1,3,1))


texts: Solving the N-queens puzzle the Racket or Scheme way

texts:
My final version is a direct translation from Python. Thanks to build-in support for generator, its speed is almost the same as Python. As I quite like using generator and list comprehension in Python, I am not sure I get the right way in Racket.

Moreover, I've only found explicit support for generator in Racket these days, other scheme languages like MIT scheme and chez scheme seem not. So maybe there are some better way or more "schemeic" way to solve this problem and I am very curious about it.

This is my racket code, if needed:

#lang racket
(require racket/generator)

(define (safe? x y sln)
    (if (null? sln)
        #t
        (let ((px (caar sln)) (py (cadar sln)))
            (if (or (= y py) (= (- py y) (- px x)) (= (- py y) (- x px)))
                #f
                (safe? x y (cdr sln))))))

; input-> n, output-> a generator that yields
;            every possible list of n queens' coordinates
(define (nqueen n)
    (let recur ((x (- n 1)))
        (generator ()
            (if (= x -1)
                (yield '())
                (for* ([sln (in-producer (recur (- x 1)) (void))]
                       [y   (range n)])
                    (and (safe? x y sln)
                         (yield (cons (list x y) sln)))))
        (void))))

(for ([e (in-producer (nqueen 8) (void))])
  (displayln e))


texts:
I have made a small Python script that will generate some test sets for my project.

The script generates 2 datasets with the same dimensions n*m. One contains binary values 0,1 and the other contains floats.

The script runs fine and generates the output I need, but if I want to scale to many dimensions the for-loop in pick_random() slows down my computation time.
How can I get rid of it? Perhaps with some array comprehension using numpy?

What throws my reasoning off is the if-stmt. Because the sampling should occur with a probability.

# Probabilities must sum to 1
AMOUNT1 = {0.6 : get_10_20,
           0.4 : get_20_30}

AMOUNT2 = {0.4 : get_10_20,
           0.6 : get_20_30}

OUTCOMES = [AMOUNT1, AMOUNT2]

def pick_random(prob_dict):
    '''
    Given a probability dictionary, with the first argument being the probability,
    Returns a random number given the probability dictionary
    '''
    r, s = random.random(), 0
    for num in prob_dict:
        s += num
        if s >= r:
            return prob_dict[num]()

def compute_trade_amount(action):
    '''
    Select with a probability, depending on the action.
    '''
    return pick_random(OUTCOMES[action])

ACTIONS = pd.DataFrame(np.random.randint(2, size=(n, m)))
AMOUNTS = ACTIONS.applymap(compute_trade_amount)


texts:
This is the first program I've created without help from a tutorial.  Written in Python 3.4, it gathers a specified number of media files and opens them in the default player (I use VLC on Windows 8.1). Python is my first language I have been learning mostly through trial and error. I am posting here to see what I can improve and to learn as much as I can.

import os, random, sys

completed_media = (r"C:\Users\user_000\Desktop\Completed Media")

all_media = []
playlist_ = []

def create_media_list():
    for path, subdirs, files in os.walk(completed_media):
        for file in files:
            if file.lower().endswith(('.mkv', '.mp4', '.divx', '.avi')):
                all_media.append(os.path.join(path, file))

def random_selection_from_media():
    random_selection = random.choice(all_media)
    if random_selection not in playlist_:
        playlist_.append(random_selection)
    else:
        pass

def get_selections():
    for i in range(number):
        random_selection_from_media()
    print_playlist_()
    playlist_confirmation()

def number_of_selections():
    while True:
        try:
            global number
            number = int(input('How many files would you like to add to playlist? >>> '))
            break
        except ValueError:
            print('Enter a number.')

def print_playlist_():
    print('\n-------In playlist-------\n')
    print('[{0}]'.format('\n-------------------------\n'.join(str(i) for i in enumerate(playlist_, 1))))
    print('\n-------End playlist------\n')

def remove_selection():
    while True:
        try:
            to_remove = int(input('To remove a selection enter the number of the selection you want removed here. >>> '))
            if to_remove <= len(playlist_):
            break
        except ValueError:
            print('Enter a number.')
            remove_selection()
        try:
            playlist_.pop((to_remove - 1))
            break
        except (IndexError, UnboundLocalError):
            print('Enter a vaild number')
            remove_selection()
    clear()
    print_playlist_()
    playlist_confirmation()

def playlist_confirmation():
    ok = input('This list ok? >>> ').lower()
    if ok == 'yes' or ok == 'y':
        play_playlist_()
    elif ok == 'no' or ok == 'n':
        while True:
            new = input('Get new list or remove a specific selection? >>> ').lower()
            if new == 'new list' or new == 'n':
                del playlist_[:]
                clear()
                get_selections()
                break
            elif new == 'specific selection' or new == 's':
                remove_selection()
                break
            else:
                 print('Enter \'new\' or \'selection\'')
    else:
        playlist_confirmation()

def play_playlist_():
    for i in playlist_:
        play_cmd = "rundll32 url.dll,FileProtocolHandler \"" + i + "\""
        os.system(play_cmd)

def clear():
    os.system('cls')

def main():
    create_media_list()
    number_of_selections()
    get_selections()

if __name__=="__main__":
    main()


texts: Is this code likely to stand the test of time? (Add select box to DOM with JS)

texts:
The reason I asked about standing the test of time is that I previously used PHP echo to create a string and placed it into a div with .innerHTML, but modern browsers were not passing the value of the select box. (Went back and tested wit IE9 and the innerHTML version worked.)

file:js_selecttest.php

<form method="post" action='js_selecttest.php'>

    <input type="text" name="text_input" onClick="create_sel(document.getElementById('select_holder'),'class_date',op_array)">

Filled by JS

<input type="submit">

</form>

<?php
if($_POST)
  {
    var_dump($_POST);
  }
?>

Would you have any suggestions or improvements?


texts:
I ran into a problem, I'm using MyIsam tables in mysql database, using PDO to connect.

In all my tests (calling for 1 user everything works fine), now having around 300 users connected at the same time all day making requests is really really slowing down mySQL. Ive got my.cnf with (key_buffer=512M and max_connections=200) my server is VPS with 2GB RAM and 3 cores. And each table has around 40K records

All queries/updates/inserts are super slow, but I've discovered that this PHP file is the root of the problem, it's requested every 10 seconds for every user (not at the same time, and if the call fails it's delayed another 10 seconds):

 //User Info -----------------------
    $sqlcommand = "SELECT * FROM tbl_User WHERE FB_ID='". $FB_ID . "'";
    $statement = $pdo->query($sqlcommand);
    $row = $statement->fetch(PDO::FETCH_ASSOC);

    if($row) {
       //Do its thing
    }
//How Many Gifts are there-----------------
    $sqlcommand = "SELECT * FROM tbl_Gifts_Sent WHERE FB_ID='". $FB_ID . "'";

    $statement = $pdo->query($sqlcommand);
    $row = $statement->fetchAll();

    if (!$row) {
        $amountOfGifts=0;
    } else {
        foreach ($pdo->query($sqlcommand) as $row){
                $amountOfGifts=$amountOfGifts+1;
        }
    }

//Daily Leaderboard King---------------
    $sqlcommand = "SELECT * FROM tbl_Leaderboard_DAY WHERE Today = " . $midnight . " ORDER BY XP_Gain DESC";

    $statement = $pdo->query($sqlcommand);
    $row = $statement->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        //Do its thing
    }

//-------- THE STATE ON ALL Themes WITH GIFTS AND ALL
    $sqlcommand = "SELECT * FROM tbl_User_Reel WHERE FB_ID='". $FB_ID . "'";
    foreach ($pdo->query($sqlcommand) as $db_gmInfo){
         //DO its thing
    }

this 4 queries are on the same php file.

Im a newbie in this and this is my first php mysql project, so I'm thinking there's gotta be a better way to do this, :S any recommendations, help or pointers on how to make it work super fast are greatly appreciated! thank you


texts: Simple animation with Javascript and JQuery

texts:
I'm learning Javascript and JQuery, and just finished a chapter on JQuery animations.So i decided to give it a try and implement a simple animation on Html document i had.

Here is the code:

jQuery(document).ready(function($) {

    var animInfo = {

        iter         : 1,      // Iterator
        elementCount : 4,      // Number of (

 ) structures to animate
        socAnimSpeed : 500,    // soc  - Section One Content Animation Speed
        socpAnimSpeed: 1000    // scop - Section One Content
 Animation Speed

    };

    animSoc( animInfo );       // Start the Animations

});

/*  Logic Behind the Functions

    function
    animSoc(obj) ---- If Iterator is <= to Number of Elements,<<<<<<
                |                      v                            ^
                |                      v                            ^
                 ---- Animate Section One Content( Iter value )     ^
                                   ( Width )                        ^
                                       v                            ^
    function                           v                            ^
    animSocp(obj) --- Animate Section One Content( Iter value )
 ^
                |                  ( FadeIn )                       ^
                |                      v                            ^
                |                      v                            ^
                 ---- Increase the Iterator by One   >>>>>>>>>>>>>>>
*/

function animSoc( obj ){

    if ( obj.iter <= obj.elementCount ){

        $( ".soc" + obj.iter ).animate( { width: "60%" },   obj.socAnimSpeed,
            function(){
                animSocp( obj );
            });
    }
    return;
}

function animSocp( obj ){

    $( ".soc" + obj.iter + " + p" ).fadeIn( obj.socpAnimSpeed,
        function() {
            obj.iter++;
            animSoc( obj );
        });
}

The things I am most concerned about :

Is this considered bad practice ? If yes why ?
Commenting of the Code Sample. Is it good or bad ?
Errors.
Your professional opinion.


texts: REST API stored in a MongoDB Atlas Database

texts:
I am building my first REST API using data stored in my MongoDB Atlas Database. I tried to read the REST API conventions with the versioning, using plural nouns for resources and sending the right error codes. I wonder if the following code correctly follows Good Practices for REST APIs and if there is anything that can be written better or more neatly.

connection_str = config.connection_str
db_name = config.db_name

app = Flask(__name__)
cors = CORS(app)
client = MongoClient(connection_str)
db = client.get_database(db_name)

@app.route("/api/v1/players", methods = ['GET'])
def get_all_players():
    # TODO: Implement pagination
    """
    returns a list of players
    """
    try:
        players = db.players.find()
        output = []
        for player in players:
            output.append({
                'name': player['name'],
                'position': player['position'],
                'nationality': player['nation'],
                'position': player['position'],
                'foot': player['foot'],
                'age': utils.date_to_age(player['birth_date']),
                'profile_img': player['profile_img'],
                'abilities': player['abilities']
            })
        return jsonify({'result': output})

    except:
        return jsonify({
            'result': 'failure',
            "error": 400,
            "message": 'Bad Request'}), 400

@app.route("/api/v1/players/<name>", methods = ['GET'])
def get_player(name):
    """
    returns an object of a player given a name
    """
    try:
        player = db.players.find_one({'name': name})
        output = {
            'name': player['name'],
            'position': player['position'],
            'nationality': player['nation'],
            'position': player['position'],
            'foot': player['foot'],
            'age': utils.date_to_age(player['birth_date']),
            'profile_img': player['profile_img'],
            'abilities': player['abilities']
        }
        return jsonify({'result': output})

    except:
        return jsonify({
            'result': 'failure',
            "error": 400,
            "message": "Bad Request (Double check player's name)"}), 400

if __name__ == "__main__":
    # app.run(ssl_context='adhoc')
    app.run()

The API doesn't do that much right now. It just reads data in the DB, but I want to see if any style can be fixed at this early stage.


texts: Partition Equal Subset Sum Challenge LeetCode

texts:
I solved this problem in LeetCode.

  Given a non-empty array containing only positive integers, find if the array can
  be partitioned into two subsets such that the sum of elements in both
  subsets is equal.

  Note: Each of the array element will not exceed 100. The array size will not exceed 200.

Example 1:

  Input: [1, 5, 11, 5]

  Output: true

  Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

  Input: [1, 2, 3, 5]

  Output: false

  Explanation: The array cannot be partitioned into equal sum subsets.

class Solution {
public:
   bool canPartition(vector<int>& nums) {
        int sum = 0;
        for(auto it = nums.begin(); it != nums.end(); ++it)
        {
            sum += (*it);
        }

        if((sum % 2 != 0) || nums.size() <= 1)
        {
            return false;
        }

        vector < vector < bool > > isValid((sum /2) + 1, vector < bool > (nums.size() + 1, false));

        for(int i = 0; i <= nums.size(); ++i)
        {
            isValid[0][i] = true;
        }

        for(int row = 1; row <= (sum/2); ++row)
        {
            for(int col=1; col<= nums.size(); ++col)
            {
                if(row >= nums[col - 1])
                {
                    isValid[row][col] = isValid[row][col -1] || isValid[row - nums[col - 1]][col-1];
                }
                else
                {
                    isValid[row][col] = isValid[row][col -1];
                }
            }
        }
        return isValid[sum/2][nums.size()];
    }
};

The approach was a pretty straightforward DP implementation which is O(sum * n) in terms of space and time complexity.

My solution took about 1382 ms to execute all the 1183 test cases while I saw solutions which executed in about 200 ms in the same language.

As far as I know there isn't a greedy solution to this problem, only approximations algorithm exist for this.

Can you suggest if there exists a solution with better time complexity for this problem or if my implementation has some redundant initialization or iterations which slow it down.


texts: Javascript velocity converter, fully chainable

texts:
I created this out of curiosity and it has some code duplication issues and the fact that sticking .yield() on the end of a call to a unit converter is pretty strange.

How would you improve it?

/**
 * A very special velocity converter
 * Designed mainly for a very natural syntax
 * It allows full chainable conversion calls and maintains its on internal state.
 *
 * example:
 * remotewind.convert(10).knots().to.mph().to.kmh().yield();
 *
 * Each unit has a yield "method" which returns the last value (the internal state)
 *
 * @param val
 * @return Converter
 */
remotewind.convert = function(val) {

    var val = val;

    function Unit(){
        this.yield = function(){
            return val;
        }
    }

    function Ms(ms){
        val = ms;
        this.to = {
            kmh : function(){ return new Kmh(val * 3.6) },
            mph : function(){ return new Mph(val * 2.2369362920544) },
            knots: function(){ return new Knots(val * 1.943844492) }
        }
    }
    Ms.prototype = new Unit();

    function Kmh(kmh){
        val = kmh;
        this.to = {
            ms : function(){ return new Ms(val * 0.277777778) },
            mph : function(){ return new Mph(val * 0.621371192) },
            knots: function(){ return new Knots(val * 0.539956803) }
        }
    }
    Kmh.prototype = new Unit();

    function Mph(mph){
        val = mph;
        this.to = {
            ms : function(){ return new Ms(val * 0.44704) },
            kmh : function(){ return new Kmh(val * 0.621371192) },
            knots: function(){ return new Knots(val * 0.868976242) }
        }
    }
    Mph.prototype = new Unit();

    function Knots(kn){
        val = kn;
        this.to = {
            ms : function(){ return new Ms(val * 0.514444444) },
            mph : function(){ return new Mph(val * 1.150779448) },
            knots: function(){ return new Knots(val * 1.852) }
        }
    }
    Knots.prototype = new Unit();

    function Converter(val){
        return {
            ms: function(){  return new Ms(val) },
            kmh: function(){  return new Kmh(val) },
            mph: function(){  return new Mph(val) },
            knots: function(){  return new Knots(val) }
        }
    }

    return new Converter(val);
}


texts: Rewriting WPF GridViewColumn alignment in a less verbose way

texts:
I wanted just to right align one column in WPF and I found out that the syntax is not exactly syntetic... Is there a way to make it more syntetic?

Consider that this one colum, but I have 20 columns which share the same identical structure, changing only the displayed property.

<GridViewColumn Header="trial" Width="110">
 <GridViewColumn.CellTemplate>
 <DataTemplate>
  <TextBlock HorizontalAlignment="Right">
   <TextBlock.Text>
    <MultiBinding StringFormat="{}{0:N} {1}">
      <Binding Path="Income"></Binding>
      <Binding ElementName="UserControl" Path="DataContext.Pinco"></Binding>
    </MultiBinding>
   </TextBlock.Text>
  </TextBlock>
 </DataTemplate>
 </GridViewColumn.CellTemplate>
</GridViewColumn>


texts: Count combinations of positive and negative that sum to target number

texts:
The problem I'm solving is given as follows:

  You are given a list of non-negative integers, a1, a2, ..., an, and a
  target, S. Now you have 2 symbols + and -. For each integer, you
  should choose one from + and - as its new symbol.

  Find out how many ways to assign symbols to make sum of integers equal
  to target S.

Here is my solution:

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        return findTargetSum(nums, 0, S, 0);
    }

    int findTargetSum(vector<int>& nums, int i , int S, int sumSoFar){
        if(i == nums.size()){
            return sumSoFar == S;
        }

        return findTargetSum(nums, i + 1, S, sumSoFar + nums[i]) + findTargetSum(nums, i + 1, S, sumSoFar - nums[i]);
    }
};

This solution however performs slower than the target. I suspect there may be some DP solution I am missing or maybe some optimization in my current solution might be to blame. Any advice on how to cut the run time would be appreciated.


texts: Simplify IActionResult return value logic

texts:
It would be nice to simplify the verbosity of this:

public IActionResult Get(int id)
{
    var movie = context.GetMovie(id);

    if (movie != null)
    {
        return Ok(movie);
    }
    else
    {
        return NotFound();
    }
}

with something like this:

public IActionResult Get(int id)
{
    var movie = context.GetMovie(id);
    return (movie != null) ? Ok(movie) : NotFound();
}

Of course, this is an error because the two objects in the ternary must be of the same type, not just sharing the same inheritance (or is this incorrect?).

The closest I can get is to explicitly cast one of the values as an IActionResult:

return (movie != null) ? Ok(movie) : (IActionResult) NotFound();

Is there a better option?


texts: Easier way to handle a Console Theme System

texts:
I'm just curious is there an easier way to handle console colors rather than just doing something
like the code below. The problem is the code bloat I'm experiencing when writing a theming system for my console application. It contains almost 200 lines of code, just to handle the chat theme system. Is there a way to minimalize this?

public static enum UserLevel
{
    Moderator, Broadcaster, Admin, Subscriber, Normal, Turbo
}

public static void WriteLine(UserLevel l, string user, string message)
{
    DateTime ts = new DateTime();
    string t = ts.ToLongTimeString();

    Console.BackgroundColor = ConsoleColor.Black;
    Console.Write("[" + t + "] ");
    Console.ForegroundColor = ConsoleColor.Green;
    Console.Write("<");

    switch (l)
    {
        case UserLevel.Moderator:
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.Write("[M] ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(user);
            break;
        case UserLevel.Broadcaster:
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.Write("[B] ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(user);
            break;
        case UserLevel.Admin:
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.Write("[A] ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(user);
            break;
        case UserLevel.Subscriber:
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.Write("[S] ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(user);
            break;
        case UserLevel.Normal:
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(user);
            break;
        case UserLevel.Turbo:
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.Write("[T] ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(user);
            break;
        case default:
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(user);
            break;
    }

    Console.ForegroundColor = ConsoleColor.White;
    Console.Write(user);
    Console.ForegroundColor = ConsoleColor.Green;
    Console.Write("> ");
    Console.ForegroundColor = ConsoleColor.White;
    Console.Write(message);
}


texts: Efficient method to sort read-in text file in Excel

texts:
I've read in a text file to excel from a database and I've done it in such a way that it filters out unnecessary columns. My approach to filter rows was to use two subroutines and call the 2nd from within the first. It takes ~8 seconds for the sheet to be filtered and there is only 400 or so rows. The fact that it takes that long (even though it works) indicates my code is inefficient. If anyone has a better method I would greatly appreciate the knowledge! To delete rows I've used the following VBA:

Sub FilterAndDelete()
Dim LR As Long, i As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
For i = LR To 1 Step -1
Select Case Left(Range("A" & i).Value, 3)
Case "CHA", "HAM", "BKN"
    Call FilterAndDeleteB
Case Else
    Rows(i).Delete
    Call FilterAndDeleteB
End Select
Next i
End Sub

Sub FilterAndDeleteB()
Dim Br As Long, i As Long
Br = Range("B" & Rows.Count).End(xlUp).Row
For i = Br To 1 Step -1
Select Case Left(Range("B" & i).Value, 1)
Case "-"
    Rows(i).Delete
Case Else
    'do nothing
End Select
Next i