texts: Separate roles into modular parts that are interdependent

texts:
I have a IRC bot that I'm writing (code is here, bot24-irc.py is the main module).

This bot needs to be able to perform many different, separate roles so that each can be reloaded and sandboxed (for stability). I'm defining a role as being a function that reads all PRIVMSGs sent and returns a list of responses. At this moment, each role is in a separate module (just one right now, phablookup.py). I'm using the class role as a sort of wrapper to create a uniform way to "talk" to each module, to translate what the role modules want (a (different) function called with the right (different) arguments) to what the main module wants (a list of responses).

Here is the role class:

class role:
    run = False
    moduleName = ""
    checkFunc = ""
    args = []

    def init(self):
        if self.moduleName:
            try:
                print("Importing: " + self.moduleName)
                self.module = __import__(self.moduleName)
            except SyntaxError:
                print("Syntax error with " + self.moduleName + ", skipping...")
                self.run = False
                return 1
            except ImportError:
                print("Could not find " + self.moduleName + ", skipping...")
                self.run = False
                return 1
            else:
                self.funcToCall = getattr(self.module, self.checkFunc)
                return 0
        else:
            return 0

    def stop(self):
        self.run = False

    def start(self):
        self.run = True

    def check(self):
        if self.run:
            if self.moduleName:
                results = self.funcToCall(*self.args)
            else:
                results = self.checkFunc(*self.args)
            return results
        else:
            return ""

    def reload(self):
        if self.moduleName:
            try:
                reload(self.module)
            except SyntaxError:
                print("Syntax error with " + self.moduleName + ", skipping...")
                self.run = False
                return 1
            except ImportError:
                print("Could not find " + self.moduleName + ", skipping...")
                self.run = False
                return 1
            else:
                return 0
        else:
            return 0

And this is how I specify a new role:

phabLookup = role()
roles.append(phabLookup)
phabLookup.run = True
phabLookup.moduleName = 'phablookup'
phabLookup.checkFunc = 'lookup'
phabLookup.args = [msg, config['phabricator']['site'], config['phabricator']['apitoken']]

Now what I'm asking is this: is this type of module-per-role idea a good way to separate roles? Does it conform to best practices? It feels like its over complicating a really easy task. What is a better way to separate roles?


texts: Print all lines of a text file containing the same duplicated word

texts:
I'm implementing my very first Go application and I would like to receive an hint on how to make a certain check faster.

I have a huge txt file in which each line is structured like the following:

key text
key text
   .
   .
key text

Where key is ALWAYS 6 HEX digits long and text is ALWAYS 16 HEX digits long.

  I need to find and print all the lines which have the same text value.
  For instance, suppose we have 2 lines like the following

  000000 1234567890123456
  111111 1234567890123456

  They should be both printed.

Here's my code:

r, _ := os.Open("store.txt")
    scanner := bufio.NewScanner(r)
    for scanner.Scan() {
        line := scanner.Text()
        text := line[7:]
        if !contains(duplicates, text) {
            duplicates = append(duplicates, text)
        } else {
                t, _:= os.Open("store.txt")
                dupScan := bufio.NewScanner(t)
                    //currLine := dupScan.Text()
                for dupScan.Scan() {
                    currLine   := dupScan.Text()
                    currCipher := currLine[7:23]
                    if( currCipher == text ){
                    fmt.Println(currLine)
                    }
                }
                t.Close()
            }
    }
fmt.Println("Done Check")
//Close File
r.Close()

func contains(s []string, e string) bool {
    for _, a := range s {
        if a == e {
            return true
        }
    }
    return false
}

It works just fine but, since I have million lines, it's really slow. I'm only capable of doing it with a single thread and not using goroutines.

Have you any suggestion on how I should change this code to speed up the check?


texts:
I'm writing a very simple fading slider plugin for my own use. I would like to know what I could do to improve upon what I've already done.

I think I've done well, but I am certain there are things that I can do to improve.

(function($){
    $.fn.slider = function(options){
        var settings = $.extend({
            selector:this,
            speed:3000
        }, options);

        var $children = settings.selector.children();//Check the children from the element calling this function
        var $currentChildIndex = 0;//Set the current Index to 0 since we've not started yet.
        var $current = $($children[$currentChildIndex]);//Get the current child (Redundant?)

        setInterval(function(){
            $current = $($children[$currentChildIndex]);//Assign current from list of children using currentChildIndex

            $current.addClass('active');//Assign active to current slider

            $children.each(function(key,obj){
                if(!$current.is($(obj))){//Remove all active elements that aren't the current slider
                    $(obj).removeClass('active');
                }
            });

            if($currentChildIndex==($children.length-1)){//Check if Index has reached the end, if so reset to start
                $currentChildIndex=0;
            }else{
                $currentChildIndex++;
            }
        },settings.speed);//Wait every X seconds before changing slide
    }
}(jQuery));


texts: Good conduct of including numbers in css classes

texts:
I'm creating a couple of dynamic css classes, and the idea is that i get a string from an episerver context and add that to the class list of an element.

I know that numbers can be included in css classes, but what is good css code conduct, is it a good idea to include numbers in class names, or should i change it from body1 --> body-one.

body1 {
    font-size: 1.4rem;
}
body2 {
    font-size: 1.6rem;
}

body-one {
    font-size: 1.4rem;
}
body-two {
    font-size: 1.6rem;
}


texts:
I'm trying to get a better feel for how an entity-component-system system works. I'm most comfortable in JavaScript, so that's what I wrote it in. I'm mostly looking for ways my code violates ECS principles, but am also looking for ways to make my code more idiomatic.

class Component {
    get type() { return this.constructor.name; }

    constructor(data) {
        this.data = data;
    }
}

class Entity {
    get type() { return this.constructor.name; }

    constructor(id) {
        this.id = id;
        this.components = [];
    }

    get(type) { return this.components.find(c => c.type === type); }

    assign(component) {
        const included = this.get(component.type);
        if (included === undefined) this.components.push(component);
        else this.components[this.components.indexOf(included)] = component;
    }
}

class System {
    get type() { return this.constructor.name; }

    constructor(types, callback) {
        this.types = types;
        this.callback = callback;
    }

    run(entities) {
        entities.forEach(e =>
            this.types.every(t => e.get(t) !== undefined) &&
            this.callback(e)
        );
    }
}

Also, here's a basic example of how the system gets extended.

class ErrorComponent extends Component {
    constructor(error) {
        super(error);
    }
}

class ErrorSystem extends System {
    constructor() {
        super(
            ["ErrorComponent"],
            e => console.error(e.get("ErrorComponent").data)
        );
    }
}
const testComponent = new ErrorComponent("test");
const testComponent2 = new ErrorComponent("test2");

const testEntity = new Entity("test");
testEntity.assign(testComponent);
testEntity.assign(testComponent2);

const entities = [testEntity];
const testSystem = new ErrorSystem();
testSystem.run(entities);

One other thing that I feel like I don't understand about ECS is why I should extend Component and System, but not Entity. It feels asymmetrical. For example, could I say

class ErrorEntity extends Entity {
    constructor(id, error) {
        super(id);
        this.assign(new ErrorComponent(error));
    }
}

?
Or does this violate some principle of ECS?


texts:
I building a very simple price tracker web app. I am using MongoDB with pymongo. The user will enter the URL of the product he wishes to track and the desired amount, when the price goes below this amount, he should get an alert. It doesn't matter how many products he is tracking, I will send the alert when price changes in one product. I will sending generalized alert like 'Some of the product/s available at cheaper price' or something like that.

There are three collections in the database, one to store product details, one for user details and one to map products to the users who are tracking it.

A typical document in products collection will be:

{
  _id: ObjectId("53a2bfcfa7603606c2765342"),
  name: "Nexus 7 from Google (7-Inch, 16 GB, Black)",
  url: "http://rads.stackoverflow.com/amzn/click/B00DVFLJDS",
  base_price: 222,
  current_price: 213.96,
  img_url: "http://i.imgur.com/something.jpg",
  history: [
    [
      ISODate("2014-06-19T12:08:13.354Z"),
      293
    ],
    [
      ISODate("2014-06-24T14:31:38.216Z"),
      424
    ],
    [
      ISODate("2014-06-24T14:32:06.992Z"),
      424
    ]
  ]
}

in users, the tracked_products contain the Object Id of the product document and the desired price:

{
  _id: ObjectId("539c4adea760360886d7ef02"),
  email_id: "johnappleseed@apple.com",
  channels: {
    'twitter': 'usertwitterid',
    'ios_push_id': '45462722672762576422'
    'android_push_id': '2572652754762474'
    'chrome_push_id': '456456454646464'
  },
  tracked_products: [
    [
        ObjectId("53a2bfcfa7603606c2765342"),
        200
    ],
    [
        ObjectId("53a2d2ada7603606c2765344"),
        345
    ],
    [
        ObjectId("53a2d294a7603606c2765343"),
        120
    ]
  ]
}

and lastly trackers, here subscribers contain the Object Id of user document who are tracking this product:

{
    _id: ObjectId("77a2bfcfa7603606c2765399"),
    product_id: ObjectId("53a2bfcfa7603606c2765342"),
    subscribers: [
        [
            ObjectId("539c4adea760360886d7ef02"),
            200
        ],
        [
            ObjectId("12a2bfcfa7603606c2765399"),
            234
        ],
        [
            ObjectId("14a2bfcfa7603606c2765399"),
            345
        ],
}

Following is the code, which checks for the current_price and alerts the user if there is change in the price:

subscribers = set()

for product in product.collection:
    # price changed? if yes, then update
    current_price = get_current_price(product['url'])

    if current_price == product['current_price']:
        # no price change. move on
        continue

    product['history'].append((datetime.datetime.utcnow(), current_price))

    # find the subscribers:
    tracker_document = db.trackers.find_one({'product_id': product['_id']})

    for tracker in tracker_document['subscribers']:
        user_id, desired_price = tracker
        if current_price <= desired_price:
            subscribers.add(user_id)

    product.collection.save(product)

if not subscribers:
    # no price changes in any products!
    sys.exit()
email_queue = list()
twitter_queue = list()
ios_push_queue = list()
droid_push_queue = list()
chrome_push_queue = list()

for user_id in subscribers:
    user_document = db.users.find_one({'_id': user_id})
    email_queue.append(user_document['email_id'])
    twitter_queue.append(user_document['channels']['twitter'])
    ios_push_queue.append(user_document['channels']['ios_push_id'])
    droid_push_queue.append(user_document['channels']['droid_push_id'])
    chrome_push_queue.append(user_document['channels']['chrome_push_id'])

alert_users(email_queue, twitter_queue, ios_push_queue, droid_push_queue, chrome_push_queue)

I am looking for any suggestions, code improvements/readability, performance improvement, schema change etc. Anything!

PS: I am aware this would be lot easier with RDBMS and join operations, but I am sticking with MongoDB as of now.


texts: Finding words of different lengths given six letters

texts:
I'm trying to find all the 3, 4, 5, and 6 letter words given 6 letters.  I am finding them by comparing every combination of the 6 letters to an ArrayList of words called sortedDictionary.  I have worked on the code a good bit to get it to this point.

I tested how many six letter words are checked and got 720 which is good because 6*5*4*3*2*1=720 which means I am not checking any words twice.  I can't make it faster by getting rid of duplicate checks because I have already gotten rid of them all.

Can I still make this faster?

Note that sortedDictionary only contains about 27 hundred words.

for(int l1 = 0; l1 < 6; l1++){
    for(int l2 = 0; l2 < 6; l2++){
        if(l2 != l1)
            for(int l3 = 0; l3 < 6; l3++){
                if(l3 != l1 && l3 != l2){
                    if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]))
                        anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]);
                    for(int l4 = 0; l4 < 6; l4++){
                        if(l4 != l1 && l4 != l2 && l4 != l3){
                            if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]))
                                anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]);
                            for(int l5 = 0; l5 < 6; l5++){
                                if(l5 != l1 && l5 != l2 && l5 != l3 && l5 != l4){
                                   if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]))
                                       anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]);
                                   for(int l6 = 0; l6 < 6; l6++){
                                       if(l6 != l1 && l6 != l2 && l6 != l3 && l6 != l4 && l6 != l5)
                                           if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]+anagramCharacters[l6]))
                                               anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]+anagramCharacters[l6]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
    }
}

