texts:
Curious to know how I can improve it, especially the pattern matching part seems a bit repetitive at the moment (lots of case x if ds(x))

  def binarySearch(ds: Array[Double], key: Double): Int = {
    @annotation.tailrec
    def go(low: Int, mid: Int, high: Int): Int = {
      mid match {
        case x if ds(x) == key => x
        case x if high <= low => -1
        case x if ds(x) < key => go(mid + 1, (high - mid + 1) / 2  + mid, high)
        case x if ds(x) > key => go(low, (mid - low) / 2 + low, mid - 1)
      }
    }
    ds.size match {
      case 0 => -1
      case _ => go(0, ds.size / 2, ds.size - 1)
    }
  }


texts:
I'm working on code for an assignment and I was hoping you all could point me in the right direction.

Basically I had to write a program that will issue out a multiple choice test. I have 4 options, A, B, C, D and if the user accidentally chooses something other than my options I want it to ask the question over again.

I've messed around with loops and counters but I'm really hitting a standstill right here. I seem to be unable to get this to work so I'd like you to review my code as is. The code at it's current state here is working, although it does not do much.

I'm up for whatever critique, so if you see something a beginning Java student should do, please let me know.

public static void main(String[] args) {
    String[] multiChoice1;
    Scanner input = new Scanner(System.in);

    multiChoice1 = new String[5];
    multiChoice1[0] = "1. Which country currently emits the most greenhouse gases?\n";
    multiChoice1[1] = "blah blah";
    multiChoice1[2] = "blah blah";
    multiChoice1[3] = "blah blah";
    multiChoice1[4] = "blah blah";

    String userSelect1 = multiChoice1[0];

    if(userSelect1==multiChoice1[0]){
        System.out.println(multiChoice1[0]);
        System.out.println("A. United States");
        System.out.println("B. China");
        System.out.println("C. India");
        System.out.println("D. England");
        System.out.println();
        System.out.print("Your answer: ");
        String uSelect1 = input.next();

        switch (uSelect1.toUpperCase()){
            case "A":
                uSelect1 = "United States";
                System.out.println("Incorrect!\n\n");
                break;
            case "B":
                uSelect1 = "China";
                System.out.println("Correct!\n\n");
                scorePro++;
                score++;
                break;
            case "C":
                uSelect1 = "India";
                System.out.println("Incorrect!\n\n");
                break;
            case "D":
                uSelect1 = "England";
                System.out.println("Incorrect!\n\n");
                break;
            default:
                uSelect1 = "Incorrect, choice.\n\n";
                break;
        }
    }
    // more multiple choice questions with similar structure
}


texts:
I have to filter some very long lists of images many times (thousands, even 10/15k, even much more), so performance is important.

First solution:

var image_match = [];
$('#'+id_canvas+' image').each(function(i, el) {
    if (el.attributes.x.value === x && el.attributes.y.value === y) {
        image_match.push($(this));
    };
});

Second solutions:

var image_match = $('#'+id_canvas+' image[x='+x+'][y='+y+']');

Which solution is faster? Or maybe a non-jQuery solution?

Also, I can often know how many images will pass the test so when I found that number of images I can stop the search, like this:

var image_match = [];
var target_number = 3;
$('#'+id_canvas+' image').each(function(i, el) {
    if (el.attributes.x.value === x && el.attributes.y.value === y) {
        image_match.push($(this));
        if (image_match.length === target_number) {
            return false;
        };
    };
});

Can I do the same thing in the second solution?


texts: Slow JavaScript, which adresses deprecated html tags

texts:
I have written a JavaScript that can read every defined html element and changes the color for each char inside the selected element.
It works fine for smaller projects / sites, however will be laggy and even crash the browser if there are too many elements to process. Appart from 'Use JQuery', what could I do to improve the Performance? I know that .fontcolor() is deprecated. Alternatives are welcome.

/**
 * Defines all possible colors for the chars.
 *
 * @type {string[]} Array of strings with Hex Color values.
 */
var colors = [ "#1C1C1C", "#BDBDBD", "#FA58AC", "#FA58F4", "#AC58FA",
        "#5858FA", "#58ACFA", "#58FAF4", "#58FAAC", "#58FA58", "#ACFA58",
        "#F4FA58", "#FAAC58", "#FA5858" ];

/**
 * Define all elements that can have the text replaced.
 *
 * @type {NodeList}
 */
var ps = document.getElementsByTagName("p");
var h1s = document.getElementsByTagName("h1");
var h2s = document.getElementsByTagName("h2");
var h3s = document.getElementsByTagName("h3");

/**
 * Wrap all elements inside one parent
 *
 * @type {*[]} Array of Array<Elements>
 */
var allDomElements = [ ps, h1s, h2s, h3s ];

/**
 * Starts the party mode
 *
 * @param count
 *            loop gets interrupted after 20 times.
 */
function party(count) {
    // For each array in wrapper
    for (var e = 0; e < allDomElements.length; e++) {
        // For each element in array
        for (var d = 0; d < allDomElements[e].length; d++) {
            // Reference to the current element
            var currentElement = allDomElements[e][d];
            // Gets the text value of the element
            var text = currentElement.innerText;
            var result = "";

            // For each char in text change the color of a single char
            for (var i = 0, len = text.length; i < len; i++) {
                var char = text.charAt(i);
                result += setRandomColorForChar(char);
            }

            // Sets the HTML of the element to be the result
            currentElement.innerHTML = result;
        }
    }
    // If the function hasn't been called 5x times, wait 5 seconds and
    // repeat
    count = count + 1;
    if (!(count > 5)) {
        window.setTimeout(function() {
            party(count);
        }, 5000);
    } else {
        stopParty();
    }
}

/**
 * Function randomly colorizes as single char.
 *
 * @param char
 *            Char to be colorized
 * @returns {string} Colorized char
 */
function setRandomColorForChar(char) {
    var random = getRandomColor();
    var color = colors[random];
    return char.fontcolor(color);
}

/**
 * Returns a random number in the range of colors.length
 *
 * @returns {number} A random number
 */
function getRandomColor() {
    return Math.floor((Math.random() * colors.length) + 0);
}

function stopParty() {
    // For each array in wrapper
    for (var e = 0; e < allDomElements.length; e++) {
        // For each element in array
        for (var d = 0; d < allDomElements[e].length; d++) {
            // Reference to the current element
            var currentElement = allDomElements[e][d];
            // Gets the text value of the element
            var html = currentElement.innerText;
            var clean = html.replace(/<font.*?>/, '');
            clean = clean.replace(/<\/font>/, '');
            currentElement.innerHTML = clean;
        }
    }
}

JS Fiddle


texts: Shell install.sh for repository (rpi_videoloop)

texts:
I've written my first installation script in shell and was wondering on how I can improve the install procedure to make it more clean?

Here's the code:

#!/bin/bash

#Variables
DEPENDENCIES="omxplayer screen cron usbmount ntfs-3g"
PTH="/home/pi/rpi_videoloop"
INIT="/etc/init.d"
SCRIPT="videoloop_v2.sh"
CONTROLLER="vid_controller"
USBCONF="usbmount.conf"
CRONSTUFF=$(cat cron.txt)

# Checking | Installing Dependancies
if ! apt list "$DEPENDENCIES" | grep -v installed | grep -E 'omxplayer|screen|cron|usbmount|ntfs-3g' > /dev/null
then
echo "Dependencies already installed. Continuing."
else
echo "Installing dependencies."
apt-get update
apt-get install "$DEPENDENCIES" -y
fi

echo "Installing Configurations..."

#Configuring
if [ ! -d "$PTH" ]; then
    mkdir $PTH
fi
cp $SCRIPT $PTH
if [ ! -f $INIT/$CONTROLLER ]; then
    sudo cp $CONTROLLER $INIT
fi
cp $USBCONF /etc/usbmount/
sudo chmod 755 $PTH/$SCRIPT
sudo chmod 755 $INIT/$CONTROLLER
sudo update-rc.d $CONTROLLER defaults
sudo echo -n " consoleblank=10" | sudo tee -a /boot/cmdline.txt
#cat alias.txt >> ~/.bashrc
#sudo cat alias.txt >> ~/.bashrc
(crontab -u pi -l; echo "$CRONSTUFF" ) | crontab -u pi -

echo "FINISHED INSTALLATION: Service control -> /etc/init.d/vid_controller {start|stop|check|repair}"


texts: Checking against a specific sequence in python

texts:
I'm trying to learn python and I'm modeling a simple dice game that a friend and I invented.

On any one turn of the game, you must roll a specific combination to stay in the game.

The particular rule I'm trying to model is this:

Given a previous roll (where the dice are contiguous) make another contiguous roll either above the previous roll or before it. 6 and 1 are considered contiguous. Outside of being contiguous the order of the dice does not matter...

some examples

  existing roll (3, 4) valid subsequent rolls: (1, 2) (5, 6)

  existing roll (5, 6) valid subsequent rolls: (1, 2) (3, 4)

  existing roll (6, 1) valid subsequent rolls: (2, 3) (4, 5)

I have written the below python3 code to deal with this aspect of the game. However, being new to python, I'd like to know how experienced programmers would deal with this problem. Is there a smarter way to do this programmatically without all the sorting and comparisons and having to make the two arbitrary evaluations? All comments are welcome, readability, efficiency etc. Thanks for your time.

arguments:

prev = previous/ existing roll

curr = current roll to check

sides = number of sides of the dice

Program:

from itertools import cycle, islice

def chkStk(prev, curr, sides):
    def srt(a):
        return sorted(a, reverse=True if (min(a), max(a)) == (1, sides)
                      else False)

    def cmp(a):
        return a == list(x for x in islice(cycle(range(1, sides+1)),
                                           a[0]-1, a[0]+len(a)-1))
    curr = srt(curr)
    prev = srt(prev)

    return cmp(prev+curr) or cmp(curr+prev)

# examples
print(chkStk([3, 4], [1, 2], 6))
print(chkStk([3, 4], [5, 6], 6))

print(chkStk([5, 6], [1, 2], 6))
print(chkStk([5, 6], [3, 4], 6))

print(chkStk([6, 1], [2, 3], 6))
print(chkStk([6, 1], [4, 5], 6))

# counter examples
print(chkStk([6, 1], [6, 1], 6))
print(chkStk([1, 1], [1, 1], 6))
print(chkStk([1, 2], [4, 5], 6))

output:

True
True
True
True
True
True
False
False
False
[Finished in 0.1s]


