texts: N-elements byte array to integer conversion (little/big endian and signed/unsigned)

texts:
I'm trying to come up with a function to convert byte arrays to their integer representation, using both
endianness, and with a signed/unsigned option.
enum class ByteOrder {
    LITTLE,
    BIG
}

fun ByteArray.toInt(byteOrder: ByteOrder = LITTLE, signed: Boolean = true): Int {
    if (isEmpty()) {
        throw UnsupportedOperationException("Cannot convert an empty byte array")
    }

    val negative = signed &&
            (this[if (byteOrder == LITTLE) size - 1 else 0]).toInt() and 0b1000000 != 0

    if (!negative) {
        return absoluteToInt(byteOrder)
    }

    // The number is stored as two's complement.
    // Thus we invert each byte and then sum 1 to obtain the absolute value
    val negatedBytes = ByteArray(size)

    for ((i, byte) in withIndex()) {
        negatedBytes[i] = byte.inv()
    }

    return -(negatedBytes.absoluteToInt(byteOrder) + 1)
}

private fun ByteArray.absoluteToInt(byteOrder: ByteOrder): Int {
    var result = 0
    var shift = 8 * (size - 1)
    val range =
        if (byteOrder == LITTLE) {
            size - 1 downTo 0
        } else {
            0 until size
        }

    for (i in range) {
        result = this[i].toInt() and 0b11111111 shl shift or result
        shift -= 8
    }

    return result
}

You can submit a byte array of arbitrary size. Example:
val bytes: ByteArray = 9388608.toBytes() // Little endian, 4 elements
val intVal: Int = bytes.toInt() // Little endian

What's your opinion? Can this be done in a better way?


texts:
I was asked to perform addition by using vectors, so I am wondering if the function I coded looks good. If not, how can I improve the quality of my code? Below, I provided .h and .cpp files. I need feedback on the string constructor and operator+ modules.

.h file

class ubigint {
   friend ostream& operator<< (ostream&, const ubigint&);
   private:
      /*using unumber = unsigned long;
      unumber uvalue {};
      */
      using udigit_t = unsigned char;
      using ubigvalue_t = vector<udigit_t>;
      ubigvalue_t ubig_value;

   public:
      void multiply_by_2();
      void divide_by_2();

      ubigint() = default; // Need default ctor as well.
      ubigint (unsigned long);
      ubigint (const string&);

      ubigint operator+ (const ubigint&) const;
      ubigint operator- (const ubigint&) const;
      ubigint operator* (const ubigint&) const;
      ubigint operator/ (const ubigint&) const;
      ubigint operator% (const ubigint&) const;

      bool operator== (const ubigint&) const;
      bool operator<  (const ubigint&) const;
};

Currently, I am just done with the constructor and operator+. I feel like my function needs a little improvement since I seem to be repetitive in some places; however, a lot of people may say that the exhaustive creation of modules may lead to poor performance. I just tried to keep my code clean, but I don't know if the quality is good. I neither have checked if the code runs since I have to do other stuff in order to do so.
.cpp file

ubigint::ubigint (const string& that){
   DEBUGF ('~', "that = \"" << that << "\"");
   for (char digit: that) {
      if (not isdigit (digit)) {
         throw invalid_argument ("ubigint::ubigint(" + that + ")");
      }
   }

   for(string::reverse_iterator rit = that.str().rbegin(); rit != that.str().rend(); rit++) // iterate the string from end to start and store it in the vector
    {
        ubig_value.push_back(*rit); // push the character
    }

}

 ubigint ubigint::operator+ (const ubigint& that) const {  //modify to handle vector wise addition

    int carry = 0;  // current carrier
    int counter = 0;
    int pairAdditionResult = 0;
    int vectorValue = 0;
    udigit_t vectorCharValue = '0';
    ubigvalue_t result;

    do{
        pairAdditionResult = (ubig_value[counter] -'0') + (that[counter] - '0') + carry;
        carry = pairAdditionResult / 10;
        vectorValue = pairAdditionResult % 10;
        vectorCharValue = vectorValue + '0';
        result.push_back(vectorCharValue);
        counter++;

    }while(counter != ubig_value.size() && counter != that.size())

    if(ubig_value.size() != counter )  // if the size of the vectors differ
    {
        do{
          pairAdditionResult = (ubig_value[counter] - '0') + carry;
          carry = pairAdditionResult / 10;
          vectorValue = pairAdditionResult % 10;
          vectorCharValue = vectorValue  + '0';
          result.push_back(vectorCharValue);
          counter++;

        }while(counter != ubig_value.size())

    }
    else if (that.size() != counter)
    {
        do{
            pairAdditionResult =(that[counter] - '0') + carry;
            carry = pairAdditionResult / 10;
            vectorValue = pairAdditionResult % 10;
            vectorCharValue = vectorValue + '0';
            result.push_back(vectorCharValue);
            counter++;
        }while(counter != that.size(counter != that.size()))

    }

    if(carry != 0)  // for the last digit of the result
    {
        result.push_back(carry + '0');
    }

    int resultVectorSize = result.size();
    string resultVectorString;  // used for passing the number as a string in the returned object
    while(resultVectorSize != 0)
    {
        resultVectorString.push_back(result[resultVectorSize-1])
        resultVectorSize--;
    }

   return ubigint (resultVectorString);
}


texts:
Problem 33 in Project Euler asks:

  The fraction 49/98 is a curious fraction, as an inexperienced
  mathematician in attempting to simplify it may incorrectly believe
  that 49/98 = 4/8, which is correct, is obtained by canceling the 9s.

  We shall consider fractions like, 30/50 = 3/5, to be trivial examples.

  There are exactly four non-trivial examples of this type of fraction,
  less than one in value, and containing two digits in the numerator and
  denominator.

  If the product of these four fractions is given in its lowest common
  terms, find the value of the denominator.

This is the code I came up with, which solves the problem pretty handily. But, I'm concerned that this is messy and unreadable, even with the comments - and I simply hate using magic numbers/indices littered throughout the code. Also, I do not want a procedural ("C" style) solution - I'm learning how to write idiomatic (read "functional") programming with Ruby, and I'd like to learn how to write cleaner functional code.

a = 10.upto(99).to_a.map(&:to_s)  # Create array of integers 10 - 99
puts a.product(a)                 # Form cartesion product [a,b] for all 2 digit numbers a,b
      .reject{|x| x.any? {|y| y.chars.include? '0'}}     # Numbers inlcuding '0' are the trivial matches
      .reject{|x| x.first == x.last ||                   # Reject pairs where a = b
                  x.first.to_f/x.last.to_f > 1  ||       # Reject fractions greater than 1
                  (x.first.chars & x.last.chars).size != 1} # Reject pairs in which no digits are common
      .map{|x| [x.first.to_f / x.last.to_f, x.first.chars, x.last.chars, x.first.chars & x.last.chars]} # Ex: [0.5, ["4", "9"], ["9", "8"], ["9"]]
      .map{|x| [x.first, x[1] - x.last, x[2] - x.last, x[1], x[2]]}   # Ex: [0.5, ["4"], ["8"],  ["4", "9"], ["9", "8"]]
      .select{|x| x.length == 5 && x.first == x[1].join.to_f/x[2].join.to_f} # Select only the tuples which match the condition
      .map{|x| Rational(x[-2].join.to_i, x[-1].join.to_i)}  # Convert each such tuple to rational numbers
      .reduce(:*)


texts: Optimizing reading integers directly into a set without a list comprehension in Python

texts:
I am reading space separated integers, removing redundant ones and then sorting them. The following code works.

I was thinking whether this is the fastest way to do that or can it be optimized more?

import sys

def p():
    #Reads space seperated integers
    #Removes redundant
    #Then sorts them
    nums = set(map(int,next(sys.stdin).split()))
    nums = [i for i in nums] -
    nums.sort()
    print nums

EDIT:

tobia_k's suggestion is better performance-wise. Just 1 sentence instead of 3 and better in time-efficiency.

nums = sorted([int(i) for i in set(next(sys.stdin).split())])


texts: Am I using C++ pointers and references correctly?

texts:
I am a newbie to C++ programming and am currently reading this book called Jumping to C++ by Alex Allain.  I have finished the pointers chapter and I am doing the exercises at the end of the chapter.

The following paragraphs are the exercises and included are my own solutions:

  Write a function that prompts the user to enter his or her first name and last name, as two separate values. This function should
  return both values to the caller via additional pointer (or reference)
  parameters that are passed to the function. Try doing this first with
  pointers and then with references. (Hint: the function signature will
  look be similar to the swap function from earlier!)

// pointersExercise01.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;

void printName(string *pointFirstName, string *pointLastName){

    cout << endl << "Hello " << *pointFirstName << " " << *pointLastName;
}

void printName(string &pointFirstName, string &pointLastName){
    cout << endl << "Hi " << pointFirstName << " " << pointLastName;
}

int _tmain(int argc, _TCHAR* argv[])
{
    string firstName, lastName;

    cout << "Enter First Name ";
    cin >> firstName;
    cout << endl << "Enter Last Name ";
    cin >> lastName;

    /*FUNCTION POINTERS*/
    printName(&firstName, &lastName); // print out using pointers

    /*REFERENCE POINTERS*/
    printName(firstName, lastName);

    system("pause");
    return 0;
}

  The next exercise is to modify the program I wrote for exercise 1 so that instead of always prompting the user for a last name, it does
  so only if the caller passes in a NULL pointer for the last name.

// nullPointerExercise3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;

void userNames(string *pointerFirstName, string *pointerLastName){

    string firstN = *pointerFirstName;
    string LastN = *pointerLastName;
    bool flag;

    do{
        if(LastN == "NULL" ){
            cout << "Again what is your last name? ";
            cin >> LastN;

            flag = true;
        }else{
            flag = false;
        }

    }while(flag != false);
}

int _tmain(int argc, _TCHAR* argv[])
{
    string firstName, lastName;

    cout << "FIRSTNAME: ";
    cin >> firstName;
    cout << "\n" << "LASTNAME: ";
    cin >> lastName;

    userNames(&firstName, &lastName);

    system("pause");
    return 0;
}

If possible, I'd like to know if I did right for both of the exercise and if I am in the right direction.  Comments and tips will be helpful.


texts: Reporting the highest satisfied poker hand in F#

texts:
I'm learning F# by doing various small projects. One of them is a problem where the program reads Poker hands and rates them. It's Texas Hold'Em, so for each player it tries every five card selection from seven cards.

When it's time for scoring I have made a set of functions that each evaluate a hand and produces an Score option of whether that hand matches or not:

type Score =
{ Points: int
  Desc: string }

val tryStraightFlush: PokerHand -> Score option
val tryFourOfAKind: PokerHand -> Score option
// more functions ..
val getHighCard: PokerHand -> Score option

type PokerHand =
  class
    new : cards:Card list -> PokerHand
    member Cards : Card list
    member HighCard : Card option
  end

But now I have a problem, because I need to use the options that these functions produce, so I cannot do a match like this:

//Non-working code.
//Something roughly similar to this would be nice.
//But I need to use the values from the "try"-functions
//and they get thrown away here:

let scoreCards (hand: PokerHand) =
match hand with
| r when (tryStraightFlush hand) <> None -> //prod. Score
| r when (tryFourOfAKind hand) <> None -> //prod. Score
// more code

