texts:
This is my implementation of Fuzzy c-Means in Python. In the main section of the code, I compared the time it takes with the sklearn implementation of kMeans.

import time
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans

def fcm(data, n_clusters=1, n_init=30, m=2, max_iter=300, tol=1e-16):

    min_cost = np.inf
    for iter_init in range(n_init):

        # Randomly initialize centers
        centers = data[np.random.choice(
            data.shape[0], size=n_clusters, replace=False
            ), :]

        # Compute initial distances
        # Zeros are replaced by eps to avoid division issues
        dist = np.fmax(
            cdist(centers, data, metric='sqeuclidean'),
            np.finfo(np.float64).eps
        )

        for iter1 in range(max_iter):

            # Compute memberships
            u = (1 / dist) ** (1 / (m-1))
            um = (u / u.sum(axis=0))**m

            # Recompute centers
            prev_centers = centers
            centers = um.dot(data) / um.sum(axis=1)[:, None]

            dist = cdist(centers, data, metric='sqeuclidean')

            if np.linalg.norm(centers - prev_centers) < tol:
                break

        # Compute cost
        cost = np.sum(um * dist)
        if cost < min_cost:
            min_cost = cost
            min_centers = centers
            mem = um.argmax(axis=0)

    return min_centers, mem

if __name__ == '__main__':
    data = np.loadtxt('grid5_edit.txt')
    labels = data[:, -1]
    k = len(np.unique(labels))
    data = data[:, 0:-1]

    repeats = 10

    # Time This
    fcm_time = 0
    for iter1 in range(repeats):
        fcm_start = time.time()
        centers, mem = fcm(
            data, n_clusters=k, n_init=30, m=2, max_iter=300, tol=1e-16
        )
        fcm_time += (time.time() - fcm_start)
    print('Average FCM time =', fcm_time/repeats)

    # Time This (as well)
    km_time = 0
    for iter1 in range(repeats):
        km_start = time.time()
        km1 = KMeans(
            n_clusters=k, n_init=30, max_iter=300, tol=1e-16
        ).fit(data)
        km_time += (time.time() - km_start)
    print('Average kMeans time =', km_time/repeats)

    print('Ratio of time =', fcm_time / km_time)

It seems the code is around 15 to 16 times slower than kMeans.

Average FCM time = 3.7663435697555543
Average kMeans time = 0.24237003326416015
Ratio of time = 15.539642087892112

Other than a code review, I'm also hoping for any suggestions to make the code faster.


texts:
I've written the following code to find the connected components of a graph in ruby, but it is quite slow since I don't use any sensible data structure for the disjoint sets, and hence find_set is probably \$O(n^2)\$ (don't know the complexity for enumerable.find in Ruby).

Can anybody help me improve it? I am relatively new to ruby, and so would appreciate any insights. This code is meant to solve the problem posed Here:

My solution, in plain English, is the find the number of connected components in the graph given, then either calculate the cost of building a library in every node or the cost of building a library in each connected component plus the cost of building the roads for the minimum spanning tree of each component.

The Code

#!/bin/ruby

require 'set'

def roadsAndLibraries(n, c_lib, c_road, cities)
  vertices = make_set((1..n).to_a)

  #find connected components
  cities.each do |a, b|
    first_set = find_set(vertices, a)
    second_set = find_set(vertices, b)
    if first_set != second_set
      vertices.add(first_set | second_set)
      vertices.delete(first_set)
      vertices.delete(second_set)
    end
  end

  #calculate the cost of building the edges required for a MST of each component
  roads_cost = c_road * vertices.to_a.map{|x| x.size - 1}.inject(:+)

  if c_road > c_lib
    return n * c_lib
  else
    return vertices.size * c_lib + roads_cost
  end

end

#takes an array of integers, and maps them into a set of singleton sets containing each node number
def make_set(arr_n)
  vertices = Set.new
  for i in 1..arr_n.size
    vertices.add([i])
  end
  vertices.map!{|x| x.to_set}
end

#finds set containing a given node value
def find_set(set, node)
  set.find{|x| x.include?(node)}
end

# q is number of queries, n is the number of vertices in the graph
q = gets.strip.to_i
for a0 in (0..q-1)
  n, m, c_lib, c_road = gets.strip.split(' ')
  n = n.to_i
  m = m.to_i
  c_lib = c_lib.to_i
  c_road = c_road.to_i
  cities = Array.new(m)
  for cities_i in (0..m-1)
    cities_t = gets.strip
    cities[cities_i] = cities_t.split(' ').map(&:to_i)
  end
  result = roadsAndLibraries(n, c_lib, c_road, cities)
  puts result
end


texts:
I am a beginner with Erlang and currently making my way through the awesome Joe Armstrong's book. The following are my answers to exercises 5 and 6 for the concurrency chapter. The code can probably be much better but at least it seems to work fine after some tests. I'm just happy to be able to understand this language, I'm def having to re-learn how to think about my programming logic, and I think that's a good thing.

5) Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, restart it.

ex5_start(FList) ->
    spawn(fun() ->
        [bring_back(F) || F <- FList]
        end).

bring_back(FID) ->
    spawn(fun() ->
        {Pid, Ref} = spawn_monitor(FID),
            io:format("Pid = ~p~n",[Pid]),
            receive
                {'DOWN', Ref, process, Pid, normal} -> void;
                {'DOWN', Ref, process, Pid, _Why} -> bring_back(FID)
            after infinity -> void
            end
        end).

6) Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, kill all the worker processes and restart them all.

ex6_start(Flist) when is_list(Flist) ->
    Size = length(Flist),
    spawn(fun() ->
            {Pid,Ref} = spawn_monitor(fun() ->
                                        start_and_monitor(Size,Flist),
                                        receive
                                        after infinity -> true
                                        end
                                    end),
            receive
                {'DOWN',Ref,process,Pid,_} -> io:format("All dead. Restarting.~n") ,
                ex6_start(Flist)
            end
        end).

start_and_monitor(1,Flist) ->
    Fun = lists:nth(1,Flist),
    Pid = spawn_link(Fun),
    io:format("Pid ~p created.~n",[Pid]);
start_and_monitor(N,Flist) ->
    Fun = lists:nth(N,Flist),
    Pid = spawn_link(Fun),
    io:format("Pid ~p created.~n",[Pid]),
    start_and_monitor(N-1,Flist).


texts:
I implemented a Python version of KMP followed by Princeton Prof Robert Sedgewick's discussion.

However, I got a Time Limit Exceeds error. Per leetcode's explanation, TLE indicates that the solution is correct but it is extremely inefficient when test case with huge input size.

If I understand TLE correctly, this means that my solution works, but some part of my solution should be inefficient and need to be enhanced? Would this be due to an extremely large space cost when precomputing the DFA table?

class Solution(object):

    def dfa(self, haystack, needle):

        R = 256 # R : the alphabet size . We set 256 for ASCII
        M = len(needle) # M : the patten length

        # create a dictionary to encode every unique char from needle with a unique int value for later dfa retrieval.
        global needle_dict
        #needle_dict = dict(zip(list(set(needle)), range(len(list(set(needle))))))
        needle_dict = dict(zip(list(set(needle).union(set(haystack))), range(len(list(set(needle).union(set(haystack)))))))
        # create dfa table, where the # of dfa columns is M, the # of dfa rows is R.
        dfa = [[0 for i in range(M)] for j in range(R)]

        # At state 0  find the first char in the needle and set this first char's corresponding state as 1
        dfa[needle_dict[needle[0]]][0] = 1

        X = 0 # X to record previous state

        for state in range(1, M): # dfa column
            for row in range(0, R): # dfa row
                dfa[row][state] = dfa[row][X] # copy mismatch cases
            dfa[needle_dict[needle[state]]][state] = state + 1 # update the match case for present state
            X = dfa[needle_dict[needle[state]]][X] # update X

        return dfa

    def strStr(self, haystack, needle):
        if len(needle) == 0:
            return 0
        if (haystack == None or needle == None or len(haystack) < len(needle) ):
            return -1
        # precompute dfa[][]from pattern
        dfa_table = self.dfa(haystack, needle)

        i, state = 0, 0
        while (i < len(haystack) and state < len(needle)):
            state = dfa_table[needle_dict[haystack[i]]][state]
            i += 1

        if state == len(needle):
            return i - len(needle)
        else:
            return -1


texts:
I am doing a project where I use DLL's as run-time modules or plugins. To do this, I use the Windows LoadLibrary() and FreeLibrary() API calls to call two functions exported by the DLL. I decided to make a class so dealing with the DLL's would be easier. Is there anything I can add to my class to make it better, is there anything I'm doing wrong? Feel free to criticize anything you want.

SaModule.h

#ifndef SAMODULE_H__
#define SAMODULE_H__

#include <Windows.h>
#include <string>
#include <exception>
#include "WinException.h"

class SaModule
{
private:

    typedef const char* (*LPFNGETNAME)();
    typedef bool (*LPFNDOSCAN)(std::string&, std::string&);
    HINSTANCE hInstance;
    std::string path;

public:

    SaModule();
    SaModule(const std::string& path);
    ~SaModule();

    void Load(const std::string& path);
    void Unload();

    LPFNDOSCAN DoScan;
    LPFNGETNAME GetName;

    HINSTANCE GetHandle() const;
    operator HINSTANCE() const;

};

#endif//SAMODULE_H__

SaModule.cpp

#include "SaModule.h"
#include "WinException.h"
#include <sstream>
#include <iomanip>

SaModule::SaModule(): path(), hInstance(NULL)
{
    //Nothing...
}

SaModule::SaModule(const std::string& path): path(path), hInstance(NULL)
{
    Load(path);
}

SaModule::~SaModule()
{
    Unload();
}

void SaModule::Load(const std::string& path)
{

    this->path = path;

    if( NULL == (hInstance=LoadLibrary(path.c_str())) )
        throw WinException();

    if( NULL == (GetName=reinterpret_cast<LPFNGETNAME>(GetProcAddress(hInstance,"GetName"))) )
        throw WinException();

    if( NULL == (DoScan=reinterpret_cast<LPFNDOSCAN>(GetProcAddress(hInstance, "DoScan"))) )
        throw WinException();

}

void SaModule::Unload()
{
    FreeLibrary(hInstance);
}

HINSTANCE SaModule::GetHandle() const
{
    return hInstance;
}

SaModule::operator HINSTANCE() const
{
    return hInstance;
}

WinException.h

#ifndef WINEXCEPTION_H__
#define WINEXCEPTION_H__

#include <Windows.h>
#include <exception>
#include <string>

class WinException: public std::exception
{
private:

    DWORD dwError;
    std::string errMsg;

public:

    WinException();
    const char* what() const;

};

#endif//WINEXCEPTION_H__

WinException.cpp

#include "WinException.h"
#include <sstream>
#include <iomanip>

