texts: Binary Search Implementation using template

texts:
This post is follow up of this, suggested by @loki-astari which can be found here.

Any further improvement is welcome.

Binary_Search.h

#ifndef BINARY_SEARCH_H
#define BINARY_SEARCH_H

template<typename RandomIt, typename T>
RandomIt binary_search(RandomIt begin, RandomIt end, const T& key);

#endif // BINARY_SEARCH_H

Binary_Search.cpp

#include <iostream>
#include <vector>
#include "Binary_Search.h"

/* search a key in an array using binary search */
template<typename RandomIt, typename T>
RandomIt binary_search(RandomIt begin, RandomIt end, const T& key)
{
    RandomIt save_end = end;

    while ( begin <= end )
    {
        // find the middle iterator
        auto range = std::distance(begin, end);
        RandomIt mid = begin;
        std::advance(mid, range / 2);

        if ( *mid == key ) // key found
        {
            return mid;
        }
        else if ( *mid > key ) // key may be on the left half
        {
            end = mid;
            std::advance(end, -1);
        }
        else if ( *mid < key ) // key may be on the right half
        {
            begin = mid;
            std::advance(begin, 1);
        }
    }

    // key not found
    return save_end;
}

int main()
{
    std::vector<int> vec = {1, 7, 9, 10, 28, 28, 36, 49, 68, 99};

    for (auto v : vec)
    {
        if ( binary_search(vec.begin(), vec.end(), v) != vec.end() )
        {
            std::cout << v << " is present" << std::endl;
        }
        else
        {
            std::cout << v << " is not present" << std::endl;
        }
    }

    std::vector<int> vec1 = {-1, 2, 3, 12, 23, 50, 90, 98, 100};
    for (auto v : vec1)
    {
        if ( binary_search(vec.begin(), vec.end(), v) != vec.end() )
        {
            std::cout << v << " is present" << std::endl;
        }
        else
        {
            std::cout << v << " is not present" << std::endl;
        }
    }
    return 0;
}


texts: Measuring the distance between NumPy matrixes

texts:
This takes two sets of five random points stored as a NumPy matrix, and then calculates the NumPy matrix between a point of the first set and a point of the second set. While the code works, I feel it's inelegant, as if I was writing in PHP or some other language. How can the function CalculateMatrixDistances be improved?

import random
import numpy as np
import scipy
from scipy import spatial

P=5
V=5

def CalculateMatrixDistances(MatRows,MatColums):
    numberRows=MatRows.shape[0]
    numberColumns=MatColums.shape[0]
    MatrixDistances=np.matrix( [0 for c in range(numberColumns)] )
    for r in range(numberRows):
        d=[scipy.spatial.distance.euclidean (MatRows[r],MatColums[c]) for c in range(numberColumns)]
        MatrixDistances = np.vstack([MatrixDistances, d])
    MatrixDistances=np.delete(MatrixDistances, (0), axis=0)
    return MatrixDistances

PositionP=np.random.rand(P,2)
PositionV=np.random.rand(V,2)

MatrixDistancesVP=CalculateMatrixDistances(PositionV,PositionP)

print PositionP
print PositionV
print MatrixDistancesVP


texts: Display factorial with user-entered number

texts:
This needs some optimizing without any additional variables or loops. The difficult part of the task was no additional variables subroutines/functions or loops. If that seems (near) impossible then break those rules.

The output should look like:

  5 X 4 X 3 X 2 X 1 = 120

Private Sub FactorialCalculation()

 Dim Number, Factorial As Integer

 Console.WriteLine("Please enter a number")
 Number = CInt(Console.ReadLine)
 Factorial = 1

 Console.WriteLine("Your number is " & Number)

 If Number > 0 Then
     Console.Write(Number & " X ")
     For Count As Integer = 1 To Number
         If (Number - Count) > 0 And (Number - Count) <> 1 Then
             Factorial *= Count
             Console.Write("{0} X ", Number - Count)
         ElseIf (Number - Count) = 0 Then
            Factorial *= Count
         ElseIf (Number - Count) = 1 Then
             Factorial *= Count
             Console.Write(Number - Count)
         End If

     Next
     Console.WriteLine(" = {0}", Factorial)
 Else
     Console.WriteLine("Please enter a positive number greater than 0")
 End If
End Sub


texts:
I am working on a sticky element that on certain point when the user scrolls down it turns into a relative element so it's not a sticky element anymore, only when the user scrolls to the top and passes over an specific element it turns again into a fixed/sticky element.

function Sticky($el){
    this.$el = $el;
    this.$stickyEl = this.$el.find('.sticky-bar-behavior');
    this.$noSticky = this.$el.find('.no-sticky');
    this.$whenSticky = this.$el.find('.when-sticky');
    this.shareStickyFooter();
    return this;
}

// this function is because I need check where is the scroll in order to
// see if the element should be fixed or relative
Sticky.prototype.toggleStickyOnInit = function($windowHeight, $windowPosition){
    var THIS = this;
    if(!($windowHeight >= $windowPosition)) {
        THIS.$el.addClass('position-relative');
        $('.when-sticky').show();
        $('.no-sticky').show();
    }
    return THIS;
}

Sticky.prototype.shareStickyFooter = function(){
    var THIS = this;
    var $windowHeight = $window.height();
    var $windowPosition = $('.sticky-bar-behavior').position().top;
    var $scrollTop = $(this).scrollTop();
    $window.on('scroll', function() {
        // THIS.toggleStickyOnInit($windowHeight, $windowPosition);
        if ($(this).scrollTop() + $windowHeight >= $windowPosition + 300) {
            requestAnimationFrame(function(){
                THIS.$el.removeClass('position-fixed');
                THIS.$el.addClass('position-relative');
                THIS.$noSticky.show();
                THIS.$whenSticky.hide();
            });
        } else if ($windowPosition >= $(this).scrollTop()) {
            requestAnimationFrame(function(){
                THIS.$el.removeClass('position-relative');
                THIS.$el.addClass('position-fixed');
                THIS.$noSticky.hide();
                THIS.$whenSticky.show();
            });
        }
    })

    return THIS;
};

At this point what I feel as if I am repeating some code.
Is there a better way to do is?


texts: Applying a function to columns of two matrices producing their combinations

texts:
I made a short snippet for applying a function f that takes two arguments (vectors) to columns of two matrices producing all possible combinations of those columns.

function V = cross_apply(f, V1, V2)
% Apply function f to columns of V1 and V2 producing
% a matrix where V(i, j) = f(V1(:,i), V2(:,j))
    s1 = size(V1, 2);
    s2 = size(V2, 2);
    V = zeros(s1, s2);
    for i = 1:s1
        for j = 1:s2
            V(i, j) = f(V1(:, i), V2(:, j));
        end
    end
end

An example of a use of this function could include approximating a function with a polynomial using a custom inner product (not a traditional dot product) here ip and defined as a kind of integral.

close all
f = @(x) log(x);
P = @(x) x.^(0:3);
ip = @(x, y) trapz(x.*y) / (size(x, 1)-1);

t = linspace(1, 2, 10)';
V = P(t);

% Inner product matrices
A = cross_apply(ip, V, V);
b = cross_apply(ip, V, f(t));

% Coefficients for the polynomial
rr = rref([A, b])
coef = rr(:, end);

% Plot ln(t) and polynomial fit
t_ = linspace(1, 3, 1000)';
figure()
plot(t_, P(t_)*coef, 'r--')
grid on, hold on
plot(t_, f(t_), 'b:')
legend('fit', 'f(t)', 'Location', 'best')

Not using this function, one would write a whole bunch of inner products (ip in the code) for matrices A and b. I didn't find a built-in function that does this, so I'm after two things:

Is this already an implemented function in Matlab built-ins or some toolbox?
Is there some improvement to be made to the function?


texts: Registration and Login: Best way to separate responsibilities

texts:
Based on lots of read books, sometimes I get quite confused when things get bigger than the simple examples. Martin Fowler's clean code is good but not enough.

I want some feedback on how to improve my current coding workflow, especially regarding to methods doing one thing or what is exactly one thing, does it depends on context. I'll show you an example:

Let's say I have these simple features:

SIGNOUT Whenever a visitor signs out:

If the visitor is already logged in, clear user session and cookie data.

LOGIN Whenever a visitor logs in:

Signout
If there's session data assign current session data (like current cart to the logged in user)

REGISTER When a visitor submits the register form:

Signout
If the email already exist try to login with the password from registration form.
If login failed return email in use error.
If email does not exist create user, create profile info and send welcome email
Login

Controller would have something like:

[HttpPost, ValidateModelState, ExportModelStateToTempData, ValidateAntiForgeryToken]
public RedirectResult Register(AccountRegisterBindingModel binding, string returnUrl) {
    var status = customerService.Register(binding);
    if (!status.Succeded) {
        ModelState.AddModelErrors(status.Errors);
        return Redirect(Url.Action("Register", "Account", new { returnUrl }));
    }
    return Redirect(returnUrl ?? DefaultUrl);
}

As you can see, the controller is really thin, but I'm worried about the customerService.Register().

First: name suggests to be: SingoutCreateUserSendWelcomeEmailLoginAndMergeSessionData()
Second: Does this method do too many things? It looks like it.

The Register method have something like:

public SignInStatus Register(UserRegistration data) {
    authService.SignOut();
    var result = userService.CreateUser(data); // User and profile....
    if (result.Succedded) {
        communicationService.SendWelcomeEmail(data);
        customerService.MergeSessionCustomerWithUserCustomer();
    }
    return authService.Login(data)
}

Why I'm asking for a code review:

While this may seem ok, the register method does too many things.
I know I can put the logic pieces on the controller, but I have multiple endpoints for registration and I don't want to have duplicated code on controllers. Also everybody goes against it.
This method is used on multiple websites (not just one) so change the code in the future can impact a lot. that smell like something is not quite good.
If one consumer of this method changes I might have to use that in all or create a new one.
This codebase does changes a lot, constant development of features, etc.

I hope it's clear enough. In reality, the code is more complex and nested, even if I try to keep it clean I sometimes don't know where to put the code pieces to keep it as clean as possible. While this is about a simple feature, I would love to get suggestions that will work for other parts of the software.


texts: "Have a safe trip"… or not, depending on four conditions

texts:
I have 4 booleans and all must be met to determine the value of a String:

String message = (!isNameBlank && !isDestinationBlank
    && isDestinationValid && isAmountValid)
    ? "Have a safe trip!" : "Please try again!";

If I do this, it doesn't look elegant either:

String message = "";
if(!isNameBlank && !isDestinationBlank
    && isDestinationValid && isAmountValid) {
    message = "Have a safe trip!";
} else {
    message = "Please try again!";
}

Is there a better convention when comparing many booleans in a statement?


