texts: C++11 Singly Linked List with raw pointers

texts:
Regarding C++, I have an experience in writing only short non-object-oriented programs and competitive programming challenges.

I would like to get your feedback about my C++ style, design decisions, and overall quality.

The below is the implementation of a Singly Linked List containing a multiset of values of type T. Type T is required to provide equal to operator. The class supports the following operations:

push a new value to the front of the list
push a new value to the end of the list
remove the first encountered occurrence of a given value
check if the list contains a given value
get the number of elements in the list
print the list in a pretty format
swap two lists

For the design, I decided to use both head and tail pointers to make both inserts constant time operations. For now, all pointers are raw pointers. The Node class is the internal class of LinkedList and an instance of LinkedList is responsible to delete its nodes. I decided to do that because this allows freeing the memory iteratively instead of recursively, which could cause problems if stack size is limited.

/* Singly Linked List by @pkacprzak */

#ifndef LINKED_LIST_HH__
#define LINKED_LIST_HH__

#include <ostream>

template<typename T>
class LinkedList {
public:
    LinkedList() {}

    LinkedList(const LinkedList& x) {
        auto cur = x.head;
        while (cur != nullptr) {
            pushBack(cur->val);
            cur = cur->next;
        }
    }

    LinkedList& operator=(const LinkedList& rhs) {
        LinkedList tmp(rhs);
        swap(*this, tmp);
        return *this;
    }

    ~LinkedList() {
        auto cur = head;
        while (cur != nullptr) {
            auto tmp = cur;
            cur = cur->next;
            delete tmp;
            tmp = nullptr;
        }
    }

    void pushFront(T val) {
        auto node = new Node(val);
        node->next = head;
        if (head == nullptr) {
            tail = node;
        }
        head = node;
        ++sz;
    }

    void pushBack(T val) {
        auto node = new Node(val);
        if (head == nullptr) {
            head = node;
        } else {
            tail->next = node;
        }
        tail = node;
        ++sz;
    }

    bool contains(T val) const {
        auto cur = head;
        while (cur != nullptr) {
            if (cur->val == val) {
                return true;
            }
            cur = cur->next;
        }
        return false;
    }

    void removeValue(T val) {
        if (head == nullptr) return;
        if (head->val == val) {
            auto cur = head;
            head = head->next;
            delete cur;
            if (head == nullptr) {
                tail = nullptr;
            }
            --sz;
        } else {
            auto cur = head->next;
            auto prev = head;
            while (cur != nullptr) {
                if (cur->val == val) {
                    prev->next = cur->next;
                    if (cur == tail) {
                        tail = prev;
                    }
                    delete cur;
                    --sz;
                    return;
                }
                prev = cur;
                cur = cur->next;
            }
        }
    }

    int size() const {
        return sz;
    }

    friend std::ostream& operator<<(std::ostream& os, const LinkedList& x) {
        auto cur = x.head;
        os << "[";
        while (cur != nullptr) {
            os << cur->val;
            if (cur != x.tail) {
                os << ",";
            }
            cur = cur->next;
        }
        os << "]";
        return os;
    }

    friend void swap(LinkedList& a, LinkedList& b) {
        std::swap(a.head, b.head);
        std::swap(a.tail, b.tail);
    }

private:
    struct Node {
        Node(T val_) : val(val_) {}
        T val;
        Node* next = nullptr;
    };
    Node* head = nullptr;
    Node* tail = nullptr;
    int sz = 0;
};
#endif


texts: Write millions of lines to a file - Python, Dataframes and Redis

texts:
I have the following code snippet that reads a CSV into a dataframe, and writes out key-values pairs to a file in a Redis protocol-compliant fashion, i.e. SET key1 value1. The code is piecemeal and I have tried to use multiprocessing, though I am not sure of its performance (gains).

The CSV has about 6 million lines, that is read into a dataframe pretty quickly (under 2 minutes). The output file has 12 million lines (2 lines per line of the input file). This takes about 50 minutes to complete. Can any part of my code be optimized/changed to make this run faster? Once the file is complete, loading it to Redis takes less than 90 seconds. The bottleneck really is in writing to the file.

I was looking into loading all the strings I generate into a dataframe and then use the to_csv() function to dump it to a file, but I'm not sure of how its performance will be.

filepath = '/path/to/file.csv'