texts:
The comment at the top was not followed because I printed the contents. I just want an opinion on coding style.

    /*
     * Write a function setbits(x,p,n,y) that returns x with the n bits
     * that begin at position p set to the rightmost n bits of y, leaving
     * the other bits unchanged in the least number of lines.
     *
     * Note: function signatures and curly brackets dont count towards
     * the number of lines. You must also declare your variables, and
     * call the function
     *
     * build with:
     *   gcc -o bit_twiddle -Wall -g -lm ./bit_twiddle.c
     */

    #include <stdio.h>
    #include <math.h>
    #include <limits.h>

    unsigned setbits(unsigned x, unsigned p, unsigned n, unsigned y) {
        x |= (y & ~(~0 << n)) << p;
        size_t s = (int)(log(INT_MAX)/log(2)) + 1;
        printf("An int is %d bits\n", s);
        int mask = pow(2.0, (int)s);
        do {
            ((x & mask) == 0) ? printf("0") : printf("1");
            ((s%4)==0) ? printf(" ") : printf("");
            x <<= 1;
        } while (s--);
        printf("\n");
    }

    void main( ) {
        unsigned retrn=1, begin=3, nbits=3, input=7;
        unsigned x = setbits(retrn, begin, nbits, input);
    }

UPDATE

x |= (y & ~(0 << n)) << p --> x |= (y & ~(~0 << n)) << p


texts: Getting data from database and then outputing it to the DataGridView

texts:
I am at the point where I feel that I am not doing it right. It works and does the job, but I am sure that there are more efficient and smarter ways of doing it.

I would like to see if there is a way of making it more efficient, clear, and easier to use.

This is my query getter:

    public DataTable querySQL_DT_Return(String query)
    {
        var form = Form.ActiveForm as Form1;
        DataTable RETURNME = null;
        OleDbConnection conn = new OleDbConnection(cnStr);

        try
        {
            try
            {
                conn.Open();
            }
            catch
            {
                MessageBox.Show("Can't connect to the database!");
            }

            OleDbDataAdapter Data1 = null;

            try
            {
                Data1 = new OleDbDataAdapter(query, conn);
            }
            catch
            {
                MessageBox.Show("Can't open the connection to the DB, please try again!");
                return RETURNME;
            }

            DataSet a = new DataSet();
            Data1.Fill(a);

            DataTable dt = a.Tables[0];
            //Adding data to the columns
            RETURNME = dt;
        }

        catch
        {
            //MessageBox.Show("Having issues retrieving data from Database, please try again!");
            // return RETURNME;
        }
        finally
        {
            if (conn.State.ToString() == "Open")
            {
                conn.Close();
            }
        }

        if (conn.State.ToString() == "Open")
        {

            conn.Close();
        }
        return RETURNME;
    }

When I receive the DataTable, I just loop through it getting records.


texts: Calculate fractions of positive, negative and zeros

texts:
Find the fractions for, all positive numbers, all negative numbers and zeros in a given set of integer array.

I wrote the below program. If you see any improvements required, please feel free to point them out.

Sample input:
6
-4 3 -9 0 4 1

Sample output:
0.500000
0.333333
0.166667

Here is my program :)

public class Solution {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int size = scan.nextInt();
        scan.nextLine();

        String s = scan.nextLine();
        List<Double> doubleList = Arrays.stream(s.split(" ")).mapToDouble(Double::valueOf).collect(ArrayList<Double>::new, List::add, List::addAll);

        int postive = 0;
        int negative = 0;
        int zeros = 0;
        double total = (int) doubleList.stream().count();

        DoublePredicate filterPositives = d -> d > 0;
        DoublePredicate filterNegatives = d -> d < 0;
        DoublePredicate filterZeros = d -> d == 0;

        postive = countNumbers(doubleList.stream().mapToDouble(Double::valueOf), filterPositives);
        negative = countNumbers(doubleList.stream().mapToDouble(Double::valueOf), filterNegatives);
        zeros = countNumbers(doubleList.stream().mapToDouble(Double::valueOf), filterZeros);

        DecimalFormat df = new DecimalFormat("#.000000");
        System.out.println(df.format(postive/total));
        System.out.println(df.format(negative/total));
        System.out.println(df.format(zeros/total));
    }

    public static int countNumbers(DoubleStream ds, DoublePredicate fd){
        return (int) ds.filter(fd).count();
    }

}


texts:
I was seeing alot of machine learning applications calculate fitness via 1.0 / x. Division in computers is slow so I came up with a version that is about ~36% fast on my architecture (-march=x86-64).
#include <cmath>    //std::exp2, std::log
#include <numbers>  //std::numbers::log2e
#include <stdlib.h> //rand, srand
#include <iostream> //std::cout

float reciprical( float y )
{
    //e^-ln(y)
    //std::pow( log10e,  -std::log(y) )                   //~19s
    return std::exp2(std::numbers::log2e * -std::log(y)); //~17s
}

float reciprical2( float y )
{
    return 1/y;                                           //~23s
}

int main(){
    srand(1);
    for(int i=0; i < 10000000000; ++i) std::cout << reciprical(rand());
}

I got inspiration from https://codegolf.stackexchange.com/a/114588


texts:
They say you cannot get out of the monad, but I need to use the result (at least for assertions / unit tests). But print how does it do it?

Otherwise, I worked very hard for the next code with my new limited Haskell abilities (especially when talking about monads), so it needs a review.

--import Control.Monad.ST
--import Control.Monad
import qualified Data.Vector as Vec
import qualified Data.Vector.Mutable as MutableVec

assert :: Monad a => Bool -> a ()
assert False = error "assertion failed!"
assert _     = return ()

get_primes_limit :: Int -> Int
get_primes_limit limit = 1 + floor (sqrt $ fromIntegral limit)

update_sieve4_step_M 2 limit arr = do
    mapM_ (\i -> MutableVec.write arr i 0) [4, 6 .. limit-1]
update_sieve4_step_M prime limit arr = do
    mapM_ (\i -> MutableVec.write arr i 0) [3*prime, 5*prime .. limit-1]

update_sieve4_step limit arrIn = do
    arr <- Vec.unsafeThaw arrIn
    MutableVec.write arr 1 0
    update_sieve4_step_M 2 limit arr
    mapM_ (\p -> update_sieve4_step_M p limit arr) [3, 5 .. (get_primes_limit limit)]
    Vec.unsafeFreeze arr

update_sieve4 limit = update_sieve4_step limit (Vec.generate limit (id))

--TODO: cannot get this out of the monad (not m Int); print does it somehow
primes_sum4_1 limit = do
    sieve <- update_sieve4 limit
    return (Vec.sum sieve)

--primes_sum4 :: Control.Monad.Primitive.PrimMonad m => Int -> m Int
primes_sum4 limit = do
    result <- primes_sum4_1 limit
    --print result
    return result

primes_sum4_validation = do
    result <- primes_sum4_1 9
    --assert (17 == result)
    print "Nothing to validate!"

validate = do
    --assert (17 == primes_sum4 9)
    --assert (17 == primes_sum4 10)
    --assert (17 == primes_sum4 11)
    --assert (28 == primes_sum4 12)
    --assert (100 == primes_sum4 29)
    --assert (129 == primes_sum4 30)
    --assert (1060 == primes_sum4 100)
    --assert (76127 == primes_sum4 1000)
    --assert (5736396 == primes_sum4 10000)
    --assert (32405717 == primes_sum4 25000)
    --assert (454396537 == primes_sum4 100000)

    print "Nothing to validate!"

main = do
    primes_sum4 2000000


texts: LINQ query for a user's submitted time-off requests

texts:
What is a better way to create this select statement? I tried to just select 'u' and 'us', but the object properties were not accessible when I did this.

var userSubmittedRequests = (from u in db.TimeRequests
                                     join us in db.UserManagers
                                     on u.EmployeeUserID equals us.UserID
                                     join ut in db.Users
                                     on us.ManagerID equals ut.UserID
                                     where (us.ManagerID == userResult.UserID)
                                     where(u.User.disabled == false)
                                     select new PendingTimeOffViewModel
                                     {
                                       TimeRequestID = u.TimeRequestID,
                                       sDateTime = u.sDateTime,
                                       eDateTime = u.eDateTime,
                                       EmployeeUserID = u.EmployeeUserID,
                                       ManagerID = u.ManagerID,
                                       hrID = u.hrID,
                                       ApproveDenyReasonID = u.ApproveDenyReasonID,
                                       ManagerApproval = u.ManagerApproval,
                                       ManagerActionDate = u.ManagerActionDate,
                                       ManagerComment = u.ManagerComment,
                                       hrApproval = u.hrApproval,
                                       hrActionDate = u.hrActionDate,
                                       hrComment = u.hrComment,
                                       UserSubmitDate = u.UserSubmitDate,
                                       Comment = u.Comment,
                                       DayTypeID = u.DayTypeID,
                                       User = u.User,
                                       CompanyDesc = ut.Company.CompanyDesc,
                                       User1 = u.User1,
                                       User2 = u.User2,
                                       DayType = u.DayType,
                                       ManagerIDUM = us.ManagerID,
                                       ManagerADName = ut.ADUserName,
                                       ManagerName = ut.FullName
                                     }).ToList();

View model:

 public class PendingTimeOffViewModel
 {
    public int TimeRequestID { get; set; }
    public int  CompanyID {get;set;}
    public System.DateTime sDateTime { get; set; }
    public System.DateTime eDateTime { get; set; }
    public int EmployeeUserID { get; set; }
    public Nullable<int> ManagerID { get; set; }
    public Nullable<int> hrID { get; set; }
    public Nullable<int> ApproveDenyReasonID { get; set; }
    public bool ManagerApproval { get; set; }
    public Nullable<System.DateTime> ManagerActionDate { get; set; }
    public string ManagerComment { get; set; }
    public bool hrApproval { get; set; }
    public Nullable<System.DateTime> hrActionDate { get; set; }
    public string hrComment { get; set; }
    public string Comment { get; set; }
    public System.DateTime UserSubmitDate { get; set; }
    public int DayTypeID { get; set; }
    public Nullable<int> HoursRequested { get; set; }
    public virtual ApproveDenyReason ApproveDenyReason { get; set; }
    public virtual DayType DayType { get; set; }
    public virtual User User { get; set; }
    public virtual User User1 { get; set; }
    public virtual User User2 { get; set; }
    public virtual Company Company { get; set; }
    public int UserManagerID { get; set; }
    public Nullable<int> UserID { get; set; }
    public Nullable<int> ManagerIDUM { get; set; }
    public string ManagerADName { get; set; }
    public string ManagerName { get; set; }
    public string CompanyDesc { get; set; }
}


texts: Filling two angular $scope variables with data

texts:
I'm unsure about how to simplify this method properly. The method is basically responsible to allocate data.

The response object is a collection of objects. Each object contains an attribute called order and i have to distinguish between visible and invisible elements. Visible elements are represented by positive integers, invisible elements by a negative integers.

Also it is possible to overwrite the default state if the URL contains an parameter (hidden) with a list of hidden element ids. ?hidden=23,432,3,123

_hasParam() returns boolean

_getParam() returns string (separated by comma [23,432,3,123])

contains() returns boolean