texts:
In a project, we have a file that contains something like a script which we need to parse. At the moment the validation is tough since we have an array of functions returing variable and taking variableList (basically std::variant<>and vector of variants, see definition below)
I am trying to have function metadata available (number of input arguments and its type, possibly return value type for validating the input "script". I would like to replace std::function with something like this:

using variable = std::variant<bool, int, double, std::string>;
using variableList = std::vector<variable>;

enum {
    BOOL_TYPE = 0,
    INT_TYPE = 1,
    DOUBLE_TYPE = 2,
    STRING_TYPE = 3,

    VARIABLE_BOOL_TYPE = 0 | 0x80,
    VARIABLE_INT_TYPE = 1 | 0x80,
    VARIABLE_DOUBLE_TYPE = 2 | 0x80,
    VARIABLE_STRING_TYPE = 3 | 0x80
};

struct Function
{
    std::string                                 fname;
    std::vector<int>                            indexes;
    std::function<variable(variableList &&)>    fn;

    variable operator()(variableList && list)
    {
        if (indexes.size() != list.size() &&
            (indexes.size() == 0 || (indexes[0] & 0x80) != 0x80))
        {
            std::cout << "Invalid number of arguments" << std::endl;
            return variable(0);
        }

        int idx = 0;
        for (auto i : list)
        {
            if ((indexes[0] & 0x80) ? i.index() != (indexes[0] & 0x03), idx++ : i.index() != indexes[idx++])
            {
                std::cout << "Invalid argument type" << std::endl;
                return variable(0);
            }
        }

        return fn(std::forward<decltype(list)>(list));
    }
};

int main()
{
    Function f = { "fName", {BOOL_TYPE, INT_TYPE, BOOL_TYPE}, [](variableList && list) -> variable {
        for (auto i : list)
        {
            std::visit([](auto && val) -> void {
                std::cout << val << std::endl;
            }, i);
        }
        return variable(0);
    }};

    auto arguments = {variable(true),variable(true),variable(true)};
    auto returnValue = f(arguments);
}

The project supports c++17. Any modifications, suggestions are welcome.

EDIT: Initially I wanted to use templates instead of indices and enum, but I wasn't quite successful with creating array of Function class with different template arguments.


texts: Implementation of generic Graph class and Dijkstras

texts:
I participate in competitive programming contests, and I found myself implementing and re-implementing graphs constantly. So I decided to create a reusable implementation of a Graph class, and implement some common methods for it, including DFS, BFS, and Dijkstras.

Are there any edge cases that my code misses? Is there anything I could do to improve it?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

public class Graph<T> {

    public class Node {
        public T value;
        public Map<Integer, Integer> edges;

        public Node(T value) {
            this.value = value;
            edges = new HashMap<>();
        }
    }

    public List<Node> nodes;

    public boolean directed;
    public int numNodes = 0;
    public int numEdges = 0;

    public Graph() {
        this(false);
    }

    public Graph(boolean directed) {
        nodes = new ArrayList<>();
        this.directed = directed;
    }

    public void addNode(T value) {
        nodes.add(new Node(value));
    }

    public void connect(int i, int j, int weight) {
        nodes.get(i).edges.put(j, weight);
        if (!directed)
            nodes.get(j).edges.put(i, weight);
    }

    public class DijkstrasNode extends Node {
        int dist = -1;
        boolean visited = false;
        DijkstrasNode previous;

        public DijkstrasNode(T value) {
            super(value);
        }

        public DijkstrasNode(Node node) {
            super(node.value);
            this.edges = node.edges;
        }
    }

    public void processBFS(int source, BiConsumer<Node, Integer> consumer) {
        Queue<Integer> q = new LinkedList<>();
        boolean[] visited = new boolean[nodes.size()];
        q.add(source);
        while (!q.isEmpty()) {
            int id = q.poll();
            if (visited[id])
                continue;
            visited[id] = true;
            Node n = nodes.get(id);
            consumer.accept(n, id);
            for (int c: n.edges.keySet())
                q.add(c);
        }
    }

    public void processDFS(int source, BiConsumer<Node, Integer> consumer) {
        Stack<Integer> q = new Stack<>();
        boolean[] visited = new boolean[nodes.size()];
        q.push(source);
        while (!q.isEmpty()) {
            int id = q.pop();
            if (visited[id])
                continue;
            visited[id] = true;
            Node n = nodes.get(id);
            consumer.accept(n, id);
            for (int c: n.edges.keySet())
                q.add(c);
        }
    }

    public List<DijkstrasNode> dijkstras(int source) {
        List<DijkstrasNode> djk = nodes.stream().map(DijkstrasNode::new).collect(Collectors.toList());
        djk.get(source).dist = 0;
        PriorityQueue<DijkstrasNode> q = new PriorityQueue<>((i, j) -> i.dist - j.dist);
        q.add(djk.get(source));
        int visitCount = 0;
        while (!q.isEmpty() && visitCount < djk.size()) {
            DijkstrasNode n = q.poll();
            if (n.visited)
                continue;
            n.visited = true;
            visitCount++;
            for (int child : n.edges.keySet()) {
                DijkstrasNode cn = djk.get(child);
                if (!cn.visited && (cn.dist == -1 || n.dist + n.edges.get(child) < cn.dist)) {
                    if (cn.dist != -1)
                        q.remove(cn);
                    cn.dist = n.dist + n.edges.get(child);
                    cn.previous = n;
                    q.add(cn);
                }
            }
        }
        return djk;
    }

}


texts:
From the command line, I can easily find the path to rubygems.rb

$ gem which rubygems
/usr/lib/ruby/1.9.1/rubygems.rb

and from a Ruby script I can also do this

require 'rubygems/commands/which_command'
wc = Gem::Commands::WhichCommand.new
puts wc.find_paths 'rubygems', $LOAD_PATH

However is a simpler way available to do this, for example without using
require 'rubygems/commands/which_command', and without a system() call?

Update from posted answer

puts $".grep(/rubygems.rb/).first

Update from posted comment

puts Gem.method(:dir).source_location.first


texts:
I would like some feedback on my code, I'm new to coding with C# but I do have some knowledge on Lua and Python. Is there anything that I need to change/clean up to make it more simplified?
using System;
using System.Linq;

class MainClass {
  public static void Main () {
    int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};

    Console.WriteLine("Welcome to Blackjack. Here are your draws.");

    Random drawCard = new Random();
    int draw1 = drawCard.Next(cards.Min(), cards.Max());
    int draw2 = drawCard.Next(cards.Min(), cards.Max());

    Console.WriteLine("You recieved a " + draw1 + " card!");
    Console.WriteLine("You recieved a " + draw2 + " card!");

    int sum1 = draw1 + draw2;

    if (sum1 == 21) //Blackjack Ending
    {
      Console.WriteLine("Congratulations! You got " + sum1 + "!");
    }

    else if (sum1 >= 11) //Choice of 3rd draw
    {
      Console.WriteLine("Is " + sum1 + " enough?");
      bool cont1 = false;

      drawChoice(cont1); //Call the draw choice function

      if (cont1 == true)
      {
        int draw3 = drawCard.Next(cards.Min(), cards.Max());
        Console.WriteLine("You drawed a " + draw3 + " card!");

        int sum2 = draw3 + sum1;
        Console.WriteLine("You have a total of " + sum2 + ".");

        if (sum2 > 21) Console.WriteLine("Game Over!");
      }

      else //NPC's turn starts
      {

      }
    }

    else //Player has less than 11 cards, auto draw
    {
      Console.WriteLine("You have a total of " + sum1 + ".");
      Console.WriteLine("You will be forced to draw another card.");

      int draw3 = drawCard.Next(cards.Min(), cards.Max());
      Console.WriteLine("You drawed a " + draw3 + " card!");

      int sum2 = draw3 + sum1;
      Console.WriteLine("You have a total of " + sum2 + ".");
    }
  }

  static void drawChoice(bool contChoice) //Function for player to choose whether to draw
  {
    Console.WriteLine("Would you like to draw another card? Y/N");
    string choice1 = Console.ReadLine();

    if (choice1 == "Y" || choice1 == "y")
    {
      contChoice = true;
      Console.WriteLine(contChoice);
    }

    else if (choice1 == "N" || choice1 == "n")
    {
      contChoice = false;
      Console.WriteLine(contChoice);
    }
  }
}


texts:
I created an MVC router based on knowledge of an MVC design pattern.

It will simply take a URL as a string (class/method/params...), then it will instantiate a requested class controller and call its method.

In my class, I call a controller method and then include the view at the same time to display data.

My questions are:

Is this a valid MVC router?
Is it good practice to make this class call include views for our application?

class FrontController {
    //default view
    private $view = 'index';
    //default methode
    private $method = 'indexMethode';
    //default controller
    private $controller = 'Page';
    //this attribute to store data returned
    private $data;
    //to store methode parameters from url.
    private $param;
    public function __construct() {
        //getting user url request
        $url = $this->getUrl();
        //checking user input
        if (isset($url[0])) {
              //getting class name from user input
              $this->controller = ucwords($url[0]);
              unset($url[0]);
        }
        //checking if class file exsiste if yes we include it
        if(file_exists('controllers/'.$this->controller.'.php')){
              require 'controllers/'.$this->controller.'.php';
        }
        //instantiating the demanded class
        $this->controller = new $this->controller;

        //getting demanded class method if it is demanded by user
        if (isset($url[1])) {
              if(method_exists($this->controller, $url[1]))
                  $this->method = $url[1];

        }

        //checking if there is a view for our request
        if(file_exists('view/'.$url[1].'.php')){
            //setting the sutable template for the methode
            $this->view = $url[1];
            unset($url[1]);
        }

        //Getting methode parameters from user input if exsist
        $this->param = $url ? array_values($url) : [];

        //Calling the methode and getting the result
        $this->data = call_user_func_array([$this->controller,
        $this->method], $this->param);

        //Getting the sutable page for  the responde to display it.
        include 'view/' . $this->view . '.php';
    }
    //To get any private var in our class
    public function __get($name) {
        return $this->$name;
    }
    //Here we are gona take user input and devide it as array element
    public function getUrl() {
      //checking user input and filtring it for unwanted charecters
        if (!empty($_GET['url'])) {
            // remove / char from url
            $url = rtrim($_GET['url'], '/');
            //Checking url for unwanted chars
            $url = filter_var($url, FILTER_SANITIZE_URL);
            //forming array from url
            $url = explode('/', $url);
            //Sending back url array
            return $url;
        }
    }
}


texts: Text replacement with Räubersprache ("Røversprog")

texts:
I've been toying with Haskell again and implementing a simple text replacement program that replaces all consonants c in a text by coc, i.e., inserting an 'o' in between:
> robber_simple "abcdef"
"abobcocdodefof"

This is rather simple to implement:
robber_simple :: [Char] -> [Char]
robber_simple [] = []
robber_simple (x:xs)
  | x `elem` monophthongs = x:(robber_simple xs)
  | otherwise            = x:'o':x:(robber_simple xs)
  where -- vowels represented by one character, or monograph
        monophthongs :: [Char]
        monophthongs = "aeiouy"

However, in many languages, such as German, we have multigraphs which can act as vowels or consonants, such as "uh" ("uhr") or "sch" ("schokolade").
So I implemented a more complicated program which does a basic lookahead to figure out, whether the, say 's', we currently read is actually part of a "sch".  I'm not happy with it, though :)
import Data.List

