texts:
I have these two classes and they should remain separate classes, but I have a feeling that this could be implemented more efficiently and with less duplicate code. After googling around I still didn't figure a better way, so perhaps someone here could point me out. Ideally I want to get tick() method from Clock and just add alarm to it and also get set_time() method with additional attributes for setting the alarm time.
class Clock:

def __init__(self, hours, minutes, seconds):
    self.set_time(hours, minutes, seconds)

def set_time(self, hours, minutes, seconds):
    if hours < 0:
        self.hours = 0
    elif hours > 23:
        self.hours = 23
    else:
        self.hours = hours

    if minutes < 0:
        self.minutes = 0
    elif minutes > 59:
        self.minutes = 59
    else:
        self.minutes = minutes

    if seconds < 0:
        self.seconds = 0
    elif seconds > 59:
        self.seconds = 59
    else:
        self.seconds = seconds

def tick(self):
    while True:
        print(str(self.hours).zfill(2), ":", str(self.minutes).zfill(2), ":", str(self.seconds).zfill(2), sep="")
        self.seconds += 1
        time.sleep(1)
        if self.seconds == 60:
            self.seconds = 0
            self.minutes += 1
            if self.minutes == 60:
                self.minutes = 0
                self.hours += 1
                if self.hours == 24:
                    self.hours = 0

class AlarmClock(Clock):

def __init__(self, hours, minutes, seconds, alarm_hr, alarm_min, alarm_sec):
    super().__init__(hours, minutes, seconds)
    self.set_alarm(alarm_hr, alarm_min, alarm_sec)

def set_alarm(self, alarm_hr, alarm_min, alarm_sec):
    if alarm_hr < 0:
        self.alarm_hr = 0
    elif alarm_hr > 23:
        self.alarm_hr = 23
    else:
        self.alarm_hr = alarm_hr

    if alarm_min < 0:
        self.alarm_min = 0
    elif alarm_min > 59:
        self.alarm_min = 59
    else:
        self.alarm_min = alarm_min

    if alarm_sec < 0:
        self.alarm_sec = 0
    elif alarm_sec > 59:
        self.alarm_sec = 59
    else:
        self.alarm_sec = alarm_sec

def alarm(self):
    while True:
        print(str(self.hours).zfill(2), ":", str(self.minutes).zfill(2), ":", str(self.seconds).zfill(2), sep="")
        self.seconds += 1
        time.sleep(1)
        if self.seconds == 60:
            self.seconds = 0
            self.minutes += 1
            if self.minutes == 60:
                self.minutes = 0
                self.hours += 1
                if self.hours == 24:
                    self.hours = 0
        if self.hours == self.alarm_hr and self.minutes == self.alarm_min and self.seconds == self.alarm_sec:
            print("ALARM ALARM ALARM ALARM ALARM!!!!")
            break


texts:
I built a webscraper to take all the historical data from CoinMarketCap.com. A site which records historical data for cryptocurrencies which unfortunately does not have a feature to download all of their data in one convenient file.

It works but it's somewhat slow and probably could be designed better. I'm self taught so I'd love some advice on how to improve the code's functionality, speed, and readability. Thanks a lot in advance.

def scrape_coin_marketcap():
    print('Loading Packages...')
    from bs4 import BeautifulSoup
    import requests
    import pandas as pd

    print('Scraping links...')
    #Download HTML of links to historical CoinMarketCap data
    url = 'https://coinmarketcap.com/historical/'
    r  = requests.get(url)
    data = r.text
    soup = BeautifulSoup(data,'html.parser')

    #scrape a list of links to historical data
    raw_links = []
    for link in soup.find_all('a'):
        raw_links.append(link.get('href'))

    #Remove non-historical links
    historical_links = []
    for link in raw_links:
        if "201" in str(link):
            historical_links.append('https://coinmarketcap.com' + link)

    print('Scraping Data....')

    #Scrape historical data from each time period
    master_df = pd.DataFrame()
    num_links = len(historical_links)
    print(str(num_links) + " dates to be scraped...")
    for link in historical_links:
        try:
            res = requests.get(link)
            soup = BeautifulSoup(res.content, 'lxml')
            table = soup.find_all('table')[0]
            df = pd.read_html(str(table))[0]
            date = str(soup.find_all('h1')[0])[51:-5]
            df['date'] = date
            master_df = master_df.append(df)
            print("    Scraping: " + str(date))
        except:
            print("    ERROR Scraping: " + str(link))

    print('Saving to disk...')
    master_df.to_csv('CoinMarketCap.csv', index = False)
    print("Completed.")

if __name__ == "__main__":
    scrape_coin_marketcap()


texts: Writing a proper (and simple) auth/login class in PHP

texts:
How to write and design a simple (but still proper and secure) login class for PHP?

Currently I'm checking whether there is a login request (user entered data into login form) or the session is already existent and contains $_SESSION['authenticated'] == TRUE;. If both checks failed the user is not (properly) logged in. In code:

class Auth {
    private function __construct() {
        // new login
        if(isset($_POST['login'], $_POST['username'], $_POST['password']) && validCSRFToken()) {
            $user = $_POST['username'];
            $password = $_POST['password'];

            if(($row = querySingle('
               SELECT `id`, `password`
               FROM `users` u
               WHERE `nick` = "?"',
               $user)))
               // Crypt::hash checks the salted password
               && Crypt::hash($password, $row['password'])) {
                // credential change (guest -> user) regenerate session id
                session_regenerate_id(TRUE);

                $_SESSION['authenticated'] = TRUE;
                $_SESSION['userid'] = $row['id'];
                $_SESSION['user'] = $user;

                // prevent 'your browser has to re-send some data to display this page'
                redirect($_SERVER['REQUEST_URI']);
            } else {
                $this->logout();
                throw new AuthException('login failed. wrong user/password');
            }
        } else if($_SESSION['authenticated'] && $_SESSION['userid'] > 0 && !empty($_SESSION['user'])) {
            // user already logged in, nothing to see here, move on
        } else {
                    // not logged in!
                    throw new AuthException('not logged in. please login');
        }
    }

    public function logout() {
        $this->authenticated = FALSE;
        $this->user = '';
        $this->userid = 0;

        $this->session->destroy();
        $this->session->regenerate_id(TRUE);
    }
}

An object of the Auth class has to be created on every page that requires authentication from users:

try {
  $auth = new Auth();

  /*
   * rest of the page
   */

} catch(AuthException $ex) {
  // something went wrong during login
  displayError();
  displayLoginForm();
  exit; // halt further execution of script
}

Is this the right way to do it? Do you see anything (seriously) flawed with this approach? Can users impersonate other users? Users getting logged out randomly? Users getting logged out by malicious attackers? (although CSRF checks are in place). I'm afraid, I might be missing something obvious.

Any improvements apreciated, thanks!

(Please don't suggest using a PHP framework like CodeIgniter, Zend Framework, Kohana, etc.)


texts:
New to Rust and would like some clarification on idiomatic and readable use of Result and Error types. Here I'm simply connecting to a database using Diesel. In my opinion, the use of match and Boxing error makes be feel like there's a more concise but still readable way to do this.

fn establish_database_connection() -> Result<PgConnection, Box<std::error::Error>> {
    dotenv().ok();

    let database_url = match env::var("DATABASE_URL") {
        Ok(url) => url,
        Err(err) => return Err(Box::new(err)),
    };

    match PgConnection::establish(&database_url) {
        Ok(connection) => Ok(connection),
        Err(err) => Err(Box::new(err)),
    }
}


texts:
I have console application that sends and process XML data. I have created a fault mechanism that the connection drops. I go in a "fault" mode. And try to reconnect to my server. I'm sending keepalives and so is the server. When I'm not receiving any keepalives and any others messages in a timespan of 2 minutes the programs enters a fault mode. Is this the correct method of doing such operations?

This is my watchdog class (reduced code).

internal class Watchdog
{
    private Timer _timer = new Timer(1000);
    public bool Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnStatusChanged(new CustomEventArgs(value));
        }
    }

    protected virtual void OnStatusChanged(CustomEventArgs e)
    {
        var handler = StatusChanged;
        if (handler != null) handler(this, e);
    }

    public void Stop()
    {
        _timer.Enabled = false;
    }

    public void SetStatus()
    {
        _latestAction = DateTime.Now;
    }

    public void SetManually()
    {
        _latestAction = DateTime.Now.AddDays(-1); //fool the timer
        Status = true;
    }

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if ((DateTime.Now - _latestAction) > TimeSpan.FromSeconds(22))
        {
            Status = true;
        }
        if ((DateTime.Now - _latestAction) < TimeSpan.FromSeconds(22))
        {
            Status = false;
        }
    }
}

This is other class where I call the handler. And try to reconnect.

    void _watchdog_StatusChanged(object sender, CustomEventArgs e)
    {
        if (e.Status) //no message has been processed in two minutes or nothing can be sent, something can be wrong
        {
            _watchdog.Stop(); //stop timer otherwise this method has not enough time to execute and will be recalled
            Console.WriteLine(DateTime.Now + " Error mode initiated!");
            if (!Connection.Connected)
            {
                ((IDisposable) Connection).Dispose();
                openConnection(); //try to reopen conn
                if (Connection.Connected)
                {
                    initialize(); //init all settings
                    _watchdog.SetStatus(); //set live tick
                }
            }
            _watchdog.Start();
        }
        else //fault has been restored.
        {
            Console.WriteLine(DateTime.Now + " Error has been resolved!");
        }
    }

And the event handlers where I receive messages I set a live tick.

    private void _tcpReader_AlarmResponseComplete(object sender, CustomEventArgs e)
    {
        Console.WriteLine("alarmresponse received");
        _processAlarmResponsesToDatabase.Add(e.AlarmResponse);
        _watchdog.SetStatus();
    }

And where I try to send a message

    private void send(string msg) //TODO: must be set to private is now so for testing purpose public
    {
        if (Connection.Connected)
        {
            if (!_tcpReader.IsStopped)
            {
                _writer.Write(msg);
                _writer.Flush();
            }
            else
                Console.Error.WriteLine(
                    "Unable to send message to the server, a request has been made to terminate the connection.");
            _watchdog.SetStatus(); //give live tick to watchdog
        }
        else
        {
            Console.Error.WriteLine("Unable to send message, not connected to the server.");
            _watchdog.Stop(); //the next statement generates an event and the timer would generate the same events wich causes to many events
            _watchdog.SetManually(); //set manually that connection has been terminated
        }
    }


texts:
Honestly, I'm doing a practice and get blocked. Problem link.

The problem is simple, given a string, calculate the number of max length palindromes (Any substring is valid, which means you can take any chars you want and reorder them as you want). Return the result modulo 1000000007.

For example, given amim, the answer is 2 (mim and mam).

Full Code

#!/bin/python3

import math
import os
import random
import re
import sys
from itertools import permutations
from functools import lru_cache

# Complete the initialize function below.
def initialize(s):
    # This function is called once before all queries.
    s = [ord(i) - 97 for i in s]
    results = [[0] * 26]
    for i, v in enumerate(s):
        result = results[i].copy()
        result[v] += 1
        results.append(result)
    return results

def count(s):
    result = [0] * 26
    for i in s:
        result[i] += 1
    return result