def df_to_file:
    df = pd.read_csv(filepath)
    f = open('output_file', 'w')
    for i in range(len(df.index)):
        if df['col1'].iloc[i] != '':
            key1 = str_const1+str(df['col1'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1 = df['col_n+1'].iloc[i]

            key1a = str_const1a+str(df['col1'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1a = df['col_n+2'].iloc[i]

            print('SET {0} {1}\nSET {0} {1}'.format(key1, val1, key1a, val1a), file = f)

        if df['col2'].iloc[i] != '':
            key1 = str_const2+str(df['col2'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1 = df['col_n+1'].iloc[i]

            key1a = str_const2a+str(df['col2'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1a = df['col_n+2'].iloc[i]

            print('SET {0} {1}\nSET {0} {1}'.format(key1, val1, key1a, val1a), file = f)
        if df['col3'].iloc[i] != '':
            key1 = str_const3+str(df['col3'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1 = df['col_n+1'].iloc[i]

            key1a = str_const3a+str(df['col3'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1a = df['col_n+2'].iloc[i]

            print('SET {0} {1}\nSET {0} {1}'.format(key1, val1, key1a, val1a), file = f)
    f.close()

p = Process(target = df_to_file)
p.start()
p.join()


texts:
My requirement is to add two binary numbers, say "1001" and "0101" as binary1 and binary2.

Partial Class Default2
    Inherits System.Web.UI.Page
    Dim carry As Boolean = False ' Boolean variable to hold the carry if occured
    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        Dim binary1 As String = TextBox1.Text 'First binary number
        Dim binary2 As String = TextBox2.Text 'Second binary number
        Dim result As String = "" 'to store the result
        For i As Integer = Len(binary1 ) - 1 To 0 Step -1
            result = bin_add(getbyte(binary1 , i), getbyte(binary1, i)) & result ' calling function
        Next
        If carry = True Then
            result = "1" & result 'if a carry remains add it to the MSB
        End If
        MsgBox(rslt) 'Display the result
    End Sub

    Public Function bin_add(b1 As Boolean, b2 As Boolean) As String'Function which performs the addition of each single bits form the two inputs which is passed from the calling function
        Dim result As Boolean
        If b1 AndAlso b2 = True Then 'both values are 1/true
            If carry = True Then
                result = True
                carry = True
            Else
                result = False
                carry = True
            End If
        ElseIf b1 = False And b2 = False Then 'Both are 0/false
            If carry = True Then
                result = carry
                carry = False
            Else
                result = False
                carry = False
            End If
        Else
            If carry = True Then
                result = False
                carry = True
            Else
                result = True
                carry = False
            End If
        End If
        If result = True Then
            Return "1" 'return 1 for Boolean true
        Else
            Return "0" 'return 0 for Boolean false
        End If
    End Function

    Private Function getbyte(s As String, ByVal place As Integer) As String'Function for getting each individual letters from the input string. i got it from net.
        If place < Len(s) Then
            place = place + 1
            getbyte = Mid(s, place, 1)
        Else
            getbyte = ""
        End If
   End Function
End Class

Notes:

It gives good results for me only if the no. of digits in both numbers are the same.

Question:

How can I improve the code? Especially, how can I reduce the length of code?


texts:
I'm working on this code and I can't find a better way to improve this code, can anyone improve it more? My PHP is pretty bad, this is the best I could do.

The code checks if iTunes link exists in the database if not search it on iTunes with API and if successfully found a link in itunes api it will be added in the database. If iTunes search is empty and iTunes row in the database is empty a string 'gol' will be saved in the MySQL and based on this string it will be rechecked in the future because Itunes has a 20 searches per minute limit.
Hope i explained what is the code supposed to do.

if (empty($video['itunes'])) {
    //if mysql row $video['itunes'] is empty check the function ituneslink
    $itunecheck = ituneslink($mystrings);
    //ituneslink is a function that searches the itunes library for Movies/Music
    if (empty($itunecheck)) {
    //if ituneslink function is empty trigger the empty string itunesgol and
        $itunesgol = '';
        $smarty->assign('itunesgol', $itunesgol);
        itunes_add_item("gol", $video['uniq_id']);
    //add in mysql 'gol' that the itunescheck didn't found nothing on itunes
    //search api, this will be useful for future rechecks
    }
} elseif($video['itunes'] != "gol") {
    // if row itunes is not 'gol' it means that itunescheck got the itunes link
    //and succesfully added in database
    $itunecheck = $video['itunes'];
} else {
    $itunesgol = '';
    $smarty->assign('itunesgol', $itunesgol);
}

if ($video['itunes'] == 'gol') {
    //because itunes seach api has a limit of 20 req per minute i had to recheck
    //for this string if available because maybe the first search got 403
    //fobiden because of to many queries
    $itunecheck = ituneslink($mystrings);
    itunes_add_item($itunecheck, $video['uniq_id']);
}

if (empty($video['itunes']) && !empty($itunecheck) && $video['itunes'] != "gol") {

    //NOW here i check if itunes is empty and itunescheck not empty and row
    //itunes not 'gol'. If all of them comply it will be added in the database
    itunes_add_item($itunecheck, $video['uniq_id']);
}

The code works well, what i want is: to improve it, to shorten the code, to make it smoother, faster, it looks too messy


texts: Parsing s-expression structure into tree and summing the paths

texts:
I'm new to Python, just attempted the task here.

The part I found hardest was parsing the expression into the tree structure. I was originally trying to build a regular tree structure (i.e. a Node object with left and right nodes), but without any logic for the insertion (i.e. newNode < node then insert left, newNode > node then insert right) I couldn't find a way.

In the end I've used Python's lists to kind of replicate the expression structure, and walk the paths as they're created. Each time I find a leaf, I calculate the cumulative sum, pop the last added node, and carry on.

The one part of the code I really don't like is the way I'm finding leafs:

if tree and expression[i-1:i+3] == ['(',')','(',')']:

and I don't like that I've done:

pair[1].replace('(', ' ( ').replace(')', ' ) ').split()

twice.

Any guidance on any part of this - style or just general approach and logic would be great.

def pairs(value):
    """ Yields pairs (target, expression) """
    nest_level = 0
    expr = ""
    target = 0

    value = value.replace('(', ' ( ').replace(')', ' ) ').split()
    for x in value:
        if x.isdigit() and not expr:
            target = x
        else:
            expr += x

        if x is '(':
            nest_level += 1
        elif x is ')':
            nest_level -= 1
            if nest_level is 0:
                yield target, expr
                expr = ''
                target = 0

def main():
    with open('input') as f:
        expr_input = f.read()

        level = 0
        current_target = 0

        for pair in pairs(expr_input):
            current_target = pair[0]
            # stack representing the 'current path'
            tree = list()
            # store the cumulative total of each path for this expression
            cumulative_totals = list()
            running_total = 0

            expression = pair[1].replace('(', ' ( ').replace(')', ' ) ').split()
            for i, s in enumerate(expression):
                if s is '(':
                    level += 1
                elif s == ')':
                    level -= 1
                    # "is leaf?" ugh.
                    if tree and expression[i-1:i+3] == ['(',')','(',')']:
                        cumulative_totals.append(running_total)
                        # remove the node and carry on down the next path
                        node = tree.pop()
                        running_total = running_total - int(node)
                    if level is 0:
                        if int(current_target) in cumulative_totals:
                            print "yes"
                        else:
                            print "no"
                else:
                    running_total += int(s)
                    tree.append(s)

if __name__ == '__main__':
    main()


texts: Write a function that adds two numbers stored in a linked list and returns the sum

texts:
Just for fun I did the following exercise from "Cracking the coding interview. 4th edition":

  You have two numbers represented by a linked list, where each node
  contains a single digit. The digits are stored in reverse order,
  such that the 1’s digit is at the head of the list. Write a function
  that adds the two numbers and returns the
  sum as a linked list.

  EXAMPLE Input: (3 -> 1 -> 5), (5 -> 9 -> 2)

  Output: 8 -> 0 -> 8

Although my solution it seems to return valid results it is significantly different from the proposed solution. I implemented my own structures and I haven't used recursion.

I know both solutions are valid, but in case of a real interview: How would the interviewer consider my answer? Which caveats should I consider?

public class ex24
{
    public static void Run()
    {

        var n1 = CreateNumber(5, 1, 3);
        var n2 = CreateNumber(2, 9, 5);

        Figure xF = n1;
        Figure xY = n2;
        int alpha = 0;

        Figure prev = null;
        Figure ini;
        do
        {
            int n1v = n1 != null ? n1.Value : 0;
            int n2v = n2 != null ? n2.Value : 0;

            int sum = n1v + n2v + alpha;

            decimal f = sum / (decimal)10;
            alpha = (int)f;
            sum = (int)((f - alpha) * 10);

            if (prev == null)
            {
                ini = new Figure(sum);
                prev = ini;
            }
            else
            {
                prev.Next = new Figure(sum);
                prev = prev.Next;
            }

            n1 = n1 != null ? n1.Next : null;
            n2 = n2 != null ? n2.Next : null;

        } while (n1 != null || n2 != null || alpha != 0);

      // Result is stored on 'ini'.

    }
    public class Figure
    {
        public Figure Next;
        public int Value;

        public Figure(int value)
        {
            this.Value = value;
        }

        public override string ToString() =>"" + this.Value;

    }

    public static Figure CreateNumber(params int[] values)
    {
        Figure ini = new Figure(values[values.Length - 1]);
        Figure prev = ini;
        for (var ix = values.Length - 2; ix >= 0; ix--)
        {
            prev.Next = new Figure(values[ix]);
            prev = prev.Next;
        }

        return ini;
    }

}


texts:
I've written some code that allows Unity3D's inspector to display fields that conform to an interface. Unity has some quirks about their inspector, so as a preface they are listed here:

If you add a [Serializable] attribute to a class, Unity's Inspector will attempt to show all public fields inside that class.
Any class extending Monobehaviour automatically has the [Serializable] attribute
Unity's inspector will attempt to display any private field with the [SerializeField] attribute.
Unity's inspector will not attempt to display generic types or interfaces, with the exception of List<T>, which is hard-coded.
Unity's inspector will not attempt to display properties. A common workaround is to have a private backing field for your property with [SerializeField] attached. Setters won't be called on the value set in the inspector. It's typically only set pre-compilation time, although a developer can modify values in the inspector during runtime. Currently it is acceptable to me to only take the initial value, although if anybody has a simple and efficient way to update successfully, I'd be happy to hear it.
Unity has a PropertyDrawer class you can extend to control how a type is displayed in the inspector. The PropertyDrawer for an interface or generic type will be ignored.

The code

UnityInterfaceHelper.cs

[Serializable]
public class UnityInterfaceHelperBase
{
    [Tooltip("The component that is of the type required.")]
    [SerializeField]
    public Component target;
}

[Serializable]
public class UnityInterfaceHelper<TInterface> where TInterface : class
{
    public TInterface TargetAsInterface
    {
        get
        {
            if (targetAsInterface == null)
            {
                targetAsInterface = target as TInterface;
            }
            return targetAsInterface;
        }

        set
        {
            if (targetAsInterface != value)
            {
                targetAsInterface = value;
                if (value as Component != null)
                {
                    target = targetAsInterface as Component;
                }
            }
        }
    }

    [Tooltip("The component that is of the type required.")]
    [SerializeField]
    private Component target;

    private TInterface targetAsInterface;

    public static implicit operator UnityInterfaceHelper<TInterface>(UnityInterfaceHelperBase b)
    {
        return new UnityInterfaceHelper<TInterface>()
        {
            target = b.target
        };
    }

    public static implicit operator UnityInterfaceHelperBase(UnityInterfaceHelper<TInterface> b)
    {
        return new UnityInterfaceHelperBase()
            {
                target = b.target
            };
    }
}

UnityInterfaceHelperPropertyDrawer.cs

[CustomPropertyDrawer(typeof(UnityInterfaceHelperBase), true)]
public class UnityInterfaceHelperPropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        label = EditorGUI.BeginProperty(position, label, property);

            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
            EditorGUI.PropertyField(position, property.FindPropertyRelative("target"), GUIContent.none);

        EditorGUI.EndProperty();
    }
}

Typical usage

[SerializeField]
private UnityInterfaceHelperBase itemComparable;

public IComparable ItemComparable
{
    get { return ((UnityInterfaceHelper<IComparable>)itemComparable).TargetAsInterface; }
    set { ((UnityInterfaceHelper<IComparable>)landedComparable).TargetAsInterface = value; }
}

public void CompareItems()
{
    if(ItemComparable.CompareTo("Hello") == 0)
    {
        Debug.Log("Hello world!");
    }
}

I'm looking to reduce the amount of code I have to repeat for every property, it's already down quite a way, but I'm hoping to make it as simple as possible, but any other comments on the code are welcome too.


texts: Routes for a user controller in a Node.js application

texts:
I have a very simple Node application that routes requests to /users to the following file:

users.js

var express = require('express');
var router = express.Router();
var User = require('models/user');
var sequelizeSuccessHandler = require('lib/sequelizeSuccessHandler');
var sequelizeErrorHandler = require('lib/sequelizeErrorHandler');

router.get('/', function(request, response) {
  User.findAll()
  .then(sequelizeSuccessHandler(response))
  .catch(sequelizeErrorHandler(response));
});

router.post('/', function(request, response) {
  User.create(User.params(request.body))
  .then(sequelizeSuccessHandler(response))
  .catch(sequelizeErrorHandler(response));
});

router.get('/:id', function(request, response) {
  User.findOne({where: {id: request.params.id}})
  .then(sequelizeSuccessHandler(response))
  .catch(sequelizeErrorHandler(response));
});

router.patch('/:id', function(request, response) {
  User.findOne({where: {id: request.params.id}})
  .then(function(user) {
    return user.update(User.params(request.body));
  })
  .then(sequelizeSuccessHandler(response))
  .catch(sequelizeErrorHandler(response));
});

router.delete('/:id', function(request, response) {
  User.findOne({where: {id: request.params.id}})
  .then(function(user) {
    return user.destroy();
  })
  .then(sequelizeSuccessHandler(response))
  .catch(sequelizeErrorHandler(response));
});

module.exports = router;

lib/sequelizeSuccessHandler.js

var Sequelize = require('sequelize');

function successHandler(response) {
  return function(object) {
    response.send(JSON.stringify(object));
  };
}

module.exports = successHandler;

lib/sequelizeErrorHandler.js

var Sequelize = require('sequelize');

function errorHandler(response) {
  return function(error) {
    if (error.constructor == Sequelize.ValidationError) {
      response.status(400).send();
    } else {
      response.status(500).send();
    }
  };
}

module.exports = errorHandler;

Looking at users.js, you can see that I tried to DRY things up by creating sequelizeSuccessHandler and sequelizeErrorHandler (I hate those names), but there's still a lot of repetition. I feel like there is a better way to do this.

How can I clean this up?


texts: Controller structure for a browser game module with filters and pagination

texts:
To get an idea of what the controller code reflects, here is a screenshot:

Basically, the idea is that you print out a list of football players which you can then filter by their name, price, field position, and team. I'm not sure whether it's better to handle all the scope logic within a single controller, or break it down into separate controllers, isolating the filters from the player list, pagination, and so on. I'm currently going with the single controller approach, and here's what I have:

app.controller('playersController', function($scope, $filter, minMax, buildOptions, PlayersModel, TeamsModel, CommonValues){
    $scope.basehref         = CommonValues.getBaseHref();
    $scope.imgbase          = CommonValues.getImgBase();
    $scope.players          = PlayersModel;
    $scope.teams            = TeamsModel;
    $scope.predicate        = 'team.name';
    $scope.minMax           = minMax($scope.players);

    $scope.filters          = { // filter model
        searchString: '',       // string input from user
        selectedTeam: {},       // selected team
        selectedTeamMs: [],     // selected teams from multiselect
        roles: {
            1: true,            // forward
            2: true,            // defense
            3: true,            // midfield
            4: true             // goalie
        },
        slider: {               // set up boundaries for slider filter
            min: $scope.minMax[0],
            max: $scope.minMax[1],
            step: 10000
        },
        pagination: {           // set up pagination
            totalItems: $scope.players.length,
            currentPage: 1,
            maxSize: 5,
            pages: buildPages()
        }
    };
    var cache = $scope.players;   // save original player model for later use

    /**********
     * Watchers
     **********/

    // watch for filter model changes, start filtering
    $scope.$watch('filters', function(newVal, oldVal){
        if (newVal !== oldVal || newVal.id !== oldVal.id || newVal.length !== oldVal.length) {
            var result;

            result = $filter('textFilter')(cache, $scope.filters);                 // filter by phrase
            result = $filter('roleFilter')(result, $scope.filters);                // filter by field position
            result = $filter('teamFilter')(result, $scope.filters.selectedTeamMs); // filter by team

            $scope.players = result;
        }
    }, true);

    /***********
     * Scope API
     ***********/

    // pagination logic
    $scope.changePage  = function(newVal, oldVal) {
        var maxSize    = $scope.filters.pagination.maxSize;
        var offset     = maxSize * oldVal;
        var result     = [];

        if (newVal < oldVal)  offset = (maxSize * newVal) - maxSize;

        for (var i = 0; i < cache.length; i++) {
            if (i >= offset) result.push(cache[i]);
        }
        $scope.players = result;
    };

    /****************
     * Helper methods
     ****************/
    function buildPages() {
        return null;
    }
});

Is it ok to encapsulate all the logic into that one controller, including helper methods, and so on, or should I refactor?


texts:
I have run into a bit of a dilemma.  Binding user input and building a prepared statement is all well and good, but what if I need the user input as a variable for a compare?

Can I just create a function to clean the input?

This is the line that worries me:

$password = $_POST['password']

What I have working so far:

// QUERY
public function query($query){
    $this->stmt = $this->dbh->prepare($query);
}

// RESULT SET
public function resultset(){
$this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

// EXECUTE
public function execute(){
    return $this->stmt->execute();
}

Check that the password matches with the database password if username exists

<?php
if (isset($_POST['login'])) {

    $dbpass = '';
    $password = $_POST['password'];

    //Select username, password, salt and active
    $database->query('SELECT username, password, salt, active FROM wcx_admin WHERE username = :username');

    $database->bind(':username', $_POST['username']);

    $rows = $database->resultset();

    if(isset($rows[0])) {
        $salt = $rows[0]['salt'];
        $dbpass = $rows[0]['password'];
        $password = hash("sha512", $password . $salt);
    }
    if($password !== $dbpass) {
        echo 'Incorrect Username or Password';
    }
}

?>

Binding Function

// BIND
public function bind($param, $value, $type = null){
if (is_null($type)) {
    switch (true) {
        case is_int($value):
            $type = PDO::PARAM_INT;
            break;
        case is_bool($value):
            $type = PDO::PARAM_BOOL;
            break;
        case is_null($value):
            $type = PDO::PARAM_NULL;
            break;
        default:
            $type = PDO::PARAM_STR;
    }
}
$this->stmt->bindValue($param, $value, $type);
}


texts: Shell script to sync dotfiles repository

texts:
I'm doing the git dot files thing and created a script -- my first Unix shell script -- to synchronise the repo dot files with those in the user's home. It checks which dot files exist in the repo folder (except for .git) and then archives any clashes in the home directory before symlinking to the repo... I wrote this largely by experimentation and Googling. It works, but I'm just checking to see if there's anything I missed or if there are better solutions?

#!/bin/sh

# Archive existing dot files and symlink to the new ones
# Run from ~/dotfiles

# All dot files apart from .git, . and ..
dotFiles=(`ls -da .* | grep -Pxv '\.git|\.+'`)

# Existing dot files to archive
toArchive=()

cd ~

# Archive: Find clashes and tarball+gzip them
for i in ${dotFiles[*]}; do
  toArchive=(${toArchive[@]} `ls -d $i`)
done
if [ ${#toArchive[*]} != 0 ]; then
  archiveFile="dotfiles"`date +%Y%m%d`".tar.gz"
  tar czf $archiveFile ${toArchive[*]} --remove-files
fi

# Create symlinks
for i in ${dotFiles[*]}; do
  dotFileLink="dotfiles/"$i
  ln -s $dotFileLink $i
done


texts:
I'm working on an A* search algorithm implemention and this is what I came up with for the open list:

from heapq import heappush, heappop

class OpenList(set):
    '''
    This uses a heap for fast retrieval of the node with the lowest path score.
    It also uses a set for efficiently checking if a node is contained.
    '''

    REMOVED = object()

    def __init__(self, *args, **kwargs):
        set.__init__(self, *args, **kwargs)
        self._heap = []

    def add(self, node):
        set.add(self, node)

        heappush(self._heap, (node.get_path_score(), node))

    def remove(self, node):
        set.remove(self, node)

        i = self._heap.index((node.get_path_score(), node))
        self._heap[i] = self.REMOVED

    def pop_node_with_lowest_path_score(self):
        ''' remove and return the node with the lowest path score '''

        item = heappop(self._heap)
        while item is self.REMOVED:
            item = heappop(self._heap)
        set.remove(self, item[1])
        return item[1]

Should I keep the path_score in the heap, when I mark the item as removed as in the following code:

self._heap[i] = (node.get_path_score(), self.REMOVED)

What do you think about it? What can be made more efficient, simple or cleaner?


texts:
This takes a width specified by user and prints a diamond of that width.  It uses only three for loops, but could I reduce that further? Is there a more elegant solution?

public class Diamond {

    static boolean cont = true;

    public static void main (String[] args) {
        Scanner input = new Scanner(System.in);
        while (cont) {
            System.out.print("Width: ");
            int width = input.nextInt();
            int lines = width;
            System.out.println();
            for (int line = 0; line < lines; line++) {
                for (int spaces = 0; spaces < Math.abs(line - (lines / 2)); spaces++) {
                    System.out.print(" ");
                }
                for (int marks = 0; marks < width - 2 * (Math.abs(line - (lines / 2))); marks++) {
                    System.out.print("x");
                }
                System.out.println();
            }
            System.out.println();
        }
    }
}


texts:
We're calculating entropy of a string a few places in Stack Overflow as a signifier of low quality.

I whipped up this simple method which counts unique characters in a string, but it is quite literally the first thing that popped into my head. It's the "dumbest thing that works".

/// <summary>
/// returns the # of unique characters in a string as a rough
/// measurement of entropy
/// </summary>
public static int Entropy(this string s)
{
  var d = new Dictionary<char, bool>();
  foreach (char c in s)
      if (!d.ContainsKey(c)) d.Add(c, true);
  return d.Count();
}

Is there a better / more elegant / more accurate way to calculate the entropy of a string?

Efficiency is also good, though we never call this on large strings so it is not a huge concern.


texts:
I have a table in Lua, which contains two 1-dimensional arrays in which each array contains approximately 800,000 elements. I want to serialize this Lua table to file efficiently. Hence, I planned to use Lua C bindings.

#include "lua.h"
#include "lauxlib.h"
#include <stdio.h>
#include <assert.h>

static int do_it(lua_State *L) {
  assert(L && lua_type(L, -1) == LUA_TTABLE);

  int len, idx;
  void *ptr;
  FILE *f;
  size_t r;

  lua_pushstring(L, "p");
  lua_gettable(L, -2);
  len = lua_objlen(L, -1);
  // instead of using lua_rawlen, i used lua_objlen. see below
  // len = lua_rawlen(L, -1); // it throws the following error
  // lua: error loading module 'savetable' from file './savetable.so':
  //    ./savetable.so: undefined symbol: lua_rawlen
  int p_values[len];
  for (idx = 1; idx <= len; idx++) {
    lua_rawgeti(L, -1, idx);
    p_values[idx - 1] = (int)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }

  f = fopen("p.bin", "wb");
  assert(f);
  r = fwrite(p_values, sizeof(int), len, f);
  printf("[p] wrote %zu elements out of %d requested\n", r, len);
  fclose(f);
  lua_pop(L, 1);

  lua_pushstring(L, "q");
  lua_gettable(L, -2);
  len = lua_objlen(L, -1);
  double q_values[len];
  for (idx = 1; idx <= len; idx++) {
    lua_rawgeti(L, -1, idx);
    q_values[idx - 1] = (double)lua_tonumber(L, -1);
    lua_pop(L, 1);
  }

  f = fopen("q.bin", "wb");
  assert(f);
  r = fwrite(q_values, sizeof(double), len, f);
  printf("[q] wrote %zu elements out of %d requested\n", r, len);
  fclose(f);
  lua_pop(L, 1);

  return 1;
}

int luaopen_savetable(lua_State *L) {
  static const luaL_reg Map[] = {{"do_it", do_it}, {NULL, NULL}};

  luaL_register(L, "mytask", Map);
  return 1;
}

Please note that for debugging purpose, I have defined two very small 1-dimensional arrays:

my_table = {p = {11, 22, 33, 44}, q = {0.12, 0.23, 0.34, 0.45, 0.56}}

require "savetable"
mytask.do_it(my_table)

I used the following commands to compile and run it:

> gcc -I/usr/include/lua5.1 -o savetable.so -shared savetable.c -fPIC
> lua wrapper.lua

The code works, however, I am looking for suggestions to make table serialization to file much faster than current.

Please note that I am using Lua 5.1 on a 64-bit Ubuntu PC.


texts:
I'm currently attempting to learn Haskell after a fair history of imperative programming. When I saw the Pizza Hut Pi Day math problems, I thought the first one would be a good candidate for my Haskell experimenting.  The question is:

  I’m thinking of a ten-digit integer whose digits are all distinct. It happens that the number formed by the first n of them is divisible by n for each n from 1 to 10. What is my number?

And I came up with the following code:

module Main where
import System.Environment

import Data.List

pizza2 = [ x | x <- [1000000000..9999999999],
            (x `div` (10 ^ 0)) `mod` (10) == 0,
            (x `div` (10 ^ 1)) `mod` (9) == 0,
            (x `div` (10 ^ 2)) `mod` (8) == 0,
            (x `div` (10 ^ 3)) `mod` (7) == 0,
            (x `div` (10 ^ 4)) `mod` (6) == 0,
            (x `div` (10 ^ 5)) `mod` (5) == 0,
            (x `div` (10 ^ 6)) `mod` (4) == 0,
            (x `div` (10 ^ 7)) `mod` (3) == 0,
            (x `div` (10 ^ 8)) `mod` (2) == 0,
            (x `div` (10 ^ 9)) `mod` (1) == 0,
            nub ( show x ) == show x]

main :: IO ()
main = do
putStrLn (show (nub (pizza2)))

To my suprise, this actually compiles, runs, and returns the correct result. However, due to my inexperience (I think), it takes about 9 minutes to run and I feel like it should take less than a minute on the long side and just a couple seconds on the short side.

Two questions:

Why does this take so long?
I really feel like all those extra conditions I wrote should be able to be abstracted into one condition, but I couldn't figure it out on my own. Any ideas on how to condense that into one, more abstract condition?


texts: Warshall's algorithm for transitive closure

texts:
I was going through this code for implementing Warshall's algorithm.
I think the time complexity for this simple problem is huge because there are too many loops running here. The time complexity for this code should be \$O(n^3)\$.

Is there a way to optimize this code so that the time complexity can be reduced a bit?

#include<stdio.h>
#include<unistd.h>
#include<math.h>
int maximum(int,int);
void warshal(int p[10][10],int n)
{
int i,j,k;

for(i=1;i<=n;i++)
 for(j=1;j<=n;j++)
   for(k=1;k<=n;k++)
     p[i][j]=maximum(p[i][j],p[i][k]&&p[k][j]);
}
int maximum(int a,int b)
{                                                       ;
if(a>b)
return(a);
else
return(b);
}
void main()
{
int p[10][10]={0},n,e,u,v,i,j;

 printf("\n Enter the number of vertices:");
 scanf("%d",&n);

 printf("\n input values now\n");
 for(i=1;i<=n;i++)
  for(j=1;j<=n;j++)
   scanf("%d",&p[i][j]);

   printf("\n Matrix of input data: \n");
 for(i=1;i<=n;i++)
 {
   for(j=1;j<=n;j++)
 printf("%d\t",p[i][j]);
 printf("\n");
 }
 warshal(p,n);
 printf("\n Transitive closure: \n");
 for(i=1;i<=n;i++)
 {
 for(j=1;j<=n;j++)
 printf("%d\t",p[i][j]);
 printf("\n");
 }
  }


texts: File to String Pattern for uploading to a server

texts:
I need to upload some images to a server. This is done with a json object. The json object has 2 values, a timestamp and a Base64 encoded string of the image. I am using the jackson library and was wondering if this is a good way to upload the images. I am worried about memory consumption if I happen to upload images asyncronusly in the future. Here is is...

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Photo {

    @JsonIgnore
    private String path;
    private String id;
    @JsonProperty("ts")
    private long timestamp;

    public Photo(long timestamp, String path) {
        this.timestamp = timestamp;
        this.path = path;
    }

    public String getData() {
        Bitmap bm = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        bm.recycle();
        byte[] byteArray = baos.toByteArray();
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }
}


texts:
Telegram Bot that retrieves book information from GoodReads

I've created a Telegram bot that implements the inline/offline modes to get the brief info about a book, searched by title(inline mode) or with command /random. The data is retrieved from GoodReads. I was wondering how can I modify the body of 'description', so that I would be able to add here that rating info and name of the author? The "idea" of the interpretation is as an example of IMDB's bot

The GoodReads client

import goodreads
from goodreads import client
import random

client_key = '[redacted']
client_secret = '[redacted']

gc = client.GoodreadsClient(client_key, client_secret)

def parse_book(book):
    return {
        'title': book_data.title,
        'author': book_data.authors[0],
        'rating': book_data.rating,
        'review': book_data.review,
        'cover': book_data.image_url,
        'link': book_data.link
    }

  def book_info(title):
      books = gc.search_books(str(title), page=1, search_field='all')

      return map(parse_book, books)

  def random_book():
      index = random.randint(1, 1000000)
      book = gc.book(index)

      return parse_book(book)

The Telegram Bot implementation

import telebot
from telebot import types
import gd

token = '[redacted']
bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])  # greeting
def send_welcome(message):
    bot.reply_to(message.chat.id, "Hi! How are you?")

@bot.message_handler(commands=['help'])  # command list
def send_welcome(message):
    bot.reply_to(message.chat.id, "This bot can do: ")

@bot.message_handler(commands=['random']) # /random
def random(message):
    book = random_book()
    text = "Some text"
    bot.send_message(message.chat.id, text, disable_web_page_preview=False)

@bot.inline_handler(lambda query: query.query == 'text')  # inline session
def query_text(query):
    raise Http404("Poll does not exist")
    book_req = book_info(query)
    try:
        result = []
        i = 0
        for book in book_req:
            result.append(types.InlineQueryResultArticle(id=i,
                title=book[i]['title'],
                url=book[i]['link'],
                hide_url=True,
                description=book[i]['review'],
                thumb_url=book[i]['cover'], thumb_width=48, thumb_height=48
                ))
            i += 1
        bot.answer_inline_query(query.id, result)
    except Exception as e:
        print("{!s}\n{!s}".format(type(e), str(e)))

def main_loop():
    bot.polling(True)
    while 1:
        time.sleep(3)

if __name__ == '__main__':
    try:
        main_loop()
    except KeyboardInterrupt:
        print >> sys.stderr, '\nExiting by user request.\n'
        sys.exit(0)


texts: Writing an excel doc with a subset of my data in R. Currently the code is excessively long

texts:
I'm fairly new to R. I have used the 'r2excel' package to create an excel workbook from a subset of my R data. This should have 3 sheets for the three different subsets. What I have written works fine, but its a lot of code and is very clunky, just re written three times.
If there is a better way of framing my question/best practice tips, I'd love to learn.

# Create an Excel workbook.
filename <- "validitycheck.xlsx" #The name of the file that will be saved
wb <- createWorkbook(type="xlsx") #Creating an excel workbook

# Create a sheet in that workbook to contain the data table
sheet1 <- createSheet(wb, sheetName = "prime1")
sheet2 <- createSheet(wb, sheetName = "prime2")
sheet3 <- createSheet(wb, sheetName = "prime3")

# Add header for sheet 1
xlsx.addHeader(wb, sheet1, value="Prime 1",level=1,
               color="black", underline=1)
xlsx.addLineBreak(sheet1, 1)

# Add header for sheet 2
xlsx.addHeader(wb, sheet2, value="Prime 2",level=1,
               color="black", underline=1)
xlsx.addLineBreak(sheet2, 1)

# Add header for sheet 3
xlsx.addHeader(wb, sheet3, value="Prime 3",level=1,
               color="black", underline=1)
xlsx.addLineBreak(sheet3, 1)

# Add a paragraph : Author
author=paste("Author : Gabriella. \n",
             "20% randomly chosen validity check.",
             "\n Source: filename", sep="")

#Add author for sheet 1
xlsx.addParagraph(wb, sheet1,value=author, isItalic=TRUE, colSpan=5,
                  rowSpan=4, fontColor="darkgray", fontSize=14)

#Add author para for sheet 2
xlsx.addParagraph(wb, sheet2,value=author, isItalic=TRUE, colSpan=5,
                  rowSpan=4, fontColor="darkgray", fontSize=14)

#Add author para for sheet 3
xlsx.addParagraph(wb, sheet3,value=author, isItalic=TRUE, colSpan=5,
                  rowSpan=4, fontColor="darkgray", fontSize=14)

xlsx.addLineBreak(sheet1, 3)
xlsx.addLineBreak(sheet2, 3)
xlsx.addLineBreak(sheet3, 3)

# Add table : add a data frame for sheet 1
xlsx.addHeader(wb, sheet1, value="Validty for prime 1")
xlsx.addLineBreak(sheet1, 1)
xlsx.addTable(wb, sheet1, sample_prime1,
               fontColor="darkblue", fontSize=14,
              rowFill=c("white", "lightblue"),
              startCol=2,
              row.names=FALSE,
              col.names = TRUE)

# Add table : add a data frame for sheet 2
xlsx.addHeader(wb, sheet2, value="Validty for prime 2")
xlsx.addLineBreak(sheet2, 1)
xlsx.addTable(wb, sheet2, sample_prime2,
               fontColor="darkblue", fontSize=14,
              rowFill=c("white", "lightblue"),
              startCol=2,
              row.names=FALSE,
              col.names = TRUE)

# Add table : add a data frame for sheet 3
xlsx.addHeader(wb, sheet3, value="Validty for prime 3")
xlsx.addLineBreak(sheet3, 1)
xlsx.addTable(wb, sheet3, sample_prime3,
               fontColor="darkblue", fontSize=14,
              rowFill=c("white", "lightblue"),
              startCol=2,
              row.names=FALSE,
              col.names = TRUE)

# save the workbook to an Excel file
saveWorkbook(wb, filename, password = "secret")
xlsx.openFile(filename)# View the file
```


texts:
I solved this problem in Ruby:

  Write an utility that takes 3 command-line parameters P1, P2 and P3.
  P3 is OPTIONAL (see below) P1 is always a file path/name. P2 can take
  the values:

  “lines”
  “words”
  “find”

  Only P2 is “find”, then P3 is relevant/needed, otherwise it is not.

  So, the utility does the following:

  If P2 is “rows” it says how many lines it has
  If P2 is “words” it says how many words it has (the complete file)
  If P2 is “find” it prints out the lines where P3 is present

My solution looks like this:

#!/usr/bin/env ruby

def print_usage
  puts "Usage: #{$0} <file> words|lines"
  puts "       #{$0} <file> find <what-to-find>"
end

class LineCounter
  # Initialize instance variables
  def initialize
    @line_count = 0
  end
  def process(line)
    @line_count += 1
  end
  def print_result
    puts "#{@line_count} lines"
  end
end

class WordCounter
  # Initialize instance variables
  def initialize
    @word_count = 0
  end
  def process(line)
    @word_count += line.scan(/\w+/).size
  end
  def print_result
    puts "#{@word_count} words"
  end
end

class WordMatcher
  # Initialize instance variables, using constructor parameter
  def initialize(word_to_find)
    @matches = []
    @word_to_find = word_to_find
  end
  def process(line)
    if line.scan(/#{@word_to_find}/).size > 0
      @matches << line
    end
  end
  def print_result
    @matches.each { |line|
      puts line
    }
  end
end

# Main program
if __FILE__ == $PROGRAM_NAME

  processor = nil

  # Try to find a line-processor
  if ARGV.length == 2
    if ARGV[1] == "lines"
      processor = LineCounter.new
    elsif ARGV[1] == "words"
      processor = WordCounter.new
    end
  elsif ARGV.length == 3 && ARGV[1] == "find"
    word_to_find = ARGV[2]
    processor = WordMatcher.new(word_to_find)
  end

  if not processor
    # Print usage and exit if no processor found
    print_usage
    exit 1
  else
    # Process the lines and print result
    File.readlines(ARGV[0]).each { |line|
      processor.process(line)
    }
    processor.print_result
  end

end

My questions are:

Is there a more Ruby-esque way of solving it?
More compact, but still readable / elegant?

It seems checking for correct command-line parameter combinations takes up a lot of space...

Contrast it to the Scala version found here:

https://gist.github.com/anonymous/93a975cb7aba6dae5a91#file-counting-scala


texts: Standard primitive types vs custom structs in public API

texts:
I am writing a .NET library and have a lot of properties like this:

public ??? SomeProperty { get; set; }

where valid values are 0-15 (or from 00000000 to 00001111 in binary). So I should choose a proper type of the property. I see two options:

byte

I can use byte and insert value validation in each property setter:

public byte SomeProperty
{
    get { return _someValue; }
    set
    {
        if (value > 15)
            throw new ArgumentOutOfRangeException(nameof(value), value, "Message.");

        _someValue = value;
    }
}

Advantages:

you don't need to cast literals from 0 to 15 to some another type.

Disadvantages:

value check must be inserted in each property setter;
property signature doesn't reflect valid values.

custom value type

Or I can create a struct like FourBitNumber handling invalid values in its constructor:

public struct FourBitNumber
{
    private readonly byte _someValue;

    public FourBitNumber(byte value)
    {
        if (value > 15)
            throw new ArgumentOutOfRangeException(nameof(value), value, "Message.");

        _someValue = value;
    }
}

and use this struct as type for the property:

public FourBitNumber SomeProperty { get; set; }

Advantages:

user of the API takes care about passed values by casting them to FourBitNumber so the library always gets valid values;
property type clearly says what valid values are.

Disadvantages:

you need always cast values of primitive types to FourBitNumber which is inconvenient especially with literals.

At now the second way seems better for me but necessity of casting everywhere is really annoying. What other aspects should I take into an account to take final decision?


texts:
I'm working on an hours of operation display, which list the hours out:

Monday - Friday / 8 - 4
Saturday / 8 - 2
Sunday / Closed

I have my script add a class to highlight the lines depending on which day of the week it is, but I wonder another way to complete the task. I would like it if I was able to define monday-friday as one instead of the entire list of them in classes.

var now = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var checkTime = function() {
  var today = weekday[now.getDay()];
  var timeDiv = document.getElementById('timeDiv');
  var dayOfWeek = now.getDay();
  var hour = now.getHours();
  var minutes = now.getMinutes();

  //add AM or PM
  var suffix = hour >= 12 ? "PM" : "AM";

  // add 0 to one digit minutes
  if (minutes < 10) {
    minutes = "0" + minutes
  };

  if ((dayOfWeek == 6) && hour >= 8 && hour <= 14) {
    hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
    timeDiv.innerHTML = '' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
    timeDiv.className = 'open';
  }

  else if ((dayOfWeek == 1 || dayOfWeek == 2 || dayOfWeek == 3 || dayOfWeek == 4  || dayOfWeek == 5) && hour >= 8 && hour <= 16) {
    hour = ((hour + 11) % 12 + 1);
    timeDiv.innerHTML = 'Hi!! ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
    timeDiv.className = 'open';
  }

  else {
    if (hour == 0 || hour > 12) {
      hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
    }
    timeDiv.innerHTML = ' Sorry—we\'re closed!';
    timeDiv.className = 'closed';
  }
};

    var currentDay = weekday[now.getDay()];
    var currentDayCLASS = "." + currentDay; //gets todays weekday and turns it into     class
    $(currentDayCLASS).toggleClass("today"); //hightlights today in the view hours

    setInterval(checkTime, 1000);
    checkTime();

Hours

Monday - Friday

8:00am - 4:00pm

Saturday

8:00am - 2:00pm

Sunday

Closed


texts:
As I've mentioned in previous questions, I am writing MySQL statements to update overlapping database entries and insert new data into various tables. My database design looks something like this, where there's one parent table (hash is the primary key and id is indexed):

+---------------+
| hashes        |
+---------------+
| hash  | id    |
+---------------+
| hash1 | id1   |
| hash2 | id1   |
| hash3 | id1   |
| hash4 | id2   |
+---------------+

And many child tables (id is indexed, there are no primary or unique keys):

+-------------------------+
| other_table             |
+-------------------------+
| id  | group_id  | value |
+-------------------------+
| id1 | groupid1  | val1  |
| id1 | groupid1  | val2  |
| id2 | groupid2  | val3  |
| id2 | groupid3  | val4  |
+-------------------------+

There are foreign key constraints on the child table id columns, so that if any ids in the hashes table are updated, all child tables update with the new information. The ids change when any inserted hashes are overlapped somewhere in the hashes table.

To achieve all this, I wrote the following statement:

START TRANSACTION;

    /* Generated with PHP */
    SET @id = '610de097-26d0-41b2-839b-1bd8c0d05dea';
    SET @group_id = '54c41b95-5897-4984-961c-cc8fc97fc586';

    /* Insert new data */
    INSERT INTO hashes
        (id, hash)
    VALUES
        (@id, 'hash1'), (@id, 'hash2')
    ON DUPLICATE KEY UPDATE
        repeat_count = repeat_count + 1;

    INSERT IGNORE INTO categories
        (id, group_id, value)
    VALUES
        (@id, @group_id, 'some value');

COMMIT;

And a collection of updates to run after everything is inserted:

/* Update all parent table ids for any overlapping hashes */
UPDATE hashes
SET id=@id
WHERE id IN (
    SELECT id
    FROM (SELECT id, hash FROM hashes ORDER BY id) as temp
    WHERE hash IN ('hash1', 'hash2')
    ORDER BY id ASC
);

This works, and with around 950 entries to insert, it takes around 25 seconds to run. The slowest part, by far, is the many update statements since it needs to search over the entire hash table and update rows accordingly.

Consequently, if I want to see any speed improvements, I need to modify those update statements. Any ideas?


texts:
I am writing a conditional that checks two values, for several different scenarios.

What I am modifying is a series of objects, some of these objects are in arrays, and some are just arrays. I need to check these values and then check a file, and then check my values (the series of objects, array objects, and arrays) and then "Update" the old data with my new data if needed. However the user has the ability to turn some sections off if they don't want their data to be overwritten in the case of changes. So in order to do this I check if a certain property exists (the ones used to turn them on or off) and then check if its on or if its off. which has led to a conditional of this size: (And this is NOT everything, I stopped here to see if there was a shorter less counter-productive way of doing this

if ((this.Config[key] === this.Config.PunishTiers || this.Config[key] === this.Config.Titles || this.Config[key] === this.Config.Ranks || this.Config[key] === this.Config.Messages && this.Config.Message.Messages) || (this.Config[key] === this.Config.Prefix && this.Config.Prefix.Prefixes))
             || (this.Config[key] === this.Config.Settings && this.Config.Settings.Settings)) {
                oldData.push(this.Config[key]);
        }

The first three checks do not have the setting, so they are fine but everything after has the check if it exists, and check for the setting to be on or off. Is there any way to reduce this? Make it neater and possibly less of a struggle when used.

This has to stick with mainly pure JavaScript if possible.

This is being used through a plugin for the oxide framework. To check a plugin's configuration file grab the data, check for local configs and apply changes where specified. or "Updates"

Here is the whole function setup:

loadSmartConfig: function(changed) {
            print("Smart Updating Data Now.")
            var oldData = [],
                newData = [];
            for (var key in this.Config) {
                if (this.Config[key] === this.Config.PunishTiers || this.Config[key] === this.Config.Titles || this.Config[key] === this.Config.Ranks) {
                    oldData.push(this.Config[key]);
                if ((this.Config[key] === this.Config.Messages && this.Config.Message.Messages)
                    || (this.Config[key] === this.Config.Prefix && this.Config.Prefix.Prefixes)
                    || (this.Config[key] === this.Config.Settings && this.Config.Settings.Settings)) {
                    oldData.push(this.Config[key]);
                }
                } else {
                    continue;

}
            }
            if (oldData.length > 0) {
                this.LoadDefaultConfig();
            }

        if (this.Config.PunishTiers !== undefined && this.Config.Titles !== undefined && this.Config.Ranks !== undefined) {
            for (var i = 0; i < oldData.length; i++) {
                if (oldData[i].length === 1) {
                    this.Config.PunishTiers = oldData[i];
                } else if (oldData[i].hasOwnProperty("authLvl")) {
                    this.Config.Titles = oldData[i];
                } else if (oldData[i].hasOwnProperty("rank")) {
                    this.Config.Ranks = oldData[i];
                } else if (oldData[i].hasOwnProperty("Messages") && oldData[i].Messages) {
                    this.Config.Messages = oldData[i];
                } else if (oldData[i].hasOwnProperty("Prefixes") && oldData[i].Prefixes) {
                    this.Config.Prefix = oldData[i];
                } else if (oldData[i].hasOwnProperty("Settings") && oldData[i].Settings){
                    this.Config.Settings = oldData[i];
                }
            }
            this.SaveConfig();
        },

this is also why I was pushing for pure JavaScript if possible.


texts:
I'm trying to write an equivalent of PHP's htmlspecialchars() in C. What is my implementation missing or doing wrong?

char www_specialchars_html(char *dest, char *dest_last, char *src) {
while (*src != 0) {
    switch(*src) {
        //If a special character is found, replace with its HTML entity.
        case '&':
            if ((dest + 5) > dest_last) {
                return 1;
            }
            *dest = '&';
            dest++;
            *dest = 'a';
            dest++;
            *dest = 'm';
            dest++;
            *dest = 'p';
            dest++;
            *dest = ';';
            dest++;
            src++;
            break;
        case '"':
            if ((dest + 6) > dest_last) {
                return 1;
            }
            *dest = '&';
            dest++;
            *dest = 'q';
            dest++;
            *dest = 'u';
            dest++;
            *dest = 'o';
            dest++;
            *dest = 't';
            dest++;
            *dest = ';';
            dest++;
            src++;
            break;
        case '\'':
            if ((dest + 6) > dest_last) {
                return 1;
            }
            *dest = '&';
            dest++;
            *dest = '#';
            dest++;
            *dest = '0';
            dest++;
            *dest = '3';
            dest++;
            *dest = '9';
            dest++;
            *dest = ';';
            dest++;
            src++;
            break;
        case '<':
            if ((dest + 4) > dest_last) {
                return 1;
            }
            *dest = '&';
            dest++;
            *dest = 'l';
            dest++;
            *dest = 't';
            dest++;
            *dest = ';';
            dest++;
            src++;
            break;
        case '>':
            if ((dest + 4) > dest_last) {
                return 1;
            }
            *dest = '&';
            dest++;
            *dest = 'g';
            dest++;
            *dest = 't';
            dest++;
            *dest = ';';
            dest++;
            src++;
            break;
        case '\\': //Not required in HTML.
            if ((dest) > dest_last) {
                return 1;
            }
            src++;
            break;
        default:
            //Default for characters that don't need to be replaced.
            if ((dest + 1) > dest_last) {
                return 1;
            }
            *dest = *src;
            src++;
            dest++;
            break;
    }
}
*dest = 0;
return 0;
}

The function takes pointers to the destination, the last element of the destination and the source. It returns 1 if it can't write to the destination, and returns 0 when it has successfully copied to the destination. I'm still a relatively new C programmer.


texts:
This is a INSERT function. It's working... I just pulled out the function from the class, atm to try it out. And improve. I think the code is a bit messy, And I am pretty sure I can improve the code, less code, for example.. Any ideas?

   $data['test'] = array('username' => 'john',
              'password' => 'hello',
              'userlevel' => '__d');

$table = 'users';

$numItems = count($data['test']);
$i = 0;

$sql = "INSERT INTO " . $table . "(". implode(", ", array_keys($data['test'])) .")";

$sql .= " VALUES (";

$i = 0;

foreach ($data['test'] as $value) {

    if ($i+1 == $numItems and $value == '__d') {
        $sql .= "" . 'NOW()' . ")";
    } else if ($i+1 == $numItems) {
        $sql .= "'" . $value . "')";
    } else if ($value == '__d') {
        $sql .= "" . 'NOW()' . ", ";
    } else {
        $sql .= "'" . $value . "', ";
    }

            $i++;

}

echo $sql;


texts: Helper function to make `setTimeout` synchronous

texts:
I'm making a helper function to make setTimeout synchronous. Currently, it is asynchronous so other code runs before the timeout is done.

function syncSetTimeout(func, ms, callback) {
    (function sync(done) {
            if (!done) {
            setTimeout(function() {
                eval("(" + func + ")();");
                sync(true);
            }, ms);
            return;
        }
        eval("(" + callback + ")();");
    })();
}

func is a function that should be run after the specified timeout.
ms specifies how many milliseconds to wait before running func.
callback is the function that runs after the func is done running.

Is there a way to get rid of those eval statements? I've read that eval is evil. I'm also wondering if I can do this without a nested function. If there are any other ways to improve this code then please say so.


texts: High performance exponential of a skew Hermitian matrix in Fortran 95

texts:
I'm new to Fortran, and this is pretty much my first escapade. Below is a function that I wrote which relies on calls to LAPACK. The function is sat in a module with some other functions and works perfectly, but seeing as this is really the workhorse of the program I'm building I want to squeeze it hard for performance. How does it look? Am I doing anything stupid, or would another call to BLAS or LAPACK somewhere improve the performance?

The function takes a Hermitian matrix H, and returns the matrix exponential of the skew-Hermitian matrix -iHt where i is the imaginary number and t is a real number. (This is the solution to the Schrodinger equation for a time independent Hamiltonian.) s, the length of one side of the Hamiltonian, is included for automatic array initialisation rather than using allocations. Typically it'll be less than 10.

function time_indep_schrodinger(s,H,t)
    ! s : The length of one side of H.
    ! H : The Hamiltonian.
    ! t : The time t.
    !
    ! The LAPACK subroutine zheev requires a tridiagonal
    ! subcopy of H. This array is then transformed into
    ! a matrix of eigenvectors. This also yields the
    ! eigenvalues as a 1D array, which are then
    ! exponentiated before using the matrices of
    ! eigenvectors to produce the evolution operator.
    !
    ! Finds the eigenvalues of Ht, then uses U exp(-i*eigs) U^H.

    integer,    intent(in) :: s
    complex*16, intent(in) :: H(s,s)
    real*8,     intent(in) :: t
    complex*16             :: B(s,s), eigv(s,s), time_indep_schrodinger(s,s), work(2*s-1)
    real*8                 :: rwork(3*s-2), eigs(s)
    integer                :: info, n, m

    ! Hermitian matrix to diagonalise.
    forall (n=1:s, m=1:s, m>=n) eigv(n,m) = H(n,m)*t

    ! Get eigenvectors and eigenvalues.
    call zheev('V','U',s,eigv,s,eigs,work,2*s-1,rwork,info)

    ! Scale columns of copied matrix be exponentiated eigenvalues (with -i).
    do n=1,s
      B(:,n) = eigv(:,n)*exp((0,-1)*eigs(n))
    end do

    ! Finally multiply scaled eigenvectors with conjugate of eigv.
    time_indep_schrodinger = matmul(B,conjg(transpose(eigv)))

end function


texts: React multi-select-like component with filter

texts:
I am new to react (and javascript in general) but am enjoying learning it.
I have decided to make a little multiselect component which should work as follows:

I start with my data in one list, when I select an item from the list it goes into a second list (I can 'unselect' as well).

I also can filter the first list with a text input.

Before you review, I realize that there are likely existing solutions for this functionality that I could use, but I am just doing this to learn.

codepen here https://codepen.io/str8wavedave/pen/ZqWXQp

class MultiSelect extends React.Component {
  render(){
    return(

      {this.props.objects.map((object, index) =>
 this.props.onClickFunction(index)}>{object.name}
)}

    );
  }
}

class DoubleMultiselect extends React.Component {
  state = {
    value: '',
    filteredUnselectedObjects: this.props.objects,
    unselectedObjects: this.props.objects,
    selectedObjects: [],
  }
  filterList = (event) => {
    var updatedList = this.state.unselectedObjects;
    updatedList = updatedList.filter(function(item){
      return item.name.toLowerCase().search(
      event.target.value.toLowerCase()) !== -1;
    });
    this.setState({
      filteredUnselectedObjects: updatedList,
      value: event.target.value
    })
  }
  handleSelect = (index) => {
    var obj = this.state.filteredUnselectedObjects[index]
    var newSelected = this.state.selectedObjects.slice()
    newSelected.push(obj)

    var newUnselected = this.state.unselectedObjects.slice()
    var originalIndex = newUnselected.indexOf(obj);
    newUnselected.splice(originalIndex, 1)

    var newFilteredUnselected = this.state.filteredUnselectedObjects.slice()
    newFilteredUnselected.splice(index, 1)

    this.setState({
      selectedObjects: newSelected,
      unselectedObjects: newUnselected,
      filteredUnselectedObjects: newFilteredUnselected
    });
  }

  handleUnselect = (index) => {
    var obj = this.state.selectedObjects[index]
    var newUnselected = this.state.unselectedObjects.slice()
    newUnselected.push(obj)

    var newFilteredUnselected = this.state.filteredUnselectedObjects.slice()
    if(obj.name.toLowerCase().search(this.state.value.toLowerCase()) !== -1)
    {
      newFilteredUnselected.push(obj)
    }
    var newSelected = this.state.selectedObjects.slice()
    newSelected.splice(index, 1)
    this.setState({
      unselectedObjects: newUnselected,
      selectedObjects: newSelected,
      filteredUnselectedObjects: newFilteredUnselected
    });
  }

  render() {
    return(

        <input type="text" onChange={this.filterList}/>
        <MultiSelect objects={this.state.filteredUnselectedObjects} onClickFunction={this.handleSelect}/>
        <MultiSelect objects={this.state.selectedObjects} onClickFunction={this.handleUnselect}/>

    );
  }
}
const PLAYERS =[
  {name: 'Charlie', id: 1},
  {name: 'David', id: 2},
  {name: 'Eric', id: 3},
  {name: 'Emily', id: 4},
  {name: 'Peter', id: 5},
  {name: 'Sam', id: 6},
  {name: 'Doug', id: 7}
]
React.render(<DoubleMultiselect objects={PLAYERS}/>, document.getElementById('app'));


texts:
I've written a simple web scraper in Python. As it is my first venture in Python, I'd like to ask for a code review from more experienced coders. All input is welcome.

A little bit of background:

I'm a huge fan of video games. In Japan, there is a company called Media Create which tracks all sales of games and consoles and releases them weekly (in Japanese language). Another site (www.gematsu.com) translates those charts and releases them weekly on their website. My script fetches the data and saves it to a text file.

The script should run as-is, but it is dependent on a text file of the previous week existing in script-location/data.

The name of the script needs to be something like media-create-sales-11-26-18-12-2-18.txt (replacing the start and end dates with any dates other than the dates of the most recently released data).

I am not affiliated with Media Create or Gematsu and this script serves no commercial purpose.

import requests
from bs4 import BeautifulSoup
import datetime
import glob
import os

def getLatestFilename():

    list_of_files = glob.glob('data/*')
    latest_file = max(list_of_files, key=os.path.getctime)

    return latest_file

def parseUrl(dateString):

    dateString = dateString.split('-')

    lastdateString = str("-".join(dateString[6:9])).split('.')[0]

    lastdate_object = datetime.datetime.strptime(lastdateString, "%m-%d-%y")

    current_startdatetime_object = lastdate_object + datetime.timedelta(days=1)
    current_enddatetime_object = lastdate_object + datetime.timedelta(days=7)

    cur_startDateString = current_startdatetime_object.strftime("%m-%d-%y").lstrip("0").replace("0", "")
    cur_endDateString = current_enddatetime_object.strftime("%m-%d-%y").lstrip("0").replace("0", "")

    return (cur_startDateString + '-' + cur_endDateString)

def getUrl(filename):

    curIntervalString = parseUrl(filename)

    now = datetime.datetime.now()

    url = list()
    url.append("https://gematsu.com/")
    url.append(str(now.year))
    url.append('/')
    url.append(str(now.month))
    url.append('/')
    url.append('media-create-sales-')
    url.append(curIntervalString)

    return url

def fetchContentForUrl(url):

    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')

    outputfile = open("data/media" + url.split('media')[1] + ".txt", "w")

    outputfile.write(url + '\n' + '\n')

    content = soup.find(class_='entry')

    gameCharts = content.findNext('ol')
    gameEntries = gameCharts.find_all('li')

    for idx,entry in enumerate(gameEntries,start=1):
        outputfile.write(str(idx) + "." + entry.get_text() + "\n")

    print ('\n')

    consoleCharts = gameCharts.find_next_sibling("ol")
    consoleEntries = consoleCharts.find_all('li')

    for entry in consoleEntries:
        outputfile.write(entry.get_text() + "\n")

def main():
    latestFilename = getLatestFilename()
    print (latestFilename)
    url = ''.join(getUrl(latestFilename))
    print (url)
    fetchContentForUrl(url)

if __name__ == '__main__':
    main()


texts:
I wrote a little class that will calculate 6 business days from today. The reason it's in a class is because it will be used as a part of a bigger program.

I would like a way to refactor this class and make it a little more object oriented along with a little prettier.

from datetime import datetime, timedelta

class BusinessDay(object):
    """
    Calculate a business day of 6 days skipping Saturday and Sunday
    """
    return_date = []  # Array to store the calculated day

    def __init__(self, start_day):
        """
        :type start_day: Object, datetime object
        """
        self.start_day = start_day

    def calc_bus_day(self):
        """Calculate 6 business days from the self.start_day example:
        >>> import BusinessDay
        >>> test = BusinessDay(datetime(2016, 9, 14))
        >>> test.calc_bus_day()
        >>> #2016-09-22
        """
        days_skipped = self.start_day + timedelta(8)

        if datetime.isoweekday(days_skipped) in range(2, 6):
            print("Date {} is a weekday.".format(self.start_day))
            self.return_date = days_skipped
            print("Six days from today will be {}".format(self.return_date))
        else:
            print("Date {} is a weekend.".format(self.start_day))
            self.return_date = days_skipped + timedelta(2)
            print("Six days from the weekend will be {}".format(self.return_date.strftime("%m-%d-%Y")))

        if self.return_date.isoweekday() is 1 or 7:
            if self.return_date == 1:
                self.return_date = self.return_date + timedelta(2)
                return self.return_date - timedelta(2)
            else:
                self.return_date = self.return_date + timedelta(1)
                return self.return_date - timedelta(2)


texts:
I'm trying to learn functional programming and Scala, following through Project Euler problems.

I'm solving get the sum of multiples x & y in a list. So for a list [1,2,3,4,5,6,7,8,9] get multiples of 3, 5 returns 3, 5, 6 and 9, the sum being 23.

I'm accepting two parameters list and multiples
Mapping multiples to list of functions, that test if input is a multiple
Filtering anything that returns true in the mapped multiples list

  def multiplesOf(list: List[Int], multiples: List[Int]): List[Int] = {
    def filterMultipleOf(x: Int) : Int => Boolean = (y: Int) => {
      y % x == 0
    }
    val multiplesFilter = multiples.map(filterMultipleOf(_))
    list.filter( int => multiplesFilter.exists(mOf => mOf(int)))
  }

scala> multiplesOf(List.range(1,10), List(3,5)).sum
res: Int = 23

My main question: Is this the Scale/FP way?

Is defining filterMultipleOf inside my function still pure? Is there a better way to express this in Scala or FP?


texts: Encoding a list of frequencies as WAV audio

texts:
This code gets a list of signals with predefined frequency from struc.num

I need to encode it to wave format, so i use this code. This works, but i dont sure it is a correct decision to encode like this in python. Is there any ways to do it better?

def compiler():
    import out
    print("Loaded out.py")
    print("Compiling...")
    lst = list(my_code(out.code))
    print("Compiled!")
    print("Linking...")

    print("Bytes len: ", len(lst), " = ", blen * len(lst))

    music = wave.open('out.wav', 'w')
    music.setparams((2, 1, freq, 0, 'NONE', 'not compressed'))

    for i in lst:
        if (i == "0"):
            packed_value = wave.struct.pack('h', 0)
            for _ in range(100):
                music.writeframes(packed_value)
            continue

        key = i[0:i.find("(")]
        frame = Syntax.struc.num[int(key)]

        duration = 0.05
        samplerate = freq  # Hz
        samples = duration * samplerate
        frequency = frame #Hz
        period = samplerate / float(frequency)  # in sample points
        omega = N.pi * 2 / period

        xaxis = N.arange(int(period), dtype=N.float) * omega
        ydata = 16384 * N.sin(xaxis)

        signal = N.resize(ydata, 400) # 2-й параметр - скорость

        ssignal = b''
        for i in range(len(signal)):
            ssignal += wave.struct.pack('h', int(signal[i]))  # transform to binary

        music.writeframes(signal)

        #packed_value = wave.struct.pack('h', frame)
        #for _ in range(blen):
        #    music.writeframes(packed_value)
    music.close()

print("Linked to out.wav!")


texts:
I have a some classes and interface

public interface IGeoObject
    {
        GeoCoordinate GetGeocoordinate();
    }

public class User : IGeoObject
    {
        public GeoCoordinate GetGeocoordinate()
        {
            //...
            return GeoCoordinate;
        }
    }

public class Venue : IGeoObject
    {
        public GeoCoordinate GetGeocoordinate()
        {
            //...
            return GeoCoordinate;
        }
    }

public class Place : IGeoObject
    {
        public GeoCoordinate GetGeocoordinate()
        {
            //...
            return GeoCoordinate;
        }
    }

I have, example variable users with type List<User>

And I have method with signature

double GetMinDistance(List<IGeoObject> objects, GeoCoordinate position)

I can't pass users to GetMinDistance, because covariance of generic types not work.

I can create additional list and use method .ConvertAll (or .CasT<T>):

List<IGeoObject> list = new List<User>(listUser).ConvertAll(x => (IGeoObject)x);
var dist = GeoTest.GetMinDistance(list, position);

I'm not sure that this is the most elegant solution. Most embarrassing that the caller must do this conversion.

This is similar to my problems in the architecture? There are more elegant solutions?

P.S. Long story, but I really can not give the coordinates of the same species in all classes.


texts: Too many null checks in an XML-to-XML transformation

texts:
I'm writing a conversion mechanism in C#. I deserialize a big XML document of one type and return a big XML document of another type (via serialization of another object).

While I'm doing the conversion, I find myself doing a TON of null checks (checking whether or not a certain property has a value, which then would need to be translated). Here's an example piece of code:

if (MyPatientCareReport.eHistory != null && // Check if eHistory field exists
    MyPatientCareReport.eHistory.eHistoryCurrentMedsGroup != null && // Check if group exists
    MyPatientCareReport.eHistory.eHistoryCurrentMedsGroup.Count > 0 && // Make sure items exist
    MyPatientCareReport.eHistory.eHistoryCurrentMedsGroup[0].eHistory12 != null && // Null check
    MyPatientCareReport.eHistory.eHistoryCurrentMedsGroup[0].eHistory12.PN != "8801015") // None reported value (NEMSIS)
{
    string PertinantNegatives = MyPatientCareReport.eHistory.eHistoryCurrentMedsGroup[0].eHistory12.PN;
    if (PertinantNegatives == "8801019" || PertinantNegatives == "8801023")
    {
        // Add a new XML serializable boolean to the CDA object
        BL MyBL = new BL();
        MyBL.nullFlavor = "NI";
        MyCurrentlyOnMedicationObservation.value.Add(MyBL);
    }
    else
    {
        MyCurrentlyOnMedicationObservation.value.Add(new BL(true));
    }
}
else
{
    MyCurrentlyOnMedicationObservation.value.Add(new BL(false));
}

To me this look ugly. Should I be doing this a different way? If so, how?


texts:
This program downloads a Code Review HTML file and parses it.

Could you review my program?

Main.java

import java.net.URL;

public class Main {
    public static void main(String[] args) throws Exception {
        final String site1 = "http://codereview.stackexchange.com/questions/";
        String site2;
        String site3;
        URL url;
        HtmlGetter htmlGetter = new HtmlGetter();

        while(true) {
            site2 = "69";
            site3 = "is-this-implementation-of-shamos-hoey-algorithm-ok";
            url = new URL(site1 + site2 + "/" + site3);
            htmlGetter.setFileName("[" + site2 + "]" + site3 + ".html");
            htmlGetter.download(url);
            htmlGetter.parse();
            break;
        }
    }
}

HtmlGetter.java

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.Scanner;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.io.IOUtils;

public class HtmlGetter {
    private String fileName;

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() {
        return fileName;
    }

    public void download(URL url) throws Exception {
        final InputStream in = url.openStream();
        final OutputStream out = new FileOutputStream(fileName);
        IOUtils.copy(in, out);
        in.close();
        out.close();
    }

    public void parse() throws Exception {
        Scanner scanner = new Scanner(new File(fileName));
        String oneLine;
        String htmlTagRegex = "<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>";

        while(scanner.hasNextLine()) {
            oneLine = scanner.nextLine();
            if(oneLine.matches(".*<code>.*")) {
                while(scanner.hasNextLine()&&(!oneLine.matches(".*</code>.*"))) {
                    oneLine = StringEscapeUtils.unescapeHtml4(oneLine.replaceAll(htmlTagRegex, ""));
                    System.out.println(oneLine);
                    oneLine = scanner.nextLine();
                    // This cannot handle such kind of a line which has <code> and </code> together.
                }
                System.out.println("-------------------------------------------");
            }
        }
    }
}


texts: 32-bit factorial calculator in x86 NASM assembly

texts:
This is how it handles input:

if negative, terminate program
if 0-2, display input without calculating
if greater than or equal to 3, calculate and display result

I have also used some macros from an included file:

nwln: outputs a newline
PutStr: displays a label
GetLInt: receives a 32-bit integer
PutLInt: displays a 32-bit integer

My questions:

Is my input validation reducing readability, or is that not important as long as the program proceeds with only the correct input?
Should I need to check for non-numerical values, or does it not really matter?
Since the result register (EAX) is 32-bit, should I take into account a possible result that may not fit in 32 bits?  If I get a larger result, it won't display properly, and the user may be unaware.
Is doing a bunch of adds still faster than using mul?  I'm also avoiding mul because I still have trouble getting all the bits in the right place.
Should any of these procedures be organized differently?  I'm still not sure how important this is in assembly when most procedures have jumps or branches.  In this program, it makes sense to have check_input after get_input and with no jump in between them.

Other than that, I'd like a review on anything you may find.

%include "macros.s"

.DATA

input_lbl:       DB   "Number: ", 0
bad_input_lbl:   DB   "Number must be positive!", 0
result_lbl:      DB   "Total: ", 0

input:    DD   0
result:   DD   0

.CODE
.STARTUP

; EAX - input
; EBX - input (for counter)
get_input:
   PutStr    input_lbl
   GetLInt   [input]
   mov       EAX, [input]
   mov       EBX, [input]

; EBX - input
check_input:
   ; terminate if input is negative
   cmp   EBX, 0
   jl    report_bad_input

   ; no need to calculate if below 3
   cmp    EBX, 3
   jge    calc_factorial

   ; input is 0, 1, or 2
   jmp    display_result

report_bad_input:
   PutStr   bad_input_lbl
   .EXIT

; EAX - result
display_result:
   nwln
   mov       [result], EAX
   PutStr    result_lbl
   PutLInt   [result]
   .EXIT

; EAX - current value
; EBX - counter
; ECX - current total (for multiplication)
; EDX - counter (for multiplication)
calc_factorial:
   ; no need to multiply by 1
   dec   EBX
   cmp   EBX, 1
   je    display_result

   ; perform addition instead of multiplication
   mov   ECX, EAX
   mov   EDX, EBX
   jmp   mult_with_addition

   jmp   calc_factorial

; EAX - current total
; ECX - current total (for multiplication)
; EDX - counter (for multiplication)
mult_with_addition:
   ; determine if addition should stop
   dec   EDX
   cmp   EDX, 0
   je    calc_factorial

   add   EAX, ECX

   jmp   mult_with_addition

Sample tests:

  Input: 3
  Output: 6

  Input: 2
  Output: 2

  Input: 1
  Output: 1

  Input: 0
  Output: 0

  Input: -1
  Output: "Number must be positive!"


texts:
I was working on a practice Java exam online:

  Write a function that, given a list and a target sum, returns
  zero-based indices of any two distinct elements whose sum is equal to
  the target sum. If there are no such elements, the function should
  return null.
       For example, findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12) should return a single dimensional array with two elements and contain any of
  the following pairs of indices:

1 and 4 (3 + 9 = 12)
2 and 3 (5 + 7 = 12)
3 and 2 (7 + 5 = 12)
4 and 1 (9 + 3 = 12)

Here is my solution:

public class TwoSum {

    public static int[] findTwoSum(int[] list, int sum) {
        int[] twoSum = null;
        if(list != null){
            int listSize = list.length;
            int mod = listSize % 2;
            int half = listSize/2;
            int stop = mod > 0 ? half+1 : half;
            if(listSize >= 2){
                outer: for(int currentIndex=0; currentIndex<listSize; currentIndex++){
                            if(currentIndex == stop){
                                break;
                            }
                            for(int otherIndex=0; otherIndex<listSize; otherIndex++){
                                if(currentIndex < otherIndex){
                                    int current = list[currentIndex];
                                    int other = list[otherIndex];
                                    int currentSum = current + other;
                                    if(currentSum == sum){
                                        twoSum = new int[]{currentIndex, otherIndex};
                                        break outer;
                                    }
                                }
                            }
                        }
            }
        }
        return twoSum;
    }

    public static void main(String[] args) {
        int[] indices = findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12);
        System.out.println(indices[0] + " " + indices[1]);
    }
}

My code passed all the unit tests, however, they have another check for a large list, and apparently my code runs too slow when the list size grows. Apart from me trying to decipher what their definition of too slow is, simply put, are there any optimizations I can make to have my code run faster? I tried to find the 'tipping point' in comparing numbers where I could stop checking, and I added that optimization, but apparently, that isn't good enough.


texts: Finding decreasing sequences in an array of numbers

texts:
Ants

  Requirement

  Given a natural number \$n\$, representing the number of days the study is made, and then a number \$x\$ of \$n\$ natural numbers, representing the number of working ant flies after food, where the \$x_i\$ number of working ants is the day \$i\$. It is required to determine the number of maximum sequences, ordered strictly decreasing after the number of divisors, of minimum length \$2\$.

  Input data

  The input file furnici.in contains two lines. On the first line is the natural number \$n\$, with the meaning of the requirement and on the second line, the elements of the string \$x\$, with the meaning in the requirement.

  Output data

  The output file furnici.out will contain a natural number representing the number of maximum sequences, of minimum length \$2\$, ordered strictly downwards by the number of divisors.

  Restrictions and clarifications

  Time Limit - 0.5 seconds
  Memory limit - 64 MB Total / 8 MB Stack
  \$2 \leq n \leq 100000 \$
  \$10 \leq x_i \leq 1.000.000.000\$

  Example

  furnici.in

10
719 169 4065 813 289 101 123 516 516 1017

  furnici.out

2

  Explanation

  Row number of divisions is \$2\ 3\ 8\ 4\ 3\ 2\ 4\ 12\ 12\ 6\$.
  It is noted that there are two maximum sequences, of at least two, strictly decreasing, \$8\ 4\ 3\ 2\$ and \$12\ 6\$.

My program is given an array of numbers that it has to find the divisors for and then replace the number in the array with its corresponding number of divisors. In the new created array, it will have to find and count all the descending subsequences that occur.

Here is my code:

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int n,i,v[100001],nr,j,s;
int main()
{
    ifstream in("furnici.in");
    ofstream out("furnici.out");
    in>>n;
    for(i=1; i<=n; i++)
    {
        in>>v[i];
        nr=2;
        for(j=2; j<=sqrt(v[i]); j++)
        {
            if(v[i]%j==0)
            {
                nr++;
                if(j!=v[i]/j)
                    nr++;
            }
        }
        v[i]=nr;
        if(v[i]<v[i-1])
        {
            j=i;
            while(v[j]<v[j-1] && j<n)
            {
                j++;
                nr=2;
                in>>v[j];
                for(int k=2; k<=sqrt(v[j]); k++)
                {
                    if(v[j]%k==0)
                    {
                        nr++;
                        if(k!=v[j]/k)
                            nr++;
                    }
                }
                v[j]=nr;
            }
            s++;
            i=j;
        }
    }
    out<<s;
    return 0;
}

furnici.in

10
719  169 4065  813  289  101 123  516  516  1017

furnici.out

2

Explained:

10 represents how many numbers are going to be read from the file;
number 719 has 2 divisors, so 719 gets replaced with 2;
number 169 has 3 divisors, so 169 gets replaced with 3;
number 4065 has 8 divisors, so 4065 gets replaced with 8;
and so on, you kind of get the point. The resulting array will have
descending sequences: 2 3 8 4 3 2 4 12 12 6 and these need to be counted.

The issue with it is that it exceeds the time limit in the last test given to it, but otherwise the answer is correct.


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

A message containing letters from A-Z is being encoded to numbers
using the following mapping way:
'A' -> 1
'B' -> 2
...
'Z' -> 26

Beyond that, now the encoded string can also contain the character
'*', which can be treated as one of the numbers from 1 to 9.
Given the encoded message containing digits and the character '*',
return the total number of ways to decode it.
Also, since the answer may be very large, you should return the output
mod \$10^9 + 7\$.
Example 1:

Input: "*"
Output: 9
Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I".

Example 2:

Input: "1*"
Output: 9 + 9 = 18

Example 3:

Input: "2*"
Output: 15

Example 4:

Input: "3*"
Output: 9

Example 5:

Input: "44*4"
Output: 11

Note:

The length of the input string will fit in range [1, 105].
The input string will only contain the character '*' and digits '0' - '9'.

Code
#include <string>
#include <vector>

class Solution {
    static constexpr size_t MOD = 1e9 + 7;
public:
    static size_t numDecodings(const std::string message);
    static size_t decode(const char a_num_ast);
    static size_t decode(const char a_num_ast, const char b_num_ast);
};

inline size_t Solution::decode(const char a_num_ast) {
    if (a_num_ast == '*') {
        return 9;

    } else if (a_num_ast == '0') {
        return 0;

    } else {
        return 1;
    }
}

inline size_t Solution::decode(const char a_num_ast, const char b_num_ast) {
    if (a_num_ast == '1') {
        if (b_num_ast == '*') {
            return 9;

        } else if (b_num_ast >= '0' && b_num_ast <= '9') {
            return 1;
        }

    } else if (a_num_ast == '2') {
        if (b_num_ast == '*') {
            return 6;

        } else if (b_num_ast >= '0' && b_num_ast <= '6') {
            return 1;
        }

    } else if (a_num_ast == '0') {
        return 0;

    } else if (a_num_ast == '*') {
        return decode('1', b_num_ast) + decode('2',  b_num_ast);
    }

    return 0;
}

inline size_t Solution::numDecodings(const std::string message) {
    const size_t length = message.size();
    std::vector<size_t> decodes_dp(3, 0);
    decodes_dp[0] = 1;
    decodes_dp[1] = decode(message[0]);

    for (size_t index = 2; index <= length; index++) {
        decodes_dp[index % 3] = (decodes_dp[(index - 1) % 3] * decode(message[index - 1]) % MOD +
                                 decodes_dp[(index - 2) % 3] * decode(message[index - 2], message[index - 1]) % MOD) % MOD;
    }

    return decodes_dp[length % 3];
}

References

Problem

Solution

Discuss


texts: Project Euler # 24 Lexicographic permutations in Python

texts:
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of
the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call
it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012   021   102   120   201   210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

import itertools

def lexicographic(n, digits):
    """Assumes digits a string.
    returns the nth item of the lexicographic permutation of digits."""
    return list(itertools.permutations(digits))[n - 1]

if __name__ == '__main__':
    permutation = list(lexicographic(1000000, '0123456789'))
    print(''.join(permutation))


texts: Text menu and validation of the chosen item

texts:
I am writing a c# console app that will take a user input from a list of selected options and do things based on the selected option. I have it working right now but just looking over it there seems that I should be able to shorten the code with other methods and make it perform a bit faster and more efficient but for some reason I just can't see it. Am I missing something or is this really the way to be doing this check?

static void Main(string[] arguments)
{
    if (arguments.Length == 0)
    {
        Console.WriteLine("No run mode entered. Usage: JobSightMaintenance <FirstRun | NightlyMaintenance>");
        Console.WriteLine("Please select one of the following options to run:");
        printOptions();

        string userInput;
        bool isValidInput = true;

        do
        {
            userInput = Console.ReadLine();
            int selectedOption;

            try
            {
                selectedOption = int.Parse(userInput);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Invalid Option, please try again");
                printOptions();
                isValidInput = false;
                break;
            }

            switch (selectedOption)
            {
                case 1:
                    isValidInput = true;
                    break;

                case 2:
                    isValidInput = true;
                    break;

                default:
                    Console.WriteLine("Invalid Option, please try again");
                    printOptions();
                    isValidInput = false;
                    break;
            }
        }
        while (!isValidInput);
    }

    if (Debugger.IsAttached) { Console.ReadKey(); }
}

private static void printOptions()
{
    Console.WriteLine("1. Run Intial Data Import");
    Console.WriteLine("2. Nightly Maintenance");
}


texts:
Here's what I've come up with:

def bf_interpreter(code: str) -> str:
    """
    Interprets BrainF**k code

    Examples:
        ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
        Hello World!

        +++++>++++[<+>-]++++++++[<++++++>-]<.
        9

    """

    outputs = []

    ptr = 0

    values = [0]
    length = 1

    brackets = []

    index = 0
    code_length = len(code)

    while index < code_length:
        char = code[index]

        while length <= ptr:
            length += 1
            values.append(0)

        if char == '>': ptr += 1
        if char == '<': ptr -= 1

        if char == '+': values[ptr] = (values[ptr] + 1) % 256
        if char == '-': values[ptr] = (values[ptr] - 1) % 256

        if char == '[':
            brackets.append(index)

        if char == ']':
            if values[ptr] == 0:
                brackets.pop()
            else:
                index = brackets[-1]

        if char == '.':
            outputs.append(chr(values[ptr]))

        if char == ',':
            values[ptr] = ord(input())

        index += 1

    return ''.join(outputs)

How do I make this look better? (More consistent, as well as strictly following PEP 8 conventions)


texts:
I have written a rolling z-score function myself. Is my implementation of rolling z-score function correct?

#x is an xts object and y duration eg rollz(x,25)
rollz<-function(x,y){
  avg=rollapply(x, y, mean)
  std=rollapply(x, y, sd)
  z=(x-avg)/std
  return(z)
}

EDIT

Here is the description of z-score. A rolling (moving) z-score calculates z-score at a particular width like how we calculate simple moving averages.


texts: Python script to touch files of a particular pattern in all folders of a given name

texts:
The intent of this script is to hunt down all "*/testResults/*.xml" files and touch them, so that our build system doesn't issue errors that the files are too old (it's entirely intentional that tests are only re-run when the libraries they change have been modified)

import fnmatch
import os
import time

matches = []

# Find all xml files  (1)
for root, dirnames, filenames in os.walk('.'):
  for filename in fnmatch.filter(filenames, '*.xml'):
      matches.append(os.path.join(root, filename))

# filter to only the ones in a "/testResults/" folder  (2)
tests = [k for k in matches if "\\testResults\\" in k]

t = time.time()

# touch them
for test in tests:
    os.utime(test,(t,t))

Is there a simpler way to achieve this?  Specifically to perform steps (1) and (2) in a single process, rather than having to filter the matches array?  An alternative solution would be to just recursively find all folders called "/testResults/" and list the files within them.

Notes:

This script would also find "blah/testResults/blah2/result.xml" - I'm not worried about that, as the testResults folders will only contain test result xml files (but not all xml files are test results!)
This runs on Windows.


texts: Convert rating value to visible stars using fontawesome icons

texts:
Just curious if there is a more elegant way to perform the same result. I have a calculated rating which I want to convert to visible stars using fontawesome icons. Max rating is 5. I am rounding the rating to the nearest .5.
Done in js given a rating called data (sum of all votes / number of votes).

//example, can be anything from 0-5 after being computed
data = 3.65;

//get rating in nearest .5 value (this is how many stars need to be yellow)
rating = yellow = (Math.round(data*2)/2).toFixed(1);

//how many stars need to be white
white = 5 - rating;

output = '
';

//output full yellow stars
while (yellow >= 1) {
    output += '';
    yellow--;
}
//what is left can either be .5 or 0... if .5 output half yellow star
if (yellow == .5) {
    output += '';
}
//output remaining full white stars
while (white >= 1) {
    output += '';
    white--;
}

return output + '
';

The above does what I want it to, but I have to believe there is a better approach to get the same result.


texts: Project Euler #4 - Largest Palindrome Product in Java

texts:
I am seeing that this is actually not in accord with the difficulty level said there. Firstly I cannot list all possible improvements it could have.

/*
 * A palindromic number reads the same both ways. The largest palindrome
 * made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the
 * largest palindrome made from the product of two 3-digit numbers.
 */
public static int get4() {
    int max = 1;
    for (int i = 100; i < 999; i++) {
        for (int j = i; j < 999; j++) {
            int n = i * j;
            int len = (int) Math.floor(Math.log10(n));
            boolean ispalindrome = true;
            for (int k = 0; k < 3; k++) {// 100^2=10^4,999^2=998001. 5-6
                                            // digits middle atmax 3
                int digitatk = (int) ((n % Math.pow(10, k + 1) - n
                        % Math.pow(10, k)) / Math.pow(10, k));
                // eg. digit at 3 of 12345 =
                // (12345%10^4-12345%10^3)/10^3=(2345-345)/10^3=2000/10^3=2
                int l = len - k;
                int digitatl = (int) ((n % Math.pow(10, l + 1) - n
                        % Math.pow(10, l)) / Math.pow(10, l));
                if (digitatl != digitatk) {
                    ispalindrome = false;
                }
            }
            if (ispalindrome && n > max) {
                max = n;
            }
        }
    }
    return max;
}

Output:

Answer is 906609
Time taken 2.82342934 seconds

Current problems (not exhaustive):

Time
\${\mathcal O}(n^2)\$ where \$n=999\$ for looping only.
Length-checking method
Checking palindrome
Digit-finding method