robber :: [Char] -> [Char]
robber xs = robber' xs [] where
  robber' :: [Char] -> [Char] -> [Char]
  -- Read first character into backlog
  robber' (x:xs) [] = robber' xs [x]
  -- Nonempty prefix, new input can either form a multigraph prefix or end one.
  robber' (x:xs) (p:ps)
    -- Current character with existing prefix forms a prefix of a multigraph
    | token `elem` (prefixes multigraph_consonant) = robber' xs token
    | token `elem` (prefixes multigraph_vowel)     = robber' xs token
    -- The current token makes it clear that we aren't reading a multigraph
    | otherwise                                    = (robber' [] (p:ps))    ++ (robber' (x:xs) [])
    where token = (p:ps) ++ [x]
  -- No input, consume characters in backlog.
  robber' [] pref
    -- Either this forms a multigraph...
    | pref `elem` multigraph_consonant                   = pref ++ 'o':pref
    | pref `elem` multigraph_vowel                       = pref
    -- ... or not.
    | otherwise                                          = robber_simple pref

-- consonant phoneme made up of multiple characters
multigraph_consonant :: [[Char]]
multigraph_consonant = ["sch", "ch", "sc"]

-- same for vowels
multigraph_vowel :: [[Char]]
multigraph_vowel = ["ei", "uh"]

prefixes :: [[a]] -> [[a]]
prefixes xs = concat $ map prefix xs

prefix :: [a] -> [[a]]
prefix = inits

The parsing/tokenizing strategy I use, is to read characters and store them into the backlog until a character (or end of input) comes that determines that the current backlog can be treated as one unit.  That is, it either is a complete monograph (e.g., "sch") or definitely not a prefix of a monograph ("c").
In that case, I replace the backlog x with either x++'o':x or leave it, depending on whether it is a consonant or a vowel.
Finally, I carry on parsing the rest of the string.
Any suggestions welcome!


texts: Modified Coupon Collector's Problem in Java

texts:
What is Coupon Collector's Problem?

  In probability theory, the coupon collector's problem describes the "collect all coupons and win" contests. It asks the following question: Suppose that there is an urn of n different coupons, from which coupons are being collected, equally likely, with replacement. What is the probability that more than t sample trials are needed to collect all n coupons? An alternative statement is: Given n coupons, how many coupons do you expect you need to draw with replacement before having drawn each coupon at least once? from here.

What is my Modified Coupon Collector's Problem?

  Instead of "at least once", I check for "at least 2 times".

I loop for a crore times. I should get \$14.7,24.134\$. My code returns \$14.760683\$ and \$23.83069\$. Fairly correct. Maybe Java is not so randomly accurate?

Here's is my code:

package test;

import java.util.ArrayList;
import java.util.Random;

public class CouponCollector {
private static final int mMaxCouponNumber = 6;
private static final int mMinCouponNumber = 1;
private static final int EXPERIMENT_REPETITIONS = 10000000;
private static final int EACH_COUPONS_ATLEAST_OCCURENCE = 2;

public static void main(String args[]) {
    float mSumOfDraws = 0;
    for (int i = 1; i <= EXPERIMENT_REPETITIONS; i++) {
        ArrayList<Integer> mCouponList = new ArrayList<Integer>();
        int mDrawsRequired = 0;
        do {
            mCouponList.add(new Random()
                    .nextInt((mMaxCouponNumber - mMinCouponNumber) + 1)
                    + mMinCouponNumber);
            // DEBUG System.out.println("Added: " +
            // mCouponList.get(mDrawsRequired));
            ++mDrawsRequired;
            if (allCouponsCollected(mCouponList)) {
                break;
            }
        } while (true);
        if(i%10000==0){
            // Enable this if you are too impatient! :D
            //DEBUG System.out.println("Process: "+(((float)i)*100/EXPERIMENT_REPETITIONS)+"% complete.");
        }
        mSumOfDraws += mDrawsRequired;
        // DEBUG System.out.println("Draws required in " + i
        // + " st/nd/rd/th trial is " + mDrawsRequired);
    }
    System.out.println("Average value of draws required is "
            + (mSumOfDraws / EXPERIMENT_REPETITIONS));
}

private static boolean allCouponsCollected(ArrayList<Integer> pCouponList) {
    int[] mCouponCount = new int[mMaxCouponNumber - mMinCouponNumber + 1];
    for (int i = 0; i < pCouponList.size(); i++) {
        ++mCouponCount[pCouponList.get(i) - 1];
        // DEBUG System.out.println("Count of " + pCouponList.get(i) +
        // " is " + mCouponCount[pCouponList.get(i) - 1]);
    }
    for (int i = 0; i < mCouponCount.length; i++) {
        if (mCouponCount[i] < EACH_COUPONS_ATLEAST_OCCURENCE) {
            return false;
        }
    }
    return true;
}
}


texts: How to deal with some of the dependencies?

texts:
I am very beginning in PHP and Design Patterns. I have been studying the beautiful book "Head first: Design pattern" and I have been working in some of the codes originally presented in Java in order to learn more about PHP-OOP. The code below presents a kind of Observer Pattern. It is working well, however there are still some design choices that bother me? Can one help me improve this piece of code.

Questions:

Am I using a good PHP practice?
The entire code seems to be based on the idea that there are three pieces of information that are relevant, namely $temperature, $humidity and $ pressure. However, it seems that this is not a good design, since I may eventually in the future need another piece of information such as for instance pluviometric index... Is there a good way to avoid this kind of dependency?
Is it a good choice the class currentConditionsDisplay to implement both Observer and DisplayElement? It seems to be another undesirable dependency.
Are there other kinds of undesirable dependencies?
Is a better design pattern to define currentConditionsDisplay as static?

Any help is very welcome.

<?php

interface Observer{
    public function update($temp,$humidity,$pressure);
}

interface Subject{
    public function registerObserver(Observer $o);
    public function removeObserver(Observer $o);
    public function notifyObserver();
}

interface DisplayElement{
    public function display();
}

class WeatherData implements Subject{
    private $observers;
    private $temperature;
    private $humidity;
    private $pressure;

    public function __construct(){
        $this->observers=array();
    }
    public function registerObserver(Observer $o){
        array_push($this->observers,$o);
    }
    public function removeObserver(Observer $o) {
        unset($this->observers["$o"]);
    }
    public function notifyObserver(){
        foreach($this->observers as &$o){
            $o->update($this->temperature,$this->humidity,$this->pressure);
        }
    }
    public function measurementsChanged(){
        $this->notifyObserver();
    }
    public function setMeasurements($temperature,$humidity,$pressure){
        $this->temperature=$temperature;
        $this->humidity=$humidity;
        $this->pressure=$pressure;
        $this->measurementsChanged();
    }
}

class CurrentConditionsDisplay implements Observer, DisplayElement{
    private $temperature;
    private $humidity;
    private $weatherData;

    public function __construct(Subject $weatherData){
        $this->weatherData=$weatherData;
        $weatherData->registerObserver($this); // $this reffers to the currentConditionsDisplay
    }

    public function display(){
        echo "Current conditions: "."$this->temperature"." F degrees and "."$this->humidity"." humidity";
    }

    public function update($temperature,$humidity,$pressure){
        $this->temperature=$temperature;
        $this->humidity=$humidity;
        $this->display();
    }
}

$weatherData=new WeatherData();

$currentConditionsDisplay=new currentConditionsDisplay($weatherData);

$weatherData->setMeasurements(80,60,30.45);

?>


texts: VBA - If error return '0' else execute code

texts:
I am converting below excel formula to VBA code and it works as required.

=IFERROR(IF(A2="NULL",B2*C2,A2*B2*C2),0)

Could someone please review and suggest if any changes are required in terms of handling errors.

What the code does : If there is an error it returns '0' else executes the code.

Sub MultiplyValues()
'
' MultiplyValues Macro
'
' =IFERROR(IF(A2="NULL",B2*C2,A2*B2*C2),0)
' Forumala is in D

Dim rCell As Range
Dim rRng As Range
Set rRng = Range("A2", Range("A2").End(xlDown))
    For Each rCell In rRng.Cells
        On Error GoTo ErrHandler:
            If rCell.Value = "NULL" Then
                rCell.Offset(0, 3) = rCell.Offset(0, 1) * rCell.Offset(0, 2)
            Else
                rCell.Offset(0, 3) = rCell.Offset(0, 0) * rCell.Offset(0, 1) * rCell.Offset(0, 2)
            End If
            Next rCell
         Exit Sub
         ErrHandler:
            rCell.Offset(0, 3) = 0
    Resume Next
End Sub


texts:
I have a result class which wraps another object if successful or an error if failure

public class Result
{
    private Result() { }

    public bool Success { get; private set; }
    public string Error { get; private set; }
    public MyClass MyClass { get; private set; }

    public static Result CreateSuccess(MyClass myClass)
    {
        return new Result { Success = true, MyClass = myClass };
    }
    public static Result CreateFailure(string error)
    {
        return new Result { Error = error };
    }

    // ... see below
}

1. Is this a reasonable way to go about this?

I also am considering putting an implicit conversion to bool

public static implicit operator bool(Result result)
{
    return result.Success;
}

So that I can do

var result = GetResult();

if (!result)
{
    Print(result.Error);
}

2. Is this a silly idea?


texts: Project Euler Problem 11 ("Largest product in a grid") in Python


texts: Find the maximum number in an array of numbers

texts:
The task is to find the maximum number in an array of numbers.
I have taken every number in the array to be byte-sized.
I have written the code such that the result is stored in ch at the end.

The code is written to run on Intel 8086.

Code optimization and improvement required.

   org 100h

    ;registers: bx - to store the base address of the array of numbers
    ;si : to store the index of the current number in the array
    ;dl: to store the iterator value of the for loop in the program
    ;dh: to store the value of n(size of the array)
    ;ch: to store the maximum element
    ;ah: temporary register to store the current element, and to compare with
    ;the number in ch

   lea bx,array
   mov si,0h
   mov dl,0h
   mov dh,n

   cmp dl,dh
   jge end

   mov cx,0h
   ;to move the first value into the min-register to compare with other elements
   mov ch,[bx+si]
   inc dl
   inc si

loop:
   cmp dl,dh
   jge end

   mov ah,[bx+si]
   inc si
   inc dl
   cmp ah,ch
   jle loop
   mov ch,ah
   jmp loop

end:

   mov ax,0h
   mov dx,0h
   mov bx,0h
   mov si,0h

   ret

array DB 4h,45h,32h,23h,9h
n DB 5


texts: Mocking protocol with class/static functions in Swift

texts:
I am using one of the open-source Objective-C keychain wrappers to store data in iOS keychain.
For test cases, I have created protocol as:

protocol KeychainProtocol {
    func deletePassword(forService service: String, account: String) -> Bool
    func setPassword(_ password: String, forService service: String, account: String) -> Bool
}

This is my keychain wrapper class:

@interface KeychainWrapper : NSObject