WinException::WinException()
{

    std::ostringstream ss;
    dwError = GetLastError();
    LPVOID lpMsgBuf = NULL;

    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, dwError, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), reinterpret_cast<LPTSTR>(&lpMsgBuf), 0, NULL);

    ss << "Error: 0x" << std::hex << std::setfill('0') << std::setw(8) << dwError << std::endl
        << reinterpret_cast<LPTSTR>(lpMsgBuf);

    errMsg = ss.str();

    LocalFree(lpMsgBuf);

}

const char* WinException::what() const
{
    return errMsg.c_str();
}

Example Usage

#include <iostream>
#include "SaModule.h"

int main(int argc, char* argv[])
{

    try
    {
        SaModule mod("some.sa.dll");
        std::cout << "Loaded Module: " << mod.GetName() << std::endl;
    }
    catch( WinException& ex )
    {
        std::cout << ex.what() << std::endl;
    }

    return 0;

}


texts:
Over the past year I've found myself moving from back-end development to something more akin to full-stack development. I've created the following jQuery plugin as a test of my hopefully-not-so-fledgling JavaScript/jQuery skills. The plugin is used to inject <option> tags into the element(s) specified, and should follow the guidelines for creating basic plugins posted here.

(function($) {
  $.fn.injectOptions = function(opts) {
    opts = opts.map(function(opt) {
      if (typeof opt === 'string')
        return '<option>'+opt+'</option>';
      return '<option value="'+opt.key+'">'+opt.val+'</option>';
    });
    var optHTML = opts.reduce(function(html, opt) { return html+opt; });
    this.each(function() { $(this).html(optHTML); });
    return this;
  };
}(jQuery));

//example:
var fooArr = ["foo", "bar", "baz", "faz"];
var quxArr = [
  { key: 1, val: "qux"},
  { key: 2, val: "quux"},
  { key: 3, val: "quuux"},
];

