texts: Performing non-production analytics on data

texts:
I have the following Lua script which I use against my redis environment to perform some non-production analytics on my data.

My dataset contains hundreds of millions of records, hence I want to make sure that the approach that I am taking is optimal for query performance and best coding practices.

-- Tables to store the aggregations
local aUsers = {}           -- [sizeInBytes] = userID      (Table is created the other way around to allow for sorting)
local aFileTypes = {}       -- [fileTypeID] = sizeInBytes
local aFileTag = {}         -- [fileTagID] = sizeInBytes

-- Global Count of Records and Sum of Sizes in Bytes
local sumCount = 0
local sumSize = 0

-- For users 'sizeBytes' is the Table[ID] to allow sorting. Collissions are not a big deal
local function userAgregations(table, key, size)
    table[size] = key
end

-- For other agregations the `fieldID` is the key mapped against the `size` agregation
local function genericAgregations(table, key, size)
    if table[key] then
        table[key] = table[key] + size
    else
        table[key] = size
    end
end

-- For users only, sort the table by Key (size) and print return it
local function printTopUsers(t)
    local str = "["
    local sortedTable = {}
    local maxResults = 25

    for key in pairs(t) do
        sortedTable[#sortedTable+1] = key
    end

    table.sort(sortedTable, function(a,b)
        return a > b
    end)

    if #sortedTable < 25 then
        maxResults = #sortedTable
    end

    for i=1, maxResults do
        str = str .. sortedTable[i] .. ":" .. t[sortedTable[i]] .. ","
    end

    local formatted = str .. "]"
    return formatted
end

-- For other fields just return the table
local function printTable(t)
    local str = "["
    for key,value in pairs(t) do
        str = str .. key .. ":" .. value .. ","
    end

    local formatted = str .. "]"
    return formatted
end

-- Return all the keys in redis that match a given pattern (Yes, its non-production)
-- Where the keys are:  0:0000:00:00000:00:00:00:0
-- Sample query is:     5:123?:??:12346:1?:??:??:2--
local matches = redis.call("KEYS", query)

-- For each Key match, get the value and perform the agregations
for _,key in ipairs(matches) do
    local val = redis.call("GET", key)
    local sCount, sSize = val:match("([^:]+):([^:]+)")
    local count = tonumber(sCount)
    local size = tonumber(sSize)

    -- Extract a part of the key which refers to a particular agregation fieldID
    userAgregations(aUsers, string.sub(key, 11, 15), size)
    genericAgregations(aFileTypes, string.sub(key, 17, 18), size)
    genericAgregations(aFileTags, string.sub(key, 17, 18), size)

    -- Increment the Global sum and count
    sumCount = sumCount + count
    sumSize = sumSize + size
end

-- Contatenate and return response
local globalAgregation = string.format("[%s:%s]", sumCount, sumSize)
local result = printTopUsers(aUsers) .. printTable(aFileTypes) .. printTable(aFileTags) .. globalAgregation

return result


texts: Single pass algorithm for finding the topX percent of items

texts:
I'm looking for a single-pass algorithm for finding the topX percent of floats in a stream where I do not know the total number ahead of time ... but its on the order of 5-30 million floats. It needs to be single-pass since the data is generated on the fly and recreate the exact stream a second time.

The algorithm I have so far is to keep a sorted list of the topX items that I've seen so far. As the stream continues I enlarge the list as needed. Then I use bisect_left to find the insertion point if needed.

Below is the algorithm I have so far:

from bisect import bisect_left
from random import uniform
from itertools import islice

def data_gen(num):
    for _ in xrange(num):
        yield uniform(0,1)

def get_top_X_percent(iterable, percent = 0.01, min_guess = 1000):

    top_nums = sorted(list(islice(iterable, int(percent*min_guess)))) #get an initial guess

    for ind, val in enumerate(iterable, len(top_nums)):
        if int(percent*ind) > len(top_nums):
            top_nums.insert(0,None)
        newind = bisect_left(top_nums, val)
        if newind > 0:
            top_nums.insert(newind, val)
            top_nums.pop(0)

    return top_nums

if __name__ == '__main__':

    num = 1000000
    all_data = sorted(data_gen(num))
    result = get_top_X_percent(all_data)
    assert result[0] == all_data[-int(num*0.01)], 'Too far off, lowest num:%f' % result[0]
    print result[0]

In the real case the data does not come from any standard distribution (otherwise I could use some statistics knowledge).

Any suggestions would be appreciated.


texts: PHP recreate array if it contains certain values

texts:
I have $fruits_arr:

Array
(
    [0] => Array
        (
            [id] => 213
            [fruit] => banana
        )

    [1] => Array
        (
            [id] => 438
            [fruit] => apple
        )

    [2] => Array
        (
            [id] => 154
            [fruit] => peach
        )
)

And $ids_arr:

Array (
  [0] => 213
  [1] => 154
)

I want to recreate $fruits_arr to have only array items where id is equal to a value from $ids_arr. I also want to maintain the index/array order of $fruits_arr.

I'm using the following:

$selected_fruits = array();

foreach( $fruits_arr as $fruit ) :
    if ( in_array( $fruit['id'], $ids_arr ) ) :
        $selected_fruits[] = $fruit;
    endif;
endforeach;

print_r( $selected_fruits );

It seems to work but I am wondering if there is a shorter, better way to accomplish this in the latest PHP version.


texts: Invoking functions using a function pointer approach

texts:
I re-used this answer from this StackOverflow answer to simulate a function pointer approach available in high-level languages like C.

While using this approach in Python, the dictionary I am defining to map the functions needs to be defined after all the functions are defined before. It makes the dictionary definition to be the last segment of the code, which doesn't look neat.

Is there a way like in C to export all the functions beforehand, so that I can define the mapping dictionary in the beginning? (See examples below). Or what would be the most pythonic approach to do this?

Below is my sample snippet of the code using the approach.

File-1 - a1.py

#!/usr/bin/env python

from a2 import *

def arithmeticOps():
    doOps('add',6,1)
    doOps('mul',6,4)

if __name__ == '__main__':
    arithmeticOps()

and File-2 - a2.py

#!/usr/bin/env python

def doOps(op, arg1, arg2):
    arithDict[op](arg1,arg2)

def doAdd(arg1, arg2):
    print "Sum =",arg1 + arg2

def doProd(arg1, arg2):
    print "Prod =",arg1 * arg2

arithDict = {
    'add': doAdd,
    'mul': doProd
}

I am able to run this code peacefully in Python 2.7, and it gives me the result I need.

# python a1.py
Sum = 7
Prod = 24

I agree the built-in functions for addition (or) product could be used here, but the problem is for a bigger scale when I have custom functions in place.


texts:
Is there an effective way, maybe with regex, to change the following text pattern?

I have a string like abc_def_ghi_jkl. I want to replace it to AbcDefGhiJkl.  I currently use the following code to change it. Is there a more effective way than this?

implode('',array_map('ucfirst',explode('_',$string)));


texts:
Looking for a way to efficiently use 3rd party CSV reader without making a dependency on it. I would also prefer to make my class be available everywhere (not just in IoC container injectable Services), so I decided to go with a questionable decision – configure through the static property. Can you see a way to reduce amount of library code or make configuration more obvious without losing library handiness?

Repository at GitHub.

Project dependencies are:

And solution looks like this:

MyProject.Demo registers CSV library parser dependency and parses the CSV file:

class Program
{
    static void Main(string[] args)
    {
        CsvRowReader.Use();

        var text = "First,Last\nJohn,Doe\n";
        var file = NameFile.Parse(text);
        foreach (var name in file)
            WriteLine($"{name.First} {name.Last}");
    }
}

Business logic assembly MyProject defines NameFile as:

public class NameFile : RowFile<NameFile, FullName>
{
    protected override IEnumerable<FullName> Read(RowReader reader)
    {
        using(reader)
            while (reader.Read())
                yield return new FullName
                {
                    First = reader.Get<string>("First"),
                    Last = reader.Get<string>("Last")
                };
    }
}

Where FullName is:

public class FullName
{
    public string First { get; set; }
    public string Last { get; set; }
}

Using library class RowFile<TFile, TRow>:

public abstract class RowFile<TFile, TRow> : Enumerable<TRow>
    where TFile : RowFile<TFile, TRow>, new()
{
    public static readonly TFile Empty = new TFile();

    public static TFile Parse(string text) =>
        Load(new StringReader(text));

    public static TFile Load(string filePath) =>
        Load(File.OpenText(filePath));

    public static TFile Load(Stream stream) =>
        Load(new StreamReader(stream));

    public static TFile Load(TextReader reader)
    {
        var file = new TFile();
        file.Rows = file.Read(RowReader.Create(reader));
        return file;
    }

    public sealed override IEnumerator<TRow> GetEnumerator() =>
        Rows.GetEnumerator();

    protected abstract IEnumerable<TRow> Read(RowReader read);
    IEnumerable<TRow> Rows { get; set; } = new TRow[0];
}

Where:

public abstract class RowReader : IDisposable
{
    public static Func<TextReader, RowReader> Create { get; protected set; }
    public abstract void Dispose();
    public abstract bool Read();
    public abstract T Get<T>(string name);
}

And:

public abstract class Enumerable<T> : IEnumerable<T>
{
    public abstract IEnumerator<T> GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() =>
        GetEnumerator();
}

3rd party CSV reader dependency is incapsulated in MyProject.CsvHelper project:

public class CsvRowReader : RowReader
{
    public static void Use() =>
        Create = reader => new CsvRowReader(reader);

    CsvRowReader(TextReader reader)
    {
        Reader = new CsvReader(reader);
        Reader.Read();
        Reader.ReadHeader();
    }

    CsvReader Reader { get; }

    public override void Dispose() =>
        Reader.Dispose();

    public override bool Read() =>
        Reader.Read();

    public override T Get<T>(string name) =>
        Reader.GetField<T>(name);
}

I don’t like all those mutability things, but do not see a better solution at the moment...


texts:
I'm studying alone, so I don't know if I'm writing efficiently. Could this slot machine simulator be improved? How?

import acm.program.*;
import acm.util.*;

/*
 * THIS PROGRAM SIMULATES THE SLOT MACHINE
 */

public class cap6ex5 extends ConsoleProgram{

private RandomGenerator rgen = RandomGenerator.getInstance();

private int money = 50; //starting stake

private String value = "";

public void run(){

    String instAnswer = readLine("Would you like instructions?");

    while (!instAnswer.equals("yes") && !instAnswer.equals("no")) {
        instAnswer = readLine("Answer yes or no.");
    }
    if (instAnswer.equals("yes")) println("YOU SHOUD KNOW!");

    startGame(money);

}
private void startGame(int x){
    String keepPlaying = "";
    int finalMoney = x;
    int prize = 0;
    while (finalMoney > 0){
        keepPlaying = readLine("You have $" + finalMoney +". Would you like to play?");
        //avoid different answers
        while(true){
            if (keepPlaying.equals("yes") || keepPlaying.equals("no")) break;
            keepPlaying = readLine("Asnwer yes or no.");

        }
        if (keepPlaying.equals("no")) break;

        finalMoney--;
        prize = gamePrize();
        finalMoney += prize;
        println(value + "     -- You win $" + prize);
    }

    println("Okay, bye. You ended with $" + finalMoney);
}
private int gamePrize(){
    int countBAR = 0;   //BAR == 1
    int countBELL = 0;  //BELL == 2
    int countPLUM = 0;  //PLUM == 3
    int countORANGE = 0;//ORANGE == 4
    int countCHERRY = 0;//CHERRY == 5
    value = "";

    for (int i = 1; i <= 3 ; i++){
        int x = rgen.nextInt(1, 6);

        switch(x){
            case 1:
                countBAR++;
                value += "BAR ";
                break;
            case 2:
                countBELL++;
                value += "BELL ";
                break;
            case 3:
                countPLUM++;
                value += "PLUM ";
                break;
            case 4:
                countORANGE++;
                value += "ORANGE ";
                break;
            case 5:
                countCHERRY++;
                value += "CHERRY ";
                break;
            case 6: value += "LEMON "; break;
        }

    }

    return result(countBAR, countBELL, countPLUM, countORANGE, countCHERRY);

}
private int result(int bar, int bell, int plum, int orange, int cherry){
    int prize = 0;
    if (bar == 3){
        prize = 250;
    } else if ((bell > 1 && bar ==1) || bell == 3){
        prize = 20;
    } else if ((plum > 1 && bar == 1) || plum == 3){
        prize = 14;
    } else if ((orange >1 && bar == 1) || orange == 3){
        prize = 10;
    } else switch(cherry){
        case 1: prize = 7; break;
        case 2: prize = 5; break;
        case 3: prize = 2; break;
    }
    return prize;
}

}

Here are the prize rules:

  BAR BAR BAR = $250
  BELL BELL BELLorBAR = $20
  PLUM PLUM PLUMorBAR = $14
  ORANGE ORANGE ORANGEorBAR = $10
  CHERRY CHERRY CHERRY = $7
  CHERRY CHERRY --- = $5
  CHERRY --- --- = $2


texts: How can I make this WHERE clause more readable?

texts:
Without changing the semantics and performance, how can I make this where clause more readable?

where
(@Category = 'all' or
    (@Category = 'omitted' and Category is null) or
    (@Category = Category and (
        @SubCategory = 'all' or
        (@SubCategory is null and SubCategory is null) or
        (@SubCategory = SubCategory and (
            @SubSubCategory = 'all' or
            (@SubSubCategory is null and SubSubCategory is null) or
            @SubSubCategory = SubSubCategory
        ))
    ))
)

At a high level, this clause represents a user query where the user has optionally specified a category, subcategory, and sub-subcategory on a table.  For compatibility reasons, I cannot change any semantics (e.g., I cannot improve consistency by using @Category is null instead of @Category = 'omitted')


texts: LINQ for generating all possible permutations

texts:
Permutate() is supposed to generate all possible permutations of the source sequence:

foreach(var s in "abc".Permutate())
    Console.WriteLine(s); // abc
                          // acb
                          // bac
                          // bca
                          // cab
                          // cba

Where:

    public static IEnumerable<string> Permutate(this string source) =>
        source.AsEnumerable().Permutate().Select(a => new string(a));

    public static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> source)
    {
        return permutate(source, Enumerable.Empty<T>());
        IEnumerable<T[]> permutate(IEnumerable<T> reminder, IEnumerable<T> prefix) =>
            !reminder.Any() ? new[] { prefix.ToArray() } :
            reminder.SelectMany((c, i) => permutate(
                reminder.Take(i).Concat(reminder.Skip(i+1)).ToArray(),
                prefix.Append(c)));
    }