Instead my code ends up looking like this, and I have to say I don't like this deep nesting.. How can I have a small function for testing each type of configuration, while avoiding a deeply nested if-expressions?

let scoreCards (hand: PokerHand) =
  // Too much nesting!
  let r = tryStraightFlush hand
  if r <> None then
    r.Value
  else
    let r = tryFourOfAKind hand
    if r <> None then
        r.Value
    else
        let r = tryFullHouse hand
        if r <> None then
            r.Value
        else
            let r = tryFlush hand
            if r <> None then
                r.Value
            else
                // nesting continues..


texts: Single class which holds response and error message

texts:
I am working on a library which will make HTTP call to my rest service basis on inputs passed to this library. And whatever response comes back from service whether it is successful response or failure coming from the service or something happened in this library like timeout or any other errors, I am returning a response object back to the customer which customer can look into and iterate the object accordingly.

My response object is like this as of now and this is what I am returning back to the customer and customer will use this object and iterate it to figure out whether it is successful response or some failure and use it accordingly.

public class DataResponse {

    // response data
    private final String response;
    private final String date;
    private final String confidence;
    private final String mask;
    // what are the errors?
    private final ErrorCode error;
    // whether it is successful response or not
    private final StatusCode status;

    public DataResponse(String response, String date, String confidence, String mask, ErrorCode error, StatusCode status) {
        this.response = response;
        this.date = date;
        this.confidence = confidence;
        this.mask = mask;
        this.error = error;
        this.status = status;
    }

    // getters here

}

And below is my ErrorCode class which contains all the errors happened at client level or service level so that the customer can know what happened.

public enum ErrorCode {

    OK(200, "NONE", "Response is success."),
    NO_CONTENT(204, "No Content", "Response is success."),
    CLIENT_TIMEOUT(1007, "Timeout", "Timeout has occured on the Client.");
    // some more error messdates, keeping it short to show the idea

    private final int code;
    private final String status;
    private final String description;

    private ErrorCode(int code, String status, String description) {
        this.code = code;
        this.status = status;
        this.description = description;
    }

    // getters here

    @Override
    public String toString() {
        return code + " : " + status;
    }
}

And below is StatusCode class basis on which customer will decide whether it is successful response or not.

public enum StatusCode {
    SUCCESS, ERROR;
}

Customers of this library - they will use this DataResponse object in two ways:

Firstly, they can serialize DataResponse object to JSON as per their needs if they want to do it but it's up to them.
Secondly they will use this DataResponse object as it is and just iterate it normally.

So wanted to make sure from both the perspectives if the current design is good? If not what can be the improvements.

Please review my code. If you have any questions, please ask. If you have any comments, please give them.


texts: Function to check that two objects have "equivalent" values

texts:
I have two objects, a bet and a match. A match has 2 teams and both teams get a score at the end of the match. A bet has two scores set up before the match begins. Here I need to know if the bet specified the same winner as it's set on the match (once it's done).

// isGoodWinner
//
// @description :: return true if has bet on the good winner (or equality)
// @param       :: match (required): the match instance
//                 bet (require): the bet concerned
function isGoodWinner(match, bet) {
  var teamAWins = match.scoreTeamA > match.scoreTeamB;
  var teamBWins = match.scoreTeamA < match.scoreTeamB;
  var equality = match.scoreTeamA === match.scoreTeamB;

  var betOnTeamA = bet.scoreTeamA > bet.scoreTeamB;
  var betOnTeamB = bet.scoreTeamA < bet.scoreTeamB;
  var betEquality = bet.scoreTeamA === bet.scoreTeamB;

  return ((teamAWins && betOnTeamA) ||
        (equality && betEquality) ||
        (teamBWins && betOnTeamB));
}

I think my naming is poor and I don't know how to do it easier, do you have any advice?

Another question I have is: how can I be sure to unit test each case?


texts: A generic file helper for my future projects

texts:
I am learning Python and I know that a lot of my future projects will be based on files and managing them. How does this look? Is anything in here redundant or overcomplicated?

import os
import zipfile
import shutil
from datetime import datetime as dt

class File:
    def __init__(self, path, datetime=True):
        self.path = path
        self.datetime = datetime

        self.abs_path = os.path.abspath(self.path)

        self._dt_manager = lambda prop: prop if not self.datetime else dt.fromtimestamp(prop)
        self._os_path = lambda func, path_=self.abs_path, *args, **kwargs: getattr(os.path, func)(path_, *args, **kwargs)

        self.readable = False
        self.data = None
        self.lines = None
        self.line_count = None

        try:
            with open(self.path, "r") as target:
                self.data = target.read()
                self.lines = self.data.splitlines()
                self.line_count = len(self.lines)
                self.readable = True

        except UnicodeDecodeError:
            pass

        self.size_in_bytes = self._os_path("getsize")
        self.size = self.format_size(self.size_in_bytes)

        self.created = self._dt_manager(self._os_path("getctime"))
        self.last_modified = self._dt_manager(self._os_path("getmtime"))
        self.last_accessed = self._dt_manager(self._os_path("getatime"))

        self.full_name = self._os_path("basename")
        self.name, self.extension = self._os_path("splitext", self.full_name)

        self.dir_path = self._os_path("dirname")
        self.dir_name = self._os_path("basename", self.dir_path)

    def __repr__(self):
        return "<File {}>".format(self.full_name)

    def __str__(self):
        return self.abs_path

    def __getitem__(self, index):
        return self.lines[index]

    def __iter__(self):
        return self.data

    def __eq__(self, other):
        return self.abs_path == (other.abs_path if isinstance(other, File) else other)

    def __len__(self):
        return self.line_count

    @staticmethod
    def format_size(size_in_bytes, suffix="B"):
        for unit in ["", "K", "M", "G", "T"]:
            if abs(size_in_bytes) < 1024.0:
                return str(size_in_bytes) + unit + suffix
            size_in_bytes /= 1024.0

        return str(size_in_bytes) + "Y" + suffix

    def unzip(self, location=None):
        if location is None:
            location = self.dir_path

        with zipfile.ZipFile(self.abs_path, "r") as target:
            return target.extractall(location)

    def rename(self, new_name):
        return os.rename(self.abs_path, new_name)

    def copy(self, location=None, new_name=None):
        if location is None:
            location = self.abs_path

        return shutil.copy(self.abs_path, location if not new_name else location + new_name)

    def duplicate(self, amount=1, splitter="-"):
        duplicate_name = lambda index: self.name + splitter + str(index) + self.extension

        if amount > 1:
            for i in range(0, amount):
                self.copy(duplicate_name(i))

            return None

        return self.copy(duplicate_name(0))

    def delete(self):
        return os.remove(self.abs_path)

    def find(self, query):
        return [line for line in self.lines if query in line]


texts:
I was searching for a way to display a List<T> with n elements in a user friendly and easy to handle way within the console application. So I wrote this console-list-pagiation method.

Probably there are ways to improve the usability of my approach.

public static void ConsolePaging<T>(this IEnumerable<T> Values)
{
    int Pagesize = Console.WindowHeight - 2;
    int PageWidth = Console.WindowWidth - 1;
    int CurrentPage = 1;
    int PageCount = (Values.Count() + Pagesize - 1) / Pagesize;
    ConsoleKeyInfo keyInfo = new ConsoleKeyInfo();
    do
    {
        if (keyInfo.Key == ConsoleKey.RightArrow || keyInfo.Key == (ConsoleKey)0 || keyInfo.Key == ConsoleKey.LeftArrow)
        {
            if (keyInfo.Key == ConsoleKey.RightArrow && CurrentPage < PageCount)
            {
                CurrentPage++;
            }
            else if (keyInfo.Key == ConsoleKey.LeftArrow && CurrentPage > 1)
            {
                CurrentPage--;
            }
            Console.Clear();
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            string HeaderText = string.Format("Page:[{0}]/[{1}] │ Records:[{2}] ║ [◄] Previous │ [►] Next │ [Esc] Escape", CurrentPage, PageCount, Values.Count());
            Console.WriteLine(HeaderText.PadRight(Console.BufferWidth - 1, ' '));
            Console.ResetColor();
            foreach (T item in Values.Skip(Pagesize * (CurrentPage - 1)).Take(Pagesize))
            {
                string row = item.ToString();
                if (row.Length > PageWidth)
                {
                    row = row.Substring(0, PageWidth);
                }
                Console.WriteLine(row);
            }
        }
        keyInfo = Console.ReadKey(true);
    } while (keyInfo.Key != ConsoleKey.Escape);
}

usage:

Enumerable.Range(1, 1000).ToList().ConsolePaging();


texts:
I'm new to swift and I want to know if I'm doing something wrong or a harder way. I made a simple war game app. Tames of variables aren't correct, I know, but I was doing it quickly and I didn't worry about names of variables in that small project so I named them in English with Polish grammar.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var LeftCardOutlet: UIImageView!
    @IBOutlet weak var RightcardOutlet: UIImageView!
    @IBOutlet weak var LeftScoreOutlet: UILabel!
    @IBOutlet weak var RightscoreOutlet: UILabel!

    var karty = ["card2","card3","card4","card5","card6","card7","card8","card9","card10","jack","queen","king"]

    var scoreplayer:Int=0
    var CPUscore:Int=0
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    @IBAction func DealClicked(_ sender: UIButton) {
        var random1:Int = 0
        var random2:Int = 0
        random1 = Int(arc4random_uniform(UInt32(12)))
        random2 = Int(arc4random_uniform(UInt32(12)))
        var im1=UIImage(named:"\(karty[random1])")
        var im2=UIImage(named: "\(karty[random2])")
        LeftCardOutlet.image=im1
        RightcardOutlet.image=im2
        if random1>random2 {
            scoreplayer+=1
            LeftScoreOutlet.text=String(scoreplayer)
        }
        if random1<random2 {
            CPUscore+=1
            RightscoreOutlet.text=String(CPUscore)
        }
    }

}


texts:
I'm working on a Random Quote Generator Project, and as part of the project, the second instruction is to create a getRandomQuote Function which

should take in one parameter that will later get passed into this function when it is invoked will be the array of quotes.
The body of the function should select and return a random quote object from the quotesarray.

I'm kinda confused with my code, I want a review on my code as to whether its fits the instruction.
Below is my code, thanks!!

// An array of Objects with the quote and source as properties
var quotes = [
    {
        quote: "In the end, it’s not the years in your life that count. It’s the life in your years",
        source: "Abraham Lincoln",

    },
    {
        quote: "Don’t gain the world and lose your soul, wisdom is better than silver or gold",
        source: "Bob Marley",

    },
    {
        quote: "Lighten up, just enjoy life, smile more, laugh more, and don’t get so worked up about things",
        source: "Kenneth Branagh",

    },
    {
        quote: "Don’t cry because it’s over, smile because it happened",
        source: "Ludwig Jacobowski",

    },
    {
        quote: "Do stuff. Be clenched, curious. Not waiting for inspiration’s shove or society’s kiss on your forehead. Pay attention. It’s all about paying attention. Attention is vitality. It connects you with others. It makes you eager. Stay eager",
        source: "Susan Sontag",

    }
];

// getRandomQuote function selects and returns a random quote object
function getRandomQuote(array) {
    for (var i = 0; i < quotes.length; i++) {
        var quoteIndex = Math.floor(Math.random() * quotes.length);
        var randomQuote = quoteIndex;
    }
    return randomQuote;
}