My solution, still probably not the best written code but it reduce the loading time from about 1-2 seconds to nearly instant (no noticeable wait time; didn't actually test how long it was).

for(int i = 0; i < sortedDictionary.size(); i++){
    for(int index = 0; index < anagram.length(); index++)
        anagramCharacters[index] = anagram.charAt(index);
    forloop:
    for(int i2 = 0; i2 < sortedDictionary.get(i).length(); i2++){
        for(int i3 = 0; i3 < anagramCharacters.length; i3++){
            if(sortedDictionary.get(i).charAt(i2) == anagramCharacters[i3]){
                anagramCharacters[i3] = 0;
                break;
            }
            else if(i3 == anagramCharacters.length-1)
                break forloop;
        }
        if(i2 == sortedDictionary.get(i).length()-1)
            anagram_words.add(sortedDictionary.get(i));
    }
}


texts: Allowing switching between operator[] and at() based on NDEBUG macro version

texts:
The problem:

std::vector and other containers have two functions for accessing / modifying their content: operator[] and at().

at() is meant for debugging, to catch out-of-bound bugs. However, at() is also quite a lot slower than operator[]. Both above facts would yearn for a way to switch between the use of at() and operator[] based on whether it is a debug build or a production build, especially if performance matters.

However, I can see no such easy way. Sadly standard containers don’t offer a flag or sth that would allow to do this.

I tried to write a simple wrapper that would switch between at() and operator[] based on whether or not NDEBUG is defined, in line with how the assert macro works.

Note: This is a different solution to the same problem as stated here: Allowing switching between operator[] and at() based on NDEBUG This solves the issue of 2d arrays. But I wanted to post two solutions, 'cuz I feared You could frown upon such a macro :(

The code:

// AOO = At Or Operator[]
#ifndef NDEBUG
  #define AOO(INDEX) .at(INDEX)
#else
  #define AOO(INDEX) [INDEX]
#endif

The use:

void testNormalUse()
{
    std::vector<int> vec(100);
    vec AOO(50) = 5;
    std::cout << vec AOO(50) << std::endl;
}

void testRequireConst()
{
    const std::vector<int> vec(100, 5);
    std::cout << vec AOO(50) << std::endl;
}

void testRvalueRef()
{
    std::vector<int>vec(100, 5);
    std::cout << std::move(vec) AOO(50) << std::endl;
}

void test2d()
{
    std::vector<std::vector<int>> vec(100, std::vector<int>(100, 5));
    std::cout << vec AOO(50) AOO(50) << std::endl;
}

int main() {
    testNormalUse();
    testRequireConst();
    testRvalueRef();
    test2d();
}

Ideone

Of course I know this is weird syntax. But the non-macro solution brings up pain with multidimensional arrays, a problem the macro version solves.

If only macros allowed punctuation, then we could make it look operator-like. But alas, they don't.


texts: Design pattern to implement Database operations

texts:
I am trying to implement design pattern in my project and have been reading material over net.

we have a sales application ( in C# ) where in we are storing entities like

Customer
Contacts
Sales Order
Lead
Opportunity

This is how i am planning to implement design pattern.

Entity would be the base class and it has common variables

namespace DesignModel.Model
{
    class Entity
    {
        protected IDBOperation dbOperation;
        public string id { get; set; }
        public int isSync { get; set; }
        public string timestamp { get; set; }

        public void insert()
        {
            dbOperation.insertData();

        }

        public void update()
        {
            dbOperation.updateData();
        }
        public void delete()
        {
            dbOperation.deleteData();

        }
    }
}

Here is the Contact class that is extending Entity class. Contact class would have its own properties too.

namespace DesignModel.Model
{
    class Contact : Entity
    {
        public Contact()
        {
             dbOperation = new DBOperations();

        }
        public string name { get; set; }
        public string company { get; set; }
        public string jobtitle { get; set; }

    }
}

Now what i have derived from the nature of this application is each entity has following operations for database interaction and to fetch data from server.

for database operation

insert
update
delete

to get and send data from server

getData
sendData

based on that i have created an interface named IDBOperation

namespace DesignModel.Database
{
    interface IDBOperation<T>
    {
        void insertData(T entity) ;
        void updateData(T entity);
        void deleteData(T entity);

        void displayData();

    }
}

and concrete class DBOperations that implements IDBOperation

namespace DesignModel.Database
{
    class DBOperations : IDBOperation<Entity>

    {

        public void insertData(Entity e) {

            Debug.WriteLine("insertData "+e.id );

        }

        public void deleteData(Entity e)
        {
            Debug.WriteLine("deleteData" + e.id);

        }

        public void updateData(Entity e)
        {
            Debug.WriteLine("updateData" + e.id);

        }
        public void displayData()
        {

        }
    }

and at last Contact class

namespace DesignModel.Model
{
    class Contact : Entity
    {
        public Contact()
        {
             dbOperation = new DBOperations();

        }
        public string name { get; set; }
        public string company { get; set; }
        public string jobtitle { get; set; }

    }
}

i am using contact as follows

    Contact contactData = new Contact();
    contactData.id = "1234";
    contactData.isSync = 1;
    contactData.jobtitle = "Sales Manger";
    contactData.insert(contactData);

I am little confused where i have been implementing it correctly or not.

the reason why i kept implementation in DBOperation because if new interface method comes i have to implement it at one place oppose to if i am implementing method in customer, contact and sales order classes.

one thing that worries me is Entity parameter in insertData inside DBOperation not sure whether i will be able to add entire contact into db or not.

so if anyone help me in providing pointers to correctly implement the design pattern in this use case then it will me more helpful


texts:
I'd like to reduce the complexity of my code
Problem :

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of a given number N?

Solution :
import java.util.Scanner;
import java.util.TreeSet;

public class Solution {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int testCases = sc.nextInt();
        for (int i = 0; i < testCases; i++) {
            int input = sc.nextInt();
            System.out.println(calculateFactors(input));

        }
    }

    public static int calculateFactors(int input) {
        TreeSet<Integer> set = new TreeSet<>();
        while (input % 2 == 0) {
            set.add(2);
            input = input / 2;
        }
        for (int i = 3; i < Math.sqrt(input); i = i + 2) {
            while (input % i == 0) {
                set.add(i);
                input = input / i;
            }
        }
        if (input > 2) {
            set.add(input);
        }
        int max = set.last();
        return max;
    }

}


texts:
I have written a method to determine whether a Vector2 lies inside a polygon or outside of it. The polygon is defined by an array of clockwise vertices, p[]. It returns true if the point is inside, false otherwise.

public bool polyCheck(Vector2 v, Vector2[] p)
{
    int j = p.Length-1;
    bool c = false;
    for(int i=0;i<p.Length;j=i++)c^=p[i].y>v.y^p[j].y>v.y&&v.x<(p[j].x-p[i].x)*(v.y-p[i].y)/(p[j].y-p[i].y)+p[i].x;
    return c;
}

It is perfectly functional, works with all edge cases, and is blazing fast. I want to know how I could make the method look prettier, and have better 'coding practices' though.


texts: Create, aggregate and plot signals using various methods for a given symbol using its historical data

texts:
I am hoping to get some help regarding code arrangement/organization using OOP concepts. My question is whether my usage of class/object selection/declaration and instantiation are sensible and what are the ways to make them more sensible.

Essentially there are 3 classes, and 1 main function that makes use of them.

class SigGen(object):

    def __init__(self, bars, method):
        self.bars= bars
        self.method = method
        self.rlzd = get_changes(self.bars) # this is an imported function from another module

    def gen_sig(self, *args):
        self.sig = self.method(args)

    ....maybe more methods will be created later, no other methods right now.

Questions:

Is the use of the get_changes function to set self.rlzd appropriate during the instantiation?
Is the use of gen_sig to create "sig" attribute outside of instantiation appropriate?

Here is the main function:

for isym, sym in enumerate(symbol_list):
    bars= get_data_for_symbol(sym)
    for im, m in enumerate(method_list):
        strat = SigGen(sym, bars, m)
        for iwindow, window in enumerate(windows):
            args = get_args(m, window)
            strat.gen_sig(*args)
            plot.create_sig_plots(strat, iwindow, window)
            df_list.append(strat.sig)
        sig[m.__name__] = pd.concat(df_list, axis =1)

        if aggregate_w == 'y':
            for i_agg, agg_method in enumerate(agg_method_list):
                agg_object = aggregator(signal_df = sig[m.__name__],
                                        rlzd = strat.rlzd,
                                        lookback = lookback_list[i_agg])
                agg_sig[m.__name__] = agg_method(agg_object)

                if plot.running_agg:
                    plot.create_agg_plots( agg_sig[sym][m.__name__], rlzd,  agg_method.__name__, len(windows))

Do I need to create an agg_object above (class declaration below)? The only reason I did it is that in the declaration of various methods in Aggregator class, I don't have to pass in all the values used in instantiation of the object.

class Aggregator(object):
    def __init__(self, signal_df, rebal_freq, realized, lookback=30):
        self.all_signals_df = signal_df
        self.rlzd = realized
        self.lookback = lookback

    def running_perf(self):
        hits= np.sign(self.all_sign_df) == np.sign(self.rlzd)
        running_performance = pd.rolling_mean(hits, self.lookback)
        agg_sig = pd.DataFrame(self.all_sig_df.lookup(running_performance.index, best_window))
        return agg_sig


texts:
I am learning Scala and want to know, what is preferred style of writing a function for a trait.

First:

sealed trait Expression

final case class Addition(left: Expression, right: Expression) extends Expression

final case class Subtraction(left: Expression, right: Expression) extends Expression

final case class Division(left: Expression, right: Expression) extends Expression

final case class SquareRoot(value: Expression) extends Expression

final case class Number(value: Double) extends Expression

object Expression {

  def eval(e: Expression): Calculation =
    e match {
      case Addition(l1, r1) => eval(l1) match {
        case Failure(rea1) => Failure(rea1)
        case Success(res1) => eval(r1) match {
          case Failure(rea2) => Failure(rea2)
          case Success(res2) => Success(res1 + res2)
        }
      }
      case Subtraction(l1, r1) => eval(l1) match {
        case Failure(rea1) => Failure(rea1)
        case Success(res1) => eval(r1) match {
          case Failure(rea2) => Failure(rea2)
          case Success(res2) => Success(res1 - res2)
        }
      }
      case Division(l1, r1) => eval(r1) match {
        case Failure(rea2) => Failure(rea2)
        case Success(res2) => res2 match {
          case 0.0 => Failure("Division by zero")
          case _ => eval(l1) match {
            case Failure(rea1) => Failure(rea1)
            case Success(res1) => Success(res1 / res2)
          }
        }
      }
      case SquareRoot(v) => eval(v) match {
        case Failure(rea) => Failure(rea)
        case Success(res) => res match {
          case x if x < 0 => Failure("Square root of negative number")
          case y => Success(math.sqrt(y))
        }
      }
      case Number(v) => Success(v)
    }

}

Second:

sealed trait Expression {
  def eval: Calculation =
    this match {
      case Addition(l, r) =>
        l.eval match {
          case Failure(reason) => Failure(reason)
          case Success(r1) =>
            r.eval match {
              case Failure(reason) => Failure(reason)
              case Success(r2) => Success(r1 + r2)
            }
        }
      case Subtraction(l, r) =>
        l.eval match {
          case Failure(reason) => Failure(reason)
          case Success(r1) =>
            r.eval match {
              case Failure(reason) => Failure(reason)
              case Success(r2) => Success(r1 - r2)
            }
        }
      case Division(l, r) =>
        l.eval match {
          case Failure(reason) => Failure(reason)
          case Success(r1) =>
            r.eval match {
              case Failure(reason) => Failure(reason)
              case Success(r2) =>
                if(r2 == 0)
                  Failure("Division by zero")
                else
                  Success(r1 / r2)
            }
        }
      case SquareRoot(v) =>
        v.eval match {
          case Success(r) => if(r < 0)
            Failure("Square root of negative number")
          else
            Success(Math.sqrt(r))
          case Failure(reason) => Failure(reason)
        }
      case Number(v) => Success(v)
    }
}
final case class Addition(left: Expression, right: Expression) extends Expression
final case class Subtraction(left: Expression, right: Expression) extends Expression
final case class Division(left: Expression, right: Expression) extends Expression
final case class SquareRoot(value: Expression) extends Expression
final case class Number(value: Int) extends Expression


texts:
I have a water reservoir with input and output rates. I want to determine when the input is exceeding the output by a certain constant. To accomplish this, I need to cumulatively sum all cases where the inflow exceeds the outflow. Thus, I've written this function:

def pos_diff_cum_sum(flow_in: np.ndarray, flow_out: np.ndarray) -> np.ndarray:
    sums = []
    cum_sum = 0
    diff = list(flow_in - flow_out)

    for dd in diff:
        cum_sum += dd
        if cum_sum < 0:
            cum_sum = 0

        sums.append(cum_sum)

    return np.array(sums)

It sums up the periods where the inflow exceeds the outflow while ignoring periods where the opposite is true. Basically, numpy.cumsum with a corner case.

Tests with plots

t_steps = 9

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(4, 8))
in_flow = np.linspace(1., 0., t_steps)
out_flow = np.linspace(0., 1., t_steps)

ax1.plot(in_flow, label="in")
ax1.plot(out_flow, label="out")
ax1.legend()

pos_diff = pos_diff_cum_sum(in_flow, out_flow)
ax2.plot(pos_diff)
pos_diff
# => array([1.  , 1.75, 2.25, 2.5 , 2.5 , 2.25, 1.75, 1.  , 0.  ])

t_steps = 9

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(4, 8))
in_flow = np.linspace(0., 1., t_steps)
out_flow = np.linspace(1., 0., t_steps)