prepare: function (response) {

    var visible = [];
    var invisible = [];

    if (_hasParam('hidden')) {

        var hidden = _getParam('hidden').split(',');

        angular.forEach(response, function (item) {
            if (hidden.contains(item.id)) {
                invisible.push(item);
            } else {
                visible.push(item);
            }
        });

    } else {

        angular.forEach(response, function (item) {
            if (item.order === -1) {
                invisible.push(item);
            } else {
                visible.push(item);
            }
        });

    }

    $rootScope.visible = visible;
    $rootScope.invisible = invisible;
}


texts:
What can be improved in my code:

        using (var oracleConnection = new OracleConnection(ConnectionString))
        {
            using (var oracleCommand = oracleConnection.CreateCommand())
            {
                oracleConnection.Open();

                oracleCommand.CommandText =
                "SELECT *
                 FROM table_sample Table_Sample
                 WHERE table_sample.id > 1000";

                using (var reader = oracleCommand.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        int id = reader.GetValue(0);
                    }
                }
            }
        }

As the most "dangerous" thing I see the ugly string statement for database query.

I dont want to use Entity Framework for Oracle - cause its not as actual as one for MS SQL Server. And also some Oracle features are not supported.


texts:
I wanted to detect if I have a member in a simple POD struct and after some searching and merging some methods I found on the web I've come up with this solution:

#include <iostream>

template<class...Fs>
struct funcs_t{};

template<class F0, class...Fs>
struct funcs_t<F0, Fs...>: F0, funcs_t<Fs...> {
    funcs_t(F0 f0, Fs... fs):
    F0(std::move(f0)), funcs_t<Fs...>(std::move(fs)...)
    {}
    using F0::operator();
    using funcs_t<Fs...>::operator();
};

template<class F>
struct funcs_t<F>:F {
    funcs_t(F f) : F(std::move(f)) {};
    using F::operator();
};

template<class...Fs>
funcs_t<std::decay_t<Fs>...> funcs(Fs&&...fs) {
    return {std::forward<Fs>(fs)...};
}

#define HAS_MEMBER(cls, memb)\
    [](){\
        auto with_memb = [](auto &&A, int x)\
                -> decltype(typename std::remove_reference<decltype(A)>::type().memb, std::true_type())\
        {\
            return std::true_type();\
        };\
        auto with_no_memb = [](auto &&A, float x) -> std::false_type {\
            return std::false_type();\
        };\
        auto has_memb = funcs(with_memb, with_no_memb);\
        return has_memb(cls(), 1);\
    }()

struct A {
    int a;
    int b;
};

int main(int argc, char const *argv[])
{
    std::cout << HAS_MEMBER(A, b) << std::endl;
    return 0;
}


texts: Linked list implementation of binary heap insertion

texts:
Is this a correct linked list implementation of binary heap insertion? This is not a homework exercise.

public BinaryHeap insert(int value , BinaryHeap node , int count)
    {

        //1. Insert into a binary tree breadth wise( satisfy complete binary property) (left to right)
        //2. Once inserted ,fix the tree by running heapify every time a new value(non duplicate) is added.
        //3. Count represents the total no of elements in the tree. Calculate the total no of parents for given set of elements.

         int parent = (count - 1)/2;

        if (node == null)
        {
            node = new BinaryHeap();
            node.data = value;

        }

            else
        {
            if (((parent == 0) && (node.left == null)) || (parent % 2 == 1))
            {

                node.left = insert(value, node.left, parent);
                Debug.Assert(node.left != null);
                node.left.parent = node;
                Heapify(node.left);
                if (node.right != null) // if both left and right sub tree are filled
                {
                    Debug.Assert(node.data < node.left.data && node.data < node.right.data);// heapified node  will be minimum
                }
                else // incomplete subtree withh right subtree not filled.
                {
                    Debug.Assert(node.data < node.left.data);
                }
            }

            else
            {
                Debug.Assert(node.left != null);
                node.right = insert(value, node.right, parent);
                Debug.Assert(node.right != null);
                node.right.parent = node;

                Heapify(node.right);
                if (node.left != null) // if both left and right sub tree are filled
                {
                    Debug.Assert(node.data < node.left.data && node.data < node.right.data);// heapified node  will be minimum
                }
                else // incomplete sub tree with right sub tree not filled.
                {
                    Debug.Assert(node.data < node.right.data);
                }

            }
        }// end of else
        // every time you add an element you run heapify to rearrange the nodes.

        return node;
    }

    public void Heapify(BinaryHeap node)

    {
   //Bubble up until you are unable to
        if (node == null)
        {
            return;
        }

        else
        {

            if (node.parent != null && node.parent.data > node.data)
            {
                //swap the value
                int temp = node.parent.data;
                node.parent.data = node.data;
                node.data = temp;
                node = node.parent;
                Heapify(node.parent);
                return;
            }
    }
  }// end of function heapify


texts: Finding average of eight immediate neighbors of a matrix

texts:
I have this basic Java code to find average of eight immediate neighbors of a matrix.

Is there any way to simplify or merge any part of it, or can I refactor it?

I'm a beginner in Java programming and am trying to improve myself.

// CODE STSRT
import java.util.Scanner;
import java.lang.*;

class Matrixer
{

   double[][] matrix, computedMatrix;
    final int rows, cols;

    public Matrixer(int N, int M, double[][] imatrix)
    {
        rows = N;
        cols = M;
        matrix = imatrix;
        computedMatrix = new double[N][M];
    }

    public void computeAverages()
    {
        for (int i = 1; i < rows - 1; i++)
        {
            for (int j = 1; j < cols - 1; j++)
            {
                computedMatrix[i][j] = cellNeighborsAverage(i, j);
            }
        }
    }

    private double cellNeighborsAverage(int row, int col)
    {
        // Ignore center cell And tack Neighbors
        double sum = matrix[row - 1][col - 1] + matrix[row - 1][col]
            + matrix[row - 1][col + 1] + matrix[row][col - 1]
            + matrix[row][col + 1] + matrix[row + 1][col - 1]
            + matrix[row + 1][col] + matrix[row + 1][col + 1];
        return sum / 8;
    }

    public void printComputedMatrix()
    {
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                System.out.printf("%.0f", computedMatrix[i][j]);
                System.out.print(" ");
            }
            System.out.println();
        }
    }

public static void main(String[] args) throws NullPointerException {
        //This part for defined the size if matrix
        int R,C;
        Scanner rc = new Scanner(System.in);
        System.out.println("Enter the number of matrix's rows :");
        R = rc.nextInt();
        Scanner cc = new Scanner(System.in);
        System.out.println("Enter the number of matrix's columns :");
        C = cc.nextInt();
        //End of defined part

        // condition part To see if columns and rows not greater than 2 stop execution
  if(R<3){System.out.println("ERROR! \n Columns and rows should be greater than 2");
  }else{
    // condition part To see if columns not equal rows stop execution
    if(R!=C){
    System.out.println("ERROR! \n The number of rows should equal number of columns");
    }
        else{

    Scanner sc = new Scanner(System.in);
    double[][] inputMatrix = new double[R][C];
    try {

        System.out.println("Enter The Elementt of matrix ("+R+"x"+C+")");
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {

                inputMatrix[i][j] = sc.nextInt();
            }
        }
        Matrixer mx = new Matrixer(R, C, inputMatrix);
        System.out.println(" average of eight immediate neighbors is \n");
        mx.computeAverages();
        mx.printComputedMatrix();

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
} } //End of conditions part
}}

//END OF THE CODE


texts:
I was reading this code where author claims that its the fastest implementation which I doubt, hence I decided to write my version of the same problem.

'use strict';

module.exports = function unique(arr) {
  if (!Array.isArray(arr)) {
    throw new TypeError('array-unique expects an array.');
  }
  return arr.filter(function(element, index) {
    return arr.indexOf(element) === index;
  });
};

The above code looks readable to me but I don't about its performance(I think mine should be faster).


texts:
I have some code that asks for a user input, and then uses TTS to convert that into speech and play the file. It then asks the user whether they want to repeat it and convert another input into speech, or whether they want to exit the program. Are there any improvements that I could make to the code?

import webbrowser
import os
import time
import sys
import getpass
from gtts import gTTS
from mutagen.mp3 import MP3

my_file = "C:/Users/%USERNAME%/Desktop/TTS/bob.mp3" #Sets a variable for the file path.

username = getpass.getuser() #Gets the username of the current user.

def repeat():
    while True:
        if os.path.isfile(my_file): #Checks to see whether there is a file present and, if so, removes it.
            os.remove(my_file)
        else:
            None

        tts = gTTS(text = input("Hello there " + username + """. This program is
used to output the user's input as speech.
Please input something for the program to say: """)) #Takes the user's input and uses it for the Text-To-Speech
        tts.save('bob.mp3') #Saves a .mp3 file of the user's input as speech.
        webbrowser.open(my_file) #Opens the .mp3 file

        audio = MP3(my_file) #Sets a variable so that the Mutagen module knows what file it's working with.
        audio_length = audio.info.length #Sets a variable of the length of the .mp3 file.
        time.sleep((audio_length) + 0.25) #Waits until the file has finished playing.
        os.system('TASKKILL /F /IM wmplayer.exe') #Closes Windows Media Player.
        time.sleep(0.5) #Waits until Windows Media Player has closed.

        while True:
            answer = input("Do you want to repeat? (Y/N) ")
            if answer == "y" or answer == "Y":
                return repeat() #Goes back to the beginning of the function if the user wants to try again.
            elif answer == "n" or answer == "N":
                if os.path.isfile(my_file): #Checks to see whether there is a file present and, if so, removes it.
                    os.remove(my_file)
                else:
                    None
                sys.exit() #Exits the program.
            else:
                print("Sorry, I didn't understand that. Please try again with either Y or N.")
                continue #Goes back to the beginning of the while loop.

repeat() #Calls the function.


texts:
I am getting the number part of the container ID that the button is in. Now I am wondering if I need to create an array using split and then put this number in a variable, or if there is a more efficient way to get it.

.match() also returns an array, so this is almost the same as using split.

I mean the code works and it's ok, but I'm curious to see if there is a better way.

 $('.add').on('click', function(e) {
   e.preventDefault();
   var $this = $(this);
   var tab_number_array = $this.parents('.tab_content').attr('id').split('_');
   var tab_number = tab_number_array[1];
   alert(tab_number);
 });

      <button class="add">Add</button>

      <button class="add">Add</button>

      <button class="add">Add</button>


texts:
I have a chunk of code that averages around the points of a grid of values and Im trying to figure out if there is a better way to do the averaging. The array itself is 1 dimensional but i am using an x and y and stride to keep track of it in 2d space. Im mainly just trying to figure out if there is a more optimized way to average this or if this is the best way.

Let me know if anything needs clearing up. Thanks for any input!