texts:
I have coded a working Tic Tac Toe game tree generator. It doesn't only generate the game tree, it also applies minimax values to each node. The code works fine on a board that already has 2 or more played moves but slows down significantly for an empty board. I'm thinking of implementing alpha-beta pruning.

I am, however, having a hard time figuring out how I could modify my existing code to accommodate that. Can anyone point me in the right direction or suggest other improvements that may help with performance?

Notes: I am representing game states as a string in this format "0,0,0,1,0,0,-1,0,0" where 1 represents player X, -1 represent player O and 0 represents and empty square.

// Node constructor
var Node = function(state, parent, toPlay) {
  this.toPlay = toPlay;
  this.bestValue = null;
  this.state = state;
  this.parent = parent;
  this.child = [];
};

// Tree constructor
var Tree = function(state, toPlay) {
  this._head = new Node(state, null, toPlay);
};

// Possible winning combinations
var winStates = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [6, 4, 2]
];

// Check if game has been won
var checkIfWon = function(gameState, mark) {
  // Convert gameState string to array
  gameState = gameState.split(",").map(function(c) {
    return parseInt(c, 10)
  });
  // Iterates thru the winning combos to see if one is active
  var winner = winStates.some(function(combination) {
    var winning = true;
    for (var y = 0; y < combination.length; y++) {
      if (gameState[combination[y]] !== mark) {
        winning = false;
      }
    }
    return winning;
  });
  return winner;
};

// Check if game is a draw
var checkIfDraw = function(gameState) {
  return possibleMoves(gameState).length === 0;
}

// Check possible moves
var possibleMoves = function(gameState) {
  // Convert gameState string to array
  gameState = gameState.split(",").map(function(c) {
    return parseInt(c, 10)
  });
  return gameState.reduce(function(p, c, i) {
    if (c === 0) {
      p.push(i);
    }
    return p;
  }, []);
}

// Populate game tree
var populateTree = function(currentNode, toPlay) {
  if (checkIfWon(currentNode.state, 1)) {
    currentNode.bestValue = 1;
    return;
  }
  if (checkIfWon(currentNode.state, -1)) {
    currentNode.bestValue = -1;
    return;
  }
  if (checkIfDraw(currentNode.state)) {
    currentNode.bestValue = 0;
    return;
  }
  // Generate possible next moves
  var possible = possibleMoves(currentNode.state);
  for (var i = currentNode.state - 1; i >= 0; i--) {
    possible.push(i);
  }

  while (possible.length) {
    // Selects the next move randomly
    var move = possible.splice(Math.floor(Math.random() * possible.length),
      1)[0];

    // Updates the new game state
    var val = currentNode.state.split(",").map(function(c, i) {
      if (i === move) {
        return toPlay;
      }
      return parseInt(c, 10)
    }).join();

    // Create a new child Node
    currentNode.child.push(new Node(val, currentNode, toPlay * -1));
    nodeCount++;
  }

  // Recursive call
  for (var j = 0; j < currentNode.child.length; j++) {
    populateTree(currentNode.child[j], toPlay * -1);

  }

  // Assign bestValue according to the value of child Nodes
  if (currentNode.toPlay === 1) {
    currentNode.bestValue = currentNode.child.reduce(function(p, c) {
      return p > c.bestValue ? p : c.bestValue;
    }, -1);

  } else {
    currentNode.bestValue = currentNode.child.reduce(function(p, c) {
      return p < c.bestValue ? p : c.bestValue;
    }, 1);
  }

};

var nodeCount = 0;
tree = new Tree("0,0,0,1,0,0,-1,0,0", 1);
populateTree(tree._head, tree._head.toPlay);
//console.log(tree);
console.log(nodeCount);


texts: Stored Procedure enhancement for updating columns in a subset

texts:
The purpose of this store procedure is to reach into a large database (test), query for a subset, and update a column value, but with a big constraint - I can only update one row at a time in order to avoid deadlocks because the database is large and used by many resources.

The code attempts to change the value of test.[stat] to 'R' if a subset is found with the corresponding stat values.

ALTER PROCEDURE [dbo].testProcedure (@name NVARCHAR(10),
                                    @num INT,
                                    @msg NVARCHAR(200) OUTPUT )

AS