ax1.plot(in_flow, label="in")
ax1.plot(out_flow, label="out")
ax1.legend()

pos_diff = pos_diff_cum_sum(in_flow, out_flow)
ax2.plot(pos_diff)
pos_diff

# => array([0.  , 0.  , 0.  , 0.  , 0.  , 0.25, 0.75, 1.5 , 2.5 ])

This code isn't vectorized, but it's going to be called very frequently, so is there some way I should speed it up? Is there any way to make this more elegant?


texts:
This program is an implementation of the classic puzzle Tower of Hanoi! This is my first mostly recursive Assembly program. Any advice and all topical comments on code optimization and conventions is appreciated!

Compiled as follows using VS2017 x64 Native Tools Command Prompt:

> nasm -g -fwin64 hanoi.asm

> cl /Zi hanoi.obj msvcrt.lib legacy_stdio_definitions.lib

hanoi.asm

;; bits 64
default rel

extern printf, scanf

section .text
    global main
    global hanoi
main:
    sub     rsp, 56
    lea     rcx, [prompt]
    call    printf
    lea     rdx, [rsp+32]
    lea     rcx, [scan_fmt]
    call    scanf
    cmp     eax, 1
    jz      .call_hanoi
    lea     rcx, [scan_fail]
    call    printf
    mov     eax, 1                      ; return 1
.end:
    add     rsp, 56
    ret
.call_hanoi:
    mov     ecx, dword [rsp+32]         ; ecx = num_disks
    mov     r9d, 3                      ; r9d = tmp
    mov     r8d, 2                      ; r8d = dst
    mov     edx, 1                      ; edx = src
    call    hanoi                       ; hanoi(num_disks, src, dst, tmp)
    xor     eax, eax                    ; return 0
    jmp     .end
hanoi:
    push    r12
    mov     r12d, r8d                   ; r12d = r8d = dst
    push    rbp
    push    rdi
    push    rsi
    mov     esi, edx                    ; esi = edx = src
    push    rbx
    sub     rsp, 40
    cmp     ecx, 1                      ; if num_disks == 1
    jz      .skip_recursive_move
    mov     ebx, ecx
    mov     edi, r9d                    ; edi = r9d = tmp
.move_disk:
    lea     ebp, [rbx-1H]               ; ebp = num_disks - 1
    mov     r9d, r12d                   ; r9d = r12d = dst
    mov     r8d, edi                    ; r8d = edi = tmp
    mov     edx, esi                    ; edx = esi = src
    mov     ecx, ebp                    ; ecx = edp = num_disks - 1
    call    hanoi                       ; tmp & dst are swapped for this call
    mov     edx, ebx                    ; edx = ebx = num_disks
    mov     r9d, r12d                   ; update r9d after hanoi call
    mov     r8d, esi                    ; update r8d after hanoi call
    lea     rcx, [prompt_move_disk]
    mov     ebx, ebp                    ; ebx = ebp = num_disks - 1
    call    printf
    cmp     ebp, 1                      ; if num_disks == 1
    jz      .move_one_disk
    mov     eax, esi
    mov     esi, edi
    mov     edi, eax                    ; swaps tmp and src (esi and edi)
    jmp     .move_disk
.skip_recursive_move:
    mov     edi, edx                    ; edi = edx = src
.move_one_disk:
    add     rsp, 40
    mov     r8d, r12d
    mov     edx, edi
    pop     rbx
    lea     rcx, [prompt_move_one_disk]
    pop     rsi
    pop     rdi
    pop     rbp
    pop     r12
    jmp     printf

%macro str 2
    %2: db %1, 0
%endmacro

section .rdata
    str "How many disks do you want to play with? ", prompt
    str "%u", scan_fmt
    str {"Uh-oh, I couldn't understand that...  No towers of Hanoi for you!", 10}, scan_fail
    str {"Move disk 1 from %d to %d", 10}, prompt_move_one_disk
    str {"Move disk %d from %d to %d", 10}, prompt_move_disk

Sample output


texts: Plotting text from a dictionary with Matplotlib

texts:
I have the following dictionary:

top = {'aaaa': {'☹': 7, '': 12, '': 6},
      'bbbb': {'': 2, '': 2, '': 2},
      'cccc': {'☹': 5, '': 3, '': 3},
      'dddd': {'': 8, '': 7, '': 3},
      'eeee': {'☺': 3, '': 5, '': 4},
      'ffff': {'☹': 5, '': 5, '': 5}}

Each 'aaaa' or 'bbbb' is the user's name, and his values is the emoji he is using the most.
I want to plot a decent looking graph to visualize.
After a few tries, this is my best work:

with the code:

import matplotlib.pyplot as plt

def top_emoji(top):
    fig, ax = plt.subplots(figsize=(8, 5))
    y = 9
    level = 0
    start = 9
    for name, dictionary in top.items():
        ax.text(start, y - level, name, fontsize=20)
        x = 3
        for emoj in dictionary.keys():
            ax.text(start - x, y - level, emoj, fontname='Segoe UI Emoji', fontsize=20)
            x += 1
        level += 1

    ax.axis([0, 10, 0, 10])
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.axis('off')
    plt.show()

Which is terrible in my opinion. Any recommendations for improvements will be much appreciated.


texts:
How can I improve the string RecvData() function?

std::string Socket::RecvData() {
    std::string strBuffer;
    do{
        char buffer;
        int recvInt = recv(s_, &buffer, 1, 0);
        if (recvInt == INVALID_SOCKET)
        {
            return "";
        }
        if (recvInt == SOCKET_ERROR)
        {
            if (errno == EAGAIN) {
                return strBuffer;
            }
            else {
                // not connected anymore
                return "";
            }
        }

        strBuffer += buffer;
        if (buffer == '\n')  return strBuffer;
    } while (true);
}


texts: LSD radix sort (force avoid div or idiv compiler instruction) in C++

texts:
I was trying to optimize the Radix Sort code, just because. Nothing more, nothing less. Here it is!!! So tell me, how does it look?
Summary:

instead of a div or mod ,i use left shift and right shift to avoid div or idiv compiler instruction.

the dual instruction is for avoiding jumps and the usual stuff.

btw you can do arr pointer with same code just change obj_arr*&arr with obj_arr**&arr and add some function to the class obj_arr to get unsigned int
example: arr[i]->get_unsigned_int().
or operator if that you like.
postdata: take in mind you are using arr of obj class.
#pragma once
#define modpow2(num,div_pow2,mod_pow2)  (num>>div_pow2) - (num >> mod_pow2+div_pow2 << mod_pow2)

template<class obj_arr>
unsigned int getmax(obj_arr*& arr, size_t& size);

template<class obj_arr>
void countrad(obj_arr*& arr, obj_arr*& aux_arr, size_t& size, unsigned int*& count, const unsigned int& mod_pow2, const unsigned int& div_pow2);

template<class obj_arr>
void radix_sort_ftl(obj_arr* arr, size_t size, unsigned int mod_pow2 = 4);

template<class obj_arr>
unsigned int getmax(obj_arr*& arr, size_t& size) {

    size_t i = modpow2(size,0,1);
    unsigned int aux=arr[0];
    for (; i < size; i += 2) {
        aux = arr[i] * (aux < arr[i]) + aux * (aux >= arr[i]);
        aux = arr[i + 1] * (aux < arr[i + 1]) + aux * (aux >= arr[i + 1]);
    }
    return aux;
}

template<class obj_arr>
void radix_sort_ftl(obj_arr* arr, size_t size, unsigned int mod_pow2) {
    unsigned int max = getmax(arr, size) + 1;
    obj_arr* aux_arr = new obj_arr[size];
    unsigned int* count = new unsigned int[1<< mod_pow2 + 1];

    for (unsigned int divpow2 = 0; max > (1<< divpow2); divpow2 += mod_pow2){
        countrad(arr,aux_arr,size,count,mod_pow2, divpow2);
    }

    delete[] aux_arr;
    delete[] count;

}