factorial = lru_cache(None)(math.factorial)

p = 1000000007

pow = lru_cache(None)(pow)

# Complete the answerQuery function below.
def answerQuery(l, r):
    # Return the answer for this query modulo 1000000007.
    counted1 = counted_list[l - 1]
    counted2 = counted_list[r]
    counted = [counted2[i] - counted1[i] for i in range(26)]
    left = 0
    total = 0
    divide = []
    for temp in counted:
        left += temp & 1
        total += temp >> 1
        divide.append(temp >> 1)
    total = factorial(total)
    total = total % p
    for i in divide:
        temp = factorial(i)
        temp = pow(temp, p - 2, p)
        total = total * temp
    result = total * (left or 1)
    return result % p

if __name__ == '__main__':
    s = input()

    counted_list = initialize(s)
    q = int(input())

    for q_itr in range(q):
        lr = input().split()

        l = int(lr[0])

        r = int(lr[1])

        result = answerQuery(l, r)

        print(result)

The code above can pass #0~#21 testcases and will fail in #22 due to timeout. (Just copy it to Problem link page given at the top)

As #22 testcase is very huge, I cannot post it here. So here is the link:

https://files.fm/u/mekwpf8u

If I can use numpy to rewrite this function, I think it will be better. But I cannot, I can only use the standard libs.

update

I use another customized factorial function but exceed memory usage limitation :/ But it really reduces the total time cost.

factorial_table = [1, 1]
def factorial(n):
    if n < len(factorial_table):
        return factorial_table[n]

    last = len(factorial_table) - 1
    total = factorial_table[last]
    for i in range(last + 1, n + 1):
        total *= i
        factorial_table.append(total)

    return total


texts: Using $q in Angular JS to pass navigator geo JSON from factory to controller

texts:
This code is used to get the users location and deliver it as a resource to the controller. The aim is to have this data shared across multiple controllers in the application. So far this does deliver the data as a parameter of the then() method on the promise.  Is this pattern a suitable way of sharing a resource which is delivered through a promise? Any feedback would be greatly appreciated.

angular.module('geolocation', [])
.factory('geolocation', function ($q, $window) {
    return {
        getLocation: function () {
            var deferred = $q.defer();

            $window.navigator.geolocation.getCurrentPosition(function(position){
                deferred.resolve(position);
            });

            return deferred.promise;
        }
    };
});

angular.module('nearestLocationCtrl', [
    'geolocation'
])
.controller('NearestLocationCtrl', ['$scope', 'geolocation', function ($scope, geolocation) {
    geolocation.getLocation().then(function (data) {
        console.log(data);
    });
}]);


texts: Converting multi-dimensional array into row data


texts: jQuery score card form to determine pass or fail

texts:
I have made a simple scorecard form which uses jQuery to automatically calculate the score of submissions depending on field values. Some fields are "critical" which means if they are a fail they automatically fail.

You can see a jsFiddle example to get a better understanding. I have tried to make the code as efficient as possible but would welcome peoples opinions on what improvements can be made.

//disable individual radios by#
$("#edit-submitted-calc-verification-completed-idv-correctly-1, #edit-submitted-calc-summary--action-2-notes-1").attr('disabled',true);

$("#webform-component-calc select, #webform-component-calc :radio").change(function(){

   var $score = 0;
   var $fails = 0;
   var $critFails = 0;

    $('select option:selected, :radio:checked').each(function(){

        var $thisVal = $(this).val();
        var $split = $thisVal.split('_');
        var $string = $split[0];
        var $points = parseInt($split[1],10);

      $(this).parents('tr').find('.webform-grid-option').removeClass('pass fail');

      if ($string == 'fail' || $string == 'critical') {

          $(this).parents('.webform-grid-option').addClass('fail');

          if($string == 'fail') {
              $fails += 1;
          }
          if($string == 'critical') {
              $critFails += 1;
          }
      }

      else {

          $(this).parents('.webform-grid-option').addClass('pass');
           if($string == 'pass' || $string == 'na') {
              $score += $points;
           }
        }
    });

    var $finalScore = $score;
    if($critFails > 0){
         var $finalScore = 0;
       }

    var $summary = 'Final Call score: '+$finalScore+'% with '+$fails+' Fails / '+$critFails+' Critical Fails';

    //alert($summary);
    $('#edit-submitted-calc-number-of-fails').val($fails);
    $('#edit-submitted-calc-call-score').val($score);
    $('#edit-submitted-calc-critical-failures-number-of-critial-fails').val($critFails);
    $('#edit-submitted-calc-critical-failures-final-score').val($finalScore);
    $('#edit-submitted-calc-summary').val($summary);

});


texts:
This code is Express NodeJS code that handles post registration .post action where the user must select a custom username. The username is validated, and if valid, the database is updated. If not, the user is redirected to the page with an error message so he/she can try again.

I would like to know if you would refactor this code with the extract method, that is extracting some functionality into their own extracted method to improve fragmentation of this code and readability.

// This route is only used for newly registered facebook user so they can supply a custom userName.
users_router.route( "/userName" )

    // Process the customUserName recording.
    .post( function( req, res ) {
        // Receive data from the customUserName form field.
        let form = new forms.IncomingForm()
        form.parse( req, function( err, fields, files ) {

            let userModel = new User( fields ).userModel() // Instantiate current user
            let validationResults = new Validation( userModel, fields ).validationResults()

            // There is no error: Update the customUserName field in the database.
            if ( validationResults === g.error.no ) {
                let properties: string = req.session[ "userModel" ].id.content // Session holds copy of model
                let customUserNameField = fields[ "custom_user_name" ]
                let customUserNameData = { "facebookId": properties, "customUserName": customUserNameField }

                customUserNameDbUpdate( customUserNameData, function() {
                    console.log( "Custom user name was added" )
                    res.end( "ok" ) // TODO: redirect
                })
            }

            // There are errors: redirect back to user name selection page with error message.
            if ( validationResults !== g.error.no ) {
                let errorMessage = validationResults[ "custom_user_name" ].errorMessage

                res.render( "apps/users/views/chooseUsername.handlebars", { // TODO: should not redirect to template
                    error: errorMessage
                })
            }
        })
    })


texts: SpamAssassin checker via Python (using spamd)

texts:
I needed to implement SpamAssasin directly inside my Python code (to control the entire flow) so I implemented a client using spamd (the SpamAssassin daemon) that I connect via socket. Here's the code, with an example of how to use it.

If you have any suggestions on how to improve it (keeping exotic libraries out is better), I'm happy to get your opinion!

Note: I haven't find something similar, that's why I did it. I used a lot of code from https://github.com/slimta/python-slimta/blob/master/slimta/policy/spamassassin.py though.

# -*- config:utf-8 -*-

import socket, select, re, logging
from io import BytesIO

divider_pattern = re.compile(br'^(.*?)\r?\n(.*?)\r?\n\r?\n', re.DOTALL)
first_line_pattern = re.compile(br'^SPAMD/[^ ]+ 0 EX_OK$')

# @see https://github.com/slimta/python-slimta/blob/master/slimta/policy/spamassassin.py
class SpamAssassin(object):
    def __init__(self, message, timeout=3):
        self.score = None
        self.symbols = None

        # Connecting
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.settimeout(timeout)
        client.connect(('127.0.0.1', 783))

        # Sending
        client.sendall(self._build_message(message))
        client.shutdown(socket.SHUT_WR)

        # Reading
        resfp = BytesIO()
        while True:
            ready = select.select([client], [], [], timeout)
            if ready[0] is None:
                # Kill with Timeout!
                logging.info('[SpamAssassin] - Timeout ({0}s)!'.format(str(timeout)))
                break

            data = client.recv(4096)
            if data == b'':
                break

            resfp.write(data)

        # Closing
        client.close()
        client = None

        self._parse_response(resfp.getvalue())

    def _build_message(self, message):
        reqfp = BytesIO()
        data_len = str(len(message)).encode()
        reqfp.write(b'SYMBOLS SPAMC/1.2\r\n')
        reqfp.write(b'Content-Length: ' + data_len + b'\r\n')
        reqfp.write(b'User: cx42\r\n\r\n')
        reqfp.write(message)
        return reqfp.getvalue()

    def _parse_response(self, response):
        if response == b'':
            logging.info("[SPAM ASSASSIN] Empty response")
            return None

        match = divider_pattern.match(response)
        if not match:
            logging.error("[SPAM ASSASSIN] Response error:")
            logging.error(response)
            return None

        first_line = match.group(1)
        headers = match.group(2)
        body = response[match.end(0):]

        # Checking response is good
        match = first_line_pattern.match(first_line)
        if not match:
            logging.error("[SPAM ASSASSIN] invalid response:")
            logging.error(first_line)
            return None

        self.symbols = [s.decode('ascii').strip() for s in body.strip().split(',')]

        headers = headers.replace(' ', '').replace(':', ';').replace('/', ';').split(';')
        self.score = float(headers[2])

    def get_score(self):
        return self.score

    def get_symbols(self):
        return self.symbols

    def is_spam(self, level=5):
        return self.score is None or self.score > level

And here's how to use it:

from spamassassin import SpamAssassin

# message contains the DATA part
assassin = SpamAssassin(message)
if assassin.is_spam():
    print "The received message is considered spam with a score of {0}".format(assassin.get_score())

That's all :) Let me know


texts:
I solved the following problem:

You will be given a mathematical string and your task will be to remove all braces as follows:
solve("x-(y+z)") = "x-y-z"`

solve("x-(y-z)") = "x-y+z"`

solve("u-(v-w-(x+y))-z") = "u-v+w+x+y-z"`

solve("x-(-y-z)") = "x+y+z"`

There are no spaces in the expression. Only two operators are given: "+" or "-".

This is the solution I came up with:
function removeAt(s, index) {
    if (index === s.length - 1) {
        return s.slice(0, -1)
    }
    return s.slice(0, index) + s.slice(index + 1);
}

function insertAt(s, index, str) {
    return s.slice(0, index) + str + s.slice(index);
}

function replaceAt(s, index, chr) {
    if (index > s.length - 1) return s;
    return s.slice(0, index) + chr + s.slice(index + 1);
}

function reverseSigns(s, start, end) {
    for (var i = start; i < end; i++) {
        if (s[i] === '-') {
            s = replaceAt(s, i, '+');
        } else if (s[i] === '+') {
            s = replaceAt(s, i, '-');
        }
    }
    return s;
}

function solve(s) {
    //Get the position of the parenthesis
    var Close = 0, Open = -1;
    while (s[Close] !== ')' && Close < s.length) {
        if (s[Close] === '(') {
            Open = Close;
        }
        Close++;
    }
    //Check to see if there is any parenthesis
    if (Open !== -1) {
        //Insert sign before if there is none
        if (s[Open + 1] !== '+' && s[Open + 1] !== '-') {
            s = insertAt(s, Open + 1, '+');
            //'Close' parenthesis has changed --> +1 right
            Close++;
        }
        //Check to see if a sign has to be replaced
        if (s[Open - 1] === '-') {
            s = reverseSigns(s, Open + 1, Close - 1);
        }
        //Remove the parenthesis
        s = removeAt(s, Close);
        s = removeAt(s, Open);
        //Remove the sign before paranthesis
        if (s[Open - 1] === '-' || s[Open - 1] === '+') {
            s = removeAt(s, Open - 1);
        }
        //Recursive call
        return solve(s);
        //return s;
    }
    //Remove unnecessary +
    if (s[0] === '+') {
        s = removeAt(s, 0);
    }
    return s;
}