BEGIN

  DECLARE @val1 NVARCHAR(10)
  DECLARE @val2 INT

  SELECT  t.val1, t.val2, t.stat, 'N' rel
  INTO #temp
  FROM   dbo.test t
  WHERE  t.[name] = @name
    AND t.[stat] IN ('A','B')
    AND t.[num] = @num
  IF @@ROWCOUNT = 0
  BEGIN
    SET @msg = 'Nothing returned'
    PRINT @msg
    RETURN -1
  END

  SELECT @val1 = val1 FROM #temp where rel = 'N'

  SET @msg = ' val1: ' +  @val1 + ' '

  WHILE EXISTS (SELECT 1 from #temp WHERE rel = 'N')
    BEGIN
        SELECT @val2 = val2 FROM #temp where rel = 'N'

        UPDATE t
        SET [stat] = 'R'
        FROM   dbo.test t
        WHERE  t.val1 = @val1 AND t.[stat] IN ('A', 'B') AND t.val2 = @val2

        UPDATE #temp
        SET rel = 'Y'
        WHERE val2 = @val2

        SET @msg = @msg + ' - ' + ISNULL(CONVERT(NVARCHAR,@val2),' ')
    END

  IF OBJECT_ID('tempdb..#tempd') IS NOT NULL DROP TABLE #temp

  PRINT @msg
END

Any help on how to improve this code will be greatly appreciated.


texts: Munkres algorithm in Python: calculating maximum profit

texts:
I'm using Munkres library from https://github.com/bmc/munkres/ to calculate maximum profit (reversed problem).

What do you think about this coding style?

def get_no_of_vowels(str):
    return sum(str.lower().count(c) for c in "aeiuoy")

def get_no_of_consonants(str):
    return sum(str.lower().count(c) for c in "bcdfghjklmnpqrstvwxz")

def count_letters(str):
    return sum(c.isalpha() for c in str)

def compute_ss(name, item):
    if not count_letters(item)%2:
        ss = get_no_of_vowels(name)*1.5
    else:
        ss = get_no_of_consonants(name)
    if gcd(count_letters(name), count_letters(item)) > 1:
        ss*=1.5
    return ss

if __name__ == "__main__":
    with open(sys.argv[1]) as f:
        for line in f:
            names = line.strip().split(';')[0].split(',')
            items = line.strip().split(';')[1].split(',')
            dic = collections.defaultdict(list)
            profit_matrix = []
            for name in names:
                row = []
                for item in items:
                    row.append(compute_ss(name, item))
                profit_matrix.append(row)
            m = Munkres()
            cost_matrix = make_cost_matrix(profit_matrix, lambda x: 1e10 - x)
            indexes = m.compute(cost_matrix)
            total = 0
            for row, column in indexes:
                value = profit_matrix[row][column]
                # print '(%.2f, %.2f) -> %.2f' % (row, column, value)
                total += value
            print "%.2f"%total


texts: MySQL group PO data in ranges with avg number of approvals

texts:
I expanded the query provided by Gordon Linoff here.

I used this query, configured for my invoices, and it worked great - it took around 1.3 seconds to run. However, when configured as below for my Purchase Order data, it never returns a result timing out while the query runs. What optimization can I do to make this code (or something with the same desired result) run faster?

Desired result:

Customer name (database ()), number of orders in each range, total dollar amount, avg number of approvals for this range.

SELECT DATABASE() as PURCHASING_Count_Range,
(case WHEN (total =0) then '$0' WHEN (total < 500) then 'Less than
$500' WHEN (total >= 500) AND (total < 1000) then 'Between $500 and
$1,000' WHEN (total >= 1000) AND (total < 10000) then 'Between $1,000
and $10,000' WHEN (total >= 10000) and (total<=100000) then 'Between
$10K and $100K' WHEN (total >10000.01) and (total <= 100000) then
'Between $10K and $100K' WHEN (total >= 100000.01) then 'Over
$100K'end)
as 'Range',

count(*) as Number_of_Reqs,
SUM(case WHEN total =0 then total WHEN total < 500 then total WHEN
total >= 500 AND total < 1000 then total WHEN total >= 1000 AND total <
10000 then total WHEN total >= 10000 and total <=100000 then total WHEN
total>100000.01 then total end)
as 'VALUE',

(COUNT(app.approvable_id)/Count(*)) as AVG_Approvals

FROM (select requisition_lines.header_id, sum(reporting_total) as total
FROM requisition_lines LEFT JOIN requisition_headers ON
(requisition_lines.header_id = requisition_headers.id)

GROUP BY requisition_lines.header_id) requisition_lines
LEFT JOIN requisition_headers ON
(requisition_lines.header_id=requisition_headers.id =
requisition_headers.id)

LEFT JOIN (SELECT COUNT(approver_id) num_of_approvals, approvable_id

FROM approvals where status = 'approved' group by approvable_id) app ON
(requisition_headers.id=app.approvable_id)

WHERE (requisition_headers.status NOT LIKE '%draft%')
GROUP BY(case WHEN (total =0) then '$0' WHEN (total < 500) then 'Less
than $500' WHEN (total >= 500) AND (total < 1000) then 'Between $500
and $1,000' WHEN (total >= 1000) AND (total < 10000) then 'Between
$1,000 and $10,000'WHEN (total >= 10000) and (total<=100000) then
'Between $10K and $100K'WHEN (total >10000.01) and (total <= 100000)
then 'Between $10K and $100K' WHEN (total >= 100000.01) then 'Over
$100K'end)


texts: Constructing a tibble from another tibble (without for loops?)

texts:
tibbles documentation
I've got this doing what I want, but it's using a for loop and I've read many times to avoid for loops in R for efficiency and style. Well, it's not a computationally demanding task and I think it might be as clear as it could be in a for loop. In any case, it seems a bit tricky to process this functionally rather than iteratively.
I'm starting with one tibble: source_tbl.
I want to make another tibble: constructed_tbl.
Every column in constructed_tbl is a sum of a subset of columns in source_tbl.
The column mapping is stored in col_conversion_tbl.
>print(col_conversion_tbl)

# A tibble: 6 x 2
source_col       constructed_col
<chr>            <chr>
1 col1             A
2 col2             A
3 col3             A
4 col4             A
5 col5             B
6 col6             B

So,
constructed_tbl[,'A']
should be equal to ...
rowSums(source_tbl[,c('col1','col2','col3','col4')])
The best way I've come up with
The best way I've come up with is to

convert col_conversion_tbl to a list, col_conversion_lst, where each item is an array of source_cols and is named after a constructed_col.
initialize an empty constructed_tbl tibble w/ appropriate nrows, ncols, and column names
Loop through names(col_conversion_lst) replacing the empty column from constructed_tbl with the sum of the appropriate columns from source_tbl.

Here's my code
library(tibble)
library(magrittr)
library(purrr)

source_tbl <- tibble(col1=c(1,1,1),col2=c(2,2,2),col3=c(3,3,3),col4=c(4,4,4),col5=c(5,5,5),col6=c(6,6,6))
col_conversion_tbl <- tibble(source_col = c('col1','col2','col3','col4','col5','col6'), constructed_col = c('A','A','A','A','B','B'))

col_conversion_lst <- col_conversion_tbl %>%
    split(.$constructed_col) %>%
    map(~.$source_col)

constructed_tbl <- as_tibble(matrix(nrow=nrow(source_tbl),ncol= length(col_conversion_lst) ))
colnames(constructed_tbl) <- names(col_conversion_lst)

for (n in names(col_conversion_lst)){
    constructed_tbl[,n] <- rowSums(source_tbl[ ,col_conversion_lst[[n]]])
}


texts: Tracking stock prices using Python and Google Sheets

texts:
The purpose of this program is to keep track of some stocks that we bought in a game and every week we must list the closing prices of each stock in a Google Sheet. I thought since I had a lot of different investments to keep track of I would write a quick script to do it for me. And I could have my friends in class send me their stocks as well to save them time.

I am just looking for any bad practices I might have in my code as well as any more efficient ways of carrying out some of the functions.

from yahoofinancials import YahooFinancials
import re
import pygsheets
import pandas as pd
import datetime

now = datetime.datetime.now()
time_now = (now.year, now.month, now.day)
time_now = str(time_now)

data = []
formatedData = []
shortData = []
everything = []
tickers = ['XOM', 'JNJ', 'TR', 'CRON', 'HSY', 'FL', 'PLNT', 'MCD', 'ARLP', 'LULU', 'RCII', 'DELL', 'DNKN', 'DIS']

def main(sheet, everything,place):
    gc = pygsheets.authorize(service_file='creds.json')

    # Create empty dataframe
    df = pd.DataFrame()

    # Create a column
    df['Closings: ' + time_now] = everything
    # open the google spreadsheet (where 'PY to Gsheet Test' is the name of my sheet)
    sh = gc.open('PY to Gsheet Test')

    # select the first sheet
    wks = sh[sheet]

    # update the first sheet with df, starting at cell A2.
    wks.set_dataframe(df, (1, place))  # up/down,left right

for i in tickers:
    tick = YahooFinancials(i)
    history = tick.get_historical_price_data('2019-03-07', '2019-03-08', 'daily')
    y = str(history)
    data.append(y)

for i in data:
    i = i[i.index('adjclose'):]
    i = re.findall("\d+\.-?\d*", i)
    i = str(i)
    if len(i) > 7:
        formatedData.append(i[2:9]) #the decimals were really long so this shortens them down a bit
    else:
        formatedData.append(i)

y = 0
for i in tickers:
    x = i
    x = x + " : " + formatedData[y]
    y = y + 1
    everything.append(x)

def get_name(person):
    if person == 'tommy':
        sheet = 0
    elif person == 'chad':
        sheet = 1
    elif person == 'kaya':
        sheet = 2
    elif person == 'twohey':
        sheet = 3
    elif person == 'majers':
        sheet = 4
    elif person == 'tori':
        sheet = 5
    elif person == 'kayla':
        sheet = 6
    place = input("What Week Is This? 1,2,3,4,5?: ") # This will move the entry one place over for each week
    place = int(place)
    main(sheet, everything,place)

print('DONT FORGET TO CHANGE TICKER')
person = input("Whos Data Is Going In: ")
get_name(person)


texts:
I have a dashboard page which populates some charts. They execute a Linq query to then transform the data into Json to populate the Chart.

These charts maybe used throughout the site, so I am looking to make them as reuse-able as possible. Something just doesn't feel quite right with the way I am doing it at the moment.

Chart.cs

    public class Chart
    {
        StaffContext _db = new StaffContext();

        public List<PieChartColours> GetPieChartColours(int noOfColours)
        {
            var chartColours = _db.ChartColours.Take(noOfColours).OrderBy(c => Guid.NewGuid())
                .Select(s => new PieChartColours { Colour = s.Colour, HighlightedColour = s.HighlightedColour }).ToList();

            return chartColours;
        }

        public List<PieChart> PopulatePieChart(IEnumerable<dynamic> data)
        {
           var colour = GetPieChartColours(data.Count());

           var colourList = new List<PieChart>();

            var i = 0;
            foreach (var row in data)
            {
                colourList.Add(new PieChart
                {
                    value = row.value,
                    color = colour[i].Colour,
                    highlight = colour[i].HighlightedColour,
                    label = row.label
                });
                i++;
            }

            return colourList;
        }
    }

DashboardController.cs

public JsonResult WeeklyAttendanceSummary()
    {
        Chart chart = new Chart();

        DateTime d = DateTime.Today;

        int offset = d.DayOfWeek - DayOfWeek.Monday;
        offset = (offset < 0) ? 6 : offset;

        DateTime startDate = d.AddDays(-offset);
        DateTime endDate = startDate.AddDays(7);

        var data = (from a in _db.Attendances
                    join at in _db.AttendanceTypes on a.Type equals at.AttendanceTypeID
                    where a.Date >= startDate
                    && a.Date < endDate
                    group at by at.AttendanceTypeDescription into g
                    select new
                    {
                        value = g.Count(),
                        label = g.Key
                    }).ToList();

        return Json(JsonConvert.SerializeObject(chart.PopulatePieChart(data)), JsonRequestBehavior.AllowGet);
    }

    public JsonResult MonthlyAttendanceSummary()
    {
        Chart chart = new Chart();

        DateTime today = DateTime.Today;

        DateTime startDate = new DateTime(today.Year, today.Month, 1);
        DateTime endDate = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));

        var data = (from a in _db.Attendances
                    join at in _db.AttendanceTypes on a.Type equals at.AttendanceTypeID
                    where a.Date >= startDate
                    && a.Date < endDate
                    group at by at.AttendanceTypeDescription into g
                    select new
                    {
                        value = g.Count(),
                        label = g.Key
                    }).ToList();

        return Json(JsonConvert.SerializeObject(chart.PopulatePieChart(data)), JsonRequestBehavior.AllowGet);
    }


texts:
I'm wanting to model a family tree in the F# type system.  The basic requirements:

A family tree is made up of family members
A family member has a required ancestor
A family member has an optional partner

My struggle is what to do with the "root" family member.  I thought about making it an option:

type FamilyMember = { Name:string; Ancestor:FamilyMember option; ... }

but it seems all family members are required to come from somewhere.

So, that lead me to think an ancestor union type, where either it is an empty root or it is a descendant.  Is there a cleaner way?

Here's what I have:

type Person = string
type FamilyMember = {
    Person: Person
    Partner: Person option
    Ancestor: Ancestor
}
and Ancestor =
    | Root
    | Descendent of FamilyMember

let joe = { Person = "joe"; Partner = Some("joyce"); Ancestor = Root; }
let steve = { Person = "steve"; Partner = Some("pat"); Ancestor = Descendent(joe) }
let megan = { Person = "megan"; Partner = None; Ancestor = Descendent(steve)}
megan


texts: Best way to work out angle between points?

texts:
I have the following JavaScript code to work out the angle between two points (clockwise). The code I have seems a bit "hacky" to me, as I have a while loop ensuring the number is not negative (to make the range 0-360), as well as I have to subtract 270 degrees to get it to work correctly. Is there a better way to do this?

this.angle = function(point)
{
    var delta = point.subtract(this);
    var aR = Math.atan2(delta.y, delta.x);
    var aD = aR * (180 / Math.PI);
    aD -= 270;
    while (aD < 0)
    {
        aD += 360;
    }
    return aD;
};


texts: Perl CGI script to respond to erroneous Base64 image requests

texts:
I often get lines like this in my Apache error log:

  File does not exist: /path/to/www/data:image/gif;base64,R0lGODlhBgAGAIAOAP/yH5BAEACAEALAAAAAAGGAYAAAIJhB0Xi5vOoFwFADs=

Obviously, this is due to somebody using an outdated browser (or a robot) which doesn't handle inline images (Data URI/base64 encoded).

I am thinking it must be easy to redirect requests starting with "data:image/gif;base64," to a short perl CGI script which returns the requested value as a binary image, with the correct content header (both GIFs and PNGs are used), and without having to read any image files.

I am thinking something along the lines of the following CGI (after a rewrite places the request URL in the query string):

#!/usr/bin/perl
use strict;
use warnings;
use MIME::Base64 ();
$ENV{QUERY_STRING} =~ m{^data:(\w+/\w+);base64,(.+)$} or die "bad input";
print "Content-Type: $1\n\n";
print MIME::Base64::decode ($2);

Would that work and would there be any downsides to this approach (apart from accommodating people with last-century browsers)?


texts:
I was asked to solve the following exercise:

Given an input vector<string>, I have to find the anagrams and return a vector<string> with only the strings that are not an anagram from other strings in the vector.

Example:

Input vector:

"code","doce","framy","frame","sad","cat","frema"

Output:

"code","framy","sad","cat"

Here, the anagram "frame" == "frema" is removed. All words which are anagrams from one another are removed.

My solution is to sum the ASCII values from the strings, if two strings are equal, then I sort it to check for equality.

#include <iostream>
#include <bits/stdc++.h>
#include <algorithm>    // std::sort

using namespace std::chrono;
using namespace std;

int sumASCII(string input) {

    int i;
    int sum = 0;
    int size = input.size();

    for( i = 0; i < size; i++) {

        sum+=(int)input[i];
    }

    return sum;
}

int sortStringAndCompare(string &a, string &b)
{
   sort(a.begin(), a.end());
   sort(b.begin(), b.end());
   return a.compare(b);
}

vector<string> funWithAnagrams(vector<string> &text) {

    bool anagram = false;
    int i;
    int size = text.size();
    int sumCurr = 0;
    int sumPrev = 0;
    int k = 0;
    int originalSize = 0;

    string copyA;
    string copyB;

    vector<string> originalStrings;

    originalStrings.push_back(text[0]);

    for( i = 1 ; i < size;  i++ ) {
        sumCurr = sumASCII(text[i]);
        originalSize = originalStrings.size();

        for( k = 0; k < originalSize; k++ ) {

            if(originalStrings[k].size() == text[i].size() ) {
                sumPrev = sumASCII(originalStrings[k]);

                if(sumPrev == sumCurr) {// means it found a possible anagram.

                    copyA = originalStrings[k];
                    copyB = text[i];
                    if(sortStringAndCompare(copyA,copyB) == 0)
                    {
                        anagram = true;
                        break;
                    }
                }
                else
                    anagram = false;
            }
            else {
                anagram = false;
            }

        }
        if(!anagram) {
            originalStrings.push_back(text[i]);
            }
    }

    return originalStrings;
}

int stringCompare(std::string a,std::string b)
{
    return a.compare(b);

}

void print(std::vector<string> const &input)
{
    int size = input.size();
    printf("[ ");
    for (int i = 0; i < size; i++) {
        std::cout << input.at(i) << ' ';

        if(i < (size-1))
            printf(",");
    }

    printf(" ]");
}

int main() {

    printf("TEST STARTED\n");
    vector<string> input{"doceframe","code", "doce","ecod","framer","frame", "frema","cat","sad"};
    vector<string> out;

    // Get starting timepoint
    auto start = high_resolution_clock::now();
    out = funWithAnagrams(input);
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);

    cout << "Time taken by function: " << duration.count() << " microseconds" << endl;
    printf("\n \n");
    print(out);
    printf("\n");

    printf("TEST ENDED\n");

    return 0;

}