template<class obj_arr>
void countrad(obj_arr*& arr, obj_arr*& aux_arr, size_t& size, unsigned int*& count, const unsigned int& mod_pow2, const unsigned int& div_pow2) {

    unsigned int i, move,max_mod=1<<mod_pow2;

    i = modpow2(max_mod + 1,0,1);
    count[0] = 0;
    for (; i < max_mod + 1; i += 2) {
        count[i] = 0;
        count[i + 1] = 0;
    }

    i = modpow2(size, 0, 1);
    count[modpow2(arr[0],div_pow2,mod_pow2)+ 1] += i;
    for (; i < size; i += 2) {
        count[modpow2(arr[i], div_pow2, mod_pow2) + 1]++;
        count[modpow2(arr[i+1], div_pow2, mod_pow2) + 1]++;
    }

    i = modpow2(max_mod + 2, 0, 1) + 1;
    for (; i < max_mod + 1; i += 2) {
        count[i] += count[i - 1];
        count[i + 1] += count[i];
    }

    i = modpow2(size, 0, 1);
    move = modpow2(arr[0], div_pow2, mod_pow2);
    aux_arr[count[move]] = arr[0];
    count[move] += i;
    for (; i < size; i += 2) {
        move = modpow2(arr[i], div_pow2, mod_pow2);
        aux_arr[count[move]] = arr[i];
        count[move]++;

        move = modpow2(arr[i+1], div_pow2, mod_pow2);
        aux_arr[count[move]] = arr[i + 1];
        count[move]++;
    }

    i = modpow2(size, 0, 1);
    arr[0] = aux_arr[0];
    for (; i < size; i += 2) {
        arr[i] = aux_arr[i];
        arr[i + 1] = aux_arr[i + 1];
    }
}

