texts:
The previous and initial iteration at Kruskal's algorithm in Java

Now what I did is remove the fields and let the actual Kruskal-routine create the required data structures in the local scope, which leads to thread safety.

The only file that changed is KruskalMSTFinder.java:

package net.coderodde.graph.mst.support;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.coderodde.graph.UndirectedGraphEdge;
import net.coderodde.graph.UndirectedGraphNode;
import net.coderodde.graph.WeightFunction;
import net.coderodde.graph.mst.MSTFinder;

public class KruskalMSTFinder implements MSTFinder {

    @Override
    public List<UndirectedGraphEdge>
        findMinimumSpanningTree(final List<UndirectedGraphNode> graph,
                                final WeightFunction weightFunction) {
        final Map<UndirectedGraphNode,
                  DisjointSet<UndirectedGraphNode>> map = new HashMap<>();
        final Set<UndirectedGraphEdge> edgeSet = new HashSet<>();
        final List<UndirectedGraphEdge> edgeList = new ArrayList<>();

        prepareEdgeList(graph,
                        weightFunction,
                        map,
                        edgeSet,
                        edgeList);

        final List<UndirectedGraphEdge> minimumSpanningTree = new ArrayList<>();

        for (final UndirectedGraphEdge edge : edgeList) {
            final UndirectedGraphNode u = edge.firstNode();
            final UndirectedGraphNode v = edge.secondNode();

            DisjointSet<UndirectedGraphNode> us = map.get(u);
            DisjointSet<UndirectedGraphNode> vs = map.get(v);

            us = us.find(us);
            vs = vs.find(vs);

            if (us != vs) {
                minimumSpanningTree.add(edge);
                us.union(vs);
            }
        }

        return minimumSpanningTree;
    }

    private void
        prepareEdgeList(final List<UndirectedGraphNode> graph,
                        final WeightFunction weightFunction,
                        final Map<UndirectedGraphNode,
                                  DisjointSet<UndirectedGraphNode>> map,
                        final Set<UndirectedGraphEdge> edgeSet,
                        final List<UndirectedGraphEdge> edgeList) {
        for (final UndirectedGraphNode node : graph) {
            map.put(node, new DisjointSet<>());

            for (final UndirectedGraphNode neighbor : node) {
                edgeSet.add(
                        new UndirectedGraphEdge(node,
                                                neighbor,
                                                weightFunction
                                                        .get(node, neighbor)));
            }
        }

        edgeList.addAll(edgeSet);
        Collections.<UndirectedGraphEdge>sort(edgeList);
    }
}

Anything else to improve?


texts: Button to dynamically clone a form field

texts:
I am very new to javascript and started with a very basic add button to my django app. Everything I found was using jQuery but for only one small script jQuery seems to be a too big overhead for me. Everything is working but I want to get some suggestions regarding coding style:

function hasReachedMaxNum(type) {
    var total = parseInt(document.querySelector("#" + type + "-TOTAL_FORMS").value);
    var max = parseInt(document.querySelector("#" + type + "-MAX_NUM_FORMS").value);
    return total >= max
}

function cloneMore(element, type) {
    var total = parseInt(document.querySelector("#" + type + "-TOTAL_FORMS").value);
    newElement = element.cloneNode(true);
    for (var input of newElement.getElementsByTagName("input")) {
        input.name = input.name.replace("-" + (total - 1) + "-", "-" + total + "-");
        input.id = input.name;
        input.value = null;
    }
    for (var label of newElement.getElementsByTagName("label")) {
        var forElement = label.getAttribute("for");
        forElement = forElement.replace("-" + (total - 1) + "-", "-" + total + "-");
        label.setAttribute("for", forElement)
    }
    total += 1;
    element.parentNode.insertBefore(newElement, element.nextSibling);
    document.querySelector("#" + type + "-TOTAL_FORMS").value = total;
    return newElement
}
var addChoice = document.getElementById("add-choice");
addChoice.onclick = function() {
    var choices = document.getElementById("choices");
    cloneMore(choices.lastElementChild, "choice_set");
    if (hasReachedMaxNum("choice_set")) {
        this.disabled = true
    }
};

Just for reference the html looks like this:

    Choice:

    <input id="choice_set-0-choice_text" maxlength="200" name="choice_set-0-choice_text" type="text" />

    Choice:

    <input id="choice_set-1-choice_text" maxlength="200" name="choice_set-1-choice_text" type="text" />

    Choice:

    <input id="choice_set-2-choice_text" maxlength="200" name="choice_set-2-choice_text" type="text" />

  <button type="button" id="add-choice">Add another choice
  </button>


texts:
I implemented the binary search algorithm. Input vector is sorted by < than operator implemented by type T. The less than operator is expensive so we want to use it as few times as possible.

I would like to know if there are any stupid mistakes, bad practices that I used and how I can improve the code.

template<class T>
long binary_search(const std::vector<T>& v, const T& key){

    if(v.empty()) { return -1; }

    long lo = 0;
    long hi = v.size() - 1;
    long mid = (long) floor((lo + hi ) / 2);
    long pmid = -1;  // prev mid

    while(lo < hi && pmid != mid){

        if(v[mid] < key){
            lo = mid;
        }
        else{
            hi = mid;
        }

        pmid = mid;
        mid = (long) floor((lo + hi) / 2);
    }

    if(!(v[mid] < key) && !(key < v[mid])){
        return mid;
    }

    if(mid - 1 >= 0){
        if( !(v[mid - 1] < key) && !(key < v[mid - 1])){
            return mid - 1;
        }
    }

    if(mid + 1 <= v.size()){
        if(!( v[mid + 1] < key) && !(key < v[mid + 1] )){
            return mid + 1;
        }
    }

    return -1;
}


texts: Recursive function with Promise and setTimeout to ping DOM

texts:
I use this function in browser automation. It pings the document in the browser to check if an element we are looking for is available (useful when there is JavaScript generated async content). If it's not available, it will retry after a given interval or times out eventually.

Example usage:

function clickContinue() {
  return $(":contains('Continue')");
}

elementFinder(clickContinue).then(el => el.click());

Function:

// accepts both document.querySelector and jQuery() selector
function elementFinder(selectorFn) {
  const interval = 500;
  const timeout = 8000;
  const maxTries = timeout / interval;
  function checkerFn(resolve, reject, tryCount=0) {
    if(tryCount > maxTries) {
      reject(`Timeout ${timeout}ms reached when searching for element`);
      return;
    }
    setTimeout(() => {
      const el = selectorFn();
      // null check is for document.querySelector, zero check is for jQuery()
      if(el !== null && el.length !== 0) {
        resolve(el);
        return;
      }
      tryCount += 1;
      checkerFn(resolve, reject, tryCount)
    }, tryCount === 0 ? 0 : interval);
  }
  return new Promise(function(resolve, reject) {
    checkerFn(resolve, reject)
  });
}

It seems weird to me that I define a function within a function, wonder if this can be maybe done with one function or if there are some other issues.


texts: Print character + the ASCII value, 10 pairs per line

texts:
My exercise was:

  Write a program that reads input as a stream of characters until encountering
  EOF. Have the program print each input character and its ASCII decimal value.
  Note that characters preceding the space character in the ASCII sequence are
  nonprinting characters. Treat them specially. If the nonprinting character is a
  newline or tab, print \n or \t, respectively.
  Print 10 pairs per line, except start a fresh line each time a newline character is encountered.

This is my code (regarding the special characters, I defined only \n and \t):

#include <stdio.h>
int special_chars(int ch);

int main(void)

{
    int x;
    printf("please enter a some characters, and ctrl + d to quit\n");

    special_chars(x);

    return 0;
}

int special_chars(int ch)

{
    int pairsNum = 0;

    while ((ch = getchar()) != EOF)// testing charecters while not end of file.
    {

    if (ch == '\n')// testing if a control charecter, and printing its
     {
        printf("\\n ");
        pairsNum++;
     }

    else if (ch == '\t')
     {
        printf("\\t ");
        pairsNum++;
     }

    else
    {
        printf("%c,%d ", ch, ch);
        pairsNum++;
    }

    if (pairsNum == 10)// counting the number of outputs, and printing a newline when is 10 (limit).
        printf("\n");
    }
    return ch;
}


texts: Changing a matrix by multiplying indexes of min element

texts:
I need to make the following C program: Given A (N, N) matrix (2D array). The program needs to find the min element in each column. Then it needs to multiply the row in which the element is, with the difference of its indexes (a[i] * i - j). Then transfer the new row on another matrix. Print the new matrix.

Here is my code:

#include<stdio.h>

void InputArray(int a[][50],int M, int *N);
void NewArray(int a[][50], int b [][50], int N);
void PrintA(int a[][50], int N);
void PrintB(int b[][50], int N);

void main(){
    int a[50][50], b[50][50], N;
    InputArray(a, 50, &N);
    system("cls");
    NewArray(a, b, N);
    PrintA(a, N);
    PrintB(b, N);
}
void InputArray(int a[][50], int M, int *N){
    do{
        printf("Enter rows and columns: ");
        scanf("%d", N);
    } while (*N < 1 || *N > M);

    for (int i = 0; i < *N; i++){
        for (int j = 0; j < *N; j++){
            printf("Enter i[%d][%d] element ", i, j);
            scanf("%d", &a[i][j]);
        }
    }
}