$(".foo-options").injectOptions(fooArr);
$(".qux-options").injectOptions(quxArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="foo-options">
</select>
<select class="qux-options">
</select>
<select class="qux-options">
</select>

Any/all suggestions are welcome!


texts:
Solved, question with improved code
I've created a simple npm module and CLI program to get the latest GitHub and Bitbucket release from their APIs using Node.js. Please tell me if there's anything to improve!
Module code:
#!/usr/bin/env node
const fetch = require("node-fetch");

/**
 * @param {string} string
 * @return {string}
 */
const normalize = (string) => {
    try {
        return string.toUpperCase().trim()
    } catch (e) {
        return string
    }
}

/**
 * @param {string} provider
 * @param {string} user
 * @param {string} repo
 * @param {string} part
 */
module.exports.getRelease = async ({provider, user, repo, part = ""}) => {
    if (normalize(provider) === normalize("github")) {
        let json = (await (await fetch(`https://api.github.com/repos/${user}/${repo}/releases/latest`)).json())
        if (json.message === "Not Found") throw "Invalid repository"
        if (!("assets" in json)) throw "Rate limit exceeded"
        let browser_download_urls = json.assets.map(asset => asset.browser_download_url)
        return browser_download_urls.filter(url => url.includes(part))
    } else if (normalize(provider) === normalize("bitbucket")) {
        let json = (await (await fetch(`https://api.bitbucket.org/2.0/repositories/${user}/${repo}/downloads/`)).json())
        if (json.type === "error") throw "Invalid repository"
        let links = json.values.map(value => value.links.self.href)
        return links.filter(url => url.includes(part))
    } else {
        throw "Invalid provider"
    }
}

const usage = _ => {
    console.log(
        `Usage: get-release (github|bitbucket) user repo [partofreleasefile]
   Ex: get-release github phhusson treble_experimentations
       get-release github phhusson treble_experimentations arm64-ab-gapps
       get-release bitbucket JesusFreke smali
       get-release bitbucket JesusFreke smali baksmali`
    )
    process.exit(1)
}

// If via CLI
if (require.main === module) {
    let args = process.argv.slice(2)
    if (args.length !== 3 && args.length !== 4) {
        usage()
    }
    module.exports.getRelease({
        provider: args[0],
        user: args[1],
        repo: args[2],
        part: args[3]
    }).then(result => {
        if (result.length !== 1) {
            console.log(result)
        } else {
            console.log(result[0])
        }
    }).catch(error => {
        console.log(error)
        usage()
        process.exit(1)
    })
}

Called using:
const { getRelease } = require("get-release")
;(async _ => {
  let url = await getRelease(
      {
          provider: "github",
          user: "phhusson",
          repo: "treble_experimentations",
          part: "arm64-ab-gapps"
      }
  )
  console.log(url[0])
})()


texts: Implementation of Equals and GetHashCode for base class

texts:
Is this a good implementation for Equals and GetHashCode for a base class in C#? If it's not good enough, can you suggest improvements for it, please?

public abstract class Entity<TKey>    //TKey = Type of the Key
{
    private string FullClassName;
    private bool KeyIsNullable;
    private Type BaseClassType;
    private bool KeyIsComplex;

    public abstract TKey Key { get; }    //Key of the object, which determine it's uniqueness

    public Entity()
    {
        FullClassName = GetType().FullName + "#";
        KeyIsNullable = typeof(TKey).IsAssignableFrom(typeof(Nullable));
        BaseClassType = typeof(Entity<TKey>);
        KeyIsComplex= !typeof(TKey).IsPrimitive;
    }

    public override bool Equals(object obj)
    {
        bool result = BaseClassType.IsAssignableFrom(obj.GetType());
        result
            = result
                && (
                        (
                            (
                                !KeyIsNullable
                                ||
                                (Key != null && ((Entity<TKey>)obj).Key != null
                            )
                        )
                        &&
                        Key.Equals(((Entity<TKey>)obj).Key )
                    )    // The key is not nullable, or (it's nullable but) both aren't null, and also equal
                    ||
                    (
                        KeyIsNullable
                        &&
                        Key == null
                        &&
                        ((Entity<TKey>)obj).Key == null
                    )
                ); // Or the key is nullable, and both are null
        return result;
    }

    public override int GetHashCode()
    {
        if ((KeyIsNullable&& Key == null) || (!KeyIsNullable&& Key .Equals(default(TKey))))
        {
            return base.GetHashCode();
        }
        string stringRepresentation = FullClassName + ((KeyIsComplex)? Key.GetHashCode().ToString() : Key.ToString());
        return stringRepresentation.GetHashCode();
    }
}

Example of a derived class:

public class Foo : Entity<int>
{
    public virtual int FooId { set; get; }
    public virtual string FooDescription { set; get; }

    public override int Key { get { return FooId; } }
}

Specific and special details to the proposal:

Any instance of a derived class is considered equal to a instance of the base class if they have the same key.
The key could be null.
If the key of the current class and the key of the comparing object are both null, the two objects are considered equal. This is because I am planning to handle just one new object at a time, and if the key is nullable, it will be null for the new object. So if I have two instances with a null key, I will consider them as the same entity.


texts: Small script to verify hash of a downloaded file

texts:
You know how whenever you download a file you should really compare the hash of the download to the one provided on the website? This makes absolute sense, but it's a pain to do it letter for letter, digit for digit. So, I wrote this little script to take care of the job. Any comments are welcome.

#!/bin/bash

# hash_checker - program to verify a downloaded file

error_exit()
{
    echo "$1" 1>&2
    exit 1
}

usage="usage: hash_checker downloaded_file hash_provided -a algorithm"
downloaded_file=
hash_given=
hash_calc=
algo="sha256"

# check if file and hash were provided
if [ $# -lt 2 ]; then
    error_exit "$usage"
fi

# parsing the provided hash and file
downloaded_file="$1"
hash_given="$2"

# parsing the algorithm, if provided
if [ "$3" != "" ]; then
    if [ "$3" = "-a" ]; then
        algo="$4"
    else
        error_exit "$usage"
    fi
fi

# check if input is a valid file
if [ ! -f "$downloaded_file" ]; then
    error_exit "Invalid file! Aborting."
fi

# calculate the hash for the file
hash_calc="$($algo'sum' $downloaded_file)"
hash_array=($hash_calc)
hash_calc=${hash_array[0]}

# compare the calculated hash to the provided one
if [ "$hash_calc" = "$hash_given" ]; then
    echo "The hashes match. File seems to be valid."
else
    echo "The hashes do not match. File does not seem to be valid."
fi


texts:
I'm working on a login system in Go (Golang). Previously, I was using Gorilla Sessions for this, but I wanted to see if I could reinvent the wheel and make it simpler.

Also, I don't need to store many user values—just one: whether a user is logged in or not. For this, I decided to use a map.

sessions := make(map[string]bool)

When a user tries to login, this function gets called.

func tryLogin(username, password string) (http.Cookie, error) {
    if exists := db.UserExists(username, password); !exists {
        return http.Cookie{},
            errors.New("The username or password you entered isn't correct.")
    }

    sid, err := randString(32)
    if err != nil {
         return http.Cookie{}, err
    }

    sessions[sid] = true

    loginCookie := http.Cookie{
        Name:     "id",
        Value:    sid,
        MaxAge:   int((time.Hour * 12).Seconds()),
        HttpOnly: true,
        Domain:   "mydomain.com",
        Path:     "/admin/",
    }

    return loginCookie, nil
}

My randString function, which I use to generate a session ID, just reads random bytes and base64 encodes them.

func randString(size int) (string, error) {
    buf := make([]byte, size)

    if _, err := rand.Read(buf); err != nil {
        log.Println(err)
        return "", errors.New("Couldn't generate random string")
    }

    return base64.URLEncoding.EncodeToString(buf)[:size], nil
}

If a user exists in my database, then they get redirected to an admin area. One of the first things I do on every admin page is call sessionExists to make sure they're still logged in.

func sessionExists(req *http.Request) bool {
    cookie, err := req.Cookie("id")
    if err == http.ErrNoCookie {
        return false
    } else if err != nil {
        log.Println(err)
        return false
    }

    if _, exists := sessions[cookie.Value]; !exists {
        return false
    }

    return true
}

If sessionExists returns false, then I redirect the user to the login page.

I don't currently have HTTPS working, so I can't turn on the secure flag on my login cookie. But besides that, would this design provide adequate protection against intruders?


texts: DateTime Extensions StartOfWeek, StartOfMonth and WorkingDays

texts:
I have Developed an Extension for DateTime in order to get the start of the week or start of the month (1-xx-xxxx) given a DateTime, and the working days of a month given a datetime and a list with bank days (Type DayOfWeek)

Any suggestions to improve it?

 public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {

        int diff = ((dt.DayOfWeek - startOfWeek)) % 7;

        if (startOfWeek == DayOfWeek.Sunday)
            return dt.AddDays((7+(startOfWeek - dt.DayOfWeek)) % 7).Date;
        return dt.AddDays(-1 * diff).Date;
    }

    public static DateTime StartOfMonth(this DateTime dt)
    {
        return new DateTime(dt.Year, dt.Month, 1);
    }

    public static int WorkingDays(this DateTime dt, IList<DayOfWeek> freeDays)
    {
        var workingDays = 0;
        var current = new DateTime(dt.Year, dt.Month, 1);
        var nextMonth = current.AddMonths(1);

        while (current < nextMonth)
        {
            if (!freeDays.Contains(current.DayOfWeek))
                workingDays++;
            current =current.AddDays(1);
        }
        return workingDays;
    }
    public static int WorkingDays(this DateTime dt, IList<DayOfWeek> freeDays, IList<DateTime> bankDays)
    {
        var workingDays = 0;
        var current = new DateTime(dt.Year, dt.Month, 1);
        var nextMonth = current.AddMonths(1);

       while (current < nextMonth)
       {
           if (!freeDays.Contains(current.DayOfWeek) && !bankDays.Contains(current))
               workingDays++;
            current =current.AddDays(1);
    }
    return workingDays;
   }

}


texts: I want a nice design pattern for "All", "many" or "one"

texts:
In my particular usage here, I'm using two functions to deal with one thing.

Lets say the user request comes in to select "ALL" the records, in which case I would pass on some code such as:

function getRecords() {
    return some_sql("Select * from whatever WHERE id > 0;");
}

But then I want to run just one record, I'd do

function getRecords(SomeID) {
    return some_sql("Select * from whatever WHERE id = SomeID;");
}

And if I wanted to get a specific list of records, I'd do something like

function getRecordsByID(someArray(1,2,3,10,11,99)) {
    var someIDs = "";
    for (i in someArray) {
        someIDs = "(" + someArray.join(",")  + ")";
    }
    return some_sql("Select * from whatever WHERE id IN SomeIDs;");
}

It dawns on me that I could of course use getRecordByID everywhere I've used getRecord, but I can't do this for getRecords.

Is there a common or overlooked design pattern I'm missing here? My first guess would be something like checking the argument's contents for a valid array and running based on that, but I'd like to see a better option.


texts:
I've created a class that's used for cleaning variables for use. You set a name, value and options and it will set the value if it matches the criteria/options.

It is used like this:

$var = new Variable();
$var->clean('username', $_POST['username'], '3,13,alphanumeric,True');
echo 'Username', $var->clean("username");
echo 'Username', $var->html("username");

It seems very messy and as though it could be done in a better way.

<?php
include_once __DIR__ . '/header.php';

class Variable
{
    var $clean = array(); // Filtered data
    var $html = array(); // Escaped htmlentities() data

    /**
     * variable->addClean()
     *
     * @param mixed $name - Name of clean value
     * @param mixed $value - Value to clean
     * @param string $options - Options in the format specified
     * @return mixed - Clean value.
     *
     * Options format:
     *    {min length} - set to -1 to ignore.
     *    {max length} - set to -1 to ignore.
     *    {type} - set to null to ignore. Types:
     *       - Numeric.
     *       - AlphaNumeric.
     *       - Alpha.
     *    {trim} - default is true.
     *
     *    eg.
     *    $var = new Variable();
     *    $var->clean('username', $_POST['username'], '3,13,alphanumeric,True');
     *    echo 'Username', $var->clean("username");
     *
     */
    public function clean($name, $value = null, $options = '')
    {
        if ($value === null && $name !== null)
            return isset($this->clean[$name]) ? $this->clean[$name] : null;

        else if ($value !== null && $name !== null) {
            if (!empty($options)) {
                list($minlen, $maxlen, $type, $trim) = array_pad(explode(',', (string)$options), 4, '');

                if (strtolower($trim) !== 'false')
                    $value = trim($value);

                if ($minlen !== '-1')
                    if (!(strlen($value) > $minlen))
                        return false;

                if ($maxlen !== '-1')
                    if (!(strlen($value) < $maxlen))
                        return false;

                switch (strtolower($type)) {
                    case 'numeric':
                        if (is_numeric($value))
                            $this->clean[$name] = intval($value);
                        break;
                    case 'alphanumeric':
                        if (ctype_alnum($value))
                            $this->clean[$name] = $value;
                        break;
                    case 'alpha':
                        if (ctype_alpha($value))
                            $this->clean[$name] = $value;
                        break;
                    default:
                        $this->clean[$name] = $value;
                        break;
                }
            } else
                $this->clean[$name] = $value;
        }
        return isset($this->clean[$name]);
    }

    public function isClean($name)
    {
        return isset($this->clean[$name]);
    }

    public function html($name)
    {
        if (!isset($this->html[$name]) && isset($this->clean[$name]))
            $this->html[$name] = htmlentities($this->clean[$name], ENT_QUOTES, 'UTF-8');

        return (isset($this->html[$name]) ? $this->html[$name] : null);
    }
}


texts: Find all possible words in a board of characters

texts:
This question has 2 possible solutions and I am trying to implement the DFS solution.

Here is the Trie and DFS solution: Boggle using Trie and DFS

Please review for performance.

  Given a dictionary, a method to do lookup in dictionary and a M x N
  board where every cell has one character. Find all possible words that
  can be formed by a sequence of adjacent characters. Note that we can
  move to any of 8 adjacent characters, but a word should not have
  multiple instances of same cell.

Example:

Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"};
       boggle[][]   = {{'G', 'I', 'Z'},
                       {'U', 'E', 'K'},
                       {'Q', 'S', 'E'}};
      isWord(str): returns true if str is present in dictionary
                   else false.

Output:  Following words of dictionary are present
         GEEKS
         QUIZ

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GraphsQuestions
{
    /// <summary>
    /// https://www.geeksforgeeks.org/boggle-find-possible-words-board-characters/
    /// </summary>
    [TestClass]
    public class BoggleDfs
    {
        private List<string> _list = new List<string>();
        [TestMethod]
        public void GeeksForGeeksTest()
        {
            string[] dictionary = { "GEEKS", "FOR", "QUIZ", "GO" };
            char[,] boggle = {{'G', 'I', 'Z'},
                              {'U', 'E', 'K'},
                              {'Q', 'S', 'E'}};

            FindWords(boggle, dictionary);
            string[] expected = { "GEEKS", "QUIZ" };
            CollectionAssert.AreEqual(expected,_list.ToArray());
        }

        private void FindWords(char[,] boggle, string[] dictionary)
        {
            bool[,] visited = new bool[boggle.GetLength(0), boggle.GetLength(1)];
            StringBuilder str = new StringBuilder();
            //run DFS for all the options and compare with the dictionary
            for (int i = 0; i < boggle.GetLength(0); i++)
            {
                for (int j = 0; j < boggle.GetLength(1); j++)
                {
                    DFS(i, j, boggle, dictionary, str, visited);
                }
            }
        }

        private void DFS(int i, int j, char[,] boggle, string[] dictionary, StringBuilder str, bool[,] visited)
        {
            //mark we already visited this vertex
            visited[i, j] = true;

            str.Append(boggle[i, j]);
            if (IsWord(str.ToString(), dictionary))
            {
                _list.Add(str.ToString());
            }

            for (int row = i - 1; row <= i + 1 && row < boggle.GetLength(0); row++)
            {
                for (int col = j - 1; col <= j + 1 && col < boggle.GetLength(1); col++)
                {
                    if (col >= 0 && row >= 0 && !visited[row, col])
                    {
                        DFS(row, col, boggle, dictionary, str, visited);
                    }
                }
            }

            visited[i, j] = false;
            str.Remove(str.Length - 1, 1);
        }

        private bool IsWord(string str, string[] dictionary)
        {
            for (int i = 0; i < dictionary.Length; i++)
            {
                if (string.CompareOrdinal(str, dictionary[i]) == 0)
                {
                    return true;
                }
            }
            return false;
        }
    }
}


texts: Parsing a text file into a pandas DataFrame

texts:
I have a .txt file that looks like this:
SHT1 E:   T1:30.45°C    H1:59.14 %RH
SHT2 S:   T2:29.93°C    H2:67.38 %RH

SHT1 E:   T1:30.49°C    H1:58.87 %RH
SHT2 S:   T2:29.94°C    H2:67.22 %RH

SHT1 E:   T1:30.53°C    H1:58.69 %RH
SHT2 S:   T2:29.95°C    H2:67.22 %RH

I want to have a DataFrame that looks like this:
      T1     H1     T2     H2
0  30.45  59.14  29.93  67.38
1  30.49  58.87  29.94  67.22
2  30.53  58.69  29.95  67.22

I parse this by:

Reading up the text file line by line
Parsing the lines e.g. matching only the parts with T1, T2, H1, and H2, splitting by :, and removing °C and %RH
The above produces a list of lists each having two items
I flatten the list of lists
Just to chop it up into a list of four-item lists
Dump that to a df
Write to an Excel file

Here's the code:
import itertools

import pandas as pd

def read_lines(file_object) -> list:
    return [
        parse_line(line) for line in file_object.readlines() if line.strip()
    ]

def parse_line(line: str) -> list:
    return [
        i.split(":")[-1].replace("°C", "").replace("%RH", "")
        for i in line.strip().split()
        if i.startswith(("T1", "T2", "H1", "H2"))
    ]

def flatten(parsed_lines: list) -> list:
    return list(itertools.chain.from_iterable(parsed_lines))

def cut_into_pieces(flattened_lines: list, piece_size: int = 4) -> list:
    return [
        flattened_lines[i:i + piece_size] for i
        in range(0, len(flattened_lines), piece_size)
    ]

with open("your_text_data.txt") as data:
    df = pd.DataFrame(
        cut_into_pieces(flatten(read_lines(data))),
        columns=["T1", "H1", "T2", "H2"],
    )
    print(df)
    df.to_excel("your_table.xlsx", index=False)

This works and I get what I want but I feel like points 3, 4, and 5 are a bit of redundant work, especially creating a list of list just to flatten it and then chop it up again.

Question:
How could I simplify the whole parsing process? Or maybe most of the heavy-lifting can be done with pandas alone?
Also, any other feedback is more than welcomed.


texts: Countdown to multiple update times each day

texts:
I'm creating an update function to show my users when the next update will be available. I'm using the jQuery countdown plugin to show the time. What is a more efficient way to write this?

today = new Date();
todayDay = today.getDate();
todayYear = today.getFullYear();
todayMonth = today.getMonth();
todayMonth ++;
var countTo = "";
// $('#countdown').countdown('12:00:00');
var morningUpdate = new Date();
morningUpdate.setHours(10,0,0,0);

var middayUpdate = new Date();
middayUpdate.setHours(14,0,0,0);

var afternoonUpdate = new Date();
afternoonUpdate.setHours(17,0,0,0);

if(today < afternoonUpdate) {
 countTo = "17:00:00";
}

if(today < middayUpdate) {
    countTo = "14:00:00";
}

if(today < morningUpdate) {
    countTo = "10:00:00";
}

todayString = todayYear + "/" + todayMonth + "/" + todayDay;
console.log(todayString);
var countDownTo = todayString + " " + countTo;
console.log(countDownTo);
console.log("2015/5/13 12:00:00");

$('#clock').countdown(countDownTo, function(event) {
    var totalHours = event.offset.totalDays * 24 + event.offset.hours;
    $(this).html(event.strftime(totalHours + ' hr %M min %S sec'));
});


texts: Note class for managing information on various musical notes

texts:
I just finished (re)reading Clean Code, and one of the ideas I learned was the SRP. However, I am not quite sure on what defines a "Single Responsibility." In the piece of code below, I have a Note class which I think may be doing too many things; it stores pitch and length, and converts these into a Names enum and a Lengths enum. Is this more than one responsibility, and if so, how should I define the classes instead?  Other tips are welcome as well).