```


texts:
My algorithm scrapes an infinite-scroll page but it takes too long. It scrolls three times but I'm wondering if there is a way to do a ScrollBottom() so no need of repeated code.

Regarding the site from the example: Scroll is done by jQuery ScrollExtend goo.gl/Sq4vVx triggered when the users scroll beyond a particular tag. When that happens a particular class is added into the tag and removed after the pagination is done.

I think there's room for improvement code and performance wise.

"use strict";

var Xray = require('x-ray');
var phantom = require('x-ray-phantom');

var phantom_opts = {
    webSecurity: false,
    images: false,
    weak: false
};

var x = Xray().driver(phantom(phantom_opts, function (nightmare, done) {
    done
        .useragent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36")
        .goto(nightmare.request.req.url)
        .scrollTo(4000, 0)
        .wait()
        .scrollTo(8000, 0)
        .wait()
        .scrollTo(12000, 0)
        .wait()
}));

x('https://www.compraonline.grupoeroski.com/es/supermercado/2059698-Alimentos-Frescos/2059746-Carnes-y-aves/2059753-Pollo/', '.product_list li',
    [{
        name: '.description_1',
        unitPrice: '.description_2',
        image: '.image_line img@src',
        price: '.product_price_cont p',
        url: '.image_line a@href',
        volumen: '.description_1',
        medida: '.description_1'
    }])(function (err, products) {
        if (err) console.log(err);

        console.log(products.length);

        process.exit(0);
    });


texts:
I made a simple temperature converter to serve as an introduction to swing.  I used Eclipse WindowBuilder and did not attempt to make the components more modular.  I'm curious as to how you guys would organize this code to improve readability.

Also, if you have any other criticism I'd love to hear it.

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.TextField;
import java.awt.FlowLayout;
import javax.swing.JTextPane;
import javax.swing.JButton;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import javax.swing.UIManager;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ButtonGroup;

public class TempConvert extends JFrame {

private JPanel contentPane;
private final ButtonGroup buttonGroup = new ButtonGroup();

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                TempConvert frame = new TempConvert();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public TempConvert() {

    setTitle("Temperature Converter");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(0, -33, 385, 272);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JTextPane txtTempIn = new JTextPane();
    txtTempIn.setBounds(12, 46, 124, 26);
    contentPane.add(txtTempIn);

    JRadioButton celRadio = new JRadioButton("Celcius");
    buttonGroup.add(celRadio);
    celRadio.setBounds(212, 34, 67, 24);
    contentPane.add(celRadio);

    JRadioButton fahrenRadio = new JRadioButton("Fahrenheit");
    buttonGroup.add(fahrenRadio);
    fahrenRadio.setBounds(212, 62, 85, 24);
    contentPane.add(fahrenRadio);

    JLabel lblTem = new JLabel("Degrees");
    lblTem.setBounds(154, 49, 78, 16);
    contentPane.add(lblTem);

    JTextPane tempOutput = new JTextPane();
    tempOutput.setBackground(UIManager.getColor("Button.background"));
    tempOutput.setEditable(false);
    tempOutput.setBounds(12, 138, 267, 22);
    contentPane.add(tempOutput);

    JButton btnNewButton = new JButton("Convert");
    btnNewButton.setBounds(12, 84, 98, 26);
    contentPane.add(btnNewButton);
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            if(celRadio.isSelected()){
                try{
                    double temp=Double.parseDouble(txtTempIn.getText());
                    temp = temp * 1.8 + 32;
                    tempOutput.setText(Double.toString(temp));
                }catch(Exception e){
                    tempOutput.setText("Please enter a valid temperature.");
                }
            }else{
                try{
                    double temp=Double.parseDouble(txtTempIn.getText());
                    temp = (temp - 32) * (5.0/9.0);
                    tempOutput.setText(Double.toString(temp));
                }catch(Exception e){
                    tempOutput.setText("Please enter a valid temperature.");
                }
            }
        }
    });
}
}


texts:
This finds a peak element in an array. Please consider I want only one peak element. Also, my code should follow only C++11/14 and not C++03.

#include <iostream>

int peak(int * arr, size_t size)
{
    auto start = 0;
    auto end = size - 1;

    //empty array
    if(arr == nullptr || size <= 0)
    {
        return -1;
    }

    while(start <= end)
    {
      auto  mid = start + (end - start)/2;
        printf("arr[mid] %d \n",arr[mid]);
        if(start == end)
            return arr[start];

        if(arr[mid] >= arr [mid+1] && arr[mid] >= arr[mid-1])
        {
            return arr[mid];
        }
        else if(arr[mid] < arr[mid-1])
        {
            end = mid;
        }
        else
        {
            start = mid;
        }

    }

    return -1;
}

int main(int argc, const char * argv[]) {
    // insert code here...

    int arr[] = {1,1,8,9,22,2};

    auto elem = peak(arr, sizeof(arr)/sizeof(int)); //Do not understand how to use decaltype instead of int

    printf("%d",elem);

    return 0;
}


texts: Filter by multiple options - also only if not empty

texts:
Here's how my json looks like. I'm trying to write a function which filters based on participantCriteria.criteriaType & participantCriteria._id

participantCriteria ": [ {
  "_id": "9be6c6299cca48f597fe71bc99c37b2f",
  "caption": "XXXXXXXXXXX",
  "criteriaType": "YYYYYY",
  "inputSources": [{
      "_id": "66be4486ffd3431eb60e6ea6326158fe",
      "caption": "docId",
      "participantCriteriaId": "9be6c6299cca48f597fe71bc99c37b2f",
      "referenceId": null,
      "type": "identifier"
    },
    {
      "_id": "1ecdf410b3314865be2b52ca9b4c8539",
      "caption": "limit",
      "participantCriteriaId": "9be6c6299cca48f597fe71bc99c37b2f",
      "referenceId": null,
      "type": "number"
    }
  ]
},

Here is the function I have written to filter out the JSON above.

filterFunction(id) // returns the above JSON
.then((criteria) => {
  let filteredCriteria = (participantType ? criteria.filter(({ criteriaType }) =>
    criteriaType === participantType) : criteria); // if participantType is provided, filter the JSON where criteriaType === participantType

  filteredCriteria = (participantCriteriaId ? filteredCriteria.filter(({ _id }) =>
    _id === participantCriteriaId) : filteredCriteria) // if participantCriteriaId is provided, filter the json where _id === participantCriteriaId
    .map(({ _objectId: _id, caption, criteriaType, inputSources }) => ({
      _id,
      caption,
      criteriaType,
      inputSources: inputSources
        .map(({ _objectId, caption: inputCaption, isLookup, lookupId, picklistId, type }) => {
          let inputSourceType = type;
          if (type === 'identifier') { inputSourceType = (isLookup && lookupId) ? 'lookup' : 'key'; }
          return {
            _id: _objectId,
            caption: inputCaption,
            participantCriteriaId: _id,
            referenceId: (lookupId || picklistId) || null,
            type: inputSourceType,
          };
        }),
    }));
  res.json({
    data: {
      participantCriteria: filteredCriteria,
    },
  });
  return undefined;
})

Is there a better way to achieve this filtering ? or Maybe a way to chain the two filters I have added above (the lines where I have added comments).


texts:
I've been working on optimizing such as loop unrolling, is there anything I can do to optimize this code to make it run faster/in less cycles?

void compute_ranks(float *F, int N, int *R, float *avg, float *passing_avg, int *num_passed) {
    int i, j;
    *num_passed = 0;
    *avg = 0.0;
    *passing_avg = 0.0;

    // init ranks
    for (i = 0; i < N; i++) {
        R[i] = 1;
    }

    // compute ranks
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            if (F[i] < F[j]) {
                R[i] += 1;
            }
        }
    }

    // compute averages
    for (i = 0; i < N; i++) {
        *avg += F[i];
        if (F[i] >= 50.0) {
            *passing_avg += F[i];
            *num_passed += 1;
        }
    }

    // check for div by 0
    if (N > 0) *avg /= N;
    if (*num_passed) *passing_avg /= *num_passed;

} // compute_ranks

I did this for the first one

or (i = 0; i < N; i += 5) {
        R[i] = 1;
        R[i+1] = 1;
        R[i+2] = 1;
        R[i+3] = 1;
        R[i+4] = 1;
    }*/

Is there a way to not use pointers or anything really to make this more optimized?


texts:
I have 20+ key set. Keyset is like:

Key[0] = { "PossibleKey0", "PossibleKey0Another", "AnotherPossibleKey0" }
Key[1] = { ....

There is an encryption which needs to be broken, it will receive 20+ keys, one after another. So it applies decryption one-by-one.

So key[0] has 3 different possible keys, same for key[1], key[2], etc.

I should try each key with its each possible keys. I decided to write it like:

for i in range(0, len(Key[0])):
    for j in range(0, len(Key[1])):
        for k in range(0, len(Key[2])):
            for l in range(0, len(Key[2])):
                Decrypt(Key[0][i], Key[1][j], Key[2][k], Key[3][l])

But it looks OK for small key sets, what's better approach when there will be 20+ keys?


texts:
I am tring to learn coding in clear way. I developed easy application to simulate EKG. I would like to ask some experts, if the code is clean and if they have any suggestion, what could I improve. Possible improvment is not to avoid first loop (no counter of data is set to -1, to avoid first read), but I do not have an idea how to make it.

EkgDataModel

struct ekgDataModel {
    int amountOfData;
    int frequency;
    float newValue;
    float previousValue;
};

void initEKGData(struct ekgDataModel *ekgData) {
    // -1 to avoid first loop
    ekgData->amountOfData = -1;
    ekgData->frequency = 0;
    ekgData->newValue = 0;
    ekgData->previousValue = 0;
}

EkgFunctionality.c

void runElectrocardiography() {
    struct ekgDataModel ekgData;
    initEKGData(&ekgData);

    while (ekgData.newValue != END_VALUE) {
        analyzeNewValue(&ekgData);
        ekgData.previousValue = ekgData.newValue;
        ekgData.newValue = getNewInput();
    }
}

void analyzeNewValue(struct ekgDataModel* ekgData) {
    if (ekgData->newValue >= MIN_INPUT_RANGE && ekgData->newValue <= MAX_INPUT_RANGE) {
        ++(ekgData->amountOfData);
        ekgData->frequency += checkCrossing(ekgData);
        checkIfFrequencyValid(ekgData);
    }
}

void checkIfFrequencyValid(struct ekgDataModel* ekgData) {
    if (ekgData->amountOfData == MAX_AMOUNT_OF_DATA
        && (ekgData->frequency < MIN_FREQUENCY_ALLOWED
                || ekgData->frequency > MAX_FREQUENCY_ALLOWED)) {
        displayWrongFrequencyMessage(&ekgData->frequency);
        ekgData->frequency = 0;
        ekgData->amountOfData = 0;
    }
}

int checkCrossing(struct ekgDataModel* ekgData) {
    if (ekgData->newValue * ekgData->previousValue < 0)
        return 1;
    else
        return 0;
}

EkgInputOutputOperations.c

float getNewInput() {
    float newValue;
    scanf("%f", &newValue);
    return newValue;
}

void displayWrongFrequencyMessage(int *frequency) {
    printf("Bad frequency result: %d\n", *frequency);
}


texts: Measuring a given method's execution time

texts:
I have been playing around with some improvements to some sort algorithms like Selection Sort and Merge Sort and I ended up needing some sort of measurement to check if my versions were any faster than the original algorithm form. I also had a need to implement some sort of time measurement before but never did it, so here came the chance. And so I ended up coding the following measurement method:

public static double Measure(Action action, bool print = true)
{
    Stopwatch watch = new Stopwatch();
    const int precision = 1; //estimated precision of 1 milisecond on my machine
    const int error = 1; //max error
    const int times = 10;
    double min = double.MaxValue;
    for (int i = 0; i < times; ++i)
    {
        int iterations = 0;
        watch.Restart();
        while (watch.Elapsed.Milliseconds < precision*(100-error))
        {
            action();
            ++iterations;
        }
        watch.Stop();
        min = Math.Min(min, watch.Elapsed.Milliseconds*1000.0/iterations);
    }

    if(print)
        Debug.WriteLine("The action takes {0:N4} nanos to complete", min);

    return min;
}

Is this a well conducted measurement algorithm? Any suggestions or improvements that I could apply?


texts: Count number of gemstones in a set of minerals

texts:
This is the "Gemstones" problem on Hackerrank.

  John has collected various rocks. Each rock has various minerals embeded in it. Each type of mineral is designated by a lowercase letter in the range a-z. There may be multiple occurrences of a mineral in a rock. A mineral is called a gemstone if it occurs at least once in each of the rocks in John's collection.
  Given a list of minerals embedded in each of John's rocks, display the number of types of gemstones he has in his collection.
  For example, the array of mineral composition strings [abc, abc, bc] The minerals b and c appear in each composite, so there are 2 gemstones.

This is my Python code:

def gemstones(arr):
    for i in range(len(arr)):
        arr[i] = "".join(set(arr[i]))

    long = max(arr, key=len)
    arrlen = len(arr)
    flag,count = 0,0
    for i in long:
        for j in range(arrlen):
            if i not in arr[j]: flag = 1
        if flag is 0: count += 1
        flag = 0
    return count

Are there ways to improve this code? I feel I'm not using the full functionality of Python.

A test case:

>>> arr = ['abcdde', 'baccd', 'eeabg']
>>> print(gemstones(arr))
2


texts:
This plugin is for article pages that has a very long main content (left side) and a shorter sidebar. When the user scrolls down mostly the right part will be white space.

What this plugin does is make the sidebar stick or make it fixed past a point and will stop sticking when it collides with the bottom part or a footer. The functionality will not work if the main content is short.

Anyway, I'm asking feedback on how to improve my JS code.

;(function ( $, window, document, undefined ) {

// Create the defaults once
var pluginName = "scrollMinUntil",
defaults = {
    article: null,
    topPadding: 0
};

// The actual plugin constructor
var Plugin = function ( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}

Plugin.prototype = {

init: function() {

    if($(this.element).length <= 0)
      return null;

    this.scroll(this.element, this.options);
},

scroll: function(el, options) {
    var article = options.article,
        topPadding = options.topPadding,
        w = $(window),
        wrap = $(el).children('.wrap'),
        startingPos = wrap.offset().top,
        fixedPosTrigger = wrap.offset().top + wrap.outerHeight(),
        stopMovingPosTrigger = 0,
        staticMarginTop = 0,
        scrollTop = 0,
        elHeight = 0,
        stopMovingPos = 0,
        fixed = false,
        staticFlag = false;

    if(options.article.outerHeight() > 1500) {
      w.scroll(function() {

        // Calculate dynamic values
        scrollTop = $(this).scrollTop(),
        elHeight = wrap.outerHeight(),
        fixed = wrap.hasClass('fixed'),
        staticFlag = wrap.hasClass('static'),
        stopMovingPos = article.outerHeight() + article.offset().top;

        // Check if scrolling before or after the fixed trigger, set stopMovingPosTrigger accordingly
        (scrollTop < fixedPosTrigger) ? stopMovingPosTrigger = scrollTop : stopMovingPosTrigger = scrollTop + elHeight;

        // Making sure that fixed is triggered when scrolling pass the trigger position from the original area
        if(scrollTop > fixedPosTrigger && !staticFlag)
          wrap
            .addClass('fixed')
            .css({
              'padding-top': topPadding + 'px'
            });

        // Fixed positioned area, setting paddings and margins, and transition scrolling from the static area
        if((scrollTop > fixedPosTrigger) && (stopMovingPosTrigger < stopMovingPos)){
          wrap
            .removeClass('static')
            .addClass('fixed')
            .css({
              'margin-top': 0
            });
        }

        // Static positioned area, setting dynamically the margin-top for the element
        else if((stopMovingPosTrigger > stopMovingPos) && fixed) {

          // Calculate top margin to be added to the static element
          staticMarginTop = (stopMovingPos - startingPos) - elHeight;

          wrap
            .removeClass('fixed')
            .addClass('static')
            .css({
              'margin-top': staticMarginTop
            });
        }

        // Original area before the fixed position area
        else if(scrollTop < fixedPosTrigger) {
          wrap
            .removeClass('fixed static')
            .css({
              'padding-top': 0
            });
        }
      });
    }
}
};

// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function ( options ) {
return this.each(function () {
    if (!$.data(this, "plugin_" + pluginName)) {
        $.data(this, "plugin_" + pluginName,
        new Plugin( this, options ));
    }
});
};

})( jQuery, window, document );


texts:
I'm a computer science student who's just starting out with algorithms and their implementation. I wrote this code for a dynamically morphing square. I was wondering if I could get a review on it.  I apologize if the comments are excessive, this is how I submitted on it at school.

import time  #imported the time module to make the loop stop for a .5 sec before the next iteration

user_input = int(input("Input a number greater than 3: ")) #gets the user input in the form of an integer

def pattern(count): #created a function here called pattern, and gave it a parameter called count
    while user_input > 3: #This loop works as long as the integer entered is > 3
        min = 0 #initialize the variable min as the starting corner of the square i.e zero point.
        max = count - 1 #initialize the variable max as "count -1". This is because this variable will be updated by the loops through each iteration.
        for run in range(0,count): #first loop to control the iterations of the square
            print(run) #This will print the number of the iteration we are in at the time. This is put here as a check to see if the loop works as intended.
            for i in range(0,count): #this loop goes from row 0 to row N, where N is the value entered by the user.
                for j in range(0,count): #this loop goes from column 0 to column N, where N is the value entered by the user. This will be responsible for printing the stars in the square, from column to column.
                    if (min <= max and min <= i and i <= max and min <= j and j <= max) and (i == min or i == max or j == min or j == max): #this branch checks if ceertain cinditions are met. then prints * if they are. The conditions are explained below.
                        print("*",end="") #prints * without a line break after every iteration of its loop
                    else:
                        print(".",end="") #prints . without a line break after every iteration of its loop
                print("") #prints a new line
            print("") #prints a new line
            if run < count / 2: #in this branch, if the iterations of the boxes < half of the user input, the variable min will be incremented by 1
                min += 1        #and the variable max will be reduced by 1
                max -= 1
            if run >= count / 2: #if the iterations of the boxes > half of the user input, min will be reduced by 1 and  max will increase by 1.
                min -= 1
                max += 1
            time.sleep(.5) #pauses for .5 secs between iterations of the square.

if user_input >= 3: #if the user input > 3, the function called pattern will be called
    pattern(user_input)
else: #if the user input < 3, there will be an error message printed
    print("Enter a number greater than 3 ")

# The first branch in this function checks if the variable min<max, if min < i <= max, if min < j <= max, if i = min, if j = min, if i = max and if j = max.
# These conditions confine the points that are printed to the space between min and max, in both the rows and columns of the square.
# The four final conditions are there to allow the square to dissappear creating a set of dots and display the first square where both rows and columns are equal to the number entered by the user.

The results are as follows:


texts: Risk board game - best practices, private vs public variables and methods

texts:
This is my first attempt at writing something in JavaScript besides a few Project Euler problems I did first. It's intended to be a library used client side and server side (both of which I know very little about).  I've read Crockford's Javascript: The Good Parts, but nothing else. I have the most current experience with Python.

I'd appreciate any feedback (especially style concerns), I know there's a terrifically large amount of stuff to address, so if that's overwhelming, I have these immediate concerns:

By using closure with my country object, am I wasting memory, and hence should be using prototypical inheritance?
My JSONify code seems redundant, I assume there's a more correct way to do this?
Mixing private instance variables like "countries" and public instance variables looks ugly.  Is that how it's supposed to be done?

Full code available, link is to the commit which brings that code up to date with what I've posted here. There's a larger object (250 lines) I would love to post if that's not excessive, but for now here's the smaller object. (50 lines)

var country = function(name, connected_to){
    // variables in constructor signature are private
    // These are private variables that weren't in the constructor signature
    var helper = function(player, num_troops){
        // These are public methods
        return {
            'get_name' : function(){return name},
            'get_troops' : function(){return num_troops;},
            'get_owner' : function(){return player;},
            'get_touching_names' : function(){return connected_to},
            'is_owned_by' : function(in_player){return in_player == player},
            'is_touching' : function(to){
                if (!(typeof to === 'string')){
                    to = to.get_name();
                }
                for (var i = 0; i < connected_to.length; i++){
                    if (connected_to[i] === to){
                        return true;
                    }
                }
                return false;
            },

            'set_state' : function(in_player, in_num_troops){
                player = in_player;
                num_troops = in_num_troops;
            },
            'toString' : function(){
                return '[country '+name+']';
            },
            'get_ascii' : function(){
                return name + ' owned by ' + player + ' with '+ num_troops +
                    '\n        connected to ' + connected_to;
            },
            'jsonify' : function(){
                var j = {
                    'name' : name,
                    'player' : player,
                    'num_troops' : num_troops,
                    'connected_to' : connected_to
                }
                return j;
            },
            'dejasonify' : function(j){
                name = j.name;
                player = j.player;
                num_troops = j.num_troops;
                connected_to = j.connected_to;
            }
        };
    };
    return helper(null, null)
};


texts:
Just wondering if there's anything I can improve on, I just started with Python recently and this is one of my first programs.

# Defining Score variables
x = 0
score = x

# Question One
print("What is 1 + 1")
answer_1 = input("a)1\nb)2\nc)3\nd)4\n:")
if answer_1.lower() == "b" or answer_1.lower() == "2":
    print("Correct")
    x = x + 1
else:
    print("Incorrect, 1 + 1 is 2")

# Question Two
print("Who is the 45th president of the United States?")
answer_2 = input("a)Barack Obama\nb)Hillary Clinton\nc)Donald      Trump\nd)Tom Brady\n:")
if answer_2.lower() == "c" or answer_2.lower() == "donald trump":
    print("Correct")
    x = x + 1
else:
    print("Incorrect, The 45th president is Donald Trump")

# Question Three
print("True or False... The Toronto Maple Leafs have won 13 Stanley   Cups?")
answer_3 = input(":")
if answer_3.lower() == "true" or answer_3.lower() == "t":
    print("Correct")
    x = x + 1
else:
    print("Incorrect")

# Question Four
print("What was the last year the Toronto Maple Leafs won the Stanley   Cup?")
answer_4 = input("a)1967\nb)1955\nc)1987\nd)1994\n:")
if answer_4.lower() == "a" or answer_4 == "1967":
    print("Correct")
    x = x + 1
else:
    print("Incorrect, The last time the Toronto Maple Leafs won the Stanley Cup was 1967")

# Question Five
print("True or False... The current Prime Minister of Canada is Pierre Elliot Tredeau?")
answer_5 = input(":")
if answer_5.lower() == "false" or answer_5.lower() == "f":
    print("Correct")
    x = x + 1
else:
    print("Incorrect, The current Prime Minster of Canada is Justin Tredeau")

#Total Score
score = float(x / 5) * 100
print(x,"out of 5, that is",score, "%")


texts: How to speed up the code for LeetCode "Container with most water" task?

texts:
I'm trying to solve the LeetCode question where you need to find out the area of the container with the most water. I have created the solution that seems to work in my testing but it fails for being too slow when I try to submit it on LeetCode.
My idea is that I create a dictionary of (x, y) tuples from the input list and then for every item I need to find the maximum distance to any of other lines that are equal or taller than it and from here I can calculate what the maximum area is possible for this line.
How else can I approach this to get it to run faster? (I can't submit solution successfully so can't see examples of answers by other users)
def max_area(height) -> int:
    areas = []
    coords = {x: (x, y) for x, y in enumerate(height)}
    for x in coords:
        higher = [k for k in coords if coords[k][1] >= coords[x][1]]
        area = max(abs(coords[j][0] - coords[x][0]) for j in higher) * coords[x][1]
        areas.append(area)
    return max(areas)


texts: Wow that's a big integer! What's its largest prime factor?

texts:
I see that there are a few other people who have tackled Project Euler Problem #3. I hope you're not all sick of that question yet. I've not taken a look at those yet (purposely), but am about to now.

I feel like I did a pretty good job on this one, but you tell me. How can I further improve this code? I'm particularly interested in how it could be made even faster, but it seems to already be a pretty quick implementation. My first version took over an hour, this one runs almost instantly. I'm also interested in how I could have used a List<T> instead of an array, if you feel that would have been a better data structure.

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

Numbers.cs - 79 Lines

There are three functions: IsPrime, IsFactor, and PrimeFactors.

namespace Challenges
{
    public class Numbers
    {
        public static Boolean IsPrime(Int64 number)
        {
            if (number < 2)
            {
                return false;
            }

            if (number == 2)
            {
                return true;
            }

            if (number % 2 == 0)
            {
                return false;
            }

            double sqrtOfNumber = Math.Sqrt(number);

            for (var index = 3; index <= sqrtOfNumber; index += 2) //skip even numbers
            {
                if (number % index == 0)
                {
                    return false;
                }
            }

            return true;

        }

        public static bool IsFactor(Int64 dividend, Int64 divisor)
        {
            return (dividend % divisor == 0);
        }

        public static Int64[] PrimeFactors(Int64 number)
        {
            Int64[] results = { };

            Int64 maxDivisor = number / 2;
            int index = 0;
            for (Int64 divisor = 2; divisor < maxDivisor; divisor++ )
            {
                if (IsFactor(number,divisor) && IsPrime(divisor))
                {
                    Array.Resize(ref results, results.Length + 1);
                    results[index] = divisor;
                    index++;

                    Int64 factor = number / divisor;
                    if (IsPrime(factor))
                    {
                        Array.Resize(ref results, results.Length + 1);
                        results[index] = factor;
                        break;
                    }
                    else
                    {
                        Int64[] recursiveResults = PrimeFactors(factor);
                        Array.Resize(ref results, results.Length + recursiveResults.Length);
                        for (int i = 0; i < recursiveResults.Length; i++)
                        {
                            results[index] = recursiveResults[i];
                            index++;
                        }
                        break;
                    }
                }
            }

            return results;
        }
    }
}

Console Program

To prove it works, you can check my answer.

namespace Challenges
{
    class ProjectEuler3Program
    {
        static void Main(string[] args)
        {
            const Int64 verybigint = 600851475143;
            Int64[] factors = Numbers.PrimeFactors(verybigint);

            Console.WriteLine((factors.Max()));

            Console.WriteLine();
            Console.WriteLine("Press enter to close...");
            Console.ReadLine();
        }
    }
}


texts: Improving readability and logic on "re-indexing" method

texts:
This is a method which takes an input of a "page" object, which includes SortOrder.  It then fetches the existing page items from a database and attempts to re-index.

I don't think this is at all efficient and reads horribly and wondered if anybody could make some recommendations?

    public Boolean ReIndexOutputTemplatePages(OutputTemplatePage page)
    {
        try
        {

            int? requiredIndex = page.SortOrder;

            var items = from t1 in db.OutputTemplatePages
                        where (t1.OutputTemplateId == page.OutputTemplateId)
                        orderby t1.SortOrder
                        select t1;

            Boolean boolHasBeenAdded = false;
            int ctr = 0;
            if (items.Count() == 0)
            {
                Add(page);
                boolHasBeenAdded = true;
            }
            else
            {
                foreach (OutputTemplatePage template in items)
                {
                    if (requiredIndex == ctr)
                    {
                        Add(page);
                        ctr++;
                        boolHasBeenAdded = true;
                    }

                    OutputTemplateRepository repo = new OutputTemplateRepository();
                    OutputTemplatePage pg = repo.GetOutputTemplatePageById(template.Id);
                    pg.SortOrder = ctr;
                    repo.Save();

                    ctr++;

                }
            }
            if (!boolHasBeenAdded)
            {
                Add(page);
            }
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }


texts:
Here's some code I've written for an MMO server I'm working on. I'd love some opinions and eventually unspotted bugs.

struct Data { Data(int i) :id(i) {} int id; };

class list
{
public:
    struct Node { std::shared_ptr<Data> d_; std::shared_ptr<Node> next; };

private:
    CRITICAL_SECTION update_lock;
    concurrency::concurrent_queue<std::shared_ptr<Data>> to_add;
    concurrency::concurrent_queue<int> to_remove;
    std::shared_ptr<Node> head;
    std::atomic_uint32_t  count;

    void push_back(std::shared_ptr<Data> d) {
        std::shared_ptr<Node> n = std::make_shared<Node>();
        n->d_ = std::move(d);
        n->next = head;
        while (!std::atomic_compare_exchange_weak(&head, &head, n)) {}
        count++;
    }

    void remove(int id) {
        std::shared_ptr<Node> t_0 = nullptr;
        std::shared_ptr<Node> t_1 = head;
        while (1)
        {
            if (!t_1) break;

            if (t_1->d_->id == id)
            {
                if (!t_0) { while (1) { if (std::atomic_compare_exchange_weak(&head, &head, head->next))break; } }
                else { while (1) { if (std::atomic_compare_exchange_weak(&t_0->next, &t_0->next, t_1->next))break; } }

                t_1 = nullptr;
                count--;
                break;
            }
            t_0 = t_1;
            t_1 = t_1->next;
        }
    }

public:
    list() : head(nullptr) { InitializeCriticalSection(&update_lock); }
    ~list() {

        //clear the list
        while (head)
        {
            head = head->next;
        }

        DeleteCriticalSection(&update_lock);
    }

    uint32_t get_count() { return count.load(std::memory_order_relaxed); }

    void add_remove(std::shared_ptr<Data> d, bool add) {
        if (add) to_add.push(std::move(d)); else to_remove.push(d->id);

        unsigned char t_c = 0;

        /*IMPORTANT-TO-GET: no. of instructions it takes for the function to exit the while_loop and leave the critical_section*/
        unsigned char n = 10;

        while (1) {
            if (++t_c > n) return;
            if (TryEnterCriticalSection(&update_lock)) break;
        }

        std::shared_ptr<Data> temp = nullptr;
        while (1)
        {
            if (!to_add.try_pop(temp)) break;
            push_back(temp);
        }

        int temp_id;
        while (1)
        {
            if (!to_remove.try_pop(temp_id)) break;
            remove(temp_id);
        }

        LeaveCriticalSection(&update_lock);
    }

};


texts:
I am taking a C++ course and we have received our final assignment, I was looking for some suggestions and or tips so I can continue to improve.

I am aware that the use of using namespace std is bad practice but my professor prefers that we use this way since it is a beginners course.

The assignment was a two part assignment I have commented out the piece of the code that was unneeded for the second part.

Part One:

  Write a program that simulates a lottery. The program should have an array of 7 integers
  named winningDigits, with a randomly generated number in the range of 0 through 9 for each element in the array. The program should ask the user to enter 7 digits and should store them in a second integer array named player. The program must compare the corresponding elements in the two arrays and count how many digits match.

  For example, the following shows the winningDigits array and the player array with sample numbers stored in each. There are two matching digits, elements 2 and 4.

  WinningDigits:    7    4    9    1    3    5    0

  Player: 4    2    9    7    3    4    2

Part Two:

  Modify the lab solution so that the player numbers are entered not from the keyboard, but from the file player.dat (you will need to create this file and add 7 numbers).

What can I do better?

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

int main()
{
    const int size = 7;
    int winningDigits[size];
    int player[size];
    int count=0;
    ifstream datafile;

    datafile.open("player.dat");

    for(int i=0; i<size; i++)
    {
        winningDigits[i]=rand()%10;
        datafile >> player[i];
        if (winningDigits[i]==player[i])
        count++;
    }
/*
for(int i=0; i<size; i++)
{
    winningDigits[i]=rand()%10;
    cout << "Enter number " << i+1 << " ";
    cin >> player[i];

    if (winningDigits[i]==player[i])
        count++;
}
*/
    cout << "WinningDigits: ";
    for(int i=0; i<size; i++)
    cout << winningDigits[i] << " ";

    cout << "\nPlayer:        ";
    for(int i=0; i<size; i++)
    cout << player[i] << " ";

    cout << " \nThere are " << count << " matching elements ";
    for(int i=0; i<size; i++)
    if(winningDigits[i]==player[i])
    cout << i+1 << " ";
    cout << "\n";
}


texts:
I need to print this in Java, but I feel that my code is too big:

*
**
***
****
***
**
*

public static void main(String[] args) {

    for(int i=0; i<=3; i++) {
        for(int j=0; j<=i; j++) {
            System.out.print("*");
        }
        System.out.println();
    }

    for(int j=1; j<=3; j++) {
        for(int i=3; i>=j; i--) {
            System.out.print("*");
        }
        System.out.println();
    }
}


texts: A function to convert FASTA .txt to a dictionary

texts:
I'd like feedback on my function to convert FASTA data to a dictionary in Python. Here's an example of FASTA text:

>gi|33112219|sp|O93279.1|A4_TAKRU RecName: Full=Amyloid beta A4 protein; AltName: Full=ABPP; Short=APP; AltName: Full=Alzheimer disease amyloid A4 protein homolog; Contains: RecName: Full=Beta-amyloid protein; AltName: Full=A-beta; AltName: Full=Beta-APP; Flags: Precursor
MGETTAFVLLLVATLTRSSEIPADDTVGLLTEPQVAMFCGKLNMHINVQNGKWESDPSGTKSCLNTKEGI
LQYCQEVYPELQITNVVEANQPVSIQNWCKKGRKQCRSHTHIVVPYRCLVGEFVSDALLVPDKCKFLHQE
RMNQCESHLHWHTVAKESCGDRSMNLHDYGMLLPCGIDRFRGVKFVCCPAETEQETDSSEVEGEESDVWW
GGADPEYSENSPPTPSRATYVAGDAFERDENGDGDEDEEDDEDVDPTDEQESDERTANVAMTTTTTTTTE
SVEEVVRAVCWAQAESGPCRAMLERWYFNPKKRRCVPFLFGGCGGNRNNFESEEYCLAVCSSSLPTVAPS
PPDAVDQYFEAPGDDNEHADFRKAKESLEAKHRERMSQVMREWEEAERQAKNLPRADKKAVIQHFQEKVE
ALEQEAAGERQQLVETHMARVEALLNSRRRLTLENYLGALQANPPRARQVLSLLKKYVRAEQKDRQHTLK
HYEHVRTVDPKKAAQIRPQVLTHLRVIDERMNQSLALLYKVPSVASEIQNQIYPAAGSDCKDPVEHCVCP
QVDGLVSYGNDALMPDQAYSSAPMDMGVDGLGSIDQSFNQANTENHVEPVDARPIPDRGLPTRPVSSLKL
EEMPEVRTETDKRQSAGYEVYHQKLVFFADDVGSNKGAIIGLMVGGVVIATVIVITLVMLRKKQYTSIHH
GVIEVDAAVTPEERHLARMQQNGYENPTYKFFEQMQN

FASTA lines to be used as a key begin with '>'
FASTA lines to be used as a value follow the key line.
Repeat

Is this the best way to remove whitespace, tabs, newlines, etc? I suspect it isn't because I can't tell which escape characters my .txt has.

def txt2dict(filename, key_id, \
    replace_id_list = ['\r','\n','\w','\s','\t','\v','\f'], min_len = 1):

    """A .txt file is opened as lines. Every line containing 'key_id' is added
    to the dictionary as a key. Every line which doesn't contain 'key_id' is
    added to the dictionary as a value for the previous key."""

    dictionary = dict()
    open_file = open(filename, 'r')
    lines = open_file.readlines()
    open_file.close()
    for line in lines:
        if key_id in line:
            key_line = line
            value_line = str()
        if key_id not in line:
            value_line = value_line + line
            dictionary.update({key_line:value_line})
    copy = dictionary.copy()
    for key, value in dictionary.items():
        if len(value) <= min_len:
            del copy[key]
        else:
            for replace_id in replace_id_list:
                value = value.replace(replace_id, '')
            copy.update({key:value})
    return copy

Here's an example returned dictionary. I have truncated the keys and values.

{'>gi|33112219|sp|O93279.1|A4': 'MGETTAFVLLLVATLTRSSEIPADDTVG', '>gi|another protein': 'ANDITSSEQUENCE'}

The above dictionary could have come from the text:

>gi|33112219|sp|O93279.1|A4\n
MGETTAFVLLLVATLTRSSEIPADDTVG\n
>gi|another protein\n
ANDITS\n
SEQUENCE\n


texts:
I believe with everyone's help on Stack Overflow, I got my code safe guarded from SQL injection. I'm trying to confirm that is correct, just in case I misinterpreted the help and advice I received.

<?php
$username = "xxxx";
$password = "xxxx";
?>

xxxx

<form name="form" action="xxxx.php" method="get">
<input type="text" name="q" size="60" />
<input type="submit" name="Submit" value="Search">
</form>

<?

$var = $_GET['q'];

try {
$conn = new PDO('mysql:host=localhost;dbname=xxxx', $username, $password);
$stmt = $conn->prepare("SELECT * FROM xxxx WHERE xxxx LIKE :search");
$stmt->execute(array(':search' => '%'.$var.'%'));

$result = $stmt->fetchAll();

if ( count($result) ) {
foreach($result as $row) {
echo "
"
. $row['xxxx'] .
"	"
. $row['xxxx'] .
"	"
. $row['xxxx'] .
"	"
. $row['xxxx'] .
"	" .
"	http://www.xxx.com/" . $row['image'] . "

<form action=xxx.php method=POST>
<input type=hidden value=" . $row['id'] . " name=edit>
<input type=image src=http://www.xxx.com/images/edit.png height=30>
</form>
	      <form action=xxx.php
method=POST>
<input type=hidden value=" . $row['id'] . " name=delete>
<input type=image src=http://www.xxx.com/images/delete.png height=30>
</form>

";
}
}
else {
echo "No results found.";
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>


texts: Invoicing - calling multiple pages of Api and concatinating the results

texts:
I have the following code: It works completely as expected, but I feel there is a better way to refactor it out.

The flow is as follows:

Call the end point with 1 page
Get the total number of results.
If total count of items more than itemsPerPage.
Call the API more times till results from all pages are returned, join them together as single invoice list
Append with initial request and send back.

Do I need GetAllInvoices function? Reason it is kept there is because I believe the responsibility of calling each pages of API does not belong to main function.

public async Task<IEnumerable<Invoice>> GetAllInvoicesAsync()
{
    const string endPoint = @"foo/{0}/invoices?pageNum={1}&itemsPerPage={2}";
    const int itemsPerPage = xxx;
    InvoiceCollection response = await _apiClient
        .GetAsync<InvoiceCollection>(string.Format(endPoint, _apiClient.OrgId, 1, itemsPerPage));

    if (response?.TotalCount > itemsPerPage)
    {
        var allInvoices = (await GetAllInvoices(endPoint,response.TotalCount, itemsPerPage))
            .SelectMany(i => i.Invoices?? Enumerable.Empty<Invoice>());
        response.Invoices = (response.Invoices ?? Enumerable.Empty<Invoice>()).Concat(allInvoices);
    }

    return response?.Invoices;
}

private async Task<List<InvoiceCollection>> GetAllInvoices(string endPoint,int totalCount, int itemsPerPage)
{
    var totalPages = (int)Math.Ceiling(totalCount / (double)itemsPerPage);
    var tasks = new List<Task<InvoiceCollection>>();

    for (int currentPage = 2; currentPage<=totalPages;currentPage++)
    {
        tasks.Add(_apiClient
            .GetAsync<InvoiceCollection>(string.Format(endPoint, _apiClient.OrgId, currentPage, itemsPerPage)));
    }
    var response = new List<InvoiceCollection>(await Task.WhenAll(tasks));
    return response;
}

public class InvoiceCollection
 {
     [JsonProperty("foo")]
     public IEnumerable<Invoice> Invoices { get; set; }
     public int TotalCount { get; set; }
 }


texts: Groovy optimize method to convert JSON to map

texts:
I have this method which creates a map from a JSON request parameter. Right now I've hard-coded JSON keys to convert it to map. Can it be converted to a generic method which converts a request's JSON object to a map?

Request:

Content-Disposition: form-data; name="invoice_903"
{"id":"903","parcelId":18,"referenceId":"T44428"}`