Any optimizations? Could it be shorter?


texts:
public class ArrayUtil {

    /**
     * Field INPUT_LESS_THAN_TWO. (value is 2)
     */
    private static final int INPUT_LESS_THAN_TWO = 2;

    /**
     * Method removeDuplicateElement. Given a sorted array of integers, this
     * method removes the duplicate elements. Input array is sorted array and
     * can have only negative values, only positive value or a mix of both.
     *
     * @param inputArray
     *            int[]
     *
     * @return int[]
     * @throws IllegalArgumentException
     */
    public int[] removeDuplicateElement(final int[] inputArray)
            throws IllegalArgumentException {

        int j = 0; // Marks the begining of the array
        int i = 1; // Points toward the second element in the array

        if (null == inputArray || 0 == inputArray.length) {
            throw new IllegalArgumentException(
                    "Input Array is either null or of zero length");
        } // end of null and 0 length check

        // Return if the input array has only one item
        if (inputArray.length < INPUT_LESS_THAN_TWO) {
            return inputArray;
        } // end of check for length less than 2
        while (i < inputArray.length) {
            if (inputArray[i] == inputArray[j]) {
                i++;
            } else {
                inputArray[++j] = inputArray[i++];
            }
        } // end of while loop

        // copy and return the array
        final int[] outputArray = new int[j + 1];
        for (int k = 0; k < outputArray.length; k++) {
            outputArray[k] = inputArray[k];
        }

        return outputArray;
    }

}

I believe that the time complexity of this algorithm is \$O(N)\$.


texts: Advent of Code #4 in Haskell - Ascending digits with double digit

texts:
This problem is from Advent of Code day 4 (part 1). The problem is to find the number of ints in the given range satisfying:

all digits are non decreasing
there is at least one group of at least two equal digits in a row

combinations only generates non-decreasing sequences; for example:

λ> combinations 2 ['1'..'3']
["11","12","13","22","23","33"]

The algorithm generates all non-decreasing combinations from ['0'..'9'], then checks that there's at least one repeating character, that there are no leading zeros, and that the number is in range. Running it with the input 125730-579381 correctly prints 2081.

The main things I want to know about are whether there's a way to improve the algorithm, and whether the readability is good.

import Data.List (tails, group)
import Control.Arrow
import Control.Monad

-- all non-decreasing combinations of k from xs
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations k xs = do
  xs'@(x:_) <- tails xs
  map (x:) $ combinations (pred k) xs'

-- return True iff all predicates are satisfied
allF :: [a -> Bool] -> a -> Bool
allF fs x = and $ map ($ x) fs

-- all ints within the range satisfying:
  -- strictly increasing digits
  -- at least one sequence of exactly 2 of the same digit
solve :: Int -> Int -> Int
solve low hi = length . takeWhile (<= hi) . dropWhile (< low) . map read .
  filter (allF [hasDouble, noLeadingZeros]) $ combinations 6 ['0'..'9']
  where hasDouble = any ((> 1) . length) . group
        noLeadingZeros = (/= '0') . head

main :: IO ()
main = do
  (low, high) <- join (***) read <$> second tail <$> span (/= '-') <$> getLine
  print $ solve low high


texts:
This works, but there must be a better, more memory-efficient way to do it.

log.Init checks to make sure log file exists, and creates it if it doesn't. It also sets a maximum file size for the log file.

package log

import (
    "errors"
    "fmt"
    "io/ioutil"
    "os"
    "time"
)

var logFile string
var fileLimit int

func Init(dir, name string, l int) error {
    fileLimit = l
    p := dir + "/" + name
    info, err := os.Stat(p)
    if err != nil {
        if os.IsNotExist(err) {
            err := os.MkdirAll(dir, os.ModePerm)
            if err != nil {
                return errors.New("Unable to create directory: " + err.Error())
            }

            _, err = os.Create(p)
            if err != nil {
                return errors.New("Unable to create log file: " + err.Error())
            }

            logFile = p
            return nil
        }

        return errors.New("Unable to stat log file: " + err.Error())
    }

    if info.IsDir() {
        return errors.New("File name is directory")
    }

    logFile = p
    return nil
}

func Append(message string) {
    file, err := os.OpenFile(logFile, os.O_APPEND|os.O_WRONLY, 0600)
    if err != nil {
        fmt.Printf("Unable to open log file: %s\n%s\n", err, message)
        return
    }
    defer file.Close()

    if _, err = file.WriteString("[" + time.Now().Format(time.ANSIC) + "] " + message + "\n"); err != nil {
        fmt.Printf("Unable to write to log file: %s\n%s\n", err, message)
        return
    }

    fi, err := os.Stat(logFile)
    if err != nil {
        fmt.Println("Unable to stat log file: " + err.Error())
        return
    }

    fileSize := int(fi.Size())
    if fileSize > fileLimit {
        b, err := ioutil.ReadFile(logFile)
        if err != nil {
            fmt.Println("Unable to read log file" + err.Error())
            return
        }

        err = file.Truncate(0)
        if err != nil {
            fmt.Println("Unable to truncate log file" + err.Error())
            return
        }

        new := b[fileSize-fileLimit:]
        _, err = file.Write(new)
        if err != nil {
            fmt.Println("Unable to write to log file" + err.Error())
            return
        }
    }
}


texts: Review internet connection pinging method

texts:
This is some C code I have to simply test the internet connection.  Any comments/tips on efficiency and refactoring this program down would be greatly appreciated.

int testConnection(void)
{
    int status;
    struct addrinfo host_info;
    struct addrinfo *host_info_list;
    memset(&host_info, 0, sizeof host_info);
    #ifdef DEBUG
    fprintf(stdout,"Setting up the structs...");
    #endif
    host_info.ai_family = AF_UNSPEC;     // IP version not specified. Can be both.
    host_info.ai_socktype = SOCK_STREAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP.

    status = getaddrinfo("www.google.com", "80", &host_info, &host_info_list);
    if (status != 0)  fprintf(stdout, "Address info error:: %s\n", gai_strerror(status));

    #ifdef DEBUG
    fprintf(stdout, "Creating a socket...\n");
    #endif
    int socketfd ;
    socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol);
    if (socketfd == -1)  fprintf(stderr, "Socket error\n");

    #ifdef DEBUG
    fprintf(stdout, "Connecting...");
    #endif
    status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
    if (status < 0) fprintf(stderr, "Error while connecting.\n");

    #ifdef DEBUG
    fprintf(stdout, "Sending message...\n");
    #endif
    const char *msg = "GET / HTTP/1.1\nhost: www.google.com\n\n";
    int len = strlen(msg);
    ssize_t bytes_sent = send(socketfd, msg, len, 0);
    if (bytes_sent == 0) fprintf(stderr, "No bytes sent.\n");
    #ifdef DEBUG
    fprintf(stdout, "Bytes sent: %d\n", bytes_sent);
    fprintf(stdout, "Waiting to recieve data...\n");
    #endif
    char incomming_data_buffer[1000];
    ssize_t bytes_recieved = recv(socketfd, incomming_data_buffer,1000, 0);
    // If no data arrives, the program will just wait here until some data arrives.
    if (bytes_recieved == 0) fprintf(stderr, "Host shut down.\n");
    if (bytes_recieved == -1) fprintf(stderr, "Recieve error.\n");
    incomming_data_buffer[bytes_recieved - 2] = '\0';
    #ifdef DEBUG
    fprintf(stdout, "Bytes recieved: %d\n", bytes_recieved);
    fprintf(stdout, "%s\n", incomming_data_buffer);
    fprintf(stdout, "Receiving complete. Closing socket...\n");
    #endif
    freeaddrinfo(host_info_list);
    close(socketfd);
    #ifdef DEBUG
    fprintf(stdout, "Socket closed.\n");
    #endif
    return 0;
}