My program is not the best in terms of memory, i shall improve it. But my task, at the moment, is to develop the fastest algorithm possible. How can I improve it?


texts: moving player right or left depending on swipe

texts:
In my Player.java class, I want to incorporate a function that moves my player according to the left or right swipes. I also used time in seconds in order to vary the movement in an cyclic way:

'''
class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00"));
            Date currentLocalTime = cal.getTime();
            DateFormat date = new SimpleDateFormat("KK:mm");
            date.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
            String localTime = date.format(currentLocalTime);
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X-=K;
                    int currentSeconds = cal.get(Calendar.SECOND);
                    Y=Y*Math.cos(18.currentSeconds);
                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X+=K;
                    int currentSeconds = cal.get(Calendar.SECOND);
                    Y=Y*Math.cos(18.currentSeconds);
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
'''

After some research, this is the class I included in player.java. So my question is: Is there a more efficient way to detect swiping directions(without creating any additional class) and what is your opinion about the code structure knowing that the objective is to change X according to swipe direction.

Thank you.


texts: addition of two list elementwise with abortion if condition satisfied python

texts:
I have a function that sums two arrays element-wise and stops if the sum at a certain index is greater strictly than 1. This function is called lot of times (15817145 times for a small simulation and expects to grow a lot more as the simulation size grows). Profiling my code shows that it is among the five most consuming functions of my code  and  I believe can be optimized further.
def add_lis(lis1, lis2):
    res = []
    for i, j in zip(lis1, lis2):
        if i + j > 1:
            return
        res.append(i + j)
    return array('H', res)

lis1 and lis2 are both of type array.array('H',..). The two lists have the same length which can be up to 100 and they are both filled with zeroes and ones only. I tried with numpy arrays but there is too much overhead that it is not beneficial to use it.
My question is can this function be optimized? Maybe in a sort of list comprehension ?


texts: Time calculator for a given speed and file size

texts:
I wrote this little code in c++. It calculates the needed time for a given speed of a medium (for example the speed is 1024 B/s, the file size is 1MB, it'll take 17 minutes and 4 seconds to finish). The code works, but I'm not sure if it's proper.

Can you tell me if it's okay or not?

#include <iostream>

int main()
{
    int transmission_speed; //speed of the transmission in bytes per seconds
    int file_size_mb; //file's size in MBs

    std::cout << "Enter the speed of the transmission in bytes per seconds: ";
    std::cin >> transmission_speed;
    std::cout << "Enter the file's size in megabytes: ";
    std::cin >> file_size_mb;

    int file_size_b = file_size_mb *1024*1024;

    int seconds_needed = file_size_b / transmission_speed;

    int days_needed = (seconds_needed / 3600) / 24;
    seconds_needed -= days_needed*86400;

    int hours_needed = seconds_needed / 3600;
    seconds_needed -= hours_needed*3600;

    std::cout << "Days needed: " << days_needed << std::endl;
    std::cout << "Hours needed: " << hours_needed << std::endl;
    std::cout << "Seconds needed: " << seconds_needed << std::endl;
    return(0);
}


texts:
This my solution to this Good Range Coding Challenge

There is a number space given from 1 to N. And there are M queries followed by that. In each query, we were given a number between 1 to N (both inclusive). We add these number one by one into a set.
Good range: A range in which there is exactly one element present from the set.
For each query, we need to find the good ranges. We need to return the sum of boundry of all good ranges.
Input:
First line will take two integer for input N and M.
Then following m lines would be numbers between 1 and N (both inclusive).
Output:
Following M lines contains sum of boudaries of good ranges.
Note:
Range can consist of single element and represented as (x-x) where boundary sum will be x+x.
Example:
Input:

10 4
2
5
7
9

Output:

11
18
30
46

Explaination:

step-1) set: 2
good range: (1-10)
sum: 1+10=11

step-2) set: 2 5
good range: (1-4), (3-10)
sum: 1+4+3+10=18

step-3) set: 2 5 7
good range: (1-4), (3-6), (6-10)
sum: 1+4+3+6+6+10=30

step-4) set: 2 5 7 9
good range: (1-4), (3-6), (6-8), (8-10)
sum: 1+4+3+6+6+8+8+10=46

#include <iostream>
#include <set>
using namespace std;

class Solution
{
    public:
    Solution(const unsigned int _N, const unsigned int _M) : N(_N), M(_M) {}

    void solve()
    {
        for(unsigned int i=0; i<M; ++i)
        {
            unsigned int v;
            cin >> v;
            cout << "New Element = " << v << endl;
            q.insert(v);
            print_res();
            cout << endl;
        }
    }

    void print_res()
    {
        unsigned int left=1;
        auto it=q.begin();
        unsigned int last = *it;

        for(++it; it!=q.end(); ++it)
        {
            const unsigned int curr = *it;
            const unsigned int right = curr-1;
            cout << "[" << left << ", "<< right << "] contains " << last << " and sum = " << (left+right) << endl;
            left = last+1;
            last = curr;
        }
        const unsigned right = N;
        cout << "[" << left << ", "<< right << "] contains " << last << " and sum = " << (left+right) << endl;
    }

    private:
    unsigned int N;
    unsigned int M;
    set<unsigned int> q;
};

int main() {
    // your code goes here
    unsigned int N=0;
    unsigned int M=0;
    cin >> N >> M;
    Solution sol(N,M);
    sol.solve();
    return 0;
}

Note: I am aware I'm returning more information than required by the problem description but I have chosen to do it to include also debugging information


texts:
I've decided to learn a bit of C++, and so I've started with a simple linked list. There's no input to the program and should always output hlo. This is as in main I build a list consisting of hello, and use Get and last to get the data.

I don't know C++, or C, and so this is mostly a stab in the dark. I don't know if I'm using C++ correctly, but I got a working program where I'm mostly exploring pointers, so I would like to know if my usage for them is correct. Otherwise please review any and all aspects of my code.

#include <iostream>

class Node {
public:
    Node(char data_) {
        data = data_;
    }

    Node *next = NULL;
    char data;
};

class LinkedList {
public:
    Node *root = NULL;
    Node *last = NULL;
    LinkedList() {}

    void Add(char data) {
        if (root == NULL) {
            root = new Node(data);
            last = root;
        } else {
            last->next = new Node(data);
            last = last->next;
        }
    }

    char Get(int index) {
        return _Get(index)->data;
    }
private:
    Node* _Get(int index) {
        Node *node = root;
        for (int i = 0; i < index; i++) {
            if (node == NULL) {
                throw std::out_of_range("List doesn't contain that item.");
            }
            node = node->next;
        }
        return node;
    }
};

int main() {
    LinkedList list = LinkedList();
    list.Add('h');
    list.Add('e');
    list.Add('l');
    list.Add('l');
    list.Add('o');
    std::cout << list.Get(0) << list.Get(2) << list.last->data << std::endl;
    return 0;
}


texts: Angular spinner combined with a response interceptor

texts:
So using angular-spinner angular-spinner github

i have created a directive that connects with a factory that is using a $http.interceptor

Using this i am able to use the Observer design pattern to "listen" for when data has been collected for a given route in my Api

The code looks something like this:

responseInterceptor Factory

angular.module('Api').factory('responseInterceptor', function () {
    var routeSubscribers = {};

    function notifyRouteSubscribers(route) {
        if (routeSubscribers[route]) {
            while (routeSubscribers[route].length) {
                routeSubscribers[route].pop()();
            }
        }
    }

    return {
        response: function (response) {
            if (response.config.url.indexOf('api') >= 0) {
                var myRegexp = /[^\/]+$/g;
                var match = myRegexp.exec(response.config.url);
                notifyRouteSubscribers(match[0]);
            }
            return response;
        },
        subScribeToRoute: function (route, callback) {
            if (routeSubscribers[route]) {
                routeSubscribers[route].push(callback);
            }
            else {
                routeSubscribers[route] = [callback];
            }
        }

    }
});

contentSpinner directive

angular.module('Api').directive('contentSpinner', function (responseInterceptor,$timeout) {
    return {
        restrict: 'E',
        templateUrl: 'js/helpers/Api/directives/content-spinner/content-spinner.html',
        scope: {
            boundRoute: '@',
            timeout: '=',
            timeoutms: '@'
        },
        link: function (scope, element, attr) {
            scope.shouldSpin = true;
            if (scope.boundRoute) {
                responseInterceptor.subScribeToRoute(scope.boundRoute, function () {
                    //Route has been completed and the spinner is ready to stop!
                    scope.shouldSpin = false;
                })
            }
            if (scope.timeout) {
                $timeout(function () {
                    scope.shouldSpin = false;
                }, scope.timeoutms);
            }

        }
    }
});

What i am worried about with this code is that when my application grows will this still be a viable way to do it? :) Hope some of you can give me a review :D


texts:
I wrote a SHA256 password cracker. I initially used lists to store the information in list1.txt and list2.txt but I would end up getting memory overloads. So I now use files.
I noticed that when I made this transition, the programme speed reduced hugely. Is there a way to optimise the speed of this programming without running into memory overload issues?
Thanks
import hashlib
import time
import os

def extract_password(fname):
    if fname == 0:
        filename = "list2.txt"
    else:
        filename = "list1.txt"
    for line in open(filename, "r"):
        yield line.strip()

def save_password(fname, password):
    if fname == 0:
        filename = "list1.txt"
    else:
        filename = "list2.txt"

    file = open(filename, "a")
    file.write(password)
    file.write("\n")
    file.close()

def next_password(lsta, item,next_char, secure_password):
    found = 0
    guess = item + chr(next_char)
    if hash_password(guess) == secure_password:
        print(guess)
        found = 1
    save_password(lsta, guess)
    return found

def hash_password(pwrd):
    #Generates hash of original password
    pwrd = pwrd.encode("UTF-8")
    password = hashlib.sha256()
    password.update(pwrd)
    return password.hexdigest()

def delete_file(ltsa):
    try:
        if ltsa == 1:
            os.remove("list2.txt")
        else:
            os.remove("list1.txt")
    except:
        pass

def reset_file_status():
    try:
        os.remove("list2.txt")
        os.remove("list1.txt")
    except:
        pass

def find_password(secure_password):
    #Brute force to find original password
    found = 0
    lsta = 1
    for length in range(1, 15):
        if found == 1: break
        lsta = lsta^1
        delete_file(lsta)
        for next_char in range(65, 123):
            if found == 1: break
            if length == 1:
                found = next_password(lsta, "", next_char, secure_password)
                if found == 1: break
            else:
                for item in extract_password(lsta):
                    found = next_password(lsta, item, next_char, secure_password)
                    if found == 1: break

if __name__ == "__main__":
    reset_file_status()
    start = time.time()
    secure_password = hash_password("AAAA")
    find_password(secure_password)
    print(f"{(time.time() - start)} seconds")


texts:
I recently learned the core .NET Queue type uses arrays internally, and that this is actually much more efficient. I've had a go at writing a singly-linked list version of a queue, MyQueue.

Running basic stopwatch times against this type and the .NET type shows about 50ms difference when queuing 1 million items and checking the length.

How can it be improved?

MyQueueNode

namespace MyQ.Core
{
    public class MyQueueNode<T> : IMyQueueNode<T>
    {
        private MyQueueNode<T> _nextNode;