Groovy method:

def getRequestParameterMap(def request) {
        def params = request.getParameterNames()
        def requestParamMap = [:]
        while (params.hasMoreElements()) {
            String fieldName = (String) params.nextElement();
            if (fieldName.startsWith("invoice_")) {
                JSONObject obj = JSONUtil.parseJSONObject(request.getParameter(fieldName));
                def id = obj.get("id").toString()
                def parcelId = obj.get("parcelId").toString()
                def referenceId = obj.get("referenceId").toString()
                requestParamMap["id"] = id
                requestParamMap["parcelId"] = parcelId
                requestParamMap["referenceId"] = referenceId
            }
        }
        requestParamMap
    }


texts: C++ with Qt - Conversion of angle in radians to DDD°MM′SS.FFF″ string

texts:
I had to write a function which takes an angle in radians and precision N as input and returns a string representation of its magnitude in the format DDD°MM′SS.FFF″ where FFF is fraction of the second N decimal digits long.

As conversion of a floating-point binary number to a decimal string can be tricky, I've decided to not reinvent any wheels for generation of the .FFF part, and instead use some existing ones like QString::number. Here's the code I've written:

#include <QString>
#include <QStringList>
#include <cmath>
#include <cassert>

QString angleMagnitudeToString(double angleInRad, int precision)
{
    const auto angleInDeg = std::abs(angleInRad*180/M_PI);
    auto degrees = static_cast<int>(angleInDeg);
    auto minutes = static_cast<int>((angleInDeg-degrees)*60);
    const auto seconds = ((angleInDeg-degrees)*60-minutes)*60;

    const auto secStr = QString::number(seconds, 'f', precision);
    auto secStrIntAndFrac = secStr.split('.');
    if(precision==0)
        assert(secStrIntAndFrac.size()==1);
    else
        assert(secStrIntAndFrac.size()==2);

    // Rounding on converison to string may have resulted in 60 seconds, which should be carried to minutes
    if(secStrIntAndFrac[0]=="60")
    {
        secStrIntAndFrac[0]="0";
        ++minutes;
    }
    // Carry to minutes may have resulted in 60 minutes, which should be carried to degrees
    if(minutes==60)
    {
        minutes=0;
        ++degrees;
    }

    const auto intSecStr  = secStrIntAndFrac[0].rightJustified(2, '0');
    const auto fracSecStr = precision==0 ? "" : "."+secStrIntAndFrac[1];

    return QString::fromUtf8(u8"%1°%2′%3″")
                  .arg(degrees, 3, 10, QChar('0'))
                  .arg(minutes, 2, 10, QChar('0'))
                  .arg(intSecStr+fracSecStr);
}