texts:
I'm working through the Free Code Camp syllabus and I'm on to Intermediate JavaScript Algorithms. This Pairwise problem was the last challenge in that section. The section came just after "Object Oriented JavaScript." So I figured they were looking for an OO solution, but the instructions included a link to MDN's array.reduce(). My solution doesn't use array.reduce() and I'd really appreciate some feedback on  what I could have done better to make my code more compact and efficient. It feels a little clunky but passes all the tests.

The instructions

  Return the sum of all indices of elements of 'arr' that can be paired
  with one other element to form a sum that equals the value in the
  second argument 'arg'. If multiple sums are possible, return the
  smallest sum. Once an element has been used, it cannot be reused to
  pair with another.

  For example, pairwise([1, 4, 2, 3, 0, 5], 7) should return 11 because
  4, 2, 3 and 5 can be paired with each other to equal 7.

  pairwise([1, 3, 2, 4], 4) would only equal 1, because only the first
  two elements can be paired to equal 4, and the first element has an
  index of 0!

  Remember to use RSAP if you get stuck. Try to pair program. Write your
  own code.

  Here are some helpful links:

Array.reduce()

My Solution

function pairwise(arr, arg) {
    this.objects = [];
    var total = 0;

    function Element(value, index) {
        this.value = value;
        this.index = index;
        this.used = 0;
    }

    for (var i = 0; i < arr.length; i++) {
        this.objects.push(new Element(arr[i], i));
    }

    for (var j = 0; j < objects.length; j++) {
        if (objects[j].used === 0) {
            for (var k = 0; k < objects.length; k++) {
                if (objects[k].used === 0 && objects[k].index != objects[j].index) {
                    if (arg - objects[j].value == objects[k].value) {
                        total = total + objects[j].index + objects[k].index;
                        objects[j].used = 1;
                        objects[k].used = 1;
                        break;
                    }
                }
            }
        }
    }

    return total;
}

pairwise([1,1,1], 2);


texts: Finding area and perimeter of rectangles and circles that are instance of interface region

texts:
The missing code in task 1 were the methodsarea(), perimeter() and toString().
In task 2 I know that using built in collection such as Arraylist would be efficient and simpler,So any new different idea and implementation are appreciated.

Make the classes Circle and Rectangle complete: write the missing code.

A static method selectRectangle accepts an array of areas of type Region, and returns an array that only contains the areas that are of type Rectangle. Create that method.

Create an array that contains both circles (objects of type Circle) and rectangles (objects of type Rectangle). Write code that determines and shows the perimeter and area of these regions. Call the method selectRectangles with the created array as argument.

public interface Region {
    double area();
    double perimeter();
}

class Circle implements Region {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * radius;
    }

    @Override
    public double perimeter() {

        return Math.PI * 2 * radius;
    }
}

class Rectangle implements Region {
    private double with;
    private double length;

    public Rectangle(double with, double length) {
        this.length = length;
        this.with = with;
    }

    @Override
    public double area() {
        return length * with;
    }

    @Override
    public double perimeter() {
        return 2 * (length + with);
    }

    public String toString() {
       return "<" + this.with + this.with + this.area() + this.perimeter() + ">";
    }

    public static Rectangle[] selectRectangle(Region[] region) {
        int countRect = 0;

        for (int i = 0; i < region.length; i++) {
            if (region[i] instanceof Rectangle) {
                countRect++;
            }
        }
        Rectangle[] rect = new Rectangle[countRect];
        int companionVar = 0;
        for (int i = 0; i < region.length; i++) {
            if (region[i] instanceof Rectangle) {
                rect[companionVar++] = (Rectangle) region[i];
            }
        }
        return rect;
    }

    public static void main(String[] args) {
        Region[] region = {new Circle(5),
                new Rectangle(2, 4),
                new Circle(2),
                new Rectangle(7, 9),
                new Circle(6)

        };

        for (int i = 0; i < region.length; i++) {
            System.out.println(region[i].area() + region[i].perimeter());
        }

        Rectangle[] rectangle = selectRectangle(region);

    }

}


texts:
I have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits: 59853 -> 83559

Please let me know if there are any better solutions. I would like feedback how to improve this.

def next_bigger(num):
    numlist = [int(i) for i in str(num)]

    index_of_replace_num = -1
    i = len(numlist) - 1
    while i > 0:
        if numlist[i] > numlist[i-1]:
            index_of_replace_num = i - 1
            break
        i -= 1

    if index_of_replace_num == -1:
        return -1
    else:
        firstlist = numlist[:index_of_replace_num]
        replaced_num = numlist[index_of_replace_num]
        secondlist = numlist[index_of_replace_num+1:]
        new_replaced_num = 9
        i = 0
        delindex = 0
        while i < len(secondlist):
            if secondlist[i] > replaced_num and secondlist[i] < new_replaced_num:
                new_replaced_num = secondlist[i]
                delindex = i
            i += 1

        secondlist.pop(delindex)
        secondlist.append(replaced_num)
        firstlist.append(new_replaced_num)
        output = firstlist + sorted(secondlist)
        return int(''.join(str(x) for x in output))


texts: Initializing an Array of Alternating Values

texts:
My goal in this project is to make something that can—as, quickly, effectively, and efficiently as Array(repeating: , count: )—initialize an Array of alternating values.

Note: I am using Swift 4.1 and Xcode 9.3

My Array Initialization:

extension Array {
    init (repeatingValues arr: Array, count: Int) {
        precondition(!arr.isEmpty, "Initialization values cannot be empty")
        precondition(count > 0, "Count cannot be less than 1")
        var newArr = Array<Element>()
        for i in 0..<count {
            newArr.append(arr[i % arr.count])
        }
        self = newArr
    }
}

Usage

Initialization - init(repeatingValues: , count: ):

let array = Array(repeatingValues: [true, false], count: 10)

print(array) //prints: [true, false, true, false, true, false, true, false, true, false]

Benchmark Comparison

Comparing: Array(repeating: , count: ) vs. Array(repeatingValues: , count: )

Benchmark Time Extension:

extension Date {
      func elapsedTime(to date: Date) -> String {

        let attoseconds100 = date.timeIntervalSince(self) * 10000000000000

        switch attoseconds100 {
        case 6048000000000000000...:
            let weeks : Int = Int(attoseconds100 / 6048000000000000000)
            return "\(weeks)w" + " " + "\(Int(attoseconds100 / 864000000000000000) - (weeks * 7))d"

        case 864000000000000000...:
            let days : Int = Int(attoseconds100 / 864000000000000000)
            return "\(days)d" + " " + "\(Int(attoseconds100 / 36000000000000000) - (days * 24))h"

        case 36000000000000000...:
            let hours : Int = Int(attoseconds100 / 36000000000000000)
            return "\(hours)h" + " " + "\(Int(attoseconds100 / 600000000000000) - (hours * 60))m"

        case 600000000000000...:
            let mins : Int = Int(attoseconds100 / 600000000000000)
            return "\(mins)m" + " " + "\(Int(attoseconds100 / 10000000000000) - (mins * 60))s"

        case 10000000000000...:
            let secs : Int = Int(attoseconds100 / 10000000000000)
            return "\(secs)s" + " " + "\(Int(attoseconds100 / 10000000000) - (secs * 1000))ms"

        case 10000000000...:
            let millisecs : Int = Int(attoseconds100 / 10000000000)
            return "\(millisecs)ms" + " " + "\(Int(attoseconds100 / 10000000) - (millisecs * 1000))μs"

        case 10000000...:
            let microsecs : Int = Int(attoseconds100 / 10000000)
            return "\(microsecs)μs" + " " + "\(Int(attoseconds100 / 10000) - (microsecs * 1000))ns"

        case 10000...:
            let nanosecs : Int = Int(attoseconds100 / 10000)
            return "\(nanosecs)ns" + " " + "\(Int(attoseconds100 / 10) - (nanosecs * 1000))ps"

        case 10...:
            let picosecs : Int = Int(attoseconds100 / 10)
            return "\(picosecs)ps" + " " + "\(Int(attoseconds100 / 0.01) - (picosecs * 1000))fs"

        case 0.01...:
            let femtosecs : Int = Int(attoseconds100 * 100)
            return "\(femtosecs)fs" + " " + "\((Int(attoseconds100 / 0.001) - (femtosecs * 10)) * 100)as"
        case 0.001...:
            return "\(Int(attoseconds100 * 100000))as"

        default:
            return "Less than 100 attoseconds"
        }
    }
}

Array(repeating: , count: ):

let start = Date()
let _ = Array(repeating: true, count: 1000000)
let end = Date()
print(start.elapsedTime(to: end)) //2ms 470μs

Execution Time: 2ms 470μs

Array(repeatingValues: , count: ):

let start = Date()
let _ = Array(repeatingValues: [true, false], count: 1000000)
let end = Date()
print(start.elapsedTime(to: end)) //472ms 555μs

Execution Time: 472ms 555μs

Results:

Array(repeatingValues: , count: ) 191.3x slower than Array(repeating: , count: )

How can I match Apple's efficiency and speed?


texts:
I have implemented an Integer to Roman Numeral converter that converts any number in the range \$[1 \le x \le4999]\$ to its Roman number equivalent. Any comments on improving my code style or organization?

#include <string>
#include <iostream>

class Solution{
public:
    Solution () : IntVal {1,5,10,50,100,500,1000} , roman {'I', 'V' , 'X', 'L' ,'C', 'D' ,'M'} {}
    std::string intToRoman(int num);
private:
    int IntVal[7];
    char roman[7];
    int fslt(int num);
    std::string output;
    void helper(int num);
    void postProcess();
    void str_replace( std::string &s, const std::string &search, const std::string &replace);
};

#include "roman.hpp"

int Solution::fslt(int num){
    if (num>=50){
        if (num<100) return 3;
        else if (num>=100 && num < 500) return 4;
        else if (num>=500 && num < 1000) return 5;
        else return 6;
    }
    else{ // num < 50
        if (num>=10) return 2;
        else if (num>=5) return 1;
        else return 0;
    }
}

void Solution::helper (int num){
    int div = fslt(num);

    if (div == 0){
        for (int i = 0; i <num ;i++){
            output += roman[div];
        }
         return;
    }
    else {
        int rn = fslt(num);
        int numTimes = num/IntVal[rn];
        for (int i=0;i < numTimes; i++){
            output += roman[rn];
        }
        helper(num-numTimes*IntVal[rn]);
    }
}

