texts: PHP/MySQL to delete data from 4 different tables at once

texts:
I have four mysql tables setup like the following:

users (userid, firstname, lastname)  *one entry per user
schedules (userid, scheduleid, schedulename) *each user could have multiple schedules
classes (classid, scheduleid, classname) *each schedule is made up of multiple classes
schools (scheduleid, schoolid, schoolname) *one entry per user

I want the user to be able to delete their account, including ANY info from other tables tied to their account. So if they had 3 schedules with a bunch of classes in each and a school tied to each schedule, I'd want ALL of that data (including their user info) to be deleted in one fell swoop.

userid is all I need to delete from the users and schedules table easily.  But the classes and schools tables DON'T have a userid field, so I have to do some other way.

I wrote and tested the following code and it works fine...

//first get all schedules associated with this user account and put scheduleids into array
$sql = "SELECT scheduleid FROM schedules
        WHERE userid = '$userid'";
        $selectschedules = mysqli_query($connection, $sql);
        if (!$selectschedules) {
        die("Database query failed: " . mysqli_error());
        } else {
            while($data=mysqli_fetch_assoc($selectschedules)){
                 $schedules[] = $data;
            }
        }
//now loop through each schedule to delete all classes and any school associated with that particular schedule
foreach ($schedules as $item) {
    $sql = "DELETE FROM classes
            WHERE scheduleid = '".$item['scheduleid']."'";
            $deleteclasses = mysqli_query($connection, $sql);
            if (!$deleteclasses) {
            die("Database query failed: " . mysqli_error());
            } else {
            }
    $sql = "DELETE FROM schools
            WHERE scheduleid = '".$item['scheduleid']."'";
            $deleteschool = mysqli_query($connection, $sql);
            if (!$deleteschool) {
            die("Database query failed: " . mysqli_error());
            } else {
            }
}
//next delete all schedules associated with user account
$sql = "DELETE FROM schedules
        WHERE userid = '$userid'";
        $deleteschedules = mysqli_query($connection, $sql);
        if (!$deleteschedules) {
        die("Database query failed: " . mysqli_error());
        } else {
        }
//finally, delete the user's account
$sql = "DELETE FROM users
        WHERE userid = '$userid'
        LIMIT 1"; //should only be one, just being safe
        $deleteuser = mysqli_query($connection, $sql);
        if (!$deleteuser) {
        die("Database query failed: " . mysqli_error());
        } else {
        }

However, I believe the above code is inefficient (particularly looping through each schedule and doing delete queries on every loop). So I'm curious if there is a shorter/more efficient way to accomplish this same thing.  I am not good with JOINS and could be wrong, but would using JOINS potentially be the key to shortening this and NOT having to loop at all?

SIDE NOTE: Earlier I mentioned that classes and schools tables DON'T have a userid field.  If they did, it would be very easy to delete all of this stuff in one query. So it begs the question:  Should I add the userid field to the other tables?  I don't want to add it just to make deleting easier, but if you think it SHOULD have it regardless, then I would consider.

Any info/suggestions would be greatly appreciated.


texts:
The gist of the code is, you give it a date, it will start counting down how many days, hours, minutes and seconds left by emitting an event 'countDown' and once 0 is reached 'expired' event is emitted.

How can this code be improved?

class DateCountDown {
    listeners: Map<string, Array<Function>>;

    constructor(date: Date) {

        this.startCountDown(date);
        this.listeners = new Map();
        this.listeners.set("countDown", []);
        this.listeners.set("expired", []);
    }

    on(eventName: "countDown", listener: (values: CountDownValues) => void);
    on(eventName: "expired", listener: (isExpired: boolean) => void);
    on(eventName: string, listener: Function) {
        this.listeners.get(eventName).push(listener);
    }

    startCountDown(date: Date) {
        const thousand = 1000;
        const sixty = 60;
        const twentyfour = 24;

        const timer = setInterval(() => {
            const now = new Date().getTime();
            const t = date.valueOf() - now;

            const days = Math.floor(t / (thousand * sixty * sixty * twentyfour));
            const hours = Math.floor((t % (thousand * sixty * sixty * twentyfour)) / (thousand * sixty * sixty));
            const minutes = Math.floor((t % (thousand * sixty * sixty)) / (thousand * sixty));
            const seconds = Math.floor((t % (thousand * sixty)) / thousand);

            if (t <= 0) {
                clearInterval(timer);
                this.listeners.get("expired").forEach(listener =>
                    listener(true));
                return;
            }

            this.listeners.get("countDown").forEach(listener =>
                listener(new CountDownValues(days, hours, minutes, seconds))
            );
        }, 1000);
    }
}
    class CountDownValues {
    days: number;
    hours: number;
    minutes: number;
    seconds: number;

    constructor(days: number, hours: number, minutes: number, seconds: number) {
        this.days = days;
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;
    }

}
var date = new Date();
date.setSeconds(date.getSeconds() + 20);

let countDown = new DateCountDown(date);

countDown.on("countDown", values => {
    console.log("from first", values);
});
countDown.on("expired", isExpired => {
    console.log("expired:", isExpired);
});


texts: Implementing Division of Streams (where it's a stream of polynomial coefficients)

texts:
Per this homework, I'm trying to implement a Fractional (Stream Integer) where the stream represents coefficients of polynomials:

  where Q is defined as Q = (A'/b0) + x((1/b0)(A' − QB0)).

  where A/B = Q,

  That is, the first element of the result is A'/b0; the remainder is
  formed by computing A' − QB' and dividing each of its elements by b0

  Note that A' == tail of A and same for B'

Here's my attempt:

divStreams :: Stream Integer -> Stream Integer -> Stream Integer
divStreams a@(Cons x xs) b@(Cons y ys) =
    Cons (x `div` y) (streamMap ((1 `div` y) *) xs - (multStreams q ys) )
      where q = divStreams a b

with the following functions' definitions:

multStreams :: Stream Integer -> Stream Integer -> Stream Integer
multStreams (Cons x xs) b@(Cons y ys) =
    Cons (x * y) (streamMap (*x) ys + multStreams xs b)

data Stream a = Cons a (Stream a)

streamMap :: (a -> b) -> Stream a -> Stream b
streamMap f (Cons x xs) = Cons (f x) rest
   where rest = streamMap f xs

Note that I defined Num (Stream Integer) where (+) == combineStreams (+)

combineStreams :: (a -> b -> c) -> Stream a -> Stream b -> Stream c
combineStreams f (Cons x xs) (Cons y ys) = Cons (f x y) rest
   where rest = combineStreams f xs ys

Thanks to this answer that resolved an issue I had implementing multiplication of Streams.


texts: Project Euler 4 - Largest palindrome product

texts:
I submitted a solution to Project Euler 4 exercise: Largest palindrome product in Java. The content of following exercise:

  A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit
  numbers.

I wrote a method called isPalindrome that checks is reversing of string the same as output string. I have to obviously convert int to String to check is given number is palindrome. I created palindromes list and I loop for all possible three-digits numbers that would be multiplied and I check are these products palindromes. If yes, then I add it product to list. Next, I select only maximum palindrome from list and I print it to console.

Main.java:

package pl.hubot.projecteuler.problem4;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> palindromes = new ArrayList<>();
        for (int i = 100; i <= 999; i++) {
            for (int j = 100; j <= 999; j++) {
                if (isPalindrome(Integer.toString(i * j)))
                    palindromes.add(i * j);
            }
        }
        System.out.print(Collections.max(palindromes));
    }

    private static boolean isPalindrome(String str) {
        return str.equals(new StringBuilder(str).reverse().toString());
    }
}


texts:
Its been years (10+) since I have worked with sorting algorithms directly.  So I have been trying to go over them again to refresh my memory. The thing is my ideas of how to do it doesn't seam to match the way I have the tutorials doing it.

Does it matter?  Assuming that my code is working I would almost mean that its correct.  However I have also been looking into the Big-O I really cant remember ever seeing this before.  I would almost think that if you code it incorrectly it will slow things down and mess up the performance.

public class MergeSort2
    {

        public MergeSort2()
        {
            var data = Util.CreateData.CreateRandomIntArray(200);  // just a method that spits out an array of ints
            var sortedData = Sort(data);

        }

       private int[] copyArray(int[] A, int start, int end)
        {

            int[] result = new int[end-start];

            int cnt = 0;
            for (int i = start; i < end; i++)
            {
                result[cnt] = A[i];
                cnt++;
            }

            return result;
        }

        public int[] Sort(int[] data)
        {

            if (data.Length <= 1)
                return data;

            var length = data.Length / 2;

            int[] LeftArray = copyArray(data,0,length);
            int[] RightArray = copyArray(data, length,data.Length);

            Array.ForEach(data, a => Console.Write(a + ","));
            Console.Write("\r\n");
            Array.ForEach(LeftArray, a => Console.Write(a + ","));
            Console.Write("\t - \t");
            Array.ForEach(RightArray, a => Console.Write(a + ","));
            Console.Write("\r\n");

            RightArray = Sort(RightArray);
            LeftArray = Sort(LeftArray);

            var sorted = merge(RightArray, LeftArray);

            Console.Write("Sorted: ");
            Array.ForEach(sorted, a => Console.Write(a + ","));
            Console.Write("\r\n");

            return sorted;
        }

        public int[] merge(int[] right, int[] left)
        {

            int[] merged = new int[right.Length + left.Length];

            int cntright = 0;
            int cntleft = 0;

            for (int i = 0; i < merged.Length; i++)
            {
                if (cntright == right.Length)
                {
                    merged[i] = left[cntleft];
                    cntleft++;
                }
                else if (cntleft == left.Length)
                {
                    merged[i] = right[cntright];
                    cntright++;
                }
                else if (right[cntright] <= left[cntleft])
                {
                    merged[i] = right[cntright];
                    cntright++;
                }
                else
                {
                    merged[i] = left[cntleft];
                    cntleft++;
                }
            }

            return merged;
        }

    }

So I guess my question is two fold:

How is my implementation of merge sort?
Does it matter that I'm implementation isn't exactly the same as everyone else?


texts:
I am a C++ programmer new to Ruby and someone suggested that I post my code here since it doesn't quite match Ruby standards. Is there a more Ruby way of doing this?

I have created a 2D array full of MapTile class objects and then I draw the tiles to the screen by iterating through the 2D Array using a for loop. Here is some code.

class MapTile
attr_accessor :tileSprite, :attribute

    def initialize(sprite, attr)
    @tileSprite = sprite
    @attribute = attr
    end

    def tileSprite
        @tileSprite
    end

    def attribute
        @attribute
    end

end

def array2D(width,height)
  a = Array.new(width, MapTile.new(123,0))
  a.map! { Array.new(height, MapTile.new(123,0)) }
  return a
end

@mapData = array2D(@mapSize,@mapSize)

for i in 0..@mapSize - 1
   for j in 0..@mapSize - 1
      mapData[i][j].tileSprite = tileNum
      @tile.draw(mapData[i][j].tileSprite)
   end
end


texts:
I have a task formulated like this

  Please print a matrix in spiral order, clockwise from outer rings to inner rings.

I decided to implement it in Clojure.

(def matrix '((1 2 3 4) (5 6 7 8) (9 10 11 12) (13 14 15 16)))

(def big-matrix '(
    ( 1   2  3  4  5  6  7  8  9 )
    ( 32 33 34 35 36 37 38 39 10 )
    ( 31 56 57 58 59 60 61 40 11 )
    ( 30 55 72 73 74 75 62 41 12 )
    ( 29 54 71 80 81 76 63 42 13 )
    ( 28 53 70 79 78 77 64 43 14 )
    ( 27 52 69 68 67 66 65 44 15 )
    ( 26 51 50 49 48 47 46 45 16 )
    ( 25 24 23 22 21 20 19 18 17 ))
)