public class Note {

    public enum Lengths {
        DOUBLE_WHOLE_NOTE(0.5f),
        ...
        SIXTYFOURTH_NOTE(64);

        private float length;

        Lengths(float length) {

            this.length = length;
        }

        public float getLength() {

            return length;
        }

        private static final Map<Float, Lengths> lookup = new HashMap<Float, Lengths>();
        static {
            for (Lengths length : Lengths.values())
                lookup.put(length.getLength(), length);
        }

        public static Lengths get(float length) {

            return lookup.get(length);
        }

    }

    public enum Names {
        C(0),
        ...
        REST(-1);

        private final int number;

        Names(int number) {

            this.number = number;
        }

        public int getValue() {

            return number;
        }

        private static final Map<Integer, Names> lookup = new HashMap<Integer, Names>();
        static {
            for (Names name : Names.values())
                lookup.put(name.getValue(), name);
        }

        public static Names get(Integer value) {

            return lookup.get(value);
        }

    }

    private int pitch;
    private float length;

    public int getPitch() {

        return pitch;
    }

    public void setPitch(int pitch) {

        this.pitch = pitch;
    }

    public float getLength() {

        return length;
    }

    public void setLength(float length) {

        this.length = length;
    }

    private Note(int pitch, float length) {

        this.length = length;
        this.pitch = pitch;
    }

    public int getOctave() {

        return (pitch / 12) - 5;
    }

    public Note.Names getNameOfNote() {

        return Names.get(this.getPitch() % 12);
    }

    public Note.Lengths getLengthOfNote() {

        return Lengths.get(this.getLength());
    }

}


texts: Find Single Element in a Sorted Array, from LeetCode

texts:
The problem quoted:

https://leetcode.com/problems/single-element-in-a-sorted-array/

Given a sorted array consisting of only integers where every element appears exactly twice except for one element which appears exactly once. Find this single element that appears only once.

Example 1:

Input: [1,1,2,3,3,4,4,8,8]
Output: 2

Example 2:

Input: [3,3,7,7,10,11,11]
Output: 10

Note: Your solution should run in O(log n) time and O(1) space.

The answer:

var singleNonDuplicate = function(nums) {
    var low = 0, high = nums.length - 2, mid;

    while (low < high) {
        mid = low + Math.floor((high - low) / 2);
        if (mid % 2 === 1) mid--;           // make sure it is even

        if (nums[mid] !== nums[mid+1]) {    // the single element already happened on the left
            high = mid - 1;
        } else {
            low = mid + 2;
        }
    }
    return nums[low];
};

The fourth line:

while (low < high) {

if changed to

while (low <= high) {

can also pass all tests on the website. But which version is correct or more robust?

I also had to decide whether it is better to set the initial high to

high = nums.length - 2

or to

high = nums.length - 1

The same with

high = mid - 1;

I wonder if it is best to set it to mid - 1 or mid - 2.

It seems it can be complicated near the "end game", when there are 3, 5, 7, 9 remaining array elements, when the mid, low, high can be calculated in the way that the loop will not terminate or find the incorrect answer. If there are many elements remaining, such as 21, 31, etc, the algorithm in general works. It seems you have to consider the small cases when the number of remaining elements is small.


texts: Project Euler 25 - 1000-digit Fibonacci Number

texts:
I have recently completed problem 25 from the project Euler site.

  The Fibonacci sequence is defined by the recurrence relation:

  \$\qquad F_n = F_{n−1} + F_{n−2}\$, where \$F_1 = 1\$ and \$F_2 = 1\$.

  Hence the first 12 terms will be:

  \$\qquad F_1 = 1\$

  \$\qquad F_2 = 1\$

  \$\qquad F_3 = 2\$

  \$\qquad F_4 = 3\$

  \$\qquad F_5 = 5\$

  \$\qquad F_6 = 8\$

  \$\qquad F_7 = 13\$

  \$\qquad F_8 = 21\$

  \$\qquad F_9 = 34\$

  \$\qquad F_{10} = 55\$

  \$\qquad F_{11} = 89\$

  \$\qquad F_{12} = 144\$

  The 12th term, \$F_{12}\$, is the first term to contain three digits.

  What is the first term in the Fibonacci sequence to contain 1000 digits?

I have solved this problem in Java, however, the execution time is fairly slow, and, I am looking for ways to improve it; below is my code, as well as the output given:

import java.util.ArrayList;
import java.math.BigInteger;
public class ProjectEuler25 {
  public static void main(String [] args) {
    long start = System.nanoTime();
    ArrayList<BigInteger> fibonacciNumbers = new ArrayList<BigInteger>();
    boolean validNo = true;
    int x = 2;
    BigInteger tempAns = null;
    fibonacciNumbers.add(BigInteger.valueOf(1));
    fibonacciNumbers.add(BigInteger.valueOf(1));
    do {
        tempAns = fibonacciNumbers.get(x-1).add(fibonacciNumbers.get(x-2));
        fibonacciNumbers.add(tempAns);
        x++;
        if(tempAns.toString().length() >= 1000) {
            validNo = false;
        }
    } while (validNo == true);
    Long stop = System.nanoTime();
    System.out.println("The first term in the Fibonacci sequence to contain 1,000 digits is term: " + fibonacciNumbers.size());
    System.out.println("Execution time: " + ((stop - start) / 1e+6) + " ms");
  }
}

Output:

  The first term in the Fibonacci sequence to contain 1,000 digits is term: 4782

  Execution time: 220.858659 ms

I know that it is possible to solve this problem in C# in 2ms. I have provided the code for this solution below:

int i = 0;
int cnt = 2;
BigInteger limit = BigInteger.Pow(10, 999);
BigInteger[] fib = new BigInteger[3];

fib[0] = 1;
fib[2] = 1;

while (fib[i] <= limit) {
    i = (i + 1) % 3;
    cnt++;
    fib[i] = fib[(i + 1) % 3] + fib[(i + 2) % 3];
}

C# code sourced from here.

From looking at the C# code, the one thing which stands out to me, is maybe there is a better way to store the previous numbers than using an ArrayList?


texts:
               <?php
                   for($i = 1; $i <= 3; $i++) {
                      $marginRight = ($i < 3 ? "margin-right:4px" : "");
                      echo "
";
                      echo "{$i}. Kind";
                      echo "<select id='param_kind{$i}' class='selFields' name='param_kind{$i}' style='margin-top:3px'>";
                      echo  "<option selected='' value='-1'>--- </option>";
                      for($j = 1; $j <= 16; $j++) {
                         $selected = ($oRecherche->getParamValue("param_kind{$i}") == $j ? "selected='selected'" : "");
                         $option_text = ($j == 1 ? "&lt; 2 Jah." : $j + "Jahre");
                         echo "<option value='{$j}' {$selected}>{$option_text}</option>";
                      }
                      echo "</select>";
                      echo "
";
                   }
               ?>


texts:
I would like to know whether I could make my solution to this challenge shorter and more efficient. Below is the description of the challenge (this is a Leetcode problem) -

  In the video game Fallout 4, the quest "Road to Freedom" requires
  players to reach a metal dial called the "Freedom Trail Ring", and use
  the dial to spell a specific keyword in order to open the door.

  Given a string ring, which represents the code engraved on the
  outer ring and another string key, which represents the keyword
  needs to be spelled. You need to find the minimum number of steps
  in order to spell all the characters in the keyword.

  Initially, the first character of the ring is aligned at the 12:00
  direction. You need to spell all the characters in the string key
  one by one by rotating the ring clockwise or anticlockwise to make
  each character of the string key aligned at the 12:00 direction
  and then by pressing the center button.

  At the stage of rotating the ring to spell the key character
  key[i] -

  You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is
  to align one of the string ring's characters at the 12:00
  direction, where this character must equal to the character
  key[i].
  If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also
  counts as 1 step. After the pressing, you could begin to spell the
  next character in the key (next stage), otherwise, you've finished all
  the spelling.

  Example -

Input: ring = "godding", key = "gd"
Output: 4

# Explanation:
# For the first key character 'g', since it is already in place, we just need 1 step to spell this character.
# For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
# Also, we need 1 more step for spelling.
# So the final output is 4.

  Note -

  Length of both ring and key will be in range 1 to 100.
  There are only lowercase letters in both strings and might be some duplicate characters in both strings.
  It's guaranteed that string key could always be spelled by rotating the string ring.

Here is my solution to this challenge -

# Uses dynamic programming

def find_rotate_steps(ring, key):
    """
    :type ring: str
    :type key: str
    :rtype: int
    """
    dp = [[min(i, len(ring) - i) for i in range(len(ring))]]
    dp.extend([[float('inf')] * len(ring) for _ in range(len(key))])
    for i in range(1, len(key) + 1):
        for j in range(len(ring)):
            if ring[j] != key[i - 1]:
                continue
            min_step = float('inf')
            for k in range(len(ring)):
                if dp[i - 1][k] == float('inf'):
                    continue
                step = abs(k - j)
                step = min(step, len(ring) - step) + 1 + dp[i - 1][k]
                min_step = min(min_step, step)
            dp[i][j] = min_step
    return min(dp[-1])

Here is the time taken for the example output -

# %timeit find_rotate_steps("godding", "gd")

36.2 µs ± 1.33 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Here is my Leetcode result for 302 test cases -

NOTE - Here is what dynamic programming means (according to freeCodeCamp) -

  Dynamic programming amounts to breaking down an optimization problem
  into simpler sub-problems and storing the solution to each sub-problem
  so that each sub-problem is only solved once.


texts:
Are there any other more exotic ways ... or is this one just good?

void strdev (char *str, long from, long to)
{
    char *part1 = malloc(strlen(str) - strlen(&str[from]));
    long i;

    part1[from] = '\0';

    //for(i=0; i<from; i++) part1[i] = str[i]; // Old copying
    memmove(part1, str, from); // New copying
    sprintf(str, "%s%s", part1, &str[to+1]);
    free(part1);
}


texts: Group collections by their elements property

texts:
I have a Customer class:

public class Customer
{
    public Guid Id { get; set; }
    // Some other properties...}

And three transactions classes that have a reference to Customer:

public class Order
{
    public Guid CustomerId { get; set; }
    // Some other properties...}

public class Invoice
{
    public Guid CustomerId { get; set; }
    // Some other properties...}

public class Payment
{
    public Guid CustomerId { get; set; }
    // Some other properties...}

I have a collection for each of transaction type. And I want to get this collection to be "grouped" by their elements CustomerId properties. So, as a result I'd like to get a collection of such objects:

public class CustomerInfo
{
    public CustomerInfo(Guid customerId, IEnumerable<Order> orders,
        IEnumerable<Invoice> invoices, IEnumerable<Payment> payments){...}

    public Guid CustomerId { get; set; }
    public IEnumerable<Invoice> Invoices { get; set; }
    public IEnumerable<Order> Orders { get; set; }
    public IEnumerable<Payment> Payments { get; set; }
}

Right now I am doing so by this function:

private IEnumerable<CustomerInfo> _GetCustomerInfo(
    IEnumerable<Payment> payments, IEnumerable<Invoice> invoices,
    IEnumerable<Order> orders)
{
    var invoicesGroupdByCustomers = invoices.GroupBy(x => x.CustomerId);
    var ordersGroupdByCustomers = orders.GroupBy(x => x.CustomerId);
    var paymentsGroupdByCustomers = payments.GroupBy(x => x.CustomerId);

    var result = new List<CustomerInfo>();
    foreach (var group in invoicesGroupdByCustomers)
        result.Add(new CustomerInfo(group.Key,
            ordersGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key),
            group,
            paymentsGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key)));

    foreach (var group in ordersGroupdByCustomers)
        if (!result.Any(x => x.CustomerId == group.Key))
            result.Add(new CustomerInfo(group.Key,
                group,
                invoicesGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key),
                paymentsGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key)));

    foreach (var group in paymentsGroupdByCustomers)
        if (!result.Any(x => x.CustomerId == group.Key))
            result.Add(new CustomerInfo(group.Key,
                ordersGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key),
                invoicesGroupdByCustomers.FirstOrDefault(x => x.Key == group.Key),
                group));

    return result;
}

Here is sample of calculations where I use these transactions collections:

private Dictionary<Guid, decimal> _CalculateSales(
    IEnumerable<CustomerInfo> customersSalesInfo)
{
    var result = new Dictionary<Guid, decimal>();

    foreach (var customerInfo in customersSalesInfo)
    {
        var sales = customerInfo.Invoices.Sum(x => x.Header.SubTotalAmt) +
            customerInfo.Orders.Sum(x => x.Header.SubTotalAmt) -
            customerInfo.Payments.Sum(x => x.Header.SubTotalAmt);
        result.Add(customerInfo.CustomerId, sales);
    }

    return result;
}

Is there a better approach?


texts:
I Need your help, please. I'm trying to develop a simple Questionnaire.

Here is what I did already. First, I have interfaces for Question and Answer entities.

interface IAnswerProvider{

    public function getAnswers();

}

interface IQuestionProvider{
    public function getQuestions();
}

Then I have classes which implement these interfaces. Both Answers and Questions have translations in different languages - that's why each of them have a $current_language property.

class Answer implements IAnswerProvider
{

    private $current_language = '';

    private $current_question_id = 0;

    public function __construct($current_language, $question_id = 0)
    {
        if (!empty($question_id)) {
            $this->setCurrentQuestionId($question_id);
        }

        $this->setCurrentLanguage($current_language);
    }

    public function getAnswers()
    {

        $question_id = $this->getCurrentQuestionId();

        if (empty($question_id)) {
            throw new Error('Question ID is not defined');
        }

        $query = 'select * from  answers a   where a.question_id=' . escape($question_id);

        return DB::getInstance()->fetchAllRows($query);
    }

    /**
     * @return string
     */
    public function getCurrentLanguage()
    {
        return $this->current_language;
    }

    /**
     * @param string $current_language
     */
    public function setCurrentLanguage($current_language)
    {
        $this->current_language = $current_language;
    }

    /**
     * @return int
     */
    public function getCurrentQuestionId()
    {
        return $this->current_question_id;
    }

    /**
     * @param int $current_question_id
     */
    public function setCurrentQuestionId($current_question_id)
    {
        $this->current_question_id = $current_question_id;
    }

}

class Question implements IQuestionProvider
{

    private $current_language = '';

    public function __construct($current_language)
    {
        $this->setCurrentLanguage($current_language);
    }

    /**
     * @return string
     */
    public function getCurrentLanguage()
    {
        return $this->current_language;
    }

    /**
     * @param string $current_languge
     */
    public function setCurrentLanguage($current_language)
    {
        $this->current_language = $current_language;
    }

    public function getQuestions()
    {

        $query = 'select * from questions q where language ='.escape($this->getCurrentLanguage());

        return DB::getInstance()->fetchAllRows($query);
    }

}

And here is a class which does all jobs related with questions and answers.

class Questionnaire{

    private $oQuestionProvider = '';

    private $oAnswerProvider = '';

    public function __construct(IQuestionProvider $oQueston, IAnswerProvider $oAnswer)
    {
        $this->oQuestionProvider = $oQueston;
        $this->oAnswerProvider = $oAnswer;
    }

    /**
    * Returns an array of questions , each question has answers property
    * with array of answers
    */
    public function getQuestionsWithAnswers(){

        $aData = $this->oQuestionProvider->getQuestions();

        //assign answers to each question
        foreach ($aData as $v){
            $this->oAnswerProvider->setCurrentQuestionId($v->question_id);
            $v->answers = $this->oAnswerProvider->getAnswers();
        }

        return $aData;
    }

}

What I 'm concerned about is that I have code duplication in the Question and Answer classes - I mean setCurrentLanguage and getCurrentLanguage methods. Maybe it's better to move them into some abstract class and then inherit both Answer and Question  classes from it ? Are SOLID principles being violated here?

Please let me know what do you think about this code.
Thanks


texts:
This is my simple game that gives you a country and has you enter the corresponding capital. What do you think? (Before running it you need to do score.txt.)

package com.company;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws FileNotFoundException{

        Random r = new Random();

        Scanner input = new Scanner(System.in);

        String[] capital = {"Lisbon", "Madrid", "Paris", "Berlin", "Warsaw", "Kiev", "Moscow", "Prague", "Rome"};
        String[] country = {"Portugal", "Spain", "France", "Germany", "Poland", "Ukraine", "Russia", "Czech Republic", "Italy"};
        Boolean[] was = new Boolean[9];

        int score = 0;
        int good = 0;
        int bad = 0;

        File file = new File("score.txt");
        Scanner lastscoreopener = new Scanner(file);
        String lastscore = lastscoreopener.nextLine();
        System.out.print("Your last score was: " +lastscore +"\n");

        for (int d = 1; d<4; d++) {
            int randomint = r.nextInt(9);
            while (was[randomint] == Boolean.FALSE){
                randomint = r.nextInt(9);
            }
            was[randomint] = false;

            while (was[randomint] == true);
            for (int x = 0; x < 3; x++) {
                System.out.print("What's capital of " + country[randomint] + "\n");
                String answer = input.nextLine();
                if (answer.toLowerCase().equals(capital[randomint].toLowerCase())) {
                    if (x==0){
                        score = score+3;
                        good++;
                    }
                    else if(x==1){
                        score = score+2;
                        good++;
                    }
                    else if (x==2){
                        score = score+1;
                        good++;
                    }
                    System.out.print("Good. Your score is" +score +". \n");
                    break;
                } else {
                    if (x != 2){
                        System.out.print("Bad. You have " +(2-x) +" chances. ");}
                    if (x == 2){
                        System.out.print("Bad. Good answer is" +capital[randomint] +"\n");
                    }
                    bad++;
                }
            }
        }
        System.out.print("End of game. Good answers:" +good +". Bad answers: " +bad +". Score: " +score);

        PrintWriter saver = new PrintWriter("score.txt");
        saver.println(score);
        saver.close();

    }
}