void Solution::postProcess(){
    str_replace(output, "DCCCC", "CM");
    str_replace(output, "CCCC", "CD");
    str_replace(output, "LXXXX", "XC");
    str_replace(output, "XXXX", "XL");

    str_replace(output, "VIIII", "IX");
    str_replace(output, "IIII", "IV");
}

std::string Solution::intToRoman(int num){
    Solution::helper(num);
    Solution::postProcess();
    return output;
}

void Solution::str_replace( std::string &s, const std::string &search, const std::string &replace)
{
     for( size_t pos = 0; ; pos += replace.length() )
    {
         pos = s.find( search, pos );
         if( pos == std::string::npos ) break;

         s.erase( pos, search.length() );
         s.insert( pos, replace );
     }
}

int main(){
    Solution mySol;
    std::cout <<  mySol.intToRoman(4999) << std::endl;
    return 0;

}


texts:
This is currently the code that I'm using to validate and check for errors in a flask app, where the form fields are coming from a /registration html page:

@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        if request.form['register'] == 'Register':
            if request.form.get("eulacheck") != "on":
                return regError("Please read and agree to the Terms and Conditions and the License Terms.")
            if request.form['username'] == "":
                return regError("Please select a username.")
            if request.form['password1'] == "":
                return regError("Please enter a password.")
            if request.form['password2'] == "":
                return regError("Please confirm password.")
            if request.form['password1'] != request.form['password2']:
                return regError("Passwords did not match. Please enter passwords again.")
            username = request.form['username']
            password = request.form['password1']
            hash = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt())
            id = randint(1000,9999)
            if request.form['email1'] != "":
                if request.form['email2'] == "":
                    return regError("Please confirm email.")
                if request.form['email1'] != request.form['email2']:
                    return regError("Email addresses did not match. Please enter emails again.")
                email = request.form['email1']
                insert_db("INSERT INTO Users (ID, Username, Email, Hash) VALUES (?, ?, ?, ?)", (id, username, email, hash))
                flash("Account registration successfull! Please use your credentials to login below.")
                return render_template("login.html",pageType=['login'],flashType="info")
            insert_db("INSERT INTO Users (ID, Username, Hash) VALUES (?, ?, ?)", (id, username, hash))
            flash("Account registration successfull! Please use your credentials to login below.")
            return render_template("login.html",pageType=['login'],flashType="info")
    return render_template("register.html",pageType=['register'])

def regError(message):
    flash(message)
    return render_template("register.html",pageType=['register'],flashType="danger")

This code seems a bit messy and repetitive, is there a better way that I should be doing this?
  Thanks a lot!


texts:
I've build a handlebars helper that takes n total pages and currentPage and returns the HTML for the page number links, skipping out pages far away from the current page to avoid it being too big. I feel like there are a lot of if statements in there and it could be a bit more compact.

'use strict';

var config = require('config');
var pagesInGroup = config.pagesInGroup;

module.exports =  function(n, currentPage, block) {
    var accum = '';
    var preEllipsis = '';
    var postEllipsis = '';
    currentPage = parseInt(currentPage, 10);
    n = parseInt(n, 10);

    if (currentPage > (pagesInGroup / 2) + 1) {
        preEllipsis = '
...
';
    }
    if (currentPage < n - (pagesInGroup / 2)) {
        postEllipsis = '
...
';
    }

    if (currentPage === 1) {
        accum += '
1
'+preEllipsis;
    } else {
        accum += '
1
'+preEllipsis;
    }

    for(var page = 2; page < n; page++) {
        if (page !== currentPage && page <= currentPage + (pagesInGroup / 2) && page >= currentPage - (pagesInGroup / 2)) {
          accum += '
'+page+'
';
        } else if (page === currentPage) {
          accum += '
'+page+'
';
        }
    }

    if (n === currentPage && n>1) {
        accum += postEllipsis+'
'+n+'
';
    } else if (n>1) {
        accum += postEllipsis+'
'+n+'
';
    }

    return accum;
};


texts: Initializing an Android activity by reading a CSV file with image IDs, names, and descriptions

texts:
I am using Java to create an Android app. I have the main activity read a CSV file, create objects, and then save them into a singleton class so the rest of the activities in the app can access them easily.

This is working perfectly fine but I am not sure if there are some other ways to achieve the same result that are considered better practice, or if perhaps my solution could cause issues down the line that I am not aware of.

MainActivity extends AppCompatActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    createItemObjects();
}

public void createItemObjects(){
    InputStream is = getResources().openRawResource(R.raw.items_csv);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

    ArrayList<Item> items = new ArrayList<Item>();
    String line = "";
    try {
        while((line = reader.readLine())!=null) {
            String[] values = line.split(",");
            String img = values[0];
            int imgID = getResources().getIdentifier(img , "drawable", getPackageName());
            items.add(new Item(imgID, values[1], values[2]));
        }
    } catch (IOException e) {
        Log.v("Main Activity", "Error Reading File on Line " + line, e);
        e.printStackTrace();
    }
    ItemListHolder.getInstance().setItemsArrayList(items);
}

So as you can see, when the app launches it reads the CSV file, creates Item objects, creates an ArrayList to store those Item objects, then sends it into the ItemListHolder singleton, so that all the Activities in the app can use ItemListHolder.getInstance().getItemsArrayList() to retrieve the ArrayList of Item.  Each Item is constructed with an image ID, name, and description from a line in the CSV file.

This works without any issues, but my question is: Is having your Android app create objects from a CSV file everytime it restarts considered good practice/safe to use/efficient ect, or should you be storing your objects in some other way, such as shared preferences, so that they are actually saved in memory and do not need to be created everytime the app launches and then held inside a class.

I am familiar with Java but am very new to Android so I really have no idea what other ways of saving objects may or may not exist, or what is considered good to use.  Is it better to save them to the fileOutputStream? Is it better to save them to sharedPreferences? Is there some other storage method that is better?


texts:
I previously attempted to make a C++ vector here, yet it was not very successful. Now I have made a basic reimplementation of it, so I'm checking that it is fine, and that I will not have to re make it again.

Note: I also implemented an allocator class, but it works the same as the std:: equivalent.

template < typename _Ty, typename _Alloc = allocator<_Ty> > class vector
{
public:
    typedef vector<_Ty, _Alloc> _Myt;
    typedef _Ty value_type;
    typedef _Alloc  allocator_type;
    typedef value_type *pointer;
    typedef const value_type *const_pointer;
    typedef value_type *iterator;
    typedef const value_type *const_iterator;
    typedef value_type &reference;
    typedef const value_type &const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

    vector()
        : __size(0), __capacity(20), __data(_Alloc().allocate(20))
    {
    }

    vector(const _Myt &_Rhs)
        : __size(_Rhs.__size), __capacity(_Rhs.__size + 20), __data(_Alloc().allocate(_Rhs.__size))
    {
        int count = 0;
        for (iterator i = &_Rhs.__data[0]; i != &_Rhs.__data[_Rhs.__size]; ++i, ++count)
        {
            _Alloc().construct(&__data[count], *i);
        }
    }

    ~vector()
    {
        if (!empty())
        {
            for (iterator i = begin(); i != end(); ++i)
            {
                _Alloc().destroy(i);
            }
            _Alloc().deallocate(__data, __capacity);
        }
    }

    _Myt &push_back(const value_type &_Value)
    {
        if (++__size >= __capacity)
        {
            reserve(__capacity * 2);
        }
        _Alloc().construct(&__data[__size - 1], _Value);
        return *this;
    }

    _Myt &push_front(const value_type &_Value)
    {
        if (++__size >= __capacity)
        {
            reserve(__capacity * 2);
        }
        if (!empty())
        {
            iterator _e = end(), _b = begin();
            std::uninitialized_copy(_e - 1, _e, _e);
            ++_e;
            std::copy_backward(_b, _e - 2, _e - 1);
        }
        _Alloc().construct(&__data[0], _Value);
        return *this;
    }

    _Myt &reserve(size_type _Capacity)
    {
        int count = 0;
        if (_Capacity < __capacity)
        {
            return *this;
        }
        pointer buf = _Alloc().allocate(_Capacity);
        for (iterator i = begin(); i != end(); ++i, ++count)
        {
            _Alloc().construct(&buf[count], *i);
        }
        std::swap(__data, buf);
        for (iterator i = &buf[0]; i != &buf[__capacity]; ++i)
        {
            _Alloc().destroy(i);
        }
        _Alloc().deallocate(buf, __capacity);
        __capacity = _Capacity;
        return *this;
    }

    iterator begin()
    {
        return &__data[0];
    }

    iterator end()
    {
        return &__data[__size];
    }

    size_type size()
    {
        return __size;
    }

    size_type capacity()
    {
        return __capacity;
    }

    bool empty()
    {
        return !__data;
    }

    const_pointer data()
    {
        return __data;
    }

private:
    pointer __data;
    size_type __size, __capacity;
};


texts:
i am just start to learn C++ and would like to know if there is a better and efficient way to solve this problem or some recommendations.

  Problem: Remove all vowels from file and create new one without
  vowels.

Here is my solution.

#include <iostream>
#include <fstream>

bool is_vowel(char &ch) {
    ch = tolower(ch);//clion showing warning here(value of type 'int' may not fit into type 'char') ,dont know why , i havent int here.
    return (ch == 'a' || ch == 'o' || ch == 'u' || ch == 'i' || ch == 'e');
}

int main() {
    ifstream file{"data.txt"};
    ofstream outfile{"new.txt"};
    string word;
    getline(file, word);
    for (char &ch : word) {
        if (!is_vowel(ch))
            outfile << ch;
    }
}


texts: Handling users connection to the application

texts:
This is a simple User class that I'm using throughout the application for anything related to the users. To tell if a user is logged in or not, I check the presence of the userID in the $_SESSION. When I'm logging in the user, I simply set the $_SESSION["userID"] equal to the ID of the user.

class User{

protected $pdo;

public function __construct(PDO $pdo)
{
    $this->pdo = $pdo;
}

public function getID()
{
    if(!$this->isConnected()) return 0;
    return $_SESSION["userID"];
}

public function isConnected()
{
    return !empty($_SESSION["userID"]);
}

public function login($username, $password)
{
    $q1 = $this->pdo->prepare("SELECT * FROM users WHERE username = ?");
    $q1->execute([$username]);
    $user = $q1->fetch();

    if(empty($user)) return false;
    if(!password_verify($password, $user->password)) return false;

    $_SESSION["userID"] = $user->id;
    $_SESSION["username"] = $user->username;
    return true;
}
}

I'm putting everything in a class just so that it's organized and easily accessible, but I'm pretty sure I'm not doing this properly. I presume that the correct way to handle this is to use properties for the class (example: $isConnected, $id) and change them when the user logs in/logs out.