(defn get-str
  ([] "")
  ([a] a)
  ([a b] (str a " " b)))

(defn print-first-row [matrix] (reduce get-str (first matrix)))
(defn print-last-elements [matrix] (reduce get-str (map last matrix)))
(defn print-last-row-reversed [matrix] (reduce get-str (reverse (last matrix))))
(defn print-first-elements-reversed [matrix] (reduce get-str (reverse (map first matrix))))

(defn spiral (
    [matrix]
      (spiral matrix :first-row)
  )(
    [matrix op]
      (if (not (empty? matrix))
      (cond
        (= op :first-row) (str (print-first-row matrix) " " (spiral (rest matrix) :last-els))
        (= op :last-els)  (str (print-last-elements matrix) " " (spiral (map butlast matrix) :last-row))
        (= op :last-row)  (str (print-last-row-reversed matrix) " " (spiral (butlast matrix) :first-els))
        (= op :first-els) (str (print-first-elements-reversed matrix) " " (spiral (map rest matrix) :first-row)))
      )
  )
)

(spiral matrix)
(spiral big-matrix)
(spiral '())

Output:

For the first matrix the function call (spiral matrix) returns string "1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 "

The task itself is pretty simple but I am pretty new to Clojure so I would like to hear any possible improvements for this code. Thanks!


texts:
Though I have heard about the magic method __autload, I still prefer to use this code:

function autoload($array)
{
    foreach ($array as $value)
    {
        switch ($value)
        {
            case 'database' :
                include ROOT_DIR.'/core/database.php';
                break ;
            case 'user' :
                include ROOT_DIR.'/core/user_class.php';
                break ;
            case 'error_handler' :
                include ROOT_DIR.'/core/error_class.php';
                break ;
            case 'template' :
                include ROOT_DIR.'/template/rain.tpl.class.php';
                break ;
            case 'email' :
                include ROOT_DIR.'/core/email_class.php';
                break ;
        }
    }
}

I'm not exactly sure if this is a good option.  Should I switch to the magic method __autoload or keep using my simple switch case?  If you propose that I need to use the magic method instead, is it due to a performance-wise factor?  If not, why are you suggesting it?


texts: Check narrowing floating point conversions

texts:
In some code I'm working on there is a (narrowing) conversion from double to float.  The legacy code has some checks in place after the conversion is done to at least warn about values that could not be converted or whose conversion error is larger than some threshold (0.1 for example).  Just for comparison:

float target = source; // decltype(source) == double
if (std::abs(source) < 1e16) {
  if (std::abs(target) > 1e16) {
    // WARNING
  }
} else if (abs(target/source - 1) > 1e16) {
  // WARNING
}

This code lies directly on the (most) critical path, and felt very inelegant (and wrong?) to me, so I tried to improve it. Note that I don't intend to replicate the exact same behavior as the legacy code.

if (!representable_with_digits_after_point_in<float>(source, 3)) {
  // WARNING
}
float target = source;

With the following (templated) function:

/** Check whether the given value can be represented in the Target
    type with at least given number of (binary) digits after point.
 */
template <class Target, class Value>
bool representable_with_digits_after_point_in(Value const value,
                                              int digits) {
  static_assert(std::is_floating_point<Value>::value
                && std::is_floating_point<Target>::value,
                "Intended to be used with floating point types");
  using limits = std::numeric_limits<Target>;
  int exponent;
  static_cast<void>(std::frexp(value, &exponent));
  if (exponent > limits::max_exponent
      || (limits::digits - exponent) < digits) {
    return false;
  }
  return true;
}

I'm pretty sure (though I haven't measured yet) that my version is a lot faster than the legacy one on one of the target platforms which doesn't have hardware floating point support.  I'm also guessing that on the other platforms the actual speed difference will be negligible.

What I'm more concerned about: Do I correctly detect all circumstances where the conversion result will be +/- Infinity (when the source is not) and where the conversion error (abs(static_cast<double>(target) - source) so to say) will be more than 2^(-digits) (digits = 3 in my example call above)?

Apart from that, any other suggestions on how to improve my code? Other ways to get the job done without any floating point arithmetic?


texts: Compute the number of ways a given amount (cents) can be changed

texts:
Given an infinite number of different coin types (such as pennies,
  nickels, dimes, quarters) find out how many ways n cents can be
  represented.

My code appears to work (although I am curious to know if it has any correctness issue). But I feel like the memoization I am doing is a bit inelegant. Can we do without dictionaries/maps, perhaps a dynamic programming based approach using 2d arrays? Or is that even worse in terms of time and space complexity?

Also is my code to update the memoized_sol good in terms of coding technique?

'''
Parameters:
    cents: amount to get change for.
    coin_vals: list of coin denominations in no particular order.

Returns:
    number of ways <cents> can be changes using any number of coins from the given list
'''
def get_coin_change_count (cents, coin_vals):
    memoized_sol = {}
    return compute_coin_change_count(cents, coin_vals, 0, memoized_sol )

def compute_coin_change_count (rem_cents, coin_vals, coin_index, memoized_sol ):

    if coin_index in memoized_sol:
        if rem_cents in memoized_sol[coin_index]:
            return memoized_sol[coin_index][rem_cents]
    else:
        memoized_sol[coin_index] = {}

    if rem_cents == 0:
        return 1

    if coin_index >= len(coin_vals):
        return 0

    coin_val = coin_vals[coin_index]

    i = 0
    count = 0
    while i*coin_val <= rem_cents:
        count = count + compute_coin_change_count\
            ( rem_cents - i*coin_val, coin_vals, coin_index+1, memoized_sol )
        i = i + 1

    memoized_sol[coin_index][rem_cents] = count
    return count

w = get_coin_change_count ( 37, [10, 1, 5, 25])
print (w)


texts: Inefficient PowerShell function for checking group membership

texts:
I use the following function in a PowerShell script to check and - depending on the value of the $Action - either add or remove an Active Directory User Object from a Security Group.

Function Update-Group-Membership ($Action, $ADUser_Properties, $GroupName, $LogPathFileName) {

    $CurrentGroupMembers = Get-ADGroupMember -Identity:$GroupName | ? { $_.objectClass -ieq 'user' } | Select-Object -ExpandProperty "samAccountName"
    $ExistingMember = [bool]($ADUser_Properties | ? { $CurrentGroupMembers -contains $_.samAccountName })

    If ($Action -eq "ADD") {
        If ($ExistingMember) {
            "[" + (Get-Date -format "dd/MM/yyyy HH:mm:ss") + "]  ... Update NOT Required: Existing Member of $GroupName" | Out-File $LogPathFileName -Append
            Write-Host "  ... Update NOT Required: Existing Member of $GroupName" -ForegroundColor DarkGray
        } Else {
            # Add to the group
            $PSCommand = $ADUser_Properties | Add-ADPrincipalGroupMembership -MemberOf:$GroupName
            "[" + (Get-Date -format "dd/MM/yyyy HH:mm:ss") + "]  ... Updated: Added to $GroupName" | Out-File $LogPathFileName -Append
            Write-Host "  ... Updated: Added to $GroupName" -ForegroundColor Yellow
        }
    }

    If ($Action -eq "REMOVE") {
        If ($ExistingMember) {
            # Remove to the group
            $PSCommand = $ADUser_Properties | Remove-ADPrincipalGroupMembership -MemberOf:$GroupName -Confirm $False
            "[" + (Get-Date -format "dd/MM/yyyy HH:mm:ss") + "]  ... Updated: Removed from $GroupName" | Out-File $LogPathFileName -Append
            Write-Host "  ... Updated: Removed from $GroupName" -ForegroundColor Yellow
        }
}
}

The function is called as follows:

Update-Group-Membership "ADD" $ADUser_Properties "SECURITY_GROUP_NAME" $LogPathFileName

$ADUser_Properties contains the output of the Get-ADUser command.

Whilst this function performs as expected, it is not particularly efficient and takes over a second to check a single user which consequently means processing several hundred users takes several hours.

Does anyone have any suggestions on how to improve or fine-tune it?


texts:
I would like to know if I'm writing a plugin for jquery correctly. I followed the official guide and also added some tweaks that I've found from various sources over time.

While this works perfectly, I don't know if I'm doing something wrong.

This is the sample:

(function($)
{
    var plugin = "my_plugin_name";
    var methods = {
        init : function(user_settings)
        {
            return this.each(function(index)
            {
                if(!$(this).hasClass("plugin_class"))
                {
                    $(this).addClass("plugin_class");

                    var $this = $(this);
                    var data = $this.data(plugin);

                    if(!data)
                    {
                        var default_settings = {
                            optionA: "abc",
                            optionB: 123,
                            optionB: true
                        };

                        if(user_settings)
                        {
                            $.extend(true, default_settings, user_settings);
                        }

                        $this.data(plugin,
                        {
                            "settings": default_settings
                        });
                    }

                    privateMethod($this);
                }
           });
        },
        exposedMethodX : function(value) //$(selector).my_plugin_name("exposedMethodX", true)
        {
            console.log(value)
        }
    };

    $.fn[plugin] = function(method)
    {
        if(methods[method])
        {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if(typeof method === "object" || !method)
        {
            return methods.init.apply(this, arguments);
        }
        else
        {
            alert("Method " +  method + " does not exist");
        }
    };

    function privateMethod(obj)
    {
        console.log(obj.data(plugin).settings);
    }
})(jQuery);


texts:
This question is similar to Project Euler #48 but constraints are different:

$$N < 2000000$$

Just in case the link is unavailable, here is the problem statement:

We've to print

$$\left( \sum_{i=1}^N i^i \right) \mod 10^{10}$$

I've tried the following, but I need something faster than that, because the execution time limit is 2s, and this program can only compute values until \$ N=30000\$ (approx) in the given time limit.

#include <iostream>
using namespace std;

#define Mod 10000000000

int main()
{
    int N;
    cin>>N;
    long long Temp,Sum=0;
    for( int ii=1 ; ii<=N ; ii++ )
    {
        if(ii%10==0)
        {
            continue;
        }
        Temp=1;
        for( int jj=1 ; jj<=ii ; jj++ )
        {
            Temp*=ii;
            Temp=Temp%Mod;
        }
        Sum+=Temp;
        Sum=Sum%Mod;
    }
    cout<<Sum;
    return 0;
}

I've added

if(N%10==0)
{
    continue;
}

because numbers of form $$ (k*10)^{k*10}=k^{k*10}*10^{k*10}=k^{k*10}*10^{k}*10^{10} $$ are not at all going to contribute to the answer.

Note: code is compiled using g++ 4.8.2, C++11 mode


texts:
I just started coding programs with python. As a challenge I wanted to program something to print out the Fibonacci Numbers. It looks like I've done what I wanted to do (I checked the first few numbers) and because I just started coding, I obviously don't know if this is a legitimate code and somebody would code it like that. Keep in mind that I have only done some basic lessons in python so I just want to get some feedback and advice for better code.

def spiral(sequence):
    numbers = []
    for i in sequence:
        numbers.append(0)
        if i == 0 or i == 1:
            numbers[i] = 1
            continue
        numbers[i] = numbers[i-1] + numbers[i-2]
    return numbers
times = range(int(input("How many times do you want to go through? ")))
fibonacci = spiral(times)
print(fibonacci)


texts: R function to generate predictions from ratings

texts:
I am trying to improve the run time of a program I wrote in R. Generally, what I am doing is feeding a function a data frame of values and generating a prediction off of operations on specific columns. The function is a custom function that is being used with sapply (code below). What I'm doing is much too large to provide any meaningful example, so instead I will try to describe the inputs to the process. I know this will restrict how helpful answers can be, but I am interested in any ideas for optimizing the time it takes me to compute a prediction. Currently it is taking me about 10 seconds to generate one prediction (running the sapply for one line of a dataframe).

mean_rating <- function(df){
  user<-df$user
  movie<-df$movie
  u_row<-which(U_lookup == user)[1]
  m_row<-which(M_lookup==movie)[1]

  knn_match<- knn_txt[u_row,1:100]

  knn_match1<-as.numeric(unlist(knn_match))

  dfm_test<- dfm[knn_match1,]

  dfm_mov<- dfm_test[,m_row] # row number from DFM associated with the query_movie
  C<-mean(dfm_mov)

}

test<-sapply(1:nrow(probe_test),function(x) mean_rating(probe_test[x,]))

Inputs: dfm is my main data matrix, users in the rows and movies in the columns. Very sparse.

> str(dfm)
Formal class 'dgTMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:99072112] 378 1137 1755 1893 2359 3156 3423 4380 5103 6762 ...
  ..@ j       : int [1:99072112] 0 0 0 0 0 0 0 0 0 0 ...
  ..@ Dim     : int [1:2] 480189 17770
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:99072112] 4 5 4 1 4 5 4 5 3 3 ...
  ..@ factors : list()

