texts: Sum of Even Fibonacci numbers in functional programming

texts:
I want to solve this problem in functional programming (fp) way only.

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

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

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

Source: https://projecteuler.net/problem=2

This is my fp approach:

const range = num => Array.from(new Array(num), (_, i) => i);
const divisibleBy = divisor => num => num % divisor === 0;
const isEven = i => divisibleBy(2)(i);
const sum = (acc, val) => acc + val;
const fibonacciOf = n => {
    if (n === 0) {
        return 1;
    }
    if (n === 1) {
        return 2;
    }
    return fibonacciOf(n - 1) + fibonacciOf(n - 2);
};
const doUntil = maxVal => (fiboResult, i) => {
    const next = i + 1;
    return fiboResult >= maxVal ? i : doUntil(maxVal)(fibonacciOf(next), next);
};
const until4Mil = doUntil(4000000);
const maxRange = until4Mil(0, 0);

const solution = range(maxRange)
    .map(fibonacciOf)
    .filter(isEven)
    .reduce(sum);

console.log("solution ", solution);

1) I was struggling with the recursion, because that was the only way I could think of how to emulate the do...while loop. Do you know any alternative to the do...while loop (aka. a loop where you don't know when it ends) in fp?

2) Also, I'm not sure whether the part const maxRange = until4Mil(0, 0); is clean code or not.

Any other improvement suggestions are welcomed as well.


texts:
Basically, I made a function which switches between stages (see the Switch class below).

The way I call it is seen in the Controller below. I wanted to ask if this code  (in the Switch class) is good practice or not.

Login class:

public class Login extends Application{
    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Login.fxml"));

        Scene scene = new Scene(root, 600, 500);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Login");
        primaryStage.setResizable(false);
        primaryStage.sizeToScene();
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

FXML:

<BorderPane
        fx:controller="client.controller.LoginController"
        xmlns:fx="http://javafx.com/fxml">
    <center>
        <GridPane alignment="CENTER" hgap="10" vgap="8">
            <Button fx:id="registerButton" onAction="#goToRegister"
                    text="Register" defaultButton="true"
                    GridPane.columnIndex="0" GridPane.rowIndex="0"/>
        </GridPane>
    </center>
</BorderPane>

Controller:

public class LoginController {
    public Button registerButton;

    public void goToRegister(ActionEvent actionEvent) {
        Switcher.switchWindow((Stage)registerButton.getScene().getWindow(), new Temp());
    }
}

Switch class:

public static void switchWindow(Stage window, Application app) {
    try {
        app.start(window);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Temp Class:

public class Temp extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/temp.fxml"));

        Scene scene = new Scene(root, 600, 500);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Temp");
        primaryStage.setResizable(false);
        primaryStage.sizeToScene();
        primaryStage.show();
    }
}


texts: FIFO queue for a 2D array in ANSI C, version 2

texts:
This is a modification of my previous version.
I would like advice on improving a FIFO algorithm for a 2D array that I've developed in ANSI C.
I have written code that uses this algorithm for test purposes. Random numbers are put into an array until all elements are full. The program then asks the user what numbers need to go in to the 2D array in order to update it. The code then removes the oldest array, shifts all remaining arrays up by one, and then adds the new array (as input by the user).
I am asking for a review of the FIFO code, fifo_algorithm; the surrounding code is only for testing purposes. I would appreciate any suggestions that only use standard C.
code:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

void random_num_input(void);
void print_random_num_input(void);
void print_new_array(void);
void fifo_algorithm(void);

int user_num[5] = { 0 };
uint16_t big_array[10][5] = { 0 };
uint16_t big_array_copy[10][5] = { 0 };
uint16_t array_print[1] = { 0 };
uint8_t count = 0;
int main()
{
    random_num_input();
    printf("These are the original numbers in the big array:\n");
    print_random_num_input();
    while (count < 10)
    {
        printf("Please enter values to swap in:\n");
        for (int i = 0; i < 5; i++)
        {
            scanf("%d", &user_num[i]);
        }
           printf("\n\n");
           fifo_algorithm();
        count++;
    }
}
//stores random numbers between 0-255 into big_array and big_array_copy
void random_num_input(void)
{
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 5; i++)
        {
            big_array[j][i] = rand() % 255;
        }
    }

}
//prints the random values within the big_array
void print_random_num_input(void)
{
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 5; i++)
        {
            array_print[0] = big_array[j][i];
            printf("%d,", array_print[0]);
        }
        printf("\n");
    }
}
//This algorithm removes the oldest array in big_array_copy (element 9), shifts every
//element up by 1 and stores the user inputted array into element 0. Thus a fifo that updates
//the 2d array with the user input values every time
void fifo_algorithm(void)
{
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 5; i++)
        {
            big_array_copy[j][i] = big_array[j][i];
        }
    }
    for (int k = 0; k < 5; k++)
    {
        big_array_copy[10 - 1][k] = 0;
    }
    for (int j = 9; j > 0; j--)
    {
        for (int i = 0; i < 5; i++)
        {
            big_array_copy[j][i] = big_array[j - 1][i];
        }
    }
    for (int i = 0; i < 5; i++)
    {
        big_array_copy[0][i] = user_num[i];
    }
    print_new_array();
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 5; i++)
        {
            big_array[j][i] = big_array_copy[j][i];
        }
    }
}
//simply prints the new, updated values in big_array_copy
void print_new_array(void)
{
    printf("These array values have been swapped:\n ");
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 5; i++)
        {
            array_print[0] = big_array_copy[j][i];
            printf("%d,", array_print[0]);
        }
        printf("\n");
    }
}

Thanks


texts:
I know that there are combinatoric libraries for this kind of thing. However, with me being new to C# and coding in general I found that I couldn't understand the code well enough to implement it in my solution.

Here is the challenge:

  Given two integers: L and R,

  find the maximal values of A xor B given, L ≤ A ≤ B ≤ R

  Input Format  The input contains two lines, L is present in the first line.  R in the second line.

  Constraints  1 ≤ L ≤ R ≤ 103

  Output Format  The maximal value as mentioned in the problem statement.

  Sample Input#00

 1
 10

  Sample Output#00

15

  Sample Input#01

10
15

  Sample Output#01

7

   Explanation for the second example is as follows:

  In the second sample let's say L=10, R=15, then all pairs
  which comply to above condition are

  10⊕10=0   10⊕11=1  10⊕12=6  10⊕13=7  10⊕14=4  10⊕15=5  11⊕11=0  11⊕12=7  11⊕13=6  11⊕14=5
  11⊕15=4  12⊕12=0  12⊕13=1  12⊕14=2  12⊕15=3
  13⊕13=0  13⊕14=3  13⊕15=2  14⊕14=0  14⊕15=1
  15⊕15=0

  Here two pairs (10,13) and (11,12) have maximum xor value 7 and this
  is the answer.

The code below represents my solution to the problem in question. It works but I feel like I reinvented the wheel on this one. Is there a better way of going about it than what I have?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {

    public static List<int[]> Combinations( List<int> number_list )
    {

        // We are only choosing 2 values out of any list of numbers
        int[] TwoList = new int[2];

        List<int[]> result = new List<int[]>();

        List<int> stack = new List<int>(number_list);

        while (stack.Count > 0)
        {

            int StackLast = stack.Count - 1;

            for (int i =0; i < stack.Count; i++)
            {
                TwoList[0] = stack[StackLast];

                TwoList[1] = stack[i];

                result.Add(new int[] {TwoList[0], TwoList[1]});
            }
            stack.RemoveAt(StackLast);
        }

        return result;

    }

    static int MaxXor(int l, int r)
    {

        List<int> NumList = new List<int>(Enumerable.Range(l, r - l + 1));

        // Inserts the list combinations as int arrays
        List<int[]> comboList = Combinations(NumList);

        int max = 0;

        foreach(var two in comboList)
        {

            int XorValue = two[0] ^ two[1];

            max = ( max > XorValue )? max : XorValue;
        }

        return max;
    }

    static void Main(String[] args)
    {

        int _l;
        int _r;

        _l = Convert.ToInt32(Console.ReadLine());

        _r = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine(MaxXor(_l, _r));
    }
}


texts: Rock Paper Scissors Beginner Python Game

texts:
I recently made this game for rock, paper, scissors in Python 3. Everything works as intended, but I am sure this is not an optimal way of accomplishing this task. Wondering if there is any beginner friendly advice on how to improve upon this. Thank you!

def main():
    import random
    game_active = True
    options = ['Rock', 'Paper', 'Scissors']
    print("\nWelcome to Rock, Paper, Scissors!\n\nPlease choose one:\nR for Rock\nP for Paper\nS for Scissors\n")
    choice = input("Enter your choice: ")
    cpu_choice = random.choice(options)
    if choice != 'R' or 'P' or 'S':
        print("Invalid choice!")
    elif choice == 'R' or 'P' or 'S':
        if choice == 'R':
            choice = "Rock"
        elif choice == 'P':
            choice = "Paper"
        elif choice == 'S':
            choice = "Scissors"

    while choice != cpu_choice:
        if choice == "Rock":
            if cpu_choice == "Paper":
               print("\nYou chose rock and the computer chose paper.\nYou lose!")
            elif cpu_choice == "Scissors":
                print("\nYou chose rock and the computer chose scissors.\nYou win!")
        elif choice == "Paper":
            if cpu_choice == "Rock":
                print("\nYou chose paper and the computer chose rock. \nYou win!")
            elif cpu_choice == "Scissors":
                print("\nYou chose paper and the computer chose scissors. \nYou lose!")
        elif choice == "Scissors":
            if cpu_choice == "Rock":
                print("\nYou chose scissors and the computer chose rock. \nYou lose!")
            elif cpu_choice == "Paper":
                print("\nYou chose scissors and the computer chose paper. \nYou win!")
        break
    while cpu_choice == choice:
        print("You chose", choice + "!")
        print("Computer chooses", cpu_choice + "!")
        break
    cont = input("Play again? (Y/N): ")
    if cont == 'Y':
        main()
    else:
        print("Thank you for playing!")
main()

(This is also my first time using a function)


texts: Hackerrank All Women's Codesprint 2019: Visually Balanced Sections

texts:
Link: https://www.hackerrank.com/contests/hackerrank-all-womens-codesprint-2019/challenges/visually-balanced-sections/problem

Problem Description

  A rack has \$n\$ horizontal compartments. The leftmost compartment is the \$1^{st}\$ compartment and the rightmost compartment is the \$n^{th}\$ compartment. Each of the compartments of a rack has a colorful item. A section of a rack consists of one or more consecutive compartments.

  A section (\$i^{th}\$ compartment to \$j^{th}\$ compartment where, \$i \le j\$) of a rack is visually balanced if the items within the section can be re-arranged in such a way that the color sequence of the items from the \$i^{th}\$ compartment to the \$j^{th}\$ compartment is same as the color sequence of the items from the \$j^{th}\$ compartment to the \$i^{th}\$ compartment.

  Few examples of visually balanced sections are:

  Note that, in the third example, the items in this section can be re-arranged in such a way that the color sequence of the items from the \$1^{st}\$ compartment of this section to the compartment of this section will be same as the color sequence of the items from the compartment of this section to the \$1^{st}\$ compartment of this section.

  Given the colors of each of the \$n\$ items of a rack, your task is to determine the number of visually balanced sections of a rack.

  Function Description

  Complete the visuallyBalancedSections function in the editor below. It should return an integer denoting the number of visually balanced sections of a rack..

  visuallyBalancedSections has the following parameter(s):

  colors: an integer array representing the colors of item in each compartment

  Input Format

  The first line contains a single integer \$t\$ denoting the number of scenarios.
  The first line of each scenario contains a single integer \$n\$ denoting the number of compartments of a rack.
  Each of the next line \$i\$ of the \$n\$ subsequent lines (where \$1 \le i \le n\$) of a scenario contains an integer \$color\$ denoting the color of the item in the \$i^{th}\$ compartment.

  Constraints

  \$1 \le t \le 100\$
  \$1 \le n \le 1000\$
  \$1 \le color \le 50\$

  Output Format

  For each scenario, print an integer denoting the number of visually balanced sections of a rack.

  Sample Input 0