+ (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account;
+ (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account;

@end

I have written mock class KeychainProtocolMock which conforms to KeychainProtocol.
In test cases I am simply doing this:

class DatabaseInterfaceTests: XCTestCase {

    override func setUp() {
        super.setUp()
        KeychainController.shared.delegate = KeychainProtocolMock()
    }

    override func tearDown() {
        KeychainController.shared.delegate = nil
        super.tearDown()
    }

    func testPasswordsAfterWipeAllData() {
        //test functions which deals with keychain data
    }
}

This is my controller class:

class KeychainController: NSObject {

    static let shared = KeychainController()
    var delegate: KeychainProtocol?

    class func deletePassword(forService service: String, account: String) -> Bool {
        let delegate = KeychainController.shared.delegate
        return delegate != nil ? delegate!.deletePassword(forService: service, account: account) : KeychainWrapper.deletePassword(forService: service, account: account)
    }

    class func setPassword(_ password: String, forService service: String, account: String) -> Bool {
        let delegate = KeychainController.shared.delegate
        return delegate != nil ? delegate!.setPassword(password, forService: service, account: account) : KeychainWrapper.setPassword(password, forService: service, account: account)
    }
}

In my app code, whenever I need keychain data I am accessing it through controller class as:

let password = KeychainController.password(forService: DBPasswordService, account: DBPasswordAccount)

It is working absolutely fine, but still I have some doubt about my implementation ofKeychainController class.
It looks messy!

Is there any better way to handle this situation where I can use class/static protocol methods in Swift and ask Objective-C keychain wrapper class to conform it?


texts:
For a Project Euler problem, I made a Ruby roman numeral converter:

def romanize(num)
    digits = {
        1000 => "M",
        900  => "CM", 500 => "D", 400 => "CD", 100 => "C",
        90   => "XC", 50  => "L", 40  => "XL", 10  => "X",
        9    => "IX", 5   => "V", 4   => "IV", 1   => "I"
    }
    digits.reduce("") do |acc, digit|
        key, numeral = digit
        occurances, num = num.divmod(key)
        acc + (numeral * occurances)
    end
end

This works great, but I'm not sure it's good Ruby. Specifically, I'm wondering if the body of the reduce block could be shortened, and if it could made more clear.

For example, I don't think its that obvious that num is being modified in the middle of the reduce block.

Also, I know I can monkey patch this into the Fixnum class, but that's not what I'm looking for.

Update #1

@Tokland's answer taught me some new things. His answer works well, and is pretty clever.

If I take just two of his concepts and apply them to mine, the digits.reduce("") ... block can be simplified to:

digits.map do |key, numeral|
    occurances, num = num.divmod(key)
    numeral * occurances
end.join

This needs one less line because it deconstructs the digit key/value in the block arguments. Also, it creates an array which is joined into a string at the end. For big numbers (around 100-trillion), this is much quicker.

The only problem I still see is that it's modifying the num variable, which is essentially global state to the block.


texts:
I just yesterday started learning some Java. I wrote this piece and got some help from @Simon André Forsberg to refine it some. I added a few things since. It's super-simple but I just want to make sure I have a few concepts down before I move on to more complex things. Any constructive criticism is appreciated!

import java.lang.*;

public class HelloWorld {
    private final String output;

    public HelloWorld(String name) {
        output = "Hello World, " + name + "!";
    }

    public String getMessage() {
        return output;
    }

    public static void main (String args[]) {
        HelloWorld helloObj;
        helloObj = new HelloWorld("Phrancis");
        System.out.println(helloObj.getMessage());
    }
}

Console output:

Hello World, Phrancis!


texts: N-layered application structure in ASP.NET MVC 5

texts:
I've been trying to set up an n-layered application in ASP.NET MVC 5. I've converted my account controller to look like this.

I would like some feedback as to whether this is going in the right direction. What I'm trying to achieve is to off-load my controllers and leave the logic to the service. My Controller should just be doing the routing.

// all services inherit this to expose the DbContext
public class BaseService
{
    protected AppDbContext db = new AppDbContext();
}

interface IAccountService
{
    bool Login(HttpContextBase httpContext, string userName, string password);
    bool Logout(HttpContextBase httpContext, HttpSessionStateBase session);
}

public class AccountService : BaseService, IAccountService
{
    private UserManager<IdentityUser> userManager;

    public AccountService()
    {
        userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
    }

    public bool Login(HttpContextBase httpContext, string userName, string password)
    {
        var user = userManager.Find(userName, password);

        if (user != null) {
            IAuthenticationManager authenticationManager = httpContext.GetOwinContext().Authentication;

            authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            authenticationManager.SignIn(userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie));

            return true;
        }

        return false;
    }

    public void Logout(HttpContextBase httpContext, HttpSessionStateBase session)
    {
        IAuthenticationManager authenticationManager = httpContext.GetOwinContext().Authentication;

        authenticationManager.SignOut();
        session.Clear();
    }
}

public class AccountController : Controller
{
    private readonly IAccountService service;

    public AccountController()
    {
        service = new AccountService();
    }

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Index(IndexViewModel viewModel)
    {
        ActionResult result;

        if (service.Login(HttpContext, viewModel.UserName, viewModel.Password)) {
            result = RedirectToAction("Index", "Home");
        } else {
            result = View(viewModel);
        }

        return result;
    }

    public ActionResult Logout()
    {
        service.Logout(HttpContext, Session);

        return RedirectToAction("Index");
    }
}


texts: Conditionally replacing an input field when submitting a form

texts:
I just wrote this, and cleaned it up as much as I could. A couple things worry me:

I change the scope of $(this) twice (and apparently don't know how to use =>)
The big if if/else statement. Is there a better way to write that?

Also, it's an IIFE, and the big identing makes the )() at the end look out of place.

  emptyTagFieldsOnDeletion = (->
    $('form.simple_form').submit ->
      $form = $(this)
      $form.find('.fake-input').each ->
        $fakeInput = $(this)
        $ulId = $fakeInput.closest('ul').attr('id')
        if $fakeInput.children('li').length is 1
          $fakeInput.children().remove()
          if $ulId is 'primary_diagnosis_select'
            $fakeInput.append emptyListArrayHTML('primary_icd9_codes')
          else if $ulId is 'secondary_diagnosis_select'
            $fakeInput.append emptyListArrayHTML('secondary_icd9_codes')
          else
            $fakeInput.append emptyListArrayHTML('med_names')
  )()

For reference, the emptyListArrayHTML method looks like this:

emptyListArrayHTML = (list_type)->
  "<input type='text' name='#{nameWithListType(list_type)}' value=''>"


texts: Determine the roots of a Quadratic Equation

texts:
A code that determines the roots of a quadratic equation.
Also, determine the following based on the discriminant b² – 4ac:

If b² − 4ac is positive, display: “There are TWO REAL SOLUTIONS.”
If b² − 4ac is zero, display: “There is ONLY ONE REAL SOLUTION.”
If b² − 4ac is negative, display: “There are TWO COMPLEX SOLUTIONS.”

#include <stdio.h>
#include <math.h>

int main(){

    int a, b, c, d;
    double root1_real, root2_real, root1_complex, root1_i, root2_complex, root2_i, root_zero;

    printf("Enter a, b and c where a*x*x + b*x + c = 0\n");
    scanf("%d %d %d", &a, &b, &c);

    d = b * b - 4 * a * c;

     if(d > 0){ // Positive
        root1_real = (-b + sqrt(d)) / (2*a);
        root2_real = (-b - sqrt(d)) / (2*a);
        printf("First Root : %.2lf\n", root1_real);
        printf("Second Root : %.2lf\n", root2_real);
        printf("There are TWO REAL SOLUTIONS\n");
     }else if(d < 0){ // Negative
        root1_complex = -b / (2 * a); root1_i = sqrt(-d) / (2 * a);
        root2_complex = -b / (2 * a); root2_i = sqrt(-d) / (2 * a);
        printf("First root : %.2lf + i%.2lf\n", root1_complex, root1_i);
        printf("Second root : %.2lf + i%.2lf\n", root2_complex, root2_i);
        printf("There are TWO COMPLEX SOLUTIONS\n");
     }else{ // Zero
        root_zero = (-b + sqrt(d)) / (2*a);
        printf("Root : %.2lf\n", root_zero);
        printf("There is ONLY ONE REAL SOLUTION\n");
     }

     return 0;

}


texts: Recuperate user's details into fake JSON server

texts:
This is the 'details.ts' which define the user's details that I want to recuperate in a JSON (user's role, logintime, duration).

import {AuthenticationService} from '../_services';

import { User } from '../_models';

export class Details {

authenticationService : AuthenticationService;

currentUser = this.authenticationService.currentUserValue;

role = this.currentUser.role;
logintime = this.authenticationService.today;
duree = this.authenticationService.timeLeft;

}

and this is the service "details.service.ts" which implement the method create and get:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Employee } from '../shared/employee';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import {Details} from './details';
@Injectable({
providedIn: 'root'
})
export class DetailsService  {
apiURL = 'http://localhost:3000';

constructor(private http: HttpClient)    { }

httpOptions = {
headers: new HttpHeaders({
  'Content-Type': 'application/json'
})
}

createEmployee(details): Observable<Details> {
return this.http.post<Details>(this.apiURL + '/details',
JSON.stringify(details), this.httpOptions)
.pipe(
  retry(1),
  catchError(this.handleError)
)
}

getEmployees(): Observable<Details> {
return this.http.get<Details>(this.apiURL + '/details')
.pipe(
  retry(1),
  catchError(this.handleError)
)
}
deleteEmployee(id){
return this.http.delete<Details>(this.apiURL + '/details/' + id,
this.httpOptions)
.pipe(
  retry(1),
  catchError(this.handleError)
)
}

handleError(error) {
let errorMessage = '';
if(error.error instanceof ErrorEvent) {
  // Get client-side error
  errorMessage = error.error.message;
} else {
  // Get server-side error
  errorMessage = `Error Code: ${error.status}\nMessage:
${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}

}


texts:
I order to speed up opening of a file (which contents are displayed in a series of tabs), I made it so that tab content is generated only when the user first clicks on the tab. If user never opens the tab, code never executes.

The problem is I could not any find any TabPage events that would trigger when that tab is selected. I had to use SelectedIndexChanged event from the TabControl.

In order to make it work, I created a new interface (ICreateTab) that every TabPage implemented. It only has CreateTab() method which would contain the code that would generate data for the TabPage.

This is the snippet of the code:

    TabControl tabs;
    bool[] tabCreated;

    public ConstructorForClassThatHasTabControl()
    {
        tabs = new TabControl();
        tabs.Controls.Add(new TabPageWithImplementedICreateTabInterface1());
        .
        .
        .
        tabs.Controls.Add(new TabPageWithImplementedICreateTabInterfaceN());

        tabs.SelectedIndexChanged += OnSelectedIndexChanged;

        tabCreated = new bool[tabs.TabCount];

        // Create first tab, since the event won't be initially triggered
        ((ICreateTab)tabs.Controls[0]).CreateTab();
        tabCreated[0] = true;

        Controls.Add(tabs);
    }

    private void OnSelectedIndexChanged(object sender, EventArgs e)
    {
        if (!tabCreated[tabs.SelectedIndex])
        {
            tabCreated[tabs.SelectedIndex] = true;
            ((ICreateTab)tabs.SelectedTab).CreateTab();
        }
    }

This looks very ugly and messy to me. I'd rather each TabPage have an event that would create it's contents and remove itself so it's not triggered again. I need to avoid dragging TabControl into this matter.

Does TabPage have an event that is triggered when the TabPage is selected? Even if it doesn't, is there a proper way of doing this? I find it hard to believe that TabPage does not know when it's selected.


texts: Sum Square Difference, which way is more Pythonic?

texts:
I'm using python 3 and I am creating an algorithm to find the sum square difference for the first 100 (or 1 to x) natural numbers. This happens to be project euler problem 6 if anyone is wondering.

I've written it two ways and I am looking for criticism on my writing style to further guide me in how I code algorithms. I am aware there is probably a better "optimized" solution in terms of big(o) but my math skills just haven't reached there yet.

Algorithm 1

def sum_square_difference(max_range):
    #Finds the sum square difference for the first x(max range) natural numbers
    numbers = range(1,max_range+1)
    sum_squares = sum([x**2 for x in numbers])
    square_sum = sum(numbers) ** 2
    return square_sum - sum_squares

I find this algorithm to be the most readable, but something tells me it may be more verbose in terms of lines of code than necessary so I wrote the following algorithm.

Algorithm 2

def sum_square_difference2(max_range):
    numbers = range(1,max_range+1)
    return (sum(numbers) ** 2) - (sum([x**2 for x in numbers]))

This one seems much cleaner, but I find myself struggling more to understand and read what is going on, especially when considering the perspective of an outside observer.

I appreciate any insight.


texts: Readability and cyclomatic complexity of database transaction code

texts:
I consider these two options exactly the same. I prefer the first one but I'm not sure if it's better than the second option in terms of cyclomatic complexity or readability.

Assuming that this is not pure Ruby and I can call to the try method.

existing_transaction = database.find_transaction_by_id(transaction.id)
database.create_transaction(transaction) unless existing_transaction
database.update_transaction(transaction) unless existing_transaction.try(:processed)

existing_transaction = database.find_transaction_by_id(transaction.id)
if existing_transaction
  unless existing_transaction.processed
    database.update_transaction(transaction)
  end
else
  database.create_transaction(transaction)
end


texts:
Because I use the task so often, I wrote a C header for reading a file. I never formally learned C, so I'd really appreciate a code review on the code.

As a matter of personal taste, I do not put a space between the final parenthesis and an opening brace (){).

readfile.h

#ifndef _READ_FILE_INCL
#define _READ_FILE_INCL
#include <stdio.h>     /* for FILE, fopen, getc, fclose, EOF */
#include <stdlib.h>    /* for malloc, realloc */

// the amount of bytes the file is initially guessed to be
#ifndef _READFILE_GUESS
    #define _READFILE_GUESS 256
#endif

/*
 * function `read_file`
 * arguments: a file name (char*)
 * returns: the contents of the file (char*) or NULL if:
 *   1. the file does not exist
 *   2. memory allocation failed
 * return value must be freed
 */
char* read_file(char* name){
    FILE* file;
    file = fopen(name, "r");

    // 1. the file does not exist: return null
    if(!file)
        return NULL;

    // allocate memory according to the initial guess
    // (+ 1) for trailing null byte
    char* result = malloc(sizeof(char) * _READFILE_GUESS + 1);

    // 2. memory allocation failed
    if(result == NULL)
        return NULL;

    // the position in the string to write the character to
    size_t pos = 0;

    // the amount of memory allocated for the string
    size_t capacity = _READFILE_GUESS;

    // character to hold the currently-read character from the file
    char ch;

    // until the character is the EOF character
    while((ch = getc(file)) != EOF){
        // update the character at position `pos` to `ch`
        result[pos++] = ch;

        // if the next position would exceed bounds
        if(pos >= capacity){
            // add the guess to the capacity
            capacity += _READFILE_GUESS;

            // allocate memory accordingly
            // (+ 1) for trailing null byte
            result = realloc(result, sizeof(char) * capacity + 1);

            // 2. memory allocation failed
            if(result == NULL)
                return NULL;
        }
    }

    // close the file
    fclose(file);

    // remove extra memory
    result = realloc(result, sizeof(char) * pos);

    // 2. memory allocation failed
    if(result == NULL)
        return NULL;

    // `pos` now points to the index after the last character read
    result[pos] = '\0';

    return result;
}

#undef _READFILE_GUESS

/*
 * MIT License
 *
 * Copyright (c) 2017 Conor O'Brien
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#endif


texts:
I've written a piece of code which combines given letters in groups of n letters, and writes all the combinations in a text file. This is my first attempt and I wonder if there is an optimal way to do this.

letter_input = raw_input(' Type in letters: ')

number_input = int(raw_input(' Letters per word: '))

split_letters = list(letter_input)

def function():

    all_combinations_list = list(itertools.permutations(split_letters, number_input))

    output_file = open('/tmp/list.txt', 'w')

    number_of_combinations = len(all_combinations_list)

    for n in range(0,number_of_combinations):
        raw_characters = str(all_combinations_list[n])
        out_1 = raw_characters.translate(string.maketrans('',''), string.punctuation)
        out_2 = out_1.replace(' ','')
        print >>output_file, out_2

    output_file.close()


texts:
This is a ledger kind of table, initial amount is when the movement is null and all transactions on it is based on the Waste_Seq

the query take the last entry (id) based on the movement and change the initial amount

this query seem to work for my scenario and seem fast, is there a better or alternative way of doing what the query does?

long term this table will have more than 5-10 millions rows easily, this is a new empty table for now

Schema and data:

CREATE TABLE [dbo].[fredou](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Movement] [int] NULL,
    [Waste_Seq] [int] NOT NULL,
    [Amount] [int] NOT NULL,
    [operation] [int] NOT NULL,
 CONSTRAINT [PK_fun_fred_test] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [NonClusteredIndex] ON [dbo].[fredou]
(
    [Waste_Seq] ASC,
    [Movement] ASC,
    [Id] DESC
)
INCLUDE (   [Amount],
    [operation]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

insert into fredou values (         null,         1,      1000,         1)
insert into fredou values (         1,         1,       500,        -1)
insert into fredou values (         1,         1,       450,        -1)
insert into fredou values (         1,         1,       475,        -1)
insert into fredou values (         1,         1,       475,        -1)
insert into fredou values (         2,         1,       300,         1)
insert into fredou values (         2,         1,       200,         1)
insert into fredou values (         2,         1,       100,         1)
insert into fredou values (         3,         1,       300,         0)
insert into fredou values (         3,         1,       350,         0)
insert into fredou values (         4,         1,        50,        -1)
insert into fredou values (         4,         1,        50,         0)
insert into fredou values (         null,         2,      5000,         1)
insert into fredou values (        50,         2,      1000,        -1)
insert into fredou values (        50,         2,      1000,         0)
insert into fredou values (        51,         2,       500,        -1)
insert into fredou values (        53,         2,       400,        -1)
insert into fredou values (        51,         2,       300,        -1);

Query:

DECLARE @SEQ int = 1

SELECT SUM(f.Amount * f.Operation) as Amount
FROM
(
    SELECT  FIRST_VALUE(a.Amount)       OVER (partition BY a.Movement order by a.id desc) as Amount,
            FIRST_VALUE(a.Operation)    OVER (partition BY a.Movement order by a.id desc) as Operation,
            ROW_NUMBER()                OVER (partition BY a.Movement order by a.id desc) as rownum
    FROM [dbo].[fredou] a
    WHERE a.Waste_Seq = @SEQ
) f
where f.rownum = 1;

Link to sql fiddle


texts: Simple linear regression of two variables

texts:
This is the code I built to implement a simple linear regression to check the impact of variable A on B. I am not interested in predicting that's why the statistical approach is important for me to focus on the descriptive analytics such as the statsmodels summary and comparing RMSE of training set and test set to see if the model did a good job or not (I'm not looking to compare Dependent variable and RMSE to check prediction quality for example).
Is there anything fundamentally wrong with this approach to a simple Linear Regression?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from scipy import stats

# Import Excel File
data = pd.read_excel("C:\\Users\\AchourAh\\Desktop\\Simple_Linear_Regression\\SP Level Simple Linear Regression\\PL32_PMM_03_09_2018_SP_Level.xlsx",'Sheet1') #Import Excel file

# Replace null values of the whole dataset with 0
data1 = data.fillna(0)
print(data1)

# Extraction of the independent and dependent variable
X = data1.iloc[0:len(data1),1].values.reshape(-1, 1) #Extract the column of  the COPCOR SP we are going to check its impact
Y = data1.iloc[0:len(data1),2].values.reshape(-1, 1) #Extract the column of the PAUS SP

# Data Splitting to train and test set
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size =0.25,random_state=42)

# Training the model and Evaluation of the Model
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import math
from sklearn import model_selection
from sklearn.model_selection import KFold
lm = LinearRegression() #create an lm object of LinearRegression Class
lm.fit(X_train, Y_train)  #train our LinearRegression model using the   training set of data - dependent and independent variables as parameters.  Teaching lm that Y_train values are all corresponding to X_train.
kf = KFold(n_splits=6, random_state=None)
for train_index, test_index in kf.split(X_train):
print("Train:", train_index, "Validation:",test_index)
X_train1, X_test1 = X[train_index], X[test_index]
Y_train1, Y_test1 = Y[train_index], Y[test_index]
results = -1 * model_selection.cross_val_score(lm, X_train1,  Y_train1,scoring='neg_mean_squared_error', cv=kf)
print(results)
print(results.mean())
mse_test = mean_squared_error(X_test, Y_test)
print(mse_test)

#RMSE values interpretation test and train are similar no overfitting or underfitting the model performed well
print(math.sqrt(mse_test))
print(math.sqrt(results.mean()))

# Graph of the Training model
plt.scatter(X_train, Y_train, color = 'red')#plots scatter graph of COP COR  against PAUS for values in X_train and y_train
plt.plot(X_train, lm.predict(X_train), color = 'blue')#plots the graph of predicted PAUS against COP COR.
plt.title('SP000905974')
plt.xlabel('COP COR Quantity')
plt.ylabel('PAUS Quantity')
plt.show()#Show the graph

# Statistical Analysis of the training set with Statsmodels
X2 = sm.add_constant(X_train) # add a constant to the model
est = sm.OLS(Y_train, X2).fit()
print(est.summary()) # print the results


texts:
I have the following code which I feel that I must refactor, but not sure how to do it.

List<AlgoTuningData> feedbackScoreDatas;
List<AlgoTuningData> topRatedDatas;
int score1 = 0;
int score2 = 0;
boolean matched1 = false;
boolean matched2 = false;
for (AlgoTuningData topRatedData : topRatedDatas) {
    if (!matched1 && isMatchesTopRatedTuning(p1, topRatedData)) {
        score1 += topRatedData.getRank();
        matched1 = true;
    }

    if (!matched2 && isMatchesTopRatedTuning(p2, topRatedData)) {
        score2 += topRatedData.getRank();
        matched2 = true;
    }

    if (matched1 && matched2)
        break;
}

matched1 = false;
matched2 = false;
for (AlgoTuningData feedbackScoreData : feedbackScoreDatas) {
    if (!matched1 && isMatchesFeedbackScoreTuning(p1, feedbackScoreData))           {
        score1 += feedbackScoreData.getRank();
        matched1 = true;
    }
    if (!matched2 && isMatchesFeedbackScoreTuning(p2, feedbackScoreData)) {
        score2 += feedbackScoreData.getRank();
        matched2 = true;
    }

      if (matched1 && matched2)
      break;
}

private boolean isMatchesTopRatedTuning(Product product, AlgoTuningData topRatedData) {
        return product.getIsTopRated().equals(topRatedData.getValue());
    }

private boolean isMatchesFeedbackScoreTuning(Product product, AlgoTuningData feedbackScoreData) {
        return product.getPrice() <= feedbackScoreData.getMaxProductPrice();
    }

As you can see, I have 2 lists. each list has a different type of boolean function that verifies its objects. Each call to the function increases the score1 and score2.

I thought to use Callable, but wasn't sure how to do it for a list of items.

I would like my code to have one-line call for each List<AlgoTuningData>, something like this:

increaseScore(List<Integer> scores, List<AlgoTuningData>, myFunc)


texts: Legacy boot E820 entries written to low memory

texts:
In another post of mine, there was some discussion about a small area just above (see end of page @) BDA (500H - 534H) that handles DOS print screen. As not to interfere with this, as it would only gain me three entries anyway, map data will begin @ 540H. The addresses for this snippet are offsets from 838H, therefore, 838H + 2BH - 540H = 323H (803) bytes can be overwritten. The code could be shortened by hard coding maximum 40 entries, but I want this to stay relative.

Code is fashioned somewhat after this example albeit it is really bloated, with functionality that I don't think is really necessary.

Begin by initializing segment registers and ES:DI is the pointer to buffer for INT 15H.

 0  B85400            mov ax, 0x54          ; Just above BDA
 3  8EC0              mov es, ax
 5  8ED8              mov ds, ax
 7  31FF              xor di, di

Everything from 540H to offset 2BH (863H) can be overwritten. Doubt seriously any system will have 40 entries, but one never knows.

 9  8CC9              mov cx, cs            ; Base segment of this code
 B  C1E104            shl cx, 4             ; Convert to absolute addr
 E  81C16302          add cx, 0x263         ; Offset from CS*16 to 2DH
12  C1E004            shl ax, 4             ; Convert code segment
15  29C1              sub cx, ax            ; Total bytes

At the first iteration, the length of each entry is returned in CL, which is 20, then it will be calculated how many entries will fit in this space, meanwhile this value needs to be preserved.

17  894E01            mov [bp+1], cx

Finally, EBX, ECX, EDX & AX need to be setup for INT 15H

1A  6631C9            xor ecx, ecx
1D  6689CB            mov ebx, ecx
20  B120              mov cl, 0x20
22  66BA50414D53      mov edx, 0x534d4150    ; = 'SMAP'

NOTE: Interrupt doesn't care about high order bits (31-16) of EAX. This might be
      the case with ECX & EBX too, but I haven't experimented with that.

28  B820E8            mov ax, 0xe820

Infinite loop until one of six conditions occurs

2B  50                push ax
2C  6652              push edx
2E  CD15              int  15H
30  7233              jc   65             ; Continue until CF = 1

Continuation counter in BL is the next most significant value to be evaluated.

32  80FB01            cmp bl, 1
35  722E              jc  65                ; BL = 0, last entry has been read
37  770F              ja  0x48              ; BL > 1 continue reading entries

For some reason, only on first iteration does the signature in EDX need to be compared

39  6639D0            cmp eax, edx
3C  7527              jnz 65                ; EAX <> 'SMAP'

Calculation of max entries can be made now which will equal 40 in this version
3E  8B4601            mov ax, [bp+1]
41  31D2              xor dx, dx
43  F7F1              div cx                ; Probably 14H (20)
45  894601            mov [bp+1], ax

Unless I'm missing something, the linked example set first byte of next entry to 1. If that byte is overwritten, it has something to do with ACPI 3.0, but CL being greater than 20 does the same. Is my thinking flawed?

48  E316              jcxz 60
4A  80F914            cmp  cl, 20
4D  7711              ja   60

Haven't quite figured out why BIOS would return a zero length entry, but those entries are simply ignored by doing this

4F  668B4508          mov eax,[di+8]         ; Read high order bits
53  660B450C          or  eax,[di+12]        ; ZF = 1, null length entry
57  7407              jz  60

Have we run out of space yet, which is very unlikely

59  FE4E01            dec [bp+1]
5C  7407              jz  65

Point to next position and restore AX & EDX for next round

5E  01CF              add di,cx
60  665A              pop edx
62  58                pop ax
63  EBC6              jmp 2B

This is where error conditions will be evaluated, but at this point
not really sure what that has to be yet.

65  90                nop


texts: Bottom-up singly linked list merge sort in C++

texts:
This is an implementation of a singly linked list merge sort I did on paper during a job interview recently, using a bottom-up approach.

The requirement was simply "implement a merge sort for a singly linked list whose last node is indicated by a null value in its next pointer. An empty list is simply a null pointer to a node."

After having reviewed the code, the company decided I wasn't fit for their needs, but didn't want to disclose what in the code wasn't up to their standards. They however stressed that they not only care about whether the program works, but also whether it's elegant and easy to read.

I used a bottom-up approach because of its in-place merging abilities that make it optimal in space: O(1).

Would anybody tell me what is possibly wrong with my implementation and how it could be improved?

template <typename T>
struct Node {
    Node *next;
    T data;
};

template <typename T>
Node<T> **skip(Node<T> **pN, size_t s) {
    while (s-- && *pN)
        pN = &(*pN)->next;

    return pN;
}

template <typename T>
void insert_before(Node<T> **pAfter, Node<T> *n) {
    n->next = *pAfter;
    *pAfter = n;
}

template <typename T>
Node<T> *remove(Node<T> **pN) {
    Node<T> *n = *pN;
    *pN = n->next;
    n->next = 0;

    return n;
}

template <typename T>
Node<T> **merge_two_first_sublists(Node<T> **pN, size_t s) {
    Node<T> **pLeft = pN;
    Node<T> **pRight = skip(pN, s);

    while (*pRight && s != 0 && pLeft != pRight) {
        if ((*pRight)->data < (*pLeft)->data) {
            insert_before(pLeft, remove(pRight));
            --s;
        }
        else
            pLeft = &(*pLeft)->next;
    }

    return skip(pRight, s);
}

template <typename T>
Node<T> *merge_sort(Node<T> *n) {
    size_t s = 1;
    size_t l;

    do {
        Node<T> **pNextFirst = &n;

        for (l = 0; *pNextFirst; ++l)
            pNextFirst = merge_two_first_sublists(pNextFirst, s);

        s *= 2;
    } while (l > 1);

    return n;
}

I can see one obvious small change: merge the remove() and insert_before() functions into one move_before() function, which would  make the n->next = 0; line in the remove() function unnecessary, but do you think it's worth it?

Another change could be to use int rather than size_t, as many nowadays generally consider it harmful to use unsigned integers, but given that the type is used only internally by the merge algorithm itself and that underflows are guaranteed to not happen, is that an issue worth targetting?

A compile-and-run version on coliru: http://coliru.stacked-crooked.com/a/81638c30d4bc524f


texts:
I have a search form where users can enter ValidFrom and ValidTo dates,

There are three conditions:

ValidFrom and ValidTo NOT NULL

Action: Get values between two dates
ValidFrom is NOTNULL and ValidTo is NULL

Action: Get values where date is greater than ValidFrom
ValidFROM is NULL and ValidTo is NOTNULL

Action: get values where date is less than ValidTo

This is what I have got:

   if (model.ValidFrom != null && model.ValidTo != null)
        {
            var dateFrom = (DateTime)model.ValidFrom;
            var dateTo = (DateTime)model.ValidTo;
            dalList = dalList.Where(s =>
                DbFunctions.TruncateTime(s.ValidFrom) >= dateFrom.Date
                && DbFunctions.TruncateTime(s.ValidTo) <= dateTo.Date).AsQueryable();
        }
        if (model.ValidFrom != null && model.ValidTo == null)
        {
            var dateFrom = (DateTime)model.ValidFrom;

            dalList = dalList.Where(s => DbFunctions.TruncateTime(s.ValidFrom) >= dateFrom.Date).AsQueryable();
        }
        if (model.ValidFrom == null && model.ValidTo != null)
        {
            var dateTo = (DateTime)model.ValidTo;
            dalList = dalList.Where(s => DbFunctions.TruncateTime(s.ValidTo) <= dateTo.Date).AsQueryable();
        }

Is there a better way to write this type of search?


texts: Spurious wakeups in Java's BlockingQueue.take()

texts:
I wrote this code where I trap InterruptedException's in a blocking queue and try again to consume from the same queue thinking of spurious wakeups. I don't know if in this case I should be thinking of spurious wakeups since I am not calling wait() directly.

Basically, the worry that someone raised is that if the take throws an InterruptedException, I should stop processing (so the while should be inside the try, the opposite of what I did). There is already a mechanism to stop processing by calling a public method in the class, but I don't know if processing should also be stopped by an InterruptedException.

Does anyone have any thoughts?

private BlockingQueue<MyMessage> queue;
...
@Override
public void run() {
   log.debug("[run] Starting processing");

   while (runningController.isRunning()) {
      try {
         MyMessage message = queue.take(); // will block if empty

         assert message != null; // a blocking queue can never return null

         RuntimeMessage parsedMsg = processMessage(message);

         if (parsedMsg != null) {
            outputConsumer.messageArrived(parsedMsg);
         } else {
            log.warn("[run] Unparsed message 0x" + Integer.toHexString(message.getCommandType()));
         }

      } catch (InterruptedException exc) {
         log.error("[run] Interrupted while reading from queue", exc);
      } catch (MessageConfigurationException exc) {
         log.error("[run] Error finding structure configuration for received message", exc);
      }
   }
}


texts: recursive function : filtering large multidimensional array by key element to HTML list

texts:
I have a multidimensional array as a result from a webservice called from PHP. I cannot edit the webservice, but the result is as

array (size=5)
  'id' => int 0
  'name' =>
    array (size=7)
      'it' => string 'Tutti' (length=5)
      'ca' => string 'Tots' (length=4)
      'es' => string 'Todos' (length=5)
      'de' => string 'Alle' (length=4)
      'fr' => string 'Tous' (length=4)
      'nl' => string 'Alle' (length=4)
      'en' => string 'All' (length=3)
  'tree' =>
    array (size=0)
      empty
  'languages' =>
    array (size=7)
  'subTypes' =>
    array (size=4)
      0 =>
        array (size=5)
          'id' => int 1
          'name' =>
            array (size=29)
              ...
          'tree' =>
            array (size=1)
              ...
          'languages' =>
            array (size=29)
              ...
          'subTypes' =>
            array (size=3)
              ...
      1 =>
        array (size=5)
          'id' => int 2
          'name' =>
            array (size=29)
              ...
          'tree' =>
            array (size=1)
              ...
          'languages' =>
            array (size=29)
             ...
          'subTypes' =>
            array (size=6)
              ...

As you can see, you can interpret it as a multidimensional array of objects. Each objects can have child objects of same type.

My goal is to get only the elements on a specific language, fe en (and thus rest is not taken). I thought to use a recursive function.

// filter array
function getByKey($array, $search, $level, $valuesUsed) {
    echo '
';
    foreach($array as $key => $value) {
        if(is_array($array[$key])) {
            $valuesUsed = getByKey($array[$key], $search, $level + 1, $valuesUsed);
        } else if ($key === $search) {
            if(!in_array($value, $valuesUsed)) {
                echo "
 $key = $value
";
                $valuesUsed[] = $value;
            }
        }
    }
    echo '
';
    return $valuesUsed;
}

Then I call the above function from my HTML template by

    <?php
        getByKey($routeTypes, 'en', 0, array());
    ?>

$routeTypes is the array, obtained from the webservice.
It works as expected, it results as the list here below, which I can wrap with a js library.

this is level1

this is level1

this is level 2

this is level 2

               ... level++

Now, I'm questioning myself if this can be improved ? It doesn't take long to have a list from a large multidimensional array. (a simple print_r command resulted in 45000+ characters).

Especially checking the $valuesUsed array, to prevent duplicates (yes the webservice has objects which contains child keys which is similar to level - 2 parent (or on other level ...... ))

Each time I am running through the lower levels, I am looping through the $valuesUsed array. Is there not a better way to loop through the sublevels ? Maybe an array_walk() or array_walk_recursive() with a callback function ?


texts: Prime number sequence supporting repeated iteration

texts:
I'm a long-time Java programmer, but recently I decided to give Kotlin a try.  So far, I'm loving the language features, it feels much more expressive than what I'm used to.  As practice, I wrote this function that produces a repeatable sequence of prime numbers (i.e. the sequence can be iterated multiple times, and will make use of results from past iterations to speed up future iterations).  It feels pretty solid to me, but I'm wondering how it would look to a Kotlin veteran - are there language features that I'm not taking full advantage of, or conventions that I should be following?
One question I have in particular is regarding top-level function vs. subclass; here I chose to implement a top-level function primeSequence(): Sequence<Long> that returns an object, but I could have just about as easily implemented a class PrimeSequence : Sequence<Long>.  Is there a good rule of thumb for when to use one or the other?
fun primeSequence(): Sequence<Long> = object: Sequence<Long> {
    private val knownPrimes: MutableList<Long> = arrayListOf(2L, 3L)

    private fun Long.isMultipleOf(n: Long) = (this%n == 0L)

    private fun Long.isPrime() = knownPrimes
            .takeWhile { it*it <= this }
            .none { this.isMultipleOf(it) }

    override fun iterator(): Iterator<Long> = object: Iterator<Long> {
        private var lastPrime: Long? = null

        override fun hasNext() = true

        override fun next(): Long {
            val nextPrime = when(val lastPrime = this.lastPrime) {
                null -> 2L
                2L -> 3L
                else -> {
                    if (knownPrimes.last() > lastPrime ) {
                        knownPrimes[knownPrimes.binarySearch(lastPrime) + 1]
                    } else {
                        val np = generateSequence(lastPrime+2) { it+2 }
                                .first { it.isPrime() }
                        knownPrimes.add(np)
                        np
                    }
                }
            }
            this.lastPrime = nextPrime
            return nextPrime
        }
    }
}


texts:
Here is an async task queue implementation. The idea is to reuse node.js standard library as much as possible.

const { Readable, Writable } = require('stream');

const delay = (ms) =>
  new Promise((resolve) => {
    setTimeout(resolve, ms)
  })

const task = (message) => {
  console.log(`${message} started`)

  return delay(500).then(() => message + ' solved')
}

class AsyncTaskQueue {
  constructor(limit = 7) {

    this.queue = new Readable({
      objectMode: true,
      read(size) {}
    })
    this.processor = new Writable({
      objectMode: true,
      highWaterMark: limit + 1,
      write(task, encoding, callback) {
        task().finally(() => callback())
      },
      writev(tasks, callback) {
        Promise.all(tasks.map(({chunk}) => chunk().catch(err => err)))
          .finally(() => callback())
      }
    });
    this.queue.pipe(this.processor)
  }

  addTask(execute) {
    const closure = { resolve: null, reject: null }
    const task = () => execute().then(closure.resolve).catch(closure.reject)
    const promise = new Promise((resolve, reject) => {
      closure.resolve = resolve;
      closure.reject = reject;
    })
    this.queue.push(task)
    return promise
  }
}

const q = new AsyncTaskQueue();

for (let i = 0; i< 100; i++) {
  q.addTask(
    task.bind(null, i)
  ).then(console.log)


texts:
In another question the user was determining the probability of having a streak of 6 heads or 6 tails in 100 coin flips. To find the probability they would generate 100 random coin flips and determine if there was a streak. They would test 10,000 such sequences of 100 flips to find that there was about an 80% chance of there being a streak in 100 coin flips.
I decided to compute the exact probability. For 100 flips there are \$2^{100}\$ possible outcomes. To determine the percentage I compute how many of them have a streak, and then divide by \$2^{100}\$.
My naive solution gets me the number for 20 flips in few seconds:
from itertools import product

def naive(flips, streak):
    return sum('h' * streak in ''.join(p) or
               't' * streak in ''.join(p)
               for p in product('ht', repeat=flips))

Result:
>>> naive(20, 6)
248384

My fast solution gets me the number for 100 flips instantly:
from collections import Counter

def fast(flips, streak):
    needles = 'h' * streak, 't' * streak
    groups = {'-' * streak: 1}
    total = 0
    for i in range(flips):
        next_groups = Counter()
        for ending, count in groups.items():
            for coin in 'ht':
                new_ending = ending[1:] + coin
                if new_ending in needles:
                    total += count * 2**(flips - 1 - i)
                else:
                    next_groups[new_ending] += count
        groups = next_groups
    return total

The idea is to have a pool of still ongoing games, but grouped by the last six flips, and counts for how often that group has appeared. Then do the 100 flips one at a time, updating the groups and their counts. Any group that at some point ends with a streak doesn't continue playing, instead I add it to the total result. The group occurred count times, there are flips - 1 - i flips left, and they can be anything, so multiply count with 2flips - 1 - i.
Results (note that the result for 20 flips is the same as with the naive solution):
>>> fast(20, 6)
248384
>>> fast(100, 6)
1022766552856718355261682015984

And dividing by 2100 gives me the percentage similar to those of the linked-to experiments:
>>> 100 * fast(100, 6) / 2**100
80.68205487163246

Any comments, suggestions for improvement?


texts: Project Euler Problem 7: Find 10001st prime number

texts:
I was able to complete the problem, but I would like to improve my code and make it more idiomatic.

Here is the challenge description:

  Problem 7 - 10001st prime

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th >prime is 13.
  What is the 10 001st prime number?

  http://projecteuler.net/problem=7

Here is my code:

let isDivibleBy num denum = num % denum = 0
let isPrime x previousPrimes = not (Seq.fold (fun acc y -> (isDivibleBy x y) || acc) false previousPrimes)
let getPrime n =
    let rec getPrimesInternal count num previousPrimes =
        match count with
        | 0 -> previousPrimes
        | _ -> let prime = isPrime num previousPrimes
               match prime with
               | true -> getPrimesInternal (count - 1) (num + 1) (num::previousPrimes)
               | false -> getPrimesInternal count (num + 1) previousPrimes
    match n with
    | n when n <= 0 -> 0
    | n -> List.head (getPrimesInternal (n - 1)  2 [2])

[<EntryPoint>]
let main argv =
    printfn "%i" (getPrime 10001)
    0 // return an integer exit code

One of the major problem I would like to address is performance.  An easy way to improve the performance would be to stop the fold when a prime number is found, but I couldn't find the appropriate technique or function.

Updated version of code:

let isPrime n =
    match n with
    | _ when n < 2 -> false
    | 2 -> true
    | _ when n % 2 = 0 -> false // even numbers greater than 2
    | _ -> // odd numbers greater than 2
        let limit = int(sqrt(float(n)))
        let rec check i =
            i > limit || (n % i <> 0 && check (i + 2))
        check 3

let getPrimes n =
    let rec getPrimeInternal found i =
        if found >= n
        then []
        else
            if isPrime i
            then i::getPrimeInternal (found + 1) (i + 1)
            else getPrimeInternal found (i + 1)
    getPrimeInternal 0 2

let getPrime n =
    Seq.last (List.toSeq (getPrimes n))

[<EntryPoint>]
let main argv =
    printfn "%i" (getPrime 10001)
    0 // return an integer exit code


texts:
The code performs bubble sort on the basis if any swaps has been performed in the iteration. I made it sort of independent of number of iterations as in any conventional bubble sorting code.

I went on pretty much with what I understood from the cs50 class. This mechanism looks more intuitive to me. What improvements I need to do on the design/style/method?

#include<stdio.h>

void printMyArray(int a[],int n);

//BUBBLE SORT
int main(){
    int a[] = {-1 , 2 , 0 , -3 , 5 , 1};
    int n = 6;
    for(;;){

       int swap = 0;
       int i = 0;

       for(; i < n-1; i++)
          if( a[i+1] <= a[i]){
              int temp = a[i+1];
              a[i+1] = a[i];
              a[i] = temp;
              swap = 1;
           }
       if(swap == 0)
           break;
    }
    printMyArray(a,6);

}
void printMyArray(int a[],int n){
   int i;
   for(i = 0; i < n ; i++)
     printf("%d\t",a[i]);
   printf("\n");
}


texts: Can XSS or anything else get through this?

texts:
I coded a php chat that stores the text in a txt file and retrieves it, and I want to know if XSS can get past it or if someone can replace xhr.open("POST","uhh.php"); with something that contains the same php code but without htmlspecialchars or something like that.  What are the vulnerabilities? (More specifically, I don't want people putting html elements through the chat, and that also leads to security issues.)

This is uhh.php:

<?php
$usr=$_POST["usr"];
$msg=$_POST["msg"];
if($usr&&$msg){
    $txt="$usr: $msg";
    $txt=htmlspecialchars(join("\n",str_split($txt,33)));
    $split=explode("\n",file_get_contents("uhh.txt") . $txt);
    while(count($split)>10){
        $split=array_slice($split,1);
    }
    file_put_contents("uhh.txt",join("\n",$split) . "\n");
}
?>
watchu lookeen at???

And this is the code to the html page (JavaScript included):

<!DOCTYPE html>

<title>Chatting</title>

Bagelhead: lol
Bagelhead: yes t is
Abe: ok proxy off now
Bagelhead: gtg
Bagelhead: :P
Test: Test
Abe: &lt;p&gt;Test&lt;/p&gt;
Abe: Test
TEST: ab
TEST: abe

<input maxlength="9001" placeholder="Press / to chat" type="text" id="chatbar">

uhh.txt is just a blank text file.


texts: Better yielding tuple-d union case values in list generation

texts:
I have a situation where I'm stitching three different unions into a triplet tuple for building a map/dictionary of strongly typed values keyed on a string.

One of the union cases is very large, the second has three options, and the third has only two. Right now I loop through the large with reflection, and have six yield statements to handle the combinations of the second and third unions.

My code works fine as far as I can tell so far, but I don't quite like having yield in my code six times. How can I better represent this situation?

*If needed I can post the code for the unions too.

**Note that (RawOreName ore).Value is just a string.

let OreDataMap =
    [
        for oreType in FSharpType.GetUnionCases typeof<EveOnline.OreDomain.Types.OreType> do
            let ore = FSharpValue.MakeUnion (oreType, [| |]) |> unbox

            yield (RawOreName ore).Value, (ore, Common, IsCompressed)
            yield (RawOreName ore).Value, (ore, Uncommon, IsCompressed)
            yield (RawOreName ore).Value, (ore, Rare, IsCompressed)
            yield (RawOreName ore).Value, (ore, Common, IsNotCompressed)
            yield (RawOreName ore).Value, (ore, Uncommon, IsNotCompressed)
            yield (RawOreName ore).Value, (ore, Rare, IsNotCompressed)
    ]
    |> Map.ofList


texts:
I implemented KMP pattern matching algorithm in Scala. My code works but it looks more imperative and a scala translation of C/C++ implementation.

I am not able to figure out how to manage multiple indexes and then update them conditionally. Following is the code with some explanation, kindly suggest how to write it in scala way.

KMP algo has two parts .

first  one is where we create an array which will have information of how many character we can skip in pattern if find a mismatch.

example -

AAAA -> 0,1,2,3
ABCDE  -> 0,0,0,0,0
AABAACAABAA -> 0,1,0,1,2,0,1,2,3,4,5

Following is code to build this array from patten string

def buildLookupTable(s: String): ArrayBuffer[Int] = {
    val lookupTable = ArrayBuffer.fill(s.length)(-1)
    lookupTable(0) = 0 // first char always 0
    var len = 0
    var i = 1
    while( i < s.length) {
      if (s(i) == s(len)) {
        len += 1
        lookupTable(i) = len
        i += 1
      } else { // mismatch
        if (len == 0) {
          lookupTable(i) = 0;
          i= i+1
        } else {
          len = lookupTable(len-1)
        }
      }
    }
    lookupTable
  }

Once we have this array we can use this to find occurences of a pattern. Something like following

def searchPattern(s: String, p: String): Unit = {
    if (p.length > s.length) println("bad input")
    else if (p == s) println("same strings")
    else {
      val lookupTable = buildLookupTable(p)

      var i= 0 // for s
      var j= 0 // for p

      while (i < s.length) {
        if (s(i) == p(j)) {
          i += 1
          j += 1
        }
        if (j == p.length) {
          println(s"pattern found at ${i-j}")
          j = lookupTable(j-1)
        }
        else {
          if (i < s.length && s(i) != p(j)) {
            if (j != 0) j = lookupTable(j-1)
            else i+=1
          }
        }
      }
    }
  }

This code works for the tests cases I have. But its not beautiful scala code. Kindly suggest the right approach to look at this problem and solve it functional way.


texts:
I started learning Python 2 about a week ago, using Codecademy and Stack Overflow answers to help me learn. I wrote a code to calculate the user's free time based on user sleep and work time. It also lets the user decide whether to see percentage of free time. It's not fancy; I never intend to actually use it. It works the way I want it to.

I'm looking for feedback on how I wrote this code. What should I have done differently?

print "The program is operating."

def sleep(time):
  sleep_hours = float(raw_input("How many hours do you sleep a night?: "))
  return time - sleep_hours

def work(time):
 work_hours = float(raw_input("How many hours do you work each weekday?: "))
 time -= work_hours
 return time

def see_percent():
  reply = raw_input("Would you like to know the percent of your waking time is free time? (Y/N): ").lower()
  if reply == "y":
    print percent_round + "%."
  elif reply == "n":
    print "Okay"
  else:
    print "Y/N means enter a 'Y' for yes or a 'N' for no."

time = 24.
time_minus_sleep = sleep(time)
time_minus_work = work(time_minus_sleep)
waking_time = time_minus_sleep
percent_free = str(time_minus_work / waking_time * 100)
percent_round = percent_free[:5]

print""
print "You have %.2f hours of freetime." % time_minus_work
waking_time = time_minus_sleep
print "Of the %.0f hours in a day, you are awake for %.2f of them." % (time, waking_time)


texts: New list from the elements of two lists popping sequentially

texts:
Can this be shortened, optimised or made more pythonic ?

a = [1,9,'foo',5,7]
b = ['bar',4,8,6]
c = []

min_len = min(len(a),len(b))

for i in range(min_len):
  c.extend([a.pop(0), b.pop(0)])

c.extend(a)
c.extend(b)

print c

output: [1, 'bar', 9, 4, 'foo', 8, 5, 6, 7]


texts:
I wanted to do the following:

Count the frequencies of words in a text (over 5 letters)
Invert the map of words to frequencies, but group together words that have the same frequency in the inversion.
Sort the inverted map by keys descending order and take the top 25.

Here is the code I came up with. Did I re-invent the wheel with map-invert-preserve-dups?  Is there a more concise way to do anything I did? Am I doing anything unnecessarily (i.e. (~k)?

(defn map-invert-preserve-dups
  [m]
  (reduce
    (fn [m [k v]]
      (if (contains? m v)
        (assoc m v (cons k (get m v)))
        (assoc m v `(~k))))
    {}
    m))