probe_test is my test set, the set I'm trying to predict for. The actual probe test contains approximately 1.4 million rows but I am trying it on a subset first to optimize the time. It is being fed into my function.

> str(probe_test)
'data.frame':   6 obs. of  6 variables:
 $ X          : int  1 2 3 4 5 6
 $ movie      : int  1 1 1 1 1 1
 $ user       : int  1027056 1059319 1149588 1283744 1394012 1406595
 $ Rating     : int  3 3 4 3 5 4
 $ Rating_Date: Factor w/ 1929 levels "2000-01-06","2000-01-08",..: 1901 1847 1911 1312 1917 1803
 $ Indicator  : int  1 1 1 1 1 1

U_lookup is the lookup I use to convert between user id and the line of the matrix a user is in since we lose user id's when they are converted to a sparse matrix.

> str(U_lookup)
'data.frame':   480189 obs. of  1 variable:
 $ x: int  10 100000 1000004 1000027 1000033 1000035 1000038 1000051 1000053 1000057 ...

M_lookup is the lookup I use to convert between movie id and the column of a matrix a movie is in for similar reasons as above.

> str(M_lookup)
'data.frame':   17770 obs. of  1 variable:
 $ x: int  1 10 100 1000 10000 10001 10002 10003 10004 10005 ...

knn_text contains the 100 nearest neighbors for all the lines of dfm

> str(knn_txt)
'data.frame':   480189 obs. of  200 variables:

Does anyone have suggestions on how I could improve performance within R? Does anyone have other language suggestions? I am slightly familiar with Python so I've been looking into that one, but if anyone has specific tips on redoing this in Python I would be grateful as I'm very inexperienced with it.


texts: Printing all the permutations of a string in alphabetical order

texts:
It is a code eval challenge question https://www.codeeval.com/open_challenges/14/.
My answer was accepted, and I modified my code again to improve it. Please let me know is it possible to improve it more.

#include <iostream>
#include<fstream>
#include<algorithm>
#include<string>

void create_permute( std::string &record )
{
    if( !record.empty() )
    {
        std::sort( record.begin(), record.end() );
        bool flag=0;
        do{
            if( flag )
            {
                std::cout<<",";
            }
            flag = 1;
            std::cout << record;
        } while( std::next_permutation( record.begin(), record.end() ) );
        std::cout << "\n";
    }
}
void readInputFile( std::string filename )
{

    std::ifstream infile;
    infile.open( filename );
    std::string record;
    while( std::getline( infile,record ) )
    {
       create_permute( record );
    }
}

int main( int argc, char* argv[] )
{
    if( argc < 2 )
    {
        std::cout << "usage: filesize filename" << "\n";
        exit( 0 );
    }
    std::ios_base::sync_with_stdio( false );
    readInputFile( argv[ 1 ] );

    return 0;
}


texts: Getting last or return a default value in a Seq[Either[A, B]]

texts:
val y: Seq[Either[String, Int]]

case class Response(value: String)

val notFound = Response("Not Found")
val found    = Response("Found")

val response: Response = y.lastOption
    .map(_.fold(_ => notFound, _ => found))
    .getOrElse(notFound)

I am getting a list of Eithers. I want to get the last Either in the list. I then want to get Rightvalue. If the list is empty or the Either is  Left, I want to return a default value. The code does this but can this be done more elegantly and clearer in Scala with perhaps cats? I don't use scalaz.


texts: Remove duplicates from string without additional buffer

texts:
I completed an exercise from the Cracking the Coding Interview:

  Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.

  Follow-up: Write the test cases for this method.

I would like to ask whether my solution for the question is good enough, because the solution given in the book doesn't seem to work correctly.

import java.util.Arrays;

public class duplicateString{

    public static void rduplication(char [] word){
        if(word == null) return;
        int len = word.length;
        if(len<2) return;
        int count=0;
        for(int i =0;i<word.length;i++){
            for(int j=0;j<word.length;j++){
                if(word[i] == word[j]){
                    count = count + 1;
                    System.out.println(count);
                }
                if(word[i] == word[j] && count > 1){
                    word[j] =0;

                }

            }
            count = 0;
        }
        System.out.println(Arrays.toString(word));
    }

    public static void main(String []  args){
        String word = "ababab";
        rduplication(word.toCharArray());
    }
}


texts: Counting single degree vertex removal rounds (from a graph)

texts:
Problem:
In this problem I had to remove all vertices with degree one from a given graph in rounds and count how many rounds are required to remove all possible vertices with degree 1.
e.g. 1-2-3-4 Remove 1 and 4 in round 1. Remove 2 and 3 in round 2.
e.g. we can't Remove any vertex here. Total 0 rounds.
1---2
 \ /
  3

So here is how I solve:

Logic:

Create an adjaceny list adj.
Create a degree sets dl with dl[i] containing all vertices with degree i.
Remove all vertices of degree one and remove their adjacency list. I do not update the degree or adjacency list of it's neighbors upon removal but only after the round has completed. For this I use a map/dictionary dec such that dec[x][0] are the neighbors of the single degree vertex x whose adjacency list and degree needs to be updated while dec[x][1] is the amount of degree reduction.
If we have non-zero single degree vertices then I first pop() them and update values of their dec value.
Finally for each vertex who needs to be updated, I move it from one degree set to another and update it's adjacency list.
Finally I increase round count and then I print it.

Note: Sometimes the single degree vertices may appear in pair like 1-2 then while pop(ping) it has already been removed so no need to update in last.

Code:
Please see Codeforces 192B for input description which is basically n(number of nodes), m(number of edges) and next m lines the edges.
from collections import defaultdict

n, m = map(int, input().split())
E = [tuple(map(int, input().split())) for _ in range(m)]
adj = defaultdict(set)
for e in E:
    adj[e[0]].add(e[1])
    adj[e[1]].add(e[0])
dl = defaultdict(set)
for v in adj:
    dl[len(adj[v])].add(v)
if len(dl[1]) == 0:
    print('0')
else:
    cnt = 0
    while len(dl[1]) > 0:
        dec = defaultdict(lambda: [list(), 0])
        while len(dl[1]) > 0:
            v = dl[1].pop()
            for v2 in adj[v]:
                dec[v2][0].append(v)
                dec[v2][1] += 1
            del adj[v]
        for v2 in dec:
            if v2 in dl[len(adj[v2])]:
                dl[len(adj[v2])].remove(v2)
                dl[len(adj[v2]) - dec[v2][1]].add(v2)
                for x in dec[v2][0]:
                    adj[v2].remove(x)
        cnt += 1
    print(cnt)

Questions:

I have switched from a different language so my methods may not be very 'Pythonic' or exploiting advantages of 'Python' over others. Can you help?
Other improvements, if any?


texts:
I've created a two-player number guessing game in Haskell. My main objective was to practice dealing with "state" in a purely functional language (such as player scores, whose turn it is, etc.).
Here are the rules:
Gameplay:
Two players will take turns guessing a random number between 1 and 10. Answers will be typed into the command line.
Scoring:

If a player guesses the number correctly, they will be awarded 5 points
If a player is within two (inclusive) from the answer, the player will be awarded 3 points.
If a player is within three (inclusive) from the answer, they will be awarded 1 point.
If a player is 7 or more points off, they will lose a point. The score may not be negative.
All other offsets will result in zero points.
The game will continue until the one of the players reaches 10 points.

Caveats:

This is was not designed to be an exercise in enjoyable game design -- obviously the optimal solution is to always choose five, which doesn't make for a lot of excitement. :D
I am aware that Control.Monad.State exists, but I want to practice tracking state without it.
I know that the "mutual recursion" is difficult to follow. I would love some suggestions for getting rid of that which do not involve nesting if statements.

import Data.Char
import System.Random

main = do
    stdGen <- getStdGen
    play 0 0 P1 stdGen

play :: Int -> Int -> Player -> StdGen -> IO ()
play p1Score p2Score player stdGen
    | p1Score < 10 && p2Score < 10 = continueGame p1Score p2Score player stdGen
    | otherwise = putStrLn $ show (determineWinner p1Score p2Score) ++ " wins!"

continueGame :: Int -> Int -> Player -> StdGen -> IO ()
continueGame p1Score p2Score player stdGen = do
    putStr $ show player ++ "'s turn. Pick a number between 1 and 10: "
    chosenNumber <- getLine
    if isInteger chosenNumber
        then do
            let (randomNumber, newGen) = randomR (1, 10) stdGen :: (Int, StdGen)
            putStrLn $ "The answer is " ++ show randomNumber

            let pointsEarned = calcPointsEarned randomNumber (read chosenNumber)
            let newP1Score = min (max (p1Score + calcPointsEarnedForPlayer player P1 pointsEarned) 0) 10
            let newP2Score = min (max (p2Score + calcPointsEarnedForPlayer player P2 pointsEarned) 0) 10

            putStrLn $ "P1 Score: " ++ show newP1Score
            putStrLn $ "P2 Score: " ++ show newP2Score

            play newP1Score newP2Score (changeTurn player) newGen
        else do
            putStrLn "The input must be an integer"
            play p1Score p2Score player stdGen

data Player = P1 | P2 deriving (Show, Eq)

isInteger :: String -> Bool
isInteger = and . map isNumber

changeTurn :: Player -> Player
changeTurn player
    | player == P1 = P2
    | otherwise = P1

calcPointsEarned :: Int -> Int -> Int
calcPointsEarned actualAnswer chosenAnswer
    | offset == 0 = 5
    | offset <= 2 = 3
    | offset <= 3 = 1
    | offset >= 7 = (-1)
    | otherwise = 0
    where offset = abs $ chosenAnswer - actualAnswer

calcPointsEarnedForPlayer :: Player -> Player -> Int -> Int
calcPointsEarnedForPlayer actualTurn player pointsEarned
    | actualTurn == player = pointsEarned
    | otherwise = 0

determineWinner :: Int -> Int -> Player
determineWinner p1Score p2Score
    | p1Score > p2Score = P1
    | otherwise = P2