However, I'm not sure how I would do that and avoid overwriting the user object every time the script loads (page refresh), so at the moment I'm doing it like that.

It works fine, but I really feel like I'm missing the point of OOP here. I'm a beginner when it comes to OOP with PHP, so please don't be too harsh! I'd really like some input from experienced developers.


texts: Better way of clone and then replace some attributes with jQuery

texts:
I have HTML code like this :

Add Text

            <input class="form-control" id="project_components_attributes_32943600_name" name="project[components_attributes][32943600][name]" type="text">

              <input id="project_components_attributes_32943600__destroy" name="project[components_attributes][32943600][_destroy]" type="hidden" value="false">

If I click link "Add Text", It will clone div with class form-inline and append to div#nF and then replacing all attribute of input tag in form-inline (id and name) with new value from new date and time.

For Illustration :

  id => project_components_attributes_32943600_name => replace
  "32943600" with new value

  name => project[components_attributes][32943600][_destroy] => replace
  "32943600" with new value

And this javascript :

$(document).ready(function(){
    $('#addTxt').click(function(){
        var time = new Date().getTime();
        var $target = $('#nF').find('div.form-inline:first');
        $target.clone().appendTo('#nF');
        $target.find('input').each(function(){
           $(this).val('');
           var tID = $(this).attr("id").split(/_/);
           var re = new RegExp(tID[3],"g");
           var newID = $(this).attr('id').replace(re, time);
           var newName = $(this).attr('name').replace(re, time);
           $(this).attr('id', newID);
           $(this).attr('name', newName);
        });
    });
});

Live Demo : http://jsfiddle.net/gjj8mzya/

Is there any way to clone element and replace attributes?


texts: Passing listener to customized extended View in Android

texts:
I extended NumberPicker with several methods needed in my application. When I came to defining a OnValueChangeListener this is how I did it:

import android.widget.NumberPicker;

interface ValueChangeCallback {
    public void execute(RemListView list, int oldVal, int newVal);
}

public class RemListView extends NumberPicker  {
    ValueChangeCallback mValueChangeCallback;
    RemListView thisList = this;

    public void setValueChangeCallback(ValueChangeCallback callback) {
        mValueChangeCallback = callback;

        setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                mValueChangeCallback.execute(thisList, oldVal, newVal);
            }
        });
    }
}

This code works fine but I'm new to Android and somehow I'm not sure I did it the proper way so I'm asking for a code review.

Do I have to save the callback in member variable?

I couldn't access this from within callback so I introduced thisList variable. Can it be avoided?


texts:
Suppose my milestone is this:

milestones = [ {state: 'unavailable'}, {state: 'arrived'}, {state: 'completed'} ]

I want to remove all the unavailable state from the list of hashes except the last one. My function works pretty well but I need some help to re factor it even further, and will appreciate any comments you can give. Here my code:

def filter_milestones(milestones)
      track_unavailable = Set.new
      filtered_milestones = []
      total_length = milestones.length
      if total_length == 1
        filtered_milestones = milestones
      else
        milestones.each_with_index do |value, index|
          if value[:state] == 'unavailable' && index != total_length - 1
            track_unavailable.add index
          end
        end
        milestones.each_with_index do |value, index|
          unless track_unavailable.include? index
            filtered_milestones << value
          end
        end
      end
      filtered_milestones
    end

So if my input milestone is [ {state: 'unavailable'}, {state: 'arrived'}, {state: 'completed'} ] then the return will be [ {state: 'arrived'}, {state: 'completed'} ].


texts:
Provides 3 types of normal ajax - get, post, and post for form data.

Also provides serialized ajax (get style) using a queue.

Please review the correctness of this code.

/**************************************************************************************************
AJAX
*/

// ... snip
    Pub.ajax = function (config_ajax) {
        var xhr;

        // get
        if (config_ajax.type === 'get') {
            xhr = new win.XMLHttpRequest();
            xhr.open('GET', config_ajax.url, true);
            xhr.onload = function () {
                if (this.status === 200) {
                    config_ajax.callback(xhr.responseText);
                }
            };
            xhr.send(null);
        }

        // post
        if (config_ajax.type === 'post') {
            xhr = new win.XMLHttpRequest();
            xhr.open("POST", config_ajax.url, true);
            xhr.setRequestHeader("Content-type",
                    "application/x-www-form-urlencoded");
            xhr.onload = function () {
                if (this.status === 200) {
                    config_ajax.callback(xhr.responseText);
                }
            };
            xhr.send(config_ajax.data);
        }

        // post for form_data
        if (config_ajax.type === 'multi') {
            xhr = new win.XMLHttpRequest();
            xhr.open("POST", config_ajax.url, true);
            xhr.onload = function () {
                if (this.status === 200) {
                    config_ajax.callback(xhr.responseText);
                }
            };
            xhr.send(config_ajax.data);
        }
    };

    // queue used for serial ajax
    Priv.Queue = (function () {
        var queue = [],
            publik = {};
        function getIndexFromToken(callback) {
            var hold;
            $A.someIndex(queue, function (val, index) {
                if (val.callback === callback) {
                    hold = index;
                    return index;
                }
            });
            return hold;
        }
        function getBlockedProperty(item) {
            var blocked;
            if (item) {
                blocked = item.blocked;
            } else {
                blocked = false;
            }
            return blocked;
        }
        publik.addItem = function (callback) {
            var temp = {};
            temp.blocked = false;
            temp.callback = callback;
            temp.response_text = null;
            queue.push(temp);
        };
        publik.itemCompleted = function (response_text, callback) {
            var index,
                item,
                blocked;
            index = getIndexFromToken(callback);
            if (index !== 0) {
                queue[index].blocked = true;
                queue[index].response_text = response_text;
            } else {
                item = queue.shift();
                item.callback(response_text);
                blocked = getBlockedProperty(queue[0]);
                while (blocked) {
                    item = queue.shift();
                    item.callback(item.response_text);
                    blocked = getBlockedProperty(queue[0]);
                }
            }
        };
        return publik;
    }());

    // serial ajax
    // unlike normal ajax the ordering is guaranteed
    Pub.serialAjax = function (source, callback) {
        Priv.Queue.addItem(callback);
        Pub.ajax({
            type:       'get',
            url:        source,
            callback:   function (response_text) {
                Priv.Queue.itemCompleted(response_text, callback);
            }
        });
    };
// ... snip


texts:
I'm a fresh verilog / HDL programmer and I'm writing this post to get some feedback from more experienced verilog / HDL programmers.

My very first task was to divide a clock by eight.

I know there are some better methods to do this, but as I'm new to HDL this is my first, naive, attempt:

module prescaleMainCLK(CLK, prescaledCLK);
    input CLK;
    output reg prescaledCLK;

    // ''Define'' a 4bit counter, max value: 15
    reg [3:0] counter;

    initial begin
        // Initialise both variables
        prescaledCLK <= 0;
        counter      <= 0;
    end

    always @ (posedge CLK) begin

        // Did the counter reach its end?
        if (counter > 7) begin

            // Reset the counter
            counter <= 0;

            // Toggle the prescaled clock output
            prescaledCLK <= ~prescaledCLK;

        end else begin

            // Increment counter
            counter <= counter + 1;

        end

    end

endmodule

The Simulation output (EDAPlayground) is as I expect it to be:

Now I want to know if that code is suitable for real applications or if there are some things I need to reconsider.


texts: Determine if elements in an ArrayList are consecutively ordered

texts:
Write a method isConsecutive that accepts an ArrayList of integers as
  a parameter and returns true if the list contains a sequence of
  consecutive integers and false otherwise. Consecutive integers are
  integers that come one after the other in ascending order, as in 5, 6,
  7, 8, 9, etc. For example, if a variable called list stores the values
  [3, 4, 5, 6, 7, 8, 9], then the call of list.isConsecutive() should
  return true. If the list instead stored [3, 4, 5, 6, 7, 12, 13] then
  the call should return false because the numbers 7 and 12 are not
  consecutive. The list [3, 2, 1] might seem to be consecutive, but the
  elements appear in reverse order, so the method would return false in
  that case. Any list with fewer than two values should be considered to
  be consecutive. You may assume that the list passed is not null.

Wondering which better ways there are to do this, and how to improve my future code.

public boolean isConsecutive(ArrayList<Integer> list) {
    int count = 0;
    for (int i = 0; i < list.size() - 1; i++) {
        if (list.get(i) == (list.get(i + 1) - 1)) {
            count++;
        } else {
            count = 0;
        }
    }
    return list.size() - 1 == count || list.isEmpty();
}


texts: Nested LINQ Nightmare, calculating %completed

texts:
This code horrifies and scares me. I wrote this.

public IQueryable<StudentTrack> StudentTracks(int employeeId)
{

    IQueryable<StudentTrack> EducationPortalStudentTracks =
        from studentTrack in _dbContext.EducationPortalStudentTracks
        join track in _dbContext.EducationPortalTracks on studentTrack.TrackId equals track.Id
        orderby track.Id
        where studentTrack.EmployeeId == employeeId
        select new StudentTrack
        {
            Id = studentTrack.Id,
            TrackId = studentTrack.TrackId,
            Name = track.Name,
            Deadline = studentTrack.Deadline,

            // this is where it gets bad
            PercentComplete = (from doesntMatter in _dbContext.EducationPortalStudentCourses
                               let courses = (from studentCourse in _dbContext.EducationPortalStudentCourses
                                              join studentTrack_ in _dbContext.EducationPortalStudentTracks on studentCourse.TrackId equals studentTrack_.TrackId
                                              where studentTrack.Id == studentTrack.Id && studentTrack.EmployeeId == studentCourse.EmployeeId
                                              select studentCourse)
                               select courses.Where(x => x.Status == true).Count() * 100 / courses.Count()).FirstOrDefault()

        };
    return EducationPortalStudentTracks;
}

Let me explain how this fits in to the rest of the application. On the top level, a Kendo Grid control calls an MVC controller for its data. That controller calls another controller, which calls this. So this method returns the data which populates a grid in the UI. That grid lists all of the StudentTracks in the database. In order to return the StudentTracks, this method does a little bit of Linq and returns a series of StudentTrack objects.

So the problem starts with the PercentComplete field. To calculate the value for that field, we first find all of the children StudentCourses. We then figure out how many of the StudentCourses are complete (a.k.a. have True in the Status column) and divide that by the total number of StudentCourses.

Anyway, this is what I came up with. I'm not pleased with it, but I don't know how to do it any better. Any ideas on how I can make this a little more elegant?


texts:
I've got some if and else if statements to show and hide svg elements and it works the way it should but I wonder if I can shorten the code since it looks so repetitive.

I'm not sure if it's possible since I'm not a JS/JQuery expert.