for (int y=0;y<lockObj.m_iSize[1];y++)
    {
        for (int x=0;x<lockObj.m_iSize[0];x++)
        {
            if(m_bShouldSmooth)
            {

                float avgAround = 0.0f;
                if(x == 0)
                {
                    if(y==0)
                        avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+x]) / 4;
                    else if(y==lockObj.m_iSize[1]-1)
                        avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x+1)] + pDest[(y-1)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x+1)]) / 4;
                    else
                        avgAround = (pDest[(y)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x+1)] + pDest[(y)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x)]) / 6;
                }
                else if(x==lockObj.m_iSize[0]-1)
                {
                    if(y==0)
                        avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+x]) / 4;
                    else if(y==lockObj.m_iSize[1]-1)
                        avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+(x)]) / 4;
                    else
                        avgAround = (pDest[(y)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x)] + pDest[(y-1)*lockObj.m_iStride+(x-1)] + pDest[(y)*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+(x)]) / 6;
                }
                else
                {
                    if(y==0)
                        avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+(x-1)] + pDest[(y+1)*lockObj.m_iStride+x] + pDest[(y+1)*lockObj.m_iStride+(x+1)] + pDest[(y)*lockObj.m_iStride+(x+1)]) / 6;
                    else if(y==lockObj.m_iSize[1]-1)
                        avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+x] + pDest[(y-1)*lockObj.m_iStride+(x+1)] + pDest[(y)*lockObj.m_iStride+(x+1)]) / 6;
                    else
                        avgAround = (pDest[y*lockObj.m_iStride+x] + pDest[y*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+(x-1)] + pDest[(y-1)*lockObj.m_iStride+x] + pDest[(y-1)*lockObj.m_iStride+(x+1)] + pDest[(y)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x+1)] + pDest[(y+1)*lockObj.m_iStride+(x)] + pDest[(y+1)*lockObj.m_iStride+(x-1)]) / 9;
                }

                if(this->GetContactForce() > 0){
                    if(avgAround < pDest[y*lockObj.m_iStride+x])
                        pDest[y*lockObj.m_iStride+x] = avgAround;
                }
            }
        }
    }


texts:
This is an E-mailer class that I created to send me E-mail when/if the Windows service (that will be installed on computers all over) throws an error, so that I know what is going on.

I use a similar set up all over the place, so I would like to know if this is clean and efficient.

class Emailer
{
    public void sendEmail(string bodyText, string sender, List<string> recipientAddresses)
    {
        int portNumber = 25;
        SmtpClient smtpClient = new SmtpClient("mailexchanger_String", portNumber);
        using (MailMessage mailMsg = new MailMessage())
        {
            mailMsg.Body = bodyText;
            mailMsg.IsBodyHtml = true;
            mailMsg.Priority = MailPriority.High; //I want to know now!
            foreach (string address in recipientAddresses)
            {
                mailMsg.To.Add(address);
            }
            mailMsg.From = new MailAddress(sender);

            smtpClient.Send(mailMsg);
        }
    }
}

I would also like to know if I have the right ideas about how classes should work and function; this is just a simple method wrapped inside of a class. Is this how it should be?


texts:
I learned here that it is unsafe to design encryption algorithms from scratch. Given that advice, I made a pair of encryption functions based on mcrypt:

function aes128ctr_en($data,$key,$hmac = false) {
    $key = ($hmac===false) ? hash('sha256',$key,true) : hash_hmac('sha256',$key,$hmac,true);
    $data .= hash('md5',$data,true);
    $iv = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
    return mcrypt_encrypt('rijndael-128',$key,$data,'ctr',$iv).$iv;
}

function aes128ctr_de($data,$key,$hmac = false) {
    $key = ($hmac===false) ? hash('sha256',$key,true) : hash_hmac('sha256',$key,$hmac,true);
    $iv = substr($data,-16);
    $data = substr($data,0,strlen($data)-16);
    $data = mcrypt_decrypt('rijndael-128',$key,$data,'ctr',$iv);
    $md5 = substr($data,-16);
    $data = substr($data,0,strlen($data)-16);
    return (hash('md5',$data,true)===$md5) ? $data : false;
}

$encrypted = aes128ctr_en('secret text','password');
echo aes128ctr_de($encrypted,'password');

Are these safe?
What about the IV? Is it ok to just add it to the end of the encrypted string?
Would it be better/faster to make all this by module, that is by using mcrypt_module_open?


texts: First calculator in c++, tips for optimisation

texts:
So this is my first attempt at making a calculator in c++, and i'm looking for experienced people to pinpoint what i could do better to make my calculator run better! *please note that i had to translate some parts of the code to english from my native language, and had to change bunch of names so if i forgot something somewhere my bad :P

#include <cmath>
#include <iostream>
#include <stdio.h>

using namespace std;

int prompt(const char* name)
{
printf("%s", name);
int value;
scanf("%d", &value);
return value;
}

int main()
{
    int mod;
    cout << "U kojem modu kalkulatora zelis biti? " << mod << endl;
    cout << "Mod 1 je za zbrajanje" << endl;
    cout << "Mod 2 je za oduzimanje" << endl;
    cout << "Mod 3 je za mnozenje" << endl;
    cout << "Mod 4 je za dijeljenje" << endl;
    cin >> mod;

    switch (mod)
    {
        case 1:
            cout << "Odabrali ste zbrajanje!" << endl;
            int a, b, zbroj;
            a = prompt("a: ");
            b = prompt("b: ");
            zbroj = a + b;
            printf("%d + %d = %d", a, b, zbroj);
            break;
        case 2:
            cout << "Odabrali ste oduzimanje!" << endl;
            int razlika;
            a = prompt("a: ");
            b = prompt("b: ");
            razlika = a - b;
            printf("%d - %d = %d", a, b, razlika);
            break;
        case 3:
            cout << "Odabrali ste mnozenje!" << endl;
            int umnozak;
            a = prompt("a: ");
            b = prompt("b: ");
            umnozak = a * b;
            printf("%d * %d = %d", a, b, umnozak);
            break;
        case 4:
            cout << "Odabrali ste dijeljenje!" << endl;
            int kolicnik;
            a = prompt("a: ");
            b = prompt("b: ");
            kolicnik = a / b;
            printf("%d / %d = %d", a, b, kolicnik);
            break;

        default:
            cout << "Nemamo tu opciju trenutno, prcekajte za nadogradnju programa, ili se javite developeru!" << endl;
    }
    return 0;
}

I'm a newbie :P


texts:
Another stab at the Josephus problem, this time using Actors. N people stand in a circle and every stepth person is eliminated until one is remaining.

The way I solve it here is to give each actor a reference to their successor, and the actors send their successor a count of places since the last elimination. If an actor is eliminated, it replies with a reference to its successor so that the previous actor now links the one after.

I've hardly used Actors before. I'd like general comments, but in particular I'm wondering:

is using Actors appropriate for this problem?
are the messages I used sensible?
is the wait for reply necessary?
how would you do it differently?

btw I'm going to try this with Akka as well - if that will make any major difference to the solution that you know of, please mention!

object Josephus_Actors extends App {
  import actors._

  val N = 40
  val step = 3

  case class Person(id: Int) extends Actor { Self =>
    // would like to make `next` private[this], but it's then very tricky to set up
    var next: Person = _
    private[this] var alive = true
    def act {
      while (alive) {
        // Messages consist of (count, sender) where count is distance from last man out
        receive {
          // last man standing
          case (_, Self) => {
            println("Winner: "+id)
            sys.exit(0)
          }
          // kill self
          case (x: Int, _) if x == step => {
            alive = false
            reply {next}
          }
          // kill next
          case (x: Int, _) if x == step - 1 => {
            // wait until we have received our next value
            next !? ((step, Self)) match {
              case a: Person => next = a
              case _ =>
            }
            next ! (1, Self)
          }
          /* pass on message */
          case (x: Int, _) => {
            next ! (x + 1, Self)
          }
          case other => println(id + " unrecognized message: " + other)
        }
      }
    }
  }

  val acts = 1 to N map Person
  acts foreach { p =>
    // add reference to successor
    p.next = p.id match {
      case N => acts(0)
      case x => acts(x)
    }
    p.start()
  }
  acts(0) ! (1, null)
}


texts:
Previously asked here.
The code is now available on GitHub.
Since the previous review I have added unit tests.
Since it is big it will come in a couple of parts.
Part 1 | Part 2 | Part 3 | Part 4
Part 2
This is a simple helper object. It stores the result of parsing the string in an object. This way we don't need to re-parse the string for information.
FormatInfo.h
#ifndef THORSANVIL_IOUTIL_FORMAT_INFO_H
#define THORSANVIL_IOUTIL_FORMAT_INFO_H

#include <iostream>
#include <typeinfo>

namespace ThorsAnvil::IOUtil
{

// Enum representing the Length, specifier and type information provided by the format string
#pragma vera-pushoff
                                                                                // printf doc http://www.cplusplus.com/reference/cstdio/printf/
enum class Length    {none, hh, h, l, ll, j, z, t, L};                          // Use the same values as in printf documentation so it is easy to lookup
enum class Specifier {d, i, u, o, x, X, f, F, e, E, g, G, a, A, c, s, p, n};    // Use the same values as in printf documentation so it is easy to lookup
enum class Type      {Int, UInt, Float, Char, String, Pointer, Count};          // The type we are expecting
enum class Dynamic   {None, Width, Precision, Both};                            // If width and/or precision are specified by parameter
#pragma vera-pop

using AllowedType = std::pair<std::type_info const*, int>;

struct FormatInfo
{
    // Formatter has the text representation:
    //      %<Flag>*<Width>?[.<Precision>]?<Length>?<Specifier>
    //
    //      Flag:       - + <space> # 0
    //      Width:      {1-9}{0-9}*
    //      Precision:  {0-9}*
    //      Length:     hh h l ll j z t L
    //      Specifier:  d i u o x X f F e E g G a A c s p n

    // Flags
    bool                    leftJustify;    // -    Left-justify within the given field width; Right justification is the default (see width sub-specifier).
    bool                    forceSign;      // +    Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
    bool                    forceSignWidth; // (space)  If no sign is going to be written, a blank space is inserted before the value.
    bool                    prefixType;     // #    Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero.
                                            //      Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
    bool                    leftPad;        // 0    Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
    // Width and precision of the formatter.
    std::size_t             width;
    std::size_t             precision;
    Length                  length;
    Specifier               specifier;

    // Pre-calculate a some values based on the format string
    Type                    type;           // Calculated based on length/specifier
    Dynamic                 useDynamicSize; // Are width/precision dynamically specified.
    AllowedType             expectedType;   // Type info we expect the next argument to be based on length/specifier
    std::ios_base::fmtflags format;         // The format flags that will be applied to stream before the next argument

};

}

#endif


texts:
I want to construct KD-Tree from unsorted List of points in the plane (i.e. 2-KD-Tree). To do so I used the method from Wikipedia: http://en.wikipedia.org/wiki/Kd-tree#Construction  This is my code:

public static Node buildKDTree(List<Node> list, boolean depth){
    if(depth){
        Collections.sort(list, Node.xComparator);
    }
    else{
        Collections.sort(list, Node.yComparator);
    }
    int middle = list.size()/2;
    Node root = list.get(middle);
    List<Node> left = new ArrayList<Node>();
    for (int i = 0; i < middle; i++) {
        left.add(list.get(i));
    }
    List<Node> right = new ArrayList<Node>();
    for (int i = middle+1; i < list.size(); i++) {
        right.add(list.get(i));
    }
    root.leftChild = buildKDTree(left, !depth);
    depth = !depth;
    root.rightChild = buildKDTree(right, !depth);
    return root;
}

The implementation of Node class is not impotrant (I think). What I dont like in my code is that in each iteration I spend O(n) time to copy the first half of the sorted list into new list (left) and then do the same for the other half of the list(right). Is there any way to avoid this? I was thinking to include indexes begin and end as parameters to my method but I dont see how it would speed up, since I dont know method for collectios that will sort the collection partly, i.e. from begin to middle and then from middle to end.


texts:
I wrote a simple python port scanner today and I would like to get some advice on how to improve on the code in different ways.

I am aware that I can implement threading to reduce runtime but I won't for now as it feels a bit advanced at this time. Rather I would like tips/opinions on how to improve the program in other ways.

You can find the code on my GitHub.

I am aware that the logging is a bit redundant as it doesn't log anything now, I simply forgot to remove it.

# Network port scanner
# Focus first will be on making the functionality of the software.
# Second focus will be on lowering the runtime of the software.

import socket
import logging
import time

class SConnect:

    def __init__(self, ip, port=None):
        self.ip = ip
        self.port = port
        self.address = (self.ip, self.port)
        self.s_connection = socket.socket(socket.AF_INET,       socket.SOCK_STREAM)
        self.s_connection.settimeout(0.3)

    def portscan(self):

        return self.s_connection.connect_ex(self.address)

def main():

    logging.basicConfig(filename="errlog.log", format="%(asctime)s : %(message)s")
    logging.info("Start")
    print("\nHello user and welcome to Network Port Scanner!")
    print("Please insert a IP address that you want to scan for open and     closed ports.")
    print("The range of ports scanned is 1-65535.")
    u_ip = input("\nTarget IP: ")

    open_pcounter = 0
    closed_pcounter = 0

    if u_ip is not None:
        for p in range(1, 65536):
            start_ptime = time.time()
            c = SConnect(u_ip, p)
            if c.portscan() == 0:
                print("Port {} is open".format(p))
                open_pcounter += 1
            else:
                print("Port {} is closed".format(p))
                closed_pcounter += 1
            print("--- %s seconds ---" % (time.time() - start_ptime))
    else:
        print("You failed, terminating.\n")

    print("Total open ports:%s".format(open_pcounter))
    print("Total closed ports:%s".format(closed_pcounter))
    logging.info("Finished")

if __name__ == '__main__':
    start_time = time.time()
    main()
    print("--- %s seconds ---" % (time.time() - start_time))


texts: System for inputting and monitoring worker shifts

texts:
I've been building a system for inputting and monitoring shifts for casual staff, who work across multiple sites with the ability to generate accounting information.

I've had some help from Stack Overflow in building this project, as I had no prior knowledge of PHP or MySQL, and each time I posted some of my code I had comments about the lack of security.

In my system, sensitive information like salaries, work hours and things are protected by having different levels of user accounts. The code below is a snippet of code from my Admin Area allowing me to edit an account's userLevel and password.

if(isset($_POST['submit'])) {

    $editid = htmlentities($_POST['id'], ENT_QUOTES, 'UTF-8');
    $userLevel = htmlentities($_POST['userLevel'], ENT_QUOTES, 'UTF-8');

    if(!empty($_POST['password'])) {

        $password = password_hash("$_POST['password']", PASSWORD_DEFAULT)

        $sql = "UPDATE users SET userLevel = ?, password = ?, salt = ? WHERE id = ?";
        $stmt = $connection->prepare($sql);
        $stmt->bind_param('ssss', $userLevel, $password, $salt, $editid);

    } else {

        $sql = "UPDATE users SET userLevel = ? WHERE id = ?";
        $stmt = $connection->prepare($sql);
        $stmt->bind_param('ss', $userLevel, $editid);

    }

        $stmt->execute();
}

I specify UTF-8 charset at the top of my php files, and all raw output variables, posts, gets and sessions are wrapped in htmlentities tags. My account passwords are hashed and salted.

My system is only used locally and will never be used on the web (unless I post the code somewhere, which I could do to help other new people learn), but as I'm learning I was told I should get in the habit of writing secure code. So finally we get to the question.. Is the above code of a secure enough level for the web? If not, please offer suggestions.


texts: Thread safe log class which creates log files according to the current date when entry was added

texts:
From this question and some help I created a thread safe logging class on which the name of the log file is same as the current date (short date) when the log entry was added. e.g. If I create ten entries today say they will all get written to log file named "07.10.2015.txt". I want to use this class from DLL.
I am curious on your opinion if this is reasonable and thread safe class?

public static class Logger
{
    static readonly object _syncObject = new object();

    public static void Write(string logMessage)
    {
        try
        {
            var todaysLogFilePath = Path.Combine(ConfigManager.GetAppSetting("logPath"),
                                                    ("Log" + DateTime.Now.ToString("yyyy-MMMM-dd") + ".txt"));
            Log(logMessage, todaysLogFilePath);
        }
        catch (IOException e)
        {
            //log somewhere else if required
        }
    }

    static void Log(string logMessage, string logFilePath)
    {
        lock (_syncObject)
        {
            File.AppendAllText(logFilePath,
                        string.Format("{0} {1} {2}",
                        DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString(), logMessage));
        }
    }
}

PS. I don't want third party classes because they have some requirements sometimes if used from DLL which is my requirement, and in some cases I don't know directly how to enable in those classes ability to name the log entries same as the current date when log was added.


texts:
I've followed this blog to get images with nice pretty rounded corners in Android.

I've managed to strip out a lot of the superfluous arrayAdapter stuff and make it much more simple.

I've largely tweaked this just until I made it work.  Does anyone have any feedback?

class StreamDrawable extends Drawable {

    private final float mCornerRadius;
    private final RectF mRect = new RectF();
    private final BitmapShader mBitmapShader;
    private final Paint mPaint;
    private final int mMargin;

    StreamDrawable(Bitmap bitmap, float cornerRadius, int margin) {
        mCornerRadius = cornerRadius;

        mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setShader(mBitmapShader);

        mMargin = margin;
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        mRect.set(mMargin, mMargin, bounds.width() - mMargin, bounds.height() - mMargin);
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawRoundRect(mRect, mCornerRadius, mCornerRadius, mPaint);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    @Override
    public void setAlpha(int alpha) {
        mPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        mPaint.setColorFilter(cf);
    }
}

public void drawit(){
    final int CORNER_RADIUS = 24; // dips
    final int MARGIN = 12; // dips

    final int mCornerRadius;
    final int mMargin;

    final float density = this.getResources().getDisplayMetrics().density;
    mCornerRadius = (int) (CORNER_RADIUS * density + 0.5f);
    mMargin = (int) (MARGIN * density + 0.5f);

    ImageView imgvw = (ImageView) findViewById(R.id.imageView2);

    Bitmap myBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.london);

    Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, imgvw.getWidth(), imgvw.getHeight(), false);

    StreamDrawable d = new StreamDrawable(resizedBitmap, mCornerRadius, mMargin);
    imgvw.setBackground(d);
}


texts: Converting a string to various number formats

texts:
I'm working on a set of PostgreSQL helper classes, and am representing each PostgreSQL data type as objects. Instead of creating a class for each number format, I've created a template so the user can create a Number<int>, Number<double> etc as necessary, which is awesome as it saves me lots of coding!

The problem I'm facing is I have the need to convert a string representing the value of the number (which is returned from libpq) to its relevant format (the fromString method).

It's kinda messy.  Is there a neater solution than a lot of if / else's?
I also have the problem that if the string doesn't contain type T, it causes an exception, so, to be safe, I'd have to wrap everything inside a try/catch making it even more messier! So, is there a way around doing this?

template <typename T>
class Number : public spg::datatypes::BaseDataType
{
public:
    Number() : BaseDataType(false) { checkTIsNumeric(); }
    Number(T val) : BaseDataType(false), val(val) { checkTIsNumeric(); }
    Number(const std::string& s) : BaseDataType(false) { checkTIsNumeric(); fromString(s); }

    std::string toString() const { return std::to_string(val); }
    int getParamCount() { return 1; }

    T val;

protected:
    void parseString(std::vector<std::string>& splitted)
    {
        // see http://www.cplusplus.com/reference/string/

        size_t hc = typeid(T).hash_code();

        // TODO maybe these should be wrapped inside try/catch because if string doesn't contain T, it will throw
        if (hc == typeid(int).hash_code())
            val = std::stoi(splitted[0]);
        else if (hc == typeid(double).hash_code())
            val = std::stod(splitted[0]);
        else if (hc == typeid(long double).hash_code())
            val = std::stold(splitted[0]);
        else if (hc == typeid(float).hash_code())
            val = std::stof(splitted[0]);
        else if (hc == typeid(long).hash_code())
            val = std::stol(splitted[0]);
        else if (hc == typeid(unsigned long).hash_code())
            val = std::stoul(splitted[0]);
        else if (hc == typeid(long long).hash_code())
            val = std::stoll(splitted[0]);
        else if (hc == typeid(unsigned long long).hash_code())
            val = std::stoull(splitted[0]);
    }

private:
    void checkTIsNumeric()
    {
        if (!std::is_arithmetic<T>::value || std::is_class<T>::value)
            throw "T is not numeric";
    }

};

I'm not sure if the checkTIsNumeric is necessary, as compilation will fail if a non numeric type is passed as T because std::to_string doesn't have a suitable overload.

I did a few tests using the giant if / else above, and using a std::stringstream. The latter was noticeably slower. E.g. in one benchmark, 14.0781s for the above code vs 19.6901s using std::stringstream.


texts:
After reading about Strand Sort on Wikipedia and testing the provided Python version, I decided to try my hand at a faster implementation. I've studied the "Time Complexity" page, read many different approaches to mergesort (and borrowed some), tested the code myself with profiler, line_profiler, and timeit, and I think I've got sped up pretty well.

I'm looking for any ideas on how to optimize this code without changing the sorting algorithm itself or resorting to using Python's timsort for any number of elements.

def strand_sort(array):
    if len(array) < 2:
        return array
    result = []
    while array:
        i = 0
        sublist = []
        sublist.append(array.pop())
        while i < len(array):
            num = array[i]
            if num > sublist[-1]:
                sublist.append(num)
                del array[i]
            else:
                i = i + 1
        result = merge(list(result), sublist)
    return result

def merge(list_1, list_2):
    i = 0
    j = 0
    merged_list = []
    while i < len(list_1) and j < len(list_2):
        if list_1[i] > list_2[j]:
            merged_list.append(list_2[j])
            j += 1
        else:
            merged_list.append(list_1[i])
            i += 1
    merged_list += list_1[i:]
    merged_list += list_2[j:]
    return merged_list