```


texts: Laravel time-punching database structure

texts:
I am trying to build a database structure for a time punching system. What I'm trying to figure out is if what I have is the ideal structure, or if something else exists that I'm overlooking.

I want the records to be connected in some way so that I can pull out all of the records into a table and display them by date and time.

Here is my migration table:

Schema::create('punches', function(Blueprint $t)
        {
            $t->increments('id');
            $t->integer('user_id');
            $t->dateTime('time');
            $t->boolean('in_punch');
            $t->timestamps();
        });

I want to be able to have the in punch and the out punch connected, so I don't feel like this is the best way to go about doing it, but I can't come up with anything better. Can you?


texts:
Suppose rectangles are parallel to x-axis/y-axis. Check if two rectangles overlap or not and if they do, output the overlap area.

Here is my code and I track min/max x-coordinate and min/max y-coordinate for each rectangle. Using Python 2.7.

Any comments on code bugs, code style and performance improvements in terms of algorithm time complexity are appreciated.

class Rectangle:
    def __init__(self, min_x, max_x, min_y, max_y):
        self.min_x = min_x
        self.max_x = max_x
        self.min_y = min_y
        self.max_y = max_y

    def is_intersect(self, other):
        if self.min_x > other.max_x or self.max_x < other.min_x:
            return False
        if self.min_y > other.max_y or self.max_y < other.min_y:
            return False
        return True

    def get_insersec_region(self, other):
        if not self.is_intersect(other):
            return None
        min_x = max(self.min_x, other.min_x)
        max_x = min(self.max_x, other.max_x)
        min_y = max(self.min_y, other.min_y)
        max_y = min(self.max_y, other.max_y)

        return Rectangle(min_x, max_x, min_y, max_y)

    def __str__(self):
        return str(self.min_x) + '\t' + str(self.max_x) + '\t' + str(self.min_y) + '\t' + str(self.max_y)

if __name__ == "__main__":
    r1 = Rectangle(0,10,0,10)
    r2 = Rectangle(5,15,5,15)
    print r1.is_intersect(r2)
    print r1.get_insersec_region(r2)


texts:
This script implements a command line level trashcan system.

Designed to work around rm doing the bits needed to implement a trashcan system at command line level. Any user flags hands the request over to rm. This means rm -f will still delete a file with no recovery. Prevents execution by root as too many dependencies at superuser level. Deployment by adding aliases rm=trash and rmoops=untrash. Only implemented on files, does not cater for directories.

Appreciate any and all suggestions from formatting, expansion of the idea to glaring issues. Looking for an experienced eye to pin point potential issues.

/usr/local/bin/trash

#!/bin/bash
#
# Trashcan script
# alias rm=trash
#

error() {
  echo $1
  exit 1
}

bypass() {
  exec rm $*
}

file="$1"
trash=~/.trash
keep=5

## bypass scenarios
# root user
[ "$(id -u)" = "0" ] && error "Please do not run as root user."
# special cases
case $file in
  -*) bypass $* ;;
  $trash/* ) bypass $* ;;
esac
# only single filename supported
[ $# -gt 1 ] && bypass $*
# can we access the file?
[ -f "$file" ] || error "File not specified."

# move existing versions out of the way
ls $trash/$file.version.* 2>/dev/null | tac | while read name; do
  version=$((${name##*.}+1))
  # keep the only the last number of versions
  if [ $version -gt $keep ]; then
    rm $name || error "Unable to remove file $name."
  else
    mv $name $trash/$file.version.$version || error "Unable to move version $version."
  fi
done

# move file into trash (volume friendly)
cp --preserve $file $trash/$file.version.1 || error "Unable to trash your file."
rm -f $file || error "Unable to cleanup the file."

exit 0

/usr/local/bin/untrash

#!/bin/bash
#
# Restore files from Trashcan
# alias rmoops=untrash
#

error() {
  echo $1
  exit 1
}

file="$1"
trash=~/.trash
keep=5

## bypass scenarios
# root user
[ "$(id -u)" = "0" ] && error "Please do not run as root user."

# any flags so rm -rf actually does it
case $file in
  -*) error "Flags are not supported." ;;
  $trash/*) error "You cant restore from trash directly." ;;
esac

# only single filename supported
[ $# -ne 1 ] && error "File not specified."

version=0
# find latest version
for name in `ls $trash/$file.version.* 2>/dev/null | tac`
do
  version=${name##*.}
  break
done
[ $version -gt 0 ] || error "Sorry I cannot find your file in the trash."

echo "I have versions 1 to $version, 1 being the most recent."
echo -n "Which would you like to restore? [1]:"
read user
[ -n "$user" ] || user=1

# check we have the actual file
[ -f $trash/$file.version.$user ] || error "Sorry I cannot find that version."
# move existing file out of the way
[ -f $file ] && mv $file $file.old
# restore the file
cp $trash/$file.version.$user $file || error "Unable to restore file."
echo Version $user restored.

exit 0


texts: Chaining async functions of a module without Promises

texts:
I know that promises are the current recommended way to go for asynchronous chaining but, every time I use promises, I don't feel as comfortable as I wish. All that "then" statements and managing scopes always look a bit strange for me.
So, this is the way I've been creating modules and chaining functions. I use a simple queue to chain the calls.

In my opinion, the code is more understandable, you don't need "then" statements, you can explicit change context if needed. It looks easier for me.
I would like opinions and improvements suggestions, critics are welcome. Why should I use promise over this?

"use strict";

var pause = function(ms, callback) {
    setTimeout(function() {
        callback();
    }, ms);
};

var temp = {
    prop1: 'This is the temp prop1 property!'
};

var P = function() {
    let queue = [];
    let SCOPE = this;

    this.prop1 = 'Property';

    this.displayProperty = function(property) {
        var me = this;
        queue.push(function() {
            console.log(this[property]);
            me.resolve();
        });
        return this;
    }

    this.setProperty = function(property, data) {
        var me = this;
        queue.push(function() {
            this[property] = data;
            me.resolve();
        });
        return this;
    }

    this.asyncDisplayProperty = function(property, data) {
        var me = this;
        queue.push(function() {
            var scope = this;
            pause(3000, function() {
                console.log(scope[property]);
                me.resolve();
            });
        });
        return this;
    }

    this.resolve = function() {
        let fn = queue.shift();
        if (fn) {
            fn.apply(SCOPE, arguments);
        }
    }

    this.bind = function(s) {
        queue.push(() => {
            SCOPE = s;
            this.resolve();
        });
        return this;
    }

}

var foo = new P();

foo
    .displayProperty('prop1') //"Property"
    .asyncDisplayProperty('prop1') //"Property" after 3s
    .setProperty('prop1', 'changed property')
    .displayProperty('prop1') //"changed property"
    .bind(temp) //change the context
    .asyncDisplayProperty('prop1') //"This is the temp prop1 property!" after 3s
    .setProperty('prop1', 'changed temp property')
    .displayProperty('prop1') //"changed temp property"
    .resolve();

Just for the record, this is the promise version I've been using:

"use strict";

var temp = {
    prop1: 'This is the temp prop1 property!'
};

var P = function() {
    let CONTEXT = this;

    this.prop1 = 'Property';

    this.displayProperty = function(property) {
        var me = CONTEXT;
        return new Promise((resolve, reject) => {
            console.log(me[property]);
            resolve();
        });
    }

    this.setProperty = function(property, data) {
        var me = CONTEXT;
        return new Promise((resolve, reject) => {
            me[property] = data;
            resolve();
        });
    }

    this.asyncDisplayProperty = function(property, data) {
        var me = CONTEXT;
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(me[property]);
                resolve();
            }, 3000)
        });
    }

    this.bind = function(s) {
        return new Promise((resolve, reject) => {
            CONTEXT = s;
            resolve();
        });
    }
};

var foo = new P();

Promise.resolve()
    .then(() => foo.asyncDisplayProperty('prop1'))
    .then(() => foo.asyncDisplayProperty('prop1'))
    .then(() => foo.setProperty('prop1', 'changed property'))
    .then(() => foo.displayProperty('prop1'))
    .then(() => foo.asyncDisplayProperty('prop1'))
    .then(() => foo.bind(temp))
    .then(() => foo.displayProperty('prop1'))
    .then(() => foo.setProperty('prop1', 'changed temp property'))
    .then(() => foo.displayProperty('prop1'));


texts:
Please review my Secret Santa random pair allocator written in JavaScript. Random pairs will be generated every time you run the code.

Input data is hardcoded for now (line # 41).

I would love to know if you have any suggestions on improving the algorithm or any other feedback that you might have.

function getSecretSantaRandomPairs(inputArray){

  if(inputArray.length % 2 !== 0){ // array length should be even
    return;
  }

  var allocatedPairs = [], // variables for housekeeping
      randomNumber,
      randomPerson;

  while(inputArray.length !== 0){ // process the inputArray
    randomNumber = getRandomInteger(0, inputArray.length-1); // get a random number
    randomPerson = inputArray[randomNumber]; // the corresponding random person from the given list
    allocatedPairs = allocate(allocatedPairs, randomPerson); // allocate the randomPerson and update the array to be returned - allocatedPairs
    inputArray.splice(randomNumber, 1); // remove from the inputArray so that the person is not allocated again
  }

  return allocatedPairs;

}

function allocate(allocatedPairs, candidate){ // in the allocatedPairs array, mantain the pairs as objects, example: {person1: 'Peter', person2: 'Jordan'}
  // first allocate as 'person1' in the object
  if(allocatedPairs.length === 0 || (allocatedPairs[allocatedPairs.length-1].hasOwnProperty('person1') && allocatedPairs[allocatedPairs.length-1].hasOwnProperty('person2') )){ // allocatedPairs is either an empty array or the object at the bottom of the allocatedPairs array had both person1 and person2
    allocatedPairs.push({person1: candidate});
  } else{ // otherwise 'person2'
    allocatedPairs[allocatedPairs.length-1].person2 = candidate;
  }

  return allocatedPairs;
}

// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInteger(min, max) {
  return Math.round(Math.random() * (max - min)) + min;
}

// lets test this out

var newList = getSecretSantaRandomPairs(['John', 'Amy', 'Harry', 'Aliston', 'Jeff', 'Chris', 'Kurt', 'Jessica']);

if(newList !== undefined){
  console.log('Secret Santa Random Pairs: ', newList);

  var pairsUL = document.getElementById('pairs'),
      pairsLI,
      textLI;

  // iterate over the newList to create DOM elements
  newList.forEach(function(currentValue, index){
    pairsLI = document.createElement('li'); // the LI element
    textLI = newList[index].person1 + ' and ' + newList[index].person2; // the text for the LI
    pairsLI.appendChild(document.createTextNode(textLI)); // add text to the LI
    pairsUL.appendChild(pairsLI); // append the LI to the UL
  });
} else {
  document.body.innerHTML = '
Please input an even number of people!
'; // source: http://stackoverflow.com/a/5419800/586051
}

Equivalent jsFiddle


texts:
In my project the value slider must be sometimes set. Then no notification may be generated because otherwise the new value will written in database again. I have this solved in the following way. Is there a better solution?

package application;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class SliderApp extends Application {
    final Slider slider = new Slider(0d, 10d, 0d);
    final Label label = new Label(String.valueOf(slider.getValue()));
    final Button button = new Button("Set to 5");

    final ChangeListener<Number> slListener = (ChangeListener<Number>) (obs, oldNo, newNo) -> {
        label.setText(String.valueOf(newNo));
    };

    @Override
    public void start(final Stage primaryStage) {
        try {
            final BorderPane root = new BorderPane();
            root.setCenter(slider);
            root.setBottom(button);
            root.setRight(label);

            slider.valueProperty().addListener(slListener);
            button.setOnAction(event -> {
                setSlider(5d);
            });

            primaryStage.setScene(new Scene(root));
            primaryStage.show();
        } catch (final Exception e) {
            e.printStackTrace();
        }
   }

    private synchronized void setSlider(final double value) {
        slider.valueProperty().removeListener(slListener);
        slider.setValue(value);
        slider.valueProperty().addListener(slListener);
    }

    public static void main(final String[] args) {
        launch(args);
    }
}

Thanking you in anticipation
Misi


texts:
This is not homework. I am trying to learn OOD principles and design patterns myself.

Suppose I have a problem like this:

  A book-shop buys and sells two types of books:

  Non-technical {Title, Author, Price}
  Technical {Title, Author, Price, CD}

  Also, customer gets a CD when he buys a Technical book. A CD object is
  defined as, CD {Title, Price}.

  A Non-technical book's price will be only the price of the book. A
  Technical book's price will be the sum of the price of the book and
  the CD.

  Create a C# program to show the following info:

  Total number of book Bought & Price: XXX & XXX.XX
  Total number of book Sold & Price: XXX & XXX.XX
  Total Technical Book Sold & Price: XXX & XXX.XX
  Total Non-technical Book sold & Price: XXX & XXX.XX

I have designed the program like this:

abstract class Publication
{
    public virtual string Title { get; set; }
    public virtual double Price { get; set; }
}

class CD : Publication
{
}

abstract class Book : Publication
{
    public virtual string Author { get; set; }
}

class TechnicalBook : Book
{
    public CD Cd { get; set; }
    public override double Price
    {
        get
        {
            return (base.Price + Cd.Price);
        }
    }
}

class NonTechnicalbook : Book
{
}

abstract class Shop
{
    private IDictionary<string, Book> boughtDictionary;
    private IDictionary<string, Book> soldDictionary;

    public Shop()
    {
        boughtDictionary = new Dictionary<string, Book>();
        soldDictionary = new Dictionary<string, Book>();
    }

    public virtual void Buy(Book item)
    {
        boughtDictionary.Add(item.Title, item);
    }

    public virtual void Sell(string title)
    {
        Book book = boughtDictionary[title];
        boughtDictionary.Remove(book.Title);
        soldDictionary.Add(book.Title, book);
    }

    public virtual int GetBoughtBookCount()
    {
        return boughtDictionary.Count;
    }

    public virtual double GetBoughtBookPrice()
    {
        double price = 0.0;

        foreach (string title in boughtDictionary.Keys)
        {
            price = price + boughtDictionary[title].Price;
        }
    }

    public virtual int GetSoldBookCount()
    {
        return boughtDictionary.Count;
    }

    public virtual double GetSoldBookPrice()
    {
        double price = 0.0;

        foreach (string title in soldDictionary.Keys)
        {
            price = price + soldDictionary[title].Price;
        }
    }

    public virtual double GetTotalBookCount()
    {
        return this.GetBoughtBookCount() + this.GetSoldBookCount();
    }

    public virtual double GetTotalBookPrice()
    {
        return this.GetBoughtBookPrice() + this.GetSoldBookPrice();
    }

    public virtual void Show()
    {
        Console.WriteLine("Total number of books Bought & Price: ", this.GetTotalBookCount() + " & " + this.GetTotalBookPrice());
        Console.WriteLine("Total number of books Sold & Price: ", this.GetSoldBookCount() + " & " + this.GetSoldBookPrice());
    }
}

Does this design conform to the Open-Closed principle? Now I am unable to understand how to separate Technical and Non-technical books at this point.


texts: Trying to create a directory if it doesn't exist

texts:
I am trying to create a directory, but I have to check whether /usr is present initially, later /usr/local is present and so on, is this an elegant way of writing it?

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

int main ()
{
  char str[] ="/usr/local/mnt/";
  char path[40] = {0};
  char temp[40] = {0};
  char *slash = "/";
  char *pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str,"/");
  printf (" First one %s\n",pch);
  while (pch != NULL)
  {
    snprintf(path, sizeof(path), "%s%s%s", temp, slash, pch);
    strncpy(temp, path, 40);
    if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)){
        printf("Directory path already exists\n");
    }
    else{
          if(mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0){
            printf("directory creation error");
            return -1;
        }
    }
    pch = strtok (NULL, "/");

  }
  return 0;
}


texts:
FizzBuzz was fun, and I got great feedback and learned a few things (which I hope I put in practice here), but only scratched the surface. I wanted to explore the LOLCODE language a bit more, so I implemented a little rock-paper-scissors, to play with functions, parameters, return values.. and user input.
Unfortunately I haven't figured out how to get compileonline to take more than a single value through STDIN, so I dropped the idea of making a GAEMLOOPZ and only made it a single round.
Also AFAICT there's no way of generating random numbers in LOLCODE (specs), so the LOLCAT always wins - it even has a seekrit move for invalid inputs!
HAI 1.2

  I HAS A CHEEZ ITZ "CHEEZ"       BTW "ROCK"
  I HAS A BURGR ITZ "BURGR"       BTW "PAPER"
  I HAS A WAFLZ ITZ "WAFLZ"       BTW "SCISSORS"
  I HAS A SEEKRITMOOV ITZ "ZPOCK" BTW SHH, SEEKRIT

  HOW IZ I GETAMOOV

    VISIBLE "WHAT U PLAY?"
    VISIBLE "[C]HEEZ [B]URGR [W]AFLZ"

    I HAS A MOOV
    GIMMEH MOOV

    MOOV R I IZ VALID8MOOV YR MOOV MKAY
    FOUND YR MOOV

  IF U SAY SO

  HOW IZ I VALID8MOOV YR MOOV

    MOOV, WTF?
      OMG "C", OMG "c"
        MOOV R CHEEZ
        GTFO

      OMG "B", OMG "b"
        MOOV R BURGR
        GTFO

      OMG "W", OMG "w"
        MOOV R WAFLZ
        GTFO

      OMGWTF
        ANY OF BOTH SAEM MOOV AN "ZPOCK" AN BOTH SAEM MOOV AN "zpock" MKAY
        O RLY?
          YA RLY, MOOV R SEEKRITMOOV
          NO WAI
            MOOV R SMOOSH "... WUTS " AN MOOV AN " ANYWAI" MKAY
        OIC

    OIC

    FOUND YR MOOV

  IF U SAY SO

  HOW IZ I PIKAMOOV YR MOOV

    I HAS A ULTIMAETMOOV

    MOOV, WTF?
      OMG "CHEEZ" BTW must be a constant value :(
        ULTIMAETMOOV R BURGR
        GTFO

      OMG "BURGR" BTW must be a constant value :(
        ULTIMAETMOOV R WAFLZ
        GTFO

      OMG "WAFLZ" BTW must be a constant value :(
        ULTIMAETMOOV R CHEEZ
        GTFO

      OMG "ZPOCK" BTW must be a constant value :(
        ULTIMAETMOOV R "Y U CHEAT? I"
        GTFO

      OMGWTF
        ULTIMAETMOOV R SEEKRITMOOV

    OIC

    FOUND YR ULTIMAETMOOV

  IF U SAY SO

  HOW IZ I WINTEHGAEM YR MOOV AN YR ULTIMAETMOOV

    VISIBLE SMOOSH "Y U PLAY " AN MOOV MKAY
    VISIBLE SMOOSH "MAH " AN ULTIMAETMOOV AN " WINZ LOL" MKAY

  IF U SAY SO

  OBTW
    was going to make a GAEMLOOP,
    but stupidly I can't seem to figure out
    how to pass multiple values to STDIN with this "IDE"...
    so this program will only run a single round.
  TLDR

  HOW IZ I PLAYAMOOV

    I HAS A MOOV
    MOOV R I IZ GETAMOOV MKAY

    I HAS A ULTIMAETMOOV
    ULTIMAETMOOV R I IZ PIKAMOOV YR MOOV MKAY

    I IZ WINTEHGAEM YR MOOV AN YR ULTIMAETMOOV MKAY

  IF U SAY SO

  VISIBLE "CHEEZ-BURGR-WAFLZ:)"
  I IZ PLAYAMOOV MKAY

KTHXBYE

Outputs
Input: c or C

CHEEZ-BURGR-WAFLZ

WHAT U PLAY?
[C]HEEZ [B]URGR [W]AFLZ
Y U PLAY CHEEZ
MAH BURGR WINZ LOL

Input: b or B

CHEEZ-BURGR-WAFLZ

WHAT U PLAY?
[C]HEEZ [B]URGR [W]AFLZ
Y U PLAY BURGR
MAH WAFLZ WINZ LOL

Input: w or W

CHEEZ-BURGR-WAFLZ

WHAT U PLAY?
[C]HEEZ [B]URGR [W]AFLZ
Y U PLAY WAFLZ
MAH CHEEZ WINZ LOL

Input: zzz ..or pretty much anything else:

CHEEZ-BURGR-WAFLZ

WHAT U PLAY?
[C]HEEZ [B]URGR [W]AFLZ
Y U PLAY ... WUTS zzz ANYWAI
MAH ZPOCK WINZ LOL

Input: zpock or ZPOCK

CHEEZ-BURGR-WAFLZ

WHAT U PLAY?
[C]HEEZ [B]URGR [W]AFLZ
Y U PLAY ZPOCK
MAH Y U CHEAT? I WINZ LOL

I don't like that I'm hard-coding the strings in the WTF (switch) block in VALID8MOOV, but I don't think it's possible to extract just the first letter of a YARN (string)... or is it? Also there doesn't seem to be a way of defining compile-time constants, so I had to put literal strings in PIKAMOOV as well.


texts:
Given a string, assuming the string is numbers only, rearrange the string to that it is the greatest possible number.

Below is my solution to the problem above. I'd like feedback mainly on the algorithm, as I wrote this up very quickly. I used comprehension syntax to find the largest num, which I'm trying to use more. Any other feedback is appreciated as well.

def largest_number(string: str) -> str:
    """
    Given a string, organize the numbers such as the
    rearrangement is now the largest possible number
    """
    string = list(string)
    largest = ""
    for _ in string:
        largest_num = str(max([int(num) for num in string]))
        largest += largest_num
        string[string.index(largest_num)] = -1
    return largest

if __name__ == '__main__':

    # Test Cases #

    assert largest_number("12345") == "54321"
    assert largest_number("4689123") == "9864321"
    assert largest_number("9") == "9"
    assert largest_number("1923") == "9321"


texts: Is there a better, more object oriented way to write this Finder method?

texts:
I have several lists of objects which are stored in different locations, based on what they are and who needs them - the system, or the user, for example. There are times where I am only given an ID and need to find the name, type, or description, but I would like a very succinct, efficient way to do so. Since I'm also trying to improve the quality of my code, I want to ensure I'm doing things the best way possible.

Is there a better way to do this? I first was passing in the object and using instanceof, but I thought this was a better way.

/**
 * This method searches all known types / locations to find the object name based on ID.
 * @param whatClass The type of the object you are searching for
 * @param id ID of the object for which you are searching.
 * @return The string name or type. Returns null if no match is found.
 */
public static <T> String nameByID(Class<?> whatClass, int id) {
    if (whatClass == ProjectCode.class) {
        for (ProjectCode c : User.getInstance().getProjects()) {
            if (c.getProjCdId() == id) {
                return c.getProjNm();
            }
        }
    } else if (whatClass == TransactionType.class) {
        for (TransactionType type : Session.getInstance().getTransactionTypes()) {
            if (type.getTransactionTypeId() == id) {
                return type.getTransactionNm();
            }
        }
    } else if (whatClass == CurrencyType.class) {
        for (CurrencyType currencyType : Session.getInstance().getCurrencies()) {
            if (currencyType.getCurrencyTypeId() == id) {
                return currencyType.getCurrencyTypeNm();
            }
        }
    }

    // no matches found
    return null;
}


texts: Detecting two keys pressed in quick succession

texts:
My computer has been having this issue where when I press a key, two key presses get registered. The goal of this program is to detect the time delta between the two keys so that I can set an effective debounce threshold. I also thought that it would be a good idea to try out Rust, so here it is:

use std::{mem, ptr, env, process, io};
use std::io::Read;
use std::io::Write;
use std::fs::File;
use std::collections::HashMap;

const EV_SYN: u16 = 0x00;
const EV_KEY: u16 = 0x01;

#[repr(C)]
struct LinuxTimeval {
    tv_sec: isize,
    tv_usec: isize,
}

impl LinuxTimeval {
    fn to_microseconds(&self) -> u64 {
        self.tv_sec as u64 * 1000000u64 + self.tv_usec as u64
    }
}

#[repr(C)]
struct LinuxInputEvent {
    time: LinuxTimeval,
    type_: u16,
    code: u16,
    value: i32,
}

fn read_struct_from_file<T: Sized>(file: &mut File) -> T {
    let mut buf = vec![0u8; mem::size_of::<T>()];
    match file.read(&mut buf) {
        Ok(sz) => assert!(sz == buf.len()),
        Err(err) => panic!("Unable to read from device: {}", err),
    }
    let ptr = &buf as &[u8] as *const [u8] as *const T;
    unsafe { ptr::read(ptr) }
}

fn read_events_from_file(file: &mut File) -> Vec<LinuxInputEvent> {
    let mut vec = Vec::new();
    loop {
        let event: LinuxInputEvent = read_struct_from_file(file);
        if event.type_ == EV_SYN {
            if vec.len() > 0 {
                break;
            } else {
                continue;
            }
        } else {
            vec.push(event);
        }
    }
    vec
}

fn process_key_event(event: &LinuxInputEvent,
                     last_occurence_per_key: &mut HashMap<u16, u64>,
                     threshold: u64) {
    let key = event.code;
    let micros = event.time.to_microseconds();
    match last_occurence_per_key.get(&key) {
        None => (),
        Some(last_micros) => {
            let delta = micros - last_micros;
            if delta < threshold {
                println!("Key code {:3}: event delta: {} us",
                         key, delta);
            }
        }
    }
    last_occurence_per_key.insert(key, micros);
}

fn print_usage_and_exit(program_name: &str) {
    writeln!(&mut io::stderr(), "Usage: {} <microseconds-delta>",
             program_name).unwrap();
    process::exit(1);
}

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() != 2 { print_usage_and_exit(&args[0]); }
    let threshold: u64 = args[1].parse().unwrap_or(0);
    if threshold == 0 { print_usage_and_exit(&args[0]); }
    let mut file;
    match File::open("/dev/input/by-path/platform-i8042-serio-0-event-kbd") {
        Ok(f) => { file = f },
        Err(err) => panic!("Unable to open file: {}", err),
    }
    let mut last_occurence_per_key = HashMap::new();
    loop {
        match read_events_from_file(&mut file)
                .iter().find(|&event| event.type_ == EV_KEY && event.value == 1) {
            None => continue,
            Some(event) => process_key_event(event,
                                             &mut last_occurence_per_key,
                                             threshold),
        }
    }
}

Please let me know if any improvements can be made.


texts: Find the 4 best parameters of a function to have the best cumulative sum

texts:
I have a dataframe data with several columns and for each columns there are 10 years of daily data on average, something around 4000 rows then. The dataframe looks like this:
Date           A       B      C    ...
YYYY-MM-DD   123.4   56.7   89.0
YYYY-MM-DD   12.34   -5.6    NaN
...

Date is datetime64, every value is a float (positive and negative, they are real numbers), there could be NaN, there are no upside or downside boundaries.
I have this function :
def fct(data, name_a, name_b, param_a, param_b, param_c, param_d):

    df = data.loc[(data[name_a].notnull()) & (data[name_b].notnull()),[name_a, name_b]]

    df_corr = pd.DataFrame()
    df_corr[name_a] = df[name_a]
    df_corr[name_b] = df[name_b].shift(param_a)
    print(df_corr.corr().iloc[0,1])

    df['pct'] = df[name_a].pct_change()
    df['name_b_delta'] = df[name_b].shift(2+param_a)-df[name_b].shift(2+param_a+param_b)
    df['is_ok'] = df['name_b_delta'].apply(lambda x : np.sign(x+(-param_c)))

    if param_d:
        df['results'] = df['is_ok'] * (-1) * df['pct']
    else:
        df['results'] = df['is_ok'] * df['pct']

    df['cumul_results'] = df['results'].cumsum()

    return df

and currently, to optimize the cumul_results for differents pairs of name_a and name_b, I search for the best params using those nested loops :
name_a_list = ['a_dozen_of_elements_here']
name_b_list= ['25_elements_here']

df_line= []
df_index = []

for name_a in name_a_list :
    for name_b in name_b_list :
        for param_a in range(0,15):
            for param_b in range(1,15):
                for param_c in range (-2, 3, 1):
                    for param_d in [True, False]:
                        df = fct(data, name_a, name_b, param_a, param_b, param_c/1000, param_d):
                        df_index.append(f"{name_a}-{name_b}")
                        df_line.append([df['cumul_results'].iloc[-1], param_a, param_b, param_c, param_d])

results = pd.DataFrame(index=df_index, data=df_line, columns=['final result', 'param_a', 'param_b', 'param_c', 'param_d'])

It's more than 840 000 calls of the function fct and takes around 4 hours. I was wondering then if I could increase the performance of this code to reduce time. Thanks !


texts:
I would like advice if this is a good implementation of an application for maintaining information about people (first name, last name, and age).

The index.html contains an empty div and 2 templates (1 for listing people and the other for entering/editing a user):

<div id="app">
</div>

<script type="text/template" id="listTemplate">
<!-- Iterates over people and makes a table. -->
</script>

<script type="text/template" id="editTemplate">
<!-- Displays a form which if for existing user will fill the values. -->
</script>

In my starting point JS file I put into a namespace 'people.global' a bunch of things that I use throughout the application:

$(function() {

    people.global = {
        people: new people.collections.PeopleCollection()
    };

    people.global = $.extend(people.global, {
        listView: new people.views.ListView(),
        editView: new people.views.EditView(),
        router: new people.Router()
    });

    people.global.people.fetch();

    Backbone.history.start();

});

The router demonstrates the basic idea which is depending on the screen that should be shown it takes the View's el and draws it in the #app element:

var people = people || {};

people.Router = Backbone.Router.extend({

    $app: $('#app'),

    routes: {
        '': 'list',
        'edit': 'edit',
        'edit/:id': 'edit',
        'delete/:id': 'delete'
    },

    list: function() {
        this.$app.html(people.global.listView.render().el);
    },

    edit: function(id) {
        people.global.editView.setId(id);
        this.$app.html(people.global.editView.render().el);
    },

    delete: function(id) {
        var person = people.global.people.get(id);
        person.destroy();
        this.navigate('', {trigger: true, replace: true});
    }

});

Below is the view for editing/adding a person:

var people = people || {};
people.views = people.views || {};

people.views.EditView = Backbone.View.extend({

    template: _.template($('#editTemplate').html()),

    setId: function(id) {
        this.id = id;
    },

    edit: function() {
        var person;

        if (this.$("#id").val() !== '') {
            person = people.global.people.get(this.id);
            person.set({
                'first': this.$("#first").val(),
                'last': this.$("#last").val(),
                'age': this.$("#age").val()
            });

            person.save();
        } else {
            people.global.people.create({
                first: this.$('#first').val(),
                last: this.$('#last').val(),
                age: this.$('#age').val()
            });
        }

                people.global.router.navigate('', {trigger: true, replace: true});
    },

    render: function() {
        var person,
            that = this;

        if (this.id) {
            person = people.global.people.get(this.id);
            this.$el.html(this.template(person.toJSON()));
        } else {
            this.$el.html(this.template({}));
        }

        this.$('button').click(function() {
            that.edit();
        });

        return this;
    }

});

Is this a good design choice?

Is there something that can be done better?


texts: T-SQL Pbdfk2 (Rfc2898 SHA2_256) Implementation

texts:
Using my previous function as a base I've come up the following:

create function dbo.Pbkdf2 (
    @password varbinary(8000)
  , @salt varbinary(7996)
  , @iterations int = 1000
  , @derivedKeyLength int = 32
)
returns varbinary(max)
as
begin;
    declare @hmacLength int = 32;
    declare @i int = 1;
    declare @l int = (@derivedKeyLength + @hmacLength - 1) / @hmacLength;
    declare @r int = @derivedKeyLength - (@l - 1) * @hmacLength;
    declare @derivedKey varbinary(max) = Cast('' as varbinary(max));
    declare @u varbinary(8000);
    declare @uA binary(32);
    declare @uB binary(32);

    while(@i <= @l)
    begin;
        declare @j int = 1;

        select @u = @salt + Cast(@i as binary(4));
        select @uA = uA.[Hash]
             , @uB = uA.[Hash]
        from dbo.Hmac(@password, @u) as uA;

        while @j < @iterations
        begin;
            select @uA = tA.[Hash] from dbo.Hmac(@password, @uA) as tA;
            select @uB = tB.[Hash]
            from (values(
              -- unrolled loop to XOR uA and uB
                Cast(Substring(@uA, 1, 8) ^ Cast(Substring(@uB, 1, 8)  as bigint) as binary(8))
              + Cast(Substring(@uA, 9, 8) ^ Cast(Substring(@uB, 9, 8)  as bigint) as binary(8))
              + Cast(Substring(@uA, 17, 8) ^ Cast(Substring(@uB, 17, 8)  as bigint) as binary(8))
              + Cast(Substring(@uA, 25, 8) ^ Cast(Substring(@uB, 25, 8)  as bigint) as binary(8))
            )) tB ([Hash]);

            select @j = @j + 1;
        end;

        select @derivedKey = @derivedKey + Cast(case when @i = @l then Left(@uB, @r) else @uB end as varbinary(32));

        select @i = @i + 1;
    end;

    return @derivedKey;
end;

I'd really like to replace the loops with something set-based so that I can turn this into an inline-TVF but just can't seem to wrap my head around it...


texts: Creating accounts in a cpanel/whm account

texts:
I am trying to make this code that creates accounts in a cpanel/whm account more secure.

Could someone please let me know what needs to be done to make this more secure?

<?php
///////  YOUR WHM LOGIN DATA
$whm_user   = "username";      // reseller username
$whm_pass   = "password";  // the password you use to login to WHM

#####################################################################################
##############          END OF SETTINGS. DO NOT EDIT BELOW    #######################
#####################################################################################

$whm_host   = $_SERVER['HTTP_HOST'];

function getVar($name, $def = '') {
  if (isset($_REQUEST[$name]))
    return $_REQUEST[$name];
  else
    return $def;
}

// Domain name of new hosting account
// To create subdomain just pass full subdomain name
// Example: newuser.zubrag.com
if (!isset($user_domain)) {
  $user_domain = getVar('domain');
}

// Username of the new hosting account
if (!isset($user_name)) {
  $user_name = getVar('user');
}

// Password for the new hosting account
if (!isset($user_pass)) {
  $user_pass = getVar('password');
}

// New hosting account Package
if (!isset($user_plan)) {
  $user_plan = getVar('package');
}

// Contact email
if (!isset($user_email)) {
  $user_email = getVar('email');
}

// if parameters passed then create account
if (!empty($user_name)) {

  // create account on the cPanel server
  $script = "http://{$whm_user}:{$whm_pass}@{$whm_host}:2086/scripts/wwwacct";
  $params = "?plan={$user_plan}&domain={$user_domain}&username={$user_name}&password={$user_pass}&contactemail={$user_email}";
  $result = file_get_contents($script.$params);
}
// otherwise show input form
else {
$frm = <<<EOD
EOD;
echo $frm;
}

?>

EDIT:

This works:

$whm_host   = $_SERVER['SERVER_NAME'];

function getVar($name, $def = '', $sg_method = 'POST') {
  switch($sg_method){
      case 'POST'   : return isset($_POST[$name])   ? $_POST[$name]   : $def;
        break;
      case 'GET'    : return isset($_GET[$name])    ? $_GET[$name]    : $def;
        break;
      case 'COOKIE' : return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $def;
        break;
      default : return $def;
  }
}

// Domain name of new hosting account
// To create subdomain just pass full subdomain name
// Example: newuser.zubrag.com
if (!isset($user_domain)) {
  $user_domain = getVar('domain');
}

// Username of the new hosting account
if (!isset($user_name)) {
  $user_name = getVar('user');
}

// Password for the new hosting account
if (!isset($user_pass)) {
  $user_pass = getVar('password');
}

// New hosting account Package
if (!isset($user_plan)) {
  $user_plan = getVar('package');
}

// Contact email
if (!isset($user_email)) {
  $user_email = getVar('email');
}

// if parameters passed then create account
if (!empty($user_name)) {

  // create account on the cPanel server
  $script = "http://{$whm_user}:{$whm_pass}@{$whm_host}:2086/scripts/wwwacct";
  $params = "?plan={$user_plan}&domain={$user_domain}&username={$user_name}&password={$user_pass}&contactemail={$user_email}";
  $result = file_get_contents($script.$params);
}
// otherwise show input form
else {
$frm = <<<EOD
EOD;
echo $frm;
}


texts: Sending data from UART to microcontroller via AT89C2051 functioning as a UART/SPI bridge

texts:
I have an unusual setup. I have an AT89S52 microcontroller in which its UART is used by the PC. I needed a way to make a second UART based device work with it, so what I decided to do was make a UART to SPI converter using an AT89C2051 due to its smaller size and smaller cost. Now I have some trouble sending data from the AT89S52 to the 2nd UART through the UART to SPI converter.

I have attached code for the converter. Ideally what my program should do is (upon a clock trigger), it will read in 5 bits (4 for data, 1 for status) one by one and as it reads a bit, it outputs another on another pin. Once the bits are read into the converter, I'd like the converter to add a sequence number to the byte to increase chances of data integrity.

For example, if I wanted to send these nibbles (in hex):

D A B E

Then I want the UART connected device to see the following sent:

D0 A1 B2 E3

When the UART sends data, I want the sequence number checked to see if its correct and as long as it is correct, the data will be in a temporary variable until it's ready to be read, and the output is then the expected nibble of data.

Someone please review this code to see if there is anything I can do to improve it. I'm specifically interested in receiving all data as it comes in without losing data. and I'm also interested in being able to send all the data.

All microcontrollers are running at the same clock speed, and I only have 4 I/O lines I can work with. Because of the nature of the microcontrollers, I can force a logic low to any output because a logic high is actually high impedance, so if forcing a low on an output will make my job easier in this situation, then I'd like to know.

  ;DATA FORMAT to/from UART:
  ;max 8 bit chain -> nnnncccc. nnnn=data nibble. cccc=decrementing sequence #

  ;Data format to/from SPI master:
  ;5 bit chain -> nnnnc, nnnn=data nibble, c=special.
  ;For transmit, C=1=reset counter. For receive, C=0=Data received

  DOUT equ P1.6 ;dat out
  DIN equ P1.5 ;dat in to me
  HASDAT equ P3.4 ;has data
  CLK equ P3.5
  HASDATI bit 0h
  SEQTX equ 23h
  SEQRX equ 22h

  start:
  ;setup everything
  mov P1,#0FFh
  mov P3,#0FFh
  setb HASDATI ;HASDATI: internal variable. 1=no data from serial
  mov SP,#50h
  mov PSW,#18h
  mov PCON,#80h
  mov SCON,#52h
  mov TMOD,#22h
  mov TH1,#0E8h ;4.8kbps serial speed
  mov TL1,TH1
  setb TR1 ;start serial
  jb CLK,$ ;fix clock. wait for clock=LOW to start
  main:
jb CLK,datio ;activate SPI when clock=HIGH
continue:
jbc RI,recvok ;assume data at serial
  sjmp main
  recvok:
  jnb HASDATI,main
  ;only enter serial port processing once until data is read
  mov B,SBUF ;Get data as B
  mov A,B    ;copy it
  anl A,#0Fh ;get sequence #
  cjne A,SEQRX,noseq ;and if it matches...
    inc SEQRX            ;use next sequence #
    anl SEQRX,#0Fh     ;and make it 0 if its 16
    clr HASDAT         ;let callers know new data is in
    clr HASDATI
    sjmp main
  noseq:
  ;Sequence doesn't match so start over
  mov SEQRX,#0h
  setb HASDAT
  setb HASDATI
  sjmp main

  datio:
mov R5,#0h ;clear output buffer
mov R3,#5h ;We exchange 5 bits
mov A,B     ;load recently received data
mov C,HASDATI ;and data reception indicator
mov ACC.3,C   ;attach indicator to data
mov R4,A    ;R4=data to output
rrr:
  ;shift out bit
  mov A,R4
  RLC A
  mov DOUT,C
  mov R4,A
  ;wait until remote lowers clock line
  jb CLK,$
  ;Receive bit
  mov A,R5
  mov C,DIN
  RRC A
  mov R5,A
djnz R3,rrr
;Check MSB of lower nibble received
;and if its 1, set it to 0 and reset transmit counter
jnb ACC.3,noresc
  mov SEQTX,#0h
  clr ACC.3
noresc:
;lower nibble=transmit count, high nibble=data
orl A,SEQTX
CLR TI     ;reset transmit to UART flag
mov SBUF,A ;and send byte
inc SEQTX       ;use next sequence number
anl SEQTX,#0Fh  ;and if its 16, make it 0
setb HASDATI          ;reset data indicator since we got the data
setb HASDAT
mov B,#0h       ;reset new data value so if we read too fast, we get nothing
jnb TI,$        ;stall until serial port finally read the byte
  ajmp continue


texts: Advanced formatting with argument passing

texts:
I want to customise how my objects are printed using the .format() function.

I have two problems to make that happen in clear and concise way. But since the second one stems from the first one I'm presenting both here.

Formatting array

Passing options to .format() in array seems to me to be awfully messy if I want to match default behaviour with __repr__:

import binascii

def format_data(data, formatstr):
    if 'x' in formatstr:
        return binascii.b2a_hex(data).decode('ascii')
    else:
        return repr(data)

class InsideA(object):
    def __repr__(self):
        return "InsideA()"

    def __format__(self, _):
        return "InsideA()"

class InsideB(object):
    def __init__(self, data):
        self.data = data

    def __repr__(self):
        data = format_data(self.data, 'x')
        return "InsideB(data={0})".format(data)

    def __format__(self, formatstr):
        data = format_data(self.data, formatstr)
        return "InsideB(data={0})".format(data)

if __name__ == "__main__":
    a = InsideA()
    b = InsideB(bytearray(b'test\xff\xff'))

    array = [a, b]

    print("what I want:")
    print(array)
    print("")

    print("doesn't work:")
    try:
        print("{0:x}".format(array))
    except Exception as e:  # catch just to continue execution
        print(e)
    print("")

    print("Leaves ' around elements:")
    print(["{0:x}".format(elem) for elem in array])
    print("")

    print("Works but seems overly complex:")
    print("[" + ", ".join("{0:x}".format(elem) for elem in array) + "]")

Produces:

What I want:

[InsideA(), InsideB(data=74657374ffff)]

Doesn't work:

non-empty format string passed to object.__format__

Leaves ' around elements:

['InsideA()', 'InsideB(data=74657374ffff)']

Works but seems overly complex:

[InsideA(), InsideB(data=74657374ffff)]

Formatting with non-uniform objects

The problem only gets compounded if the array elements don't always implement the format function, requiring use of try except clauses:

from __future__ import print_function
import binascii

def format_data(data, formatstr):
    if 'x' in formatstr:
        return binascii.b2a_hex(data).decode('ascii')
    else:
        return repr(data)

class InsideA(object):
    def __repr__(self):
        return "InsideA()"

class InsideB(object):
    def __init__(self, data):
        self.data = data

    def __repr__(self):
        data = format_data(self.data, 'x')
        return "InsideB(data={0})".format(data)

    def __format__(self, formatstr):
        data = format_data(self.data, formatstr)
        return "InsideB(data={0})".format(data)

def format_array(array, formatstr):
    if array is None:
        return "None"
    else:
        str_array = []
        for elem in array:
            try:
                str_array += ["{0:{1}}".format(elem, formatstr)]
            except (TypeError, ValueError):  # Py2 and Py3 compat
                str_array += [repr(elem)]
        return "[" + ", ".join(str_array) + "]"

if __name__ == "__main__":
    a = InsideA()
    b = InsideB(bytearray(b'test\xff\xff'))

    array = [a, b]

    print("Automatic:")
    print(array)
    print("")

    print("With format:")
    print(format_array(array, "x"))

Prints:

Automatic:

[InsideA(), InsideB(data=74657374ffff)]

With format:

[InsideA(), InsideB(data=74657374ffff)]

This code in format_array() seems to me to be too complex for what it does. Do I don't know of some syntax that makes this a breeze or is it the best Python can do?

(Yes, I know that I can implement __repr__ as just a call to format(), leaving that in for readability of example.)


texts: Do I need still to be concerned about favouring str_replace over preg_replace in PHP 7?

texts:
I have the following piece of code:

$Page = str_replace('-&amp;-', '-[+]-', $Page);
$Page = str_replace('&amp;', '-[+]-', $Page);
$Page = str_replace('-and-', '-[+]-', $Page);
$Page = str_replace('-et-', '-[+]-', $Page);
$Page = str_replace('-und-', '-[+]-', $Page);
$Page = str_replace('-y-', '-[+]-', $Page);
$Page = str_replace('-&-', '-[+]-', $Page);

which I then run many times per page load (perhaps 10 to 40 times).

  N.B. $Page represents a URL fragment - rarely more than 20 characters long.

Am I better off leaving it as it is, or may I, for the purposes of code maintenance, rewrite this code as:

$Page = preg_replace('/(-&-|-&amp;-|&amp;|-and-|-et-|-und-|-y-)/', '-[+]-', $Page);

without suffering a slowdown of one or several hundredths of a second?

(If the slowdown is a matter of milliseconds, I am less bothered).

Background:

I am less familiar with the evolution of PHP than with that of javascript, css etc. so when I see recommendations (long-stated, albeit from the late 2000s and early 2010s) like:

  Avoid preg_replace unless you need to use it and always use
  str_replace instead, which is an order of magnitude faster.

I don't know if that recommendation still has any relevancy for PHP 7.3 in 2020, or whether that recommendation was important to follow in the days of PHP 5, but is less of a concern now (given that PHP 7 is so much faster and more optimised than its predecessor).


texts: Find the number of elements larger than a given element in BST

texts:
I'm trying to solve the Hackerrank's Insertion Sort Advanced Analysis problem using BST (similar to this question on SO). As I put items in the tree, I need to find out the number of items greater than it (the get_rank() method in the code):

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
        self.num_left_children = 0
        self.num_right_children = 0

    def insert(self, data):
        if data <= self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)
            self.num_left_children += 1
        else:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)
            self.num_right_children += 1

    def get_rank(self, data):
        if data < self.data:
            return self.num_right_children + self.left.get_rank(data) + 1
        elif data > self.data:
            return self.right.get_rank(data)
        else:
            return self.num_right_children

How can I improve the performance of this code (e.g. in case multiple identical items are put into the tree) ?


texts: Cleaning up code for Conway's Game of Life

texts:
I've implemented a Ruby version of Conway's Game of Life that functions correctly and passes all my tests.  I was hoping to get some advice on how I could clean up the code for readability and efficiency.

For anyone who doesn't know the rule to the Game of life, they are as follows:

  Any live cell with fewer than two live neighbours dies, as if by needs caused by underpopulation.
  Any live cell with more than three live neighbours dies, as if by overcrowding.
  Any live cell with two or three live neighbours lives, unchanged, to the next generation.
  Any dead cell with exactly three live neighbours becomes a live cell.

(In my implementation, 1 is an alive cell and 0 is a dead cell).

class Game_of_life
  def initialize(hash)
    @test = nil
    str = hash[:string]
    size = hash[:size]
    @length = nil
    @board = []
    if str != nil
      str.each_char {|c| @board << c.to_i}
      @test = true
      @length = Math.sqrt(str.length)
    else
      (size*size).times do
        @board << [0,1].sample
      end
      @length = size
    end
  end

  def check_board

    @board.each_with_index do |organism, index|
      neighbours = {alive: 0, dead: 0}
      neighbour_positions = choose_neighbour_set(index)
      neighbour_positions.each do |position|
        neighbours[:alive] += 1 if @board[index+position] == 1
        neighbours[:dead] += 1 if @board[index+position] == 0
      end
      @board[index] = 0 if organism == 1 && (neighbours[:alive] < 2 || neighbours[:alive] > 3)
      @board[index] = 1 if organism == 0 && neighbours[:alive] == 3
    end
    if @test
      return @board.join("")
    else
      sleep 0.5
      puts "\e[H\e[2J"
      @board.each_slice(@length) {|row| p row }
      check_board
    end
  end

  def choose_neighbour_set(index)
    neighbour_set = [-(@length), -(@length - 1), 1, (@length+1), @length, (@length-1), -1, -(@length + 1)]
    neighbour_set.delete_if{|position| [-(@length + 1), -(@length),-(@length - 1)].include?(position)} if index < @length
    neighbour_set.delete_if{|position| [(@length-1),@length,(@length+1)].include?(position)} if index > ((@length*(@length-1)) -1)
    neighbour_set.delete_if{|position| [-(@length + 1),-1,(@length-1)].include?(position)} if index % @length == 0 || index == 0
    neighbour_set.delete_if{|position| [(@length+1),1,-(@length - 1)].include?(position)} if (index + 1) % @length == 0 && index != 0
    return neighbour_set
  end
end

# Uncomment to watch the game of life unfold!
# Game_of_life.new({size: 25}).check_board

# >>>>>>>>>>>>>>>>>>>>> Driver code

# Test string one
arr = "100100111110100011110110001100110010000010111101100010010111110110111100110000011"
game = Game_of_life.new({string: arr})
p game.check_board == "110000101000111101110000101111110001100011101101000000000000110111111001101011111"

# test string two
arr2 = "110111000101110010011000100110100100000101110111001110111011011101110010010110110"
game2 = Game_of_life.new({string: arr2})
p game2.check_board == "110011000100110110001010100001010010000100011101001000101001011100010001000111110"

# test string three
arr3 ='100110010'
game3 = Game_of_life.new({string: arr3})
p game3.check_board == "110011011"

# test string four

arr4 = "0010010111001001"
game4 = Game_of_life.new({string: arr4})
p game4.check_board == "0010101110100000"


texts:
Here's my implementation to factorize a positive integer:

def is_prime(n):
    if n == 1:
        return False
    if n % 2 == 0:
        return False
    i = 3
    while i * i <= n:
        if n % i == 0:
            return False
        i += 2
    return True

# @timeit
def prime_factors(n):
    prime_factor_list = []
    while not n % 2:
        prime_factor_list.append(2)
        n //= 2
    while not n % 3:
        prime_factor_list.append(3)
        n //= 3
    i = 5
    while n != 1:
        if is_prime(i):
            while not n % i:
                prime_factor_list.append(i)
                n //= i
        i += 2

    return prime_factor_list

How can I improve this code in speed and make it pythonic?


texts:
I recently wrote a function that replaces every white space with '%20', just for fun (and sharping my coding skills). The input string is terminated with extra white spaces, with the length that the string should have after encoding takes place. For example:

input = "Not encoded  " //2 white spaces in the end
output = "Not%20encoded"

Although I was able to implement such encoding in-place, I was still not pleased with the result, specially due to the inner loop that shifts the whole string to the right everytime a white space is found. Here is my solution, written in C#:

    public string encode(string str)
    {
        var array = str.ToCharArray();
        for (int i = 0; i < array.Length; i++) {
            if (array[i] != ' ') continue;

            //switch every char >> 2, from the end of the string to i
            for (int j = array.Length - 1; j > i; j--) {
                array[j] = array[j - 2];
            }

            array[i++] = '%';
            array[i++] = '2';
            array[i] = '0';
        }
        return new String(array);
    }

I'm looking for a solution that operates in O(n), possibly performing a single traversal on the input string. Additional feedback on how to improve performance/readability of my function are always very appreciated :)


texts:
I have the following method that is working perfectly. Main problem I see is that I think it can be done just in one line, but I don't know how:

def _animate_display(self, display):
    self._timer += 1 / bge.logic.getAverageFrameRate()

    symbolic_level = self.battery.get_symbolic_level()

    if self._timer >= 5.0:
        self._timer = symbolic_level / 25
    elif (self._timer >= 4.0) and (symbolic_level <= 100):
        utils.change_texture(display, 'DisplayMat', 'icons/battery_100.png')
    elif (self._timer >= 3.0) and (symbolic_level <= 75):
        utils.change_texture(display, 'DisplayMat', 'icons/battery_75.png')
    elif (self._timer >= 2.0) and (symbolic_level <= 50):
        utils.change_texture(display, 'DisplayMat', 'icons/battery_50.png')
    elif (self._timer >= 1.0) and (symbolic_level <= 25):
        utils.change_texture(display, 'DisplayMat', 'icons/battery_25.png')
    elif (self._timer >= 0.0) and (symbolic_level <= 0):
        utils.change_texture(display, 'DisplayMat', 'icons/battery_0.png')

It models a simple animation of a charging battery in steps of 1 second. Something like: [....] --1s--> [=...] --1s--> [==..] --1s--> [===.] --1s--> [====] --1s--> [....] ...

Symbolic level is a variable that keep a value of [0, 25, 50, 75, 100], one of these, so animation loops from that symbolic value so it doesn't start from 0.


texts: Assigning values to array elements based on a lookup table

texts:
I am writing a C# program wherein I need to populate an array based on a lookup table and set of string arrays with metadata. My lookup table looks like this (Table with key: transmitter, value: Array of receiver):

{
    LED1: ["px1","px2","px3"],
    LED2: ["px4","px5","px6"]
}

and my meta arrays looks like this (it is dynamic (just an example) and comes as a response from a DB query):

var transmitters = new string[] { "LED1", "LED2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };

My requirement is:

If the transmitter LED1 or LED2 (or any other transmitter) is present in the lookup table, the value of the transmitter (i.e. ["px1","px2","px3"]) has to be compared with the receiver which are present in the lookup and led has to be marked yellow.
Orphan transmitter or/ receiver has to be marked red.

Example

Lookup

{
        LED1: ["px1", "px2", "px3"],
        LED2: ["px5", "px8"]
}

Transmitters and receivers

var transmitters = new string[] { "led1", "led2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };

The result should be a list as:

led1-yellow
px1-yellow
px2-yellow
px3-yellow
led2-yellow
px5-yellow
px4-red
px6-red.

I have written code that works:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
      var transmitters = new string[] { "led1", "led2", "led3" };
      var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };
      var lookup = new Dictionary<string, string[]>() {
          { "led1", new string[] { "px1", "px2", "px3" } },
          { "led2", new string[] { "px5", "px8"} }
      };

      var blocks = new List<Block>();
      var blocksTracker = new List<string>();

      foreach (var transmitter in transmitters)
      {
        if (lookup.ContainsKey(transmitter))
        {
          var receiverLookup = lookup[transmitter];
          var intersection = receivers.Intersect(receiverLookup).ToArray();
          if (intersection.Length > 0)
          {
             blocks.Add(new Block() { Id = transmitter, status = "yellow"});
             blocksTracker.Add(transmitter);
            foreach (var receiver in intersection)
            {
              blocks.Add(new Block(){Id = receiver, status = "yellow"});
              blocksTracker.Add(receiver);
            }
          } else
          {
            blocks.Add(new Block(){Id = transmitter, status = "red"});
            blocksTracker.Add(transmitter);
          }
        }
      }

      var ungrouped = receivers.Except(blocksTracker).ToArray();

      foreach (var receiver in ungrouped)
      {
        blocks.Add(new Block(){Id = receiver, status = "red"});
        blocksTracker.Add(receiver);
      }

      foreach (var i in blocks)
      {
        Console.WriteLine(i.Id + "-"+i.status);
      }
    }

    public class Block
    {
      public string Id { get; set; }

      public string status { get; set; }
    }
}

I am new to C# and I wanted to know if there is a better way of doing this. You can see the working Fiddle here.


texts: Optimising fingerprint scan compare process

texts:
I'm creating some python script in Raspberry Pi to running fingerprint scan and compare it against database. Using this library, on raspberry start this script will get all the database record for fingerprint characteristics and the for loops will compare it. After getting about 100 records the loops is running very slow.

import RPi.GPIO as GPIO
import time
import requests
import hashlib
import MySQLdb
from pyfingerprint.pyfingerprint import PyFingerprint

def connect():
    return MySQLdb.connect(host="192.168.1.1", user="root", passwd="123456", db="abc")

GPIO.setmode(GPIO.BOARD)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.LOW)

try:
    f = PyFingerprint('/dev/ttyUSB1', 57600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    pass

db = connect()
cur = db.cursor()
cur.execute("SELECT * FROM fingers")
row = cur.fetchall()
while True:
    try:
        print('Waiting for finger...')
        while(f.readImage() == False):
            pass

        f.convertImage(0x01)

        for ro in row:
            ss = eval(ro[2])
            f.uploadCharacteristics(0x02,eval(ss))
            if ( f.compareCharacteristics() == 0 ):
                #print('Fingers do not match')
                pass
            else:
                #print('Finger Match')
                GPIO.output(18, GPIO.HIGH)
                time.sleep(1)
                GPIO.output(18, GPIO.LOW)
                time.sleep(1)
                break
    #db.close()

    except Exception as e:
        print('Operation failed!')
        print('Exception message: ' + str(e))
        pass

Any suggestion? Thanks