If/else if code

        //Door type 1
        if( id2 == "#Door1" && id3 == "#Grey")
        {
            var door = "#Door1Grey"
            $("g" + door).show().siblings("g:not(#BG)").hide();
            //console.log($("g" + door).show().siblings());
        }
        else if( id2 == "#Door1" && id3 == "#Blue")
        {
            var door = "#Door1Blue"
            $("g" + door).show().siblings("g:not(#BG," + id + ")").hide();
            //console.log(door);
        }
        else if( id2 == "#Door1" && id3 == "#Red")
        {
            var door = "#Door1Red"
            $("g" + door).show().siblings("g:not(#BG," + id + ")").hide();
            //console.log(door);
        }

        //Door type 2
        else if( id2 == "#Door2" && id3 == "#Grey")
        {
            var door = "#Door2Grey"
            $("g" + door).show().siblings("g:not(#BG," + id + ")").hide();
            //console.log(door);
        }
        else if( id2 == "#Door2" && id3 == "#Blue")
        {
            var door = "#Door2Blue"
            $("g" + door).show().siblings("g:not(#BG," + id + ")").hide();
            //console.log(door);
        }
        else if( id2 == "#Door2" && id3 == "#Red")
        {
            var door = "#Door2Red"
            $("g" + door).show().siblings("g:not(#BG," + id + ")").hide();
            //console.log(door);
        }

        //Door type 3
        else if( id2 == "#Door3" && id3 == "#Grey")
        {
            var door = "#Door3Grey"
            $("g" + door).show().siblings("g:not(#BG," + id + ")").hide();
            //console.log(door);
        }
        else if( id2 == "#Door3" && id3 == "#Blue")
        {
            var door = "#Door3Blue"
            $("g" + door).show().siblings("g:not(#BG," + id + ")").hide();
            //console.log(door);
        }
        else if( id2 == "#Door3" && id3 == "#Red")
        {
            var door = "#Door3Red"
            $("g" + door).show().siblings("g:not(#BG," + id + ")").hide();
            //console.log(door);
        }

id, id2 and id3 are set here:

        var wallChoice = String($('input[name=radiosWall]:checked', '#myFormFront').val());
        var id = String("#" + wallChoice);
        $("g" + id).show().siblings("g:not(#BG," + id + ")").hide();

        var doorChoice = String($('input[name=radiosDoor]:checked', '#myFormFront').val());
        var id2 = String("#" + doorChoice);

        var doorColorChoice = String($('input[name=radiosColor]:checked', '#myFormFront').val());
        var id3 = String("#" + doorColorChoice);


texts: Linq query performance that use ToList()

texts:
This code written by @Rahul Singh in this post:

var result = _dbContext.ExtensionsCategories.ToList().GroupBy(x => x.Category)
                .Select(x =>
                    {
                        var files = _dbContext.FileLists.Count(f => x.Select(z => z.Extension).Contains(f.Extension));
                        return new
                        {
                            Category = x.Key,
                            TotalFileCount = files
                        };
                    });

This code has a problem when used inside database context and we should use ToList() like this to fix "Only primitive types or enumeration types are supported in this context" error:

 var result = _dbContext.ExtensionsCategories.ToList().GroupBy(x => x.Category)

The problem of this is that ToList() fetches all records and reduces performance. Now I wrote my own code:

    var categoriesByExtensionFileCount =
        _dbContext.ExtensionsCategories.Select(
            ec =>
                new
                {
                    Category = ec.Category,
                    TotalSize = _dbContext.FileLists.Count(w => w.Extension == ec.Extension)
                });

    var categoriesTotalFileCount =
        categoriesByExtensionFileCount.Select(
            se =>
                new
                {
                    se.Category,
                    TotalCount =
                        categoriesByExtensionFileCount.Where(w => w.Category == se.Category).Sum(su => su.TotalSize)
                }).GroupBy(x => x.Category).Select(y => y.FirstOrDefault());

The performance of this code is better but it has many lines of code. Any idea about improving the performance of the latter, or reducing the length of the former?


texts: Creating an image in Excel using the colors from an input image

texts:
I'm having some performance issues in this code and need some suggestions on how to improve it. I'm not interested in "general code style" improvements unless they have performance implications.

The purpose is to create an image in Excel using the colors from an input image. What is my performance issue is that it takes time setting the styles (about 45% of time each when profiling) and it is increasing linearly by each "pixel" created.

Currently it becomes annoyingly slow with pictures larger than about 50 x 50.

style.setFillForegroundColor(new XSSFColor(color));
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

I was thinking of doing it in parallel, but I don't think POI is thread safe when trying. I also tried to do with HSSF (but got reduced number of colors and styles allowed and maximum 255 pixels wide, however it was fast).

My next thinking was to reduce number of colors used in the image and cache styles for each color so I can reuse the style for several pixels. I have not tried it yet however.

Do you have any other suggestions?

package test.test;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;