1
4
1
2
1
2

  Sample Output 0

7

  Explanation 0

  There is only one scenario where the rack has four compartments.

  The \$1^{st}\$ compartment has an item of \$= 1\$.
  The \$2^{nd}\$ compartment has an item of \$= 2\$.
  The \$3^{rd}\$ compartment has an item of \$= 1\$.
  The \$4^{th}\$ compartment has an item of \$= 2\$.

  The visually balanced sections are:

  {\$\{1\}\$} - compartment 1
  {\$\{2\}\$} - compartment 2
  {\$\{1\}\$} - compartment 3
  {\$\{2\}\$} - compartment 4
  {\$\{1, 2, 1\}\$} - compartments 1, 2 and 3
  {\$\{2, 1, 2\}\$} - compartments 2, 3 and 4
  {\$\{1, 2, 1, 2\}\$} - compartments 1, 2, 3 and 4

This current solution times out. I have an idea for a faster solution with memoisation, but I'm still working on it so I decided to submit this for review in the interim.

Current Solution

from collections import defaultdict
from copy import copy

def is_palindrome(counter):
    return len(list(filter(lambda x: x%2, counter.values()))) == (1 if sum(counter.values()) % 2 else 0)

def visuallyBalancedSections(colours):
    counter = defaultdict(lambda: 0)
    total = 0
    for i, val in enumerate(colours):
        counter[val] += 1
        temp_counter = copy(counter)
        for j in range(i+1):
            total += int(is_palindrome(temp_counter))
            temp_counter[colours[j]] -= 1
    return total


texts: code review for count then sort problems (go lang)

texts:
the question is simple, for a input [apple, banana, orange, apple, banana, apple], the program will count it as a map: {apple : 3, orange: 1, banana: 2}, then sort this map by it's values, get [(apple, 3), (banana, 2), (orange, 1)]
below is my go version, I'm a go newbie, could you please review it and lecture me how to polish the code? I add a python version for reference

package main

//input, a url.log file, like "apple\nbanana\norange\napple\nbanana\napple\n"
//output, a output.txt file, should be "apple: 3\nbanana: 2\norange: 1\n"
import (
    "fmt"
    "bufio"
    "os"
    "sort"
    "strings"
    "io"
)