I was wondering if my code could be improved.


texts:
To find the row  with max zero Matrix will have either 0 or 1 in sorted manner.

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[][] inp=new int[][]{
                            {0,0,0,1,1},
                            {0,1,1,1,1},
                            {0,0,1,1,1},
                            {0,0,0,0,1}
                            };
    int j=0,rownum=0;
    for(int i=0;i<4;i++){
        while(j<=4&&inp[i][j]!=1){
            rownum=i;
            j++;
        }
    }
    System.out.println("Row "+(rownum+1)+" has Max zero");

}

Complexity of the  above program is \$O(m+n)\$ where \$m\$ is row size and \$n\$ is column size.

If any better approach is there then please post in this


texts:
Suppose you have two lists:

One is a "dictionary", a list of words
The other is "documents", a list of documents (which in turn, are strings)

I would check whether a dictionary's word is within a document.

# DOCUMENTS
doc1 = "My sister likes to have sugar, but not my father."
doc2 = "Doctors suggest that driving may cause increased stress."

documents = [doc1, doc2]

# DICTIONARY
dictionary = ["doctors", "sister", "like"]

# CHECK DOCUMENT WORDS WITHIN DICTIONARY
for word in dictionary:
    for doc in documents:
        if word in doc:
            print "\n\n\nWord:",
            print word,
            print "in document:",
            print doc

What's a more "pythonic" way?


texts:
import random
import operator
import pickle

classname = ""
while True:
    classpick = input("Enter class name (\"A,B,C\") ").upper()
    try:
        if classpick in ["A","B","C"]:
            classname = "class"+classpick+".txt"
            break
        else:
            raise ValueError
    except ValueError:
        print("Invalid value. Please enter a letter A,B or C.")
        break

with open(classname + ".txt", "rb") as handle:
    data = pickle.load(handle)

def test():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, num1)

    ops = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
    }

    ops_keys = list(ops.keys()) ##=> ['+', '*', '-']
    ops_key_choice = random.choice(ops_keys)  #e.g. '+'
    operation = ops[ops_key_choice]  #e.g. operator.add

    correct_result = operation(num1, num2)
    question = ("Q{}. What is {} {} {}?".format(i+1,num1, ops_key_choice, num2))
    print(question)
    while True:
        try:
            user_answer= int(input("Answer: "))
        except ValueError:
            print ("That is not a valid answer")
            print (question)
        else:
            break

    if user_answer != correct_result:
        print ("Incorrect. The right answer is {}".format(correct_result))
        return False
    else:
        print("Correct!")
        return True
###
def sort_dict(data):
    while True:
        sortpick = str(input('''Enter a number to sort by:
                         \n1. Alphabetically
                         \n2. Highest Score
                         \n3. Highest Average Score'''))
        try:
            if sortpick in ["1","2","3"]:
                break
            else:
                raise ValueError
        except ValueError:
            print("Invalid value. Please enter a number in the range of 1-3.")
        break

    if sortpick == "1":    #Alphabetical
        for x, y in sorted(data.items()):
            print(x,y)

    elif sortpick == "2":    #Highest Score
        for k,v in sorted(((max(data[k]), k) for k in data), reverse=True):
            print('{} : {}'.format(v,k))

    else:   #Highest Average Score
        sort = sorted(data, key=lambda k: sum(data[k]) / len(data[k]), reverse=True)
        for i in sort:
            print("{} : {}".format(i,
                                   round(sum(data[i])/len(data[i]),1 ) ))

username = input("What is your name? ").upper()
print("Hi {}! Welcome to the Primary School Arithmetic quiz...".format(username))

correct_count = 0
question_count = 10

for i in range(question_count):
    if test():
        correct_count +=1

if username in data:
    if len(data[username]) == 3:
        del(data[username][0])
        data[username].append(correct_count)
    else:
        data[username].append(correct_count)
else:
    data[username] = [correct_count]

print("{}: You got {}/{} questions correct. {}".format(
    username,
    correct_count,
    question_count,
    'Great job!' if (correct_count>7) else 'Better luck next time...'
))

with open(classname+".txt", "wb") as handle:
    pickle.dump(data, handle)

print("{}: {}".format(k, v) for k, v in data.items())    #prints whole dict
for k, v in data.items():
    print("{}: {}".format(k, v))
while True:
    try:
        sort_or_not = input("Would you like to sort the class results?? Y/N").upper()
        if sort_or_not.isalpha() == True:
            break
        else:
            raise ValueError
    except ValueError:
        print ("That is not a valid input")
    break

if sort_or_not == "Y":
    print("")
else:
    quit()

sort_dict(data)

The code above is designed to ask users a set of 10 randomized maths questions then save the score to a file and sort the scores.

How can I make this code more efficient?


texts:
I'll be honest this isn't all my code, I have made some tweaks to bring it more up to date. The main goal is to do some browser detection and add classes to whichever element we want. I am simply looking for your input regarding the code.

// Detect browser and add appropriate classes to calling element, typically 'html'
// Usage: $('html').add_browser_classes();
// Test function: alert('html classes: ' + jQuery('html').attr('class'));

(function($) {
    $.fn.add_browser_classes = function() {

        // Begin with the negation classes

        $(this).addClass('javascript not-webkit not-firefox not-opera not-ie');

        if (/Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)) {
            $(this).removeClass('not-webkit').addClass('webkit chrome');
        } else if (/Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor)) {
            $(this).removeClass('not-webkit').addClass('webkit safari');
        } else if (/Firefox/.test(navigator.userAgent)) {
            $(this).removeClass('not-firefox').addClass('firefox');
        } else if (window.opera && window.opera.buildNumber) {
            $(this).removeClass('not-opera').addClass('opera');
        } else if (Function('/*@cc_on return /^10/.test(@_jscript_version) @*/')()) {
            $(this).removeClass('not-ie').addClass('ie ie10');
        } else if (!document.querySelector) {
            $(this).removeClass('not-ie');
            $(this).addClass('ie ie7 lt-ie11 lt-ie10 lt-ie9 lt-ie8');
        } else if (!document.addEventListener) {
            $(this).removeClass('not-ie');
            $(this).addClass('ie ie8 lt-ie11 lt-ie10 lt-ie9');
        } else if (!window.atob) {
            $(this).removeClass('not-ie');
            $(this).addClass('ie ie9 lt-ie11 lt-ie10');
        } else if (!document.__proto__) {
            $(this).removeClass('not-ie');
            $(this).addClass('ie ie10 lt-ie11');
        } else if (!!(navigator.userAgent.match(/Trident/) && !navigator.userAgent.match(/MSIE/))){
            $(this).removeClass('not-ie');
            $(this).addClass('ie ie11');
        }
        //The last condition checks to see if the browser is IE 11 or greater
        //If we need to test for specific versions of IE 11 and above replace the above else if conditional to this -
        //!!(navigator.userAgent.match(/Trident/) && navigator.userAgent.match(/rv[ :]11/))
        //if it isnt obvious change the 11 in the conditional to the version you are looking for
        return this;
    };
})(jQuery);


texts:
I'd like to see if there's any code reuse I'm missing, or anything else that can be rewritten in a better way, but always following the same data structures (without adding more classes or using the C++ list implementation).

Node* merge(Node* list1, Node* list2){
    if (list1 == nullptr){
        return list2;
    }
    else{
        if (list2 == nullptr){
            return list1;
        }
        else{
            Node* newList = nullptr;
            if (list1->data <= list2->data){
                newList = list1;
            }
            else{
                newList = list2;
            }
            while (list1->next != nullptr) {
                if (list1->next->data > list2->data){
                    Node* aux = list1->next;
                    list1->next = list2;
                    list2 = aux;
                }
                list1 = list1->next;
            }
            if (list1->next == nullptr){
                list1->next = list2;
            }
            return newList;
        }
    }
}


texts:
I've been studying Java for some days and I'm just now starting to make some simple programs, I'd like to know if there's any 'noob' mistakes or habits that I could avoid.

In other words: how could my code be more streamlined to Java?

My code:

import java.util.Scanner;

public class Main
{
    private static String reverse_string(String my_string)
    {
        String reversed_string = "";
        for(int j = my_string.length() - 1; j >= 0; j--)
        {
            reversed_string = reversed_string + my_string.charAt(j);
        }
        return reversed_string;
    }

    public static void main(String[] args)
    {
        System.out.print("Insert a 'String': ");

        Scanner input = new Scanner(System.in);
        String user_string = input.nextLine().toLowerCase().replace(" ", "");

        if (user_string.equals(reverse_string(user_string)))
            {
                System.out.println("It is a palindrome.");
            } else
            {
                System.out.println("It is not a palindrome.");
            }
    }
}

I believe there are already other alternatives to my  reverse_string function, hence the 'reinventing the wheel' tag.


texts: Implicitly passing client context to services in Node.js

texts:
In node.js I have been trying to find a way to pass client context from the Express routes into the services without every service function to have a context. By context I mean an object with user type, ID, possible queries passed on the request, etc.

I see four possible ways to do this, keep the context as argument of services (already more or less how it is done), refactor all services to only receive the exact data they need (a lot of work and have to take into account that other services might be getting called passing the context), instantiate services with the context (I already pass mongoose model on initializing services, seemed weird to always create new instances) or what I am trying to do, implicitly pass the context object between services with a Service base class like:

class Service {
  call(service, context = null) {
    service._context = context || this._context;
    return service;
  }

  callWith(context) {
    this._context = context || this._context;
    return this;
  }
}

class FooService extends Service {
  constructor(model) {
    this.model = model;
  }

  async foo(bar) {
    // Calls other service and passes the context object to it
    bar.test = await this.call(barService).test(bar);
    return await this.model.foo(bar);
  }
}

// Somewhere else, defining my Express routes:
app.route(`foo/`).get(async (req, res, next) => {
  try {
    const limit = parseInt(req.query.limit, 10);
    const data = await fooService.callWith(req.context)
      .foo({ prop: req.query.property, limit: !isNaN(limit) ? limit : null });
    res.send(data);
  } catch (err) {
    next(err);
  }
});

If there is a nicer clean way to do this would be great to know. Also I am worried that as services are singleton instances somehow it can run asynchronous code while using the wrong context. I know node is single-threaded, but the context property is not async while the methods are and context can change while still resolving a promise on another service.

Any ideas are welcome, thanks. (Originally posted on Stackoverflow)


texts:
This is my code which works and compiles but I feel it may be non-optimal, especially the tag mapping and  use of the if command.

It reads two .xml files and finds what has been added or deleted on the new file. For new items it uses a map to link a tag name to a category of data (content tag is a description for example). This is important since different files have different naming conventions on the tags.

Finally, it does work on the data depending on its category (coming soon) and prints it.

#include "pugi/pugixml.hpp"

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