(->> "http://www.weeklyscript.com/Pulp%20Fiction.txt"
  (slurp)
  (re-seq #"\w{5,}")
  (frequencies)
  (map-invert-preserve-dups)
  (sort)
  (reverse)
  (take 25))


texts: Image-processing algorithm on mobile device

texts:
I have written the following algorithm (for Android/NDK) to apply levels to a bitmap. The problem is that it is really very slow.  On a fast device such as the SGSIII, it can take up to 4 seconds for an 8MP image. And on devices with ARMv6 takes ages (over 10 seconds). I know that can be speed up with NEON instructions, but I don't have such knowledge.

Is there any way to optimize it?

void applyLevels(unsigned int *rgb, const unsigned int width, const unsigned int height, const float exposure, const float brightness, const float contrast, const float saturation)
{
    float R, G, B;

    unsigned int pixelIndex = 0;

    float exposureFactor   = powf(2.0f, exposure);
    float brightnessFactor = brightness / 10.0f;
    float contrastFactor   = contrast > 0.0f ? contrast : 0.0f;
    float saturationFactor = 1.0f - saturation;

    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            const int pixelValue = buffer[pixelIndex];

            R = ((pixelValue & 0xff0000) >> 16) / 255.0f;
            G = ((pixelValue & 0xff00) >> 8) / 255.0f;
            B = (pixelValue & 0xff) / 255.0f;

            // Clamp values

            R = R > 1.0f ? 1.0f : R < 0.0f ? 0.0f : R;
            G = G > 1.0f ? 1.0f : G < 0.0f ? 0.0f : G;
            B = B > 1.0f ? 1.0f : B < 0.0f ? 0.0f : B;

            // Exposure

            R *= exposureFactor;
            G *= exposureFactor;
            B *= exposureFactor;

            // Contrast

            R = (((R - 0.5f) * contrastFactor) + 0.5f);
            G = (((G - 0.5f) * contrastFactor) + 0.5f);
            B = (((B - 0.5f) * contrastFactor) + 0.5f);

            // Saturation

            float gray = (R * 0.3f) + (G * 0.59f) + (B * 0.11f);
            R = (gray * saturationFactor) + R * saturation;
            G = (gray * saturationFactor) + G * saturation;
            B = (gray * saturationFactor) + B * saturation;

            // Brightness

            R += brightnessFactor;
            G += brightnessFactor;
            B += brightnessFactor;

            // Clamp values

            R = R > 1.0f ? 1.0f : R < 0.0f ? 0.0f : R;
            G = G > 1.0f ? 1.0f : G < 0.0f ? 0.0f : G;
            B = B > 1.0f ? 1.0f : B < 0.0f ? 0.0f : B;

            // Store new pixel value

            R *= 255.0f;
            G *= 255.0f;
            B *= 255.0f;

            buffer[pixelIndex] = ((int)R << 16) | ((int)G << 8) | (int)B;

            pixelIndex++;
        }
    }
}