func main() {
    m := make(map[string]int)

    // read file line by line
    filename := "url.log"
    f, err := os.Open(filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    r := bufio.NewReader(f)
    for line, err := r.ReadString('\n'); err == nil; {
        url := strings.TrimRight(line, "\n")
        m[url] += 1  // build the map
        line, err = r.ReadString('\n')
    }

    if err != nil {
        fmt.Println(err)
        return
    }

    //sort the map by it's value
    vs := NewValSorter(m)
    vs.Sort()

    // output
    f_out, _ := os.Create("output.go.txt")
    defer f_out.Close()
    var line string
    for i, k := range vs.Keys {
        line = fmt.Sprintf("%s: %d\n", k, vs.Vals[i])
        io.WriteString(f_out, line)
    }

}

type ValSorter struct {
    Keys []string
    Vals []int
}

func NewValSorter(m map[string]int) *ValSorter {
    vs := &ValSorter {
        Keys: make([]string, 0, len(m)),
        Vals: make([]int, 0, len(m)),
    }
    for k, v := range m {
        vs.Keys = append(vs.Keys, k)
        vs.Vals = append(vs.Vals, v)
    }
    return vs
}

func (vs *ValSorter) Sort() {
    sort.Sort(vs)
}

func (vs *ValSorter) Len() int {
    return len(vs.Vals)
}

func (vs *ValSorter) Less(i, j int) bool {
    return vs.Vals[i] > vs.Vals[j]
}

func (vs *ValSorter) Swap(i, j int) {
    vs.Vals[i], vs.Vals[j] = vs.Vals[j], vs.Vals[i]
    vs.Keys[i], vs.Keys[j] = vs.Keys[j], vs.Keys[i]
}

python version:

from collections import Counter

def main():
    count = Counter()
    with open("url.log", "rb") as f:
        for line in f:
            url = line.rstrip()
            count[url] += 1
    with open("output.py.txt", "wb") as f:
        for key, value in count.most_common():
            f.write("%s: %d\n" %(key, value))

if __name__ == "__main__":
    main()


texts:
Below is the code for user recommendations using mahout.

DataModel dm = new FileDataModel(new File(inputFile));
UserSimilarity sim = new LogLikelihoodSimilarity(dm);
UserNeighborhood neighborhood = new NearestNUserNeighborhood(100, sim,
        dm);
GenericUserBasedRecommender recommender = new GenericUserBasedRecommender(
        dm, neighborhood, sim);

After the recommendations are generated, I am trying to write it to a file like this:

FileWriter writer = new FileWriter(outputFile);
for (LongPrimitiveIterator userIterator = dm.getItemIDs(); userIterator.hasNext();) {
long user = (long) userIterator.next();
List<RecommendedItem> recs = recommender.recommend(user, numOfRec );
    for (RecommendedItem item : recs) {
        writer.write(user + "," + item.getItemID() + ","
                + item.getValue()+"\n");
    }
}
writer.close();

This code to write to file is taking lot of time. How can I speed up the write operations?

I tried with BufferedWriter, but was unable to gain speed-up.


texts: Anything I'm missing on this delegate implementation?

texts:
Just as the question states and to be sure, am I missing anything on this? Something important/obvious that I overlooked? As is, I can save any functor, function pointer and member function pointer using this delegate class (copy ctor and assignment operator left out for brevity, as were the versions with parameters).

template<class Type>
void Deleter(void* object){
    Type* obj_ptr = static_cast<Type*>(object);
    delete obj_ptr;
}

template<class Functor>
struct DelegateHelper{
    typedef typename Functor::result_type result_type;

    DelegateHelper(Functor func)
        : func_(func)
    {}

    result_type operator()(){
        return func_();
    }

    Functor func_;
};

template<class Obj, class R>
struct DelegateHelper<R (Obj::*)()>{
    typedef R (Obj::*FuncPtr)();

    DelegateHelper(Obj* obj_ptr, FuncPtr func)
        : object_(obj_ptr)
        , func_(func)
    {}

    R operator()(){
        return (object_->*func_)();
    }

    Obj* object_;
    FuncPtr func_;
};

template<class R>
struct DelegateHelper<R (*)()>{
    typedef R (*FuncPtr)();

    DelegateHelper(FuncPtr func)
        : func_(func)
    {}

    R operator()(){
        return (*func_)();
    }

    FuncPtr func_;
};

template<class Sig>
struct Delegate;

template<class R>
struct Delegate<R ()>{
    typedef R (*SinkPtr)(void*);

    Delegate()
        : object_(0)
        , func_(0)
        , deleter_(0)
    {}

    template<class F>
    Delegate(F func)
        : object_(new DelegateHelper<F>(func))
        , func_(&Sink<DelegateHelper<F> >)
        , deleter_(&Deleter<DelegateHelper<F> >)
    {}

    template<class C, class F>
    Delegate(C* obj, F func)
        : object_(new DelegateHelper<F>(obj, func))
        , func_(&Sink<DelegateHelper<F> >)
        , deleter_(&Deleter<DelegateHelper<F> >)
    {}

    ~Delegate(){
        if(deleter_)
            (*deleter_)(object_);
    }

    R operator()(){
        return (*func_)(object_);
    }

    template<class Type>
    static R Sink(void* obj_ptr){
        Type* object = (Type*)obj_ptr;
        return (*object)();
    }

    typedef void (*DeleteFunc)(void*);

    void* object_;
    SinkPtr func_;
    DeleteFunc deleter_;
};

For the delegate in effect, see here on Ideone.


texts: Converting bytes to an escaped hexadecimal string

texts:
I wrote this function to convert an array of bytes to a C/C++ string representation using hexadecimal escape codes (\xhh). Any suggestions are welcome:

std::string toEscapedHexaString(const std::uint8_t * data, const int dataSizeBytes,
                                const int maxCols = 80, const int padding = 0)
{
    assert(data != nullptr);
    assert((maxCols % 4) == 0);
    assert((padding % 2) == 0);

    int column = 0;
    char hexaStr[64] = {'\0'};

    std::string result = "\"";
    for (int i = 0; i < dataSizeBytes; ++i, ++data)
    {
        std::snprintf(hexaStr, sizeof(hexaStr), "\\x%02X", static_cast<unsigned>(*data));
        result += hexaStr;
        column += 4;

        if (column >= maxCols)
        {
            if (i != (dataSizeBytes - 1)) // If not the last iteration
            {
                result += "\"\n\"";
            }
            column = 0;
        }
    }

    // Add zero padding at the end to ensure the data size
    // is evenly divisible by the given padding value.
    if (padding > 0)
    {
        for (int i = dataSizeBytes; (i % padding) != 0; ++i)
        {
            result += "\\x00";
            column += 4;

            if (column >= maxCols)
            {
                if ((i + 1) % padding) // If not the last iteration
                {
                    result += "\"\n\"";
                }
                column = 0;
            }
        }
    }

    result += "\"";
    return result;
}

You can control the number of columns in the output, so for example, converting Hello World!\0 with 20 columns max (not counting the quotes):

const unsigned char str[] = "Hello World!";
auto result = toEscapedHexaString(str, sizeof(str), 20);

/* result =
   "\x48\x65\x6C\x6C\x6F"
   "\x20\x57\x6F\x72\x6C"
   "\x64\x21\x00"
*/


texts: Short Ruby program that opens a random video file from a directory

texts:
I am currently learning to code in ruby. I have created a small program that iterates through a directory of video files and opens one at random. The program is fully functioning (with the odd issue). The aim of my question is to hopefully gain some insight into how I can better structure the code, or simplify the process - I think this will really aid me in my learning!

The random selection method I have created, creates 2 random numbers and converts them to a string:

def random_num_generator
  first_num = rand(2..9) #NOTE: generates a random number that is firt name and last name. s
  second_num = rand(1..25)
  second_num < 10 ? "0#{first_num}0#{second_num}" : "0#{first_num}#{second_num}"
  #this returns value that, for example is 0101, relative to whether or not there is a requirement for the additional "0"
  #value is equal to a string
end

The second part of the program iterates through the directory where the video files are stored. As all the file names are written as "0101.mkv" for example, the iteration will then stop and open a file if it is equal to the number generated in the "random_num_generator" method.

 def episode_picker
  Dir.foreach("/GitHub/videos") do |x|
    next if x == "." or x == ".."
    if x == "#{random_num_generator}.mkv"
      system %{open "/GitHub/videos/#{x}"}
    elsif x == "#{random_num_generator}.mp4"
      puts "You are watching Season: #{x[0..1]} Episode: #{x[2..3]}!"
      system %{open "/GitHub/videos/#{x}"}
    elsif x == "#{random_num_generator}.avi"
      puts "You are watching Season: #{x[0..1]} Episode: #{x[2..3]}!"
      system %{open "/GitHub/videos/#{x}"}

    end
  end
end

Any advice is greatly appreciated and a big thanks in advance!


texts:
Working on Functionally Solving Problems from Learn You a Haskell, I worked on the "Heahtrow to London" shortest path problem.

I'm working on a reduced set of this problem in order to solve a simple problem first.

It's a shortest path problem for the following map:

The rule is: you start a A or B, and then choose across the bridge or up/down. When you reach E or F (doesn't matter), you're done.

I used a Node data structure (compliments of LYAH's previous chapter) to recurse through the shorter left or right sides. Ultimately, I return a tuple of (collective cost, list of nodes traversed).

Please critique my implementation:

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

shortestPath2 :: Tree (Int, Char) -> (Int, [Char])
shortestPath2 EmptyTree = (0, [])
shortestPath2 (Node (c, pt) EmptyTree EmptyTree) = (c + fst (shortestPath2 EmptyTree), pt : snd (shortestPath2 EmptyTree))
shortestPath2 (Node (c, pt) EmptyTree right)     = (c + fst (shortestPath2 right), pt : snd (shortestPath2 right))
shortestPath2 (Node (c, pt) left EmptyTree)      = (c + fst (shortestPath2 left), pt : snd (shortestPath2 left))
shortestPath2 (Node (c, pt) left@(Node (lcost, _) _ _) right@(Node (rcost, _) _ _)) =
                                 (c + fst (shortestPath2 next), pt : snd (shortestPath2 next))
                                       where next = if lcost < rcost then left else right

test3 :: (Int, String)
test3 = result
        where path1 = (Node (50, 'A') (Node (30, 'C') (Node (90, 'D') (Node (0, 'E') EmptyTree EmptyTree) EmptyTree) EmptyTree)
                                     (Node (5, 'C') (Node (0, 'E') EmptyTree EmptyTree) EmptyTree))

              path2 = (Node (10, 'B') (Node (30, 'D') (Node (5, 'C') (Node (0, 'E') EmptyTree EmptyTree) EmptyTree) EmptyTree)
                                      (Node (90, 'D') (Node (0, 'F') EmptyTree EmptyTree) EmptyTree))

              sp1 = shortestPath2 path1
              sp2 = shortestPath2 path2
              compare first@(cost1, _) second@(cost2, _) = if cost1 < cost2 then first else second
              result = compare sp1 sp2

Output

ghci> test3
(45,"BDCE")


texts: Perform basic string compression using the counts of repeated characters

texts:
I managed to implement this question from Cracking the Coding Interview:

  Implement a method to perform basic string compression using the counts
  of repeated characters. For example, the string aabcccccaaa would become
  a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.

Can anyone offer feedback on my code?

public static String countRepeatedChars(String str){
    int initialLength = str.length();
    char[] chars = str.toCharArray();
    int occurances = 0;
    String compressedString = "";
    char currentChar = chars[0];

    for(int i = 0; i < initialLength; i++){
        char c  = chars[i];
        if(currentChar == c && i + 1 <= initialLength){
            occurances++;
        }

        else if (currentChar != c || i + 1  > initialLength){

            compressedString += currentChar + String.valueOf(occurances);
            currentChar = chars[i];
            occurances = 1;
        }

        if(i + 1 >=  initialLength){
            compressedString += currentChar + String.valueOf(occurances);

        }
    }
    if(compressedString.length() < initialLength){
         return compressedString;
    }
    return str;
}


texts: Finding alternating sequence in a list of numbers

texts:
Please be brutal and treat this as me coding this up for an interview.

A sequence of numbers is called a zig-zag sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a zig-zag sequence.

For example, 1,7,4,9,2,5 is a zig-zag sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, 1,4,7,2,5 and 1,7,4,5,5 are not zig-zag sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, sequence, return the length of the longest subsequence of sequence that is a zig-zag sequence. A subsequence is obtained by deleting some number of elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.

More examples:

{ 1, 7, 4, 9, 2, 5 }

Returns: 6

The entire sequence is a zig-zag sequence.
{ 1, 17, 5, 10, 13, 15, 10, 5, 16, 8 }

Returns: 7

There are several subsequences that achieve this length. One is 1,17,10,13,10,16,8.
{ 44 }

Returns: 1
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }

Returns: 2
{ 70, 55, 13, 2, 99, 2, 80, 80, 80, 80, 100, 19, 7, 5, 5, 5, 1000, 32, 32 }

Returns: 8
{ 374, 40, 854, 203, 203, 156, 362, 279, 812, 955, 600, 947, 978, 46, 100, 953, 670, 862, 568, 188, 67, 669, 810, 704, 52, 861, 49, 640, 370, 908, 477, 245, 413, 109, 659, 401, 483, 308, 609, 120, 249, 22, 176, 279, 23, 22, 617, 462, 459, 244 }

Returns: 36

Worst case: \$O(n^2)\$
Space Complexity: \$O(n)\$

private static int longestAlternatingSequence(int[] values){
        if(values.length == 1){
            return 1;
        }
        int[] difference = new int[values.length-1];
        for(int i = 1; i < values.length; i++){
            difference[i-1] = values[i] - values[i-1];
        }
        int[] calculationsCache = new int[difference.length];
        calculationsCache[0] = 1;
        int max = Integer.MIN_VALUE;
        for(int i = 1; i < difference.length; i++){
            if(difference[i] > 0){
                for(int j = 0; j < i; j++){
                    if(difference[j] < 0){
                        max = Math.max(max, calculationsCache[j]);
                    }
                }
            }else if(difference[i] < 0){
                    for(int j = 0; j < i; j++){
                        if(difference[j] > 0){
                            max = Math.max(max, calculationsCache[j]);
                        }
                    }
             }else{
                   max = 0;
            }
            calculationsCache[i] = max + 1;
         }
        max = Integer.MIN_VALUE;

        for(int value : calculationsCache){
            max = Math.max(max, value);
        }
        return max + 1;
     }


texts:
I've created this very small header that allows direct creation of threads from lambdas.
I can't find anything else similar on the net so I want to know whether there are any problems with this that I have not thought of. It is based on tinythread++, but can easily be altered to work with pthread or other threading libraries that can take a void (void*) (or void* (void*)) function and a void* argument for the function to start a thread. Note that this implementation is assuming limited C++0x/11 support, i.e. just lambdas.

#include "tinythread.h"

namespace lthread {
    /// implementation details - do not use directly
    namespace impl {
        template<typename Func>
        void use_function_once(void* _f) {
            const Func* f = (const Func*)_f;
            (*f)();
            delete f; // delete - no longer needed
        }
        template<typename Func>
        void use_function(void* _f) {
            const Func* f = (const Func*)_f;
            (*f)();
        }
    }

    /// Creates a thread based on a temporary function.
    /// Copies the function onto the heap for use outside of the local scope, removes from the heap when finished.
    template<typename Func>
    tthread::thread* new_thread(const Func& f) {
        Func* _f = new Func(f); // copy to heap
        return new tthread::thread(&impl::use_function_once<Func>,(void*)_f);
    }

    /// Creates a thread based on a guaranteed persistent function.
    /// Does not copy or delete the function.
    template<typename Func>
    tthread::thread* new_thread(const Func* f) {
        return new tthread::thread(&impl::use_function<Func>, (void*)f);
    }
}

Example usage:

size_t a = 1;
size_t b = 0;
tthread::thread* t = lthread::new_thread([&] () {
    std::cout << "I'm in a thread!\n";
    std::cout << "'a' is " << a << std::endl;
    b = 1;
});
t->join();
std::cout << "'b' is " << b << std::endl;
delete t;


texts:
Currently all this does is retrieve data from specific columns, the final result will be that I will check the data to make sure that it passes the test cases, but I want to look at this foreach right now and see if I can't make it a little simpler.

A lot of what I have coded I have come back and turned into Linq statements and made things a lot simpler (shorter), and I would really like to do the same with this foreach statement, but not real sure how to do it.

I hate to admit that I am very new to using Linq, I can read it for the most part but still have a little difficulty when writing more complex statements/queries.

Is there something that I can do to make this a lot more simple before I code any more on this Scenario, I would like to simplify so that I don't write extraneous code that will be refactored out when I make this more clear.

I have also been trying to find something that imports the HTML table into a nice neat object that I can query, but everything I have found so far has been similar to what I am doing or more complex than what I am doing here.

[Then(@"see the '(.*)' of '(.*)'")]
public void ThenSeeThe(string columnHeader, string entryName)
{
    var htmlTable = Ie.FindElementByClassName("table");
    var tableHeaders = htmlTable.FindElements(By.TagName("th"));
    var rows = new List<List<string>>();

    var htmlRows = htmlTable.FindElements(By.TagName("tr"));

    foreach (var htmlRow in htmlRows)
    {
        //first row holds the table headers
        if (htmlRow.FindElements(By.TagName("th")).Count > 0)
        {
            var thList = tableHeaders.Select(th => th.Text.ToString()).ToList();
            rows.Add(thList);
            continue;
        }

        var cellsInRow = htmlRow.FindElements(By.TagName("td"));
        var cells = cellsInRow.Select(cell => cell.Text.ToString()).ToList();
        rows.Add(cells);
    }

    var columnIndex = rows.First().IndexOf(columnHeader);
    var field = rows.Where(x => x[0] == entryName).Select(x => x[columnIndex]).First();
    if (columnHeader == "Create UTC Date")
    {
        _CreateUTC = Convert.ToDateTime(field);
    }
    else if (columnHeader == "Modify UTC Date")
    {
        _ModifyUTC = Convert.ToDateTime(field);
    }

}


texts:
I'm using the flexbox for the first time for a responsive grid system. It seems to be working as far as I tested but want to make sure it works on others too and see ways to improve this.

Please see style.css for the grid system with flexbox on github.

*{
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}
html, body{
  margin: 0;
}

/*
Layout with flexbox
*/
.container{
  max-width: 1200px;
  margin: 0 auto;
}
.container--small{
  max-width: 800px;
}
.row {
  display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
  display: -ms-flexbox;      /* TWEENER - IE 10 */
  display: -webkit-flex;     /* NEW - Chrome */
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
}
.col{
  -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
  -moz-box-flex: 1;         /* OLD - Firefox 19- */
  -webkit-flex: 1;          /* Chrome */
  -ms-flex: 1;              /* IE 10 */
  flex: 1;
}

/*
Extra Layout - 33%
*/
.col--30{
  -webkit-box-flex: 0 0 33.3333%;;
  -moz-box-flex: 0 0 33.3333%;;
  -webkit-flex: 0 0 33.3333%;;
  -ms-flex: 0 0 33.3333%;;
  flex: 0 0 33.3333%;;
}

/*
Media query
*/
@media (max-width: 768px) {
  .row > .col,
  .col--30 {
    -webkit-box-flex:  0 0 100%;
    -moz-box-flex:  0 0 100%;
    -webkit-flex: 0 0 100%;
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
  }
}

1/3 - #1

1/3 - #2

1/3 - #3


texts: Processing XML configuration which stores regular expressions and format strings for a documentation tool

texts:
I'm investigating some feature for the ScalaDoc tool, which would allow library writers to link to documentation created by third party tools like JavaDoc.

My idea is to have some (XML) configuration which specifies which package prefixes belong to which vendor and how to create a valid URL from the the class name, stored in the XML as regular expressions and format strings.

I only need one public method getLink(entity: String): Option[String] which either returns Some(validURL) or None, if the package name is not supported by the given configuration. Everything else can be changed as much as I want if it improves the code.

Consider this code:

object ExternalReferences2 {
  import java.util.regex._
  import collection.mutable._

  private object Mapping {
    def fromXml(mapping: scala.xml.NodeSeq) = {
      new Mapping(mapping \ "vendor" text, mapping \ "match" text, mapping \ "format" text)
    }
  }
  private case class Mapping(vendor: String, matches: String, format: String) {
    private val pattern = Pattern.compile(matches)
    private var currentMatcher: Matcher = null

    def hasValue(entity: String) = {
      currentMatcher = pattern.matcher(entity);
      currentMatcher.matches
    }

    def getValue = {
      val range = 0 until currentMatcher.groupCount()
      val groups = range
                     .map (currentMatcher.group(_))
                     .filterNot (_ == null)
                     .map (_.replace('.', '/'))
      format.format(groups: _*)
    }
  }

  private val config =
    <external-links>
      <mapping>
        <vendor>OpenJDK</vendor>
        <match>{ """^(javax?|sunw?|com.sun|org\.(ietf\.jgss|omg|w3c\.dom|xml\.sax))(\.[^.]+)+$""" }</match>
        <format>{ "http://download.oracle.com/javase/7/docs/api/%s.html" }</format>
      </mapping>
    </external-links>

  private def lookUp(entity: String) =
    (config \ "mapping").view
      .map(m => Mapping.fromXml(m))
      .find(_.hasValue(entity))
      .map(_.getValue)

  private val links: Map[String, Option[String]] = Map[String, Option[String]]()
    .withDefault(entry => {val result = lookUp(entry); links += ((entry, result)); result})

  def getLink(entity: String) = links(entity)
}

How can I improve that code?

The necessity to call hasValue before getValue is pretty bad, but I don't want to create the matcher twice.
Which environment variables do I have to use so that the tool can pick up the configuration from the current directory or from an arbitrary place with a command line switch?
Is there a better way to do simple caching than using withDefault to mutate the underlying map?
Any idea on how to improve lookUp?
Are there any ideas for better names? I'm not happy with Mapping, Link, Reference ... things are all over the place.


texts: Is there a route to the end of the jump table?

texts:
I'm currently learning about Dynamic Programming and solving a "coding question" related to the topic.

Given an array of non-negative integers, you are initially positioned
at the first index of the array.
Each element in the array represents your maximum jump length at that
position.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Example 2:
Input: [3,2,1,0,4]
Output: false

Here's my code:
    def canJump(nums: List[int]) -> bool:
        memo = {len(nums) - 1: True}
        def canJumpPos(pos):
            if pos >= len(nums):
                return False
            elif pos in memo:
                return memo[pos]
            else:
                for i in range(nums[pos], 0, -1):
                    if canJumpPos(i + pos):
                        return True
                memo[pos] = False

        return canJumpPos(0)

I'm having trouble reasoning about the time/space complexity of my approach. My understanding is that without memoization, this approach would be exponential. But, with memoization, this becomes a linear time algorithm? Is this correct? How would you recommend I calculate time complexity in the future when I'm dealing with dynamic programming?


texts:
I've picked up the timeout-function below from ActiveState's recipes for Python2 and polished it for python3.4.

Is there any leaner, less clunky way to write it?

import signal, time

class TimedOutExc(Exception):
    def __init__(self, value = "Timed Out"):
        self.value = value
    def __str__(self):
        return repr(self.value)

def TimedOutFn(f, timeout, *args, **kwargs):
    def handler(signum, frame):
        raise TimedOutExc()

    old = signal.signal(signal.SIGALRM, handler)
    signal.alarm(timeout)
    try:
        result = f(*args, **kwargs)
    finally:
        signal.signal(signal.SIGALRM, old)
    signal.alarm(0)
    return result

def timed_out(timeout):
    def decorate(f):
        def handler(signum, frame):
            raise TimedOutExc()

        def new_f(*args, **kwargs):
            old = signal.signal(signal.SIGALRM, handler)
            signal.alarm(timeout)
            try:
                result = f(*args, **kwargs)
            finally:
                signal.signal(signal.SIGALRM, old)
            signal.alarm(0)
            return result

        new_f.__name__ = f.__name__
        return new_f

    return decorate

def fn_1(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(4)
def fn_2(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(2)
def fn_3(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(2)
def fn_4(secs):
    try:
        time.sleep(secs)
        return "Finished"
    except TimedOutExc:
        print( "(Caught TimedOutExc, so cleaining up, and re-raising it) - ")
        raise TimedOutExc

if __name__ == '__main__':

    try:
        print( "fn_1 (sleep 2, timeout 4): ")
        print( TimedOutFn(fn_1, 4, 2) )
    except TimedOutExc:
        print( "took too long")

    try:
        print( "fn_2 (sleep 2, timeout 4): ")
        print( fn_2(2) )
    except TimedOutExc:
        print( "took too long")

    try:
        print( "fn_1 (sleep 4, timeout 2): ")
        print( TimedOutFn(fn_1, 2, 4) )
    except TimedOutExc:
        print( "took too long")

    try:
        print( "fn_3 (sleep 4, timeout 2): ")
        print( fn_3(4) )
    except TimedOutExc:
        print( "took too long")

    try:
        print( "fn_4 (sleep 4, timeout 2): ")
        print( fn_4(4) )
    except TimedOutExc:
        print( "took too long")


texts: Dividing by the total count based on occupation

texts:
I have this query where I am working out the percentage of peoples occupation. I have a sub query that works out the total count of people codes and that result is what I used to divide by. I could hardcode this but the count could change.

It just looks a bit messy and I am wondering if there is a nicer way to do the sub query.

SELECT
    CONVERT(VARCHAR(20),COUNT(CO.code)*100 /
(
SELECT
COUNT(CO.Code)
FROM
TABLE1 K
INNER JOIN TABLE2 CO ON(CO.id= K.id AND CO.status= 'Something' AND K.statuscode = 0  AND CO.statuscode =0))
)+'%',

Here is the final query. I needed the sub query because of the group by which if I did the count in the SELECT, it would just return the number of people who had a specific occupation.

SELECT
    CONVERT(VARCHAR(20),COUNT(CO.code)*100 /
(
SELECT
COUNT(CO.Code)
FROM
TABLE1 K
INNER JOIN TABLE2 CO ON(CO.id= K.id AND CO.status= 'Something' AND K.statuscode = 0  AND CO.statuscode =0))
)+'%',
K.occupation
FROM
TABLE 1 K
LEFT OUTER TABLE 2 CO  ON(CO.id = K.id AND CO.status = 'Something' AND K.statuscode = 0 AND CO.statuscode = 0)
GROUP BY
K.occupation
ORDER BY
COUNT(CO.Code) DESC

Is there a nicer/more efficient way to do this?


texts:
This is a simple program that I wrote. It takes a 64-bit unsigned int as input and returns its English name.

#include <iostream>
#include <string>
#include <cmath>
#include <stdint-gcc.h>
using namespace std;
int container[7];                       /// every element contains a number between 0 and 999
string conv0to19(uint64_t);   /// converts 1 to 19 to its name
string conv_dec(uint64_t);    /// converts 20,30...,90 to its name
string convert(uint64_t);       ///converts a number from of range uint64_t to its name
void fillContainer(uint64_t);
string convert1to999(uint64_t, int);

string name[]={"","thousand","million","billion","trillion","quadrillion","quintillion"};

string conv0to19(uint64_t a)
{
    switch (a)
    {
        case 0:return "";   break;
        case 1:return "one ";  break;
        case 2:return "two ";  break;
        case 3:return "three ";break;
        case 4:return "four "; break;
        case 5:return "five "; break;
        case 6:return "six ";  break;
        case 7:return "seven ";break;
        case 8:return "eight ";break;
        case 9:return "nine "; break;
        case 10:return "ten ";  break;
        case 11:return "eleven "; break;
        case 12:return "twelve "; break;
        case 13:return "thirteen ";break;
        case 14:return "fourteen "; break;
        case 15:return "fifteen "; break;
        case 16:return "sixteen "; break;
        case 17:return "seventeen ";break;
        case 18:return "eighteen ";break;
        case 19:return "nineteen ";break;
    }
}

string conv_dec(uint64_t a)
{
    switch(a)
    {
        case 0:return "";break;
        case 1:return "";break;
        case 2:return "twenty ";   break;
        case 3:return "thirty ";  break;
        case 4:return "forty ";  break;
        case 5:return "fifty "; break;
        case 6:return "sixty "; break;
        case 7:return "seventy "; break;
        case 8:return "eighty ";  break;
        case 9:return "ninety ";break;

    }
}

string convert1to999(uint64_t a,int i)
{
    if(a!=0)
    {
        if (a>0&&a<20)
            return conv0to19(a)+name[i];

        if(a>20&&a<100&&a%10!=0)
            return conv_dec(a/10)+conv0to19(a%10)+name[i];

        if(a>=20&&a&&a<100&&a%10==0)
            return conv_dec(a/10)+name[i];

        if(a>=100&&a<1000)
            return conv0to19(a/100)+"hundred "+conv_dec(fmod((a/10),10))+conv0to19(a%10)+name[i];
    }
    else return "";
}

void fillContainer(uint64_t a)
{
    for(int i=0;i<=6;i++)
    {
        container[i]=a%1000;
        a/=1000;
    }
}

string convert(uint64_t a)
{
    if(a!=0)
    {
        string output;
        fillContainer(a);

        for(int i=6;i>=0;i--)
            if(container[i]!=0)
                output=output+convert1to999(container[i],i)+" ";

        while(output[output.size()-1]==' ')         ///deletes the
        output.resize(output.size()-1);            ///white spaces on the end

        return output;
    }
    else
        return "zero";
}

int main()
{
    uint64_t a;
    cin>>a;
    cout<<convert(a);
}


texts: ASP.NET MVC return early from an action that returns a model

texts:
Consider the following code segment written by a coworker of mine:

public ActionResult Index()
    {

        DataRetrieveModel dataRetrieveModel = new DataRetrieveModel();

        using (spc_web_trunkEntities db = new spc_web_trunkEntities())
        {
            DataRetrieveDAL dataRetrieveDAL = new DataRetrieveDAL(db);

            dataRetrieveModel.CustomerList = dataRetrieveDAL.GetCustomerList();

            dataRetrieveModel.LineList = dataRetrieveDAL.GetLineList();
            if (dataRetrieveModel.LineList.Count > 0)
            {
                dataRetrieveModel.ModelList = dataRetrieveDAL.GetModelList(dataRetrieveModel.LineList[0].Value);
            }

            if (dataRetrieveModel.LineList.Count > 0 &&
                dataRetrieveModel.ModelList.Count > 0)
            {
                dataRetrieveModel.LotList = dataRetrieveDAL.GetLotList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
            }

            if (dataRetrieveModel.LineList.Count > 0 &&
                dataRetrieveModel.ModelList.Count > 0)
            {
                dataRetrieveModel.EquipmentList = dataRetrieveDAL.GetEquipmentList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
            }
        }

        return View(dataRetrieveModel);
    }

It's a very simple controller that returns a model.

My question is given this code, how would you go about cleaning/refactoring it?

Here's my approach. First, I identified a lot of short circuiting points along with empty spaces, so I went ahead and cleaned those up first:

public ActionResult Index()
    {
        DataRetrieveModel dataRetrieveModel = new DataRetrieveModel();

        using (spc_web_trunkEntities db = new spc_web_trunkEntities())
        {
            DataRetrieveDAL dataRetrieveDAL = new DataRetrieveDAL(db);

            dataRetrieveModel.CustomerList = dataRetrieveDAL.GetCustomerList();
            dataRetrieveModel.LineList = dataRetrieveDAL.GetLineList();
            if (!dataRetrieveModel.LineList.Any())
                return View(dataRetrieveModel);

            dataRetrieveModel.ModelList = dataRetrieveDAL.GetModelList(dataRetrieveModel.LineList[0].Value);

            if (!dataRetrieveModel.ModelList.Any())
                return View(dataRetrieveModel);

            dataRetrieveModel.LotList = dataRetrieveDAL.GetLotList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
            dataRetrieveModel.EquipmentList = dataRetrieveDAL.GetEquipmentList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
        }

        return View(dataRetrieveModel);
    }

I'm also wondering why multiple queries have to be made to initialize dataRetrieveModel, but for now, I only want to focus on this method.

But then all those return View(dataRetrieveModel) seems too verbose, so I thought about defining a return label and using a goto. I'm not sure how others feel about it.

I'd like to hear any suggestions on this matter.


texts: Copying a lot of code to filter four PHP arrays

texts:
I have made this search filter and it works fine, but I think the code looks a little messy and I have no idea how to clean it up.

I hope the following makes sense, otherwise please tell me which information you need, and I will provide it ASAP.

// GET THE POST VALUE FROM FORM FIELDS
          $field_value_service =  $_POST['service_filter'];
          $field_value_region  =  $_POST['service_region'];
          $field_value_postal  =  $_POST['postal_code'];
          $field_value_gender  =  $_POST['gender_filter'];

          // GET USER INFO FROM USERS WHERE USERS VALUES IS EQUAL TO FORM FIELD VALUES
          $valuesService = get_cimyFieldValue(false, 'service', $field_value_service);
          $valuesRegion  = get_cimyFieldValue(false, 'region', $field_value_region);
          $valuesPostal  = get_cimyFieldValue(false, 'postnummer', $field_value_postal);
          $valuesGender  = get_cimyFieldValue(false, 'gender', $field_value_gender);

          // CREATE EMPTY ARRAYS
          $userArray = array();
          $userArrayTwo = array();
          $userArrayThree = array();
          $userArrayFour  = array();
          $userArrayFive = array();

          foreach ($valuesService as $value) {
            $userArray[] = $value['user_id'];
          }
          foreach ($valuesRegion as $value) {
            $userArrayTwo[] = $value['user_id'];
          }
          foreach ($valuesPostal as $value) {
            $userArrayThree[] = $value['user_id'];
          }
          foreach ($valuesGender as $value) {
            $userArrayFour[] = $value['user_id'];
          }

          $firstResult = array_merge($userArray, $userArrayTwo);
          $duplicates = array_unique(array_diff_assoc($firstResult, array_unique($firstResult)));
          $secondResult = array_merge($duplicates, $userArrayThree);
          $secondDuplicates = array_unique(array_diff_assoc($secondResult, array_unique($secondResult)));
          $thirdResult = array_merge($secondDuplicates, $userArrayFour);
          $thirdDuplicates = array_unique(array_diff_assoc($thirdResult, array_unique($thirdResult)));


texts: Design dilemma: extensibility vs simplicity

texts:
Here is my problem abstracted to Bird classes. I know that number of Birds will increase on the future and new behaviors might be needed. With 10 Birds first design might not look so simple and lead to lots of duplicated code. On the other hand, second design can be perceived as "class explosion". Which of these two designs would be considered best-practice?

Classic:

#include <iostream>

class Bird
{
  public:
    virtual void Fly() const = 0;
    virtual void Speak() const = 0;
};

class Eagle : public Bird
{
  public:
    virtual void Fly() const
    {
      std::cout << "Eagle shall fly now!" << std::endl;
    }
    virtual void Speak() const
    {
      std::cout << "Eagle speaking!" << std::endl;
    }
};

class Penguin : public Bird
{
  public:
    virtual void Fly() const
    {
      std::cout << "Penguin shall fly now!" << std::endl;
    }
    virtual void Speak() const
    {
      std::cout << "Penquin speaking!" << std::endl;
    }
};

int main()
{
  std::cout << "..." << std::endl;
  Bird* bird = NULL;

  bird = new Eagle();
  bird->Fly();
  bird->Speak();
  delete bird; bird = NULL;

  bird = new Penguin();
  bird->Fly();
  bird->Speak();
  delete bird; bird = NULL;

  return 0;
}

"Better?

#include <iostream>
#include <cassert>

class FlyStyle
{
  public:
    virtual void Fly() const = 0;
};

class FlyHigh : public FlyStyle
{
  virtual void Fly() const
  {
    std::cout << "Fly high!" << std::endl;
  }
};

class NoFly : public FlyStyle
{
  virtual void Fly() const
  {
    std::cout << "No fly!" << std::endl;
  }
};

class SpeakStyle
{
  public:
    virtual void Speak() const = 0;
};

class SpeakLoud : public SpeakStyle
{
  virtual void Speak() const
  {
    std::cout << "Speak LAUD!!!!" << std::endl;
  }
};

class NoSpeak : public SpeakStyle
{
  virtual void Speak() const
  {
    std::cout << "No speaking!" << std::endl;
  }
};

class SuperBird
{
  public:
    SuperBird(FlyStyle* fly, SpeakStyle* speak)
      : flystyle(fly),
      speakstyle(speak)
  {
    assert(NULL != flystyle);
    assert(NULL != speakstyle);
  }

    ~SuperBird() { delete flystyle; delete speakstyle;}

    virtual void Fly() const
    {
      flystyle->Fly();
    }
    virtual void Speak() const
    {
      speakstyle->Speak();
    }
  protected:
    FlyStyle* flystyle;
    SpeakStyle* speakstyle;
};

class SuperBirdFactory
{
  public:
    static SuperBird* createEagle()
    {
      return new SuperBird(new FlyHigh(), new SpeakLoud());
    }
    static SuperBird* createPenguin()
    {
      return new SuperBird(new NoFly(), new NoSpeak());
    }
};

int main()
{
  SuperBird* bird = NULL;

  bird = SuperBirdFactory::createEagle();
  bird->Fly();
  bird->Speak();
  delete bird; bird = NULL;

  bird = SuperBirdFactory::createPenguin();
  bird->Fly();
  bird->Speak();
  delete bird; bird = NULL;

  return 0;
}


texts: use Identity value in entity after insert in Database

texts:
i want to generate value using current date and ID of inserted entity
problem is that ID value not generated until insert object to  database,
so i use this code for generate value:

public ActionResult Create([Bind(Include = "ID,TrackingCode,FirstName,LastName,ProductName,CurrentStats,FailureReason,ReceiveDateTime,DeliveryDateTime,Price,Description,SerialNumber,ExtraItems,PhoneNumber")] Tracking tracking)
    {
        if (ModelState.IsValid)
        {
            db.Trackings.Add(tracking);
            db.SaveChanges();
            Tracking _tracking = db.Trackings.Find(tracking.ID);
            db.Entry(_tracking).State = EntityState.Modified;
            _tracking.TrackingCode = Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd") + tracking.ID.ToString());
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(tracking);
    }

code work fine and do job that i want
but i think this is not standard way is there any better approach to improve this code?


texts: Check if page was scrolled all the way to the end

texts:
I am not sure if this is the best way of doing this or if it works in all situations.

function atPageEnd() {
    var height;

    height = window.document.documentElement.scrollHeight;

    return window.pageYOffset + window.innerHeight === height;
}


texts:
I want to read csv file in to array of structs with NULL ending.

test.txt:

11,345,1,k
12,34.23,3,v
13,13.4,5,x
14,15.7,6,c

My code:

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

struct csv_line {
  int value1;
  float value3;
  int value2;
  char char1;
};

struct csv_line *line_pointer = NULL;

int main(void) {
    FILE *csvFile = NULL;
    csvFile = fopen("test.txt", "r");
    if (csvFile == NULL)
      exit(1);

    size_t i = 0;
    while (1) {
    line_pointer = (struct csv_line *)realloc(line_pointer, sizeof(struct csv_line) * (i + 1));
    if (fscanf(csvFile, "%d,%f,%d,%c",
            &(line_pointer + i)->value1,
            &(line_pointer + i)->value3,
            &(line_pointer + i)->value2,
            &(line_pointer + i)->char1) != EOF) {
      i++;
    } else{
        (line_pointer + i)->value1 = 0;
        (line_pointer + i)->value3 = 0.0;
        (line_pointer + i)->value2 = 0;
        (line_pointer + i)->char1 = '\0';
        break;
     }
    }
    fclose(csvFile);
    int k = 0;
    while('\0' != (line_pointer + k)->char1) {
        printf("%d, %.2f, %d, %c",
                (line_pointer + k)->value1,
                (line_pointer + k)->value3,
                (line_pointer + k)->value2,
                (line_pointer + k)->char1);
        printf("\n");
        k++;
    }

    free(line_pointer);

    return EXIT_SUCCESS;
}

Questons:

Is it possible to move fscanf condition inside while-loop condition instead of endless (1) ?
How to set "end" of array with single NULL like "line_pointer[i] = NULL" in else statement?


texts:
Today I read this thing about the Collatz Conjecture and wanted to try and write a program that calculates all the numbers. If you have any idea how the code could be shortened, please tell me.

List<string> liste = new List<string>();
long num = 1;
        long z = num;

        while (num != 100000)
        {
            while (z != 1)
            {
                if (z % 2 == 0)
                {
                    z = z / 2;
                }
                else
                {
                    z = (z * 3) + 1;
                }
            }
            liste.Add(num + ": " + z);
            Console.WriteLine(num+": "+z);
            finalnumber = z;
            num++;
        }

            string path = @"N:\Desktop\test.txt";
            File.Delete(path);
            for (int i = 0; i < liste.Count; i++)
            {
                string appendText = ""+liste[i]+"" + Environment.NewLine;
                File.AppendAllText(path, appendText);
            }


texts: Calculate future date based on business days

texts:
I've written a program for calculating the future date after certain number of business days.

function add_business_days($startdate,$businessdays,$holidays,$dateformat){
   $i=1;
   $dayx = strtotime($startdate);

  while($i < $businessdays){
     $day = date('N',$dayx);
     $date = date('Y-m-d',$dayx);
     if($day < 6 && !in_array($date,$holidays))$i++;
     $dayx = strtotime($date.' +1 day');
  }
  return date($dateformat,$dayx);
}

But the problem with this function is that it doesn't check the last date of business day for Saturday and Sunday. Also, the last day could be the holiday. Can anyone provide me a better solution for this?

I've made a solution to this problem as

function add_business_days($startdate,$businessdays,$holidays,$dateformat){
   $i=1;
   $dayx = strtotime($startdate);

  while($i <= $businessdays){
     $day = date('N',$dayx);
     $date = date('Y-m-d',$dayx);
     if($day < 6 && !in_array($date,$holidays))$i++;
     $dayx = strtotime($date.' +1 day');
  }
  return date($dateformat,strtotime(date('Y-m-d', $dayx) . ' -1 day'));
}

But it doesn't seems good.

Usage Example

I'm using this method for calculating the shipment date on which a product will be delivered to the customer.

$startdate = "2014-05-28";  //Order placing date
$businessdays = 7; //number of days for delivery
$holidays = array('2014-05-30','2014-06-03');  //array of dates having holidays. excluding business days.
$dateformat = 'd-m-Y';  //output date format for displaying.
$delivery = add_business_days($startdate, $businessdays, $holidays, $dateformat);

The $delivery is supposed to have date 09-06-2014 but the first code returns 07-06-2014 which doesn't check for the last date in loop for weekends (Saturday or Sunday). I've made the solution in the second program by execution the loop one more time and then return the previous date. But this approach doesn't seem good. Any suggestions on not going over and returning the previous date?


texts:
I always prefer to minimize the code, but sometimes I get into conflict with other people about the DRY concept.

In this simple example, which one would be a good choice?

function str_cleaner($str)
{
    $str = trim($str);
    $str = str_replace(".", "", $str);
    $str = str_replace(",", "", $str);
    $str = str_replace("-", "", $str);
    $str = str_replace("/", "", $str);
    return $str;
}

function str_cleaner($str)
{
    $chars = array('.', ',', '-', '/');
    foreach($chars as $char) {
        $str = str_replace($char, '', trim($str));
    }
    return $str;
}


texts:
I am quite an experienced developer but I am quite new to JS/frontend/functional programming and I am working with react-native in my day-job now.

I'm trying to do my own flux implementation to better understand redux. My goal is to have a performant data store that will behave predictably. This solution seems to be working for me, but will become slower the longer the app runs.

I've looked at using immutable.js and lodash but I'm not sure it's necessary. I've also considered using a mutable currentState variable and only merging the changes since the last call to getState() and then resetting i.e changes = [] and updating currentState. I'd also like some opinions on my use of a promise in the getState function.

export default class Session {

  static changes = []

  static getState() {
    return new Promise((resolve, reject) => {
      resolve(this.changes.reduce((a, x) => Object.assign(a,x),{}))
    })
  }

  static update(value) {
    this.changes.push(value)
  }

  static showChanges() {
    this.changes.forEach((x)=> console.log(x))
  }
}

Object.defineProperty(Session, 'changes',{
  writable: false,
  enumerable: true
})


texts: What is the best option to replace a loop?

texts:
I'm using Flask on Python and I'm displaying the username at the top of the site (and it's working) as follows:
@app.route("/")
@login_required
def index():
    """Queries the user's First Name to display in the title"""
    names = db.execute("""
        SELECT first_name
        FROM users
        WHERE id=:user_id
        """,
        user_id = session["user_id"]
    )
    return render_template("index.html", names = names)

  {% for name in names %}

{{ name["first_name"] }}' Bookshelf

  {% else %}

Your Bookshelf

  {% endfor %}

I don't know if it is necessary, but here is my database configuration:

Although it is working, I believe that it is not ideal to use for loop to display just one name. Does anyone have any suggestions?


texts:
I tried to find the correspondences between columns in two datasets, which is called schema matching. I implemented the algorithm like a c-style program so that I could implement it easily but I have noticed my logic is very bad.

Could someone look at it and guide me on how I can improve the stuff using plain-ruby methods?

I am not allowed to use cronjob or other background jobs, etc.

require 'csv'

imdb_csv = CSV.read("imdb.csv", :headers => true)
rotten_tomatoes_csv = CSV.read("rotten_tomatoes.csv", :headers => true)
g    = [["imdb.Name", "rt.Name"],["imdb.YearRange", "rt.Year"],["imdb.ReleaseDate", "rt.ReleaseDate"],["imdb.Director", "rt.Director"],["imdb.Creator", "rt.Creator"], ["imdb.Cast", "rt.Cast"],["imdb.Duration", "rt.Duration"],["imdb.RatingValue", "rt.RatingValue"],["imdb.Genre", "rt.Genre"],["imdb.Description", "rt.Description"]]

imdb = imdb_csv.to_a
rt = rotten_tomatoes_csv.to_a

def get_list(imdb, rt, g)
  imdb_rows = imdb.count
  imdb_columns = imdb[0].count
  rt_rows = rt.count
  rt_columns = rt[0].count
  list = []

  for j in 0..(imdb_columns-1) do
    d = 0
    for l in 0..(rt_columns-1) do
      sim_total = 0
      for i in 1..(imdb_rows-1) do

        str1 = imdb[i][j].nil? ? "" : imdb[i][j].delete(" \t\r\n")
        length1 = str1.nil? ? 0 : str1.length

        sim_single = 0

        for k in 1..(rt_rows-1) do

          str2 = rt[k][l].nil? ? "" : rt[k][l].delete(" \t\r\n")
          length2 = str2.nil? ? 0 : str2.length

          distance = 0
          m = 0

          while m < length1 and m < length2 do
            if str1[m] == str2[m]
              distance = distance + 1
            end
            m = m + 1
          end

          similarity = 0

          if ((distance == length1 and distance >= (length2/3)) or (distance == length2 and distance >= (length1/3))) and str1 != "" and str2 != ""
            similarity = 1
          end

          sim_single = sim_single + similarity

        end

        sim_total = sim_total + sim_single

      end

      if sim_total > d and sim_total > 0
        list << ["imdb.#{imdb[0][j]}", "rt.#{rt[0][l]}"]
        d = sim_total
      end

    end

    printf("===== %d", j)
  end


texts: Javascript to show folder and files by calling Web Api

texts:
I have this Javascript which call the web api to see the available folder and then the available files. Any comment or code review on my code?

    var divFolder = document.getElementById("rootFolder");
    var divFiles = document.getElementById("files");

    function createFolderElement(data) {
        var li = document.createElement("div");
        li.setAttribute('data-id', data.filePathId);
        li.setAttribute('class', "folder");

        divFolder.appendChild(li);
        li.innerHTML = data.folderName
    }

    function createFileElement(data) {
        debugger
        var li = document.createElement("div");
        li.setAttribute('data-id', data.id);
        li.setAttribute('class', "file");

        divFiles.appendChild(li);
        li.innerHTML = data.fileName
    }

    async function fetchFolder(parentId) {
        document.getElementById('spinner').style.display = 'block'
        divFolder.innerHTML = ''

        const response = await fetch(`https://localhost:44371/api/file/folder/${parentId}`);

        if (!response.ok) {
            const message = `An error has occured: ${response.status}`;
            $("div.message").text(message);
            $("div.message").addClass("message alert alert-warning");
            //throw new Error(message);
        }

        const files = await response.json();
        if (files.length > 0) {
            files.forEach((data) => {
                createFolderElement(data)
            })

            createFolderEventListener();

            document.getElementById('spinner').style.display = 'none'
        }
    }

    async function fetchFiles(filePathId) {
        document.getElementById('spinner').style.display = 'block'
        divFolder.innerHTML = ''

        const response = await fetch(`https://localhost:44371/api/file/files/${filePathId}`);

        if (!response.ok) {
            const message = `An error has occured: ${response.status}`;
            $("div.message").text(message);
            $("div.message").addClass("message alert alert-warning");
            //throw new Error(message);
        }

        const folders = await response.json();
        debugger
        if (folders.length > 0) {
            folders.forEach((data) => {
                createFileElement(data)
            })

            createFileEventListener();
        }

        document.getElementById('spinner').style.display = 'none'
    }

    function createFolderEventListener() {
        const myfolder = document.getElementsByClassName("folder");
        [...myfolder].forEach(function (element) {
            element.addEventListener("click", function () {
                fetchFolder(element.dataset.id);
                fetchFiles(element.dataset.id);
            });
        });
    };

    function createFileEventListener() {
        const myfolder = document.getElementsByClassName("file");
        [...myfolder].forEach(function (element) {
            element.addEventListener("click", function () {
                downloadPdf(element.dataset.id, element.textContent)
            });
        });
    };

    $(function () {
        document.getElementById('spinner').style.display = 'none'
        fetchFolder(1);
    })
    div.folder {
        border: 1px solid black;
        margin: 2px;
        cursor: pointer
    }

    div.file {
        border: 1px solid black;
        margin: 2px;
        cursor: pointer
    }


texts: Determining common divisors of two numbers

texts:
Is there a better algorithm for finding the common divisors of two numbers?  Can this code be shortened?

import java.util.*;

public class Testing1 {
public static void main (String args[]){
    Scanner x=new Scanner(System.in);
    System.out.print("Enter the 1st number(larger number) :  ");
    int y=x.nextInt();
    System.out.print("Enter the 2nd number : ");
    int z=x.nextInt();

    int ar1[]=new int[y];
    int ar2[]=new int[z];

    for( int i=1;i<y;i++){ //puts the divisors of the larger number to an array ar1[]
         int l=y%i;
         if(l==0)
           ar1[i]=i;}

    for( int i=1;i<z;i++){//puts the divisors of the other number to an array ar2[]
        int l=z%i;
        if(l==0)
          ar2[i]=i;}System.out.print("Common divisors of "+y+", "+z+" = ");

    for(int i=1;i<=ar2.length-1;i++){ //printing the common elements of both arrays.
     if((ar1[i]==ar2[i])&&ar2[i]!=0)
        System.out.print(i+" ");
}}}


texts: Simple, pixel independent, CSS Grid resizing with no third party libraries

texts:
I wanted to see if I could implement codepen-like or jsfiddle-like window resizing by using simple boxes and CSS grid without any third party libraries.

Live version can be found here:
https://codepen.io/Aquazi/pen/bYomRN?editors=0011

HTML, a simple div containing 3 divs:

A

B

CSS,

body{
  margin: 0px;
}

.container{
    display: grid;
    grid-template-columns: 1fr 2px 1fr;
    background-color: powderblue;
    height: 10em;
}

.handler{
   background-color: white;
}

.handler:hover{
  cursor: col-resize;
}

Javascript, the actual functionality:

/** creates variables out of interested DOM elements**/

var tophandler = document.getElementById("tophandler");
var topContainer = document.getElementById("topcontainer");

function allowResizing(){

    window.addEventListener(("mousemove"), mousePosition);
    /** adds the event listener tracking mousemovement and adjusting sizing of
        the two boxes**/

    window.addEventListener(("mouseup"), disallowResizing);
    /** adds the event listener in charge of removing the previous event
    listener so the event is not called each time "mousemove" is triggered on the
    window saving unnecessary cpu calls**/
};

function mousePosition(){
   /** sets the new container grid sizing each time the mouse if moved following
       a mousedown on the handlder **/

    var fraction = Math.round(event.clientX*4000 / (window.innerWidth -2))/4000;
    /** takes the mouse position on the X axis and divides it the the window
        width minus the fixed width of the handler. The values is rounded
        after being multiplied by 4000 (to ensure little error on 4k screens)
        and divided again by 4000**/

    topContainer.style.gridTemplateColumns = fraction + "fr 2px " + (1-fraction)
+ "fr";
    /** applies the desired styling on each mouse movement **/
};

function disallowResizing(){
  /** removes mousemove event listener **/
  window.removeEventListener(("mousemove"), mousePosition);
};

tophandler.addEventListener(("mousedown"), allowResizing);
/** When mouse is pressed on the handler allows Resizing of the boxes **/


texts:
I wrote a program that will take a number from 0 to 999,999,999,999 and spell out that number in English.

How could I improve the readability of my code?

class Say
  UNITS ={
    1=> "one",
    2=> "two",
    3=> "three",
    4=> "four",
    5=> "five",
    6=> "six",
    7=> "seven",
    8=> "eight",
    9=> "nine"
  }
  TEENS ={
    11=> "eleven",
    12=> "twelve",
    13=> "thirteen",
    14=> "fourteen",
    15=> "fifteen",
    16=> "sixteen",
    17=> "seventeen",
    18=> "eighteen",
    19=> "nineteen"
  }
  TENS ={
    1=> "ten",
    2=> "twenty",
    3=> "thirty",
    4=> "forty",
    5=> "fifty",
    6=> "sixty",
    7=> "seventy",
    8=> "eighty",
    9=> "ninety"
  }
  NUMBER_SCALE = {
    1=>"hundred",
    2=>"thousand",
    3=>"million",
    4=>"billion",
    5=>"trillion"
  }

  def initialize(number)
    @number = number.to_s
  end

  def in_english
    raise ArgumentError if @number.to_i < 0 or @number.to_i > 999_999_999_999
    return "zero" if @number == "0"
    ret_val =""
    chunks = chunks_of_thousand(@number)
    chunks.each.with_index do |n,i|
      if n.length > 2
        ret_val << " " unless ret_val.empty?
        ret_val << "#{UNITS[n[0].to_i]} #{NUMBER_SCALE[1]}"
        two_digit_number = n[1]+n[2]
        if two_digit_number.to_i > 0
          ret_val << " " unless ret_val.empty?
          ret_val << "#{less_than_100(two_digit_number)}"
        end
      else
        if n.to_i > 0
          ret_val << " " unless ret_val.empty?
          ret_val << less_than_100(n)
        end
      end
      ret_val << " #{NUMBER_SCALE[chunks.length-i]}" if chunks.length-i > 1 && n.to_i > 0
    end
    #system `say #{ret_val}`
    ret_val
  end

  private
  def chunks_of_thousand(a)
    ret_val =[]
    n = a.to_i.to_s.length
    num_chunks= n/3
    rem = n % 3
    if rem > 0 then
      ret_val << a.to_i.to_s.split("")[0..rem-1].join().to_i.to_s
      start = rem
    else
      start = 0
    end
    0.upto(num_chunks-1) do |i|
      ret_val << a.to_i.to_s[start..3*(i+1)+(rem-1)].to_i.to_s
      start= 3*(i+1)+rem
    end
    ret_val
  end

  def less_than_100(n)
    return UNITS[n.to_i] if n.length == 1
    return TENS[n[0].to_i] if n.length == 2 && n[1] == "0"
    return TEENS[n.to_i] if n.length == 2 && n[0] == "1"
    return "#{TENS[n[0].to_i]}-#{UNITS[n[1].to_i]}" if n.length == 2
    raise "Number length is greater then 2"
  end
end


texts: Enum, constants, or other to represent chess pieces

texts:
I'm learning C# and I decided to write a chess program to help me practice the concepts I'm learning in my book. I started the Board class tonight, which is going to handle 1) the board state and 2) checking if moves are legal.

I feel like I need to give careful consideration to how I represent the board. I started with a list of constants:

// CONSTANTS
private const sbyte EMPTYSQUARE = 0;
private const sbyte WKING = 1;
private const sbyte WQUEEN = 2;
private const sbyte WROOK = 3;
private const sbyte WBISHOP = 4;
private const sbyte WKNIGHT = 5;
private const sbyte WPAWN = 6;
private const sbyte BKING = 7;
private const sbyte BQUEEN = 8;
private const sbyte BROOK = 9;
private const sbyte BBISHOP = 10;
private const sbyte BKNIGHT = 11;
private const sbyte BPAWN = 12;

private const sbyte GAMEINPROGRESS = 0;
private const sbyte CHECKMATEWHITE = 1;
private const sbyte CHECKMATEBLACK = 2;
private const sbyte NOLEGALMOVESDRAW = 3;
private const sbyte THREEMOVEDRAW = 4;
private const sbyte FIFTYMOVEDRAW = 5;
private const sbyte WHITERESIGNED = 6;
private const sbyte BLACKRESIGNED = 7;

// VARIABLES
private sbyte[,] board =
{
    {9, 11, 10, 8,  7,  10, 11, 9},
    {12,12, 12, 12, 12, 12, 12,12},
    {0, 0,  0,  0,  0,  0,  0,  0},
    {0, 0,  0,  0,  0,  0,  0,  0},
    {0, 0,  0,  0,  0,  0,  0,  0},
    {0, 0,  0,  0,  0,  0,  0,  0},
    {6, 6,  6,  6,  6,  6,  6,  6},
    {3, 5,  4,  2,  1,  4,  5,  3}
};

Then I realized I could use an enum here, which I hear is good practice so you don't go mixing up your "magic numbers":

private enum Piece
{
    EMPTY, WKING, WQUEEN, WROOK, WBISHOP, WKNIGHT, WPAWN, BKING, BQUEEN, BROOK, BBISHOP, BKNIGHT, BPAWN
}

private enum State
{
    GAMEINPROGRESS, CHECKMATEWHITE, CHECKMATEBLACK, NOLEGALMOVEDRAW, THREEMOVEDRAW, FIFTYMOVEDRAW, WHITERESIGNED, BLACKRESIGNED
}

I then go to declare the board array and I had to use this ugly-looking monstrosity:

private sbyte[,] board =
{
    {(sbyte)Piece.BROOK, (sbyte)Piece.BKNIGHT, (sbyte)Piece.BBISHOP, (sbyte)Piece.BQUEEN, (sbyte)Piece.BKING, (sbyte)Piece.BBISHOP, (sbyte)Piece.BKNIGHT, (sbyte)Piece.BROOK},
    {(sbyte)Piece.BPAWN, (sbyte)Piece.BPAWN, (sbyte)Piece.BPAWN, (sbyte)Piece.BPAWN, (sbyte)Piece.BPAWN, (sbyte)Piece.BPAWN, (sbyte)Piece.BPAWN, (sbyte)Piece.BPAWN},
    {(sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY},
    {(sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY},
    {(sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY},
    {(sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY, (sbyte)Piece.EMPTY},
    {(sbyte)Piece.WPAWN, (sbyte)Piece.WPAWN, (sbyte)Piece.WPAWN, (sbyte)Piece.WPAWN, (sbyte)Piece.WPAWN, (sbyte)Piece.WPAWN, (sbyte)Piece.WPAWN, (sbyte)Piece.WPAWN},
    {(sbyte)Piece.WROOK, (sbyte)Piece.WKNIGHT, (sbyte)Piece.WBISHOP, (sbyte)Piece.WQUEEN, (sbyte)Piece.WKING, (sbyte)Piece.WBISHOP, (sbyte)Piece.WKNIGHT, (sbyte)Piece.WROOK}
};

It's really making me second-guess whether or not I want to keep using enum. That's a lot of typing and typecasting just to program in one chess board.

What do you think? Should I go constants or enums?

And while we're at it, what do you think of my choice of data structure for a chess board? Are there faster structures? Are there smaller structures? (I only need to store numbers 0 through 12) Should I enlarge the array to help me compute off-the-board knight moves? Should I be using a different data structure entirely?


texts: Shorten code to perform search based on four slash-delimited parameters

texts:
How can I make this code more compact?

It is a ASP.net WebForms project

It is a SinglePageApplication for searching in list mode and map mode.

I have many paths for a page.

/Denmark
/Denmark/Copenhagen
/Denmark/Copenhagen/Christiansborg
Map/Denmark
Map/Denmark/Copenhagen
Map/Denmark/Copenhagen/Christiansborg

in which that control the UI and parameteres passed to a JavaScript function

string parameters = (string)Page.RouteData.Values["params"],
    param1 = string.Empty,
        param2 = string.Empty,
            param3 = string.Empty,
                param4 = string.Empty;

if (!string.IsNullOrWhiteSpace(parameters))
{
    var parameterArray = parameters.Split('/');
    var i = 0;
    while (i < parameterArray.Length)
    {
        if (i == 3)
            param4 = parameterArray[3];

        if (i == 2)
            param3 = parameterArray[2];

        if (i == 1)
            param2 = parameterArray[1];

        if (i == 0)
            param1 = parameterArray[0];

        i++;
    }
}

SearchState = new RoomSearchState(param1, param2, param3, param4);

And the RoomStateSearch

public RoomSearchState(string param1, string param2, string param3, string param4)
{
    if (!string.IsNullOrWhiteSpace(param1))
    {
        if (param1.Equals("Kort", StringComparison.InvariantCultureIgnoreCase))
        {
            ViewType = "Map";

            if (!string.IsNullOrWhiteSpace(param2) && !string.IsNullOrWhiteSpace(param3) && !string.IsNullOrWhiteSpace(param4))
            {
                Country = param2.ToUnfriendlyUrl();
                Area = param3.ToUnfriendlyUrl();
                SubArea = param4.ToUnfriendlyUrl();
                SearchType = SearchStateType.Address;
            }
            else if (!string.IsNullOrWhiteSpace(param2) && !string.IsNullOrWhiteSpace(param3))
            {
                SearchType = param2.StartsWith("@") ? SearchStateType.Coordinates : SearchStateType.Address;
                Area = param3.ToUnfriendlyUrl();
                Country = param2.ToUnfriendlyUrl();
            }
            else if (!string.IsNullOrWhiteSpace(param2) && param2.StartsWith("@"))
            {
                SearchType = SearchStateType.Coordinates;
                Area = param2;
            }
            else if (!string.IsNullOrWhiteSpace(param2))
            {
                SearchType = SearchStateType.Address;
                Area = param2.ToUnfriendlyUrl();
            }
            else
            {
                SearchType = SearchStateType.Empty;
            }
        }
        else
        {
            ViewType = "Default";

            if (!string.IsNullOrWhiteSpace(param1) && !string.IsNullOrWhiteSpace(param2) && !string.IsNullOrWhiteSpace(param3))
            {
                Country = param1.ToUnfriendlyUrl();
                Area = param3.ToUnfriendlyUrl();
                SearchType = SearchStateType.Address;
                SubArea = param2.ToUnfriendlyUrl();
            }
            else if (!string.IsNullOrWhiteSpace(param1) && !string.IsNullOrWhiteSpace(param2))
            {
                Area = param2.ToUnfriendlyUrl();
                SearchType = SearchStateType.Address;
                Country = param1.ToUnfriendlyUrl();
            }
            else if (!string.IsNullOrWhiteSpace(param1) && param1.StartsWith("@"))
            {
                SearchType = SearchStateType.Coordinates;
                Area = param1;
            }
            else if (!string.IsNullOrWhiteSpace(param1))
            {
                SearchType = SearchStateType.Address;
                Area = param1.ToUnfriendlyUrl();
            }
            else
            {
                SearchType = SearchStateType.Empty;
            }
        }
    }
    else
    {
        SearchType = SearchStateType.Empty;
    }
}


texts:
I have here a snippet of code from a simple video game AI enemy.  The basic idea behind the enemy is that he can be in one of a few states.  By default he is in a patrolling state, where he moves around at a slow speed to random points within a circle.  While in this state, he is rolling every X seconds to switch to one of his more interesting states.  Currently, he may either transition into a state where he spins rapidly while patrolling as stated above, but at a much faster move speed. Or he will can instead go into a stationary defensive spin.  Here is the current method which handles this state change:

IEnumerator RollForStateChange()
{
    while (true)
    {
        yield return new WaitForSeconds(RollTickTime);

        if (CanRollForStateChange)
        {
            float spinAttackRoll = Random.Range(0, 100);

            if (spinAttackRoll <= SpinAttackChancePerTick)
            {
                StartCoroutine(SpinAttackTimer());
                continue;
            }

            float spinDefenseRoll = Random.Range(0, 100);

            if(spinDefenseRoll <= SpinDefenceChancePerTick)
            {
                StartCoroutine(DefenseSpinTimer());
                continue;
            }
        }
    }
}

While this sort of dice rolling method works just fine for now, I can't help but feel that it is more likely to choose the spin attack, since that roll goes first.  I can also see this becoming more inefficient if I wanted to add more states for the enemy to transition into.  However, I am struggling to come up with a more elegant way to decide which state the enemy should go into.


texts: Is it a good practice to use only one database instance?

texts:
I want to ask whether is good practice to have single instance of database connection or declare new every times when we needed? I have this two designs shown in below:

This is database class:

<?php
class Database extends PDO {
    //Variable declaration
    private $host = "localhost";
    private $passwd = "";
    private $username = "root";
    private $dbname = "";

    //Connect to DB when the class construct
    public function __construct($host=NULL, $dbname=NULL, $username=NULL, $passwd=NULL) {
        if(isset($host) && !empty($host)) {
            $this->host = $host;
        }

        if(isset($dbname) && !empty($dbname)) {
            $this->dbname = $dbname;
        }

        if(isset($username) && !empty($username)) {
            $this->username = $username;
        }

        if(isset($passwd) && !empty($passwd)) {
            $this->passwd = $passwd;
        }

        parent::__construct("mysql:dbname=$this->dbname;host=$this->host", $this->username, $this->passwd, NULL);
        parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        parent::setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    }

}
?>

Method 1: Dependency Injection

<?php
class User {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    //Some update and insert below here
}

class Employee {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    //Some update and insert below here
}
?>

So, I will do this when I want to use the classes:

<?php
    $db = new Database();

    $user = new User($db);
    $user->update($id,$data);

    $emp = new Employee($db);
    $emp->delete($id);
?>

or the other ways?

Method 2:

<?php
class User {
    private $db;

    public function __construct() {
        $this->db = new Database();
    }

    //Some update and insert below here
}

class Employee {
    private $db;

    public function __construct() {
        $this->db = new Database();
    }

    //Some update and insert below here
}
?>

and when I want to use it I will:

<?php
    $user = new User();
    $user->update($id,$data);

    $emp = new Employee();
    $emp->delete($id);
?>

Which method is preferable or better?  Offer an explanation if possible.


texts:
I'm making a bot that will be used for "points" tracking and such, like a reward system and I'm using Ecto with postgrex, this is my approach so far, it works but I'm not sure if I'm doing it in an "Elixir", functional way or if I can improve this a bit ^-^

defmodule Cord.Commands do
  ...
  def add_me(msg) do
    case Repo.get_by(Rewards, user: msg.author.id) do
      # Adds user if it doesn't exist
      nil ->
        case Repo.insert(%Rewards{user: msg.author.id}) do
          {:ok, _struct} ->
            Api.create_message(msg.channel_id, ":white_check_mark:")
          {:error, _changeset} ->
            Api.create_message(msg.channel_id, ":x:")
        end
      _ ->
        Api.create_message(msg.channel_id, "You're already registered")
    end
  end

  # Maps to each id in the list and updates each one
  def thanks(msg) do
    Enum.map msg.mentions, fn user ->
      repo_user = Repo.get_by(Rewards, user: user.id)
      points = repo_user.quantity
      repo_user = Ecto.Changeset.change(repo_user, quantity: points + 1)
      Repo.update!(repo_user)
      Api.create_message(msg.channel_id, "#{msg.author.username} gave a :cookie: to #{user.username}")
    end
  end

  def not_found(_), do: IO.inspect :ignore
end


texts:
I have a text file composed of several subsequent tables. I need to get certain values from certain tables and save them in an output file. Every table has a header which contains a string that can be used to find specific tables. The size of these text files can vary from tenths of MB to some GB. I have written the following script to do the job:

string = 'str'
index = 20
n = 2

in_file = open('file.txt')
out_file = open("out.txt", 'w')
current_line = 0

for i in range(-index,index+1):
    for j in range(-index,index+1):
        for line in in_file:
            if string in line:
                En = line.split().pop(4)
                for line in in_file:
                    current_line += 1
                    if current_line == 2*(n+1)+2:
                        x = line.split().pop(10)
                    elif current_line == 3*(n+1)+2:
                        y = line.split().pop(10)
                    elif current_line == 4*(n+1)+2:
                        z = line.split().pop(10)
                        current_line = 0
                        break
                print i, j, En, x, y, z
                data = "%d %d %s %s %s %s\n" % (i,j,En,x,y,z)
                out_file.write(data)
                break
in_file.close()
out_file.close()

The script reads the file line by line searching for the specified string ('str' in this example). When found, it then extracts a value from the line containing the string and continue reading the lines that form the data table itself. Since all the tables in the file have the same number of lines and columns, I've used the variable current_line to keep track of which line is read and to specify which line contains the data I need. The first two for-loops are just there to generate a pair of indexes that I need to be printed in the output file (in this case they are between -20 and 20).

The script works fine. But since I've been learning python by myself for about one month, and the files I have to handle can be very big, I'm asking for advices on how to make the script more efficient, and overall, better.

Also, since the tables are regular, I can know beforehand which are the lines that contain the values I need. So I was wondering, instead of reading all the lines in the file, is it possible to specify which lines have to be read and then jump directly between them?

Sample input file

Here's a sample input file. I've included just some tables so you can have an idea how it's organized. This file is composed by two blocks with three tables each. In this sample file, the string "table   #" is what is used to find the data to be extracted.

Sample output file

And here's a sample output file. Keep in mind that these two files are not equivalent! This output was created by my script using an input file containing 1681 blocks of 16 tables. Each table had 13 lines just as in the sample input file.


texts: Error Handling - Controller's OnException and Application_Error

texts:
I'm pretty new to MVC. Below is the code that I have added to an existing MVC 5 application.  The code is using log4net to log any run-time error/exception.

NOTE: I could override OnException() in MVC filter "HandleErrorAttribute" but I preferred to have this functionality in my custom Controller base class.

Can anyone please review and provide feedback?

BaseController.cs

public class BaseController: Controller
{
    private log4net.ILog logger;

    protected override void OnException(ExceptionContext filterContext)
    {
        //Log error
        logger = log4net.LogManager.GetLogger(filterContext.Controller.ToString());
        logger.Error(filterContext.Exception.Message, filterContext.Exception);

        //If the request is AJAX return JSON else redirect user to Error view.
        if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            //Return JSON
            filterContext.Result = new JsonResult
            {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { error = true, message = "Sorry, an error occurred while processing your request." }
            };
        }
        else
        {
            //Redirect user to error page
            filterContext.ExceptionHandled = true;
            filterContext.Result = this.RedirectToAction("Index", "Error");
        }
        base.OnException(filterContext);
    }
}

HomeController.cs

public class HomeController : BaseController
{
    ...
}

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));

    protected void Application_Error(object sender, EventArgs e)
    {
        //Log exception
        Exception exception = Server.GetLastError();
        log.Error(exception);

        //Clear error from response stream
        Response.Clear();
        Server.ClearError();

        //Redirect user
        Context.Server.TransferRequest("~/Error/");
    }
    ...
}

For displaying errors, I have a basic ErrorController.cs with just Index() Action along with its associated Error/Index.cshtml.

Some blogs suggests different error pages for different type of errors (such as 404 error). Do I need to handle them separately?

Please share if you have any ideas to improve upon my code in terms of usability and logging details.


texts: Vba to create a new column and insert array formula

texts:
My below code is the slowest sub in my workbook. I can't set it to put the Array in immediatley, because the mode is calculated incorrectly (calculates for just one site no)

Is there a way to cut this down without breaking the fully functioning code?

Sub ModeColumn()

Dim wb As Workbook, ws As Worksheet, LastRow As Long, rng As Range

Set wb = ThisWorkbook
Set ws = Worksheets("Data")
Set rng = ws.Cells(2, 15)
    ws.Cells(1, 15) = "MODE"
    LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row                  'Finds the bottom populated row

    With ws.Range(ws.Cells(2, 15), ws.Cells(LastRow, 15))
           .Formula = "=IFERROR(MODE(IF(RC[-2]=AllSites,R2C12:R" & LastRow & "C12)),""N/A"")"
           .FormulaArray = .FormulaR1C1
    End With

End Sub

Here's what it looks like working

So above we can see that the selection works perfectly, but if I use the array formula right away, I get a lot of errors - so my time saving, breaks the expected result
And here's what it looks like if I just use "array" straight away

This is based on the following code

With ws.Range(ws.Cells(2, 15), ws.Cells(LastRow, 15))
       .FormulaArray = "=IFERROR(MODE(IF(RC[-2]=AllSites,R2C12:R" & LastRow & "C12)),""N/A"")"
End With

P.S I cannot (by request) use Excel Tables to make this easier


texts: Finding out the indices of common elements in two array lists having duplicate elements

texts:
I have two lists which are also  having some duplicate elements , i am converting this list to map as key value pair with element index as the value for the key - element

List 1 : [1, 2, 3, 4, 5, 6, 7, 2] = >

MAP 1 (Map, List>) : {1=[0], 2=[1, 7], 3=[2], 4=[3], 5=[4], 6=[5], 7=[6]}

List 2 : [3, 3, 2, 4, 7]

= > MAP 2 (Map, List>) : {2=[2], 3=[0, 1], 4=[3], 7=[4]}

i am trying to collect matching keys from both of the maps and club it another map

For above two it would give the result : {[2]=[0, 1], [3]=[3], [6]=[4], [1, 7]=[2]}

Post this , i am taking the cartesian product of key , values and only retaining the unique elements

Final output [[0, 2], [1, 2], [3, 3], [4, 6], [2, 1], [2, 7]] . These is the indices of common elements

Below is the code that i have come up with to achieve this , is there any better way i can achieve the same . I feel it will be too much costly at run time for larger lists .

 List<List<Integer>> cartesianProduct = new ArrayList<>();
 List<String> distinct1 = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "2")
 List<String> distinct2 = Arrays.asList["3", "3", "2", "4", "7"]

 Map<String, List<Integer>> result1 = IntStream.range(0, distinct1.size()).boxed()
                     .collect(Collectors.groupingBy(i -> distinct1.get(i)));

 Map<String, List<Integer>> result2 = IntStream.range(0, distinct2.size()).boxed()
                    .collect(Collectors.groupingBy(i -> distinct2.get(i)));

 result1.entrySet().stream()
                    .filter(x -> result2.containsKey(x.getKey()))
                    .collect(Collectors.toMap(x -> x.getValue(), x -> result2.get(x.getKey())))
                    .entrySet().forEach(a1 -> a1.getValue().stream()
                    .forEach(b1 -> a1.getKey().stream().forEach(c1 -> cartesianProduct.add(Arrays.asList(b1, c1)))));

   List<List<Integer>> listWithoutDuplicates = cartesianProduct.stream()
           .distinct()
           .collect(Collectors.toList());