int main()
{

    std::string var;

    const std::map<std::string, std::string> tagMap {
        {"id", "id"}, {"description", "content"}, {"url", "web_address"}
    };

    pugi::xml_document doca, docb;
    std::map<std::string, pugi::xml_node> mapa, mapb;

    if (!doca.load_file("a.xml") || !docb.load_file("b.xml")) {
        std::cout << "Can't find input files";
        return 1;
    }

    for (auto& node: doca.child("data").children("item")) {
    const char* id = node.child_value("id");
    mapa[id] = node;
    }

    for (auto& node: docb.child("data").children("item")) {
    const char* idcs = node.child_value("id");
        if (!mapa.erase(idcs)) {
        mapb[idcs] = node;
        }
    }

     for (auto& eb: mapb) {
        // Loop the tagMap, and try and associate the tag name to the content
         for (auto& kv : tagMap) {
             if (kv.first == "id") {
             std::string var = eb.second.child_value(kv.second.c_str());
             // Do work on returned value of id tag in the future (I.e validation)
             std::cout << var << endl;
             }
             if (kv.first == "description") {
             std::string var = eb.second.child_value(kv.second.c_str());
             // Do work on returned value of content tag in the future
             std::cout << var << endl;
             }
             if (kv.first == "url") {
             std::string var = eb.second.child_value(kv.second.c_str());
             // Do work on returned value of web_address tag in the future
             std::cout << var << endl;
             }
         }
     }
}


texts: Getting the smallest snippet from content containing all keywords

texts:
This returns the smallest snippet from the content containing all of the given keywords (in any order). This provides the correct solution but I would like to know if it can be made more efficient.

import itertools, re

def solve(content, keywords):
    content = content.strip()
    contentWords = content.split()
    termPosition = {}
    for term in keywords:
        index = 0
        positions = []
        while index is not None:
            try:
                index = contentWords.index(term)
                positions.append(index)
                contentWords[index] = None
            except:
                index = None
        termPosition[term] = positions
    singlePositions = []
    multiplePositions = []
    for term in termPosition.keys():
        if len(termPosition.get(term)) == 1:
            singlePositions.append(termPosition.get(term)[0])
        else:
            multiplePositions.append(termPosition.get(term))
    snippet = content
    contentWords = content.split(' ')
    for element in itertools.product(*multiplePositions):
        tempList = list(element) + singlePositions
        minPos = min(tempList)
        maxPos = max(tempList) + 1
        if len(' '.join(contentWords[minPos:maxPos])) < len(snippet):
            snippet = ' '.join(contentWords[minPos:maxPos])
    return snippet


texts: Tabbed navigation to hide and show pages

texts:
I'm new to jQuery and trying to learn how to refactor my bloated code to make it nicer and better maintainable.