void NewArray(int a[][50], int b[][50], int N){
    int i, j, min, d, k, rowb = 0, rowa = 0;
    for (i = 0; i < N; i++){
        min = a[0][i];
        d = 0 - i;
        for (j = 0; j < N; j++){
            if (a[j][i] < min){
                min = a[j][i];
                d = j - i;
                rowa = j;
            }
        }

        for (k = 0; k < N; k++){
            b[rowb][k] = a[rowa][k] * d;
        }
        rowb++;
    }
}
void PrintA(int a[][50], int N){
    printf("You've entered: \n");
    for (int i = 0; i < N; i++){
        for (int j = 0; j < N; j++){
            printf("%d  ", a[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}
void PrintB(int b[][50], int N){
    printf("New matrix is :\n");
    for (int i = 0; i < N; i++){
        for (int j = 0; j < N; j++){
            printf("%d  ", b[i][j]);
        }
        printf("\n");
    }
}

It does work, but I think it the "NewArray" function can be made better.

Here is an example output:

You've entered:
1 4 9
2 6 5
3 8 2
New matrix is:
0 0 0
-1 -4 -9
0 0 0


texts: Count the frequency of integers in an array

texts:
I recently reviewed a question here on Code Review. The problem statement is

  Write a program that prompts the user to input ten values between 80 and 85 and stores them in an array. Your program must be able to count the frequency of each value appears in the array.

I coded my own solution for the problem statement. My questions are
  - Can this be optimized more?
  - Did I miss anything in C++14 or C++17 that might improve the code?
  - Is the code readable?
  - Are the variable and function names good or can they be improved?

My goals were to write the best C++ I could, remove any magic numbers and allow the solution to scale for different sets of numbers.

#include "pch.h"
#include <iostream>
#include <array>

const size_t INPUTSIZE = 10;
const size_t FREQUENCYSIZE = 6;
const int MINLEGALVALUE = 80;
const int MAXLEGALVALUE = 85;

std::array<int, INPUTSIZE> getUserInput()
{
    std::array<int, INPUTSIZE> inputValues;

    size_t i = 0;
    do
    {
        int inputValue = 0;
        std::cout << "Please enter a number between " << MINLEGALVALUE << " and " << MAXLEGALVALUE  << ":" ;
        std::cin >> inputValue;

        if (inputValue >= MINLEGALVALUE && inputValue <= MAXLEGALVALUE)
        {
            inputValues[i] = inputValue;
            i++;
        }
        else
        {
            std::cout << "The number must be between" << MINLEGALVALUE << " and " << MAXLEGALVALUE << "\n";
        }

    } while (i < INPUTSIZE);

    return inputValues;
}

std::array<unsigned, FREQUENCYSIZE> getFrequencyCounts(std::array<int, INPUTSIZE> inputValues)
{
    std::array<unsigned, FREQUENCYSIZE> freqs = { 0 };

    for (auto inputs : inputValues)
    {
        freqs[inputs - MINLEGALVALUE]++;
    }

    return freqs;
}

void printFrequencies(std::array<unsigned, FREQUENCYSIZE> freqs)
{
    unsigned rowLabel = MINLEGALVALUE;
    for (auto frequency : freqs)
    {
        std::cout << rowLabel << "      " << frequency << "\n";
        rowLabel++;
    }
}

int main()
{
    std::array<int, INPUTSIZE> inputValues = getUserInput();
    std::array<unsigned, FREQUENCYSIZE> freqs = getFrequencyCounts(inputValues);

    std::cout << "\n";

    printFrequencies(freqs);
}


texts:
I have noticed this question https://stackoverflow.com/questions/49389392/nested-classes-and-collections-vba in StackOverflow, but it got closed faster than I could have answered. However, it was concerning a best practice for usage of collections of classes.

I usually use Array and I add to it like this:

Public Sub AddToTeam(emp As Employee)

    Dim cnt As Long
    cnt = UBound(pTeam)

    If Not pTeam(0) Is Nothing Then
        ReDim Preserve pTeam(cnt + 1)
        cnt = cnt + 1
    End If
    Set pTeam(cnt) = emp

End Sub

Furthermore, I initialize the Array like this in the class:

Private Sub Class_Initialize()
    ReDim pTeam(0)
End Sub

This is the working code, feel free to give any ideas:

Main Module

Option Explicit

Public Sub TestMe()

    Dim EmpA    As New Employee
    Dim EmpB    As New Employee
    Dim ManA    As New Employee
    Dim TeamA   As New Team

    ManA.Name = "John Doe Top Manager"
    EmpA.Name = "Peter"
    EmpB.Name = "George"

    Set EmpB.Manager = ManA
    TeamA.Name = "The best team!"

    TeamA.AddToTeam ManA
    TeamA.AddToTeam EmpA
    TeamA.AddToTeam EmpB

    TeamA.PrintNames
    Debug.Print TeamA.Name
    TeamA.PrintInfoForManagers

End Sub

Class Employee

Option Explicit

Private pName           As String
Private pManager        As Employee
Private pAge            As Long
Private pTeam           As String
Private pHasManager     As Boolean

Public Property Get HasManager() As Boolean
    HasManager = pHasManager
End Property

Public Property Let HasManager(Value As Boolean)
    pHasManager = Value
End Property

Public Property Get Manager() As Employee
    Set Manager = pManager
End Property

Public Property Set Manager(Value As Employee)
    Set pManager = Value
    HasManager = True
End Property

Public Property Get Name() As String
    Name = pName
End Property

Public Property Let Name(Value As String)
    pName = Value
End Property

Public Property Get Team() As Employee
    Team = pTeam
End Property

Public Property Let Team(Value As Employee)
    pTeam = Value
End Property

Class Team

Option Explicit

Private pTeam()         As Employee
Private pName           As String

Public Sub PrintInfoForManagers()

    Dim emp As Variant
    For Each emp In pTeam
        If emp.HasManager Then
            Debug.Print emp.Name & " is managed by " & emp.Manager.Name
        Else
            Debug.Print emp.Name & " has no manager."
        End If
    Next emp

End Sub

Public Sub PrintNames()

    Dim emp As Variant
    For Each emp In pTeam
        Debug.Print emp.Name
    Next emp

End Sub

Public Property Get Name() As String
    Name = pName
End Property

Public Property Let Name(Value As String)
    pName = Value
End Property

Public Sub AddToTeam(emp As Employee)

    Dim cnt As Long
    cnt = UBound(pTeam)

    If Not pTeam(0) Is Nothing Then
        ReDim Preserve pTeam(cnt + 1)
        cnt = cnt + 1
    End If
    Set pTeam(cnt) = emp

End Sub

Private Sub Class_Initialize()
    ReDim pTeam(0)
End Sub

So how would you review/improve it?


texts: Is there a better way to assign constructor parameter in Typescript?

texts:
I have a class with a various set of optional parameters when instantiated.
I would like to be sure that the user input ONLY the available parameters option, and also add a default value if nothing is passed.

I come with this

export enum HexagoneType {
  POINTY,
  FLAT
}

export interface HexagoneOptions {
  center?: Vector2;
  size?: number;
  color?: string;
  type?: HexagoneType;
}

export default class Hexagone {
  ctx: CanvasRenderingContext2D;
  center: Vector2;
  size: number;
  color: string;
  type: HexagoneType;

  constructor(ctx: CanvasRenderingContext2D, options?: HexagoneOptions) {
    this.ctx = ctx;
    this.center = (options && options.center) ? options.center : new Vector2();
    this.size = (options && options.size) ? options.size : 100;
    this.color = (options && options.color) ? options.color : "red";
    this.type = (options && options.type) ? options.type : HexagoneType.POINTY;
  }
}

But is there something shorter ?


texts: Password checker containing many conditional statements

texts:
Can this be shortened/improved? I'm trying to make a password checker in Python.

Could the ifs be put into a for loop?  If so, how?

pw = input("Enter password to test: ")

caps = sum(1 for c in pw if c.isupper())
lower = sum(1 for c in pw if c.islower())
nums = sum(1 for c in pw if c.isnumeric())

scr = ['weak', 'medium', 'strong']
r = [caps, lower, nums]

if len(pw) < 6:
    print("too short")
elif len(pw) > 12:
    print("too long")

if caps >= 1:
    if lower >= 1:
        if nums >= 1:
            print(scr[2])
        elif nums < 1:
            print("your password is " + scr[1])
    elif lower < 1:
        print("your password strength is " + scr[0])
elif caps < 1:
    print("your password strength is " + scr[1])


texts: Can I make a regex array to iterate through in C++?

texts:
I have to check a string to various regular expressions in C++. Up to now, I've done this using something similar to this:

regex regex_a (".."); string rewrite_a = "($1/$2)";
regex regex_b (".."); string rewrite_b = "($1)";
regex regex_c (".."); string rewrite_c = "($2)";

if (regex_match(string, regex_a)) {
    cout << regex_replace(string, regex_a, rewrite_a);
} else if (regex_match(string, regex_b)) {
    cout << regex_replace(string, regex_b, rewrite_b);
} else if (regex_match(string, regex_c)) {
    cout << regex_replace(string, regex_c, rewrite_c);
}

Is this the cleanest way to do this? Isn't there a way to make a regex array and iterate through that? It would make the code much more readable.


texts: How to write a dictionnary of object instances describing geometrical shapes

texts:
My current position implies a lot of programming but I lack formal knowledge concerning how to properly code, and this is the object of my question. I believe the form of my code could be improved. As a result, here is a much simplified version of the program I am writting, that shares the same structure but is much simpler to read. I think I could realy use the opinion of people who knows python better than me.
Here, I define a class « geometric_shape », which can be used to calculate proporties of shapes, for exemple the area square or rectangles.

The main class has two arguments, "dimensions" and "model", that is used to define the shape.
The different shapes are defined in the dictionnary "self.list_of_models".

The key is the name of the different possible shapes.
Each value is a empty subclass instance, in which we define all the parameters of a given shape, here the number of parameters that describes the shape and the function used to calculate the area.

Finally, there is one method "area" that returns the area for the defined shape.

The advantage is, I can easily get the properties of a given shape by calling them using the string "self.model". For example, here, I can call the number of parameters required to completely describe a shape using self.list_of_models[ self.model ].noparameters
The problem is that I do not feel like it is an elegant way of doing things. For exemple, if I call the object instance, I see the variable is defined in a weird way.
self.list_of_models['square']
Out[2]: <__main__.geometric_shape.__init__.<locals>.model at 0x1dc810ea988>

So my question is : Would someone know a more elegant way to input a list of « shapes » than a dictionnary of object instances, or is this formulation fine the way it is ?
# -*- coding: utf-8 -*-

class geometric_shape:
    ''' Fonction utilitaires de spindiff, importé en tant que super classe dans spindiff'''

    # ==============================================================================================
    @staticmethod
    def __squared__(a):
        return a[0]**2

    @staticmethod
    def __product__(a):
        return a[0]*a[1]

    # ==============================================================================================
    def __init__(self):
        ''' Create list of available models'''

        self.dimensions = [1, 2 ]
        self.model = 'square' # rectangle

        class model :
            ''' Définit une classe de modèle de système dans lequel la diffusion de spin est simulée.'''
            def __init__(self):
                self.noparameters = 1
                self.area_function = None

        self.list_of_models = {
                'square' : model() ,
                'rectangle' : model() ,
                }

        # model square
        self.list_of_models['square'].noparameters = 1
        self.list_of_models['square'].area_function = self.__squared__

        # model rectangle
        self.list_of_models['rectangle'].noparameters = 2
        self.list_of_models['rectangle'].area_function = self.__product__
    # ==============================================================================================

    def area(self):
        ''' Return the area of the figure '''

        if len(self.dimensions) != self.list_of_models[ self.model ].noparameters:
            raise ValueError('Nombre of parameters not compatible with this shape')

        return self.list_of_models[ self.model ].area_function( self.dimensions )

# ==============================================================================================

if __name__ == '__main__':

    square = geometric_shape()
    self = square
    square.dimensions = [ 3. ]
    square.model = 'square'
    print( square.area() )


texts:
I made a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further.
#include <iostream>
#include <algorithm>
#include <string>
#include <random>
#include <array>
#include <map>
#include <limits>

namespace
{
    enum Winner { Tie, Player, Computer, WinnerCount };
    enum Items { Rock, Paper, Scissors, ItemsCount };

    template<typename T, std::size_t N>
    using Matrix = std::array<std::array<T, N>, N>;
}

std::string user_choice(const std::array<std::string, Items::ItemsCount>& data)
{
    std::string result;
    static auto comp = [&result](const std::string& str) { return str == result; };
    bool is_input_valid = false;

    do
    {
        std::cout << "Enter your choice, rock, paper, or scissors: ";
        std::getline(std::cin, result);

        is_input_valid = !(std::cin.fail() || std::none_of(data.begin(), data.end(), comp));

        if (!is_input_valid) {
            std::cout << "Not valid input.\n";
        }

        std::cin.clear();
        std::cin.ignore(std::cin.rdbuf()->in_avail());
    } while (!is_input_valid);

    return result;
}

bool play_again()
{
    char result;
    bool is_input_valid = false;

    do
    {
        std::cout << "Do you want to play again? [y/n]: ";
        std::cin >> result;

        result = std::toupper(result);

        is_input_valid = !(std::cin.fail() || (result != 'Y' && result != 'N'));

        if (!is_input_valid)
        {
            std::cout << "Not valid input.\n";
        }

        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } while (!is_input_valid);

    return result == 'Y';
}

int main()
{
    // Set up game
    const Matrix<Winner, Winner::WinnerCount> table
    {
        {  // Rock      Paper      Scissors
            { Tie,      Computer,  Player   }, // Rock
            { Player,   Tie,       Computer }, // Paper
            { Computer, Player,    Tie      }, // Scissors
        }
    };

    const std::array<std::string, Items::ItemsCount> data
    {
        "rock",
        "paper",
        "scissors"
    };

    std::map<std::string, Items> binding_items
    {
       { data[Items::Rock],      Items::Rock     },
       { data[Items::Paper],     Items::Paper    },
       { data[Items::Scissors],  Items::Scissors },
    };

    const std::array<std::string, Winner::WinnerCount> winner_result
    {
       "It's a tie!\n\n",
       "You win!\n\n",
       "You lose!\n\n"
    };

    std::mt19937 engine{ std::random_device()() };
    auto dist = std::uniform_int_distribution<>(0, Items::ItemsCount - 1);

    // Game loop
    do
    {
        std::cout << "\n\n\tRock Paper Scissors Game\n\n";

        const auto user_chose = user_choice(data);
        const Items player = binding_items[user_chose];

        const Items computer = static_cast<Items>(dist(engine));
        const auto computer_chose = data[computer];

        std::cout << "\n\nYou entered: " << user_chose << '\n';
        std::cout << "Computer chose: " << computer_chose << '\n';

        std::cout << winner_result[table[player][computer]];
    } while (play_again());
}


texts: This python code converts integers to strings and strings to ints without the inbuilt functions "int()" and "str()"

texts:
It is my solution from a challange from edabit.com named "Drunken Python". Thats the task:
You need to create two functions to substitute str() and int(). A function called int_to_str() that converts integers into strings and a function called str_to_int() that converts strings into integers.
I hope you can tell me things I could do better and if the algorithms I used (e.g. to calculate the length of an int) are optimal.
# A function called int_to_str() that converts integers into strings and a function called str_to_int() that
# converts strings into integers without using the in built functions "int()" and str().

def str_to_int(num_str):
    dec_places = {11: 10000000000, 10: 1000000000, 9: 100000000, 8: 10000000, 7: 1000000, 6: 100000, 5: 10000, 4: 1000,
                  3: 100, 2: 10, 1: 1}
    char_digit = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    num = 0
    length = len(num_str)
    for i in range(length):
        x = char_digit[num_str[0 - (i + 1)]] * dec_places[i + 1]
        num = num + x
    return num

def calculate_length(num):
    div = 10
    i = 1
    while num / div >= 1:
        div = div * 10
        i = i + 1
    return i

def int_to_str(num_int):
    word = ""
    div = 10
    char_digit = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
    length = calculate_length(num_int)
    for i in range(length):
        x = (num_int % div) // (div // 10)
        word = char_digit[x] + word
        num_int = num_int - x
        div = div * 10
    return word
```


texts: Using C# generics and factory classes to map IDataReader to POCO?

texts:
I'm in the process of doing some mapping of POCOs via IDataReader. I'd love to hear thoughts on the approach and if they are any good ways to improve what I have done.

public class Code
{
    public int Id { get; set; }
    public string Type { get; set; }
    public string Value { get; set; }
    public string Description { get; set; }
}

public class CodeRepository : GenericRepository
{
    public CodeRepository(IDbConnection connection) : base(connection) { }

    public IEnumerable<Code> GetCodesForDemographics()
    {
        var sql = @"
            Select
                CODE_TYPE,
                CODE,
                DESCRIPTION
            From
                Codes
            Where
                CODE_TYPE In ('language', 'lang_service', 'transfer', 'admit_type', 'Value',
                                'admit_src', 'state', 'county', 'ethnic', 'race',
                                'exempt_unit_code', 'alt_care_type_code')";

        using (var manager = new DbCommandManager(this.Connection, sql))
        {
            using (var reader = manager.GetReader())
                return DbAutoMapper.MapReaderToList<Code, CodeFactory>(reader);
        }

    }

public class CodeFactory : IFactory<Code>
{
    public Code CreateTFromReader(IDataReader reader)
    {
        try
        {
            var code = new Code();
            code.Type = (reader["CODE_TYPE"] as string) ?? String.Empty;
            code.Description = (reader["DESCRIPTION"] as string) ?? String.Empty;
            code.Value = (reader["CODE"] as string) ?? String.Empty;
            return code;
        }
        catch (Exception)
        {
            throw new Exception("Error creating Code objects from reader.");
        }
    }
}


texts: Verlet integration movement - doubt for on_key_press() methods

texts:
Based on my understanding of Verlet integration I tryed to use it over my Euler method to move my character in a 2D space.
I will put only the neccessery code, but if anything else is needed I will edit my post.

This is my Character class (which I probably need to rename to Charactor)

class PlayerData(object):
    def __init__(self):
        self.applied_force = Vector(0, 0)
        self.mass = 70 /killograms
        self.position = Vector(15, 200)
        self.old_position = Vector(self.position.x, self.position.y)
        self.acceleration = Vector(self.applied_force.x / self.mass, 0)

    # These methods seems smelly
    def on_left_key_pressed(self):
        self.applied_force.x = -200
        self.old_position.x = self.position.x + 3
    def on_right_key_pressed(self):
        self.applied_force.x = 200
        self.old_position.x = self.position.x - 3
    def on_left_key_released(self):
        self.applied_force.x = 0
        self.old_position.x = self.position.x
    def on_right_key_released(self):
        self.applied_force.x = 0
        self.old_position.x = self.position.x
    def keys_up(self):
        self.applied_force = Vector(0, 0)
        self.old_position = Vector(self.position.x, self.position.y)

    def verlet(self, dt):
        self.acceleration = Vector(self.applied_force.x / self.mass, 0)
        temp = Vector(self.position.x, self.position.y)

        self.position.x += self.position.x - self.old_position.x + \
                           self.acceleration.x * dt * dt

        self.old_position = Vector(temp.x, temp.y)

    def update(self, dt):
        self.verlet(dt)
        // here be a collision detection method which I need to write
        self.rect.left = self.position.x
        self.rect.top = self.position.y

And this is the Event class which has 2 main methods - listener and handler

class EventManager(object):
    def __init__(self, player):
        self.player = player
        # few bools to indicate key states, the listener method toggles them

    def handler(self):
        ''' Calls Player on_x_key_pressed(), on_x_key_released()
        methods according to event bools set from the listener method.
        '''
        # Moving
        if self.left:
            self.player.on_left_key_pressed()
        elif self.right:
            self.player.on_right_key_pressed()
        else:
            self.player.on_keys_up()

I have jumping but I'm still trying to understand the right aproach to writing a proper verlet integration method.
I can controll how fast my object is moving by setting the self.old_position.x = self.position.x + 3 to self.old_position.x = self.position.x + 20 for example.
This also stops the movement, but I truly suspect that this is incorect or simply a very bad aproach.

EDIT: Redesigned the event handler method and shortened the bool names for simplicity.
I have no problems running the code, it is working as intented.
The thing I dont like is how my on_x_key_pressed() methods look, you can find them in PlayerData class.
I have the feeling that, to stop my character from continues move in some direction I have to set old_position.x = position.x.
Is this the right aproach to stop character movement?
And to control how fast the object is moving (the velocity), I have to manually set old_position to some value bigger/lower than position.x as seen in on_left_key_pressed() and on_right_key_pressed().
I wonder if there is better aproach to control the velocity?


texts: Scaling and incrementing non-zero elements of a NumPy matrix

texts:
I have a NumPy matrix C and want create a copy of it cPrime, which has some operation of the original matrix to all non-zero values of it. In the code below, for each non-zero element of C, I multiply by 30 and then add 1:

import numpy as np

size = 6
C = np.zeros((size,size), dtype=int)

C[4][0] = 2
C[4][1] = 5
C[4][2] = 3
C[0][3] = 1
C[1][3] = 1
C[2][3] = 1
C[3][5] = 3

cPrime = np.zeros((size, size),dtype=int)
for i in range(size):
    for j in range(size):
        if C[i][j] != 0:
            cPrime[i][j] = C[i][j]*30 + 1

This code works, but it feels inefficient. I'm about 99% sure that there's a really efficient way to achieve this goal, maybe using a masked array, but I haven't been able to figure it out.


texts:
I was trying to write Sieve for the first time and I came up with this code:

def sieve(num):
    numbers = set(range(3, num, 2))
    for i in range(3, int(num**(1/2)) + 1 , 2):
        num_set = set(i*c for c in range(3, num//2, 2))
        numbers = numbers - num_set
    return list(sorted((2, *numbers)))

The problem is that for num > 10**6 the time to create prime numbers increases.

Also, when I tried num = 10**8 my computer stopped working, started to make awkward noises and I had to restart it.

I think the problem is that I am dealing with sets. For large numbers (for instance, in num = 10**8 case) the set cannot be produced since my computer cannot process that much information, hence it stops.

Is there a way to solve this memory or time problem using my code or should use a different algorithm?


texts:
Is there any room for improvement?

import random

def play_again():
    while True:
        replay = input('Play again? Yes or No?\n')
        if replay.lower() == 'yes':
            return True
        elif replay.lower() == 'no':
            return False
        print('Invalid input.')

def main():
    print('Welcome to the number guess game!', end='\n\n')

    random_number = random.choice(range(1, 51)) #Genarate a number between 1 and 50 inclusive

    print("I'm thinking of a number which is between 1 and 50 (inclusive). Can you guess it?")

    guesses, guess = 0, 0

    while guess != random_number:
        try:
            guess = int(input("Enter a number: "))
        except:
            print('Invalid input.')
            continue
        if guess > random_number:
            print('Too high. Guess lower.')
        elif guess < random_number:
            print('Too low. Guess higher.')
        guesses+=1
    print('Congratz. You guessed my number {0} in {1} guesses'.format(random_number, guesses))

    if play_again():
        main()
    else:
        print('Bye!')

main()


texts: Resizing a discrete uniform CSRNG distribution

texts:
I have a requirement to generate a uniform distribution of cryptographically secure random numbers. To generate these numbers I only know of the RNGCryptoServiceProvider class, that has the method GetBytes(byte[] data). This is good, but I have to then change this discrete uniform distribution ranging from 0 - 256 to a different discrete uniform distribution ranging from 0 - limit.

And so I thought of three ways to do this. The first two ways were using % and /, which don't work if limit is not a divisor of 256. As this leads to a non-uniform distribution. However filtering all numbers that a not less than the limit works and gives a uniform distribution, however has terrible performance problems when limit is a small number.

I'm currently using:

private static IEnumerable<object> Cycle(object value=null)
{
    while (true)
    {
        yield return value;
    }
}

private static IEnumerable<byte> RandomBytes(int chunkSize)
{
    return Cycle().SelectMany(unused =>
    {
        var b = new byte[chunkSize];
        new RNGCryptoServiceProvider().GetBytes(b);
        return b;
    });
}

private static IEnumerable<int> RandomFilter(int chunkSize, int limit)
{
    return RandomBytes(chunkSize).Where(n => n < limit).Select(n => (int)n);
}

Since I tried using % and /, below is the code that I used to check if there is a uniform distribution, and those two solutions.

private static IEnumerable<int> RandomModulo(int chunkSize, int limit)
{
    return RandomBytes(chunkSize).Select(n => n % limit);
}

private static IEnumerable<int> RandomResize(int chunkSize, int limit)
{
    var denom = 256.0/limit;
    return RandomBytes(chunkSize).Select(n => (int)(n / denom));
}

private static void TestDistribution(int limit, int amount, int chunkSize, Func<int, int, IEnumerable<int>> fn)
{
    var counter = new Dictionary<int, int>();
    foreach (var i in Enumerable.Range(0, limit))
    {
        counter[i] = 0;
    }

    foreach (var i in fn(chunkSize, limit).Take(amount))
    {
        counter[i] += 1;
    }
    Console.WriteLine($"{limit} {amount} {chunkSize} {counter.Select(kv => kv.Value).Aggregate(0, (acc, x) => acc + x)}");
    Console.WriteLine(string.Join(", ", from kv in counter select $"{kv.Key}"));
    Console.WriteLine(string.Join(", ", from kv in counter select $"{kv.Value}"));
    Console.WriteLine();

}

private static void Main()
{
    TestDistribution(45, 100000000, 1000, RandomFilter);
    TestDistribution(32, 100000000, 1000, RandomFilter);
    Console.WriteLine();

    TestDistribution(45, 100000000, 1000, RandomModulo);
    TestDistribution(32, 100000000, 1000, RandomModulo);
    Console.WriteLine();

    TestDistribution(45, 100000000, 1000, RandomResize);
    TestDistribution(32, 100000000, 1000, RandomResize);
    Console.ReadLine();
}


texts: Time limit exceeded for SPOJ problem "Prime Generator"

texts:
Input

  The input begins with the number \$t\$ of test cases in a single line
  (\$t \le 10\$). In each of the next \$t\$ lines there are two numbers \$m\$ and \$n\$ (\$1 \le m \le n \le 1000000000\$, \$n-m \le 100000\$) separated by a space.

Output

  For every test case print all prime numbers \$p\$ such that \$m \le p \le n\$,
  one number per line, test cases separated by an empty line.

Example

Input:

2
1 10
3 5

Output:

2
3
5
7

3
5

I am trying my best to speed up this code, but I don't know any better way of doing it.

T = int(raw_input())
x= ' '
for test in xrange(T):
    minim,maxim = map(int,raw_input().split())
    if minim == 1:
        minim += 1
    for number in xrange(minim,maxim+1):
        if number == 2:
            print number
        for i in xrange(2,number):
            if number % i == 0:
                break
            elif i == number-1:
                print number
    print x


texts:
I've recently taken a renewed interest in non-standard languages like Brainfuck and TIS-100. I'm currently writing a Fibonacci generator in Brainfuck which differs a bit in approach from the usual generators already around.

Since my current understanding of the language is very limited, the limited debugging capabilities in the average Brainfuck IDE and the fact that I've never written a Fibonacci generator before, I decided to write one in Python first.

The usual Fibonacci generator seems to be recursive. If I understand correctly, mine isn't. Since the goal was to produce a generator which would serve as a blueprint for it's Brainfuck equivalent, I tried writing it as straight-forward as possible.

The straight-forwardness means no fancy stuff. Exception handling is for the weak and it's too short to warrant a function just for the sake of defining a function. If this is to be re-used, the whole thing will turn into a function.

Again, it's a blueprint for an implementation in a language where such constructs don't exist.

import sys

HIGHEST_FIBO = int(sys.argv[1])

Fibo = [1, 1, 2]

for i in Fibo:
    print i

for i in xrange(HIGHEST_FIBO-len(Fibo)):
    Fibo[0] = Fibo[1]
    Fibo[1] = Fibo[2]
    Fibo[2] = Fibo[0] + Fibo[1]
    print Fibo[2]

It's speed surprised me. 2000 under 2 seconds, where print is likely the most expensive operation. It should be very memory efficient as well.

I think this is about as simple and as clear as it gets, but let's see if there is room for improvement anyway.


texts:
I wanted to make a class for type hinting that the result of a function is a homogenous deque.

from typing import MutableSequence, T, _geqv
from collections import deque

class Deque(deque, MutableSequence[T], extra=deque):
    """A typing-like type for use with function signatures using deque's."""
    def __new__(cls, *args, **kwds):
        if _geqv(cls, Deque):
            raise TypeError("Type Deque cannot be instantiated; "
                            "use deque() instead")
        return deque.__new__(cls, *args, **kwds)

I basically copied the structure of similar code in the typing module. My question is, is this the correct way to do this?


texts: Filling a container with objects using pointers / iterators

texts:
I have a series of nested objects that I need to serialize into a byte (unsigned char) array to send out to another computer over UDP.

Right now I each object create a std::list, and pass that list to the next object up the 'tree' and then it merges the lists to create the final packet.

class Item {
  unsigned char value;
}

class Sublist {
  std::vector<Items*> items;
  std::list<unsigned char> subpacket;

  std::list<unsigned char> Sublist::serialize() {
    subpacket.clear();
    for(auto item : items) {
      subpacket.push_back(item->value);
    }
    return subpacket;
  }
}

class Superlist {
  std::queue<Sublist> sublists;
  std::list<unsigned char> serializedSublist;
  std::list<unsigned char> packet;

  std::list<unsigned char> Superlist::serialize() {
    packet.clear();
    for(auto sublist : sublists) {
      serializedSublist = sublist.serialize();
      packet.insert(packet.end(), serializedSublist.begin(), serializedSublist.end());
    }
    return packet;
  }

}

However, this feels really inefficient with unnecessary clear() and insert() calls, and in generally feels a bit sloppy.

I feel like a more efficient approach would be for the Superlist to have a unsigned char container (vector, list, deque?), and then give each Sublist a pointer to where it should write data to.

I feel like perhaps something like:

class Sublist {
  std::vector<Items*> items;

  void Sublist::serialize(std::vector::iterator begin) {
    for(auto item : items) {
      begin->push_back(item->value);
      ++begin;
    }
  }
}

class Superlist {
  std::queue<Sublist> sublists;
  std::vector<unsigned char> packet;

  std::list<unsigned char> Superlist::serialize() {
    packet.clear();
    for(auto sublist : sublists) {
      sublist.serialize(packet.end());
    }
    return packet;
  }

}

Problems with this exact code include:

I don't think I can call push_back on a iterator
It'd be nice if I could create the final packet of a final size first, and then send pointers off to the correct location in the packet for each sublist to begin writing.

Would an approach like this work?  Is there an even more concise and clever way to place all of the objects in a buffer?


texts:
I wrote some code in Flask for site menu:

def menu(parent_id=0, menutree=None):
    menutree = menutree or []
    cur = g.db.execute('select id, parent, alias, title, ord from static where parent="'+ str(parent_id) +'" and ord>0 order by ord')
    fetch = cur.fetchall()

    if not fetch:
        return None

    return [{'id':raw[0], 'parent':raw[1], 'alias':raw[2], 'title':raw[3], 'sub':menu(raw[0])} for raw in fetch]

The data is taken from the sqlite3 table:

create table static (
  id integer primary key autoincrement,
  parent integer,
  alias string not null,
  title string not null,
  text string not null,
  ord integer
);

Variable (menu_list) is transmitted to template in each route:

@app.route('/')
def index():
    menu_list = menu()
    [...]
    return render_template('index.tpl', **locals())

Despite the fact that the code is more or less normal (except for prepared statements in a query to the database), the template is not very good:

  {% for menu in menu_list %}

    {{ menu.title }}
    {% if menu.sub %}

      {% for sub in menu.sub %}

{{ sub.title }}
        {% if sub.sub %}

          {% for subsub in sub.sub %}

{{ subsub.title }}
          {% endfor %}

        {% endif %}

      {% endfor %}

    {% endif %}

  {% endfor %}

Is it possible to improve the existing code / output / logic?


texts:
In my program I need to monitor the state of a static string value that can be changed from different threads in different parts of the system. I came up with the following simple function that, once called, waits 5 seconds to get the value, and if the value is not set, returns null:

// Waits 5 seconds for value to appear and returns this value or null
public async Task<string> GetStringValueOrNull()
{
    var delayTask = Task.Delay(5000);
    var getValueTask = Task.Run(async () =>
    {
        while (true)
        {
            if (!string.IsNullOrEmpty(ExternalValueContainer.Value)) // ExternalValueContainer.Value is 'public static string'
                return ExternalValueContainer.Value;
            await Task.Delay(500);
        }
    });

    var firstCompletedTask = await Task.WhenAny(getValueTask, delayTask);
    if (firstCompletedTask == getValueTask)
    {
        return await getValueTask;
    }
    else
    {
        return null;
    }
}

The function is used like this:

string stringValue = await GetStringValueOrNull();
if (stringValue != null)
    DoSomething(stringValue);
else
    DoSomethingElse();

Can the logic in GetStringValueOrNull be somehow simplified?


texts:
I have a myDiv.mousedown, window.mousemove, and window.mouseup event. I'm trying to organize my code, and have it clean. So I created a function and returned the 3 event handlers.
The mousedown event adds a mousemove event, and the mouseup event removes the mousemove event.

Since I need to pass the exact same object to removeEventListener() as the one I used with addEventListener(), I have to create a variable for each event handler.

This doesn't seem to be organized and clean. Does this follow common practice? If not what is the 'correct', organized and clean code to perform that?

JSFiddle

var myDiv = document.getElementById('myDiv');

var VeryUsefullClass = (function() {

  function VeryUsefullClass(parentElem, options) {
    var _this = this;
    _this.index = 0;

    _this.mouseDownHandler = _this.mouseHandler().mouseDown;
    _this.mouseMoveHandler = _this.mouseHandler().mouseMove;
    _this.mouseUpHandler = _this.mouseHandler().mouseUp;

    myDiv.addEventListener('mousedown', _this.mouseDownHandler);
    window.addEventListener('mouseup', _this.mouseUpHandler);
  }

  VeryUsefullClass.prototype.mouseHandler = function() {
    var _this = this;
    var obj = {
      mouseDown: function(e) {
        console.log('mouseDown');
        window.addEventListener('mousemove', _this.mouseMoveHandler);
      },
      mouseMove: function(e) {
        myDiv.innerHTML = 'mouseMove ' + _this.index++;
      },
      mouseUp: function(e) {
        console.log('mouseUp');
        _this.index = 0;
        window.removeEventListener('mousemove', _this.mouseMoveHandler);
      }
    }
    return obj;
  }

  return VeryUsefullClass;
})();

console.clear();

var hello = new VeryUsefullClass();
#myDiv {
  position: absolute;
  background-color: orange;
  width: 200px;
  height: 100px;
}


texts:
I have a query to split a delimited string into to multiple columns. The query is extremely slow and takes more than 5 minutes to handle 80444 rows. How can I improve execution time?

  WITH cte (Execution_ID,Intake_Generic_ID, [File_Name],F1,Report_Attributes) AS ( SELECT
    Execution_ID,  Intake_Generic_ID,
    [File_Name],  F1,
    CONVERT(XML,'<Report><Attribute>'
        + REPLACE(F1,'~', '</Attribute><Attribute>')
        + '</Attribute></Report>') AS Report_Attributes FROM [dbo].[Intake_Generic] )

SELECT
    Execution_ID,  Intake_Generic_ID,
    [File_Name],
    LTRIM(RTRIM(Report.value('Attribute[1]','varchar(50)'))) AS [TransactionDate],
    LTRIM(RTRIM(Report.value('Attribute[2]','varchar(50)'))) AS [TransactionNum],
    LTRIM(RTRIM(Report.value('Attribute[3]','varchar(50)'))) AS [Interchange],
    LTRIM(RTRIM(Report.value('Attribute[4]','varchar(50)'))) AS [Gantry],
    LTRIM(RTRIM(Report.value('Attribute[6]','varchar(50)'))) AS [GantryDirection],
    LTRIM(RTRIM(Report.value('Attribute[7]','varchar(50)'))) AS [GantryEntryExit],
    LTRIM(RTRIM(Report.value('Attribute[8]','varchar(50)'))) AS [RTCID],
    LTRIM(RTRIM(Report.value('Attribute[9]','varchar(100)'))) AS [Vehicle_Classification_Cd],
    LTRIM(RTRIM(Report.value('Attribute[10]','varchar(100)'))) AS [VehicleClassification],
    LTRIM(RTRIM(Report.value('Attribute[11]','varchar(100)'))) AS [Txn_Iden_Cd],
    LTRIM(RTRIM(Report.value('Attribute[12]','varchar(100)'))) AS [TransactionIdentification] FROM  cte S
        CROSS APPLY Report_Attributes.nodes('/Report') AS Tbl(Report)  order by Intake_Generic_ID


texts: Finding ways to achieve a target sum using recursion

texts:
I need your review and suggestions how to make this code better. I'm just learning recursion and sure that this solution is not ideal.

Question:

Write a function that given an input array of integers with a varying length input integers array, and the desired target_sum, returns the number of combinations, of any length, that add up to that target_sum.

EXAMPLE 1:

total_combinations = calculate_combinations([5, 5, 15, 10], target_sum=15)

ANSWER 1:

Should return 3, as there are 3 combinations of numbers from the input array that add up to 15, namely:

15 5+10 5+10 10

solution:

private static int mainfunction(int[] input, int target)
{
    int result = 0;
    for (int i = 0; i <= input.Length - 2; i++)
    {
        int temp = mainfunction_slave(input, i, target, 1);
        result = result + temp;
    }
    return result;
}
private static int mainfunction_slave(int[] input, int index, int target, int check)
{
    if ((index  + check) > (input.Length - 1))
        return 0;
    if ((input[index] + input[index + check]) == target || (input[index] == target))
        return mainfunction_slave(input, index, target, check + 1) + 1;
    return mainfunction_slave(input, index, target, check + 1);
}

The task needs to be done via recursion, but if you have any other better solution, please let me know.


texts:
I'm writing a basic search engine for my website.

It works but I'm really unhappy with the code. I know it can't be improved but I'm lacking some experiences here.
In my params from my search I get:

{"utf8"=>"✓", "authenticity_token"=>"aNY2ZVpeyZsLnIVegQPpPz/22VYx2ug+tbfu0Nzngac=", "skills"=>"3,8", "country"=>"USA", "state"=>"TX", "city"=>"Paris", "commit"=>"Search", "controller"=>"jobs", "action"=>"index"}

Here is my controller:

class JobsController < ApplicationController
  before_action :authenticate_user!, :except => [:index]

  def index
    search_jobs
  end

  def search_jobs
    search_filters = search_params
    if search_filters.present?
      skills = search_filters[:skills]
      city, state, country = search_filters[:city], search_filters[:state], search_filters[:country]
      search_jobs = Job.select(:id).joins(:skills)
      search_jobs = search_jobs.where(build_where(skills)) if skills.present?
      search_jobs = search_jobs.group("jobs.id")
      search_jobs = search_jobs.group("jobs.city, jobs.state") if city.present? || state.present?
      search_jobs = search_jobs.group("jobs.created_at")
      search_jobs = search_jobs.order("city <> '#{city}'") if city.present?
      search_jobs = search_jobs.order("state <> '#{state}'") if state.present?
      search_jobs = search_jobs.order("country <> '#{country}'") if country.present?
      search_jobs = search_jobs.order("count(*) desc")
      search_jobs = search_jobs.order('jobs.created_at DESC')
      jobs_id = search_jobs.map(&:id)
    end
    jobs = Job.includes(:company, :skills)
    jobs = jobs.where(id: jobs_id) if jobs_id.present?
    jobs = jobs.most_recent
    @jobs = jobs
  end

  def build_where(skills_filters)
    skills = skills_filters.split(", ")
    query = "'skills'.'id' = #{skills.first}"
    skills.shift
    skills.each do |skill|
      query << " OR 'skills'.'id' = #{skill}"
    end
    return query
  end

  private

  def search_params
    params.permit(:skills, :country, :city, :state)
  end

end

Few, things:

I'm not happy with the build_where method, but I can't think of a way to build a where dynamically based on the skills the users are looking for.
The search_jobs seems the be a bad idea. When I run this in the developer console it looks like each line is executing a SQL query which is an issue performance wise. 10 queries  to get a list of IDs seems to be terrible
Then I'm doing 3 more queries afterward: to get all the jobs with all the information needed.

So, I think my code is not really good, but I'm not sure how I can improve it. My goal overall is


texts: Ghostscript check, sends e-mail if one occurs

texts:
I've created a program that will search our work server where Ghostscripts occur. How it accomplishes this is by first sshing to the server specified, running a bash command to search the server for Ghostscripts caused by our guy that uses them, most frequently. If it finds one, it e-mails somebody on my team. It will also e-mail if it doesn't find one.

I'm curious to know if there are other ways I can do this specific task. Better syntax, etc..

#!/local/usr/bin/ruby

require 'rubygems'
require '<mailgem>'
require 'etc'
require 'net/ssh'

class GhostScript

  attr_accessor :host, :usr, :pass

  def initialize(host, usr, pass)
    @host = host
    @usr  = usr
    @pass = pass
  end

  def script_search
    ssh = Net::SSH.start(host, usr, :password => pass)
    res = ssh.exec!('ps -u <user>|grep gs')
    if res == nil
      MailGem::Mail.new do |m|
        m.to      = '<email-address>'
        m.subject = 'GhostScript not found'
        m.body    = "GS not found on server: #{host}"
      end.send
      else
      alert(res)
    end
  end

  def alert(res)
    MailGem::Mail.new do |m|
      m.to      = '<email-address>'
      m.subject = 'GhostScript found'
      m.body    = "GS script found on server: #{host}",
                  "Results of search: #{res}"
    end.send
  end
end

check = GhostScript.new('<server>', Etc.getlogin, nil)
check.script_search


texts: New to immediately-invoked function expression with JavaScript, curious about placement

texts:
At the end of the immediately-invoked function expression, there is an if statement that checks the screen width and loads in some resources. I'm curious if it is best practice to include this logic inside my IIFE, or outside. Both seem to function the same as far as I can tell, though I'm curious if there is preferred/best way this should be done.

Also of interest to me, inside the IIFE I have a if/if else/else statement. I'm curious if the last else, with the return in it is necessary. Does it offer any benefits or should I remove it.

Feedback is much appreciated!

Below is the code I'm working with:

(function(w){
    w.loader = function(filetype, filename, mediaquery){

      var head = document.getElementsByTagName("head")[0],
          stylesheet = document.createElement('link'),
          script = document.createElement('script'),
          filetype = filetype.toLowerCase(); // normalize filetype data for use in conditions

      // If file type is set to CSS, create dynamic stylesheet link element
      if (filetype === 'css'){
        stylesheet.type = 'text/css';
        stylesheet.rel = 'stylesheet';
        stylesheet.href =  (filename + '.css');
        stylesheet.media = (mediaquery) ? mediaquery : 'screen'; // Use screen for media unless otherwise specified
        // If a file name has been specified, append dynamic stylesheet link element
        if (filename.length){
          head.appendChild(stylesheet);
        }
      }
      // If file type is set to JS, create dynamic script element link
      else if(filetype === 'js'){
        script.type = 'text/javascript';
        script.src = (filename + '.js');
        // If a file name has been specified, append dynamic script element
        if (filename.length){
          head.appendChild(script);
        }
      }
      else{
        return;
      }

    };

    if(Math.max(screen.width,window.outerWidth) > 600 ){
      alert("Large Screen");
      loader('CSS', 'large-screen');
      loader('JS', 'large-screen');
    }

  }(this));

  /*
  if(Math.max(screen.width,window.outerWidth) > 600 ){
    alert("Large Screen");
    loader('CSS', 'large-screen');
    loader('JS', 'large-screen');
  }
  */


texts: Classes to serialize departments and their employees

texts:
I have many small but similar classes like these:

class DepartmentSerializer < Serializer
  self.root = false
  attributes :id, :name
  has_many :employees, serializer: EmployeeSerializer
  has_one :location, serializer: LocationNameSerializer
end

class DepartmentWithManagersSerializer < Serializer
  self.root = false
  attributes :id, :name
  has_many :primary_managers, serializer: ManagerSerializer
  has_many :secondary_managers, serializer: ManagerSerializer
end

class DepartmentNameSerializer < Serializer
  self.root = false
  attributes :id, :name
end

class DepartmentWithEmployeesSerializer < Serializer
  self.root = false
  attributes :id, :name
  has_many :employees, serializer: EmployeeNameSerializer
end

As you can see they're all just variations on a theme. There is a potential here for a combinatorial explosion of classes if there are enough use cases. Should I do something like ActiveRecord's find methods which allow you to create methods like .find_by_name_and_manager_and_location?


texts: Segregate even and odd numbers in a given array

texts:
Given an array A[], write a function that segregates even and odd
  numbers. The functions should put all even numbers first, and then odd
  numbers.

  Example:

  Input = {12, 34, 45, 9, 8, 90, 3}
  Output = {12, 34, 8, 90, 45, 9, 3}

  Input = {6, 4, 6, 8, 1, 1, 1}
  Output = {6, 4, 6, 8, 1, 1, 1}

public static void main (String args[]) {
    int []array = {6,1,6,8,2,2,3};
    evenOddFunction(array);
    System.out.println(Arrays.toString(array));
}

private static void evenOddFunction(int []data) {
    int leftSide = 0;
    int rightSide = data.length - 1;

    while(rightSide >= leftSide) {
        if(data[leftSide] % 2 != 0 && data[rightSide] % 2 == 0) {
             // swapping as soon as we find even and odd combination
             swappEvenOdd(data, leftSide, rightSide);
             leftSide++;
             rightSide--;
        } else {
            if(data[leftSide] % 2 == 0) {
                leftSide++;
            }
            if(data[rightSide] % 2 == 1) {
                rightSide--;
            }
        }
    }
}

private static void swappEvenOdd(int []data , int left, int right) {
    // swapping even and odd numbers
    int temp = data[left];
    data[left] = data[right];
    data[right] = temp;
}

I don't want to use another array for this so went with swap logic. Any chances of improvement/optimizations in this code?

What is the minimum space and time complexity we can achieve for this problem?


texts: iterative binary_search Python implementation

texts:
I did a Python implementation of binary search implementation
iteratively. It passes all of the test and I was wondering if I can
get any feedback.

#!python

def binary_search_iterative(array, item):
    """iteratively return the index of the item with binary search or None if not found"""
    # Sorted array that has to be the condition
    # go through several iteration until we found this
    # First, set the lower_index = 0
    # upper_index as the length of array -1
    lower_index = 0
    upper_index = len(array) - 1
    # iteration until it is found
    while lower_index <= upper_index:
        # calculate the middle index by sum the lower_index and upper_index and divide by 2
        middle_index = (lower_index + upper_index) // 2 # // is int division
        # check if the item is found
        if array[middle_index] == item:
            return middle_index
        elif array[middle_index] < item:
            lower_index = middle_index + 1
        elif array[middle_index] > item:
            upper_index = middle_index - 1

    # Did not find
    return None

def binary_search(array, item):
    """return the index of item in sorted array or None if item is not found"""
    # change this to call your implementation to verify it passes all tests
    return binary_search_iterative(array, item)

link to my linear search code:
https://gist.github.com/anonymous/be81dc4ab1a26328785ed8cffce33346

def linear_search(array, item):
    for index, value in enumerate(array):
        if item == value:
            return index  # found
    return None  # not found

#!python

from search import linear_search, binary_search
import unittest

class SearchTest(unittest.TestCase):

    def test_binary_search_with_items_in_list(self):
        # binary search requires list values to be in sorted order
        names = ['Alex', 'James', 'Julia', 'Matthew', 'Nathan', 'Conrad', 'John']
        # binary search should return the index of each item in the list
        assert binary_search(names, 'Alex') == 0
        assert binary_search(names, 'James') == 1
        assert binary_search(names, 'Julia') == 2
        assert binary_search(names, 'Matthew') == 3
        assert binary_search(names, 'Nathan') == 4
        assert binary_search(names, 'Conrad') == 5
        assert binary_search(names, 'John') == 6

    def test_binary_search_with_items_in_list2(self):
        # binary search requires list values to be in sorted order
        names = ['Person0', 'Person1', 'Person2', 'Person3', 'Person4', 'Person5', 'Person6']
        # binary search should return the index of each item in the list
        assert linear_search(names, 'Person0') == 0
        assert linear_search(names, 'Person1') == 1
        assert linear_search(names, 'Person2') == 2
        assert linear_search(names, 'Person3') == 3
        assert linear_search(names, 'Person4') == 4
        assert linear_search(names, 'Person5') == 5
        assert linear_search(names, 'Person6') == 6

    def test_binary_search_with_items_not_in_list(self):
        # binary search requires list values to be in sorted order
        names = ['Alex', 'James', 'Julia', 'Matthew', 'Nathan', 'Conrad', 'John']
        # binary search should return None for any item not in the list
        assert binary_search(names, 'Jeffrey') is None
        assert binary_search(names, 'nobody') is None

    def test_binary_search_with_items_not_in_list2(self):
        # binary search requires list values to be in sorted order
        names = ['Person5', 'Person2', 'Person4', 'Person1', 'Person3', 'Person6', 'Person0']
        # binary search should return None for any item not in the list
        assert binary_search(names, 'Jack-in-Box') is None
        assert binary_search(names, 'nobody') is None

if __name__ == '__main__':
    unittest.main()


texts:
I have a simple webserver written in Python using aiohttp. My goal is a server that can receive many file uploads simultaneously and stream them all to disk. This code works, but I'm not sure if it is efficiently handling simultaneous connections:

import pathlib
import click
from aiohttp import web
from src import settings
from src import logger

log = None

async def upload_handler(request):
    """
    POST handler that accepts uploads to any path.
    The files are accepted and saved under the root path
    of the server.
    """
    # You cannot rely on Content-Length if transfer is chunked.
    size = 0
    local_path = settings.WWW_ROOT + request.path
    path_without_file = local_path.rsplit('/', 1)[0]
    pathlib.Path(path_without_file).mkdir(parents=True, exist_ok=True)

    with open(local_path, 'wb') as f:
        while True:
            chunk, is_end_of_http_chunk = await request.content.readchunk()
            if not chunk:
                break
            size += len(chunk)
            f.write(chunk)

    return web.Response(text='%d bytes uploaded' % size, status=201)

@click.command()
@click.option('--port', type=int, default=8000)
@click.option('--log-level', type=click.Choice(['debug', 'info', 'warning', 'error', 'critical']), default='info')
def cli(port, log_level):
    global log
    log = logger.get_default_logger(name='', log_level=log_level)
    app = web.Application(client_max_size=2e9, debug=settings.DEBUG)
    app.router.add_post('/{tail:.*}', upload_handler)
    web.run_app(app, port=port)

if __name__ == '__main__':
    cli()

The aiohttp stuff feels a little magic to me. Is this running on parallel threads? I'm seeing some high CPU usage at times.

Are there performance issues here? I see performance issues on the server, but I'm not sure if they occur here or elsewhere in the stack.


texts: Convert geodetic coordinates to geocentric (cartesian)

texts:
I'd like to retain as much float precision as possible without having to resort to specialized libraries so I need this code to work with only standard modules.

I'm doing this in QGIS where specialized libraries aren't available by default. numpy would be OK to use.

Sources for the computations can be found on Wikipedia.

Here is my code:

import math

## Ellipsoid Parameters as tuples (semi major axis, inverse flattening)
grs80 = (6378137, 298.257222100882711)
wgs84 = (6378137, 298.257223563)

def geodetic_to_geocentric(ellps, lat, lon, h):
    """
    Compute the Geocentric (Cartesian) Coordinates X, Y, Z
    given the Geodetic Coordinates lat, lon + Ellipsoid Height h
    """
    a, rf = ellps
    lat_rad = math.radians(lat)
    lon_rad = math.radians(lon)
    N = a / math.sqrt(1 - (1 - (1 - 1 / rf) ** 2) * (math.sin(lat_rad)) ** 2)
    X = (N + h) * math.cos(lat_rad) * math.cos(lon_rad)
    Y = (N + h) * math.cos(lat_rad) * math.sin(lon_rad)
    Z = ((1 - 1 / rf) ** 2 * N + h) * math.sin(lat_rad)

    return X, Y, Z

Input:

lat = 43.21009
lon = -78.120123
h = 124
print(geodetic_to_geocentric(wgs84, lat, lon, h))

Output:

(958506.0102730404, -4556367.372558064, 4344627.16166323)

This online converter gives the following output:

X: 958506.01027304
Y: -4556367.37255806
Z: 4344627.16160147

So, quite close for X and Y but slightly different for Z. Is this a rounding error ? If so, on which side ? Is there a better strategy to do the computations that may retain better precision ?


texts:
For the problem of moving zeroes to the back of the array as detailed here. I did it like below in Erlang. I just think my way is very basic and probably there is a more elegant way to do it using recursion?

-module(move_zeroes).
-compile([export_all, debug_info]).

%% This is solving this problem:

%% API exports
-export([]).

move_zeroes(L) ->
    moving_zeroes(L, []).

moving_zeroes(L, _) ->
    Zeroes = lists:filter(fun(X) -> X == 0 end, L),
    Non = lists:filter(fun(X) -> X /= 0 end, L),
    Non ++ Zeroes.


texts: Devise an algorithm of complexity O(N) finding No of 1's from a 2 dimensional matrix[N][N] containing 1's and 0's

texts:
Assume a 2D [n][n] matrix of 1's and 0's. All the 1's in any row should come before 0's. The number of 1's in any row I should be at least the number of 1's row (i+1). Find a method and write a C program to count the number of 1's in a 2D matrix. The complexity of the algorithm should be order n.

The question is from Cormen's Algorithm Book. Kindly point out the mistakes in my algorithm and hopefully suggest a better way.

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

  int **map;
   int getMatrix();

  main()
  {
   int n,i,j,t;
 j=0;
 n=getMatrix();
   i=n-1;
    int sum[n];
   for(t=0;t<n;t++)
    sum[t]=0;
int count=0;
 while ( (i>=0) && (j<n) )
 {
  if ( map[i][j] == 1 )
   {
    j++;
    count=count+1;
   }
  else
  {
     if (i==(n-1))
    {
        sum[i]==count;
        count=0;
    }
    else
    {
        sum[i]=sum[i+1]+count;
        count=0;
        i--;
    }
  }
  }
       for (t=0;t<n;t++)
         {
             if ((t==(n-1)) && (sum[t]==0))
               sum[t]=0;
                  else if ((sum[t]==0) && (sum[t+1]>0))
               sum[t]=sum[t+1];
             }
       int s=0;
          for (t=0;t<n;t++)
        s=s+sum[t];
          printf("\nThe No of 1's in the given matrix is %d \n" ,s);
        }

  int getMatrix()
 {
   FILE *input=fopen("matrix.txt","r");
 char c;
     int nVer=0,i,j;
 while((c=getc(input))!='\n')
   if(c>='0' && c<='9')
    nVer++;
      map=malloc(nVer*sizeof(int*));
    rewind(input);
    for(i=0;i<nVer;i++)
 {
  map[i]=malloc(nVer*sizeof(int));
   for(j=0;j<nVer;j++)
  {
    do
    {
        c=getc(input);
    }while(!(c>='0' && c<='9'));
    map[i][j]=c-'0';
}
}
     fclose(input);
  return nVer;
  }


texts: Grouping a dictionary of lists based on  % key and the first value in the list

texts:
How to best optimize this code ?

Problem Description:

Input(counts) is an array of \$n\$ integers, where each counts[i], (\$0\le i< n\$) denotes the total number of elements in a particular group that element i belongs to. For example, if counts = [3, 3, 3, 3, 3, 1, 3], then there are three groups; elements 0, 1, 2, 3, 4, and 6 are in one of two 3-element groups, and element 5 is in a 1-element group.

A group is valid if all the elements in the group have minimal ID numbers. In other words, a group of size \$k\$ must contain the \$k\$ smallest ID numbers belonging to a group of that size with respect to the smallest element ID in the group. For example, if counts = [3, 3, 3, 3, 3, 1, 3], then the grouping [0, 1, 2], [3, 4, 6], and [5] is valid; however, the grouping [0, 1, 4], [2, 3, 6], and [5] is not valid because the group [0, 1, 4] does not contain the three smallest element IDs for the set of element IDs belonging to 3-element groups (i.e., \${0,1,2,3,4,6}\$).

It is guaranteed that a valid grouping always exists for the given input array.

VALID GROUPING:

0 1 2
3 4 6
5

INVALID GROUPING:

0 1 4
2 3 6
5

Sample Input (1):

counts = [2,1,1,2,1]

Sample Output (1):

0 3
1
2
4

Sample Input (2):

counts = [4,2,4,5,5,4,4,5,5,2,5,7,1,7,1,7,1,7,1,7,1,7,1,7,5,5,5,5,5]

Sample Output (2):

0 2 5 6
1 9
3 4 7 8 10
11 13 15 17 19 21 23
12
14
16
18
20
22
24 25 26 27 28

Code:

from collections import OrderedDict

def groupCount(counts):
    group_dict = OrderedDict()
    for i in range(len(counts)):
        if counts[i] in group_dict.keys():
            group_dict[counts[i]].append(i)
        else:
            group_dict[counts[i]] = [i]
    op_list = []
    for key in group_dict:
        prnt_count = 0
        temp_list = []
        while len(group_dict[key])!=0:
            prnt_count += 1
            temp_list.append(group_dict[key].pop(0))
            if prnt_count % key == 0:
                op_list.append(temp_list)
                temp_list = []
    op_list.sort(key=lambda x: x[0])
    for value in op_list:
        print(*value, sep=' ')


texts:
I need to make a simple CSV->MySQL script in OOP and I was wondering if there's anything I am doing wrong in a object-oriented sense.

I have a file name db.php where I connect to MySQL via MySQLi and then I have another class where I load a csv file into MySQL like this:

class csv extends Database {

        public $file = null;

   function __construct() {

            if(count($_SERVER["argv"]) > 1){
                $this->file = $_SERVER["argv"][1];
            }else{
                $this->file = "stock.csv";
            }

            $this->db = $db;

        }

        function saveCSVtoDB(){
            //opens the file
            $fp = fopen($this->file, "r");

            $db = Database::getInstance();
            $mysqli = $db->getConnection();

            $result = $mysqli->query("LOAD DATA LOCAL INFILE 'file.csv'
                                           IGNORE INTO TABLE products
                                               CHARACTER SET UTF8
                                        FIELDS TERMINATED BY ','
                                         LINES TERMINATED BY '\n'
                                              IGNORE 1 LINES
                                              (code, name, desc, stock, price, @avai)
                                                         SET available = IF(@avai LIKE '%yes%', 1, 0)
                                               ");

            if($result){
                echo "success";
            }else{
                die("error");
            }

        }
}


texts:
I need to extract file names with their extension from an input text file to a string vector.
The input text file is quite messy and serves as configuration file for some application.

What I know about the file names I am trying to extract is they are preceded by a file = mention, the filename is quoted between ' ' or " ".

Example : file="name.abc". I also have no guarantee of how spacing is : It may be file="name.abc", file = "name.abc" , file= "name.abc"... And extension can be of different lengths.

So I tried the following code:

std::vector<std::string> attachment_names;
std::istringstream words(text_content);
std::string word;
std::string abc_extension(".abc"); // My code should support any extension
while (words >> word)
{
    auto extension_found = word.find(abc_extension);
    if (extension_found != word.npos)
    {
        auto name_start = word.find("'") + 1;
             //I am not even sure the file is quoted by ''

        std::string attachment_name = word.substr(name_start, (extension_found + 3) - name_start + 1);
             //Doing this annoys me a bit... Especially that the extension may be longer than 3 characters

        attachment_names.push_back(attachment_name);
    }
}

Is there a nicer way of doing this? Is there a possibility to rely more on the file caption to support any extension?


texts: Write a definition of a semaphore in terms of test-and-set! operations

texts:
From SICP:

  Exercise 3.47.  A semaphore (of size
  n) is a generalization of a mutex.
  Like a mutex, a semaphore supports
  acquire and release operations, but it
  is more general in that up to n
  processes can acquire it concurrently.
  Additional processes that attempt to
  acquire the semaphore must wait for
  release operations. Give
  implementations of semaphores

  b. in terms of atomic test-and-set!
  operations.

(define (make-semaphore max)
  (let ((count 0)
        (cell (list false)))
    (define (increment)
      (set! count (+ count 1)))
    (define (decrement)
      (set! count (- count 1)))
    (define (has-room?) (> max count))
    (define (the-semaphore m)
      (cond ((eq? m 'acquire)
             (if (has-room?)
                 (increment)
                 (if (test-and-set! cell) (the-semaphore 'acquire))))
            ((eq? m 'release)
             (decrement)
             (if (has-room?) (clear! cell)))))
    the-semaphore))

(define (clear! cell)
  (set-car! cell false))

(define (test-and-set! cell)
  (if (car cell)
      true
      (begin (set-car! cell true)
             false)))

Do you think that this solution is sufficient?  Can it be improved?


texts:
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);

I used a helper function approach after realizing that the "Grid" needs to be updated in the same manner over and over again

I have received feedback that storing a grid may take too much memory

Would a "mathematical" approach actually be more readable? And would it be something that can be though of within 20ish minutes (interview time)

I have many if statements that are used to exit out of loops to avoid array index errors

Any feedback or criticism is appreciated - nitpick on anything that seems off

glaring issue is that this doesn't handle edge cases well. For example: "A 2"

https://leetcode.com/problems/zigzag-conversion/
class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s
        row = [''] * (len(s) // 2)
        self.s = s
        self.numRows = numRows
        self.final_grid = []

        for i in range(numRows):
            self.final_grid.append(list(row))

        self.addElements(0, 0)

        return "".join(map("".join, self.final_grid))

    def addElements(self, count, column):
        print(column, "beg")
        for i in range(self.numRows):
            if count > len(self.s) - 1:
                break
            self.final_grid[i][column] = self.s[count]
            count += 1

        for i in range(1, self.numRows - 1):
            if count > len(self.s) - 1:
                break

            self.final_grid[self.numRows - i - 1][column + i] = self.s[count]
            count += 1
            print(column, "end")
            print(column + self.numRows - 1)

        if count < len(self.s) - 1:
            self.addElements(count, (column + self.numRows - 1))


texts: Python Search file for string and read into list

texts:
This function of my program is searching a file that is formatted as first_name last_name rate hours:

John Smith 25 80
Mary Johnson 15.5 60.0
...

With one space between each item.

The user enters the first name and last name of the employee and while the line is not equal to null it searchs for the employee. If its found then found=True and it gets the rate and hours from that line and breaks out of the loop. Then if found=True, it will print the name of the employee and their gross pay (rate * hours), else it says employee is not found. The code is working in my program but I will be using something very similar later on for adding/modifying/deleting new employee functions.

# 'print_emp', display only a single employee's data chosen by the user displayed as
# firstname, lastname, grosspay (on one line of output)
def print_emp():
    menu_name = ' '*int(OFFSET/2) + "EMPLOYEE LOOKUP"
    dotted = (OFFSET+len(menu_name))*'-'
    found = False

    try:
        file= open('employees.txt')
        line = file.readline()
        name = input('Give me an employee to search for ')
        # run thru while loop & search for employee
        while line != ' ':
            line = line.split(' ') #split into a list
            if name == line[0]+' '+line[1]:
                found = True
                rate = float(line[2])
                hours = float(line[3])
                break
            line = file.readline() # read subsequent records
        # close file
        file.close()
        if found:
            print(name, '$%4.2f' % (rate*hours))
        else:
            print('Employee is not listed')

    except FileNotFoundError:
        print("Error: File not found.")


texts:
I started studying JavaScript about a week ago and I would like some opinions and advice on my code. This program just creates a canvas and instantiates 5 planets that orbit around a sun, giving them each a different speed, color, and size.

It uses the p5.js library, the code can be run in the p5.js web editor. (You might want to expand the preview panel on the right after pasting the code, before you run the script.)

The code is in different files (class Orbiter, extra math functions and main code) but I'll put it here in one go:

// Converts from degrees to radians.
Math.radians = function(degrees) {
    return degrees * Math.PI / 180;
  };

// Converts from radians to degrees.
Math.degrees = function(radians) {
    return radians * 180 / Math.PI;
  };

class Orbiter {

    constructor(rad, orbitAlt, x = 0, y = 0, orbitAngle = 0, orbitAngleMod = 1, colorR=255, colorG=255, colorB=255, colorA=255){
        this.orbitAngle = orbitAngle; // Angle formed by the radius of the orbit and the x plane.
        this.orbitAngleMod = orbitAngleMod; // Increment/decrement of  orbitAngle
        this.rad = rad; // Radius
        this.orbitAlt = orbitAlt; // Distance to the orbited object's position (Alt for altitude)

        // Position
        this.x = x;
        this.y = y;

        // Color variables
        this.colorR = colorR;
        this.colorG = colorG;
        this.colorB = colorB;
        this.colorA = colorA;
    }

    orbit(object){
        this.x = object.x + this.orbitAlt * cos(Math.radians(this.orbitAngle));
        this.y = object.y + this.orbitAlt * sin(Math.radians(this.orbitAngle));
        this.orbitAngle = this.orbitAngle + this.orbitAngleMod;

        // Reset the angle to 0 after a complete revolution to avoid an ever increasing value.
        if(this.orbitAngle >= 360){
            this.orbitAngle = 0;
        }
    }

    display(){
        noStroke();
        fill(this.colorR, this.colorG, this.colorB, this.colorA);
        return ellipse(this.x, this.y, this.rad, this.rad);
    }

}

let planets = [];
let sun = new Orbiter(100, 0);

function setup(){
    createCanvas(windowWidth-3, windowHeight-3);
    frameRate(144);

    // Set up the Sun's colors and coordinates
    sun.colorR = 255;
        sun.colorG = 200;
        sun.colorB = 0;
    sun.x = windowWidth/2;
    sun.y = windowHeight/2;

    // Instantiate 5 planets
    for(i = 0; i < 5; i++){
        planets[i] = new Orbiter(5 + i * 15, 110 + i*70);
        planets[i].orbitAngleMod= 1.4 - i/7;
        planets[i].orbitAngle= i*5;

        planets[i].colorR = i * 50 + 5;
        planets[i].colorG = 255 - planets[i].colorR;
        planets[i].colorB = 255 - planets[i].colorR;
    }
}

function draw(){
    background(0, 10, 40);

    for(planet of planets){
        planet.orbit(sun);
        planet.display();
    sun.display()
    }

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>

I'd be really grateful if you could give me some feedback on the structure of my code, whether it's in line with JavaScript best practices, or in general if there's anything you see in there that you think is just wrong or should be written in a different way.


texts:
This code outputs each tag followed by its attributes in the given HTML, both in lexicographic order. It must be possible to keep the spirit of the code without these many nested cycles and conditionals.

from bs4 import BeautifulSoup

htmlist = ['
',
     '
Print/export
',
     '
',
     '
',
     '
Create a book
',
     '
<a href="/w/index.php?title=Special:Book&amp;bookcmd=render_article&amp;arttitle=Main+Page&amp;oldid=560327612',
     '
Printable version
',
     '
',
     '
',
     '
']

soup = BeautifulSoup("\n".join(htmlist), "html.parser")

tags = sorted(set([tag.name for tag in soup.find_all()]))

for tag in tags:
    tags_keys = list()
    for line in htmlist:
        aux=BeautifulSoup(line, "html.parser").find(tag)
        if aux:
            tags_keys.extend(list(aux.attrs))
    print(tag+":"+",".join(sorted(set(tags_keys))))

I tried something along the lines of what's below (in place of the outermost for), but couldn't even get it to work.

for tag in tags:
    print(tag+":"+",".join(sorted(soup.find(tag).attrs.keys())))

Edit: There was a typo in the code, htmlist was supposed to be as follows.

htmlist = ['
',\
           '
Print/export
',\
           '
',\
           '
',\
           '
Create a book
',\
           '
Download as PDF
',\
           '
Printable version
',\
           '
',\
           '
',\
           '
',\
          ]


texts:
I have two ViewModels with the one referencing the other:

public class GiveViewModel
{
    [Required]
    public int GivenLifelines { get; set; }
    public string ToUser { get; set; }
    public string FromUser { get; set; }
}

 public class UserDetailsViewModel
{
    public GameDetail gameDetail { get; set; }
    public UserDetail userDetail { get; set; }
    public IEnumerable<GameItem> gameItems { get; set; }
    public IEnumerable<UserDetail> allUsers { get; set; }
    //REF
    public GiveViewModel givenLifeLines { get; set; }
}

The main viewmodel is used in the controller to get all the info on the foreign keys for the page. I have IEnumerables to list all users and game items, and references to the main models to get the current users details. This enables users to give points to other users while on their details page (the DetailsController).

Technically I do not use the givenLifeLines on the first load for the view. It is only used during the POST.

I can get the values back from the POST and use it on the [HttpPost] controller
but it seems a bit awkward.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Give(UserDetailsViewModel model)
{
   int givenLifeLines = model.givenLifeLines.GivenLifelines; //got value
   string givenTo = model.givenLifeLines.ToUser; // got value
   ....
}

You see, the current logged in user selects another user based on their image by clicking the selected image:

<img src="~/@item.AppImage.ImagePath" class="img-responsive img-thumbnail user-image" data-username="@item.FirstName" style="width:100px;height:100px;" />

which gets added to a model textbox:

 @Html.TextBoxFor(model => model.givenLifeLines.ToUser, new { @class = "give-to form-control" })

That process is controlled by jQuery:

  $(".user-image").click(function () {
      $(".give-to").val($($(this)).attr('data-username'));
   })

This all works fine. I am getting the values I need in the model for the POST, but I get the feeling that this is not a good idea. Ideally I would want the textbox to be disabled, however, if I do that, the value is then not passed to POST controller model. A dirty work around would be to just display:none on the textbox and still have it enabled but that would feel wrong. I don't feel like I should be required to depend on jQuery like this.

Is there a better way to approach this that is more inline with the practices of model binding?  Should I be separating my ViewModels like I have?


texts: KMP string-matching algorithm implementation

texts:
This is Knuth-Morris-Prat algorithm implementation to check if a pattern is present in a larger text, and if it does the algorithm returns the start index of that pattern, else -1. It starts off by computing Longest Common Prefix array, please refer LCP array, and uses that to efficiently avoid redundant pattern matching. I request that my code be reviewed for implementation and naming conventions. For more context about the question please refer, StrStr()

int knuthMorrisPratt(String text, String pattern) {
    if (text == null || pattern == null || text.length() < pattern.length) {
        return -1;
    }
    if (pattern.length() == 0) {
        return 0;
    }
    int[] lcp = computeLongestCommonPrefixArray(pattern);
    int i = 0, j = 0;
    while (i < text.length() && j != pattern.length()) {
        if (text.charAt(i) == pattern.charAt(j)) {
            j++;
        }
        else {
            if (j > 0) {
                j = lcp[j - 1];
                continue;
            }
        }
        i++;
    }
    return (i - j) <= (text.length() - pattern.length()) ? (i - j) : -1;
}

int[] computeLongestCommonPrefixArray(String pattern) {
    int[] lcp = new int[pattern.length()];
    int len = 0, i = 1;
    while (i < pattern.length()) {
        if (pattern.charAt(i) == pattern.charAt(len)) {
            len++;
            lcp[i] = len;
            i++;
        }
        else {
            if (len != 0) {
                len = lcp[len - 1];
            }
            else {
                lcp[i] = 0;
                i++;
            }
        }
    }
    return lcp;
}


texts:
I have been working on a Bencoded string parser in order to improve my knowledge
of Haskell. After running the code through hlint, I still have a few questions:

As I noted in the comments, the key value in the definition of BMapT should
always be a Bstr. Is there any way to enforce a particular data constructor when
pattern matching an algrebraic datatype?
Since Bencoded dictionaries are generally stored as human readable text, I
made an instance of the Show typeclass so that I could take Bencode structures
and turn them into text. I was wondering if this is the right thing to do, or if
Haskell has another typeclass for storage/serialization a la Python's repr.
This question is kind of nebulous, but would you consider this code
'idiomatic'? Code without style isn't worth writing :)

Code:

-- This is an implementation of Bencoding for bittorrent as described at
-- http://www.bittorrent.org/beps/bep_0003.html

module Bencode where

import Text.Parsec.ByteString
import Text.Parsec.Char
import Text.Parsec.Prim
import Text.Parsec.Combinator
import qualified Text.Parsec.Error as PE
import Data.Char
import qualified Data.Map as M
import qualified Control.Monad as Mon

-- Technically this first argument can only be a Bstr, but I don't know
-- how to express that
type BMapT = M.Map Bencode Bencode

-- I have no idea why Bstr is okay as a String when it's a ByteString
data Bencode =  Bint Integer
              | Bstr String
              | Blist [Bencode]
              | Bmap BMapT
              deriving (Eq, Ord)

instance Show Bencode where
    show (Bint i) = "i" ++ show i ++ "e"
    show (Bstr s) = (show . length) s ++ ":" ++ s
    show (Blist bs) = 'l':concatMap show bs ++ "e"
    show (Bmap bm) = M.foldlWithKey (\a k b -> a ++ show k ++ show b) "d" bm  ++ "e"

-- Parse a Bencoded Integer
bInt :: Parser Bencode
bInt = do char 'i'
          num <- validNum
          char 'e'
          return $ Bint num
       -- This parser parses valid integers in Bencodings
       where validNum = do neg <- option ' ' (char '-')
                           d <- digit
                           case digitToInt d of
                                -- Only time the first digit == 0 is "i0e"
                                0 -> if neg == ' ' then
                                        -- "i0e" allowed but NOT "i-0e" or zero padded integer
                                        lookAhead (char 'e') >> return 0
                                     else
                                        parserFail "Can't have a negative zero"
                                _ -> many digit >>= \xs -> return $ read (neg:d:xs)

-- Parse a Bencoded String
bString :: Parser Bencode
bString = do ss <- many1 digit
             char ':'
             let size = read ss
             Mon.liftM Bstr $ count size anyChar

bList :: Parser Bencode
bList = do char 'l'
           ls <- many (bInt <|> bString <|> bList <|> bMap)
           char 'e'
           return $ Blist ls

-- A parser which parses bencoded dictionaries
bMap :: Parser Bencode
bMap = do char 'd'
          entries <- many dictEntry
          char 'e'
          return $ Bmap $ M.fromList entries

-- This parser will parse a key-value pair
dictEntry :: Parser (Bencode, Bencode)
dictEntry = do key <- bString
               value <- bString <|> bList <|> bInt <|> bMap
               return (key, value)

-- This function reads a torrent file. readBencodedFile "filename" reads
-- that filename and returns the parsed bencoded dictionary
readBencodedFile :: String -> IO (Either PE.ParseError Bencode)
readBencodedFile = parseFromFile bMap


texts:
Is there any simple way to detect user keystrokes that result in character input? In other words, ignore all soft keys and modifier keys? This works but seems sort of hacky:

var keycode = event.keyCode ? event.keyCode : event.charCode
if((keycode>=48 && keycode<=90) || (keycode>=96 && keycode<=111) || (keycode>=186 && keycode<=192) || (keycode>=219 && keycode<=222)){
    alert("realkey")
}


texts: Python nested json parsing and splitting the values

texts:
I am trying to split and assign the url's to the variable, I am getting the desired result but I know there is a way where I can improvise the current code.

JSON FILE

{
"Result": [
"Url::Link::Url1",
"Url::Link::Url2",
"Url::Link::Url3",
"Url::Link::Url4",
"Url::Link::Url5",
"Url::Link::Url6",
"Url::Link::Url7"
],
"Record": [
"Record::Label::Music1",
"Record::Label::Music2",
"Record::Label::Music3"
],
}

import requests
import json

url = "http:mywebsite.com"

headers = {
    'User-Agent': "PostmanRuntime/7.15.2",
    'Accept': "*/*",
    'Cache-Control': "no-cache"
    }

result= requests.get("GET", url, headers=headers).json()
url1 = []
url2 = []
url3 = []

for i in result['Result'][0:1]:
    url1.append(i.split('::')[2])

for i in result['Result'][1:2]:
    url1.append(i.split('::')[2])

for i in result['Result'][2:3]:
    url1.append(i.split('::')[2])

Output
url1=Url1
url2=Url2
...


texts: Rails service for a series of calculations

texts:
I'm writing a Rails service in which a series of operations are performed on a record:

class RecordBaseAmountService

   self.build
      new
   end

   def call(record, subrecord)
      record = calculate_base_amount(record, subrecord)
      record = adjust_base_amount(record, subrecord)
      record = pro_rate_record(record, subrecord) if subrecord.is_prorated?

      return record
   end

   private

   def calculate_base_amount(record, subrecord)
      if subrecord.type == 0
         base_amount = 10
      elsif subrecord.type == 1
         base_amount = 20
      else
         base_amount = 30
      end

      record.base_amount = base_amount
      record.audit_field += "=>base amount calculated"
      record
   end

   def adjust_base_amount(record, subrecord)
      record.base_amount = record.base_amount*30
      record.audit_field += "=>base amount adjusted"
      record
   end

   def pro_rate_record(record, subrecord)
      record.pro_rated_amount = record.base_amount*subrecord.pro_rate
      record.base_amount = record.base_amount - record.pro_rated_amount
      record.audit_field += "=>prorated"
      record
   end
end

The Record and Subrecord classes are basic Activerecord classes with validations, scopes, callbacks, and associations. Basically almost all of my business logic is farmed out to services and my models only deal with data integrity.

class Record < ActiveRecord::Base
    has_many :subrecords
    validates :base_amount, presence: true
    around_update :cache_in_subrecord

    private

    def cache_in_subrecord
        subrecord = self.subrecord
        self.audit_field += "=>subrecord cached " + Time.now.utc.to_date.to_s
        subrecord.cached_attribute_field = (subrecord.cached_attribute_field || {}).merge(get_cached_attributes)

        yield

        subrecord.save
    end

    def get_cached_attributes
        {
          record_id: self.id,
          base_amount: self.base_amount,
          audit_field: self.audit_field,
          time: Time.now.utc.to_date
        }
    end
end

class Subrecord < ActiveRecord::Base
    belongs_to :record
    validates :type, presence: true
    validates :start_date, presence: true
    validates :pro_rate, presence: true

    def is_prorated?
       same_month? && not_first_day?
    end

    def same_month?
       self.start_date.month == Date.today.month
    end

    def not_first_day?
       self.start_date.day > 1
    end
end

and the service is called from multiple places including controllers and rake tasks. In one particular rake task I call the service above with the Celluloid gem.

require "celluloid"

class MonthlyRecordWorker
  include Celluloid

  def update_record(record)
     updated_record = RecordBaseAmountService.build.call(record, record.subrecord)
     updated_record.save
  end

end

class MonthlyTaskService

    def call
        record_pool = MonthlyRecordWorker.pool(size: 10)

        Record.all.each do |i|
           record_pool.async.update_record(i)
        end
    end

end

#lib/tasks/monthly.rake

namespace :monthly do
    desc "Cron tasks"
    task :audit_records => :environment do
        MonthlyTaskService.build.call
    end
end

I'm highly concerned about thread safety, which I have no experience with. Is this code thread safe? Any comments on any improvements to be made?


texts: Prim's algorithm for minimal spanning trees

texts:
I want to write an article giving a Haskell introduction specifically to Java developers, and would like to get feedback on my implementation. Please keep in mind that I don't want to be "too clever", as too advanced Haskell concepts would only confuse the readers. On the other hand I need to show some really interesting features (e.g. that's why I decided to use Edge a a Double and a type class instance instead of a simple (String, String, Double)), else the readers would ask "And where is the advantage over Java?". So I need a good balance between clarity and "interesting stuff", showing a nice example of Haskell's expressiveness.

module Prim (
   prim,
   Edge(..)
) where

import Data.List(sort, deleteBy)
import Data.Set(member, empty, insert, singleton, Set)

data Edge a = Edge a a Double deriving (Eq, Show)

instance Ord a => Ord (Edge a) where
   compare (Edge a b c) (Edge d e f) =
      (c, min a b, max a b) `compare` (f, min d e, max d e)

prim [] = []
prim edges = loop (sort edges) [] startSet where
   startSet = singleton (startNode edges)
   startNode ((Edge node _ _):_) = node

loop [] solution _ = solution
loop edges solution vertices =
   let (e,x) = findNextEdge edges vertices
       vertices' = x `insert` vertices
       cyclicEdge (Edge a b _) = a `member` vertices' &&
                                 b `member` vertices'
       edges' = filter (not.cyclicEdge) edges
   in loop edges' (e:solution) vertices'

findNextEdge [] vs = error ("Disjunct graph with island " ++ show vs)
findNextEdge (e@(Edge a b _):edges) vertices
    | a `member` vertices = (e,b)
    | b `member` vertices = (e,a)
    | otherwise = findNextEdge edges vertices

In particular, I'm interested in these concepts:

Type inference
Laziness, immutability
Currying
Pattern matching, guards
ADTs and type polymorphism