texts:
I am creating an application which needs to validated user input to ensure the words being entered are real words. What improvements if any can I make?

class MyDictionary {

    Vector<String> words = new Vector<>();

    public MyDictionary() {
        URL url;
        try {
            url = new URL("http://www.example.com/hugewordlist.txt");
            URLConnection uc = url.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            char[] buffer = new char[1024];
            int i = 0;
            StringBuffer b = new StringBuffer();
            int readBytes = 0;
            while ((readBytes = br.read(buffer, i, 1024)) != -1) {
                i += 1024;
                b.append(buffer, 0, readBytes);
            }
            for (String w : b.toString().split("\n")) {
                words.add(w);
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean hasWord(String word) {
        return words.contains(word);
    }

    public int size() {
        return words.size();
    }
}


texts: Reduce function on custom data structure using Cats Semigroup

texts:
This is for purely pedagogical purposes only. So, within the contrived data structure and its constraints, I'm interested in knowing how might one improve that reduce function and whether I've properly used the Semigroup typeclass correctly here.

object ComplexData {
  import cats.Semigroup
  import cats.instances.all._

  case class Element(name: String, value: Int, els: List[Element] = Nil) {

  def reduce[A : Semigroup](z: A)(f: Element => A): A = {
      Semigroup[A].combine(f(this),
        els match {
          case Nil => z
          case _ => els.map(_.reduce(z)(f)).reduce((a, b) => Semigroup[A].combine(a, b))
        })
      }
    }

    val e1 = Element("Zero", 0,
      List(
        Element("One", 1,
          List(Element("Two", 2,
            List(
             Element("Three", 3),
             Element("Four", 4))))),
        Element("Five", 5,
          List(
           Element("Six", 6),
           Element("Seven", 7),
           Element("Eight", 8,
             List(
               Element("Nine", 9),
               Element("Ten", 10)))))))

   e1.reduce(0)(_.value)
   //res0: Int = 55

   e1.reduce("")(_.name + " ")
   //res1: String = Zero One Two Three...

   e1.reduce(0)(_.els.length)
   //res2: Int = 10

   e1.reduce("")(e => e.name + " -> " + e.value + ", ")
   //res3: String = One -> 1, Two -> 2, Three -> 3, ...
 }

Specifically:

While it works, not excited by the use of view bounds given that they are long since
deprecated (attempting to use A <: Semigroup[A]in the function signature did not compile), do I really need an implicit definition here of the semigroup if I wanted to go this way?
That pattern match seems accidentally complex, even given my constraints there's probably a more elegant or at least more straightforward way to do that, yes?
If I used aMonoid[A]instead of a semigroup I could get rid of thezparameter and provide aZero[A]orEmpty[A], I think - is that the preferred way to go?


texts: Program to reverse a string using std::string

texts:
Background: I'm trying to learn C++ and I'm doing that by writing some programs by myself. I'm decent with C, but I'm having trouble translating to OOP paradigm. I'm reading from learncpp.com and a book called Thinking in C++.

I'm noticing that reading doesn't really help much as much as writing programs and running into issues and solving them.

Here is a program I've written to reverse a string in C++ using std::string (SO tells me this should be used as opposed to C-style strings/char arrays):

example_one.h

#ifndef example_one_h
#define example_one_h

#include<iostream>
#include<string>
#include<cstdio>

using namespace std;

class stringOps{

    private:
        string arr;
        int length;

    public:
        // Constructor - Destructor
        stringOps(string arr);
        ~stringOps();
        // Member functions

        //1. get length of string
        int getLength();

        //2. print string
        const string& displayString(const stringOps &a);

        //3. Reverse the string and return obj of type stringOps.
        stringOps reverseStr(stringOps &a);

};

#endif

example_one.cc

#include "example_one.h"

/* Constructor and Destructor */
stringOps::stringOps(string a):arr(a), length(a.size()) {
}

stringOps::~stringOps() {
}

/* Member functions */
// 1.  get Length
int stringOps::getLength()
{
    return arr.size();
}

//2. display string
const string& stringOps::displayString(const stringOps &a)
{
    //cout << a.arr << endl;
    return a.arr;
}

//3. reverse array of the object.
stringOps stringOps::reverseStr(stringOps &a)
{
    reverse(a.arr.begin(), a.arr.end());
    return a;
}

/*  -------------------------------- Main  --------------------- */
int main()
{
    stringOps strA("Hello");

    string x = strA.displayString(strA);
    printf("Original string: %s \n", x.c_str());

    int len = strA.getLength();
    printf("String length:%d \n",(len));

    strA.reverseStr(strA);
    string y = strA.displayString(strA);
    printf("Reverse string: %s \n", y.c_str());

    return 0;
}

Questions:

What is good about this code (so that I can continue to do this for other programs)?
What is bad about this code? (Be brutal in your assessment.) Specifically, I have doubts about the best approach to take while writing functions 2 and 3.

Function 2:

const string& stringOps::displayString(const stringOps &a)
{
    //cout << a.arr << endl;
    return a.arr;
}

I tried doing this with return type as void and cout within the function, but apparently there's going to be an error for this with iostream. So is returning const string& a good way to do this? I passed by const reference because I do not change the object within the function.

Function 3:

stringOps stringOps::reverseStr(stringOps &a)
{
    reverse(a.arr.begin(), a.arr.end());
    return a;
}

This again takes the argument of type stringOps object by reference and directly manipulates the string. However, if I were to pass this argument as a const, how do I go about this?
Motivation for me to do so is that I want to return a manipulated string that is new, and not manipulate the object that is coming in directly.

The header would look something like this:

string stringOps::reverseStr(const stringOps &a)

Do I declare static string inside the function and return it? I tried using a local non-static string (which would be destroyed outside the function, but still for experiment purposes) and I got an error that said:

  read-only variable is not assignable

I'm assuming this is because it's a const reference.


texts:
Hello everyone!
In this task I had to create docstring generator. I'm just wondering how you see this problem, I have to "take data" from the dictionary
{'Args': None, 'Returns': None, 'Raises': None, 'Attributes': None, 'Summary': None, 'Description': None}

and then generate docstring in the correct order.
This is my solution:
import textwrap

def gendoc(config):
    docstring = []
    if ("Summary" in config) and (config["Summary"] is not None):
        docstring.append(config["Summary"])
    if ("Args" in config) and (config["Args"] is not None):
        args = ["Args:"] + [f"\t{arg}: Function argument" for arg in config["Args"]]
        docstring += args
    if ("Attributes" in config) and (config["Attributes"] is not None):
        attr = ["Attributes:"] + [f"\t{attr}: Information about parameter {attr}" for attr in config["Attributes"]]
        docstring += attr
    if ("Raises" in config) and (config["Raises"] is not None):
        raises = ["Raises: "] + [f"\t {config.get('Raises')}"]
        docstring += raises
    if ("Returns" in config) and (config["Returns"] is not None):
        returns = ["Returns: "] + [f"\t {config.get('Returns')}"]
        docstring += returns
    if ("Description" in config) and (config["Description"] is not None):
        value = config.get('Description')
        wrapper=textwrap.TextWrapper(subsequent_indent= '\t', width = 120)
        description = ["Description: "] + [f"\t{wrapper.fill(value)}"]
        docstring += description
    if ("Todo" in config) and (config["Todo"] is not None):
        star = "*"
        todo = ["Todo:"] + [f"\t{star} {todo}" for todo in config["Todo"]]
        docstring += todo

    docstring = "\n\n".join(docstring)
    return docstring

My output:
The Pear object describes the properties of pears.

Args:

    a: Function argument

    b: Function argument

Attributes:

    a: Information about parameter a

    b: Information about parameter b

Raises:

     AttributeError: The ``Raises`` section is a list of all exceptions that are relevant to the interface.

Returns:

     The return value. True for success, False otherwise.

Description:

    The description may span multiple lines. Following lines should be indented. The type is optional. The description may
    span multiple lines. Following lines should be indented. The type is optional.The description may span multiple lines.
    Following lines should be indented. The type is optional.The description may span multiple lines. Following lines
    should be indented. The type is optional.

Todo:

    * Do something

    * Something else

Any tips how to make this SHORTER and more neat, closer to a advanced or just better solution will be definitely on point. Thanks in advance!
Have a great day!


texts:
I've written a small piece of code to measure execution time. As this is my first attempt at something meaningful, I would really like some input on ways to improve my code.

Timer.h

/**
    Purpose: Measuring execution time using chrono.

    @author Rick Regeling
    @version 1.0 2017/01/05
*/

#ifndef TIMER_H
#define TIMER_H

#include <chrono>
#include <iostream>
#include <string>
#include <map>

namespace library {

    // Default unit: std::chrono::milliseconds
    template<typename Unit = std::chrono::milliseconds>
    class Timer {
    public:
        using Clock = std::conditional_t<std::chrono::high_resolution_clock::is_steady,
            std::chrono::high_resolution_clock,
            std::chrono::steady_clock>;

        Timer() = default;
        Timer(const std::string& name) : m_name{ std::move(name) } {}
        ~Timer() {
            m_end = Clock::now();
            output();
        }

        // Disabled operations:
        Timer(const Timer&) = delete;
        Timer(Timer&&) = delete;
        Timer& operator=(const Timer&) = delete;
        Timer& operator=(Timer&&) = delete;
    private:
        /**
            Build a map<const char*, const char*> and find the unit.
            @return The unit name.
        */
        const char* unit_name() {
            const std::map<const char* const, const char*> units{
                { typeid(std::chrono::hours).name(),"h" },
                { typeid(std::chrono::minutes).name(), "m" },
                { typeid(std::chrono::seconds).name(), "s" },
                { typeid(std::chrono::nanoseconds).name(), "ns" },
                { typeid(std::chrono::microseconds).name(), "mms" },
                { typeid(std::chrono::milliseconds).name(), "ms" } };
            auto result = units.find(typeid(Unit).name());
            return result->second;
        }

        /**
            Output the information.
        */
        void output() {
            std::cout << "Elapsed time";
            // Determine if a name is used:
            std::cout << (m_name == "" ? ": " : " (" + m_name + "): ");
            // Calculate the total time and get the unit:
            std::cout << (std::chrono::duration_cast<Unit>
                (m_end - m_start).count()) << unit_name() << '\n';
        }

        // Members:
        const Clock::time_point m_start = Clock::now();
        Clock::time_point m_end{};
        const std::string m_name{};
    };
}
#endif

Example:

#include "Timer.h"
#include <vector>
#include <numeric>

void foo() {
    std::vector<int> v(1'000'000, 42);
    std::accumulate(std::begin(v), std::end(v), 0);
}

int main() {
    // default behavior:
    {
        library::Timer<> timer;
        foo();
    }

    // different unit + description:
    {
        library::Timer<std::chrono::nanoseconds> ex_timer("foo");
        foo();
    }
    return EXIT_SUCCESS;
}


texts: Can someone have a look to my Chess Project?

texts:
I am currently working on an unfinished project about Chess, it will (at some point) be able to help me to make some chess variations just by pasting the FEN position while I play online.

But before continuing, my code must have good structure or it will become a nightmare to fix it later. So now that I have some basics, it would be great to have it reviewed:

//Note: the code uses jQuery

function writeBoard() {
    var i, j, str, bol;

    str = "

";
    for (i = 9; --i;) {
        str += "
";
        for (j = 0; j < 8; j++) {
            bol = !bol;
            str += "	";
        }
        bol = !bol;
        str += "
";
    }
    str += "

";

    $("body").append(str);
}

function setFEN(fen) {
    var i, j, len, arr, tmp, tmp2, tmp3;

    arr = (fen ? fen : DefaultFen).split(" ")[0].split("/");
    for (i = 0; i < 8; i++) {
        tmp = i * 8;
        for (j = 0, len = arr[i].length; j < len; j++) {
            tmp2 = arr[i].charAt(j);
            if (tmp2 * 1) {
                tmp += tmp2 * 1;
            } else {
                tmp3 = tmp2.toLowerCase();
                ChessBoard[i][tmp % 8] = PiecesNames.indexOf(tmp3) * (tmp2 != tmp3 ? 1 : -1);
                tmp++;
            }
        }
    }

    refreshBoard();
}

function refreshBoard() {
    var i, j, emt, fen, tmp, tmp2, tmp3, tmp4;

    fen = "";
    for (i = 9; --i;) {
        emt = 0;
        for (j = 0; j < 8; j++) {
            tmp = Math.abs(i - 8);
            tmp2 = ChessBoard[tmp][j] || 0;
            if (tmp2) {
                if (emt) {
                    fen += "" + emt;
                    emt = 0;
                }

                tmp3 = $("#" + AbcLabels[j] + "" + i);
                if (tmp2 < 0) {
                    tmp4 = PiecesNames.charAt(tmp2 * -1);
                    tmp3.addClass("b" + tmp4);
                    fen += tmp4;
                } else {
                    tmp4 = PiecesNames.charAt(tmp2);
                    tmp3.addClass("w" + tmp4);
                    fen += tmp4.toUpperCase();
                }
            } else {
                emt++;
            }
        }

        if (emt) {
            fen += "" + emt;
        }
        fen += "/";
    }

    console.log(fen); //remove the last "/"
    //fen+= can enPass, to move, castle Avility, clock, etc...
    //Fen=fen
}

var I, J, Len;
var AbcLabels = ["a", "b", "c", "d", "e", "f", "g", "h"];
var PiecesNames = "*pnbrqk"; //[wp:1][wn:2][wb:3][wr:4][wq:5][wk:6]***[bp:-1][bn:-2][bb:-3][br:-4][bq:-5][bk:-6]
var DefaultFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -";
var ChessBoard = new Array(8);
for (I = 8; I--;) {
    ChessBoard[I] = new Array(8);
}
var Fen;
var ToMove; //[0:white][1:black]
var WCastling, BCastling; //[0:none][1:short][2:long][3:both]
//var IsCheck,EnPassant;

$(function() {
    writeBoard();
    setFEN("5Rk1/1b2p2p/p2pP1p1/2rP4/2BQ2P1/6qP/PP6/1K6 b - -");
});

If you don't have a good text editor, you will find tmpX variables very hard to recognize one over the another... In my case, I just double click and they all get highlighted (using Notepad++).


texts: Is this the best way to collapse a column width?

texts:
Requirements:
When the page (or in the case of the example Frame) expands, the only column to expand with the table should be 'unfrozen' columns (without the 'freeze' class).

here is the live demo The jQuery is there to show dynamic content, it is not the code under review

What I really don't like is that is seems to hacky to just set the width of the column to 1px... I can forsee this causing issues with older/junkier browsers.

HTML

            id
            name
            description
            something else
            actions

CSS

.data-table {
    width: 100%;
    font-size: 90%;
    background-color: #fff;
    border: 1px solid #666;
}
.data-table th {
    white-space: nowrap;
    text-align: center;
}
.data-table td {
    font-size: 90%;
    color: #222;
}
.data-table td:last-child {
    white-space: nowrap;
}
.data-table td, .data-table th {
    padding: 6px;
    border-right: 1px solid #999;
}
.data-table td:last-child, .data-table th:last-child {
    border: none;
}
.data-table tbody tr {
    border: 1px solid #666;
}
.data-table tbody tr:nth-child(odd) td {
    background-color: #efefef;
}
.freeze {
    width: 1px;
}

This works in at least IE8, Chrome 16, and FF8


texts: Is there a more elegant way to catch a generic exception than using try-catch block?

texts:
Here are two sample blocks of my code:

function FindTheNumberOfAddedItems ( PageObj, ItemType )
{
    var localPageObj = PageObj;
    var localItemType = ItemType;
    var numberOfAddedItems = 0;
    var NROCssSelector  = "div[class='assessment-stub list-top-border-colour-1 clearfix box-shadow'] strong";
    var OROCssSelector  = "div[class='assessment-stub list-top-border-colour-2 clearfix box-shadow'] strong";
    var RCCssSelector  = "div[class='assessment-stub list-top-border-colour-3 clearfix box-shadow'] strong";

    try {
        switch (localItemType)
        {
            case "NRO":
                numberOfAddedItems = ParseNumberOutOfString(localPageObj.QuerySelector(NROCssSelector).innerText);
                break;
            case "ORO":
                numberOfAddedItems = ParseNumberOutOfString(localPageObj.QuerySelector(OROCssSelector).innerText);
                break;
            case "RC":
                numberOfAddedItems = ParseNumberOutOfString(localPageObj.QuerySelector(RCCssSelector).innerText);
                break;
            default:
                Log.Message("Invalid item type");
        }
    }
    catch (err){
        Log.Message("Can not find then number of added items.");
    }
    return numberOfAddedItems;
}

function ParseNumberOutOfString ( TextString )
{
    var localTextString = TextString;
    var numberOnlyRegexPattern = /\d+/g;

    try {
        return localTextString.match(numberOnlyRegexPattern);
    }
    catch (err){
        Log.Message("Can not parse number out of string.");
    }
}

I have used try-catch blocks for both functions (and for the rest of all of my functions) in case there is anything wrong with my code.

Come to think about it, having try-catch blocks everywhere is kind of messy. Is there another more elegant way to do it?


texts:
Here is my Python implementation of a simple fractions class:

class frac:
    def __init__(self, a,b):
        self.a = a
        self.b = b

    def __add__(self, x):
        return frac(self.a*x.b + self.b*x.a, self.b*x.b)

    def __mul__(self, x):
        return frac(self.a*x.a, self.b*x.b)

    def __sub__(self, x):
        return frac(self.a*x.b - self.b*x.a, self.b*x.b)

    def __div__(self, x):
        return frac(self.a*x.b, self.b*x.a)

    def __repr__(self):
        return "%s/%s"%(self.a,self.b)

It does addition OK:

x = frac(1,3)
y = frac(1,2)
print x+ y

>> 5/6

However, it can miss the mark:

x = frac(1,3)
y = frac(2,3)
print x+ y

>> 9/9

It seems if I run this library enough, the numerators and denominators will get very large.  When should I start simplifying and where should I put that code?

There seems to be a fractions class already in Python, it this was instructive to put together.

My original goal was to allow for square roots of integers as well, but I will ask this in a separate question.


texts: Returning the common divisors of two integers

texts:
I have written this function that returns the common divisors of two integers. When called recursively 10 times with big integers ranging in 100000000, it takes over 5 seconds. How can I improve it so that it is faster (less than 5 seconds)?

commonDivisors :: Int -> Int -> [Int]
commonDivisors x y = if x > y then divisors y x else divisors x y
    where divisors :: Int -> Int -> [Int]
          divisors z n = filter (\x -> n `mod` x == 0 && z `mod` x ==0) [1..n]


texts: Is `if( hidden ) return;` an antipattern?

texts:
Sometimes, when you're doing something like displaying a bunch of elements, you can avoid running a function entirely if an object is hidden.

So you can either write the check from the loop:

for( Displayable * d : displayables )
    if( d->isShowing() )
        d->draw() ;

Or you can put an "early return" in d->draw() if d is hidden:

void Displayable::draw()
{
    if( !isShowing() )  return ;
    // continue with draw..
}

With this 2nd way, you don't have to check any condition when looping, so the loop "looks cleaner"

for( Displayable * d : displayables )
    d->draw() ;

But with the 1st way, you don't have to check isShowing() at the beginning of the function, so then that looks cleaner,

void Displayable::draw()
{
    // simply draw
}

Which is better?  Is the latter an antipattern of sorts?


texts:
This is my implementation of Clojure's assoc-in function.  I am looking for tips on making it more idiomatic and in general, better.

(defn my-assoc-in
  [m [& ks] v]
  (let [sorted-keys (reverse ks)]
    (loop [curr-key (first sorted-keys)
           rem-keys (rest sorted-keys)
           curr-map (get-in m (reverse rem-keys))
           acc-val  (assoc curr-map curr-key v)]
      (if (empty? rem-keys)
        acc-val
        (let [next-key (first rem-keys)
              next-rem (rest rem-keys)
              next-map (get-in m next-rem)
              next-val (assoc next-map next-key acc-val)]
          (recur next-key next-rem next-map next-val))))))


texts: Compile time positive and negative powers of two

texts:
I'm getting started on template meta-programming and I wrote a template to compute compile-time positive and negative float powers of 2. I would like some feedback on readability and overall code complexity as I feel like I might be defining too many structures for such a simple computation. The code has to be C++98 compatible.

// Sign of an integer
template<bool b> struct SIGN {static const int value = ( b * 2 ) - 1; };

// Positive powers of two (fast exponentiation)
template<unsigned int N> struct POW2_POS {
    static const float value =
      POW2_POS<N%2>::value
    * POW2_POS<N/2>::value
    * POW2_POS<N/2>::value;
};
template<> struct POW2_POS <1> { static const float value = 2.0f; };
template<> struct POW2_POS <0> { static const float value = 1.0f; };

// Negative powers of two
template<unsigned int N> struct POW2_NEG {static const float value = 1.0f / POW2_POS<N>::value; };

// Calls POW2_POS or POW2_NEG depending on boolean parameter
template<bool b, unsigned int N> struct POW2_SIGNED;
template<unsigned int N> struct POW2_SIGNED<true, N> { static const float value = POW2_POS<N>::value;};
template<unsigned int N> struct POW2_SIGNED<false, N> { static const float value = POW2_NEG<N>::value;};

// Integer power of two
template<int N> struct POW2 {
    static const float value = POW2_SIGNED<(N>=0), SIGN<(N>=0)>::value * N>::value;
};

Example program

#include <iostream>
int main()
{
    std::cout<<POW2<0>::value <<"\n";
    std::cout<<POW2<1>::value <<"\n";
    std::cout<<POW2<4>::value <<"\n";
    std::cout<<POW2<7>::value <<"\n";
    std::cout<<POW2<-4>::value <<"\n";
}

Output

1
2
16
128
0.0625


texts: JavaScript library to notify watchers of changes

texts:
Background

Last year, while I was still entering the beginning of Immutability and Pure functions and whatnot I created a library for the community called obj-watcher.

This library is extremely simple - it allows you to register an object, and to get notified when changed happen to this object via a given API.

Problem

Everything was fine at first.  I got the maximum score for everything and then one day ...  CodeClimate changed the way they evaluate code and they rated my project as a C.

This is not good. According to them, my project is hard to maintain because it has a high cognitive load. I find that hard to believe, but I am totally biased.

What do I want?

The full code is commented via jsdoc and I know I could probably improve some functions. But I what I would really like is some feedback on my code. I would like to know if it is really that hard for someone else to understand ( PS,  removed the comments ):

const isFunction = require("lodash.isfunction");

const errors = require("./errors.js");
const callbackNotAFunction = errors.callbackNotAFunction;
const objectAlreadyWatched = errors.objectAlreadyWatched;
const objectNotWatched = errors.objectNotWatched;

const watcherFactory = () => {

    const watchMap = new Map();

    const watch = (objId, obj) => {
        if (isObjWatched(objId))
            throw objectAlreadyWatched(objId);

        watchMap.set(objId, {
            obj: obj,

            onChange: () => {}
        });
    };

    const unwatch = objId => {
        if (!isObjWatched(objId))
            throw objectNotWatched(objId);
        watchMap.delete(objId);
    };

    const get = objId => {
        if (!isObjWatched(objId))
            throw objectNotWatched(objId);
        return Object.assign({}, watchMap.get(objId).obj);
    };

    const set = (objId, newObj) => {
        if (!isObjWatched(objId))
            throw objectNotWatched(objId);

        const entry = watchMap.get(objId);
        const oldObj = Object.assign({}, entry.obj);
        entry.obj = Object.assign({}, newObj);
        entry.onChange(oldObj, entry.obj);
    };

    const onChange = (objId, callback) => {
        if (!isObjWatched(objId))
            throw objectNotWatched(objId);

        if (!isFunction(callback))
            throw callbackNotAFunction(objId);

        const entry = watchMap.get(objId);
        entry.onChange = callback;
    };

    const reset = () => {
        watchMap.clear();
    };

    const isObjWatched = objName => watchMap.has(objName);

    return Object.freeze({
        watch,
        unwatch,
        onChange,
        get,
        set,
        reset
    });
};

module.exports = watcherFactory();

CodeClimate states this code is hard due to 2 reasons:

Function watcherFactory has 47 lines of code (exceeds 25 allowed). Consider refactoring.
Function watcherFactory has a Cognitive Complexity of 12 (exceeds 5 allowed). Consider refactoring.

Here I am using the well established object factory pattern from Douglas Crockford where I have a function that creates and returns an object with methods.

This function has everything inside and is a standard way of defining public and private variables via means of closures and encapsulation.

However, after reading CodeClimate's article on cognitive complexity ( which I also recommend ):

https://docs.codeclimate.com/docs/cognitive-complexity

I think their system has an issue with factory functions because it seems them as normal function that is far too big. In a way, their system does kinda have a point... I wonder if there is a way I can refactor this to make it more obvious and win both battles.

What do you think?


texts: Lookup closest value in Pandas DataFrame


texts:
I would like to ask someone if the code i will put here is Secured for SQL injection and my password hashing and checking while user is logging in is secure and done well.

My Database connection :

$hostname='localhost';
$username='root';
$password='';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=myshop",$username,$password);
    $dbh->query ('SET NAMES utf8');
    $dbh->query ('SET CHARACTER_SET utf8_unicode_ci');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
} catch (PDOException $e) {
      echo $e->getMessage();
    }

My registration script :

include_once 'config.php';

$data = file_get_contents("php://input");
$data = json_decode($data, true);

try {
    $stmt = $dbh->prepare("INSERT INTO `accounts` (`account_id`, `firstname`, `lastname`, `username`, `password`, `email`, `city`, `postalcode`, `adress`, `country`, `role`)
      VALUES (NULL, :firstname, :lastname, :username, :password, :email, :city, :postalcode, :adress, :country, 0) ");
    $stmt->bindParam(':firstname', $data['firstname']);
    $stmt->bindParam(':lastname', $data['lastname']);
    $stmt->bindParam(':username', $data['username']);
    $stmt->bindParam(':password', password_hash($data['password'], PASSWORD_DEFAULT));
    $stmt->bindParam(':email', $data['email']);
    $stmt->bindParam(':city', $data['city']);
    $stmt->bindParam(':postalcode', $data['postalcode']);
    $stmt->bindParam(':adress', $data['adress']);
    $stmt->bindParam(':country', $data['country']);
    $stmt->execute();
  } catch (PDOException $e) {
      if (strpos($e->getMessage(), "for key 'login'") !== false) {
          echo 'Duplicate login entry';
          exit;
      } if (strpos($e->getMessage(), "for key 'email'") !== false) {
          echo 'Duplicate e-mail entry';
          exit;
      }
      else {
          throw $e;
      }
  }
  echo 'Success';

My login script :

include_once 'config.php';

$data = file_get_contents("php://input");
$data = json_decode($data, true);

try {
  $stmt = $dbh->prepare("SELECT * from accounts WHERE
    username=:username");
  $stmt->bindParam(':username', $data['username']);
  $stmt->execute();
  } catch (PDOException $e) {
          throw $e;
      }

  $rows = $stmt->rowCount();
  $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
  $json = json_encode($result);

  if ($rows === 1){
    if (password_verify($data['password'], $result[0]['password'])) {
      echo $json;
      exit;
    }
    else{
      echo 'Wrong password';
      exit;
    }}
  if ($rows === 0) {
    echo 'No account';
    exit;
  }
  else {
    echo 'Something went wrong';
    exit;


texts:
Problem

Given a square matrix of size N×N, calculate the absolute difference between the sums of its diagonals.

Input Format

The first line contains a single integer, N. The next N lines denote the matrix's rows, with each line containing N space-separated integers describing the columns.

Output Format

Print the absolute difference between the two sums of the matrix's diagonals as a single integer.

Sample Input

3
11 2 4
4 5 6
10 8 -12

Sample Output

15

Code

(ns hackerrank.core
  [:require [clojure.string :as s]])

(defn get-diagonal-sums-reducer
  [n]
  (fn
    [sums [line-number line]]
    (let
      [primary (nth line line-number)
       secondary (nth line (- n (+ 1 line-number)))]
      (assoc
        sums
        :primary (+ primary (:primary sums))
        :secondary (+ secondary (:secondary sums))))))

(let
  [n (Integer/parseInt (read-line))
   matrix (for
            [_ (range n)]
            (mapv #(Integer/parseInt %) (s/split (read-line) #"\s+")))
   matrix-enumerated (map-indexed vector matrix)
   sums (reduce
          (get-diagonal-sums-reducer n)
          {:primary 0 :secondary 0}
          matrix-enumerated)
   difference (- (:primary sums) (:secondary sums))]
  (println (max difference (- difference))))

Couple questions in particular:

can I avoid the get-diagonal-sums-reducer somehow? I'm only using it so that it closes over n.
am I doing this as lazily as possible or is there any place I'm using vectors when seqs would have worked?
is there a much less verbose way to do this? Doesn't feel like this would be as complicated in Python.


texts:
This is a metaclass for facilitating the concept of "inner classes" (as opposed to simple nested classes) in Python. I define an inner class as a nested class that expects an instance of the outer class as
the first argument to __new__ and __init__.
This metaclass implements the
descriptor protocol (non-data) for the inner class, such that calling the inner
class through an attribute access on an instance of the outer class will
automatically pass the latter as the first argument to the constructor of the
inner class.
Example:
class Car:
    class Motor(metaclass=InnerClassMeta):
        def __init__(self, car: "Car"):
            self.car = car

>>> car = Car()
>>> motor = car.Motor()
>>> motor.car is car
True

This is similar to Java's inner classes.
I'm mainly concerned with correctness, consistent behaviour, and maintainability. Note: this doesn't attempt to discriminate from which class it is being accessed,
i.e. it doesn't attempt to validate that it is being accessed from the outer class
in which it was defined (if any).
Code:
class InnerClassMeta(type):
    """Metaclass for inner classes."""

    class BoundInnerClass:
        def __init__(self, inner_class, outer_instance):
            self.inner_class = inner_class
            self.outer_instance = outer_instance

        def __repr__(self):
            return (
                f"<bound inner class {self.inner_class.__name__}"
                f" of {self.outer_instance}>"
            )

        def __call__(self, *args, **kwargs):
            return self.inner_class(self.outer_instance, *args, **kwargs)

    def __get__(cls, instance, owner):
        if instance is None:
            return cls  # don't bind to classes, just instances
        return InnerClassMeta.BoundInnerClass(cls, instance)


texts: Project Euler # 22 names scores in Python

texts:
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand
first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for
    each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth \$3 + 15 + 12 + 9 + 14 = 53\$,
is the 938th name in the list. So, COLIN would obtain a score of \$938 × 53 = 49714\$.

What is the total of all the name scores in the file?

import string

def calculate_score(filename):
    """Reads names and returns total scores."""
    letter_scores = {letter: ord(letter) - 64 for letter in string.ascii_uppercase}
    with open(filename) as names:
        total = 0
        names = sorted(names.read().replace('"', '').split(','))
        for index, name in enumerate(names):
            temp = 0
            for letter in name:
                temp += letter_scores[letter]
            total += temp * (index + 1)
        return total

if __name__ == '__main__':
    print(calculate_score('p022_names.txt'))


texts: Unit Testing of parser method using pytest

texts:
This is my first time using pytest. All feedback for this test case is much appreciated.

import pytest
from mock import mock_open, patch

def get_file_contents(file_data):
  with patch.object('builtins.open', mock_open(read_data=file_data)) as mock:
    with open('mocked_file') as f:
      return (line for line in f.readlines())

@pytest.fixture(scope="module")
def text_parser(request):
  from tparse import TextParser
  file_data = getattr(request.module, 'file_contents')
  tparse = TextParser(file_data)
  def fin():
    tparse.close()
  request.addfinalizer(fin)
  return tparse

def test_get_system_entry(self):
  file_data = 'dc nyc server server001 ipaddress 10.10.10.10'
  file_iterable = get_file_contents(file_data)
  assert file_iterable == file_data


texts:
I made a simple simulation of a falling ball. Is it possible to somehow improve or optimize this code? What tips can you give for development?
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;

int timeFallingBall() {
    static int time(0);
    return ++time;
}
void fallingBall() {
    cout << "From what height do we drop the ball? (In meters): ";
    double h;
    cin >> h;
    double v = 0, high = 0, s = 0, maxv = 0, g = 9.8;
    int t = 0;
    double hi = h;
    while (h) {
        t = timeFallingBall();
        v = static_cast<double>(t) * g;
        high = (v * static_cast<double>(t)) / 2;
        h = hi - high;
        if (h <= 0) {
            switch (t) {
            case 1:
                cout << "After " << t << " second the ball has reached the ground! Maximum speed: " << maxv << " m/s";
                break;
            default:
                cout << "After " << t << " seconds the ball has reached the ground! Maximum speed: " << maxv << " m/s";
            }
            break;
        }
        switch (t) {
        case 1:
            cout << "After " << t << " second, the ball is at a distance of " << h << " m from the ground at a speed: " << v << " m/s" << endl;
            break;
        default:
            cout << "After " << t << " seconds, the ball is at a distance of " << h << " m from the ground at a speed: " << v << " m/s" << endl;
            break;
        }
        if (v > maxv) {
            maxv = v;
        }
    }
}
int main() {
    system("chcp 1251>nul");
    fallingBall();
    return 0;
}


texts:
I've built an image/content slider using JavaScript and as I've added to it and built in new functionality I've found myself writing several if statements in order to achieve the required response.

I'm now going over it again and I want to refactor it to make it shorter (if possible) and to increase performance (again if possible).

Has anyone any ideas on how I can refactor this? I'm thinking along the line of switch statements, but I'm not sure if that's the right route to go down or whether it would actually improve anything.

/*
 * animate margin left and store current position
 */

slider.prototype.transition = function (position, offset) {
    //'use strict';

    this.position = position;

    this.offset = offset;
    // update new slide position if deeplinking

    this.slide_pos = parseInt(this.position) || this.slide_pos;

    //check slide no exists in dl_urls object
    //this.deep_link_slide_no in window ? this.deep_link_slide_no = 0 : this.deep_link_slide_no = deep_link_slide_no;
    if (window.hasOwnProperty(this.deep_link_slide_no)) {
        this.deep_link_slide_no = 0;
    } else {
        this.deep_link_slide_no = position;
    }

    if(this.position === 0 || this.slide_pos === 0) {

        if(supportCSSTransitions && this.options.hardware_accelerated) {

          if(this.options.centered) {
            this.container.css({
              'margin-left': - (0.5 * this.slideWidth),
              transition :  'margin 0.8s ease'
            });
          } else {
            this.container.css({
              'margin-left': this.offset || 0,
              transition :  'margin 0.8s ease'
            });
          }
        } else {

          if(this.options.centered) {
            this.container.velocity({
              'margin-left': - (0.5 * this.slideWidth),
            }, {
                duration: this.options.slide_delay,
                easing: this.options.easing
            });
          } else {
            this.container.velocity({
              'margin-left': this.offset || 0,
            }, {
                duration: this.options.slide_delay,
                easing: this.options.easing
            });
          }
        }

        this.slide_pos = 0;

    } else {

      if(supportCSSTransitions && this.options.hardware_accelerated) {
        //console.log ("css and hardware");

        if(this.options.centered) {

          this.container.css({
            'margin-left': - (this.slide_pos * this.slideWidth) - (0.5 * this.slideWidth),
            transition :  'margin 0.8s ease'
          });

        } else if (typeof this.offset != "undefined") {
          this.container.css({
              'margin-left': (((this.slide_pos * this.slideWidth) * -1) + this.offset),
              transition : 'margin 0.8s ease'
          });
        } else {
          this.container.css({
              'margin-left': ((this.slide_pos * this.slideWidth * -1)) || (this.current_margin + this.direction),
              transition : 'margin 0.8s ease'
          });
        }

      } else {

        if(this.options.centered) {
          this.container.velocity({
            'margin-left': - (this.slide_pos * this.slideWidth) - (0.5 * this.slideWidth),
          });
        } else if (typeof this.offset != "undefined") {
          this.container.velocity({
              'margin-left': (((this.slide_pos * this.slideWidth) * -1) + this.offset)
          });
        } else {
          this.container.velocity({
              'margin-left': ((this.slide_pos * this.slideWidth * -1)) || (this.current_margin + this.direction)
          });
        }
      }
    }

    // store and update margin each time
    this.current_margin = (this.current_margin + this.direction);

    // set button state
    this.set_button_state();

    // set active states
    this.set_active_states();
};


texts: Generic EventArgs to go with generic EventHandler?

texts:
There is as of .NET 2.0 a generic EventHandler delegate type, which can be used to define an event in terms of the EventArgs type you wish to use, without having to create a redundant delegate type to use in the event declaration.

Well, what about the EventArgs? I often find myself having to create one-offs derived from EventArgs to encapsulate extra data I wish to send. Why can't that be declared generically as well? If all I need to pass is a string, or an integer, or a Point, why do I have to create a StringEventArgs, IntEventArgs and/or PointEventArgs class respectively?

I roughed up two very basic EventArgs generic types as a proof-of-concept:

public class ReadOnlyEventArgs<T>:EventArgs
{
    public T Parameter { get; private set; }

    public ReadOnlyEventArgs(T input)
    {
        Parameter = input;
    }
}

public class EventArgs<T>:EventArgs
{
    public T Parameter { get; set; }

    public EventArgs(T input)
    {
        Parameter = input;
    }
}

The obvious difference is whether you want event handlers to be able to modify your arguments. Sometimes it's a good idea, most of the time not so good. Usage would simply look like:

public event EventHandler<EventArgs<string>> StringValidationRequested;
public event EventHandler<ReadOnlyEventArgs<int>> RecordSelectedForRetrieval;
public event EventHandler<ReadOnlyEventArgs<Point>> MouseLocationReported;

Now, obviously these are for simpler situations, but I've found most situations of event raising to be pretty simple. The only possible thing I'd add would be two more classes derived from CancelEventArgs to add that additional functionality. The fact that the Parameter can be anything including a class makes it flexible enough to pass complex data, and .NET 4's Tuples take care of the remaining situations where you might not want to define your own complex type. The only drawback I can think of is not being able to descriptively name your parameter; it's generic.


texts:
Spoilers!!
    (duh..)

This code manipulates two HTML number input controls and multiplies them.

I am trying my luck on implementing MVC in JavaScript by example. This is a very minimal and useless code! What I am doing is achievable directly; by listening to the "change" or "input" event number-input fires. And here I am bloating code in order to learn. What a waste of time, ours, combined.

Anyway, here I am and here you are:
gist | jsfiddle

function Event() {
  this.listeners = []
}

Event.prototype = {
  attach: function(listener) {
    this.listeners.push(listener)
  },
  notify: function(args) {
    this.listeners.forEach(function(l) {
      l(args)
    })
  }
}

function Model(numberValue, timesValue) {
  this.numberValue = numberValue
  this.timesValue = timesValue
  this.numberUpdated = new Event()
  this.timesUpdated = new Event()
  var self = this
  this.changeNumber = function(number) {
    self.numberValue = number
    self.numberUpdated.notify()
  }
  this.changeTimes = function(times) {
    self.timesValue = times
    self.timesUpdated.notify()
  }
  this.getNumber = function() {
    return self.numberValue
  }
  this.getTimes = function() {
    return self.timesValue
  }
}

function View(model, elements) {
  this.model = model
  this.elements = elements
  this.numberChanged = new Event()
  this.timesChanged = new Event()
  var self = this
  this.model.numberUpdated.attach(function() {
    self.recalculate()
  })
  this.model.timesUpdated.attach(function() {
    self.recalculate()
  })
  this.elements.number.addEventListener('input', function() {
    self.numberChanged.notify({
      value: self.elements.number.value
    })
  })
  this.elements.times.addEventListener('input', function() {
    self.timesChanged.notify({
      value: self.elements.times.value
    })
  })
  this.recalculate = function() {
    self.elements.result.innerHTML = self.model.getNumber() * self.model.getTimes()
  }
  this.show = function() {
    self.elements.number.value = self.model.getNumber()
    self.elements.times.value = self.model.getTimes()
    self.recalculate()
  }
}

function Controller(model, view) {
  this.model = model
  this.view = view
  var self = this
  this.view.numberChanged.attach(function() {
    self.model.changeNumber(self.view.elements.number.value)
  })
  this.view.timesChanged.attach(function() {
    self.model.changeTimes(self.view.elements.times.value)
  })
}

function run() {
  var number = document.getElementById('number')
  var times = document.getElementById('times')
  var result = document.getElementById('result')
  var model = new Model(9, 0.987654321)
  var elements = {
    number: number,
    times: times,
    result: result
  }
  var view = new View(model, elements)
  var controller = new Controller(model, view)
  view.show()
}

run()
#result,
input[type="number"] {
  padding: 4px;
  font-size: 16px;
  background-color: transparent;
  border: none;
  text-align: center;
  display: inline-block;
}

  Try changing the numbers. Use buttons. OR you know what, enter a number.

<input type="number" id="number" value="3">*
<input type="number" id="times" value="3">=

As of right now, I am very happy that I got this working. It's an achievement for me. Really! And I know this code is bad, somehow; I cannot shake the feeling. (cue Max Payne music)

I knew it when I started writing code, I knew it in my gut that something was off; I was tired, I could have stopped, I didn't. I had to find out what will be wrong with the code.

What is this code missing? What makes it less of an MVC implementation?


texts: Generating and printing chess board in Rust

texts:
This is the beginning of a chess program I'm writing in Rust.  I'm new to Rust, so while this program works, I'm sure there are many improvements that could be made.  For instance, I wanted to declare the squares variable as a fixed sized array of 64 square structs, rather than using a vector, but I couldn't get that to work, I think because I'm using a trait object.

First is the code within lib.rs.

mod piece;

use std::fmt;
use piece::*;

struct Square {
    piece: Option<Box<Piece>>
}

impl Square {
    pub fn new() -> Square {
        Square { piece: None }
    }

    fn symbol(&self) -> &str {
        match self.piece {
            Some(ref p) => p.symbol(),
            None => "."
        }
    }
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.symbol())
    }
}

pub struct Board {
    squares: Vec<Square>
}

impl Board {
    pub fn new() -> Board {
        let mut squares: Vec<Square> = Vec::new();
        let p = vec![(0, 1), (7, 6)];

        for _ in 0..64 { squares.push(Square::new()); }

        for pos in p {
            squares[pos.0 * 8 + 0].piece = Some(Box::new(Rook {}));
            squares[pos.0 * 8 + 1].piece = Some(Box::new(Knight {}));
            squares[pos.0 * 8 + 2].piece = Some(Box::new(Bishop {}));
            squares[pos.0 * 8 + 3].piece = Some(Box::new(Queen {}));
            squares[pos.0 * 8 + 4].piece = Some(Box::new(King {}));
            squares[pos.0 * 8 + 5].piece = Some(Box::new(Bishop {}));
            squares[pos.0 * 8 + 6].piece = Some(Box::new(Knight {}));
            squares[pos.0 * 8 + 7].piece = Some(Box::new(Rook {}));

            for i in (pos.1 * 8)..(pos.1 * 8 + 8) {
                squares[i].piece = Some(Box::new(Pawn { en_passant: false }))
            }
        }

        Board {
            squares: squares
        }
    }

    pub fn valid_moves() {

    }
}

impl fmt::Display for Board {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut res = String::new();
        for i in 0..8 {
            for j in 0..8 {
                res.push_str(self.squares[(i * 8) + j].symbol());
            }
            res.push_str("\n");
        }
        write!(f, "{}", res)
    }
}

Here is the code that defines the pieces (not much to this yet).

pub trait Piece {
    fn symbol(&self) -> &str;
    fn valid_moves(&self);
}

pub struct King;
impl Piece for King {
    fn symbol(&self) -> &str {
        "K"
    }

    fn valid_moves(&self) {

    }
}

pub struct Queen;
impl Piece for Queen {
    fn symbol(&self) -> &str {
        "Q"
    }

    fn valid_moves(&self) {

    }
}

pub struct Rook;
impl Piece for Rook {
    fn symbol(&self) -> &str {
        "R"
    }

    fn valid_moves(&self) {

    }
}

pub struct Bishop;
impl Piece for Bishop {
    fn symbol(&self) -> &str {
        "B"
    }

    fn valid_moves(&self) {

    }
}

pub struct Knight;
impl Piece for Knight {
    fn symbol(&self) -> &str {
        "k"
    }

    fn valid_moves(&self) {

    }
}

pub struct Pawn { pub en_passant: bool }
impl Piece for Pawn {
    fn symbol(&self) -> &str {
        "p"
    }

    fn valid_moves(&self) {

    }
}

I'd love to know if there are ways I could improve on this.


texts:
I have been trying my hand at Python lately. I have been able to look at code examples and create a custom application that queries a Microsoft SQL Server, pulls out two columns (date, balance) and charts them using pyplot embedded in tkinter for future development.

Because of the "chop and change" nature in which I wrote the code, I know there are plenty of bad practices and am looking for some constructive advice!
(I have removed the SQL script as it is huge)

import pymssql
import getpass
import matplotlib

matplotlib.rcParams['toolbar'] = 'None'
matplotlib.use('TkAgg')

import numpy as np
import tkinter as Tk
import matplotlib.dates as mdates
from matplotlib.figure import Figure

from matplotlib.ticker import FuncFormatter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def movingaverage(dvalues,window):
    weights = np.repeat(1.00,window)/window
    values = [float(val) for val in dvalues]
    sma = np.convolve(values, weights, 'valid')
    return sma

root = Tk.Tk()
root.wm_title("Daily balance tracker")

f = Figure(figsize=(10, 7), dpi=75)
a = f.add_subplot(111)

server = "RHYSPC"
user = "rhys"
password = getpass.getpass("Please enter password: ")
print("Loading results, please wait...")

conn = pymssql.connect(server, user, password, "RhysACC")

cursor = conn.cursor()

cursor.execute("""
SELECT Date, Balance FROM Example -- Not the actual query!
""")

results = cursor.fetchall()

x = [i[0] for i in results]
y = [i[1] for i in results]

yMA = movingaverage(y,31)

j = [0] * len(x)

conn.close()

def pounds(x, pos):
    return '£%1.0d' % x

formatter = FuncFormatter(pounds)

f.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%Y'))
f.gca().xaxis.set_major_locator(mdates.YearLocator())
f.gca().yaxis.set_major_formatter(formatter)

a.plot(x, j, color='k', linewidth=2.0)
a.plot(x, y, color='b', linewidth=1.0)
a.plot(x[len(x)-len(yMA):], yMA, color='r', linewidth=1.5)

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()

canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

Tk.mainloop()


texts:
My goal is to move a 'monster' (mX, mY) in a 2d grid towards the player (pX, pY). The monster can move 8 directions.

I have working code for this, but I'm very new to Python and have a strong inclination it is awful and there is faster ways to do it.

I do this by creating a 3 x 3 array around the monsters position (array slot 4), and filling it with the distance from that array position to the player. Then I check if any are lower than the monsters current distance, and if so, move the monster to it.

Here is my current code, apologies if it makes you puke, I'm still learning the ropes.

# get the distance between the monster and player
dist = math.hypot(pX - mX, pY - mY)

if dist > 1.5 and dist < 10:

    # make an 'array' grid to store updated distances in
    goto = np.full((3, 3), 10, dtype=float)

    # if each position in the array passes a
    # collision check, add each new distance

    if collisionCheck(mID, (mX-1), (mY-1), mMap) == 0:
        goto[0][0] = round(math.hypot(pX - (mX-1), pY - (mY-1)), 1)

    if collisionCheck(mID, mX, (mY-1), mMap) == 0:
        goto[0][1] = round(math.hypot(pX - mX, pY - (mY-1)), 1)

    if collisionCheck(mID, (mX+1), (mY-1), mMap) == 0:
        goto[0][2] = round(math.hypot(pX - (mX+1), pY - (mY-1)), 1)

    if collisionCheck(mID, (mX-1), mY, mMap) == 0:
        goto[1][0] = round(math.hypot(pX - (mX-1), pY - mY), 1)

    # goto[1][1] is skipped since that is the monsters current position

    if collisionCheck(mID, (mX+1), mY, mMap) == 0:
        goto[1][2] = round(math.hypot(pX - (mX+1), pY - mY), 1)

    if collisionCheck(mID, (mX-1), (mY+1), mMap) == 0:
        goto[2][0] = round(math.hypot(pX - (mX-1), pY - (mY+1)), 1)

    if collisionCheck(mID, mX, (mY+1), mMap) == 0:
        goto[2][1] = round(math.hypot(pX - mX, pY - (mY+1)), 1)

    if collisionCheck(mID, (mX+1), (mY+1), mMap) == 0:
        goto[2][2] = round(math.hypot(pX - (mX+1), pY - (mY+1)), 1)

    # get the lowest distance, and its key
    lowest = goto.min()
    lowestKey = goto.argmin()

    # if the lowest distance is lower than monsters current position, move

    if lowest < dist:
            if lowestKey == 0:
                    newX = mX - 1
                    newY = mY - 1

            if lowestKey == 1:
                    newY = mY - 1

            if lowestKey == 2:
                    newX = mX + 1
                    newY = mY - 1

            if lowestKey == 3:
                    newX = mX - 1

            if lowestKey == 5:
                    newX = mX + 1

            if lowestKey == 6:
                    newY = mY + 1
                    newX = mX - 1

            if lowestKey == 7:
                    newY = mY + 1

            if lowestKey == 8:
                    newX = mX + 1
                    newY = mY + 1

What is the cleanest, simplest, and fastest way to do what I'm doing? This is going to loop through many monsters at once!


texts: Handling shared state among a lot of elements in Angular

texts:
I am working on a project in Angular where I have a number of similar data objects. When you click on anyone of them it's state and amount of data shown will change. All of the objects start in the minimal state, when you click on one it becomes medium. From a medium you can click on the button to go to maximum or click anywhere else on it to go back down. There can only be one medium or maximum at a time. If there is one medium there can be no maximum, and vice versa.

Since all of the objects are by default min, I don't track that. I use a string to track which element is in an expanded state. Then I compare that objects key and the string in an ng-if to change its what is being shown. The size is managed by a conditional class, and CSS.

I chose ng-if, because there maybe a lot of elements loaded in the beginning, but there can only be one med/max at a time. I would rather load the med/max when the user wants it, instead of loading all of the med/max at that start and use ng-show for state view.

Is there a cleaner way to handle state change among many related objects? Does Angular have something to deal with this?

angular.module('SizeAndState', [])
.factory('Data', function() {
        return {
            query: function() {
                return {
                    a:{ name: 'A', date: '1/2/03', number: 1},
                    b:{ name: 'B', date: '4/5/06', number: 2},
                    c:{ name: 'C', date: '8/9/10', number: 3},
                    d:{ name: 'D', date: '3/2/01', number: 4},
                    e:{ name: 'E', date: '1/2/14', number: 5},
                }
            }
        };
    })
    .controller('SizeAndStateController', ['$scope', 'Data', function($scope, Data) {
        $scope.toMin = function (clickEvent){
            clickEvent.stopPropagation();
            $scope.medElement = '';
            $scope.maxElement = '';

        };
        $scope.toMed = function (elementName, clickEvent){
            if($scope.maxElement=='') {
               if($scope.medElement == elementName){
                   $scope.toMin(clickEvent);
               } else {
                   $scope.medElement = elementName;
               }
            }
        };
        $scope.toMax = function (clickEvent){
            clickEvent.stopPropagation();
            $scope.maxElement = $scope.medElement;
            $scope.medElement = '';

        };
        $scope.data = Data.query();
        $scope.medElement = '';
        $scope.maxElement = '';
    }]);
.campaign{
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: #ff685b;
  border: 1px solid #ffffff;
  color: #ffffff;
  vertical-align: top;
}
.campaign.med{
  width: 125px;
  height: 125px;
}
.campaign.max{
  width: 150px;
  height: 150px;
}

        {{element.name}} Min

   Med

{{element.date}}

            <button class="btn"
                    ng-click="toMax($event)">
     to Max
            </button>

   Max

{{element.date}}

{{element.number}}

           <button
                ng-if="maxElement == element.name"
                ng-click="toMin($event)">
             to Min
         </button>


texts:
I have written some code in python to determine the outcome(including the remaining troops of both sides) of a Risk battle fought until one side is defeated. When using the Numba's njit decorator the code can simulate one battle's outcome in ~ 0.2ms.
This is not fast enough for the application I have in mind. Ideally it would be one to two orders of magnitude faster. Any advice on how to improve performance would be greatly appreciated.
Function Code:
@njit
def _attack_(n_atk,n_def):
    n_atk_dies = 0
    n_def_dies = 0
    while n_atk >0 and n_def>0:
        if n_atk>=3:
            n_atk_dies = 3
        if n_atk==2:
            n_atk_dies = 2
        if n_atk ==1:
            n_atk_dies = 1
        if n_def >=2:
            n_def_dies = 2
        if n_def ==1:
            n_def_dies = 1
        atk_rolls = -np.sort(-np.random.randint(1,7,n_atk_dies))
        def_rolls = -np.sort(-np.random.randint(1,7,n_def_dies))
        comp_ind = min(n_def_dies,n_atk_dies)
        comp = atk_rolls[:comp_ind]-def_rolls[:comp_ind]
        atk_losses =len([1 for i in comp if i<=0])
        def_losses = len([1 for i in comp if i>0])
        n_atk -= atk_losses
        n_def -= def_losses
    return [n_atk,n_def]

Benchmarking Code:
atk_list = list(np.random.randint(1,200,10000))
def_list = list(np.random.randint(1,200,10000))
cProfile.run('list(map(_attack_,atk_list,def_list))',sort='tottime')


texts: Most common words in a text file of about 1.1 million words

texts:
I'm learning programming with Python.

I’ve written the code below for finding the most common words in a text file that has about 1.1 million words. It is working fine, but I believe there is always room for improvement.

When run, the function in the script gets a text file from the command-line argument sys.argv[1], opens the file in read mode, converts the text to lowercase, makes a list of words from the text after removing any whitespaces or empty strings, and stores the list elements as dictionary keys and values in a collections.Counter object. Finally, it returns a dictionary of the most common words and their counts. The words.most_common() method gets its argument from the optional top parameter.

import sys
import collections

def find_most_common_words(textfile, top=10):
    """ Return the most common words in a text file. """

    textfile = open(textfile)
    text = textfile.read().lower()
    textfile.close()
    words = collections.Counter(text.split()) # how often each word appears

    return dict(words.most_common(top))

filename = sys.argv[1]
top_five_words = find_most_common_words(filename, 5)


texts:
I have implemented Jump search in Python, here is my code. Am I using the algorithm correctly ? Is there any pythonic way to achieve same ?

import math
def jump_search_2(arr,search):
    interval = int(math.sqrt(len(arr)))

    ''' find last lowest element '''
    for i in range(0,len(arr),interval):
        if arr[i] < search:
            low = i
        elif arr[i] == search:
            return i
        else:
            break
    ''' apply linear search '''
    l_index = [e for e,i in enumerate(arr[low:low+interval]) if i == search]
    if l_index[0]:
        return low+l_index[0]
    return "Not Found"

Usage example:

arr = [ i for i in range(1,300,15)]
res = jump_search_2(arr, 16)
print(res)


texts: Better filereading and print formating in R

texts:
I am a beginner using R and I am trying to solve some simple statistics problems and print the output. The following code takes in two datasets, computes the mean, variance and standard deviation. Finally it computes a 95-confidence interval for the standard deviation.

This is just a sample and my real data consists of a couple of thousand values, the files below are just for illustration.

Currently I read in my data files as follows

list(as.numeric(unlist(read.table(filename)))

however, I strongly feel there must be a better method? My datafiles
usually consists of rows of data (anywhere from 3 to 10 columns) and about a 1000 rows.

Secondly I find myself doing the following a lot

cat(paste(c("Confidence Intervall for the standard variation: (",
            f(CI.sigma.low[1]),", ",#
            f(CI.sigma.high[1]),")\n"), collapse = ""))

I tried to create a function that does this, however, I ran into problems when dealing with
multiple values.

I am not looking for feedback on the mathematics. Only syntax, and tips on how to
improve the overall structure of the code

Code

data_01.txt

34.10
34.21
33.34
35.45
31.56
34.67
36.72
33.16
34.35
34.50

data_02.txt

38.82518 37.61011 39.70940 41.19950 37.91823 39.06883 41.86497 38.87179
39.72824 39.46657 36.42833 39.73950 38.15764 38.49400 37.96093 38.31201
41.23278 37.50835 39.25816 39.72357 37.11235 38.84875 37.88969 38.86277

Main.R

EXERCISE <- 1 # Global variable,

# Shorthand for printing without " or numbers
p <- function(text,value) {
  cat(paste(c(text,value,"\n"), collapse = ""))
}

# Rounds number to X decimal places
f <- function(num, decimals=3) {
  round(num*10^decimals)/10^decimals
}

# Fancy title for the problems
problem <- function(index=EXERCISE) {
  w <- strrep("=",80); w.small <- strrep(" ",35)

  cat("\n\n"); cat(w,"\n")
  p(c(w.small,"Problem 3",letters[index],w.small),"")
  cat(w,"\n\n")
  #double << increments out of current scope
  EXERCISE <<- EXERCISE + 1
}

problem() # Problem 3a

# A list makes it easy to change or add files
filenames = c("data_01.txt",
              "data_02.txt")
kvm <- list()
for (i in 1:length(filenames)) {
  kvm[i] = list(as.numeric(unlist(read.table(filenames[i]))))
}

# Applies the function "length" to each element of "kvm" u.z.w
N <- sapply(kvm, length, simplify = TRUE)
mu <- sapply(kvm, mean, simplify = TRUE)
sigma <- sapply(kvm, sd, simplify = TRUE)

p("Number of values: ",N[1])
p("  Expected value: ",f(mu[1]))
p("        Variance:  ",f(sigma[1]^2))

problem() # Problem 3b

I <- 0.95 # 95-confidence intervall
alpha <- 1 - I

# qchisq is the Chi-squared Distribution
# df= degrees of freedom (frihetsgrader)
# CI = confidence interval
CI.sigma.low = (N-1) * sigma^2 / qchisq(1-alpha/2, df=N-1)
CI.sigma.high = (N-1) * sigma^2 / qchisq(alpha/2, df=N-1)

cat(paste(c("Confidence Intervall for the standard variation: (",
            f(CI.sigma.low[1]),", ",#
            f(CI.sigma.high[1]),")\n"), collapse = ""))

problem() # Problem 3e (T-interval)

I <- 0.95; alpha <- 1 - I

d.f <- sum(N) - length(N)
sigma.p <- sqrt(sum(sigma^2*(N-1))/d.f)

p("Pooled variance: ",f(sigma.p^2))
p("Pooled standard deviation: ",f(sigma.p))

v.p <- qt(1-alpha/2, d.f) * sigma.p * sqrt(sum(1/N))

CI.diff.mu.low <- (mu[1] - mu[2])-v.p
CI.diff.mu.high <- (mu[1] - mu[2])+v.p

p1 <- "Confidence Intervall for difference "
p2 <- "between mean values (mu_1-mu_2):"

cat(paste(c("\n",p1,p2,"\n","  (",
            f(CI.diff.mu.low),", ",#
            f(CI.diff.mu.high),")\n"), collapse = ""))


texts: Improving logic for pulling and passing data();

texts:
I'm pulling data from a list of images and passing it into an information container after click. After looking at my logic I assume there is a better way to do this. Any ideas would be helpful.

var getData = function() {
  $('.guest-image').html('');
  if ($($this).data("known1") != undefined) {
    $('.guest-data .known-for li').eq(0).html('');
  }
  if ($($this).data("known2") != undefined) {
    $('.guest-data .known-for li').eq(1).html('');
  }
  if ($($this).data("known3") != undefined) {
    $('.guest-data .known-for li').eq(2).html('');
  }
  $('.guest-data .title').text($($this).data("name"));
  $('.guest-data .desc').text($($this).data("desc"));
  $('.guest-data .link').text($($this).data("link"));
  $('.guest-data .link').attr('href', $($this).data("link"));
}


texts:
I posted an earlier version of this code a couple of days ago, so it's the updated version of the code posted here.

#include <iostream>
#include <functional>
#include <conio.h>
#include <unordered_map>
#include <string>

class EventListenerHandle
{
        template <typename U>
        friend class EventChannel;
    private:
        std::function<void()> removeFunction;
        bool removed;
        EventListenerHandle() = delete;
        inline EventListenerHandle(std::function<void()> remove_function) :removed(false)
        {
            this->removeFunction = remove_function;
        }
    public:
        inline void remove()
        {
            this->removed = true;
            removeFunction();
        }
};

template <typename T>
class EventChannel
{
private:
    using idType = unsigned int;
    static const idType& getNextId()
    {
        static idType id = 0;
        return id++;
    }

    static std::unordered_map<idType, std::function<bool(const T&)>>& getHandlers()
    {
        static std::unordered_map<idType, std::function<bool(const T&)>> handlers;
        return handlers;
    }
    static void removeListener(idType listener_id)
    {
        getHandlers().erase(listener_id);
    }
public:
    static EventListenerHandle registerListener(std::function<bool(const T&)> listener)
    {
        auto& id = getNextId();
        getHandlers()[id] = listener;
        return EventListenerHandle(std::bind(EventChannel<T>::removeListener, id));

    }
    static void tringgerEvent(T e)
    {
        for (const auto& h : getHandlers())
        {
            h.second(e);
        }
    }

};
/*to force the caller to  pass the bare type (not pointer or reference) as the templapte parameter
if these where not here one could (and possibly would) write some code like:
EventChannel<TouchEvent&>::registerListener([](const TouchEvent& ev)->bool
{
});
TouchEvent t;
DISPATCH_EVENT(t);
and expect the listener to be called. so it's better to prevent them from
using pointer and reference types as template parameter for EventChannel class.
also i decided not to care for volatile types.

*/

template<typename T>
class EventChannel<T*>{};

template<typename T>
class EventChannel<T&>{};

template <typename T>
class EventChannel<const T>{};

//just for convenience
template <typename T>
void DISPATCH_EVENT(const T& t)
{
    EventChannel<T>::tringgerEvent(t);
    //std::cout << t.eventType();
}
//to let the caller pass pointers as the event object
template <typename T>
void DISPATCH_EVENT(T* t)
{
    DISPATCH_EVENT<T>(*t);
}
#define EVET_TYPE_FUNC(T) static std::string eventType(){return #T;}
#define KDFA_DEFINE_VOID_EVENT(__NAME__)    struct __NAME__{EVET_TYPE_FUNC(__NAME__)};
struct TouchEvent
{
    int t_id;
    float x;
    float y;
    EVET_TYPE_FUNC(TouchEvent);
};

KDFA_DEFINE_VOID_EVENT(CAMERA_MOVED_OR_ZOOMED);
void main()
{
    auto lid = EventChannel<TouchEvent>::registerListener([](const TouchEvent& ev)->bool
    {
        std::cout << "got touch " << ev.t_id << "\n";
        return false;
    });

    TouchEvent t;
    t.t_id = 10;

    DISPATCH_EVENT(t);//dispatch with object
    DISPATCH_EVENT(&t);// dispatch with pointer

    //it's best to use RAII to correctly call remove on event listener handles
    lid.remove();//remove listener
    lid.remove();//calling remove multiple times would not cause any problems. this is a mere design decision

    DISPATCH_EVENT(t);

    _getch();
}

consider reading the main function first, it's pretty simple to understand. As I lost the ability to think about this design out of the box, any comment is welcomed. Thanks


texts:
I am working on a small and self-contained poll application, not unlike Straw Poll whereby one user can submit a poll and other users can vote (but only once).

I am building this little application in the open, using Angular for the front-end and Web Api for the back-end. I am using Fluent Validation to validate incoming models.

Using an action filter and Fluent Validation I have managed to remove all basic model validation from my controller.

I need to carry out some more advanced validation after I load the poll from the database. My action method has become overrun by such validation logic as you can see:

public IHttpActionResult Put(int pollId, VoteInput voteInput)
{
    var poll = _session.Load<Poll>(pollId);
    var voterIp = Request.GetOwinContext().Request.RemoteIpAddress;

    if (poll == null)
    {
        return BadRequest("you cannot vote on a poll that does not exist.");
    }

    if (poll.VoterIps.Contains(voterIp))
    {
        return BadRequest("you cannot vote on this poll because you have already voted.");
    }

    if (voteInput.Options.Length > 1 && !poll.MultiChoice)
    {
        return BadRequest("you cannot vote for more than one option. noob.");
    }

    foreach (var option in poll.Options.Where(option => voteInput.Options.Contains(option.Id)))
    {
        option.Votes += 1;
    }

    poll.VoterIps.Add(voterIp);
    _session.SaveChanges();

    return Ok();
}

I would very much like to remove some, if not all of this validation logic from the controller.

I have a really sound infrastructure - I am using Fluent Validation and a DI Framework - but owing to my inexperience with said technologies, I cannot think of a clean way to extract the validation logic.

What are some ways I can reduce or eliminate the validation in my controller?


texts: Find if value exists using SQL True/False Return

texts:
Aim: To Assess if one, or more, examples of a value exists in a Database in the quickest time as I only needs a True/False result.

The variable is Alphanumeric.

Question: Is this the quickest and best way to do this?

Public Function PrcCheckIfValueExists(vVariable As String) As String
        'Here we check if the Value Exists in the database
        Try
            Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("SQLLocal").ToString()
            Using connection = New SqlConnection(ConnectionString)
                Using command As New SqlCommand("SELECT TOP 1 ID FROM TblTable WHERE ID= '" & vVariable & "'", connection)
                    connection.Open()
                    Dim result = command.ExecuteScalar()
                    connection.Close()
                    If result = "" Then
                        Return False
                    Else
                        Return True
                    End If
                End Using
            End Using

        Catch ex As Exception
            Return False
        End Try

    End Function


texts: My Python3 Library provides a Wrapper around the Popular espeak TTS

texts:
My code:

import subprocess
import os
import platform

class Speaker:
    """
    Speaker class for differentiating different speech properties.
    """

    def setVoice(self, voice):
        self.voice = voice

    def setWPM(self, wpm):
        self.wpm = wpm

    def setPitch(self, pitch):
        self.pitch = pitch

    def setProperties(self, voice="en", wpm=120, pitch=80):
        self.setVoice(voice)
        self.setWPM(wpm)
        self.setPitch(pitch)

    def __init__(self, voice="en", wpm=120, pitch=80):
        self.prevproc = None
        self.setProperties(voice, wpm, pitch)
        self.executable = os.path.dirname(os.path.abspath(__file__)) +
                              "/espeak.exe" if platform.system() == 'Windows'
                              else os.path.dirname(os.path.abspath(__file__)) + "/espeak"

    def generateCommand(self, phrase):
        cmd = [
            self.executable,
            "--path=.",
            "-v", self.voice,
            "-p", self.pitch,
            "-s", self.wpm,
            phrase
        ]
        cmd = [str(x) for x in cmd]
        return cmd

    def say(self, phrase, wait4prev=False):
        cmd=self.generateCommand(phrase)
        if wait4prev:
            try: self.prevproc.wait()
            except AttributeError: pass
        else:
            try: self.prevproc.terminate()
            except AttributeError: pass
        self.prevproc = subprocess.Popen(cmd, executable=self.executable,
                            cwd=os.path.dirname(os.path.abspath(__file__)))

How can the above code be improved?

Find it on GitHub: https://github.com/sayak-brm/espeak4py

Usage:

import espeak4py
import time

print('Testing espeak4py\n')

mySpeaker = espeak4py.Speaker()

mySpeaker.say('Testing', wait4prev=True)

print('Testing wait4prev')

mySpeaker.say('Hello, World!')
time.sleep(1)
mySpeaker.say('Interrupted!')
time.sleep(3)

mySpeaker.say('Hello, World!')
time.sleep(1)
mySpeaker.say('Not Interrupted.', wait4prev=True)
time.sleep(3)

print('Testing pitch')

myHighPitchedSpeaker = espeak4py.Speaker(pitch=120)
myHighPitchedSpeaker.say('I am a demo of the say function')
time.sleep(4)

print('Testing wpm')

myFastSpeaker = espeak4py.Speaker(wpm=140)
myFastSpeaker.say('I am a demo of the say function')
time.sleep(4)

print('Testing voice')

mySpanishSpeaker = espeak4py.Speaker(voice='es')
mySpanishSpeaker.say('Hola. Como estas?')

print('Testing Completed.')


texts: Cleaner or better readability in URL composition

texts:
I have a URL that is hardcoded via a config which I extract into a config:

$url = 'http://www.example.com/api/v1/all/limit/{limit}/offset/{offset}'
// this is stored as a string inside a config file

then $limit = 10; $offset = 0;

I currently use the following preg_replace to replace the given URL and transform into an effective URL:

$url = preg_replace('/\{([A-Z, a-z]+)\}/e', "$$1", $url);

The effective string is now:

  http://www.example.com/api/v1/all/limit/10/offset/0

It works, however, I had to dig deep into figuring out the pattern and $$1 part so there goes readability.

My questions:

Is there anything else out there that someone can think of that can be as good as the above code?
I could use a str_replace with 2 arrays and do a replacement of the variables - it might be cleaner but it maybe slower.  Would anyone advise replacing that theory instead of this?  If so, why?
The number of variables could grow - currently doing this it will capture all $variable there is within that scope - so any suggestion would need to keep in mind that limit/offset will not be the only limited variables that will be incoming:

$url = 'http://www.example.com/api/v1/all/id/{id}/limit/{limit}/offset/{offset}'

$url = 'http://www.example.com/api/v1/all/relatedId/{relatedId}/limit/{limit}/offset/{offset}'


texts:
I have 3 objects and 3 models. The note, have many tags, and every tags must have one note. So, I have a note_tag_list to store the tags and notes relationship.

The program creates a note, with some tags.

First, I create a note object, and put it into the model. And I get back the object from the model. I create the tag if it doesn't exist. Then, I read back the tag object from the DB. And use all the tags and note to create new note_tag_list object, and put this object to the model.

But I think it seems very complex for my flow. Any ways to do it more elegant? Thank you.

//load all the object
$this->load->library('obj_note');
$this->load->library('obj_tag');
$this->load->library('obj_note_tag_list');

//load all the model
$this->load->model('note_model');
$this->load->model('tag_model');
$this->load->model('note_tag_list_model');

//create a note object
$aNewUserNote    =new obj_note();

//set the object information
$user_id         =get_current_user_id();
$title           =$this->input->post('ui_title_input');
$content_url     =$this->input->post('ui_url_input');
$content         =$this->input->post('ui_textarea');
$right           =RIGHT_NOTE_PUBLIC;
$status          =STATUS_NOTE_ACTIVE;

$aNewUserNote->set_user_id($user_id);
$aNewUserNote->set_title($title);
$aNewUserNote->set_content_url($content_url);
$aNewUserNote->set_content($content);
$aNewUserNote->set_right($right);
$aNewUserNote->set_status($status);

$aNewlyCreateNoteId = 0;

if(!$this->note_model->create_note_by_note($aNewUserNote, $aNewlyCreateNoteId))
{
    //create success
    return;
}

//get back the object from the model
$aNewlyCreateObj = $this->note_model->read_note_by_note_id($aNewlyCreateNoteId);

$aTagNameString = $this->input->post('ui_tag');
$tagsStringArray = $this->convert_tags_string_to_lower_case_string_array($aTagNameString);

$aTagArray = array();
$createNewTagIsSuccess = FALSE;

//Create New Tag
for($i = 0; $i < count($tagsStringArray); $i++)
{
    $aTagObj = $this->tag_model->read_tag_by_tag_name($tagsStringArray[$i]);
    if($aTagObj == NULL)
    {
        $aNewTag =new obj_tag();
        $aNewTag->set_create_user_id($user_id);
        $aNewTag->set_tag_name($tagsStringArray[$i]);

        if(!$this->tag_model->create_tag_by_tag($aNewTag)) //create tag fail
        {
          $createNewTagIsSuccess = FALSE;
        }
    }
}

//Read all the tag
for($j = 0; $j < count($tagsStringArray); $j++)
{
    $aTagObj = $this->tag_model->read_tag_by_tag_name($tagsStringArray[$j]);
    $aTagArray[count($aTagArray)] = $aTagObj;
}

//Make the note, and tag have relationship
for($k = 0; $k < count($aTagArray); $k++)
{
    $theTagObj = $aTagArray[$k];

    $aNoteTagList = new obj_note_tag_list();
    $aNoteTagList->set_note_id($aNewlyCreateObj[0]->get_id());
    $aNoteTagList->set_tag_id($theTagObj[0]->get_id());

    $this->note_tag_list_model->create_note_tag_list_by_note_tag_list($aNoteTagList);
}


texts:
In another post I created a piece of data, which make compressor annoyed.

Create 'worst case test' data for compression test

Now I am trying to make it happy.  I generate another data set, with a lot of duplicated binarys.  Of couse a data set composed of only one value is the best, but that is too easy.

This time I use a random number generator.  Inside a loop, each time either add a new byte or duplicate some bytes until reach a predefined length.

#include <iostream>
#include <fstream>
#include <random>
#include <vector>

typedef std::vector<unsigned char> Data;

int main(int argc, char* argv[])
{
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> rand(0.0, std::nextafter(1.0, DBL_MAX));

    const unsigned int length = 0x10000; // file minimal size

    Data data;
    data.reserve(length * 2);
    while (data.size() < length)
    {
        if (data.size() <= 1 || rand(mt) < 0.5)
        {
            // add a new byte
            data.push_back((unsigned char)(rand(mt) * 256));
        }
        else
        {
            // duplicate some bytes
            unsigned int count = (unsigned int)(rand(mt) * (data.size() / 2) + 1);
            data.insert(data.end(), data.end() - count, data.end());
        }
    }

    const char* filename = "c:\\_Test\\easy.dat";
    std::ofstream ofs(filename, std::ios::binary);
    if (ofs.bad() || !ofs.is_open())
    {
        std::cerr << "fail to open file\n";
        return -1;
    }
    ofs.write((char*)data.data(), data.size());

    std::cout << "job done\n";
    return 0;
}

The 7-zip is extremely happy with it.  With 7z format, 90kb data compressed to 900 bytes, and with zip format, it compressed to less than 2kb.

Again any suggestions and help are appreciated.


texts:
I'm working on a linear algebra module to improve my knowledge with mathematics and, because I'll need a lightweight linear algebra module for my future work with Vulkan!

I tried to keep a blas-like routine style, for exemple, the related functions are called like this:

template <typename T, std::size_t M, std::size_t N>
Matrix<T, N, M> transposed(const DenseBase<T, M, N>& mat)

The whole module is templated and works with compile-time size matrices. I use an std::vector as a storage container because I want to keep it allocated on the heap (for large matrices)

The 2nd goal is to provide an access to row/column element by reference, for example:

Matrix<float, 10, 10> matrix{};
matrix.col(1)[1] = 5; // 2nd element of 2nd matrix's column is now set to 5

To achieve this, I have a hierarchy with a base class:

template <typename T, std::size_t M, std::size_t N>
class DenseBase
{
 public:
 using Matrixbase = Matrix<T, M, N>;
 using Row = Rowview<DenseBase, T, N>;
 using Col = Colview<DenseBase, T, M>;

 using ConstRow = const Rowview<const DenseBase, const T, N>;
 using ConstCol = const Colview<const DenseBase, const T, M>;

  Row row(std::size_t index) { return Row{*this, index}; }
  Col col(std::size_t index) { return Col{*this, index}; }

  ConstRow row(std::size_t index) const { return ConstRow{*this, index}; }
  ConstCol col(std::size_t index) const { return ConstCol{*this, index}; }
  T& operator()(std::size_t row, std::size_t col) { return coeff(row, col); }
  T& operator[](std::size_t index) { return coeff(index); }

  const T& operator()(std::size_t row, std::size_t col) const { return coeff(row, col); }
  const T& operator[](std::size_t index) const { return coeff(index); }

  virtual T& coeff(std::size_t row, std::size_t col) = 0;
  virtual const T& coeff(std::size_t row, std::size_t col) const = 0;

  virtual T& coeff(std::size_t index) = 0;
  virtual const T& coeff(std::size_t index) const = 0;
};

Then, I have a Rowview, Colview class which takes a Densebase as an argument and implements the coeff functions:

template <typename Parent, typename T, std::size_t N>
class Rowview : public DenseBase<T, 1, N>
{
 public:
  Rowview(Parent& parent, std::size_t row) : parent_{parent}, row_{row} {}

  T& coeff(std::size_t, std::size_t col) { return parent_(row_, col); }
  T& coeff(std::size_t index) { return parent_(row_, index); }

  const T& coeff(std::size_t, std::size_t col) const { return parent_(row_, col); }
  const T& coeff(std::size_t index) const { return parent_(row_, index); }

 private:
  Parent& parent_;
  std::size_t row_;
};

And finally, the matrix class itself, with the std::vector and the implementation of coeff methods to access its elements.

I really need some advice, maybe some ideas about how to improve the architecture. I don't like the idea of an abstract template class, but I have no alternatives yet.

Note that you can find the whole code on GitHub.


texts: Processing a tab-delimited file with vertexes and ages

texts:
The following block of code needs to be as fast as possible as it likely to be called many thousands of times in a run.

I am also conscious that my thinking style is leaning towards a more procedural style from time to time and hence I may not be taking full advantage of all the benefits that functional programming brings.

Any tips for

making the code run faster, and
making it more functional

let qarray (tableName : string) (startAge : int) (startYear : int) =

let tableData = File.ReadAllLines tableName

// find which row the vertex is in
let vrow = Array.findIndex (fun (s:string) -> s.StartsWith vertexLiteral) tableData
let firstYear = int(tableData.[vrow].Split('\t').[1])

// filter out all the row prior to the column headers e.g. table description and comments
let filteredArray = Array.sub tableData (vrow+1) (tableData.Length-vrow-1)

// use the vertex info to read all lines beyond that, converting to doubles
let f (s:string) = s.Split('\t') |> Array.map double

let fullArray = Array.map f filteredArray

[| for i in 0 .. (120 - startAge - 1) -> fullArray.[startAge + i - 1].[System.Math.Min(startYear - firstYear + i + 1, fullArray.[0].Length)] |]


texts:
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem

Given a rows x cols matrix grid representing a field of cherries.
Each cell in grid represents the number of cherries that you can
collect.
You have two robots that can collect cherries for you, Robot #1 is
located at the top-left corner (0,0), and Robot #2 is located at the
top-right corner (0, cols-1) of the grid.
Return the maximum number of cherries collection using both robots by
following the rules below:

From a cell (i,j), robots can move to cell (i+1, j-1) , (i+1, j) or (i+1, j+1).
When any robot is passing through a cell, It picks it up all cherries, and the cell becomes an empty cell (0).
When both robots stay on the same cell, only one of them takes the cherries.
Both robots cannot move outside of the grid at any moment.
Both robots should reach the bottom row in the grid.

Example 1:

Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24
Explanation: Path of robot #1 and #2 are described in color green and
blue respectively.
Cherries taken by Robot #1, \$(3 + 2 + 5 + 2) =
> 12\$.
Cherries taken by Robot #2, \$(1 + 5 + 5 + 1) = 12\$.
Total of cherries: \$12 + 12 = 24\$.
Example 2:

Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
Output: 28
Explanation: Path of robot #1 and #2 are described in
color green and blue respectively.
Cherries taken by Robot #1,
\$(1 + 9 + 5 + 2) = 17\$.
Cherries taken by Robot #2, \$(1 + 3 + 4
> + 3) = 11\$.
Total of cherries: \$17 + 11 = 28\$.
Constraints:

\$rows == grid.length\$
\$cols == grid[i].length\$
\$2 <= rows, cols <= 70\$
\$0 <= grid[i][j] <= 100 \$

Inputs
[[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
[[1,0,0,3],[0,0,0,3],[0,0,3,3],[9,0,3,3]]
[[1,10,0,3,86,40],[0,0,0,3,86,40],[0,0,3,3,86,40],[9,0,3,3,86,40], [1,0,40,3,86,40],[0,22,0,3,86,40],[99,0,3,3,86,40],[9,0,3,3,86,40]]

Outputs
24
22
819

Code
#include <vector>
#include <cstring>

struct Solution {
    int map_cherries[70][70][70] = {};

    inline int cherryPickup(std::vector<std::vector<int>> &grid) {
        std::memset(map_cherries, -1, sizeof(map_cherries));
        const int row_length = grid.size();
        const int col_length = grid[0].size();
        return depth_first_search(grid, row_length, col_length, 0, 0, col_length - 1);
    }

private:
    const inline int depth_first_search(
        std::vector<std::vector<int>> &grid,
        const int row_length,
        const int col_length,
        int row,
        int left_robot,
        int right_robot
    ) {
        if (row == row_length) {
            return 0;
        }

        if (map_cherries[row][left_robot][right_robot] != -1) {
            return map_cherries[row][left_robot][right_robot];
        }

        int max_cherries = 0;

        for (int left = -1; left < 2; left++) {
            for (int right = -1; right < 2; right++) {
                const int curr_left_robot = left_robot + left;
                const int curr_right_robot = right_robot + right;

                if (curr_left_robot > -1 and curr_left_robot < col_length and curr_right_robot > -1 and curr_right_robot < col_length) {
                    max_cherries = std::max(max_cherries, depth_first_search(
                                                grid,
                                                row_length,
                                                col_length,
                                                row + 1,
                                                curr_left_robot,
                                                curr_right_robot
                                            ));
                }
            }
        }

        int cherries = grid[row][left_robot];

        if (left_robot != right_robot) {
            cherries += grid[row][right_robot];
        }

        return map_cherries[row][left_robot][right_robot] = max_cherries + cherries;
    }
};

References

Problem

Discuss

Solution


texts:
I have implemented a tree in Python. However, due to my lack of experience with Python, I am not able to judge the overall quality of my code.

import unittest
from datetime import *
from gc import *

RET_NO = 0
RET_YES = 1
RET_MAYBE = 0.5 # haha :)

class Tree(object):
    """
    Mutable abstract data type for arbitrary data with O(N) access on elements.
    """
    def __init__(self):
        super(Tree, self).__init__()
        self.root = None

    def insert(self, element):

        if self.root:
            self.root.insert(element)
        else:
            self.root = Node(element)

    def contains(self, element):
        if self.root is None:
            print 'WARN: Contains() called before elements were inserted!!'
            raise Exception()

        return self.root.contains(element) if self.root else RET_NO

    def size(self):
        return self.root.size() if self.root else 0

    def bulk_insert(self, elements=[]):
        while len(elements):
            self.insert(element[0])
            elements = elements[1:]

class Node(object):
    """
    Node class to be used in Tree instances.
    """
    def __init__(self, element):
        super(Node, self).__init__()
        self.element = element
        self.left = None
        self.right = None

    def insert(self, element):
        if self.element == element:
            return
        if element < self.element:
            if self.left:
                self.left.insert(element)
            else:
                self.left = Node(element)
        else:
            if self.right:
                self.right.insert(element)
            else:
                self.right = Node(element)
        raise Exception('Should never reach this line!')

    def contains(self, element):
        if self.element == element:
            return RET_YES
        if element < self.element:
            if self.left:
                return self.left.contains(element)
            else:
                return RET_NO
        else:
            if self.right:
                return self.right.contains(element)
            else:
                return RET_NO
        raise Exception('Should never reach this line!')

    def size(self):
        """
        Return size
        """
        left_size = self.left.size() if self.left else 0
        right_size = self.right.size() if self.right else 0
        return left_size + right_size + 1

class TreeTest(unittest.TestCase):

    def setUp(self):
        # no setup required yet
        pass

    def tearDown(self):
        # leave memory in a clean state
        gc.collect()

    def test_1(self):
        #tree = Tree()
        #self.assertEqual(tree.size(), 0)
        #tree.insert(10)
        #self.assertEqual(tree.size(), 10)
        self.assertTrue(True)

    def test_2(self):
        start = datetime.now()

        elements = []
        for i in range(1000000):
            elements += [i]

        tree = Tree()
        # tree should be empty
        for i in elements:
            self.assertEqual(tree.contains(i), RET_NO)
        # fill tree
        for i in elements:
            tree.insert(i)
        # tree should be full
        for i in elements:
            self.assertEqual(tree.contains(i), RET_YES)

        end = datetime.now()
        elapsed = end - start
        # must not take longer than a minute
        self.assertTrue(elasped.total_seconds() < 60)

    def test_3(self):
        tree = Tree()
        try:
            tree.contains(1)
            # should have thrown an exception -> test failed
            self.assertTrue(False)
        except Exception, ValueError:
            # expected to raise an Exception -> test should pass
            self.assertTrue(True)


texts: Three buttons with click listeners that pop up a quick toast

texts:
I currently have three buttons, perhaps more to come. When I click on a button, I want a toast notification or message (popup message) to show up with some text. What I have works perfectly but it is very redundant.

How I refactor what I have below to prevent redundant code?

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

        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Context context = getApplicationContext();
                CharSequence text = "This button will launch button1 App!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
        });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Context context = getApplicationContext();
                CharSequence text = "This button will launch button2 App!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
        });

        Button  button3= (Button) findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Context context = getApplicationContext();
                CharSequence text = "This button will launch button3 App!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
        });
    }