import javax.imageio.ImageIO;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelDrawXSSF {

    public static void main(String[] args) {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet sheet = workbook.createSheet("Pic");
            // Can take any picture jpg/png if you want to try
            BufferedImage image = ImageIO.read(new File("DisplayImage.jpg"));

            int height = image.getHeight();
            int width = image.getWidth();

            for (int y = 0; y < height; y++) {
                XSSFRow row = sheet.createRow(y);
                for (int x = 0; x < width; x++) {
                    int rgb = image.getRGB(x, y);
                    Color color = new Color(rgb, true);
                    XSSFCell cell = row.createCell(x);
                    setColor(workbook, cell, color);
                    System.out.println(y + "," + x);
                }
            }

            setSmallerColumnWidth(sheet, width);

            try (FileOutputStream outputStream = new FileOutputStream("Pic.xlsx")) {
                workbook.write(outputStream);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static void setSmallerColumnWidth(XSSFSheet sheet, int width) {
        IntConsumer setToDefaultWidth = col -> sheet.setColumnWidth(col, 4 * 256);
        IntStream.range(0, width).forEach(setToDefaultWidth);
    }

    private static void setColor(XSSFWorkbook workbook, Cell cell, Color color) {
        long start = System.nanoTime();
        XSSFCellStyle style = workbook.createCellStyle();

        // Here is the performance issue.
        style.setFillForegroundColor(new XSSFColor(color));
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        cell.setCellStyle(style);
        System.out.println((System.nanoTime() - start) / (1000 * 1000));
    }

}


texts: Sauna experiment - Celsius to Fahrenheit converter

texts:
This is my program for a sauna. It is a Swedish sauna meant to only understand Celsius, but the user can only understand Fahrenheit, so when the user inputs Fahrenheit, it is converted to Celcius. Afterwards, the Celsius is rounded to an even value when presented to the user, to get rid of all the decimals from the conversion.

class Program
{
    static void tempCheck(double temperature)
    {
        if (temperature < 0)
        {
            Console.WriteLine("The sauna has now become a freezer, \nCelcius: {0}", Math.Round(temperature));
            Console.WriteLine();
        }
        else if (temperature < 73)
        {
            Console.WriteLine("This temperature is too low for sauna use, \nCelcius: {0}", Math.Round(temperature));
            Console.WriteLine();
        }
        else if (temperature > 100)
        {
            Console.WriteLine("You will be boiled alive if you use the sauna, \nCelcius: {0}", Math.Round(temperature));
            Console.WriteLine();
        }
        else if (temperature > 77)
        {
            Console.WriteLine("This heat will scald you, please lower the temperarture, \nCelcius: {0}", Math.Round(temperature));
            Console.WriteLine();
        }
        else if (temperature == 75)
        {
            Console.WriteLine("Perfect heat for sauna!");
            Console.WriteLine();
        }
        else
            Console.WriteLine("This temperature is adequate for sauna use! \nCelcius: {0}", Math.Round(temperature));

    }

    public static double FahrToCels(int fahr)
    {
        double fahrenheit = (5.0 / 9.0) * (fahr - 32);
        return fahrenheit;
    }

    static void Main(string[] args)
    {

        double temperature = 0;
        Console.WriteLine("Enter a desired temperature between 73 och 77 celcius");

        do
        {
            try
            {
                int fahrenheit = int.Parse(Console.ReadLine());
                Console.WriteLine(temperature);
                double celcius = FahrToCels(fahrenheit);
                Console.WriteLine(celcius);
                temperature = temperature + celcius;
                tempCheck(temperature);

            }
            catch (FormatException)
            {
                Console.WriteLine("Please only enter whole numbers, no decimals");
            }
            catch
            {
                Console.WriteLine("Error");
            }

        } while (temperature < 73 || temperature > 77);
    }
}
}


texts:
I'm learning C from the K.N. King book and just arrived at a question to reverse the words in a sentence.

Here is the output:

  Enter a sentence: you can cage a swallow can't you?

  Reversal of sentence: you can't swallow a cage can you?

Though I've done this and it runs correctly, I want to make my code shorter. I'm not asking for any other solution.

#include <stdio.h>

#define N 100

int main(void) {
  char ch[N], terminate;
  int i, j, k, len;
  printf("Enter a sentence: ");
  for(i = 0; i < N; i++) {
    ch[i] = getchar();
    if(ch[i] == '?' || ch[i] == '.' || ch[i] == '!' || ch[i] == '\n') {
      len = i;        //Determine the length of the string
      terminate = ch[i];
      break;
    }
  }
  int word_count = 0;
  for(j = len - 1; j >= 0; j--) {
    word_count++;
    if(ch[j] == ' ') {
      for(k = j+1; k < len; k++) {
        printf("%c", ch[k]);
      }
      printf("%c", ch[j]);  // print space character
      len = len - word_count;
      word_count = 0;
    }

  }

  for(i = 0; i < len; i++) {
    printf("%c", ch[i]);
    if(ch[i] == ' ') {
      break;
    }
  }
  printf("%c", terminate);

  return 0;
}

This can be done only with loops, arrays, getchar() and putchar() methoda using only <stdio.h> header and no extra header (restrict <string.h> header functions and methods). Also, no puts() and gets() functions. I guess this can be done only with two loops.


texts:
I would like to create a wrapper for a Boost conditional variable:

class Cond_wrap
{
private:
    boost::condition_variable cond;
    boost::mutex              mutex;
    bool work_to_do;
public:
    Cond_wrap()
    {
        work_to_do = false;
    }
    void notify_all()
    {
        boost::mutex::scoped_lock lock(mutex);
        work_to_do = true;
        cond.notify_all();
    }
    void wait()
    {
        boost::mutex::scoped_lock lock(mutex);
        while(!work_to_do)
        {
            cond.wait(lock);
            work_to_do = false;
        }
    }
    bool timed_wait(unsigned int timeout)
    {
        boost::mutex::scoped_lock lock(mutex);
        if(!work_to_do)
        {
            if(cond.timed_wait(lock, boost::chrono::milliseonds(timeout)))
            {
                work_to_do = false;
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
};

Cond_wrap condition_wrap;

void worker_func()
{
    {
        condition_wrap.notify_all();
    }
    std::cout << "After notify" << std::endl;
}

int main()
{
    boost::thread work(worker_func);
    work.detach();

    {
        boost::this_thread::sleep_for(boost::chrono::milliseonds(500));
        condition_wrap.wait();
        //there is work to do
    }
    return 0;
}

What is the main goal of that wrapper? I would like to avoid a situation in which a condition will be notified before I call waiter. Regarding this, I want to provide a help variable bool which should remember if a condition was previously set.

Small example of what I mean:

boost::condition_variable cond;
boost::mutex              mutex;

void worker_func()
{
    cond.notify_all();
    std::cout << "After notify" << std::endl;
}

void main()
{
    boost::mutex::soped_lock lock(mutex);
    boost::thread work(worker_func);
    boost::this_thread::sleep_for(boost::chrono::milliseonds(500));
    cond.wait(lock); // here is deadlock
}

The wrapper is also provides an easier way of using a Boost conditional variable.


texts:
Im making a Python program. It is basically a questionnaire and I was just wondering if there is a shorter way of doing this as at the moment I'm writing out all of the questions in separate functions. I was wondering if there is an alternative way of doing this in almost a single function where the function just repeats but the question and right answers change every time. If I cannot do this is there an alternate way to do this without having to do separate functions for each question? is there a faster/more efficient way of completing this?

All advice would be much appreciated and I have pasted the first 4 questions and the rest of the code below. I will be having many more questions but i just did 4 so that it wouldn't take up too much space :)

import time
questionNumber = 0
right = 0
wrong = 0
name = str(input("Please Enter your name"))
print()
def questions():
    def questionOne():
        global right, wrong, questionNumber
        print("What is the population of New Zealand?")
        print("Is it A:6.7m B:3.2m C:5.1m or D:4.5m")
        ans = str(input())
        if ans == "D" or ans == "d" or ans == '4.5' or ans == '4':
            print("You got it right!")
            right = right + 1
        else:
            print("You got it wrong!")
            wrong = wrong+1
        questionNumber = questionNumber + 1
    questionOne()
    time.sleep(2)
    print()
    print("So far",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions")
    print()
    time.sleep(4)
    def questionTwo():
        global right, wrong, questionNumber
        print("What year did the first european set foot on New Zealand (Abel Tasman)")
        print("Is it A:1830 B:1543 C:1642 or D:1765")
        ans = str(input())
        if ans == "C" or ans == "c" or ans == '1642'or ans == '3':
            print("You got it right!")
            right = right + 1
        else:
            print("You got it wrong!")
            wrong = wrong+1
        questionNumber = questionNumber + 1
    questionTwo()
    time.sleep(2)
    print()
    print("So far ",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions")
    print()
    time.sleep(4)
    def questionThree():
        global right, wrong, questionNumber
        print("How many Kiwi are there left in New Zealand (Approx)")
        print("Is it A:2000 B:600 C:70,000 or D:100000")
        ans = str(input())
        if ans == "D" or ans == "d" or ans == '100000'or ans == '4':
            print("You got it right!")
            right = right + 1
        else:
            print("You got it wrong!")
            wrong = wrong+1
        questionNumber = questionNumber + 1
    questionThree()
    time.sleep(2)
    print()
    print("So far ",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions")
    print()
    time.sleep(4)
    def questionFour():
        global right, wrong, questionNumber
        print("How many new babys where born in New Zealand in 2015")
        print("Is it A:61,000 B:208,000 C:98,000 or D:18,000")
        ans = str(input())
        if ans == "D" or ans == "d" or ans == '100000'or ans == '4':S
            print("You got it right!")
            right = right + 1
        else:
            print("You got it wrong!")
            wrong = wrong+1
        questionNumber = questionNumber + 1
    questionFour()
questions()


texts:
Is this a good way to get all sublists of a sequence/list that have a given length?

An inefficient way to do it would be something like

f n = (filter (\x -> (length x) > n)) . (take n) . tails

This just takes the n first elements of each tail of the original list. I think it should be slow because of the length check on every tail-element.

A smarter way would should be to "slide" a sequence of length n over an input sequence and save the result of each slide by one to the right.

-- | Get all the subsequences of a given sequence sq of length n
ngrams::Int -> Seq a -> Seq (Seq a)
ngrams n sq | length sq < n = empty
ngrams n sq | otherwise = ngrams' restSequence initialWindow empty
            where
              initialWindow = take n sq
              restSequence  = drop n sq
              ngrams' (viewl -> EmptyL) window acc = acc |> window
              ngrams' (viewl -> x :< s) window@(viewl -> a :< r) acc =
                                            ngrams' s (r |> x) (acc |> window)

Somehow I have the feeling I am missing an obvious way to do this better...


texts:
I am looking for general feedback on this small, simple program I wrote.  It works perfectly, but I am striving for readable, clean code.

I also have specific questions:

Is the switch statement the most efficient/logical way to write this class?
Is my main method too large?  Should I break it into smaller methods?  How would you suggest splitting it up?

/**
* This AirlineReservation class assigns seats on an airplane and prints boarding passes.
* (1) A boolean array is used to store a seating chart and which seats are available
* (2) The user is asked if they want a first class reservation, second class reservation, or end
* (3) A switch statement case is selected based on the user's input
* (4) The requested class of flight is checked for available seats
*       (a) seats 1-5 are first class
*       (b) seats 6-10 are economy
* (5) if available, seat is booked and boarding pass is printed
* (6) if not available, user is notified and presented with the original 3 options.
*
* NOTE:  I have commented out a method I was using to check my array for accuracy.
*/

import java.util.Scanner;
import java.util.Arrays;

public class AirlineReservations
{

public static void main(String[] args)
{
    int totalSeats = 10;
    int firstClassSeats = 5;
    int economySeats = 5;
    int classChoice = 0;
    boolean continueInput = true;

    Scanner input = new Scanner(System.in);

    boolean[] seatingChart = new boolean[totalSeats];
    Arrays.fill(seatingChart, false);

    while (continueInput == true)
    {
        System.out.print("Please type 1 for First Class, 2 for Economy Class, or 3 to exit System: ");
        classChoice = input.nextInt();
        switch (classChoice)
        {
            case 1://first class requested
                if (firstClassSeats > 0)//seat available
                {
                    seatingChart[firstClassSeats-1]=true;
                    firstClassSeats--;
                    printBoardingPass((firstClassSeats+1), classChoice);
                    //printSeatArray(seatingChart);
                }
                else //seat not available
                    System.out.print("\nFirst class seats are now SOLD OUT!\n");
                break;

            case 2://economy class requested
                if (economySeats > 0)//seat available
                {
                    seatingChart[economySeats+4]=true;
                    economySeats--;
                    printBoardingPass((economySeats+6),classChoice);
                    //printSeatArray(seatingChart);
                }
                else//seat not available
                    System.out.print("\nEconomy seats are now SOLD OUT!\n");
                break;
            case 3://exit system
                continueInput = false;
                break;
            default://incorrect input
                System.out.print("\nIncorrect input.  Please enter only a 1, 2, or 3.");
                break;
        }//end switch classChoice
    }//end while continueInput
}//end main method

private static void printBoardingPass(int seat, int classChoice)
{
    String seatingClass = (classChoice == 1? "First" : "Economy");
    System.out.print("\nBoarding Pass:  " + seatingClass + " class, Seat # " + seat +"\n\n");
}//end printBoardingPass

//private static void printSeatArray(boolean[] seatingChart)
//{
    //for (boolean element : seatingChart)
        //System.out.print(element + "\n");
    //System.out.println();
//}
}//end class


texts:
I am pretty sure my code does not follow PEP 8 and would definitely want someone to point out my errors specifically. I am open any form of criticism or suggestions.
import chess
import chess.engine
import time
import stockfish

engine = chess.engine.SimpleEngine.popen_uci("stockfish")
board = chess.Board()

def pact():  # Player's Action
    print('----------------\n' + 'The legal moves are: \n' +
          str(board.legal_moves) + '\n' + str(board))
    Action = input('Declare your moves: ')
    try:
        board.push_san(Action)
    except ValueError:
        # output: "integer division or modulo by zero"
        print('Invalid move, try again')

def cact():  # Computer's Action
    result = engine.play(board, chess.engine.Limit(time=2.0))
    board.push(result.move)

    print(board)

print(board)

for index in range(3, 0, -1):
    print('The game starts in ' + str(index) + 'seconds')
    time.sleep(1)
while(board.is_checkmate() == False):
    pact()
    cact()
    # print(engine.play.move(board, limit)

Ideally I would like to incorporate sound recognition and making it a hands-free chess playing with Stockfish or other player. For now, I just want to get the basics right to avoid any future bugs and improve overall tidiness so I can have a good habit in my future coding progress.


texts:
Anything that could be done better here?

public class ShuffleBag<T> : IEnumerable<T>
{
    private readonly int m_endIndex;
    private readonly FastRandom m_rng;
    private readonly T[] m_values;

    private int m_currentIndex;

    public ShuffleBag(T[] values, ulong state, ulong? stream = null) {
        m_currentIndex = 0;
        m_endIndex = (values.Length - 1);
        m_rng = (stream.HasValue ? new FastRandom(state, stream.Value) : new FastRandom(state));
        m_values = values;
    }
    public ShuffleBag(T[] values) : this(values, SecureRandom.GetUInt64()) { }

    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
    public IEnumerator<T> GetEnumerator() {
        var currentIndex = m_currentIndex;
        var endIndex = m_endIndex;
        var rng = m_rng;
        var values = m_values;

        while (currentIndex <= endIndex) {
            var randomIndex = rng.NextInt32(currentIndex, endIndex);
            var temp = values[randomIndex];

            values[randomIndex] = values[currentIndex];
            values[currentIndex] = temp;

            m_currentIndex = currentIndex++;

            yield return temp;
        }
    }
}

For those that might inquire, here's the source for FastRandom and SecureRandom.


texts:
I have the following:

public interface IBehaviour
{
    event EventHandler Completed;
    void Execute();
}

public interface IBehaviourA : IBehaviour
{
    // Some specific stuff here
    object A { get; set; }
}

public interface IBehaviourB : IBehaviour
{
    // Some specific stuff here
    object B {get;set;}
}

public interface IBehaviourQueue
{
    void Run();
    BehaviourQueueItem<IBehaviour> AddBehaviour<T>() where T : IBehaviour;
}

public class BehaviourQueue : Queue<BehaviourQueueItem<IBehaviour>>,  IBehaviourQueue
{
    private IBehaviourFactory factory;
    public BehaviourQueue(IBehaviourFactory factory)
    {
        this.factory = factory;
    }

    public BehaviourQueueItem<IBehaviour> AddBehaviour<T>() where T:IBehaviour
    {
        T behaviour = factory.GetNew<T>();
        var queueItem = new BehaviourQueueItem<IBehaviour>(behaviour);
        Enqueue(queueItem);
        return queueItem;
    }

    public void Run()
    {
        //Run each queue item
    }
}

public class BehaviourQueueItem<T>
{
    public IBehaviour behaviour;

    public BehaviourQueueItem(IBehaviour behaviour)
    {
        this.behaviour = behaviour;
    }

    public void WhenComplete(Func<T, bool> action)
    {
        CompletedAction = action;
    }

    public BehaviourQueueItem<T> ConfigureFor<Z>(Action<Z> dow) where Z : IBehaviour
    {
        dow((Z)behaviour);
        return this;
    }
}

This is how it is used:

var q =new BehaviourQueue(new BehaviourFactory()); // Queue here is IBehaviour
q.AddBehaviour<IBehaviourA>()
 .ConfigureFor<IBehaviourA>(x => x.A = "someValueA")
 .WhenComplete(x => DoStuffWithSomeProperty(((IBehaviourA)x).A));

q.AddBehaviour<IBehaviourB >()
 .ConfigureFor<IBehaviourB >(x => x.B = "someValueB")
 .WhenComplete(x => DoStuffWithSomeProperty(((IBehaviourB)x).B));

What I don't really like is that I have to specify which type of IBehaviour I am referring to every time. I would like to be able to write:

var q =new BehaviourQueue(new BehaviourFactory()); // Queue here is IBehaviour
q.AddBehaviour<IBehaviourA>()
 .Configure(x => x.A = "someValueA")
 .WhenComplete(x => DoStuffWithSomeProperty(x.A));

q.AddBehaviour<IBehaviourB>()
 .Configure(x => x.B = "someValueB")
 .WhenComplete(x => DoStuffWithSomeProperty(x.B));

I know that I have to modify this part:

public BehaviourQueueItem<IBehaviour> AddBehaviour<T>() where T:IBehaviour
{
    T behaviour = factory.GetNew<T>();
    var queueItem = new BehaviourQueueItem<IBehaviour>(behaviour);
    Enqueue(queueItem);
    return queueItem;
}

to something like

public BehaviourQueueItem<T> AddBehaviour<T>() where T:IBehaviour
{
    T behaviour = factory.GetNew<T>();
    var queueItem = new BehaviourQueueItem<T>(behaviour);
    Enqueue(queueItem); // It won't let me know do it because of Covariance/Contravariance thingy
    return queueItem;
}

Do you have any idea what I should write to be able to create a base typed list and add specific items and configuring it fluently?

Keep in mind that I should be able to add any type of IBehaviour to BehaviourQueue so the queue can't be a derived type.


texts:
I have states that have a requiredlogin object set as true, then I have Angular listen on stateChangeStart, but things end up pretty ugly.

Here is a state that requires a login. I think this actually pretty good and simple.

.state('dashboard',
  url: '/dashboard',
  templateUrl: 'partials/dashboard/main.jade',
  data:
    requireLogin: true
)

This is where it gets ugly. I'll eventually just change this into a loginCheck() function but I hate the logic so much; too many if statements. Also, this barely works, so I could use the improvements.

$rootScope.$on('$stateChangeStart', (event, toState) ->
    # Checks if a page or a page's parent page requires login
    if _.has(toState.data, 'requireLogin')
      if _.has($window.sessionStorage, 'userInfo')
    # If it does check for stored user information
        userInfo = JSON.parse($window.sessionStorage["userInfo"]) or null
      # Check if user info has an ID property if it does try to authorize it
        if _.has(userInfo, '_id')
          AuthService.isAuthentic(userInfo._id).then (d) ->
            if d.data == "true"
              $rootScope.userInfo = userInfo
              $rootScope.userAuth = true
            else
          $rootScope.userInfo = null
          $rootScope.userAuth = false
          $state.go('login')
    else
      event.preventDefault()
      $state.go('login')
  else
    $window.sessionStorage["userInfo"] = null
    $state.go('login')
)


texts:
I'm having trouble accessing variables throughout multiple functions. For example, I need to use userinput throughout many other functions, but do not have access to it with my current code. I am pretty sure that I need to change the parameters of my functions, so that I can pass the value of those functions by reference, but I'm having trouble doing that.

Here's what my code looks like right now:

#include <cstdlib>
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

double fahrtocels();
double celstofahr();
double celstokelv();
double kelvtocels();

int main()
{
    do { int userinput=0;

    cout << " 1) Fahr to Cels" << endl;
    cout << " 2) Cels to Fahr" << endl;
    cout << " 3) Cels to Kelv" << endl;
    cout << " 4) Kelv to Cels" << endl;
cin >> userinput;
if(userinput=1)
fahrtocels();
if(userinput=2)
celstofahr();
if(userinput=3)
celstokelv();
if(userinput=4)
kelvtocels(); } while(userinput=0);

}

double fahrtocels()
{
    int input;
    int tempinput;
    double finaloutput;
    cout <<" Please Enter the Temp in Fahrenheit"<<endl;
    cin >> input;
userinput= 1;
    tempinput = input - 32;

finaloutput = tempinput/1.8;

    cout<<input<< " degrees fahrenheit is equivalent to  " << finaloutput<< "  celsius"<< endl;
    userinput = 0;
}

double celstofahr()
{
    int inputcels;
    int tempinputcels;
    double finaloutputcels;
    cout <<" Please Enter the Temp in Celsius"<<endl;
    cin >> inputcels;

    tempinputcels = inputcels * 1.8;

finaloutputcels = tempinputcels + 32;

    cout<<inputcels<< " degrees celsius is equivalent to  " << finaloutputcels<< "  fahrenheit"<< endl;
}

double celstokelv()
{
    int inputcelskelv;
    double finaloutputcelskelv;
    cout <<" Please Enter the Temp in Celsius for Kelvin Conversion"<<endl;
    cin >> inputcelskelv;

finaloutputcelskelv = inputcelskelv + 273.15;

    cout<<inputcelskelv<< " degrees celsius is equivalent to  " << finaloutputcelskelv<< " kelvin"<< endl;
}

double kelvtocels()
{
    int inputkelvcels;
    double finaloutputkelvcels;

    cout <<" Please Enter the Temp in Kelvin for Celsius conversion"<<endl;
    cin >> inputkelvcels;

finaloutputkelvcels = inputkelvcels - 273.15;

    cout<<inputkelvcels<< " degrees kelvin is equivalent to  " << finaloutputkelvcels<< " celsius"<< endl;
}


texts:
Create hash generator with configurable hash algorithm. Also need method to create salt. Implemented in visual studio 2015. Must work in DNX Core 5.0.

 public class HashGenerator : IHashGenerator
    {
        // Algorithm has to inherit from HashAlgorithm base class.
        // For example, another algorithm that can be used is: "System.Security.Cryptography.MD5";
        private const string HashAlgorithmName = "System.Security.Cryptography.SHA256";

        public string GenerateHash(string input, string salt)
        {
            var saltedPassword = Encoding.UTF8.GetBytes($"{input}{salt}");

            var hashAlgorithm = GetHashAlgorithm();
            var hashedPassword = hashAlgorithm.ComputeHash(saltedPassword);

            return Convert.ToBase64String(hashedPassword);
        }

        public string CreateSalt()
        {
            var buffer = new byte[25];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(buffer);
            }
            return Convert.ToBase64String(buffer);
        }

        private HashAlgorithm GetHashAlgorithm()
        {
            var typeInfo = Type.GetType(HashAlgorithmName).GetTypeInfo();
            var createMethod = typeInfo.GetDeclaredMethods("Create").First(f => f.GetParameters().Count() == 0);
            var hashAlgorithm = (HashAlgorithm)createMethod.Invoke(null, null);
            return hashAlgorithm;
        }
    }


texts: ways to code for better speed of processing date comparisions / slicing in python

texts:
I wrote the below code to convert a long data frame containing start and end date event spans into a daily df with rows for each day:
output:
 **bene_id, day, death, hha**
 row 1: abc, 1 ('2018-10-01'), 0,0
 row 2: abc, 2 ('2018-10-02'), 0,1
 row 3: abc, 3 ('2018-10-03'), 0,0
 row 4: abc, 4 ('2018-10-04'), 0,1

I am planning to use the daily output in a Tableau viz.
The below code - which does work - heavily uses date comparisons and slicing - is very, very, very slow. Are there particular functions I am using that have faster alternatives? Both the for loop and the functions are slow..
from pandas import Timestamp, Series, date_range

#creates empty df for input with correct column order
long = pd.DataFrame(columns={'bene_id', 'day','date'})
cols_to_order = ['bene_id', 'day','date']
new_columns = cols_to_order + (long.columns.drop(cols_to_order).tolist())
long = long[new_columns]

#gets only necessary columns for processing from main data set
sample=s[['bene_id','event_type','event_thru_date','look_forward_90_date','service_epi_from_date','service_epi_thru_date']]

#creates the long daily table with count 1 to 90, and daily date freq
for e in sample.bene_id.drop_duplicates():
    temp=sample[sample['bene_id']==e]
    start =Timestamp(temp[temp['event_type'] =='trigger'][['event_thru_date']].iloc[0][0])
    stop= temp[temp['event_type'] =='trigger'][['look_forward_90_date']]+pd.DateOffset(1)
    stop=Timestamp(stop.iloc[0][0])
    for i,j in zip(range(1,91), Series(date_range(start,stop))):
        long = long.append(pd.Series([e,i,j],index=cols_to_order), ignore_index=True)

#create functions to add events to daily df created above "long"; count first day of event span but not last date.
def checkdate(row,event):
    temp=sample[(sample['bene_id']==row['bene_id'])&(sample['event_type']==event)]
    temp['flag']= np.where((temp['service_epi_from_date']<=row['date']) &(temp['service_epi_thru_date']>row['date']),1,0)
    daily_status =temp['flag'].sum()
    return daily_status

def checkdeath(row,event):
    temp=sample[(sample['bene_id']==row['bene_id'])&(sample['event_type']==event)]
    temp['flag']= np.where(temp['service_epi_from_date']<=row['date'],1,0)
    daily_status =temp['flag'].sum()
    return daily_status

#apply functions referencing events in original sample df
long['death']=long.apply(checkdeath, axis=1, args=('death',))
long['hha']=long.apply(checkdate, axis=1, args=('hha',))


texts: Optimizing search by id in some data in JSON structure

texts:
I have an object created by a JSON data. I need to retrieve the id for an object, I would like to know if a faster way exist, considering I am using for ..in loop.

var test =  {
     id: 0,
      cnt: [
        {
          id: 1,
          cnt: [
            {
              id: 2,
              cnt: [
                {
                  id: 3,
                  cnt:[]
                }
              ]
            }
          ]
        },

      ]
    };

    getById: function (id) {
                function getByIdInner(obj, id) {
                    var result;
                    for (var p in obj) {
                        if (obj.id == id) {
                            return obj;
                        } else {
                            if (typeof obj[p] === 'object') {
                                result = getByIdInner(obj[p], id);
                                if (result) {
                                    return result;
                                }
                            }
                        }
                    }
                    return result;
                }
                return getByIdInner(test, id);

   },