texts: using 2D array to read datatable ok? or repeatedly call function that reads record by record?

texts:
I am asking this for coding style.  I have a program class that calls a function(of a data access class) that reads from a table (using entity framework by the way), and I'm preparing to write the DataAccess.ReadMethod().

Is it better to pass the function a 2d string array string[rows][fields], reading each field and each row, and put it in the DataAccess.ReadMethod's out parameter string[rows][fields] to return to the main program and have the main program display it? or just repeatedly call the DataAccess.ReadMethod(string[fields]) and in the main program print each record out individually to the console?

I imagine that my ReadMethod() will look something like this:

public class DataAccess
{
    public Exception ReadMan(TestDatabaseEntities dbEntities, IQueryable myQuery, out string sManDetails)
    {
        Exception ex = null;
        sManDetails = "";
        try
        {
            foreach (Man m in myQuery)
            {
                sManDetails += m.ManID.ToString() + " " + m.Name + "\n";
            }
        }
        catch (Exception myException)
        {
            ex = myException;
        }
        return ex;
    }
}

the calling code in program class looks like this:

class program
{
    static private void DoRead()
    {
        var dbEntities = new TestDatabaseEntities();
        UserInterface MyUI = new UserInterface();
        DataAccess MyDA = new DataAccess();
        Exception ex = null;
        string sMyMen = "";

        var query = from person in dbEntities.Men
                    where true
                    select person;
        MyUI.DisplayDivider();
        ex = MyDA.ReadMan(dbEntities, query, out sMyMen);
        if (ex != null)
            sMyMen = ex.ToString();
        MyUI.DisplayMessage(sMyMen);
        MyUI.DisplayDivider();
    }
}


texts:
I have the following list to sort:

A 0.53
B 0.56
C 0.56
D 0.98
E 0.33

Please note that my list may contains thousands of such type of records. I am sorting my list and put the sorted list into an array as:

  String str="";
        for(String s: mylist){
            str+=s+",";
        }
        String[] sArr = str.split(",");
        String temp="";
        for(int i=0; i<sArr.length;i++) {
            for(int j= i+1; j<sArr.length;j++){
                if(sArr[i].split("\\s")[1].compareToIgnoreCase(sArr[j].split("\\s")[1])<0){
                    temp= sArr[j];
                    sArr[j]= sArr[i];
                    sArr[i]=temp;
                }
            }
        }

       //sArr now contains the sorted list

The problem is that it is taking too long to get sorted when I have thousands of records. Is there any other way to perform the same task efficiently in less time, or is there something wrong with my way of coding?


texts: Building a dynamic dictionary mapper inside function