texts: Generate voxel terrain with Perlin Noise

texts:
For my chunk generator for my game, it currently uses a triple nested loop, which seems very inefficient. It also seems like I could cut down a lot of code in the function somehow. Does anyone have any ideas?

void Chunk::Generate() {
    const int octaves = 6;
    const float heightMod = 4.0f;
    const float densityMod = 8.0f;
    const float horizontalFrequency = 1.0f / 256.0f;
    const float frontalFrequency = 1.0f / 256.0f;
    const float heightMapSize = 1.0f / 512.0f;
    for (int z = m_chunkZ; z < m_chunkZ + m_chunkDepth; z++) {
        for (int x = m_chunkX; x < m_chunkX + m_chunkWidth; x++) {
            // the last type generated
            VoxelType lastType = VoxelType::SAND;
            // the height used for this part of the chunk
            int height = static_cast<int>(noise_fractal_brownian_motion(m_noise, octaves, x * horizontalFrequency, heightMapSize, z * frontalFrequency) * (m_chunkHeight * heightMod));
            int minY = m_chunkY;
            int maxY = m_chunkY + height;
            for (int y = minY; y < maxY; y++) {
                const float colorMinCap = -0.45f;
                const float colorMaxCap = 0.45f;
                const float densityXFrequency = 1.0f / 64.0f;
                const float densityZFrequency = 1.0f / 256.0f;
                const float verticalFrequency = 1.0f / (static_cast<float>(abs(height)) * heightMod);
                float density = noise_fractal_brownian_motion(m_noise, octaves, x * densityXFrequency, abs(y) * verticalFrequency, z * densityZFrequency) * (abs(height) * densityMod);
                // todo: new noise map for color
                float colorR = noise_fractal_brownian_motion(m_noise, octaves, x * densityXFrequency, 0.0f, z * densityZFrequency - 0.15f);
                float colorG = noise_fractal_brownian_motion(m_noise, octaves, x * densityXFrequency - 0.08f, 0.0f, z * densityZFrequency);
                float colorB = noise_fractal_brownian_motion(m_noise, octaves, x * densityXFrequency - 0.32f, 0.0f, z * densityZFrequency - 0.64f);
                if (colorR >= colorMaxCap)
                    colorR = colorMaxCap;
                if (colorG >= colorMaxCap)
                    colorG = colorMaxCap;
                if (colorB >= colorMaxCap)
                    colorB = colorMaxCap;
                if (colorR <= colorMinCap)
                    colorR = colorMinCap;
                if (colorG <= colorMinCap)
                    colorG = colorMinCap;
                if (colorB <= colorMinCap)
                    colorB = colorMinCap;
                if (density >= 0.0f) {
                    VoxelType type = ((y == maxY - 1 && lastType == VoxelType::DIRT) ? VoxelType::GRASS : _GetTypeFromY(y));
                    // check if we should replace a dirt type with grass
                    if (y == maxY - 1 && type == VoxelType::DIRT) type = VoxelType::GRASS;
                    if (type == VoxelType::WATER) {
                        m_transparentRenderer.AddVoxel(Position(x, y, z), Voxel(VoxelType::WATER, 0));
                    }
                    else {
                        if (y <= m_seaLevel)
                            m_underwaterRenderer.AddVoxel(Position(x, y, z), Voxel(type, colorR, colorG, colorB));
                        else
                            m_opaqueRenderer.AddVoxel(Position(x, y, z), Voxel(type, colorR, colorG, colorB));
                    }
                    lastType = _GetTypeFromY(y);
                }
            }
            // no matter what, add one water voxel at sea level
            m_transparentRenderer.AddVoxel(Position(x, m_seaLevel, z), Voxel(VoxelType::WATER, 0));
            // no matter what, add one sand voxel at 0 (bottom of the water)
            m_underwaterRenderer.AddVoxel(Position(x, 0, z), Voxel(VoxelType::SAND, 0));
            lastType = VoxelType::SAND;
        }
    }
}