The code seems kludgy due to the fact that I had to "manually" process the possible carry from the seconds to minutes to degrees, but I couldn't find any better way.


texts: Creating an Entity, persisting it to the DB, and sending a welcome email

texts:
The reason I'm posting this piece of code is because I want to know how I'm supposed to properly handle the change in requirements/specifications and how I should accommodate it in unit testing.

/**
 * Create an Affiliate
 */
public function createUser($username, $password, $email, $firstName, $lastName, $ip, $notifications = null) {
    // These values are assumed to be validated prior to this function being
    // called.

    $date = new \DateTime();

    $user = new Affiliate();
    $user->setUsername($username)
         ->setPassword(AffiliateUtils::hashPassword($password))
         ->setStatus(Affiliate::STATUS_PENDING)
         ->setEmail($email)
         ->setFirstName($firstName)
         ->setLastName($lastName)
         ->setLastIp($ip)
         ->setRegisteredIp($ip)
         ->setLastDate($date)
         ->setRegisteredDate($date);

    try {
        $this->em->persist($user);
        $this->em->flush();
    } catch (DBALException $e) { return false; }

    if ($notifications != null)
        $notifications->sendAffiliateEmail("WELCOME_AFFILIATE", $user);

    return true;
}

This function is apart of an AffiliateHandler, which is responsible for the various business-logic-related operations on an Affiliate which is a database entity (active record). This function is called when a user registers for my site.