I have a tabbed navigation which I'm using jQuery to hide and show pages depending on the selector that is clicked.

  $('#search_distributors').on 'click', (e) =>
    e.preventDefault()
    $('#distributor_location_search_filter_form').show()
    $('#distributor_location_search_container').show()
    $('#international_distributors_location_container').hide()
    $('#all_distributors_location_container').hide()
    $('li.search_locations').addClass('active')
    $('li.international').removeClass('active')
    $('li.all_distributors').removeClass('active')

  $('#international_distributors').on 'click', (e) =>
    e.preventDefault()
    $('#international_distributors_location_container').show()
    $('#distributor_location_search_container,
      #distributor_location_search_filter_form,
      #all_distributors_location_container').hide()
    $('li.search_locations').removeClass('active')
    $('li.all_distributors').removeClass('active')
    $('li.international').addClass('active')

    $('#all_distributors').on 'click', (e) =>
      e.preventDefault()
      $('#all_distributors_location_container').show()
      $('#international_distributors_location_container,
        #distributor_location_search_container,
        #distributor_location_search_filter_form, ').hide()
      $('li.search_locations').removeClass('active')
      $('li.international').removeClass('active')
      $('li.all_distributors').addClass('active')

I'm familiar with using functions and stuff but unsure how to DRY this up.  If anyone can shed some light on this and help me learn that would be wonderful.


texts: Asymptotic complexity of multiple binary search

texts:
Since binary search is \$O(log(n))\$.  Consider this example where I am searching for the existence of e and l and f in the word.

Is this \$O(n log(n))\$ or \$O(3 log(n))\$ and thereby still \$O(log(n))\$?

def search(array, item):

    if not array:
        return False

    if len(array) == 1:
        return array[0] == item

    mid = len(array) // 2
    left = array[:mid]
    right = array[mid:]

    return search(left, item) or search(right, item)

def elfish(word, letters):
    """
    >>> elfish('', 'efl')
    False

    >>> elfish('whiteleaf', 'elf')
    True

    >>> elfish('whiteleaf', 'elf')
    True

    >>> elfish('unfriendly', 'elf')
    True

    >>> elfish('waffles', 'elf')
    True

    >>> elfish('waffles', 'elf')
    True

    >>> elfish('sameh', 'elf')
    False

    >>> elfish('wolf', 'elf')
    False

    """
    result = True
    for letter in letters:
        result = result and search(word, letter)
    return result

elfish('waffles', 'elf')

The pure Python way of doing this is:

if 'e' in word and 'l' in word and 'f' in word:
    return True

Is Python doing a binary search in the background?


texts: Finding the item with the minimal value in a sequence

texts:
This is an algorithm to find the item with the minimal value in a sequence. I've written a function called minimal to implement this algorithm.

Here is my script:

def minimal(*args):
    """Returns the item with the minimal value in a sequence. """
    if len(args) == 1:
        sequence = args[0]
    else:
        sequence = args

    index = 0
    successor = index + 1

    while successor < len(sequence):
        if sequence[index] > sequence[successor]:
            index = successor
        successor += 1

    return sequence[index]


texts: Get total count of object's elements and all children objects` elements

texts:
I have a table, Taxonomy, with data that looks something like the following:

TaxID | ParentID | Name
-----------------------------------
1     | NULL     | Animal
2     | 1        | Cat
3     | 1        | Dog
4     | 1        | Fish
5     | 3        | Poodle
6     | 3        | Golden Retriever
7     | 4        | Goldfish

I then have a second table, Table2, that has records that reference the TaxIDs in Taxonomy. I've labeled the foreign key column referencing Taxonomy, FK_TaxID.

FK_TaxID | Field2
------------------
1        | value
1        | value
1        | value
2        | value
2        | value
2        | value
3        | value

The resulting hierarchy looks something like the following:

- Parent (TaxID=1; #elements=15)
  - Child (TaxID=2; #elements=3)
  - Child (TaxID=3; #elements=8)
    - GrandChild (TaxID=6; #elements=2)
    - GrandChild (TaxID=5; #elements=0)
  - Child (TaxID=4; #elements=5)
    - GrandChild (TaxID=7; #elements=10)

The #elements is based on how many times the TaxID appears in Table2.

I have a method that takes in a Taxonomy ID, and returns the total element count for the record and its sub-children.

For example:

If ID = 1, count should = 43.
If ID = 3, count should = 10.
If ID = 5, count should = 0.

Here is the code I am currently using:

public int GetCount(int ID)
{
    List<int> childrenIDs = DbContext.Taxonomy
        .Where(x => x.ParentID == ID)
        .Select(x => x.TaxID)
        .ToList();

    List<int> grandchildrenIDs = DbContext.Taxonomy
        .Where(x => childrenIDs.Contains(x.ParentID))
        .Select(x => x.TaxID)
        .ToList();

    int count = DbContext.Table2.Count(x => x.FK_TaxID == ID
        || childrenIDs.Contains(x.FK_TaxID)
        || grandchildrenIDs.Contains(x.FK_TaxID));

    return count;
}

This code gets the count in three steps:

Sets childrenIDs to equal the list of records where the ParentID equals the given ID.
Sets grandchildrenIDs to equal the list of records where childrenIDs contains the ParentID.
Gets the count of Table2 records where the FK_TaxID equals the inputted ID, or childrenIDs contains the FK_TaxID or grandchildrenIDs contains the FK_TaxID.

This method returns the correct results, yet it is quite slow, and seems overly complicated.

How can I simplify this method? Can I somehow get rid or one of the lists and get all the IDs in one call? Is there a more efficient way of doing this than using Contains() twice?


texts: Bubble sort using user inputted numbers and size in MIPS assembly

texts:
I made this code to take user input, making a specific-sized array and printing user-inputted numbers after being sorted. It works well but I was wondering if there was a way to "shrink" it down. It seems a bit redundant to me but I don't know how to change it without messing it up. Or is it fine as it is?

.data
array: .space 100
size: .asciiz "Enter size: "
int: .asciiz "Enter int: "
final: .asciiz "\nSorted: "

.text

main:

la $a0,size
li $v0,4
syscall

li $v0,5
syscall

move $s1, $v0
sub $s1,$s1,1

addint:

la $a0,int
li $v0,4
syscall

li $v0,5
syscall

move $t3,$v0
add $t1,$zero,$zero
sll $t1,$t0,2

sw $t3,array ( $t1 )
addi $t0,$t0,1
slt $t1,$s1,$t0
beq $t1,$zero,addint

la $a0,array
addi $a1,$s1,1

jal bubble_sort

la $a0,final
li $v0,4
syscall

la $t0,array
li $t1,0

print:
lw $a0,0($t0)
li $v0,1
syscall

addi $t0,$t0,4
addi $t1,$t1,1
slt $t2,$s1,$t1
beq $t2,$zero,print

li $v0,10
syscall

bubble_sort:
li $t0,0

loop1:

addi $t0,$t0,1
bgt $t0,$a1,end
add $t1,$a1,$zero

loop2:

bge $t0,$t1,loop1

subi $t1,$t1,1

sll $t4, $t1, 2
subi $t3, $t4, 4

add $t4,$t4,$a0
add $t3,$t3,$a0
lw $t5,0($t4)
lw $t6,0($t3)

swap:
bgt $t5,$t6,loop2
sw $t5,0($t3)
sw $t6,0($t4)
j loop2

end:
jr $ra


texts: Rails 5 controller to get information about Steam users

texts:
I've done a bit of modifications and finally got it working, and did a lot of reading about @ vs @@ vs just declaring and I came up with.

It goes to Steam's API to return information (JSON Format) based on the endpoint. A list of games they own, a list of games they recently played, profile information, etc.

class SteamController < ApplicationController

  def initialize
    @steamKey = ENV["steam_api_key"]
    @ISteamUrl = "http://api.steampowered.com/ISteamUser/"
    @IPlayerUrl = "http://api.steampowered.com/IPlayerService/"
  end

  def get_steam_summary_per_user #/steam/:id
    @steamEndpoint = "GetPlayerSummaries/v0002/?key="+@steamKey+"&steamids="
    @steamId = User.find(params[:id]).steamId
    @playerUrl = @ISteamUrl + @steamEndpoint + @steamId.to_s
    @games = HTTParty.get(@playerUrl).to_json
    render json: @games
  end

  def get_steam_recently_played_per_user #/game/:id
    @recPlayedEndpoint = "GetRecentlyPlayedGames/v0001/?key="+@steamKey+"&steamid="
    @steamId = User.find(params[:id]).steamId
    @playerUrl = @IPlayerUrl + @recPlayedEndpoint + @steamId.to_s
    @games = HTTParty.get(@playerUrl).to_json
    render json: @games
  end

  def get_steam_owned_games_per_user #/allGames/:id
    @allGamesUrl = "GetOwnedGames/v0001/?key="+@steamKey+"&steamid="
    @steamId = User.find(params[:id]).steamId
    @playerUrl = @IPlayerUrl + @allGamesUrl +  @steamId.to_s
    @games = HTTParty.get(@playerUrl).to_json
    render json: @games
  end

end

Routes

  get '/steam/:id',  to: 'steam#get_steam_summary_per_user'
  get '/games/:id',  to: 'steam#get_steam_recently_played_per_user'
  get '/allgames/:id', to: 'steam#get_steam_owned_games_per_user'

I originally just has @baseUrl but realized they have multiple services and versions, but even before that I couldn't figure out why doing

@baseUrl = "http://api.steampowered.com/"+@recPlayedEndpoint+"etcetc
wouldn't work - I assumed it was related to initializing the `@recPlayedEndpoint and then re-assigning it later.

Ths code feels very redundant to me and I still have 5-6 more functions to build out.

The routes make sense, and I'm not sure if I can do them better. Please also tell me if my syntax is not proper for Rails - While I have an Angular front-end I'm trying to understand when to use camel case vs snake, vs pascal etc etc.

(All of this outputs to pure JSON and I use my Angular side render it, so if there is an easier way to do this. However, this is NOT set up on an api version of Rails)


texts: Making C++11 range-based for loops a bit more useful

texts:
C++11 is great. Probably one of the most beautiful features (in my opinion) is the so-called range-based-for-loop.
Instead of

for ( std::size_t i(0); i < range.size(); ++i )
{
   // do something to range[i];
}

or

for ( Range::iterator it(range.begin()); it != range.end(); ++it )
{
   // do something to *it;
}

or simplified with C++11 auto:

for ( auto it(range.begin()); it != range.end(); ++it )
{
   // do something to *it;
}

we can say this:

for ( auto& entry : range )
{
   // do something with entry.
}

This is very expressive: We talk about the entry, rather than the i^th position in the range or the iterator pointing to an entry. However, this syntax lacks the ability of having subranges (e.g. ignoring the last entry). In a series of small helper structs / methods, I want to add this functionality in a clean way.

So much for my motivation ;-) Now, for the real deal.

In this post, I address conditions on the entries of range. Basically, the helper code should perform the equivalent of

for ( auto& entry : range )
{
   if ( condition(entry) )
   {
       // do something to entry.
   }
}

but without that level of indentation.

Here is the code for ConditionalRange:

template <typename Range, typename Runnable>
ConditionalRange<Range, Runnable> makeConditionalRange(Range& range, Runnable&& condition)
{
   static_assert(std::is_same<decltype(condition(*std::declval<Range>().begin())), bool>::value, "Condition must return a boolean value.");
   return ConditionalRange<Range, Runnable>(range, std::forward<Runnable>(condition));
}

template <typename Range, typename Runnable>
struct ConditionalRange
{
   public:
      friend ConditionalRange makeConditionalRange<>(Range&, Runnable&&);
   public:
      using iterator_type = ConditionalIterator<decltype(std::declval<Range>().begin()), Runnable>;
      iterator_type begin() const
      {
         auto b = range.begin();
         while ( b != range.end() && !condition(*b) )
         {
            ++b;
         }
         return ConditionalIterator<decltype(std::declval<Range>().begin()), Runnable>(b, range.end(), condition);
      }
      iterator_type end() const
      {
         return ConditionalIterator<decltype(std::declval<Range>().begin()), Runnable>(range.end(), range.end(), condition);
      }
   private:
      ConditionalRange(Range& range_, Runnable&& condition_)
      :
         range(range_),
         condition(std::forward<Runnable>(condition_))
      {
      }
   private:
      Range& range;
      Runnable condition;
};

This is the helper struct for the iterator:

template <typename Iterator, typename Runnable>
struct ConditionalIterator
{
   private:
      Iterator iterator;
      Iterator end;
      const Runnable& condition;
   public:
      ConditionalIterator(Iterator b, Iterator e, const Runnable& r)
      :
         iterator(b),
         end(e),
         condition(r)
      {
      }
      auto operator*() -> decltype(*iterator)
      {
         return *iterator;
      }
      ConditionalIterator& operator++()
      {
         do
         {
            ++iterator;
         }
         while ( iterator != end && !condition(*iterator) );
         return *this;
      }
      bool operator==(const ConditionalIterator& second)
      {
         return iterator == second.iterator;
      }
      bool operator!=(const ConditionalIterator& second)
      {
         return !(*this == second);
      }
};

The intended usage is:

std::vector<int> ns{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for ( const auto& n : makeConditionalRange(ns, [](int a) { return a % 2 == 0; }) )
{
   std::cout << n << " ";
}
std::cout << "\n";

Demo: click here!

What are weaknesses of my approach? With what kind of arguments does it fail, although it shouldn't in the perfect world?


texts: Reading from a text file into a structure and posting to list boxes

texts:
I am trying to stay ahead of my Year 12 Software class. Starting to work with records and arrays. I have answered the question, but the solution feels very clunky. I am hoping someone has suggestions/links for completing this task in a more efficient way.
The task: read in lines from a text file and into a structure, and then loop through that, populating four list boxes if an animal hasn't been vaccinated.
Imports System.IO
Public Class Form1
    'Set up the variables - customer record, total pets not vaccinated, total records in the file, and a streamreader for the file.
    Structure PetsRecord
        Dim custName As String
        Dim address As String
        Dim petType As String
        Dim vacced As String
    End Structure
    Dim totNotVac As Integer
    Dim totalRecCount As Integer
    Dim PetFile As IO.StreamReader

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click

        'set an array of records to store each record as it comes in. Limitation: you need to know how many records in the file. Set the array at 15 to allow for adding more in later.
        Dim PetArray(15) As PetsRecord
        'variables that let me read in a line and split it into sections.
        Dim lineoftext As String
        Dim i As Integer
        Dim arytextfile() As String
        'tell them what text file to read
        PetFile = New IO.StreamReader("patients.txt")
        totNotVac = 0

        Try
            totalRecCount = 0
            ' read each line in and split the lines into fields for the records. Then assign the fields from the array. Finally, reset the array and loop.
            Do Until PetFile.Peek = -1
                'read in a line of text
                lineoftext = PetFile.ReadLine()
                'split that line into bits separated by commas. these will go into the array.
                arytextfile = lineoftext.Split(",")
                'dunno whether this is the best way to do it, but stick the array bits into the record, and then clear the array to start again.
                PetArray(totalRecCount).custName = arytextfile(0)
                PetArray(totalRecCount).address = arytextfile(1)
                PetArray(totalRecCount).petType = arytextfile(2)
                PetArray(totalRecCount).vacced = arytextfile(3)

                totalRecCount += 1
                Array.Clear(arytextfile, 0, arytextfile.Length)
            Loop

            For i = 0 To PetArray.GetUpperBound(0)

                If PetArray(i).vacced = "No" Then
                    lstVaccinated.Items.Add(PetArray(i).vacced)
                    lstCustomer.Items.Add(PetArray(i).custName)
                    lstAddress.Items.Add(PetArray(i).address)
                    lstPetType.Items.Add(PetArray(i).petType)

                    totNotVac += 1
                    lblVacTotal.Text = "The total number of unvaccinated animals is " & CStr(totNotVac)
                End If

            Next
        Catch ex As Exception
            MsgBox("Something went wrong with the file")
        End Try
        PetFile.Close()

    End Sub

    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        Close()

    End Sub
End Class

And one line from the patient.txt file:
    Richard Gere,16 Sunset Blvd,Gerbil,No


texts:
I'm building an authentication system using a combination of PHP, MySQL, jQuery, and AJAX. The way I'm doing it right now is I have a form that takes in a username and password. When the user clicks on the login button I pass the value of those two values along with an action to a controller file. That controller file will use an Authentication object (I wrote my own Authentication class) to determine if the user is authenticated or not. If so, it will return a string that says "authenticated" or something similar. I check for that value in the response of the AJAX request and go from there based on the response. Of course I do all sorts of server side checks so someone can't just navigate to a certain section or tamper with my jQuery to trick the system. It's all enforced behind the scenes.

Is this acceptable? Is there any major problem with doing this the way I am? Here are some snippets of my code that is responsible for handling all this:

Login section:

        <input id="username" type="text" placeholder="Username" />
        <input id="password" type="password" placeholder="Password" />

        Login

jQuery:

$(document).on("click", "#loginButton", function() {
var user = $("#username").val();
var pass = $("#password").val();

    $.post("controllers/auth.php", {"action": "authenticate", "user": user, "pass": pass}, function(data) {
        if(data == "authenticated") {
            //stuff
        }
    });
});

Controller:

if(isset($_POST['action']) && $_POST['action'] == "authenticate") {
    $credentials = array("user" => $_POST['user'], "pass" => $_POST['pass']);
    $auth = new Auth($dbh, $ldaps, $credentials);
    if($auth->authenticate()) {
        echo "authenticated";
    }
}


texts:
I created an XML wrapper to easily access XML data.
Please tell me what do you think about it.

Performance
Scalability
Anything else...

This is how you use it:

var xml = new Xml(dataString);
xml.load("UserEmail");
alert(xml.length + ", " + xml.getValueAt(0)); // Out: 2, jchen@contoso.com

XML source file:

<Users>
    <Users>
        <UserEmail>jchen@contoso.com</UserEmail>
        <UserPassword>
            BA56E5E0366D003E98EA1C7F04ABF8FCB3753889
        </UserPassword>
    </Users>
    <Users>
        <UserEmail>Kim@contoso.com</UserEmail>
        <UserPassword>
            07B7F3EE06F278DB966BE960E7CBBD103DF30CA6
        </UserPassword>
    </Users>
</Users>

Source:

function Xml(xmlString) {
    var parser = function() {
        if (typeof window.DOMParser != "undefined") {
            return (new window.DOMParser()).parseFromString(xmlString,
                    "text/xml");
        }
        else if (typeof window.ActiveXObject != "undefined"
                && new window.ActiveXObject("Microsoft.XMLDOM")) {
            var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
            xmlDoc.loadXML(xmlString);
            return xmlDoc;
        }
        else {
            throw new Error("XML parser not found");
        }
    };

    var data = parser(xmlString);
    var elements = null;
    this.length = 0;

    this.load = function(nodeName){
        elements = data.documentElement.getElementsByTagName(nodeName);
        this.length = elements.length;
    };

    this.getValueAt = function(index) {
        if(!elements || index >= this.length){
            return null;
        }
        var element = elements.item(index);

        return element.childNodes[0].data;
    };
}


texts:
I thought about using a macro to auto close FILE pointers at the end of a block. My solution so far is:

FILE *fopen_safe(const char *filename, const char *mode) {
    FILE *fp = fopen(filename, mode);

    if (!fp) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    return fp;
}

#define with_fopen(fp, filename, mode) \
    for (FILE *fp = fopen_safe(filename, mode), _invariant = { ._r = 1 }; _invariant._r--; fclose(fp))

// Usage:
with_fopen(fp, "test", "w") {
    fprintf(fp, "test\n");
}

This solution is not elegant as i am using an int in the struct to create my loop invariant.

Is there another way to auto close files? Can a block be associated with a macro in a smarter way?


texts: Writing a general purpose "split" function (for SICP's imaginary language)

texts:
From SICP 2.2.4:

The textbook has already defined a function (right-split ...) as follows:

(define (right-split painter n)
  (if (= n 0)
      painter
      (let ((smaller (right-split painter (- n 1))))
        (beside painter (below smaller smaller)))))

and they have indicated that there exists a procedure (up-split ...) which has much the same structure.

  Exercise 2.45.  Right-split and
  up-split can be expressed as instances
  of a general splitting operation.
  Define a procedure split with the
  property that evaluating

(define right-split (split beside below))
(define up-split (split below beside))

  produces procedures right-split and
  up-split with the same behaviors as
  the ones already defined.

I wrote the following function, but I'm not sure the best way to test it.  What do you think?

(define (split step1 step2)
  (define (split-f painter n)
    (if (= n 0)
        painter
        (let ((smaller (split-f painter (- n 1))))
          (step2 (step1 smaller smaller)))))
  split-f)

(define right-split (split beside below))
(define up-split (split below beside))


texts:
I'd like to find a more elegant solution to the following.

Below appears correct, but it's hard to read.

Is my first use of the map function below poor in stylistic terms?

It feels that way, and I'd like to pin down why.

I wonder what is a nicer way to achieve this.

;; ANSI Common Lisp ex 3.3, p56.
;; "Define a function that takes a list and returns a list indicating
;;  number of times each (eql) element appears, sorted from most common
;;  element to least common"
;; > (occurrences '(a b a d a c d c a))
;; ((A . 4) (C . 2) (D . 2) (B . 1))

(defun occurrences (lst)
  (labels ((build-flist (lst res)                                                            ; [1]
            (if (null lst)
                res
                (build-flist (cdr lst) (mapcar #'(lambda (x) (if (eql (car x) (car lst))     ; [2]
                                                                 (cons (car x) (1+ (cdr x))) ; [3] ; rtn inc'd freq entry
                                                                 x))                               ; rtn unchanged freq entry
                                               res))))
           (remove-dups (lst)                               ; [4]
            (if (null lst)
                nil
                (adjoin (car lst)
                        (remove-dups (cdr lst))))))

    (sort (build-flist lst (mapcar #'(lambda (x) (cons x 0)) (remove-dups lst))) ; [5]
          #'> :key #'cdr)))

;;[1] build-flist builds a frequency list. it is called like:
;;    (build-flist '(a b a d a c d c a) '((A . 0) (B . 0) (C . 0) (D . 0))
;;[2] map over entire res assoc list, incrementing frequency if it equals
;;    the el just removed from head of list, else just keep entry as is (inefficient).
;;[3] inelegant. in map, is there some kind of when form.                 ;; <<< STILL TENSION HERE, CODE IS HARD TO READ
;;[4] remove-dups uses adjoin, (set-based operator). this will help us    ;; --------------------------------------------
;;    build an zero-initialised freq list, to get us started.
;;[5] Finally, our actual function builds the frequency list, then sorts the result.
;;    We pass it a frequency list initialised to zero to get started.

;; Discussion
;; It doesn't always help to encapsulate helper functions in labels.
;; If the functions are simple, perhaps they could be global, if they're complex, perhaps they could be simplified.
```


texts: Running a script and analyzing the output with PowerShell

texts:
The task of the script is to analyze the output of a CLI program and finding specific lines.

trap {
    write-output $_
    Write-EventLog -LogName "GFI" -Source "MegaRAID" -EntryType Error -Message $_ -EventId 1408
    exit 1
}

$cli = "C:\Skripte\storcli64.exe /c0 /eall /sall show all"
$output = invoke-expression $cli
$startLine = "*Drive*State*"
$endLine = "*by drive*"
$startLineNumbers = 0..($output.Count) | Where { $output[$_] -like $startLine }
$endLineNumbers = 0..($output.Count) | Where { $output[$_] -like $endLine }
$countHDD = $startLineNumbers.Length

if ( [System.Diagnostics.EventLog]::SourceExists("MegaRAID") ) {
    Remove-EventLog -Source "MegaRAID"
}
if ( ![System.Diagnostics.EventLog]::SourceExists("MegaRAID") ) {
    New-EventLog -LogName "GFI" -Source "MegaRAID"
}

for ( $count = 0; $count -lt $countHDD; $count++ ) {
    for ( $i = $startLineNumbers[$count]; $i -lt $endLineNumbers[$count]; $i++ ) {
        if ( $output[$i] -like "*Drive*State*" ) {
            $failurenr = $output[$i]
            $failurenr = $failurenr.Replace("State :","")
        }
        if ( $output[$i] -match "Count" -and $output[$i] -gt 1 ) {
            $counter = $output[$i] -replace "\D",""
            if ( $counter -gt 1 ) {
                $message = "Problem mit $failurenr"
                echo $message
                exit 1001
            }
        }
        else {
            echo "Überprüfung erfolgreich abgeschlossen"
            exit 0
        }
    }
}

I bet there are a few points which can be optimized, especially the things inside of the for loop.


texts: Sorting a list and another list inside each item

texts:
I have a list of factories. Each factory has an item of its own and a list of other items from competitors.

I need to sort the list of factories based on price of their items and also sort list of other items from competitors for each factory.

What I am doing require to sort collection of factories and loop through all factories and sort collection of their competitors. I am wondering if there is any easier way to do it.

Factory

class Factory implements Comparator<Factory>{

String item;
double price;
List<Competitor> competitors;
@Override
    public int compare(Factory o1, Factory o2) {
        if (o1.getPrice() < o2.getPrice())
            return -1;
        if (o1.getPrice() > o2.getPrice())
            return 1;
        return 0;
    }}

Competitor

class Competitor implements Comparator<Competitor>{
String facName;
double price;
@Override
public int compare(Competitor o1, Competitor o2) {
        if (o1.getPrice() < o2.getPrice())
            return -1;
        if (o1.getPrice() > o2.getPrice())
            return 1;
        return 0;
}

Sort

Collection.sort(factoriesList); //sort list of factories
//sort list of competitors of each factory
for(int i=0;i<factoriesList.size();i++){
   Collection.sort(factoriesList.getCometitors());
}

Sample result

Factory1 Item1 222  Com1 444 Com2 555
Factory2 Item2 223  Com3 555 Com4 676
Factory3 Item3 224  Com1 543
Factory4 Item4 225  Com9 322


texts: Selecting an algorithm and key for Java Card encryption

texts:
I was playing around with Java Card and I try to do one of the examples.

P1 is what it has to do (e.g. decrypt, encrypt, etc) and P2 is to select which key to use in P1. Here is what the code looks like - well, half of it anyway, since I'm not really used to formatting in this site and it takes awhile to copy the code and make it pretty.

So my question here is, how can I simplify this nested switch? Or maybe I don't need to use nested switch at all?

switch (buf[ISO7816.OFFSET_P1]){
    case (byte) 0x01:
        switch (buf[ISO7816.OFFSET_P2]){
            case (byte) 0x01:
                doSingleDES(apdu, DESKey1);
                return;
            case (byte) 0x02:
                doSingleDES(apdu, DESKey2);
                return;
            case (byte) 0x03:
                doSingleDES(apdu, DESKey3);
                return;
            case (byte) 0x04:
                doSingleDES(apdu, DESKey3);
                return;
            default:
                ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
        }return;
    case (byte) 0x02:
        switch (buf[ISO7816.OFFSET_P2]){
            case (byte) 0x01:
                doEncrypt(apdu, DESKey1);
                return;
            case (byte) 0x02:
                doEncrypt(apdu, DESKey2);
                return;
            case (byte) 0x03:
                doEncrypt(apdu, DESKey3);
                return;
            case (byte) 0x04:
                doEncrypt(apdu, DESKey4);
                return;
            default:
                ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
    }return;
    default:
            ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);


texts:
I'm just hoping if there's a way to simplify this recursive code that takes 2 sorted lists and combines the two together in a sorted manner (without actually having to re-sort them).

def merge (l1,l2):
    if len(l1) == 0 and len(l2) == 0:
        return []
    if len(l1) == 0:
        return l2
    if len(l2) == 0:
        return l1
    if l1[0] <= l2[0]:
        return [l1[0]] + merge(l1[1:], l2)
    if l2[0] <= l1[0]:
        return [l2[0]] + merge(l1, l2[1:])


texts: Find the number of pawns available for a rook to capture

texts:
I find that very very often with matrix questions, the traversal and comparison part of the solution is very verbose and repetitive.

For example, this code (written for a coding challenge) to find the number of pawns available for a rook to capture in one move on a chess board (R is a white rook, B is a white bishop, and p is a black pawn):

class Solution:
    def numRookCaptures(self, board: List[List[str]]) -> int:
        for r in range(len(board)):
            for c in range(len(board[r])):
                if board[r][c] == 'R':
                    return self.find_p(board, r, c)

    def find_p(self, board, r, c):
        count = 0
        for i in range(r + 1, 8):
            if board[i][c] in ('B', 'p'):
                count += int(board[i][c] == 'p')
                break
        for i in range(r - 1, -1, -1):
            if board[i][c] in ('B', 'p'):
                count += int(board[i][c] == 'p')
                break
        for i in range(c + 1, 8):
            if board[r][i] in ('B', 'p'):
                count += int(board[r][i] == 'p')
                break
        for i in range(c - 1, -1, -1):
            if board[r][i] in ('B', 'p'):
                count += int(board[r][i] == 'p')
                break
        return count

This is the most concise way of writing it that I've found, without compromising clarity. The in for comparison and int for incrementing the count each save us a few lines of code.

But, it's still really verbose and repetitive. Each of the for loops are essentially doing the same exact thing, just in a different direction.

This comes up in every matrix question, whether it's just linear checks like above, BFS, DFS, they pretty much all have a four-directional comparison and traversal that produces 4 copies of code that are all identical in function.

Is there a less verbose way of writing these, without being overly fancy and hard-to-read?


texts: Is there a better way to test for the exception conditions?

texts:
This method assigns the value of a specified column in a DataRow to specified property in an object.

I have 3 conditionals handling exceptions, and I want these conditions to throw exceptions.

The final condition just allows the use of a conversion method if it exists. Is there a better way to test for and throw the exceptions?

public class ColumnToPropertyMap<colType, propType>
{
    public string ColumnName { get; private set; }
    public string PropertyName { get; private set; }
    private Func<colType, propType> conversion;

    public virtual void Map<T>(T obj, DataRow row)
    {
        if (!row.Table.Columns.Contains(this.ColumnName))
        {
            throw new ArgumentException(
                String.Format(@"Column ""{0}"" does not exist in the row.", this.ColumnName));
        }
        PropertyInfo property = obj.GetType().GetProperty(this.PropertyName);
        if (property == null)
        {
            throw new ArgumentException(String.Format(@"Property ""{0}"" does not exist for object.", this.PropertyName));
        }
        var value = row.IsNull(this.ColumnName) ? row[this.ColumnName].GetDefaultValue(typeof(colType)) : row[this.ColumnName];
        if (conversion == null && property.PropertyType != row.Table.Columns[this.ColumnName].DataType)
        {
            throw new InvalidCastException(
                string.Format(@"Mapping for {0} to {1} failed. Unable to convert {2} to {3}.", this.ColumnName, this.PropertyName, value.GetType(), property.PropertyType));
        }
        if (conversion != null)
        {
            value = conversion((colType)value);
        }
        property.SetValue(obj, value, null);
    }
}

Incorporating @Leonid and @SmartLemons comments/answers into consideration, I changed it to this:

    public virtual void Map<T>(T obj, DataRow row)
    {
        PropertyInfo property = obj.GetType().GetProperty(this.PropertyName);
        ValidateArguments(property, row);
        var value = row.IsNull(this.ColumnName) ? row[this.ColumnName].GetDefaultValue(typeof(colType)) : row[this.ColumnName];
        if (conversion != null)
        {
            value = conversion((colType)value);
        }
        property.SetValue(obj, value, null);
    }
    private void ValidateArguments(PropertyInfo property, DataRow row)
    {
        if (!row.Table.Columns.Contains(this.ColumnName))
        {
            throw new ArgumentException(
                String.Format(@"Column ""{0}"" does not exist in the row.", this.ColumnName));
        }
        if (property == null)
        {
            throw new ArgumentException(String.Format(@"Property ""{0}"" does not exist for object.", this.PropertyName));
        }
        if (conversion == null && property.PropertyType != row.Table.Columns[this.ColumnName].DataType)
        {
            throw new InvalidCastException(
                string.Format(@"Mapping for {0} to {1} failed. Unable to convert {2} to {3}.", this.ColumnName, this.PropertyName, row.Table.Columns[this.ColumnName].DataType.Name, property.PropertyType));
        }
    }

Takes the argument validation out of the method and makes the intent of the Map method clearer.


texts: Toggle four relays on/off based on bitmap stored in uint8_t

texts:
I am using a one-byte bitmap to control four relays. I am writing a function which will take the bitmap stored as uint8_t, look to see which bits are set/cleared, then turn on/off the relays appropriately. The input value to my function could be anything from 0 to 15.

This is in a controls application, so I'd like this to thing to work pretty fast (not insane optimization, since I still have to wait 10ms for my relays to latch).

Here's the function so far (I stripped out the actual relay switching to simplify):

void
relayToggle(uint8_t relayBitmap)
{
    if ( 0b00000001 & relayBitmap == 0b00000001 ) { relayOn(1); }
    else if ( 0b00000001 & relayBitmap == 0 ) { relayOff(1); }
    else if ( 0b00000010 & relayBitmap == 0b00000010 ) { relayOn(2); }
    else if ( 0b00000010 & relayBitmap == 0 ) { relayOff(2); }
    else if ( 0b00000100 & relayBitmap == 0b00000100 ) { relayOn(3); }
    else if ( 0b00000100 & relayBitmap == 0 ) { relayOff(3); }
    else if ( 0b00001000 & relayBitmap == 0b00001000 ) { relayOn(4); }
    else if ( 0b00001000 & relayBitmap == 0 ) { relayOff(4); }
}


texts: Finding an increasing sequence from a given array in a time-efficient manner in Python

texts:
Problem Statement:

  Given a sequence of integers as an array, we have to determine whether
  it is possible to obtain a strictly increasing sequence by removing no
  more than one element from the array.

  Example

  For sequence = [1, 3, 2, 1], the output should be
  almostIncreasingSequence(sequence) = false;

  Since there is no one element in this array that can be removed in
  order to get a strictly increasing sequence.

  For sequence = [1, 3, 2], the output should be
  almostIncreasingSequence(sequence) = true.

  You can remove 3 from the array to get the strictly increasing
  sequence [1, 2]. Alternately, you can remove 2 to get the strictly
  increasing sequence [1, 3].

I have formulated a solution for this which is as follows:

def almostIncreasingSequence(sequence):
    j=0
    k=0
    i=1
    m=1
    jflag=0
    kflag=0

    dupsequence = list(sequence)

    while i < len(sequence):
        difference = sequence[i]-sequence[i-1]
        if (difference) <= 0:
            j = j+1
            del sequence[i]
            i = 0
            if j > 1:
               jflag = 1
               break

        i = i + 1

    while m < len(dupsequence):
        if (dupsequence[m]-dupsequence[m-1]) <= 0:
            k = k+1
            del dupsequence[m-1]
            m = 0
            if k > 1:
                kflag = 1
                break

        m = m + 1

    if kflag == 0 or jflag == 0:
        return True

    if jflag ==1 and kflag==1:
        return False

It is working and when I try to run the above code on the stress tests provided in this link, especially the test: 26 is taking 167 milliseconds.

I tried to profile using this piece of code:

def timex():
    return time()*1000

def main():
    starttime = timex()
    almostIncreasingSequence(sequence)
    endtime = timex()
    print 'timetaken to execute is %d milliseconds' %(endtime-starttime)

if __name__ == '__main__':
    main()

  timetaken to execute is 167 milliseconds

I'm asking for a more performance and resource efficient implementation. I'm also an amateur in Python.


texts:
I have a function to calculate the normal distribution in Python:

def norm_cdf(z):
  """ Use the norm distribution functions as of Gale-Church (1993) srcfile. """
  # Equation 26.2.17 from Abramowitz and Stegun (1964:p.932)

  t = 1.0 / (1+0.2316419*z) # t = 1/(1+pz) , p=0.2316419
  probdist = 1 - 0.3989423*math.exp(-z*z/2) * ((0.319381530 * t)+ \
                                         (-0.356563782* math.pow(t,2))+ \
                                         (1.781477937 * math.pow(t,3)) + \
                                         (-1.821255978* math.pow(t,4)) + \
                                         (1.330274429 * math.pow(t,5)))
  return probdist

But I have to adhere to PEP8 and 80 char margin, hence the ugly \s. How else should I prettify my code?

In mathematical form,

$$\begin{align*}
\textrm{norm_cdf}(z) = 1 - 0.3989423 e^\frac{-z^2}{2} (&1.330274429 t^5 - 1.821255978 t^4 \\
&+ 1.781477937 t^3 - 0.356563782 t^2 + 0.319381530 t )
\end{align*}$$

where

$$ t = \frac{1}{1 + 0.2316419 z}$$


texts:
I had a situation when I needed to move all array elements in circular fashion. When I say this, I mean:

0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2

The array:

var players = ["hash1","hash2","hash3","hash4"];

Players is the array that contains user hashes and their place on the table. Table is round, so array must rotate in circular fashion.
Step dictates by how much it should move.

I came up with following algorithm (if you can call that, probably not) that works fine. I was just wondering if there was a more efficient way. Or cleaner way to do same?

The offset variable is probably wrongly named; I couldn't come up with a better name.

var step = 0 // 3,2,1,0
    var offset = 0;
    var players_new = [];
    for (var i = 0; i <= players.length - 1; i++) {
        if (i + step <= players.length - 1) {
            players_new[i + step] = players[i];
            offset++;
        } else {
            players_new[i - offset] = players[i];
        }
    };

I tested many different versions, and looks like vazha's version is the fastest all around, except in Firefox.

jsperf

Since I'm using this code in node.js, which uses the Chrome engine, results are important.


texts: Designing classes for non-standard arithmetics

texts:
This question is inspired by http://anydice.com - a dice probability calculator web application.

Anydice language has three run-time types: a number, a sequence and a die. There is also a number of unary and binary operations defined on these types. Each binary operation can take any type pair (out of the 3) as arguments, there are separate definitions of what each operation does for each possible pair of types. Some operations are not commutative.

For simplicity let's consider a single binary operation, which I'll call OpAccess, or @. My goal is to design a set of classes that represent the run-time values, so that if the access operation is executed on two of such values the correct operation implementation (depending on argument types) is called.

The main problem is that at compile time it is not known yet what run-time type a value has, yet, it's required to dispatch the correct operation implementation during the run-time.

Let's start with defining the base class for our values:

abstract class Primitive
{
  public abstract Primitive OpAccess(Primitive right);
}

Our value will use itself as the left argument in the OpAccessoperation and accept the right argument as the parameter.

Having this base we can design our value classes as follows:

class Number : Primitive
{
  public override Primitive OpAccess(Primitive right)
  {
    return OpAccess((dynamic)right);
  }
  public Primitive OpAccess(Number right)
  {
    Console.WriteLine("Number @ Number");
    return null;
  }
  public Primitive OpAccess(Sequence right)
  {
    Console.WriteLine("Number @ Sequence");
    return null;
  }
  public Primitive OpAccess(Die right)
  {
    Console.WriteLine("Number @ Die");
    return null;
  }
}
class Sequence : Primitive
{
  public override Primitive OpAccess(Primitive right)
  {
    return OpAccess((dynamic)right);
  }
  public Primitive OpAccess(Number right)
  {
    Console.WriteLine("Sequence @ Number");
    return null;
  }
  public Primitive OpAccess(Sequence right)
  {
    Console.WriteLine("Sequence @ Sequence");
    return null;
  }
  public Primitive OpAccess(Die right)
  {
    Console.WriteLine("Sequence @ Die");
    return null;
  }
}
class Die : Primitive
{
  public override Primitive OpAccess(Primitive right)
  {
    return OpAccess((dynamic)right);
  }
  public Primitive OpAccess(Number right)
  {
    Console.WriteLine("Die @ Number");
    return null;
  }
  public Primitive OpAccess(Sequence right)
  {
    Console.WriteLine("Die @ Sequence");
    return null;
  }
  public Primitive OpAccess(Die right)
  {
    Console.WriteLine("Die @ Die");
    return null;
  }
}

Now if we run something like:

Primitive a = new Sequence();
Primitive b = new Die();
a.OpAccess(b);
b.OpAccess(a);

We will get:

Sequence @ Die
Die @ Sequence

Since all operation will be defined differently the number of resulting methods is not an issue, it's really this many different ways to do an operation.

What worries me more is that I had to duplicate

public override Primitive OpAccess(Primitive left)
{
  return OpAccess((dynamic)left);
}

in each class and do not have an easy way around it. Remember, it's just one operation we are considering here, there will be more than a dozen of those in reality. Also, I have no idea if the use of dynamic becomes a performance problem. (Manual dispatch with switch/case should be faster).

But maybe I'm attacking this problem from the completely wrong angle? What do you think?

Note: this is in the context of writing a parser and an interpreter for Anydice language.

Update

Additional research prompted by Peter Taylor's answer uncovered the following article, which is most illuminating: Double Dispatch is a Code Smell


texts:
I am aiming to compute the Hurst Exponent of a 1-D signal time series in Python.  For now, I have one existing function hurst(sig) which returns the Hurst exponent of sig as a float.  Unfortunately, the code runs very slowly even for signals with only ~7500 data points.  My main concerns are:

Calculate the computational complexity of my algorithm given the size of sig.
Reduce computational complexity of the algorithm.
Reduce run-time (~1s).
Improve readability and address style convention as applies.

My code, awaiting your feedback:

import numpy as np

def hurst(sig: np.ndarray) -> float:
    """Compute the Hurst exponent of sig.

    arguments
        sig -- 1D signal
    returns
        hurst_exponent -- float
    """

    n = sig.size # num timesteps
    t = np.arange(1, n + 1)
    y = sig.cumsum() # marginally more efficient than: np.cumsum(sig)
    mean_t = y / t # running mean

    s_t = np.zeros(n)
    r_t = np.zeros(n)

    for i in range(n):
        s_t[i] = np.std(sig[:i + 1])
        x_t = y - t * mean_t[i]
        r_t[i] = np.ptp(x_t[:i + 1])

    r_s = r_t / s_t
    r_s = np.log(r_s)[1:]
    n = np.log(t)[1:]
    a = np.column_stack((n, np.ones(n.size)))
    [hurst_exponent, c] = np.linalg.lstsq(a, r_s)[0]
    return hurst_exponent


texts: Dictionary-based dispatch in Python with multiple parameters

texts:
Is there a better way to express the dispatch (switch) code without using a lambda? I think I need the lambda to act as an intermediary because the functions have varying numbers of parameters.

def printf(arg):
    print arg

def printf2(arg1, arg2):
    print arg1
    print arg2

def printn(arg):
    print arg

action = 'op2'
functions = {
    'op1': lambda: printf('op1 called'),
    'op2': lambda: printf2('op2 called', 'param 2'),
    }
functions.get(action, lambda: printn('default op'))()


texts: Google Foobar Level 3 - Lucky Triples (Find the Access Codes)

texts:
I have been working on this problem for 3 days now. I wrote a piece of java code that works perfectly on my machine testing in Eclipse, but when I put it in Foobar, it either returns "Error(400) Bad Request" or "Took too long to execute" or something else.

To quote it from this other question of the same Foobar question, the prompt of the challenge is essentially:

  Given a list (from 1 to 2000 elements) of random integers (from 1 to 999999) write a function, answer(l) that accepts a list as input and returns the number of "lucky triples" present in the list.

  For this purpose, a lucky triple is defined as a list of three numbers \$(x, y, z)\$ such that \$x\$ divides \$y\$, \$y\$ divides \$z\$, and \$x \le y \le z\$. So, for instance, \$(2, 4, 8)\$ is a lucky triple and so is \$(1, 1, 1)\$.

  Test cases:

  input: [1, 1, 1] ouput: 1

  input: [1, 2, 3, 4, 5, 6] output: 3

public static int answer(int[] l) {
    ArrayList<ArrayList<Integer>> log = new ArrayList();
    for(int i1=0; i1 < l.length; i1++){
        for(int i2=i1+1; i2 < l.length; i2++){
            for(int i3=i2+1; i3 < l.length; i3++){
                if(l[i3]%l[i2]==0 && l[i2]%l[i1]==0 && !log.contains(new ArrayList<>(Arrays.asList(l[i1], l[i2], l[i3])))){
                    log.add(new ArrayList<>(Arrays.asList(l[i1], l[i2], l[i3])));
                }
            }
        }
    }
    return log.size();
}

My idea is to generate all the possible combinations number by number and see if that combination satisfies the divisible situation, and whether it has been already recorded, if not, then record the set of numbers in a "log". Then return the size of the log. Like I said, this piece of code runs perfectly on my own machine. So I wonder if it is a performance issue.


texts:
The NICTA Haskell Course presents the following function to implement on List:

data List t =
  Nil
  | t :. List t
  deriving (Eq, Ord)

And the function:

filtering :: Applicative f => (a -> f Bool) -> List a -> f (List a)
filtering _ Nil       = pure Nil
filtering f (x :. xs) = (++) <$> ((\y -> case y of True -> x :. Nil
                                                   False -> Nil) <$> f x) <*>
                                                         filtering f xs

Please review this implementation.


texts:
As a challenge I decided to do the following problem:

  How many different numbers with n digits are there whose digits add up to k?

As this is an embarrassingly parallel problem I decided to use a bit of GPGPU programming (partly for learning purposes) using C++AMP and came up with the following solution:

#include <iostream>
#include <vector>
#include <assert.h>
#include <amp.h>
#include <chrono>
#include <ctime>
#include <numeric>

inline unsigned int AddDigits( unsigned int n ) restrict(amp, cpu)
{
        unsigned int sum = 0;
        while( n > 0 )
        {
                sum += n % 10;
                n /= 10;
        }

        return sum;
}

int main()
{
        std::chrono::steady_clock clock;
        unsigned int iSize, iSumRequired;

        std::cout << "Please enter the number of digits: ";
        std::cin >> iSize;
        std::cout << std::endl << "Please enter the sum required: ";
        std::cin >> iSumRequired;
        std::cout << std::endl;

        unsigned long long iMaxNum = std::pow( 10, iSize );

        assert( vecData.max_size() > iMaxNum );

        std::vector<unsigned int> vecData( iMaxNum );
        std::vector<int> vecNumValid( iMaxNum );

        auto tpBegin = clock.now();
        std::iota( vecData.begin(), vecData.end(), 1 );

        concurrency::array_view<const unsigned int, 1> arrayView( iMaxNum, vecData );
        concurrency::array_view<int, 1> numValid( iMaxNum, vecNumValid );

        concurrency::parallel_for_each( numValid.extent, [=]( concurrency::index<1> idx ) restrict( amp ) {
                numValid[idx] = (AddDigits( arrayView[idx] ) == iSumRequired ? 1 : 0);
        } );

        numValid.synchronize();

        int iNumValid = concurrency::parallel_reduce( vecNumValid.begin(), vecNumValid.end(), 0 );

        std::cout << "The number of valid numbers are: " << iNumValid << std::endl;
        auto tpTimeTaken = clock.now() - tpBegin;

        std::cout << "Time Taken: " << std::chrono::duration_cast<std::chrono::milliseconds>(tpTimeTaken).count() << std::endl;

        return 0;
}

This offers a significant improvement over parallel brute-forcing on the CPU (2x speedup versus 8 threads on an 8-core CPU), however out of curiosity I was wondering whether any further speedup could be gained, perhaps through somehow running the parallel_reduce on the GPU rather than on the CPU; removing the necessity to synchronize the array_view?

Moreover, this only allows for up to 8-digits (because of the restriction of the maximum value being less than 231-1) because the GPU only supports types of float, double, int, unsigned int and bool; is there a way to circumvent this and improve the maximum number of digits allowed?


texts: Counting consecutive selections of a given number when sampling integers in a range

texts:
This script counts consecutive number strikes of a number that you determine in a number-sequence that you also determine.

I would be very pleased if this script can be reviewed in terms of compactness, readability and quality. If this is perfect, please also let me know. But I am shure it will not be.

The script can be tested here

import random

desired_number = int(input("Desired number: "))
lower_range = int(input("Lower range: "))
upper_range = int(input("Upper range: "))
iterations = int(input("Iterations: "))

consecutive_strikes = 0
biggest_strike = 0

for i in range(iterations):
  actual_number = random.randint(lower_range, upper_range)
  print("Actual number: ", actual_number)

  if actual_number == desired_number:
    consecutive_strikes += 1
  else:
    if (consecutive_strikes > biggest_strike):
      biggest_strike = consecutive_strikes
    consecutive_strikes = 0

# if all numbers are the desired number, the second if-statement in the for-loop
# would never be executed
if (consecutive_strikes > biggest_strike):
  biggest_strike = consecutive_strikes

print("Biggest consecutive strike: ", biggest_strike)


texts:
I've had a go at creating a small class in C# that can generated salted hashes from text. I would like to know how this could be improved (in terms of code style) and whether or not this code is secure enough that it could be used in a professional environment (it won't be).

Hasher.cs

using System.Security.Cryptography;

namespace HashAndSaltTest
{
    public static class Hasher
    {
        private static readonly int MaxSaltLength = 32;

        public static byte[] GenerateSaltedHash(byte[] plainText)
        {
            HashAlgorithm algorithm = new SHA256Managed();
            byte[] salt = GenerateSalt();
            byte[] saltedText = new byte[plainText.Length + salt.Length];

            for (int i = 0; i < plainText.Length; i++)
                saltedText[i] = plainText[i];

            for (int i = 0; i < salt.Length; i++)
                saltedText[plainText.Length + i] = salt[i];

            return algorithm.ComputeHash(saltedText);
        }

        private static byte[] GenerateSalt()
        {
            byte[] salt = new byte[MaxSaltLength];

            using (RandomNumberGenerator random = new RNGCryptoServiceProvider())
                random.GetNonZeroBytes(salt);

            return salt;
        }
    }
}


texts:
I have made a simple MVC framework of my own for my personal website to learn a thing or two about how this whole thing even works. I think I've got the idea, but there's one thing I'm not sure about.

Now I know that a model shouldn't need anything specific - everything has to be generalized so it's accessible from multiple controllers which do something different.

My main issue, though is: How the hell do I tell the model to save something the way I want it to? If it's generalized, it should have no information about any save table, any output message or any saving pattern to begin with.

Then I remembered that there's this new fancy thing in PHP called closures and this might be a good way to use them. I have decided to deal with validation in the model in this fashion:

Controller:

private function sendMail($data)
{
    $rebuilt['name'] = array("type" => "string", "value" => $data['name'], "required" => true);
    $rebuilt['email'] = array("type" => "email", "value" => $data['email'], "required" => true);
    $rebuilt['subject'] = array("type" => "string", "value" => $data['subject'], "required" => false);
    $rebuilt['message'] = array("type" => "string", "value" => $data['message'], "required" => true);

    $callback = function() use (&$rebuilt) {
        $headers   = array();
        $headers[] = "MIME-Version: 1.0";
        $headers[] = "Content-type: text/plain; charset=utf-8";
        $headers[] = "From: {$rebuilt['name']['value']} <{$rebuilt['email']['value']}>";
        $headers[] = "Subject: {$rebuilt['subject']['value']}";
        $headers[] = "X-Mailer: PHP/".phpversion();

        mail("some@email", $rebuilt['subject']['value'], $rebuilt['message']['value'], implode("\r\n", $headers));
    };

    $this->model->validateInput($rebuilt, $callback, 'contact', "SuccessEmailReceived", 'contact');
}

Model validateInput() method:

public function validateInput(&$validation, $function, $failAnchor = 'top', $successMessage = "GeneralActionSuccessful", $successAnchor = 'top')
{
    foreach ($validation as $key=>$value) {

        // trim the string before validation
        trim($validation[$key]['value']);

        if($value['required'] == true && !$value['value']) {
            $this->error = "ErrorFieldMissing";
            $this->anchor = $failAnchor;
            $this->formFields = $validation;
            return;
        }

        switch($value['type']) {
            case 'email':
                if(!filter_var($value['value'], FILTER_VALIDATE_EMAIL)) {
                    $this->error = "ErrorInvalidEmail";
                    $this->anchor = $failAnchor;
                    $this->formFields = $validation;

                    return;
                }

                break;
        }
    }
    // success, call the function passed
    $function();
    $this->success = $successMessage;
    $this->anchor = $successAnchor;
}

Basically, what this does, is the controller calls the model validateInput() method while passing the list of data for validation as a reference. An anonymous callback function, which also uses the same validation input by reference, is then called in the model. This way, no matter how the validator deals with the input array, the function behaves accordingly.

Please note that I only have email validation set up right now, because I don't need anything else. I just need to know if I'm doing things right, or if there's something I should re-learn.