texts: Improving efficiency of Prim's Algorithm

texts:
I have implemented Prim's Algorithm in Java.  I am wondering how it can be made more efficient.
Below is the class Node for vertices.

public class Node {

private final char label;
private final Map<Node, Integer> neighbourList;

public Node(char label) {
    this.label = label;
    this.neighbourList = new LinkedHashMap<>();
}

public void addNeighbourer(Node node, int weight) {
    neighbourList.put(node, weight);
}

public char getLabel() {
    return label;
}

public Map<Node, Integer> neighbourerList() {
    return neighbourList;
}
}

Below is a Map freeMap which contains all vertices with value Integer.MAX_VALUE except for first vertex whose value is set to 0.

    freeMap.put(nodeA, 0);
    freeMap.put(nodeB, Integer.MAX_VALUE);
    freeMap.put(nodeC, Integer.MAX_VALUE);
    freeMap.put(nodeD, Integer.MAX_VALUE);
    freeMap.put(nodeE, Integer.MAX_VALUE);
    freeMap.put(nodeF, Integer.MAX_VALUE);

And below is Prim's Algorithm.

public void primMinimumWeightSpanningTree(Map<Node, Integer> freeMap) {

    Set<Node> mstSet = new LinkedHashSet<>();
    while (freeMap.size() > 0) {

        Node minNode = null;
        /* finds minimum node in freeMap as per corresponding value.*/
        for (Map.Entry<Node, Integer> entry : freeMap.entrySet()) {
            if (minNode == null) {
                minNode = entry.getKey();
            } else {
                if (entry.getValue() < freeMap.get(minNode)) {
                    minNode = entry.getKey();
                }
            }
        }

        freeMap.remove(minNode); /* remove minimum node from freeMap*/
        mstSet.add(minNode); /* add minimum node to MST set(mstSet)*/
        /* update values of adjacent nodes in freeMap*/
        for (Map.Entry<Node, Integer> entry : minNode.neighbourerList().entrySet()) {
            if (freeMap.containsKey(entry.getKey())) {
                int value = freeMap.get(entry.getKey());
                if (value > entry.getValue()) {
                    freeMap.replace(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    /* display vertices once all are added to mstSet*/
    for (Node node : mstSet) {
        System.out.print(node.getLabel() + " ");
    }
}


texts:
To learn Go I decided to write a vowel/consonant counter. I really need tips/ideas on how I can improve my code.

package main

import (
    "os"
    "bufio"
    "fmt"
)

func isVowel(x string) bool {
    vowels := [5]string{"a", "e", "i", "o", "u",}
    vowelLookupTable := make(map[string]bool)
    for _, v := range vowels {
        vowelLookupTable[v] = true
    }

    return vowelLookupTable[x]
}

func isConsonant(x string) bool {
    consonants := [21]string{"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"}
    consonantLookupTable := make(map[string]bool)
    for _, v := range consonants {
        consonantLookupTable[v] = true
    }

    return consonantLookupTable[x]

}

func formatNumbers(vowelCount int, consonantCount int) {
    fmt.Print("Consonants: ")

    for i := 0; i < consonantCount; i++ {
        fmt.Print("=")
    }

    fmt.Printf(" %d\n", consonantCount)

    fmt.Print("Vowels:     ")

    for i := 0; i < vowelCount; i++ {
        fmt.Print("=")
    }

    fmt.Printf(" %d\n", vowelCount)
}

func countVowels(input string) int {
    vowelCount := 0

    for _, x:= range input {
        var s string
        s = fmt.Sprintf("%c", x)
        if isVowel(s) {
            vowelCount += 1
        }
    }

    return vowelCount
}

func countConsonants(input string) int {
    consonantCount := 0

    for _, x:= range input {
        var s string
        s = fmt.Sprintf("%c", x)
        if isConsonant(s) {
            consonantCount += 1
        }
    }

    return consonantCount
}

func takeInput() string {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')

    return text
}

func main() {
    input := takeInput()

    vowelCount := countVowels(input)
    consonantCount := countConsonants(input)

    formatNumbers(vowelCount, consonantCount)
}


texts:
This code makes an SQL query. The last andWhere() method adds a LIKE condition with one percentage sign at the right side of the string.
I'm wondering if there is a better way to do it.
public function prepareDataProvider()
{
    /* @var $modelClass \yii\db\ActiveRecord */
    $modelClass = $this->modelClass;

    $query = $modelClass::find()
        ->where('published=1')
        ->select([
            'id',
            'city_id',
            'city_district_id',
            'seller_net_id',
            'name',
            'address',
            'type',
        ]);

    // filters
    if ($city_id = \Yii::$app->request->getQueryParam('city_id'))
        $query->andWhere('city_id = :city_id',[':city_id'=>$city_id]);
    if ($city_district_id = \Yii::$app->request->getQueryParam('city_district_id'))
        $query->andWhere('city_district_id = :city_district_id',[':city_district_id'=>$city_district_id]);
    $city_name = \Yii::$app->request->getQueryParam('name');
    if ($city_name && mb_strlen($city_name) >= \Yii::$app->params['minSearchChars'])
        $query->andWhere(['LIKE' ,'name',strtr($city_name,['%'=>'\%', '_'=>'\_', '\\'=>'\\\\']).'%', false]);

    return new ActiveDataProvider([
        'query' => $query
    ]);
}


texts:
Looking for some feedback regarding elegance, about my code below implementing a simple graph API basing on scala.collection.concurrent.TrieMap.

Background:

I am using TrieMap because concurrency is one objective, and it is the only concrete implementation of a concurrency safe index that comes along with Scala to the best of my knowledge.

While I look for general code review feedback about furthering elegance, egregious aspects of my code, and/or moderate scalability wins are very welcome.

import scala.collection.concurrent.TrieMap

/*
 * trait to be mixed in by user code for making their nodes graph friendly
 */
trait AbstractVertex[ID] {
  val id: ID
}

/*
 * trait to be mixed in by user code for making their nodes graph friendly
*/
trait AbstractEdge[ID] {
  val id1: ID
  val id2: ID
}

class Graph[ID, Vertex <: AbstractVertex[ID], Edge <: AbstractEdge[ID]] {

  private val nodeIndex = new TrieMap[ID, Vertex]
  private val edgeIndex = new TrieMap[ID, List[Edge]]

  def addNode(vertex: Vertex): Graph[ID, Vertex, Edge] = {
    nodeIndex += ((vertex.id, vertex))
    this
  }

  def getNode(id: ID): Option[Vertex] = nodeIndex.get(id)

}

object Test extends App {

  case class Node(id: Int,
                  name: String,
                  kind: String) extends AbstractVertex[Int]

  case class Relation(id1: Int,
                      Kind: String,
                      id2: Int) extends AbstractEdge[Int]

  new Graph[Int, Node, Relation].addNode(Node(3, "foo", "bar")).getNode(3).get

}

Notes

This is a directed graph; I've included an App object demonstrating the use of the API, whereas I look for an API that is firstly addressing user code straightforwardness, only then elegance of the implementation behind the API.

I figured I'd post this before implementing edge handling, keeping things short and simple.


texts: Handy tool that provides easy syntax for specifying multi-dimensional types in C++

texts:
The syntax for specifying multi-dimensional types in C++ is messy. For example, to specify a two-dimensional std::vector<int>, one has to write std::vector<std::vector<int>>. The syntax doesn't scale. So, I wrote a handy tool that provides easy syntax for this. Any kinds of comments are welcome ^_^ (original version of the code can be found here with unit test code here)

template <template <typename...> class T, typename Base, std::size_t n>
struct multi {
  static_assert(n > 0, "");
  using type = T<typename multi<T, Base, n - 1>::type>;
};

template <template <typename...> class T, typename Base>
struct multi<T, Base, 1> {
  using type = T<Base>;
};

/// Provides easy syntax for specifying multi-dimensional types.
/// For example, `multi_t<std::vector, int, 2>` is equivalent to
/// `std::vector<std::vector<int>>`.
template <template <typename...> class T, typename Base, std::size_t n>
using multi_t = typename multi<T, Base, n>::type;


texts: Class for typecasting an Activity to an interface

texts:
In several places, I have some code that looks like the following, the only difference is in the type of listener.

public class CustomFragment extends android.app.Fragment {
    SomeListener listener;

    @Override
    public void onAttach(android.app.Activity activity) {
        super.onAttach(activity);

        // duplication
        //     ||
        //    \||/
        //     \/
        try {
            listener = (SomeListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement SomeListener");
        }
    }
}

To avoid duplication, I wrote this simple class:

public class TypeConvertor {
    private final Object whatNeedToCast;

    public static TypeConvertor cast(Object whatNeedToCast) {
        return new TypeConvertor(whatNeedToCast);
    }

    private TypeConvertor(Object whatNeedToCast) {
        this.whatNeedToCast = whatNeedToCast;
    }

    public <OtherType> OtherType to(Class<OtherType> toWhichToCast) {
        try {
            return (OtherType) whatNeedToCast;
        } catch (ClassCastException e) {
            throw new ClassCastException(
                    whatNeedToCast.toString() + " must implement " + toWhichToCast.getName()
            );
        }
    }
}

And the previous code is simplified to the following:

public class CustomFragment extends android.app.Fragment {
    SomeListener listener;

    @Override
    public void onAttach(android.app.Activity activity) {
        super.onAttach(activity);
        listener = TypeConvertor.cast(activity).to(SomeListener.class);
    }
}

But I do not like name TypeConvertor. Help me pick a better name (and help refactor this simple class if needed).


texts:
I have the following function to compare a string with a wildcard string (containing ? and *), as C# doesn't seem to have a builtin function to do it.

    /// <summary>
    /// Compares wildcard to string
    /// </summary>
    /// <param name="WildString">String to compare</param>
    /// <param name="Mask">Wildcard mask (ex: *.jpg)</param>
    /// <returns>True if match found</returns>
    public static bool CompareWildcard(string WildString, string Mask, bool IgnoreCase = true)
    {
        int i = 0, k = 0;

        // Cannot continue with Mask empty
        if (string.IsNullOrEmpty(Mask))
            return false;

        // If WildString is null -> make it an empty string
        if (WildString == null)
            WildString = string.Empty;

        // If Mask is * and WildString isn't empty -> return true
        if (string.Compare(Mask, "*") == 0 && !string.IsNullOrEmpty(WildString))
            return true;

        // If Mask is ? and WildString length is 1 -> return true
        if (string.Compare(Mask, "?") == 0 && WildString.Length == 1)
            return true;

        // If WildString and Mask match -> no need to go any further
        if (string.Compare(WildString, Mask, IgnoreCase) == 0)
            return true;

        while (k != WildString.Length)
        {
            switch (Mask[i])
            {
                case '*':

                    if ((i + 1) == Mask.Length)
                        return true;

                    while (k != WildString.Length)
                    {
                        if (CompareWildcard(WildString.Substring(k + 1), Mask.Substring(i + 1), IgnoreCase))
                            return true;

                        k += 1;
                    }

                    return false;

                case '?':

                    break;

                default:

                    if (IgnoreCase == false && WildString[k] != Mask[i])
                        return false;

                    if (IgnoreCase && Char.ToLower(WildString[k]) != Char.ToLower(Mask[i]))
                        return false;

                    break;
            }

            i += 1;
            k += 1;
        }

        if (k == WildString.Length)
        {
            if (i == Mask.Length || Mask[i] == '*')
                return true;
        }

        return false;
    }

I added the check to make sure Mask isn't null/empty because if it is then switch (Mask[i]) will throw a IndexOutOfRangeException. I'm wondering if there are any other checks I should make or change (specifically during the while loop)?


texts: Extension method that writes to a stream

texts:
public static void streamReport(this Report report, Stream stream)
{
    using (var streamWriter = new StreamWriter(stream))
    {
       //some logic that calls streamWrite.Write()
       streamWriter.Flush();
    }
    //Should "return stream;" here ?
}

I am writing an extension method to an object in which I would like to transform to a CSV which is generated and returned to a client (web).

My questions are:

Should I return stream (change void to Stream) ?
Should I use the out keyword in before the Stream parameter ? Is this a common way to let the caller know the parameter will be changed ?
Should I change the method to generate a new stream (and not accept one) and trust the user to Dispose it ?
Should I pass StreamWriter instead of Stream ?


texts: SQL Server 2012: How do I eliminate multiple statements in this code to a more efficient, single statement?

texts:
This code completes under a second, however its seems like I've taken the "Mr. Bean" way around getting there.

The goal is to get the average number of orders processed in a single day based on how many days exist in the current database. The loadcount column represents how many orders are processed in a single batch.  The batch is driven by the date and time during the day.

        -- // ditch the time to get the start/end date ranges uniform by date //--
    ;with makeuniform as
    (SELECT
           cast(startrangedatetime as date) as startdate
          ,cast(endrangedatetime as date) as enddate
          ,[LoadCount]
      FROM [audit].[Tracker]
    )
    -- // next, rollup all the loadcounts by uniform date // --
    select startdate,
           sum(loadcount) TotalOrders
      into #sumthedays
     from makeuniform
     group by startdate;

    -- // since the counts have been rolled up by day, get the table count // --
    declare @howmanydays int
    select  @howmanydays = count(*) from #sumthedays;

    -- // next get the average traffic per day // --

    select sum(TotalOrders) / @howmanydays
     from #sumthedays

     drop table #sumthedays


texts:
Here is the original question.

  In order to motivate his Peruvian students, a teacher includes words
  in the Quechua language in his math class.

  Today, he defined a curious set for a given positive integer N. He
  called this set, an Inti set, and defined it as the set of all
  positive integer numbers that have the number 1 as their single common
  positive divisor with number N.

  The math class about Inti sets was amazing. After class, the students
  try to challenge to teacher. They each ask questions like this: "Could
  you tell me the sum of all numbers, between A and B (inclusive), that
  are in the Inti set of N?"

  Since the teacher is tired and he's sure that you are the best in
  class, he wants to know if you can help him.

  Input Format

  The first line of input contains an integer Q, 1 ≤ Q ≤ 20,
  representing the number of students. Each of the next Q lines contain
  three space-separated integers N, A and B, which represent a query.

  Constraints

  1 ≤ A ≤ B ≤ N ≤ 10^12

  Output Format

  The output is exactly Q lines, one per student query. For each query
  you need to find the sum of all numbers between A and B, that are in
  the Inti set of N, and print the sum modulo 1000000007.

  Sample Input

2
12 5 10
5 1 4

  Sample Output

12 10

  Explanation

  In the sample input, Q = 2, so you have to answer two questions:

  In the first question N = 12, A = 5 and B = 10. So you have to find
  the sum of all numbers between 5 and 10, that are in the Inti set of
  12.

  Inti set ( 12 ) = { 1, 5, 7, 11, 13, ... }

  2 and 4 are not in the Inti set (12) because 12 and these numbers are
  also divisible by 2.

  3 and 9 are not in the Inti set (12) because 12 and these numbers are
  also divisible by 3.

  The numbers in the Inti set, which are in the query's range, are 5 and
  7, so answer is ( 5 + 7 ) MOD 1000000007 = 12

  In the second question, the numbers in the Inti set of 5 between 1 and
  4 are: 1, 2, 3, 4; so the answer is ( 1 + 2 + 3 + 4 ) MOD 1000000007 =
  10

My code keep getting timeout. Is there any approach to tackle this question?

Here the A, B, N values can be very large. It can be upto 10^12

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

        Scanner console = new Scanner(System.in);

        int queries = Integer.parseInt(console.nextLine());
        int[][] qArr = new int[queries][];

        for (int i=0; i<queries; i++){
            int N = console.nextInt();
            int A = console.nextInt();
            int B = console.nextInt();
            int[] singleLine = new int[3];
            singleLine[0] = N;
            singleLine[1] = A;
            singleLine[2] = B;
            qArr[i] = singleLine;
            console.nextLine();

        }

        for(int[] line : qArr){

            int N = line[0];
            int A = line[1];
            int B = line[2];

            //calculate sum
            long result = sumBetweenRange(A, B, N);
            System.out.println(result);

        }
    }

    private static long sumBetweenRange(int a, int b, int n){
        long sum = 0l;

        for(int i=a; i<=b; i++){

            if(!isCommonFactorAvailable(i, n)){
                sum += i;
            }
        }
        return sum;
    }

    private static boolean isCommonFactorAvailable(int no1, int no2){

        if(no1 != 1 && no2%no1 == 0){
            return true;
        }

        for(int i=2; i<no1/2; i++){

            if(no1%i == 0 && no2%i == 0){
                return true;
            }
        }
        return false;
    }

}


texts:
Consider we have three different database stores which we want to find an Id which is unique in all this three. I mean if we query first data store and we find that id. It's over and there is no need to further attempt, if that Id is in non of this three data stores we return null, I'm new in asynchronous programming, I wanted to know if there is any better implementation for this lines of code? I mean less if/else?

 public async Task<WebData> GetDataByIdAsync(GetDataById input)
    {
        var twitterData = await DataAccess.FindDataById<TwitterData>(input.Id);
        WebData result;
        if (twitterData  == null)
        {
            var facebookData = await DataAccess.FindDataById<FacebookData>(input.Id);
            if facebookData == null)
            {
                var linkedinData = await DataAccess.FindDataById<LinkedinData>(input.Id);
                if linkedinData == null)
                {
                    return null;
                }
                result = linkedinData
            }
            else
            {
                result = facebookData;
            }
        }
        else
        {
            result = twitterData ;
        }
        return result;
    }


texts: Should I use const in this function argument?

texts:
I'm working on getting myself comfortable with C after only working in high level languages for the past 10 years.  I've done rust as well and really like the concept of notating immutability in functions.
That being said I'm confused on if I should use const wherever the compiler lets me, or just use it where it semantically makes sense (and hope no one comes behind me and does something the caller doesn't expect).
Several functions I am looking at right now are:
void kcr_scene_update(const struct KCR_Scene* scene) {
    scene->internal->cubeRotation.x += 0.01f;
    scene->internal->cubeRotation.y += 0.01f;
    scene->internal->cubeRotation.z += 0.01f;
}

void kcr_display_begin_frame(const struct KCR_Display* display) {
    for (int x = 0; x < display->windowWidth * display->windowHeight; x++) {
        display->pixelBuffer[x] = 0xFF000000;
    }
}

The compiler is allowing these, presumably because it's not changing the root pointer or direct child pointers (I guess?) but is it good practice to put const in these methods when I know there's some mutation going on?


texts:
int X = 1;
int Y = 0;
while (X != 99 - 1 || Y != 99 - 1)
{
    Y++;
    if (Y > 99 - 1)
    {
        X += 1;
        Y = 1;
    }
    Layer1ID[X, Y].Update(X, Y);
    Layer2ID[X, Y].Update(X, Y);
}

This must update a total of 19602 objects each tick. Is there any way to speed this up? Threading maybe?

Objects(Ground and buildings) are stored in Layer1 and Layer2 ID Arrays of size 99x99. Most of them do nothing during the update method.

I've only recently began programming, so I apologize for the minimal information and ignorance.

Edit: Solved my own problem w/ help

if (ObjectManager._r.Next(0, 5) == 3)
{
    NeedUpdate = new List<Point>();
    for (int x = 1; x < Layer1ID.GetLength(0); x++)
    {
        for (int y = 1; y < Layer2ID.GetLength(1); y++)
        {
            if (Layer1ID[x, y].Updates || Layer2ID[x, y].Updates)
            {
                NeedUpdate.Add(new Point(x, y));
            }
        }
    }
}
foreach (Point P in NeedUpdate)
{
    Layer1ID[P.X, P.Y].Update(P.X, P.Y);
    Layer2ID[P.X, P.Y].Update(P.X, P.Y);
}


texts: Laravel testing for compatibility between old and new password-hashing schemes

texts:
I currently have an event listener tied to Laravel's Attempting class. The listener is designed to rehash an old password to something newer. The current DB stores the pass in an old crypt format. I'm just silently converting that old hash to a newer one. This works when going to the site to login. Now I want to be a good developer and get tests down. I have a test made that passes. I am not certain however this is the proper way to test it. I would also like to make sure that passwords are not stored in plain text at any time. I am new to testing so I would like to know if this is correct test to use.

<?php

namespace Tests\Unit;

use Illuminate\Auth\Events\Attempting;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class PasswordTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    function user_is_able_to_login_with_old_rs_password()
    {
        $user = factory('App\User')->create(['password' => '<old badly used hash>']);

        $response = $this->post('/login',[
            'email' => $user->email,
            'password' => 'secret'
        ]);

        $response->assertRedirect('/');
    }

    /** @test */
    function user_password_changed_to_new_hash()
    {
        Event::fake();

        $user = factory('App\User')->create(['password' => '<old badly hashed pass>']);

        $this->post('/login',[
            'email' => $user->email,
            'password' => 'secret'
        ]);
        Event::assertDispatched(Attempting::class);

        $pw = 'secret';

        $this->assertTrue(Hash::check($pw, $user->password));
        $this->post('/logout');
        $this->post('/login',[
            'email' => $user->email,
            'password' => $pw
        ]);

        $this->assertFalse(Hash::check($pw, $pw));
    }

}