Prior to the change in requirements, the $notifications parameter was not required. The notifications class is responsible for sending a welcome email containing a link for the user to verify their email. I added a default value to the variable because the creation of the user is not dependent upon a notification and I didn't want to break/modify the unit tests associated with this particular function.

I feel like this is bad style because this function is doing too many things. Also, it creates somewhat of a dependency on the notifications class. But at the same time, if I break up the function, I need to have access to the new user created so I can send him/her the notification.

What should I be doing to handle this change without adding too much complexity to my code?


texts:
I wrote the following to check whether a string ends with a second string.

function isEndOf(origin, target) {
  return (origin.substr(target.length * -1, target.length) === target);
}

Usage:

isEndOf("A long time ago in a galaxy far, far away", "far away")

This takes a substring with the size of the target string counting from the end of the string and checks whether it's equal to the target string. Quite straightforward. However, I'm concerned about my usage of target.length * -1. This smells like using the wrong method altogether.

Is there a more idiomatic approach for writing such a basic function? Would slicing be more appropriate? The naming can probably be improved.


texts: Query to compare execution performance metrics for the three most recent months

texts:
I've been working on a semi-awkward query in that it uses a very high number of functions given its relatively small size and scope. I was hoping to get some feedback on any ways I could format or re-factor this better?

select  Name ,
        avg(TimeProcessing / 1000 + TimeRendering / 1000 + TimeDataRetrieval / 1000) as 'Current Month' ,
        isnull(count(TimeProcessing), 0) as 'Sample' ,
        min(l2.[Avg Exec Previous Month]) as 'Previous Month' ,
        isnull(min(l2.[Sample Previous Month]), 0) as 'Sample' ,
        min(l3.[Avg Exec Two Months Ago]) as 'Two Months ago' ,
        isnull(min(l3.[Sample Two Months Ago]), 0) as 'Sample'
from    marlin.report_execution_log l
        inner join      marlin.report_catalog c on l.ReportID = c.ItemID
        left outer join ( select    l2.ReportID ,
                                    avg(TimeProcessing / 1000 + TimeRendering
                                        / 1000 + TimeDataRetrieval / 1000) as 'Avg Exec Previous Month' ,
                                    count(TimeProcessing) as 'Sample Previous Month'
                          from      marlin.report_execution_log l2
                          where     TimeEnd between dateadd(MONTH, -2,
                                                            getdate())
                                            and     dateadd(MONTH, -1,
                                                            getdate())
                          group by  l2.ReportID
                        ) l2 on l.ReportID = l2.ReportID
        left outer join ( select    l3.ReportID ,
                                    avg(TimeProcessing / 1000 + TimeRendering
                                        / 1000 + TimeDataRetrieval / 1000) as 'Avg Exec Two Months Ago' ,
                                    count(TimeProcessing) as 'Sample Two Months Ago'
                          from      marlin.report_execution_log l3
                          where     TimeEnd between dateadd(MONTH, -3,
                                                            getdate())
                                            and     dateadd(MONTH, -2,
                                                            getdate())
                          group by  l3.ReportID
                        ) l3 on l.ReportID = l3.ReportID
group by l.ReportID, Name
order by Name


texts:
Due to an excercise, I've made a function that converts given string to spinal case just-like-this-one (all lower case).
I did it with two regular expressions. Can it be done with one, or generally better?

function spinalCase(str) {
  //if string is not delimited
  if(str.search(/[_\s]/) === -1){
    // insert dash before every uppercase letter
    return str.replace(/(?=[A-Z])/g , '-').toLowerCase();
  } else {
    //change delimiters to dashes
    return str.replace(/[_\s](?=[a-zA-Z])/g, '-').toLowerCase();
  }
}

edit:
variable naming was forced by excercise (wouldn't complete otherwise).
Example converted input:

"This Is Spinal Tap"

"thisIsSpinalTap"

"The_Andy_Griffith_Show"

"Teletubbies say Eh-oh"


texts:
I'm implementing a password hashing method for a website. The code below is part of the User class.

Any pointers on what I could do better?

private string GenerateSalt(int SaltLength) {
    using (var rng = new RNGCryptoServiceProvider()) {
        var salt_bytes = new byte[SaltLength];
        rng.GetNonZeroBytes(salt_bytes);
        return Convert.ToBase64String(salt_bytes);
    }
}

private string GeneratePasswordHash(string Password) {
    //create an hmac hash of the password using the pepper value as the key
    using (var hmacsha = new HMACSHA512(ConvertStringToBytes(ConfigurationManager.AppSettings["PasswordHashPepper"]))) {
        byte[] initial_hash = hmacsha.ComputeHash(ConvertStringToBytes(Password));

        //generate a key value using pbkdf2 that will serve as the password hash
        using (var pbkdf2 = new Rfc2898DeriveBytes(initial_hash, ConvertStringToBytes(this.Salt), int.Parse(ConfigurationManager.AppSettings["PasswordHashWorkFactor"]))) {
            return ConvertBytesToString(pbkdf2.GetBytes(128));
        }
    }
}

private byte[] ConvertStringToBytes(string conversionString) {
    byte[] bytes = new byte[conversionString.Length * sizeof(char)];
    System.Buffer.BlockCopy(conversionString.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

private string ConvertBytesToString(byte[] conversionBytes) {
    char[] chars = new char[conversionBytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(conversionBytes, 0, chars, 0, conversionBytes.Length);
    return new string(chars);
}

public void SetNewPassword(string NewPassword) {
    this.Salt = GenerateSalt(64);
    this.PasswordHash = GeneratePasswordHash(NewPassword);
}

public bool ValidatePassword(string AttemptedPassword) {
    return (GeneratePasswordHash(AttemptedPassword) == this.PasswordHash);
}


texts: Passing value/data from a page to another page using Vue.js and Typescript

texts:
I have a markdown editor in View A which is showing the result in the current View. I'm trying to pass a result to another page which is View B. In the View A, a button exist to share the markdown result to View B. I'm using texarea for typing text and I have vue-markdown which converts the textarea input to markdown result. My plan is to pass the same vue-markdown result into View B.
View A
  <template>

     <form id="add-form" >

            <button class="btn-share"@click="shareToPublic()">
            Share To View B</button>

            <input type="text" v-model:value="saveNotes.title">

            <textarea v-model:value="saveNotes.text" name="content"></textarea>
      </form>
            <vue-markdown :source="saveNotes.text" >
            </vue-markdown>

</template>

View B
<template>

      {{ View A markdown result }}

</template>


texts: Create quantile slices from dataframe columns

texts:
I have the following, working code:

import pandas as pd

hld_per = 12    # Holding period in months
quantiles = 10  # Number of bins/buckets; Deciles, use 10; Quartiles, use 4; etc.
permnos = pd.read_csv('Ranks.csv')
my_headers = list(permnos.columns)
total_cols = len(permnos.columns)

pntls = permnos.copy(deep=True)

# Compute the percentile of each element based on position (each column in permnos is sorted best-to-worst)
for i in range(total_cols):
    for j in range(pntls.iloc[:,i].count()):
        pntls.iloc[j,i] = (j+1)/pntls.iloc[:,i].count()

# Create slices by column based on pntls values and choice of quantiles.
# Write resultant portfolios to files (# of portfolios = # in quantile).
for i in range(quantiles):
    ports = []
    for j in range(total_cols-(hld_per-1)):
        permlist = []
        for k in range(hld_per):
            slc = (pntls.iloc[:,j+k] > i/quantiles) & (pntls.iloc[:,j+k] <=(i+1)/quantiles)
            col_slice = permnos[slc].iloc[:,j+k].tolist()
            permlist += col_slice
        ports.append(permlist)

    matrix = pd.DataFrame(ports).T
    matrix.columns = my_headers[0:len(matrix.columns)]
    matrix.to_csv("portstst2_" + str(i+1) + ".csv", sep=',', index=False, header=True)

I built this code as a solution to a question I posted on stackoverflow in this thread.  While it works, it is not very fast.  Additionally, as someone new to Python, I imagine there are much better ways to write this.

The purpose of this code is to read in a csv file which is organized as follows:  Column headers are dates in the format YYYYMMDD, descending monthly moving left to right (e.g. the first column is 20131231 followed by 20131130,etc).  The data in the rows are identifiers which are sorted from "best" to "worst" in a separate program.  The rows are of varying lengths, and the number of rows in each column determines an identifier's rank/percentile/bucket for the month/column.

The data in each column is broken into quantiles using the values calculated in the pntls dataframe.  An example:  If hld_per is 3 and quantiles is 4, the code takes the top 25% of identifiers in column 0 of permnos and places them in column 0 of the list ports.  The top 25% of identifiers in column 1 of permnos is then appended to ports.  Then the top 25% of identifiers in column 2 are appended to ports.  This will populate the first column of matrix.  The code next follows the same procedure on columns 1, 2, and 3 of permnos to populate the second column of matrix.  And so forth.  A csv file is written for each quantile.

My Specific Questions

As noted in the stackoverflow post, I initially tried to approach this using qcut(). I was unable to adapt the suggested solution to work, but perhaps it is a better method than my solution.  So question 1 is: Is there a better method to generate my slices used in the second embedded for-loop (qcut() or otherwise)?  The primary requirement is that the slices within a column are of roughly the same size for each quantile.

Question 2: Should I use a second dataframe (in this case, pntls) to do my conditioning, or should I append the calculations in the first loop to permnos?

Question 3: Given a method to determine the slices, is my second for-loop an efficient way to create ports and matrix?

Question 4: For my data, the dates that are the column headers of Ranks.csv change often.  As such, I prefer to use selection by position as opposed to selection by label.  However, most of the posts I found when writing this code use selection by label.  Is there any reason to avoid selection by position/prefer selection by label?

Finally, any other points/critiques of my code are greatly appreciated.  Please point out anything I've done in an inefficient manner, especially with regards to speed.