        private T _value;

        public MyQueueNode(T value)
        {
            _value = value;
        }

        public void SetNextNode(ref MyQueueNode<T> nextNode)
        {
            _nextNode = nextNode;
        }

        public MyQueueNode<T> GetNextNode()
        {
            return _nextNode;
        }

        public T GetValue()
        {
            return _value;
        }
    }
}

MyQueue

namespace MyQ.Core
{
    public class MyQueue<T> : IMyQueue<T> where T : class
    {
        private volatile MyQueueNode<T> _headNode, _tailNode;

        public void Enqueue(T item)
        {
            MyQueueNode<T> newNode = new MyQueueNode<T>(item);

            if (_headNode == null)
            {
                _headNode = newNode;
                _tailNode = _headNode;
            }
            else
            {
                _tailNode.SetNextNode(ref newNode);
                _tailNode = newNode;
            }

            _length++;
        }

        public T Dequeue()
        {
            if(_headNode == null)
            {
                throw new QueueEmptyException();
            }

            T value = _headNode.GetValue();

            _headNode = _headNode.GetNextNode();

            _length--;

            return value;
        }

        public T Peek()
        {
            if(_headNode == null)
            {
                return null;
            }

            return _headNode.GetValue();
        }

        private long _length = 0;

        public long Length => _length;
    }
}


texts: Joining datatables to create a new datatable

texts:
I am joining datatables to create a new datatable:

var row = from r0w1 in dt_vi.AsEnumerable()
              join r0w2 in dt_w.AsEnumerable()
              on r0w1.Field<int>("ID") equals r0w2.Field<int>("iD")
              join r0w3 in dt_re.AsEnumerable()
              on r0w1.Field<int?>("ID") equals r0w3.Field<int?>("id")
              join r0w4 in dt_def.AsEnumerable()
              on r0w1.Field<int?>("ID") equals r0w4.Field<int?>("id") into ps
              from r0w4 in ps.DefaultIfEmpty()
              select r0w1.ItemArray.Concat(r0w2.ItemArray.Concat(r0w3.ItemArray.Concat(r0w4 != null ? r0w4.ItemArray : new object[] { }))).ToArray();

foreach (object[] values in row)
    dt.Rows.Add(values);

In the above code,

foreach (object[] values in row)
    dt.Rows.Add(values);

is slow for lakhs of rows. I want to put the data of row into dt datatable. Is there any faster way of doing this?


texts:
I have the following code:

for j in range(rows):
    for i in range(cols):
        k = j * rows + i

        k1 = k + 1 if i < cols - 1 else k - 1
        k2 = k - 1 if i > 0 else k + 1
        k3 = k + cols if j < rows - 1 else k - cols
        k4 = k - cols if j > 0 else k + cols

        w1 = U[k]
        w2 = U[k-1] if i > 0 else U[k]
        w3 = V[k]
        w4 = V[k-cols] if j > 0 else V[k]

        zarray[k] = (w1 + w2 + w3 + w4) * parray[k] - (w1 * parray[k1] + w2 * parray[k2] + w3 * parray[k3] + w4 * parray[k4])

I want to know if there is a way to vectorize this loops, because I think that exists a kind of "convolution" for zarray.

U and V are arrays representing 2D matrices with 512x512 elements, and parray is also a 2D representation with 512x512 elements.

In a previous post vectorization was recommended, but now I can not figure out how to vectorize when I have different indices operations.


texts: Hook to switch the linter binaries in Emacs Lisp according to virtual environment

texts:
Problem

I use Emacs for Python development along with several linters. When I activate a Python virtual environment (venv) from within Emacs, I would like to set the linter binaries according to the following rules:

If the venv has a particular linter installed, use it
If the venv does not have a particular linter, use the one in a pre-specified, default venv
If the linter does not exist in either the active venv or the default venv, set the linter binary to nil

For example, let's say I activate a venv called my_venv that has pylint installed, but no flake8. flake8 is however installed in my default linters venv. After activating my_venv, the linters that will be used are

pylint -- my_venv
flake8 -- linters

Purpose

The reason for implementing this is that I develop Python on multiple machines that share a single, version-controlled init.el file. I do not want to guarantee that I have the same Python binaries and venvs across these machines; this implementation helps decouple my Emacs setup from the Python venvs that are present on a machine.

Additional info

The code will go inside my init.el file
I use flycheck as the interface between Emacs and the linters
I use pyvenv for Python virtual environments in Emacs

Code

(defvar linter-execs '((flycheck-python-flake8-executable "bin/flake8")
                       (flycheck-python-pylint-executable "bin/pylint")
                       (flycheck-python-pycompile-executable "bin/python")))
(defvar default-linter-venv-path (concat (getenv "WORKON_HOME") "/linters/"))

(defun switch-linters ()
  "Switch linter executables to those in the current venv.

If the venv does not have any linter packages, then they will be
set to those in the `default-linter-venv-path` venv.  If these do
not exist, then no linter will be set."
  (dolist (exec linter-execs)
    (let ((venv-linter-bin    (concat pyvenv-virtual-env (nth 1 exec)))
          (default-linter-bin (concat default-linter-venv-path (nth 1 exec)))
          (flycheck-var       (nth 0 exec)))
      (cond ((file-exists-p venv-linter-bin)
             (set flycheck-var venv-linter-bin))
            ((file-exists-p default-linter-bin)
             (set flycheck-var default-linter-bin))
            (t (set flycheck-var nil))))))

(add-hook 'pyvenv-post-activate-hooks 'switch-linters)

Explanation

linter-execs is a list of two-element lists. The first element of an entry is the flycheck variable that contains the path of a linter binary. The second element is the relative path of the binary from within the venv.
The default linter venv is $WORKON_HOME/linters
switch-linters is the call-back function attached to pyvenv-post-activate-hooks
The conditional checks for the presence of the linter binary files, first in the current venv and next in the default venv. Failing these, it sets the binary to nil in the line (t (set flycheck-var nil))

Specific questions

Is this idiomatic elisp, or is it too "Pythonic"?
Is linter-execs the proper way to implement a list of tuples in elisp?


texts: Finding columns of a matrix that are the same for combinations of events

texts:
How I can change this multi-loop to reduce the computation time?

A is a matrix (5 × 10000) where the fifth line contains values between 1 and 50 corresponding to different events of an experiment. My goal is to find the columns of the matrix which are the same for all possible combinations of 7 different events.

data = A(1:4,:);
exptEvents = A(5,:);