This test does return green.. but I have doubts. I would love any tips or tricks so I can improve.


texts:
Any thoughts?

print('*'*44+'\n****How Many Seconds Have You Been Alive****\n'+'*'*44)

while True:
    try:
        print('\n--------------------------------------------')
        Age = int(input('\nHow old are you?: '))

        if Age<1 or Age>90:
            print('(Input Error)*Enter Valid Age*')
            continue

    except(TypeError,ValueError):
        print('(Input Error)*Enter Valid Age*')
        continue

    seconds = str(Age*31536000)

    def splitthousands(x, sep=','):  #Inserts a comma after every three digits from the right.
        if len(x) <= 3: return x
        return splitthousands(x[:-3], sep) + sep + x[-3:]

    print('\nYou have been alive for '+splitthousands(seconds, sep=',')+' seconds.')
    print('\n--------------------------------------------')

    while True:
        try:
            reply = str(input('\nDo you want to play again(Y/N)?: ').title())

        except(TypeError,ValueError):
            print('(Input Error)*Enter Valid Option*')
            continue

        if reply.startswith('Y'):
            break

        else:
            raise SystemExit


texts:
I've just finished my first program written in Java. It's a simple, boring, yet well-known FizzBuzz challenge where you have to:

  Write a program that prints the numbers from 1 to 100. But for
  multiples of three print “Fizz” instead of the number and for the
  multiples of five print “Buzz”. For numbers which are multiples of
  both three and five print “FizzBuzz”."