texts: Class to fill model objects with data from the database

texts:
This is a helper class that helps fill models with data obtained from the database.

public class Util {

    public static <M> ArrayList<M> createModel(M model, Cursor cursor) throws IOException {

        try {
            final Class<?> cls = model.getClass();

            final ArrayList<M> result = new ArrayList<>();
            while (cursor.next()) {

                final Class<?> item = Class.forName(cls.getName());
                final M obj = (M) item.newInstance();

                final Field[] fields = item.getDeclaredFields();

                for (Field field : fields) {
                    field.setAccessible(true);

                    final Class<?> type = field.getType();

                    switch (type.toString()) {

                        case "int": {
                            final int value = cursor.getInt(getFieldName(field), 0);
                            field.setInt(obj, value);
                            break;
                        }

                        default:
                            //throw new IOException();
                            continue;
                    }
                }

                result.add(obj);
            }

            return result;
        } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
            e.printStackTrace();
            throw new IOException();
        }
    }

    private static String getFieldName(Field field) {
        final fieldName annotation = field.getDeclaredAnnotation(fieldName.class);
        return annotation == null ? field.getName() : annotation.name();
    }
}

All code here(pastebin.com)

I think my version is very bad, so I want to improve it, but I haven’t yet figured out how to do it.

Usage example:

String query = "SELECT * FROM table_name WHERE;";
Cursor cursor = helper.query(query);
List<Test> test = Util.createModel(new Test(), cursor);


texts:
I have overrode Rails' ActionDispatch::Routing::RouteSet::Dispatcher.controller_reference method to check if a controller exists by checking for the required constants and then creating them based upon a controller with the same name in the Generic namespace.

The problem w/ my code is that it is using begin/rescue, it won't work w/ deeply namespaced controllers, and it's rather verbose.

Can anyone provide some improvements to this code?

class ActionDispatch::Routing::RouteSet::Dispatcher

  private

  def controller_reference(controller_param)
    const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"

    obj = Object
    const_name.split('::').each do |cn|
      begin
        obj =  obj.const_get(cn)
      rescue
        if obj == Object
          obj =  obj.const_set(cn, Class.new(ApplicationController))
        else
          puts "Creating #{obj}::#{cn} based on Generic::#{cn}"
          obj =  obj.const_set(cn, Class.new("Generic::#{cn}".constantize))
        end
      end
    end

    ActiveSupport::Dependencies.constantize(const_name)
  end

end