% Find repeats
[b,i,j] = unique(data', 'rows');

% Organize the indices of the repeated columns into a cell array
reps = arrayfun(@(x) find(j==x), 1:length(i), 'UniformOutput', false);

% Find events corresponding to these repeats
reps_Events = cellfun(@(x) exptEvents(x), reps, 'UniformOutput', false);

U = cellfun(@unique, reps_Events, 'UniformOutput', false);
repeat_counts = cellfun(@length, U);

kk=1;

for i1=1:50
    for i2=1:50
        for i3=1:50
            for i4=1:50
                for i5=1:50
                    for i6=1:50
                        for i7=1:50
                            if i1~=i2 && i2~=i3 && i3~=i4 && i4~=i5 && i5~=i6 && i6~=i7
                               myEvents = [i1 i2 i3 i4 i5 i6 i7];
                               v= b(cellfun(@(x)all(ismember(myEvents,x)),U),:);
                               intersection(1,kk)=v(1);
                               intersection(2,kk)=v(2);
                               intersection(3,kk)=v(3);
                               intersection(4,kk)=v(4);
                               intersection(5,kk)=i1;
                               intersection(6,kk)=i2;
                               intersection(7,kk)=i3;
                               intersection(8,kk)=i4;
                               intersection(9,kk)=i5;
                               intersection(10,kk)=i6;
                               intersection(11,kk)=i7;
                               kk=kk+1;
                            end
                        end
                    end
                end
            end
        end
    end
end


texts: High execution time to count overlapping substrings

texts:
I was doing this HackerRank problem which basically boils down to counting overlapping substrings in a string. I used this solution from StackOverflow to build this program -

def overlapping_occurrences(string, sub):
    count = start = 0
    while True:
        start = string.find(sub, start) + 1
        if start > 0:
            count+=1
        else:
            return count

def find_health(start, end, d, genes, gene_health):
    hv = 0
    beneficial = set(genes[start:end+1])
    for b in beneficial:
        # b is just a single letter, so no possibilities of overlapping
        if len(b) == 1:
            occurrences = d.count(b)
        else:
            occurrences = overlapping_occurrences(d, b)
        total_value = sum(gene_health[b])
        hv += total_value*occurrences
    return hv

if __name__ == '__main__':
    n = int(raw_input())
    genes = list(raw_input().split())
    health = list(raw_input().split())
    gene_health = {}
    for idx in xrange(n):
        try:
            gene_health[genes[idx]].append(int(health[idx]))
        except:
            gene_health[genes[idx]] = []
            gene_health[genes[idx]].append(int(health[idx]))
    s = int(raw_input())
    health_values = []
    for _ in xrange(s):
        start, end, d = raw_input().split()
        health_values.append(find_health(int(start), int(end), d, genes, gene_health))
    low = min(health_values)
    high = max(health_values)
    print "%d %d" % (low, high)

I've used a dictionary gene_health because as the first example in the problem description shows, a single gene can have multiple different values, so I store all those values in a list which I sum over to get the total_value.

My problem is that this program takes a very long time and exceeds the time limit on most of the test cases. I do think that this algorithm is CORRECT, since for the few test cases where it doesn't time out, it gives the correct answer. So I'm just looking for a way to speed up the program, and I think the only place where any speedups can be performed is in the overlapping_occurrences method.

I've searched for other similar questions on StackOverflow but all of them use regex but regex will make it even slower (I think).

Any suggestions or poking in the right direction will help. Thank you!


texts: Make the awt.Color class constructors except out of range arguments

texts:
Ok, this might be a very stupid question/idea (I'm still a beginner). Lets say I have a construct like this:

g.setColor(new Color(random.nextInt(5) * speed, 255, speed * 3));

Now it is very likely that the passed arguments will in some cases be out of the expected range, so the code will throw an exception. To circumvent this case I wrote the following helper class:

public class SafeColor {

    static final int INT_MIN = 0;
    static final int INT_MAX = 255;
    static final float FLOAT_MIN = 0;
    static final float FLOAT_MAX = 1;

    public static Color safeIntColor(int r, int g, int b) {
        if (r < INT_MIN) r = INT_MIN;
        if (g < INT_MIN) g = INT_MIN;
        if (b < INT_MIN) b = INT_MIN;

        if (r > INT_MAX) r = INT_MAX;
        if (g > INT_MAX) g = INT_MAX;
        if (b > INT_MAX) b = INT_MAX;

        return new Color(r, g, b);
    }

    public static Color safeIntAlphaColor(int r, int g, int b, int a) {
        if (r < INT_MIN) r = INT_MIN;
        if (g < INT_MIN) g = INT_MIN;
        if (b < INT_MIN) b = INT_MIN;
        if (a < INT_MIN) a = INT_MIN;

        if (r > INT_MAX) r = INT_MAX;
        if (g > INT_MAX) g = INT_MAX;

        // ... and so on ...

Now I can do this:

g.setColor(SafeColor.safeIntColor(random.nextInt(5) * speed, 255, speed * 3));

I guess the question is, does that make any sense? The whole thing looks a bit overdone to me. Is there a better/easier way to accomplish the same thing?

Edit: For anyone interested. I boiled it down to this:

public class SafeColor {

    private static final float FLOAT_MAX = 1;
    private static final float FLOAT_MIN = 0;
    private static final int INT_MAX = 255;
    private static final int INT_MIN = 0;

    private static float safeFloat(float f) {
        return Math.max(Math.min(f, FLOAT_MAX), FLOAT_MIN);
    }

    private static int safeInt(int i) {
        return Math.max(Math.min(i, INT_MAX), INT_MIN);
    }

    public static Color safeColor(float r, float g, float b, float a) {
        return new Color(safeFloat(r), safeFloat(g), safeFloat(b), safeFloat(a));
    }

    public static Color safeColor(float r, float g, float b) {
        return new Color(safeFloat(r), safeFloat(g), safeFloat(b));
    }

    public static Color safeColor(int r, int g, int b, int a) {
        return new Color(safeInt(r), safeInt(g), safeInt(b), safeInt(a));
    }

    public static Color safeColor(int r, int g, int b) {
        return new Color(safeInt(r), safeInt(g), safeInt(b));
    }

}


texts:
This program is to return a number one at a time from a given input list of numbers, with a frequency proportional to probability/fraction associated with each number.

I know it could be made a generator function. But if I have to do it inside a class, can you please suggest improvements to this code, particularly with regards to the exception classes I have made below?

from random import random
from bisect import bisect_right

class Invalid_fraction(ValueError): pass
class Negative_fraction(ValueError): pass
class Sum_fraction(ValueError): pass
class NullValues(ValueError): pass

class RandomGen(object):
    def __init__(self, nums, fractions):
        #Basic error checks
        if ( len(nums)==0 or len(fractions) == 0):
            raise NullValues("Null sample space")

        if ( len(nums) != len(fractions) ):
            raise Invalid_fraction("Invalid fraction list")

        #Data initiallisations
        self._sum  = 0
        self._fractions= []
        self._nums = nums

    #Allocating a range within 0-1 to each of the input number, along with check for negative fraction.

        for p in fractions:
            if p < 0:
                raise Negative_fraction("negative fraction")
            self._sum += p
            self._fractions.append(self._sum)

        if self._sum != 1:
            raise Sum_fraction("Sum of fractions is not equal to 1")

    def next_num(self):
        #Get a random number between 0 and 1 and yield the number of the bucket
        random_number = random()
        index = bisect_right(self._fractions,random_number)
        return self._nums[index]


texts: Getting client timezone name to use with PHP date_default_timezone_set()

texts:
I would like to get the current user's timezone name so it can be used with the PHP date_default_timezone_set(). After looking up a few things I've finally managed to come up with a solution for this. I'm not great with code though so any code checks/help will be appreciated.

As long as it is a fair guess of the user's timezone, it is good enough for me. It seems to work OK. Here it is:

/**
 * JS/jQuery - Set cookie of current user's UTC offset (format example: -06:00)
 *
 */
$(document).ready( function() {

        // Get UTC offset
        var offset = new Date().getTimezoneOffset(), o = Math.abs(offset);
        var offset = (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);

        if (document.cookie.indexOf("hp_time_offset") >= 0) {} else {

            // Set cookie
            $.cookie( 'hp_time_offset', offset, { expires : null, path:'/' } );
        }

});

/**
 * PHP - Get the UTC offset cookie and convert it to a timezone name
 *
 */
function hp_get_timezone() {

    if( isset( $_COOKIE['hp_time_offset'] ) ) {

        $time_offset = $_COOKIE['hp_time_offset'];

        // validate - exit if offset cookie contains anything other than "0-9 + - :",
        if ( preg_match('/[^0-9:\+\-]/', $time_offset) )
            return;

        // validate - exit if offset cookie is not in correct range
        if ( ! in_array($time_offset, range(-12, 14)))
            return;

        // Calculate seconds from offset
        list($hours, $minutes) = explode(':', $time_offset);
        $seconds = $hours * 60 * 60 + $minutes * 60;

        // Get timezone name from seconds
        $tz = timezone_name_from_abbr('', $seconds, 1);

        // bug fix
        if($tz === false)
            $tz = timezone_name_from_abbr('', $seconds, 0);

        // if still false, set a default timezone name.
        if($tz === false)
            $tz = 'America/New_York';

    } else {

        // If cookie doesn't exist, set a default timezone name.
        $tz = 'America/New_York';
    }

    return $tz;
}

//set timezone
date_default_timezone_set( hp_get_timezone() );

Any help appreciated.


texts: HackerRank Array left rotation using Swift

texts:
I solve this problem in Swift. Looking for feedback on my code or a better solution:

import Foundation

// parses line to return array of numbers in string format
func readIntegers() -> [String] {
    return readLine()!.componentsSeparatedByString(" ").map { $0 }
}

// left rotates the array by a given input
func leftRotation() -> String {
    let input = readIntegers()
    let array = readIntegers()
    var newArray = [String](count: Int(input[0])!, repeatedValue: "")
    let (count, rotations) = (Int(input[0])!, Int(input[1])!)

    for index in 0..<count {
        // newIndex after rotation
        let newIndex = index + rotations
        if newIndex < count  { // up until count
            newArray[index] = array[newIndex]
        } else { // loops back to beginning index of array
            newArray[index] = array[newIndex - count]
        }
    }
    // joins the array
    return newArray.joinWithSeparator(" ")
}

print(leftRotation())


texts: Implementing sbrk for a custom allocator in C

texts:
I took on a for-fun task of creating a memory allocator which uses process memory rather than making a bunch of system calls to the operating system. The task was: implement my own malloc() and free() functions which are limited to a pool (stack array) of 20000 bytes. I already had my own malloc and free implementations which used the sbrk() in unistd.h, but I realized the difference here would be that I need to re-create an sbrk that instead of getting memory from the OS, gets memory from my array. I had no experience doing this and was quite frankly pretty unfamiliar with how sbrk() worked internally. Even more, I still don't fully understand unistd's sbrk() integer pointer param. Nevertheless, I came up with a way to imitate the functionality below:

#define MEMORY_CAPACITY 20000
//NOTE: These are GLOBAL variables below
char global_mem[MEMORY_CAPACITY] = {0};
void *p_break = &global_mem;
void* mov_sbrk(int increment)
{
    void *final_address = (char*) global_mem + (MEMORY_CAPACITY-1);
    void *original = p_break;
    if(increment == 0)
    {
        return p_break;
    }
    if(((char*)p_break + increment) < (char*)global_mem)
    {
        ERR("mov_sbrk: Cannot move to address prior to start of memory.");
        return (void*) -1;
    }
    if(((char*)p_break + increment) > (char*)final_address)
    {
        ERR("You've run out of memory!");
        return (void*) -1;
    }
    p_break = (void*) ((char*)p_break + increment);
    return original;

}

Note that ERR is just a macro for fprintf(stderr, msg). Please critique this implementation and let me know if I am missing anything. I've performed some tests with my allocator and so far, it performs as expected. The difference though is that I used a int because a int ptr like the "official" sbrk() uses as a parameter didn't make sense to me since it would force increments of the architecture's integer size rather than byte-by-byte.


texts:
WiKi and GitHub.

Sudoku rules are being checked with the following tests:

    [TestMethod]
    public void Be_Valid()
    {
        var data = new int?[,]
        {
            { 5, 3, null },
            { 6, null, null },
            { null, 9, 8 }
        };

        var board = new Board(data);
        Assert.IsTrue(board.Valid);
    }

And:

    [TestMethod]
    public void Be_Invalid()
    {
        var data = new int?[,]
        {
            { 5, 3, 8 },
            { 6, null, null },
            { null, 9, 8 }
        };

        var board = new Board(data);
        Assert.IsFalse(board.Valid);
    }

Where actual implementation looks like:

public class Board
{
    public Board(int?[,] cells)
    {
        Cells = cells ?? throw new ArgumentNullException(nameof(cells));
        if(Cells.GetLength(0) != Cells.GetLength(1))
            throw new ArgumentNullException(nameof(cells), "Square board required.");
        if (Cells.GetLength(0) % 3 != 0)
            throw new ArgumentNullException(nameof(cells), "Board size should be multiple of 3.");
    }

    int? [,] Cells { get; }
    int N => Cells.GetLength(0);

    public bool Valid => ColumnsValid && RowsValid && GridsValid;

    bool RowsValid => Rows.All(AreUnique);
    bool ColumnsValid => Columns.All(AreUnique);
    bool GridsValid => Grids.All(AreUnique);

    IEnumerable<IEnumerable<int>> Rows =>
        Range(0, N).Select(r => Numbers(0, N - 1, r, r));
    IEnumerable<IEnumerable<int>> Columns =>
        Range(0, N).Select(c => Numbers(c, c, 0, N - 1));
    IEnumerable<IEnumerable<int>> Grids =>
        from r in Range(0, N / 3)
        from c in Range(0, N / 3)
        select Numbers(
            c * 3, c * 3 + 2, r * 3, r * 3 + 2);

    bool AreUnique(IEnumerable<int> numbers) =>
        numbers.Distinct().Count() == numbers.Count();

    IEnumerable<int> Numbers(int left, int right, int top, int bottom) =>
        from r in Range(top, bottom - top + 1)
        from c in Range(left, right - left + 1)
        where Cells[r, c].HasValue
        select Cells[r, c].Value;
}


texts: plz help optimize the small code snippet, VS2010 profiling chart provided

texts:
Profiling shows MoveNext takes most time, which I guess is true as it is lazy. But I don't know in what direction I could improve the code. (Open pic in new tab would allow u see bigger chart.)

    IEnumerable<string> MixedBlock(List<string> reelLayout, string thisBlock, int length)
    {
        List<string> recentBlock = RecentBlock(length - 1, reelLayout);
        var upper = Enumerable.Range(1, length - 1);
        var lower = Enumerable.Range(1, totalWeight[thisBlock].Num);
        var query = from x in upper
                    from y in lower
                    where x + y == length
                    select Tuple.Create(x, y);
        foreach (var t in query)
        {
            string upperBlock = string.Join(",", recentBlock.Skip(length - 1 - t.Item1));
            string lowerBlock = string.Join(",", thisBlock.Split(',').Take(t.Item2));
            yield return upperBlock + "," + lowerBlock;
        }

    }


texts: Filter by a transformed list, then untransform the result

texts:
Both exercises have a common pattern of "filter by a transformed list, then untransform the result". See skip and localMaxima.

-- exercise 1
skips :: [a] -> [[a]]
skips xs = map (\n -> skip n xs) [1..(length xs)]

skip :: Integral n => n -> [a] -> [a]
skip n xs = map snd $ filter (\x -> (fst x) `mod` n == 0) (zip [1..] xs)

--exercise 2
isLocalMaximum :: Integral a => (a,a,a) -> Bool
isLocalMaximum (a,b,c) = b > a && b > c

sliding3 :: [a] -> [(a,a,a)]
sliding3 xs@(a:b:c:_) = (a,b,c) : sliding3 (tail xs)
sliding3 _ = []

localMaxima :: Integral a => [a] -> [a]
localMaxima xs = map proj2 $ filter isLocalMaximum (sliding3 xs)
  where proj2 (_,b,_) = b

-- *Main> filter isLocalMaximum (sliding3 [1,5,2,6,3])
-- [(1,5,2),(2,6,3)]

My instincts say that I could implement both of these something like this:

localMaxima' :: Integral a => [a] -> [a]
localMaxima' xs = filterBy isLocalMaximum sliding3 xs

if only I could implement filterBy

filterBy :: (b -> Bool) -> ([a] -> [b]) -> [a] -> [a]
filterBy p f as = as'
  where indexedAs = zipWith (,) [0..] as
        indexedBs = zipWith (,) [0..] (f as)
        indexedBs' = filter p indexedBs     -- doesn't typecheck; how can we teach p about the tuples?
        indexes = map fst indexedBs
        as' = map (\i -> snd (indexedAs !! i)) indexes

It's also slower than just writing out a fold. Is this all a bad idea? I've always considered fold a low level recursion operator and always try to structure in terms of higher level map and filter but maybe I am misunderstanding.

My Haskell level is: understand LYAH but not written much code.

This is a homework to CIS 194 (2013 version) (though I am not taking the class, I am working through the material on my own)


texts:
I want to convert strings with the iso date format (2015-08-02) to the default format of our app (2 Aug 2015) in ClojureScript. As I don't need anything else, I don't want to pull in libs like cljs-time.

I'm quite new to Clojure & ClojureScript, so I want to ask for some feedback on this small snippet. Thanks!

(defn format-date [date]
  (let [month-names [nil "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"]
        [year month day] (map #(js/parseInt %) (str/split date #"-0?"))]
    (str day " " (month-names month) " " year)))


texts:
This is working but right now it is not giving me the throughput that I want. The main function has the load generation loop (where it is putting work in Queue). I am trying to model a Poisson arrival process for the memcached requests (keys are randomly generated and this is handled in sendRequest). Right now it takes about 3.4 seconds to send (just send, for loop completion) 1000 requests. I want to generate about 30k requests per second or more (adjusting the lambda sleep parameter accordingly).

Is it possible to achieve that speed? What part of this code is limiting the speed of the for loop?

import pylibmc, time, csv
import random, sys, os
import numpy as np
from Queue import Queue
from threading import Thread
import threading
from size_key import size_key #size key is a dict which maps value size to a list of keys

sk=0
sizes=map(str,range(1,1001))
lock=threading.Lock()
nbr_hits=0
rts=0

def sendRequest():
    strt=time.time()
    global sk
    global sizes

    db=pylibmc.Client(["10.2.10.79:21201"]) # port for memcachedb
    mc=pylibmc.Client(["10.2.10.45:11211","10.2.10.47:11211","10.2.10.48:11211","10.2.10.61:11211"])

    r=random.randint(0,999)
    valsize=sizes[r]
    r=np.random.geometric(p=0.1)%len(sk[valsize])
    key=sk[valsize][r]

    val=mc.get(key)
    hit=True
    if val==None: # that means key was not found in memcached
        hit=False
        val=db.get(key)
        mc.set(key,val)

    elapsed=time.time()-strt

    finished(val,elapsed,hit)

def finished(v,rt,hit):
    global lock
    global rts
    global nbr_hits
    with lock:
        rts+=rt
        if hit:
            nbr_hits+=1

concurrent=256
q=Queue(concurrent*2)

def doWork():
    global q
    while True:
        nothing=q.get()
        sendRequest()
        q.task_done()

def main():
    global sk
    global rts
    global nbr_hits
    sk=size_key # same dict as before

    lambd=30000 #inverse of average inter-arrival time, request rate

    sum=0
    start=time.time()

    global concurrent
    global q
    for i in range(concurrent):
        t=Thread(target=doWork)
        t.daemon=True
        t.start()

    print "Started thread pool"
    n=1000
    try:
        st=time.time()
        for i in range(0,n):
            q.put(i)
            wt=random.expovariate(lambd)
            time.sleep(wt)

        et=time.time()-st
        print "Time to send 1k requests:%0.6f"%et
        q.join()
    except KeyboardInterrupt:
        sys.exit(1)

    print "Completed, average latency:%0.6f hit_rate:%0.3f"%(rts/n,float(nbr_hits)/n)
    elapsed=time.time()-start
    print "Time to complete 1k reqs:",elapsed

main()


texts: Simple prime factorization program in Haskell

texts:
I'm finally learning Haskell this summer and I have a few questions about conventions. I made a simple prime factorization program which is surprisingly fast, much faster than the ones I made in C++ (though to be fair I made those non-recursively).

It consists of three functions: one checks if a num is prime, one finds the prime factors, and one checks if a list's length is less than a number. The last one is because I was worried that take and length would be too slow and the Haskell wiki agreed. I just copied and pasted their at least function and reversed it.

import Data.List
import Data.Ord

isPrime :: Integer -> Bool
primes :: Integer ->[Integer]

isLengthLessThan :: Int -> [a] -> Bool
isLengthLessThan 0 _      = False
isLengthLessThan _ []     = True
isLengthLessThan n (_:ys) = isLengthLessThan (n-1) ys

isPrime x
    | x == 2       = True
    | mod x 2 == 0 = False
    | otherwise    = isLengthLessThan 2 [y | y <- [1,3.. roof], mod x y == 0]
    where roof = 1 + truncate (sqrt $fromIntegral x)

primes x
    | isPrime x = [x]
    | otherwise = factor : primes(div x factor)
    where factor = head $filter checkdiv [2..]
          checkdiv n = x `mod` n == 0

Finally the questions:

Should isLengthLessThan be in a where under isPrime?
Is isLengthLessThan's name too verbose?
What should I name my "primes" function?
Are the function type specifications called that or declarations?
Should I put the type specifications right before the function or should I put it at the start?
Do specifications help speed or do they only help us by giving us better errors?
Do parenthesis make compilation faster or do they only muddle code up?


texts: Ruby Rails - Snippets from a project that don't seem so eloquent

texts:
I'm brand new to both Ruby and Rails, and while all the following works, it seems a bit messy.

This is on a classified model to generate WHERE/AND WHERE clauses based on whether or not the user supplies a value through a dropdown. I'm not sure if there's a more Active Recordy way of doing this:

class Classified < ActiveRecord::Base
   attr_accessible :car_id, :owner_id, :owner, :price, :condition, :description, :mileage
   belongs_to :car
   belongs_to :owner, :polymorphic => true
   has_one :model, :through => :car
   has_one :make, :through => :model
   has_many :pictures
 scope :filter_active_cars, lambda { |options|
 filter = {}
 filter[:cars] = {:year => options[:year]} unless options[:year].empty?
 filter[:makes] = {:id => options[:make]} unless options[:make].empty?
 filter[:models] = {:id => options[:model]} unless options[:model].empty?

 joins(:car, :model, :make)
 .where(filter)
 .includes(:car, :model, :make)
 }

The view has this

=select_tag('car[year]', options_for_select(years, :selected => @selected_year))
=collection_select(:car, :make, Make.all, :id, :name, {:include_blank => '- Make -', :selected => @selected_make})
=collection_select(:car, :model, @selected_make ? Model.where(:make_id => @selected_make) : Model.all, :id, :name, {:include_blank => '- Model -', :selected => @selected_model})

This is the way I'm passing the "select state" on the classified view. The controller has this snippet in the index action. This is so when a user filters a result and submits the form, the corresponding select box has the same value for the form helpers above.

if params[:car]
  params[:car].each do |option, value|
    next if value.empty?
    eval("@selected_#{option} = #{value}")
  end
end

On the form partial to generate and edit a classified. Obviously the chaining of &&s sucks, but it's the only way to get the default selection on new, edit, and when a user submits a new form that contains errors.

=select_tag('car[year]', options_for_select(years, :selected => @classified.car.nil? ? nil : @classified.car.year), :prompt => "- Year -")
=collection_select(:make, :id, Make.all, :id, :name, {:prompt => '- Make -', :selected => (@classified.car && @classified.car.make && @classified.car.make.try(:id))})
=collection_select(:car, :model_id, Model.all, :id, :name, {:include_blank => '- Model -', :selected => (@classified.car && @classified.car.model && @classified.car.model.try(:id))})


texts:
There is a list consisting of zeroes and ones. I want to find out the length of the longest streak of ones. Is there a better solution?

def consecutive_one(data):
   one_list = []
   size = 0
   for num in data:
       if num == 1:
           one_list.append(num)
       elif num == 0 and size < len(one_list):
           size = len(one_list)
           one_list = []

    return size

if __name__ == '__main__':
    data = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0]
    print(consecutive_one(data))


texts: Using a Boolean method that never returns "false" to check user permissions

texts:
I need to check that a user is allowed to save/retrieve contacts to/from the database by calling a web service, and return an HTTP403 with an explanation if it is not the case.

So for the sake of factorizing the code, I decided to use a boolean method that "never" returns false and is there only to check this, and throws a corresponding exception.

public boolean canPerformAction(User authenticatedUser) throws ForbiddenActionException{
  if(authenticatedUser == null){
    throw new ForbiddenActionException("There must be a user to perform an action !");
  }

  if(!authenticatedUser.BelongToCompany(company)){
    throw new ForbiddenActionException("The user doesn't belong to the company, therefore he can't perform the action");
  }

  return true;
}

Then in saveContact, I call it as follows:

public Person saveContact(User user, Person contact) throws ForbiddenActionException{

  canPerformAction(user);

  contact= persistContact(contact);

  return contact;
}

I do the same thing in retrieveContact:

public Person retrieveContact(User user, String contactId) throws ForbiddenActionException{

    canPerformAction(user);

    return fetchContact(contactId);
 }

And finally these methods are called in the web service:

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveContact(@PathParam("contactId") String contactId) {
  try{
    Person contact= retrieveContact(getUser(), contactId);
    return Response.status(Response.Status.OK).entity(contact).build();
  }catch(ForbiddenActionException e){
    return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
  }
}

@POST
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response saveContact(@PathParam("id") String id, Person contact) {
  try{
    Person contact= saveContact(getUser(), contact);
    return Response.status(Response.Status.OK).entity(contact).build();
  }catch(ForbiddenActionException e){
    return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
  }
}

Do you think that this is an acceptable approach of dealing with the problem ?


texts:
I have a small function in Objective-C which uses the C Socket API to check if the device has an active internet connection:

#include <netdb.h>

- (BOOL)isNetworkAvailable {
    char *hostname;
    struct hostent *hostinfo;
    hostname = "youtube.com";
    hostinfo = gethostbyname(hostname);
    if (hostinfo == NULL) {
        return NO;
    } else {
        return YES;
    }
}

I have rewritten this function in Swift, using an UnsafeMutablePointer type for the hostent struct:

func isNetworkAvailable() -> Bool {
    var hostinfo: UnsafeMutablePointer<hostent>
    let hostString: String = "youtube.com"
    var hostname = (hostString.cStringUsingEncoding(NSUTF8StringEncoding))!
    hostinfo = gethostbyname(hostname)
    if (hostinfo == nil) {
        hostinfo.destroy()
        return false
    } else {
        hostinfo.destroy()
        return true
    }
}

Is there a better way to check for network connectivity in Swift without using the C API?  How can I improve this function, possibly removing the need to manually retain and release an UnsafeMutablePointer?