I know there are some other FizzBuzz questions here, but I'd really like to start learning Java in the right way, which means that I'm looking for:

Naming conventions
Coding standards and best practices

Coming from Python world, I was tempted to create a separate method named fizzBuzz() which I then called in my main() method. Is this a bit overkill for such a simple task?

package fizzbuzz;

class FizzBuzz {
/*
    Write a program that prints the numbers from 1 to 100. But for multiples of
    three print “Fizz” instead of the number and for the multiples of five print
    “Buzz”. For numbers which are multiples of both three and five print
    “FizzBuzz”."
 */

    public static void fizzBuzz() {
        for(int i = 1; i <= 100; i++) {
            if (i % 3 == 0 && i % 5 == 0)
                System.out.println("FizzBuzz");
            else if (i % 3 == 0)
                System.out.println("Fizz");
            else if (i % 5 == 0)
                System.out.println("Buzz");
            else
                System.out.println(i);
        }
    }

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


texts: Python unittest.mock.patch.object context manager

texts:
I want to test my core of handler, so I wrote this:

@unittest_run_loop
async def test_post_response(self):
    async def coro(a):
        return a
    validator = Mock()
    validator.validate = Mock(return_value=True)
    model = Mock()
    model.create_instance = Mock(side_effect=coro)
    normalizer = Mock
    normalizer.normalized = Mock(side_effect=lambda a: a)
    with patch.object(CreateMixin, 'validator', new=validator):
        with patch.object(CreateMixin, 'model', new=model):
            with patch.object(CreateMixin, 'normalizer', new=normalizer):
                response = await self.client.post('/', data='{"body": "ok"}')
                text = await response.text()
                self.assertTrue(text == '{"body": "ok"}' or text == '{\n    "body": "ok"\n}')

How can I improve this using decorators instead?


texts:
I have been working on a project and I'm actually refactoring some code. I have encountered myself with lots of foreach and if statements, which could be easily replace with LINQ.

But I have this code snippet, that I wonder how I could make it more functional style.

foreach (var notification in notifications)
{
    if (_emailService.SendEmail(notification.Message.Subject, notification.Message.Body, notification.Message.MailTo))
    {
        successNotificationIDs.AddRange(notification.ID);
    }
    else
    {
        errorCount++;
    }
}

The SendEmail method of the EmailService returns a bool. If its execution has been successfully, it will add an IEnumerable of Int to a declared collection (successNotificationsIDs). If not, I will increase the errorCount variable.


texts: Implementation of a dynamic list-like array

texts:
I needed to address an issue that I met with quite a bit, which has sort of a bag of data that I can easily add items and remove them, and iterate over them at any point without an issue.

First thing that came to mind was to use a linked list: easy to add, easy to remove, without having blank spaces in between, but the use of a linked list didn't look optimal to me.

I made a class in Java called BagArray that behaves like a list in terms of adding and removing items, and is easily iterated over with a for-each without having blank spaces.

It is a mix of a normal array to store the data, and a stack that stores indices of the normal array in which it is free to add an item without deleting another one.

import java.util.Iterator;

public class BagArray<T> implements Iterable<T> {

    private final Object mItems[];
    private final int mSlots[];
    private int mSlotsTop = -1;

    public final int size;

    public BagArray(int size) {
        this.size = size;
        mItems = new Object[size];
        mSlots = new int[size];
        for (int i = 0; i < size; i++)
            mSlots[i] = i;
        mSlotsTop = size - 1;
    }

    public boolean add(T item) {
        if (mSlotsTop < 0)
            return false;
        mItems[popSlot()] = item;
        return true;
    }

    @SuppressWarnings("unchecked")
    public T get(int i) {
        if (i < 0 || i >= size)
            throw new IndexOutOfBoundsException();
        return (T) mItems[i];
    }

    public void remove(int i) {
        if (i < 0 || i > size)
            return;
        if (mItems[i] == null)
            return;
        mItems[i] = null;
        pushSlot(i);
    }

    public void remove(T item) {
        remove(indexOf(item));
    }

    public boolean isFull() {
        return mSlotsTop == -1;
    }

    public boolean isEmpty() {
        return mSlotsTop == size - 1;
    }

    public int numFreeSlots() {
        return mSlotsTop + 1;
    }

    public int indexOf(T item) {
        for (int i = 0; i < size; i++)
            if (item == mItems[i])
                return i;
        return -1;
    }

    private int popSlot() {
        return mSlots[mSlotsTop--];
    }

    private void pushSlot(int s) {
        mSlots[++mSlotsTop] = s;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private int index = -1;

            @Override
            public boolean hasNext() {
                do {
                    index++;
                    if (index >= size)
                        return false;
                } while (mItems[index] == null);
                return true;
            }

            @Override
            @SuppressWarnings("unchecked")
            public T next() {
                return (T) mItems[index];
            }
        };
    }
}

Important thing to notice here is that the time complexity of the add(), get() and remove(index) methods are \$O(1)\$, which are the essential utilities of this class.

It is also Iterable while the for-each will skip blank spaces in the array.

This makes the use of the class very easy when we need to just "throw some items into a bag or replace them" and iterate over them quickly.

What are your opinions? Is this a good implementation, or is there another way?


texts: Extracting the IP addresses of Docker containers using JSON API

texts:
The following piece of code is imported in another file to get the status of the docker containers. I am printing the required information in a proper tabular form. I am using next() for finding out the only key available in the dictionary. This particular key will change hence used next() to find out the key. But the next() raises an exception when it reaches to the end. Currently I a handling that using PASS.

My question is "Is there a better to way to handle the exception caused by next () : StopIteration" ?

import requests
from prettytable import PrettyTable

def container_status(status):

    url = None
    if status == "all": url = "http://127.0.0.1:6000/containers/json?all=1"
    elif status == "running" : url = "http://127.0.0.1:6000/containers/json?all"
    else: raise ValueError("status should be either 'all' or 'running'")

    return requests.get(url)

def active_containers(status):

    response = container_status(status)
    table = PrettyTable(["Container Name", "Container ID", "Status", "IP ADDR"])
    for i in response.json():
        try:
            table.add_row([i["Names"][0].encode('utf-8').replace('/', ''),
                          i['Id'].encode('utf-8')[:12],
                          i["State"],
                          i["NetworkSettings"]["Networks"][next(iter(i["NetworkSettings"]["Networks"]))]["IPAddress"]])

        except StopIteration:
            pass
    print(table)

What are the other possibilities where I can improve the code?


texts:
I am using Entity Framework Core as ORM in my ASP.NET Core 2.1 project. I want to perform server-side pagination in Career Controller for getting list of careers. I have a model which looks like:

 public class Career
    {
        private string _title, _description;

        [Key]
        public long career_id { get; set; }
        [Required]
        [MaxLength(50)]
        public string title
        {
            get => _title;
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    throw new NonEmptyValueException("Title is required.");
                }
                _title = value;
            }
        }

        [Required]
        public DateTime opening_date { get; set; } = DateTime.Now;
        public DateTime? closing_date { get; set; }

        [Required]
        [MaxLength(2000)]
        public string description
        {
            get => _description;
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    throw new NonEmptyValueException("Description is required.");
                }
                _description = value;
            }
        }

        [MaxLength(70)]
        public string image_name { get; set; }

        public bool is_closed { get; set; } = false;

        public void markClosed()
        {
            is_closed = true;
            closing_date = DateTime.Now;
        }

        public void markUnclosed()
        {
            is_closed = false;
            closing_date = null;
        }
    }

This is how my DbContext looks like:

 public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }
        public DbSet<Career> careers { get; set; }
    }

Currently, I am doing this way to perform server side pagination in Controller:

public IActionResult Index(CareerFilter filter = null)
        {
            try
            {
                var careers = _careerRepo.getQueryable();

                if (!string.IsNullOrWhiteSpace(filter.title))
                {
                    careers = careers.Where(a => a.title.Contains(filter.title));
                }

                careers = careers.Where(a => a.opening_date >= filter.from_date && a.opening_date <= filter.to_date);

                ViewBag.pagerInfo = _paginatedMetaService.GetMetaData(careers.Count(), filter.page, filter.number_of_rows);

                careers = careers.Skip(filter.number_of_rows * (filter.page - 1)).Take(filter.number_of_rows);

                return View(careers.ToList());
            }
            catch (Exception ex)
            {
                AlertHelper.setMessage(this, ex.Message, messageType.error);
                return Redirect("/admin");
            }
        }

This is how my getQueryable() method in repository looks like:

public IQueryable<Career> getQueryable()
{
 return _appDbContext.Set<Career>();
}

I am personally not satisfied with the way I am exposing queryable and performing all conditional query concatenation in Controller. Controllers looked messy with increase in number of conditions. Please suggest me a better way to perform same action.


texts: RFC: Lightweight C++ 2D array template with runtime dinemsions

texts:
Any comments, critiques or questions about this? I'm using this as the base for a few rectangular board based toy programs like Conway's life and snake. Usage includes configuration of board size at runtime, hence the type doesn't carry size info, only the instances.

#include <utility>

template<typename type>
class Array2D {
   int y;
   type *data;
public:
   // We can't do a copy since we don't know
   // what size to allocate the array.
   Array2D(const Array2D&) = delete;
   Array2D& operator=(const Array2D&) = delete;

   Array2D(Array2D&& move) noexcept :
      y(std::exchange(move.y, 0)),
      data(std::exchange(move.data, nullptr)) {}

   Array2D& operator=(Array2D&& move) noexcept {
      std::swap(y, move.y);
      std::swap(data, move.data);
   }

   Array2D( int _x, int _y ) : y(_y) {
      data = new type[_x*y];
   }

   type const *operator[](int i) const {
      return data + (i * y);
   }

   type *operator[](int i) {
      return data + (i * y);
   }

   ~Array2D() {
      delete[] data;
   }
};