texts:
I have used jQuery AJAX for my development. Below I have added example code for AJAX request and response.

ajax.php

$queView = array();

$queView['time'] = 40;
$queView['name'] = "Level hard";
$queView ['noQuestions'] = 10;
$queView['queDetails'] .= "
Some html content
";
$queView['queDetails'] .= "";

foreach($users as $user){
   $queView['queDetails'] .= "
".$user['name']."
";
   $queView['queDetails'] .=  "
".$user['address']."
";
}

echo json_encode($queView);

JavaScript function with jQuery;

function showQuestions(){

 $.ajax({
        data:{showQues:'1',attemptedQue:queId,selAnswer:checkedAns,timeTaken:timeTaken},
        url:'include/ajaxAttempt.php',
        success: function(data){

            data = $.parseJSON(data);

            $('#time').html(data.time);
            $('#name').html(data.name);
            $('#noQuesitons').html(data.noQuestions);
            $('#queDetails').html(data.queDetails);
        },

        error:function(xhr,err){
            alert("Error");
        }
    });
}

$queView['queDetails'] has a lot of HTML content.

Is this a good practice?


texts: Trie with insert, search, and startsWith methods for lowercase strings

texts:
I wrote the following prefix tree data structure for this Leet code challenge.

  Implement a trie with insert, search, and startsWith methods.

  Note:
  You may assume that all inputs are consist of lowercase letters a-z.