texts:
I have one function attrmapper. The purpose for this function is to build a dictionary, information, as attribution for the object. Is there a better way for me to rewrite the obj.information.update( part? The part to update information attribution will be more clear? Because if we replace mapping to a long string, the function will be really hard to read.

mapping = {
'firstname': 'this is fisrt name: {} should be string',
'lastname': 'this is last name: {} should be string',
'address': 'this is address {} should be address1, address2, state, state and zipcode',
'phone_number': 'this is phone number {} should be 0 to 9',
'gender': 'this is gender {}: should be male or female',
'company': 'this is company {} should be start with G',
'position': 'this is position {} should be engineer, manager and level',
'aAbreu': 'Albert Abreu',
'cGreen': 'Chad Green',
'lCessa': 'Luis Cessa',
'aJudge': 'Aaron Judge',
'jEllsbury': 'Jacoby Ellsbury',
    }
def attrmapper(obj: object) -> object:
    information = {}
    for name in ['aAbreu', 'cGreen', 'lCessa', 'aJudge', 'jEllsbury']:
        obj.information.update(
            {'{}_firstname'.format(name): mapping.get('firstname').format(mapping.get(name)),
            '{}_lastname'.format(name): mapping.get('lastname').format(mapping.get(name)),
            '{}_address'.format(name): mapping.get('address').format(mapping.get(name)),
            '{}_phone_number'.format(name): mapping.get('phone_number').format(mapping.get(name)),
            '{}_company'.format(name): mapping.get('company').format(mapping.get(name)),
            '{}_position'.format(name): mapping.get('firstname').format(mapping.get(name))})
    return obj


texts: Shortest prime number generator we could come up with?

texts:
I worked with a friend on the following prime number generator. Our goal was to make it as short and as fast as possible. This is what we came up with:

def p(n): # will print out primes between 0 and n
  s=[True]*(n/2)
  for i in range(int((n/2-1)/2) >> 1):
    for j in range((i*(i+3)<<1)+3,n/2,(i<<1)+3): s[j]=False
  return [2] + [((i<<1)+3) for i in range(n/2) if (s[i])]
print p(input()) # input number for n

Can it be made any faster? Also, it crashes due to memory errors if numbers larger than 1010 are inputted. Can this be fixed to make it more memory efficient?


texts:
I've just started learning R, but I feel that I'm using it only as a normal procedural language without taking advantage of some built-in functions and data structures.

I wrote a function that calculates repayments for mortgage with an option of specifying list of overpayments to reduce monthly payments.  Please suggest any improvements on making it more native to R.

source("http://pastebin.com/raw.php?i=q7tyiEmM") ## for pmt()
mortgage <- function(price=1000000, deposit=0.10, rate=0.04, years=25, over=c()) {
    loan <- price - price * deposit
    months <- years * 12
    capital <- c()
    interest <- c()
    payments <- c()
    currentCapital <- loan
    monthlyRate <- rate / 12
    payment <- -pmt(monthlyRate, nper = months + 1, pv = loan)

    cat("Initial capital: ", loan, "\n")
    cat("Months: ", months, "\n")
    cat("Payment: ", payment, "\n")

    totalShouldPay <- payment * months
    totalPaid <- 0

    for(currentMonth in 1:months) {
        interest <- currentCapital * monthlyRate
        repaid <- payment - interest
        currentCapital <- currentCapital - repaid

        overPayments <- subset(over, over$month == currentMonth)
        if (length(overPayments) > 0 && nrow(overPayments) > 0) {
            overPayments <- sum(overPayments$payment)
            currentCapital <- currentCapital - overPayments
            payment <- -pmt(monthlyRate, nper = months + 1 - currentMonth, pv = currentCapital)
        }

        capital <- append(capital, currentCapital)

        totalPaid <- totalPaid + payment
        payments <- append(payments, payment)
    }
    cat("Would have paid: ", round(totalShouldPay, 2), "\n")
    cat("Will pay: ", round(totalPaid, 2), "\n")
    cat("Saved: ", round(totalShouldPay - totalPaid, 2), "\n")
    return(data.frame(capital=capital, payments=payments))
}

overPayments <- data.frame(
    month   = c(20,    25,    30,    35,    40),
    payment = c(20000, 20000, 20000, 20000, 20000))

cap <- mortgage(
    over = overPayments
)

#print(cap)
par(mfcol=c(1, 2))
plot(cap$payments, type="s", main = "Payments", xlab = "Month", ylab = "Payment")
plot(cap$capital, type="l", main = "Capital", xlab = "Month", ylab = "Remaining loan")


texts:
I've been using the following user agent Regular Expression to detect mobile devices, but I recently came across a few resources that listed a whole host of mobile user agents that I had not heard of before.

Whilst my agent check is only the first step in the detection process - I also have some JavaScript as a fallback - I would like for it to contain the majority of currently undisputed mobile "keywords" so as to optimise the user experience for those handsets. I would also like to keep things as future-proof as possible, but this can only ever be argued with good reasoning and not set-in-stone.

The core of the regexp follows - please note the user agent string has had it's white-space removed. The check is also specifically case dependent.

Please ignore the newlines; they are for formatting only.

/i[Pp]hone|[Mm]obile[Ss]afari|[Ww]indowsCE|[Ww]indows[Pp]hone|
 IE[Mm]obile|[Oo]pera[Mm]ini|[Oo]pera[Mm]obi|[Bb]lack[Bb]erry|
 [^A-Z]RIM[^A-Z]|[Ss]ony[Ee]ricsson|[Nn]okia|[^A-Z]MIB[^A-Z]/

These are the extra edge-case agents that I've found out about:

/[Ss]kyfire|[Tt]ea[Ss]hark|[Nn]et[Ff]ront|[Mm]inimo|
 [Ii]ris|[Ff]ennec|[Dd]oris|[Ss]eries60|BOLT|[Bb]lazer/

Does anyone have any further suggestions, or possible keywords to remove, that could cause false positives?

For example, I do not include Samsung or Android for the precise reasons that they are not unique to mobile agents. I'd rather let agents through to the JavaScript that I'm unsure about.

As a second note, many user-agents report as Like Something - i.e. Like Mobile Safari - should I filter these out of the equation, or if something is reporting this; is it also likely to be a mobile device.


texts: Daemonize a process under Microsoft Windows

texts:
I wrote a simple tool to allow to daemonize any process under Microsoft Windows.

The goal is to push any process into the background with no questions asked. That includes GUI applications, which means that the main window will not be created...or at least not shown. For console applications it will simply detach the process from the current console and not open another one. Usage is simple:

daemonize.exe PROGRAM [ARGUMENTS]

So let's cut to the code:

#include <stdio.h>
#include <string.h>

#include <windows.h>

// The important things to note and know:
//
//  * Only works with ASCII paths and filenames.
//  * Quotes all arguments regardless of content.
//  * SW_HIDE in STARTUPINFO is needed for GUI applications
//  * DETACHED_PROCESS in CreateProcessA is needed for command line applications
//

int main(int argc, char *argv[]) {
    if (argc <= 1) {
        printf("daemonize.exe COMMAND [ARGUMENTS]");
        return 1;
    }

    char* command = argv[1];
    char* arguments = NULL;

    if (argc > 2) {
        // We only need to concatenate arguments if there
        // actually are arguments.
        int idx;

        // Calculate the length of all arguments
        size_t argLength = 0;
        for (idx = 1; idx < argc; idx++) {
            argLength += strlen(argv[idx] + 2 + 1); // One for the space, two for the quotes.
        }
        argLength--; // Strip the last space.

        // Reserve some memory and NULL the new string.
        //The + 1 is the space for the last null character.
        arguments = (char*)malloc(sizeof(char) * (argLength + 1));
        arguments[0] = 0;

        // Now concatenate the arguments.
        for (idx = 1; idx < argc; idx++) {
            strcat(arguments, "\"");
            strcat(arguments, argv[idx]);
            strcat(arguments, "\"");
            if (idx < argc - 1) {
                strcat(arguments, " ");
            }
        }
    }

    STARTUPINFO startInfo;
    PROCESS_INFORMATION process;

    ZeroMemory(&startInfo, sizeof(startInfo));
    ZeroMemory(&process, sizeof(process));

    startInfo.cb = sizeof(startInfo);

    // Tell the system to use/honor the ShowWindow flags.
    startInfo.dwFlags = STARTF_USESHOWWINDOW;
    // Tell the system that the main window of the process should be hidden.
    startInfo.wShowWindow = SW_HIDE;

    if (!CreateProcessA(
            command,            // application name
            arguments,            // command line arguments
            NULL,                // process attributes
            NULL,                // thread attributes
            FALSE,                // inherit (file) handles
            // Detach the process from the current console.
            DETACHED_PROCESS,   // creation flags
            NULL,                // environment
            NULL,                // current directory
            &startInfo,            // startup info
            &process)            // process information
        ) {

        printf("Creation of the process failed, trying to fetch error message...\n");

        long lastError = GetLastError();
        char* message = NULL;

        FormatMessageA(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_ARGUMENT_ARRAY |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS, // Flags
            NULL,               // source
            lastError,          // message identifier
            0,                  // language id
            (LPSTR)&message,   // message buffer
            0,                  // size of the message
            NULL                // arguments
        );

        printf(message);

        return 1;
    }

    return 0;
}


texts: Optimization of startswith, list intersection with duplicates and substring search

texts:
def check_rule(token, training_data, mode):
    if mode == "frag":
        children = training_data["words"]
        remove = list.remove
        def in_child(x):
            for i in token:
                if i not in x:
                    return False
                remove(x, i)
            return True

        for i in children:
            if in_child(i):
                return False
        return True

        # is_present = children.map(in_child)
    elif mode == "wild":

        # is_present = training_data[1].map(methodcaller("__contains__", token))

        for i in training_data[1]:
            if token in i:
                return False
        return True

    elif mode == "prefix":
        # is_present = training_data[1].str.startswith(token)

        token_len = len(token)
        for i in training_data[1]:
            if i[:token_len] == token:
                return False
        return True

        # token_len = len(token)
        # is_present = training_data[1].str[:token_len] == token

        # is_present = training_data[1].map(methodcaller("startswith", token))

    # if is_present.any():
    #     return False
    # return True

This function takes in:

token: string
training_data: A pandas dataframe with 2 columns having ID and vendor name columns
mode: Which can be any one of the prefix, wild, frag.

I have 5 data structures:

Vendor data: Having vendor names in one column (there are other columns as well but only this name is relevant).
Sub vendor data: A dict, for each <vendor name> there is a list of <sub-vendor>.
Rule data: For each mode there is a dict with <vendor name><sub vendor name> as key and value is a string rule.

So, for each vendor and sub vendor, whole data minus the rows having the respective vendor, the corresponding rule is checked if it is present in any of the rows. This rule checking is done by the code segment I have provided.

The commented parts are the optimizations I tried after profiling. But, it still takes a lot of time. Can this be optimized further?


texts: Search for subsets within a 250k line text dataset

texts:
The code below works pretty well - it takes about 4 seconds (this seems too slow for me) to find a group that's located in the tail area of the text file I'm searching. The text file has ≃ 250,000 lines with 20 elements per line. I cut my teeth on other programming languages and picked up Python just for this current project I'm working on, so I really am a neophyte when it comes to python efficiency.

with open(file) as infile:
    datadictionary = csv.DictReader(infile, dialect='excel-tab', quoting=csv.QUOTE_NONE)
    for key, group in itertools.groupby(datadictionary, key=lambda x:x[patient_number_field_header] == patient_id):
        if key:
            super_list = group
            break

'patient_id' is a string of digits
file is a text file

I'm wondering what you think - how can I make this more efficient? Am I "doing it wrong"?


texts: A simple brainf*** interpreter in Haskell

texts:
I am very new to Haskell and come from languages like C++, although I do have some experience with Scheme. Here, I wrote a simple brainf*** interpreter, which so far is my largest project. I followed a tutorial for some of the code (such as the Tape data type), but did most of this on my own. I have one major concern with my approach, which is the way I handle the loops (which in brainf*** are written with [] and repeat until the current cell in the tape is zero. In my implementation, I used the loop as a parameter to the main recursive function, which is called if the current instruction is ] and the current cell is not 0. Since these loops modify the tape, I had to make them return an instance of Tape that would replace the current one. However, since the function also handles IO (and therefore must return an instance of IO), I made it return an IO (Tape Int) which is then unpacked in a do block. This all felt very messy and hacky, so I would really appreciate any help from more experienced Haskell developers.

import Data.Maybe

--The Tape data type and functions

data Tape a = Tape [a] a [a]

newTape :: a -> Tape a
newTape x = Tape r x r
    where r = repeat x

moveLeft :: Tape a -> Tape a
moveLeft (Tape (l:ls) x rs) = Tape ls l (x:rs)

moveRight :: Tape a -> Tape a
moveRight (Tape ls x (r:rs)) = Tape (x:ls) r rs

--The Brainf*** instruction data types

data BfInstruction
    = MovLeft
    | MovRight
    | Increment
    | Decrement
    | Output
    | Input
    | BeginLoop
    | EndLoop
    deriving (Show, Eq)

type BfProgram = [BfInstruction]

--Convert string to BfProgram

parseBf :: String -> BfProgram
parseBf = mapMaybe parse
    where
        parse :: Char -> Maybe BfInstruction
        parse x = case x of
            '<' -> Just MovLeft
            '>' -> Just MovRight
            '+' -> Just Increment
            '-' -> Just Decrement
            ',' -> Just Input
            '.' -> Just Output
            '[' -> Just BeginLoop
            ']' -> Just EndLoop
            x   -> Nothing         --anything but the above chars is a comment

--Main running function

runBf :: String -> IO ()
runBf p = runBf' (parseBf p) (newTape 0) [] >> return ()
    where
        runBf' :: BfProgram -> Tape Int -> BfProgram -> IO (Tape Int)
        runBf' [] tape _ = return tape
        runBf' prog@(p:ps) tape@(Tape ls x rs) loop = case p of
            MovLeft   -> advance prog (moveLeft tape)
            MovRight  -> advance prog (moveRight tape)
            Increment -> advance prog (Tape ls (x+1) rs)
            Decrement -> advance prog (Tape ls (x-1) rs)
            Input     -> do
                char <- getChar
                advance prog (Tape ls (fromEnum char) rs)
            Output    -> putChar (toEnum x) >> advance prog tape
            BeginLoop ->
                let lp = getLoop 1 ps
                in runBf' (length lp `drop` ps) tape lp  --Drop so that we are at the ] now
            EndLoop   ->
                if x /= 0
                then do
                    lt <- runBf' loop tape []
                    runBf' prog lt loop       --Copy the tape from the result of the loop into next iteration
                else advance prog tape

        advance :: BfProgram -> Tape Int -> IO (Tape Int)
        advance (p:ps) tape = runBf' ps tape []

        getLoop :: Int -> BfProgram -> BfProgram
        getLoop _ [] = error "Mismatched brackets in BF program"
        getLoop 1 (EndLoop:ps) = []
        getLoop n (p:ps) = p:case p of
            BeginLoop -> getLoop (n + 1) ps
            EndLoop   -> getLoop (n - 1) ps
            _         -> getLoop n ps

--Simple IO

main = do
    program <- readFile "program.bf"
    runBf program


texts:
It's an assignment from the Odin Project.
Here's my implementation:
#!/usr/bin/env ruby

def caesar_cipher(str, shift)
    low_alpha = ("a".."z").to_a
    high_alpha = ("A".."Z").to_a
    length_alpha = low_alpha.length

    chars = str.split("")
    ciphered = ""

    chars.each do |char|
        if low_alpha.include? char
            i = low_alpha.index(char)
            shifted = (i + shift) % length_alpha

            ciphered << low_alpha[shifted]
        elsif high_alpha.include? char
            i = high_alpha.index(char)
            shifted = (i + shift) % length_alpha

            ciphered << high_alpha[shifted]
        else
            ciphered << char
        end
    end

    ciphered
end

puts caesar_cipher("What a string!", 5) # Bmfy f xywnsl!
puts caesar_cipher("Abc", 5) # Fgh
puts caesar_cipher("Xyz", 3) # Abc
puts caesar_cipher("Test", 1) # Uftu
puts caesar_cipher("Zoo", 10) # Jyy

What points could be improved? What would you have done differently and why?


texts: Checking whether users have a role that allows them to index sheets

texts:
Is there any DRYer way to write this method ? or is it better to keep it this way for better reader understanding ...

Each role has a list of authorised activities for a specific resource ( in this case Sheet) , a user may have multiple roles ( depending upon his company, his working group in the company, his function in the working group). This method is a sheet_policy, if among all roles , the current user can "index" sheets, the method returns true otherwise it returns false

   def index?
    # check if sheet#index is listed in current_user roles activities
    sheet_activities = []
    user.roles.each {|role| sheet_activities << role.activities["sheet"]}
    return false if sheet_activities.first.nil? # no authorized activities on Sheet
    sheet_activities.flatten.uniq!.include?("index")
  end

activities is a JSONB attribute of the Sheet record ...

create_table :roles do |t|
  t.string      :company, null: false, default: Settings.company.default.name
  t.string      :group
  t.string      :function
  t.jsonb       :activities, null: false, default: '{}'
  t.timestamps  null: false

Seeding example :

   @role_accounting_employee = Role.create( group: "accounting", function: "employee")  # default company : "internal"
   @role_accounting_employee.activities.deep_merge!({sheet: %w(show index) })


texts: Create a summary report by summing the amount's of accounts with the same name and within the date range specified

texts:
I have heard from my friend that it is bad practice to normally loop though the whole database to meet certain criteria. He mentioned something about the proper way being that you index the objects of interest.

What I want to achieve here is make a report for our company. So I do this by summing up all the items that have the same account that is within the filter date range set by start_date and end_date to start.

Some variable definitions:

Account name: data_entries.iloc[j, 4]

Account type: data_listofaccounts.iloc[i, 1]

Account amount: data_entries.iloc[j, 5]

So is there a more efficient way to write this code that will be less computationally taxing on the computer specifically. (minimize computational requirement)

import pandas as pd
import datetime

entries_csv = "C:\\Users\\Pops\\Desktop\\Entries.csv"
listofaccounts_csv = "C:\\Users\\Pops\\Desktop\\List of Accounts.csv"

data_entries = pd.read_csv(entries_csv)
data_listofaccounts = pd.read_csv(listofaccounts_csv)
data_entries['VOUCHER DATE'] = pd.to_datetime(data_entries['VOUCHER DATE'], format="%m/%d/%Y").dt.date

summary_amount = [0]*(len(data_listofaccounts) + 1)
summary = (('DEBIT ACCOUNT', 'DEBIT AMOUNT'),)

start_date = datetime.date(2018, 4, 1)
end_date = datetime.date(2018, 10, 30)

for i in range(0, len(data_listofaccounts)):
    for j in range(0, len(data_entries)):
        if start_date <= data_entries.iloc[j, 1] <= end_date:
            if data_listofaccounts.iloc[i, 0] == data_entries.iloc[j, 4]\
                    and (data_listofaccounts.iloc[i, 1] == "CURRENT ASSET" or
                         data_listofaccounts.iloc[i, 1] == "FIXED ASSET" or
                         data_listofaccounts.iloc[i, 1] == "EXPENSE"):
                summary_amount[i] += data_entries.iloc[j, 5]
            elif data_listofaccounts.iloc[i, 0] == data_entries.iloc[j, 4]\
                    and (data_listofaccounts.iloc[i, 1] == "CURRENT LIABILITY" or
                         data_listofaccounts.iloc[i, 1] == "LONG TERM LIABILITY" or
                         data_listofaccounts.iloc[i, 1] == "EQUITY"):
                summary_amount[i] -= data_entries.iloc[j, 5]
    summary += ((data_listofaccounts.iloc[i, 0], "{:,}".format(round(summary_amount[i], 2))),)

Entries sample data:

List of Accounts sample data:

List of Accounts contains unique account names while in the Entries worksheet, it can be repeated.


texts: Class creating dropdown options from MySQL data for multiple scripts

texts:
I created this class to handle some dropdowns that I'd been creating using a squirrelly combination of HTML, jQuery, and AJAX. This works much better in the one script that I've deployed it in:

namespace appwpclass;

class PopulateDropdown
{
    public $skillArray;
    public $grpArray;
    public $facArray;
    /**
     * PopulateDropdown constructor.
     */
    public function __construct() {
        $skillArray[] = $this->skillArray;
        $grpArray[] = $this->grpArray;
        $facArray[] = $this->facArray;
    }

    public function skillSelect($category){
        //query to db to get skills
        return $skillArray;
    } //end function

    public function groupSelect($category, $mem_type, $selected_group=NULL){

// query to get list of clients -- it is allowed to be NULL in which case ALL active clients will be returned
        return $grpArray;
    } //end function

    public function facilitySelect($selected_group){
        //query to get list of facilities associated with a $selected_group, which is a required field.
            return $facArray;

    } //end function

} //end class

Now, in my admittedly "procedural" PHP script (which I'm trying to refactor), I have "required" this Class:

require '../appwpclass/PopulateDropdown.php';

And in that script, I have these statements in order to populate the various dropdowns:

$dropdown = new appwpclass\PopulateDropdown();
$skillsArr = $dropdown->skillSelect($category);
$groupArr = $dropdown->groupSelect($category, $memType, $selGroup);
$facilityArr = $dropdown->facilitySelect($selGroup);

And then I use those arrays in filter dropdown HTML, as in this example:

<select name="selGroup" id="selGroup" size="1" class="textfield" onchange="submit()">
 <option value="0">--Any--</option>
<?php
foreach( $groupArr as $group_id=>$group_name ) {
    $selected = ( $group_id == $selGroup ) ? ' selected' : '';
    ?>
    <option value="<?php echo $group_id;?>"<?php echo $selected;?>><?php echo $group_name;?></option>
<?php } ?>

This all works fine in this one script, but I have a lot of scripts that also use one, two, or all of these dropdowns.
So I thought about just using them in a "require" somewhere in each script, but I'm thinking there has to be a better OOP way.
Maybe I should create another class and instantiate PopulateDropdown in that class's constructor? Or in another method in that other class? And then have a separate method for each of those statements, e.g. a method for

 $skillsArr = $dropdown->skillSelect($category)

, etc.. I guess if I did that, I'd need to "pass" the 3 properties that are required by one or more of these existing methods.

Would anyone please provide me some direction on this? I'm pretty new to OOP and I'm starting to use Laravel but I'm nowhere near ready to refactor this enterprise system yet.

If I used a new class, as I suggested, then obviously I'd require that class or use that namespace in my other scripts. Just seems like that would be more concise and less prone to errors.


texts: Python tool to reduce number of resistors in circuit

texts:
I've written a tool in Python to help me with a specific problem I have with electronic circuit design. Here are the motivations:

It is common in circuit design to need to choose two resistor values to form a voltage divider. Any number of combinations of resistors can satisfy the divider. And there are a lot of available resistor values to choose from. It is not uncommon for an engineer to just pick a resistor value out of thin air and solve for the other.
It is very desirable to reduce the number of line items in the BOM for a circuit board. In other words, the more resistor values I can share elsewhere in the same circuit, the better.

Prior to running this program, I have created lists of candidate resistor pairs and their combined cost in separate files. The contents of these JSON-encoded files look like this:

[[RA1, RA2, priceA],[RB1,RB2,priceB],[RC1,RC2,priceC],...]

Every pair of resistors in the same file will satisfy some specified voltage divider ratio. I have as many files as I have unique voltage dividers in the circuit.

My program then takes the multiple JSON files as input arguments, generates every permutation of resistor combinations, and tries to find which permutation produces the least number of unique resistor values. I also have it only show me the outputs with the lowest combined resistor price (many resistors are the same cost, so this helps pare down the results).

I am very new to Python and come from a long history of coding in C. I want to learn how to make this code more Pythonic. In particular, I'm convinced the embedded for-loops in the middle of the code can be replaced with something much more efficient.

resistor_bom_reducer.py:

"""
  python3 resistor_bom_reducer.py file1.json file2.json file3.json ... fileN.json
"""

import json
import sys
import itertools

pairlists = []
totalperms = 1

# Read in JSON data from input arguements.
# pairlists is a list of lists representing every pair of resistors and their combined cost
for filename in sys.argv[1:]:
    with open(filename) as json_data:
        lst = json.load(json_data)
        totalperms *= len(lst)
        pairlists.append(lst)

print("Calculating permutations: %d" % totalperms)
perms = list(itertools.product(*pairlists))
print("Done")

# Loop through every permutation of resistors.
# combo is a list of flattened lists of every resistor combination
combo = [[0 for rows in range(len(pairlists)*2)] for cols in range(len(perms))]
price = [0 for x in range(len(perms))]
count = 0
for i in range(0,len(perms)):
    for j in range(0,len(pairlists)):
        combo[i][2*j] = perms[i][j][0]
        combo[i][2*j+1] = perms[i][j][1]
        price[i] += perms[i][j][2]
        count += 1
        if ( count % 1000000 == 0 ):
            print("%d of %d" % (count,totalperms))

print("")

# Find the combination with the least number of unique resistor values
minlen = 999
for s in combo:
    if ( len(set(s)) < len(pairlists)*2 ):
        if ( len(set(s)) < minlen ):
            minlen = len(set(s))

# Find the lowest combination price
minprice = 999.0
for s,p in zip(combo,price):
    if ( len(set(s)) == minlen ):
        if ( p < minprice ):
            minprice = p

# Print only combinations of the lowest price and least number of unique resistor values
for s,p in zip(combo,price):
    if ( len(set(s)) == minlen ):
        if ( p == minprice ):
            print(s,p)


texts: Underscore-case version of ActiveRecord model's name

texts:
Is there a better way to get the underscore-case version of an ActiveRecord model's name? So far this works, but it's far from ideal:

my_active_record_instance.class.name.underscore


texts: Stack having push, pop and return min in O(1)

texts:
I am using a class which is taking care of minimum value so far. Please let me know of any improvements or suggestions.

class MinStack {

    Stack<Node> s1 = new Stack<>();

    public void push(int x) {
        if(s1.isEmpty()) {
            s1.push(new Node(x,x));
        } else {
            s1.push(new Node(x,Math.min(s1.peek().min, x)));
        }

    }

    public void pop() {
        s1.pop();
    }

    public int top() {
        return s1.peek().val;
    }

    public int getMin() {
        return s1.peek().min;
    }

    static class Node{
        int val;
        int min;
        public Node(int v, int m) {
            val = v;
            min = m;
        }
    }
}


texts: Scrapy crawler to parse data recursively

texts:
I've written a script in python scrapy to parse "name" and "price" of different products from a website. Firstly, it scrapes the links of different categories from the upper sided bar located in the main page then it tracks down each categories and reach their pages and then parse the links of different sub-categories from there and finally gets to the target page and parse the aforementioned data from there. I tried to do the whole thing slightly differently from the conventional method in which it is necessary to set rules. However, I got it working the way I expected using the logic I applied here. If any improvement is to be made, I'll be very glad to comply with. Here is what I've tried with:

"sth.py" aka spider contains:

import scrapy

class SephoraSpider(scrapy.Spider):

    name = "sephorasp"

    def start_requests(self):
        yield scrapy.Request(url = "https://www.sephora.ae/en/stores/", callback = self.parse_pages)

    def parse_pages(self, response):
        for link in response.xpath('//ul[@class="nav-primary"]//a[contains(@class,"level0")]/@href').extract():
            yield scrapy.Request(url = link, callback = self.parse_inner_pages)

    def parse_inner_pages(self, response):
        for links in response.xpath('//li[contains(@class,"amshopby-cat")]/a/@href').extract():
            yield scrapy.Request(url = links, callback = self.target_page)

    def target_page(self, response):
        for titles in response.xpath('//div[@class="product-info"]'):
            product = titles.xpath('.//div[contains(@class,"product-name")]/a/text()').extract_first()
            rate = titles.xpath('.//span[@class="price"]/text()').extract_first()
            yield {'name':product,'price':rate}

"items.py" includes:

import scrapy
class SephoraItem(scrapy.Item):
    name = scrapy.Field()
    price = scrapy.Field()

The command I used to get the result along with a csv output is:

scrapy crawl sephorasp -o items.csv -t csv


texts:
Given a number of functions f1, f2, f3, ..., fn I want to create a composite function g so that g(x) calls f1(f2(f3(...(fn(x)))).

I came across a blog post which was mentioned in a related Stack Overflow question.

These solutions seem to be very involved. In my own code, I am using a very simple recursion of std::bind instead.

#pragma once

#include <functional>

// TODO: C++14: remove traits and use auto return type deduction

// traits to infer the return type of recursive binds
template<typename... Fn>
struct composite_function_traits;

// bind a single function with a placeholder
template<typename F1>
struct composite_function_traits<F1> { typedef decltype(std::bind(std::declval<F1>(), std::placeholders::_1)) type; };

template<typename F1>
typename composite_function_traits<F1>::type make_composite_function(F1&& f1)
{
    return std::bind(std::forward<F1>(f1), std::placeholders::_1);
}

// recursively bind multiple functions
template<typename F1, typename... Fn>
struct composite_function_traits<F1, Fn...> { typedef decltype(std::bind(std::declval<F1>(), std::declval<typename composite_function_traits<Fn...>::type>())) type; };

template<typename F1, typename... Fn>
typename composite_function_traits<F1, Fn...>::type make_composite_function(F1&& f1, Fn&&... fn)
{
    return std::bind(std::forward<F1>(f1), make_composite_function(std::forward<Fn>(fn)...));
}

Are there advantages to the more complex methods for function composition?