However it keeps timing out on the long input. As far as I know the insert, search and startsWith functions have \$\mathcal{O}(n)\$ time complexity, where \$n\$ is the length of the input string. Can someone review my code and see where I could improve the speed of the code?

class TrieNode(object):
    def __init__(self):
        self.next = [['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],
                     ['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],
                     ['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],['!',None],['!',None]]
        self.isWord = False

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        i = 0
        wordLength = len(word)
        node = self.root
        while i < wordLength:
            idx = ord(word[i]) - ord('a')
            if node.next[idx][0] == '!':
                node.next[idx][0] = word[i]
            if i < wordLength-1 and node.next[idx][1] == None:
                node.next[idx][1] = TrieNode()
            elif i == wordLength-1:
                node.isWord = True
                return
            i += 1
            node = node.next[idx][1]

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        i = 0
        wordLength = len(word)
        node = self.root
        while i < wordLength and node != None:
            idx = ord(word[i]) - ord('a')
            if node.next[idx][0] == '!':
                return False
            if i == wordLength - 1 and node.next[idx][1] != None:
                return node.isWord
            node = node.next[idx][1]
            i += 1
        if node == None and i < wordLength:
            return False
        return True

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie
        that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        i = 0
        wordLength = len(prefix)
        node = self.root
        while i < wordLength and node != None:
            idx = ord(prefix[i]) - ord('a')
            if node.next[idx][0] == '!':
                return False
            node = node.next[idx][1]
            i+=1
        if node == None and i < wordLength:
            return False
        return True


texts: Check if a linked list is a palindrome in Scala

texts:
The problem: Palindrome: Implement a function to check if a linked
  list is a palindrome

If it's a palindrome, the list must be the same backwards and forwards

Below is the code I wrote:

  def isPalindrome[A](list:List[A]):Boolean= (list.head, list.last)match{
    case (a,b) if a==b&&list.size>2 => isPalindrome[A](list.tail.dropRight(1))
    case (a,b) if a==b&&list.size<=2 => true
    case (a,b) if a!=b =>false
  }

May I know is there any way to improve it?