texts: Bash script which downloads the latest linux stable kernel

texts:
I made this script when I started downloading the latest stable linux kernel's source from https://www.kernel.org to compile it myself, now I have improved it a bit and decided to create a public repo for it on github (https://github.com/Tom1380/latestkernel).

This is the code (mind you this is the first time I made bash scripts):

lk (stands for latest kernel):

#!/usr/bin/env bash

cd ~

if [ ! -d "linux-stable" ]; then
    mkdir linux-stable
fi

if [ ! -f "/etc/latest_kernel" ]; then
    if  [[ $EUID > 0 ]] ; then
        echo "/etc/latest_kernel does not exist and you are not running the script as root, " \
              "please fix that either by manually running 'sudo create_etc_lk', " \
              "or rerun the script as root to automatically fix it."
        exit
    else
        touch /etc/latest_kernel
        echo "$(uname -r)" > /etc/latest_kernel
    fi
fi

wget=$(wget --output-document - --quiet https://www.kernel.org/ | grep -A 1 "latest_link")

wget=${wget##*.tar.xz\">}

wget=${wget%}

latest_acknowledged=$(</etc/latest_kernel)

if [ "$wget" == "$latest_acknowledged" ]; then
    echo "You have the latest stable kernel downloaded: $wget"
#    Uncomment (take out the #) the first 4 lines below if you want to be prompted when you are using a different kernel than
#    the latest one while already having installed it
#    runningkernel=$(uname -r)
#    if [ $runningkernel != $latest_acknowledged ]; then
#        echo "But you are running $runningkernel"
#    fi
    exit
fi

echo "Updated kernel available: $wget, you have $latest_acknowledged."

if  [[ $EUID > 0 ]] ; then
    echo "If you wish to download the latest kernel, rerun the script as root."
    exit
fi

# Since there is only a '>', /etc/latest_kernel will be overwritten entirely.

echo "$wget" > /etc/latest_kernel

echo "Writing latest kernel available in /etc/latest_kernel."

echo "Preparing to parse link to latest kernel for wget."

wget=$(wget --output-document - --quiet https://www.kernel.org/ | grep -A 1 "latest_link")

wget=${wget##**}

echo "Done parsing."

cd ~/linux-stable

echo "Changed cwd to ~/linux-stable to download kernel source."

echo "Downloading, this may take up to 10 minutes."

wget $wget

echo "Finished downloading..."

echo "Uncompressing the kernel's source."

tar xvfJ linux-$(</etc/latest_kernel).tar.xz

echo "Done uncompressing the kernel's source."

rm linux-$(</etc/latest_kernel).tar.xz

echo "Done removing the old archive, end of the script."

create_etc_lk:

#!/usr/bin/env bash

if [[ $EUID > 0 ]] ; then
    echo "You need root privileges for this script."
    exit
fi

touch /etc/latest_kernel && echo "$(uname -r)" > /etc/latest_kernel

install:

#!/usr/bin/env bash

if [[ $EUID > 0 ]] ; then
    echo "You need root privileges for this script."
    exit
fi

cp lk /usr/bin/lk
cp create_etc_lk /usr/bin/create_etc_lk
cp purgelatestkernel /usr/bin/purgelatestkernel

purgelatestkernel:

#!/usr/bin/env bash

if [[ $EUID > 0 ]] ; then
    echo "You need root privileges for this script."
    exit
fi

cp lk /usr/bin/lk
cp create_etc_lk /usr/bin/create_etc_lk
cp purgelatestkernel /usr/bin/purgelatestkernel

PS: Feel free to clone the repo if you think lk might be helpful to you


texts: Brute force algorithm for printing all possible alphanumeric combinations

texts:
I'm still very much a beginner, so I don't really know much about best practices or the speed of any particular C functions.

You'll notice that I included a "cs50" library. This is from a MOOC I'm taking, all it does in this program is allow me to use their "bool" data type. I realize I don't need to delegate all of this code to so many functions, but this is part of a bigger problem set from said MOOC, where I am to crack a password, so I thought to make the functions now rather than later.

The program loops through and prints all possible iterations of alphanumeric combinations (no uppercase) from length 1-8. The algorithm in its current state is very slow. I've also never run it to the very end:

#include <cs50.h>       //GetString, booleans, and string datatype
#include <stdio.h>      //printf
#include <string.h>     //strlen

#define LOOP_MAX 8

bool BruteForceIntializer();
int looper (int amt, int count);

char engWord[9];
char alphaNum[36] = {"0123456789abcdefghijklmnopqrstuvwxyz"};
int maxSize = sizeof(alphaNum);

int main(void)
{
    if (BruteForceIntializer() == true)
        printf("Success.\n");
    else
        printf("Failure.\n");
}

bool BruteForceIntializer()
{
    int count;
    for (int amt = 0; amt < LOOP_MAX; amt++)
    {
        memset(engWord, '\0', 9);
        count = 0;
        if (looper(amt, count) == 0)
        {
            continue;
        }
    }
    return true; //only exits loop if all chars are looped successfully
}

int looper(int amt, int count)
{
    for(int i = 0; i < maxSize; i++)
    {
        engWord[count] = alphaNum[i];
        if (count == amt) //check if we're at the last character
        {
            printf("%s\n", engWord);
            if (i == (maxSize-1))
                return 0;
        }
        if (count != amt)
        {
            if (looper(amt, count+1) == 0)
                continue;
        }
    }
    return 1;
}


texts:
I have a list X containg the data performed by different users N so the the number of the user is i=0,1,....,N-1. Each entry Xi has a different length.
I want to normalize the value of each user Xi over the global dataset X.

This is what I am doing. First of all I create a 1D list containing all the data, so:

tmp = list()
for i in range(0,len(X)):
    tmp.extend(X[i])

then I convert it to an array and I remove outliers and NaN.

A = np.array(tmp)
A = A[~np.isnan(A)] #remove NaN
tr = np.percentile(A,95)
A = A[A < tr]  #remove outliers

and then I create the histogram of this dataset

p, x = np.histogram(A, bins=10) # bin it into n = N/10 bins

finally I normalize the value of each users over the histogram I created, so:

Xn  = list()
for i in range(0,len(X)):
    tmp = np.array(X[i])
    tmp = tmp[tmp < tr]
    tmp = np.histogram(tmp, x)
    Xn.append(append(tmp[0]/sum(tmp[0]))

My data set is very large and this process could take a while. I am wondering if there is e a better way to do that or a package.


texts: Possible memory-leak on a self-removable event handler

texts:
A friend of mine asked me a question recently. He was needed to subscribe to an event of some object (window button click) and unsubscribe from it on a first call of a handler. Also he noticed that object is dynamically created and his handler is a delegate.

After some thinking I came up with a solution using closures of an object and a delegate itself:

class Program
{
    class A
    {
        public event EventHandler OnRaise;

        public void RaiseEvent(string text)
        {
            Console.WriteLine("a said: " + text);
            if (OnRaise != null)
                OnRaise(this, null);
        }
    }

    static void Main(string[] args)
    {
        var a = new A();

        EventHandler handler = null;
        handler = (x, y) =>
            {
                Console.WriteLine("handler's working");
                a.OnRaise -= handler;
            };

        a.OnRaise += handler;

        a.RaiseEvent("blah blah ");
        a.RaiseEvent("beep beep ");

        handler = null;
        a = null;

        GC.Collect();

        Console.ReadKey();
    }
}

It does all requested behavior but I'm not sure if it's good and safe from memory-leaks. It would be great if anyone can review the code and help with advice or offer a better way to solve the problem.


texts: Simple factorial program using recursion

texts:
Two concepts I realized I needed to understand and use more are recursion and Exceptions. Thus, I combined both in the following program. Although it began with a focus on using recursion it became more about Exceptions. I think the recursive part is bare-bones and straight-forward but I would nonetheless appreciate any tips/advice on using/formatting recursion in general.

On exception-handling: Is the following the optimal way of employing them or is there a more conventionally favored fashion? I get the feeling I may be missing doing something unnecessary or missing something important.

import javax.swing.JOptionPane;

class FactorialDemo {
    public static void main(String[] args) {
        int factorialNumber = 0;
        try {
            factorialNumber = Integer.parseInt(JOptionPane.showInputDialog(null,
                "Which number should we compute the factorial of?"));
        } catch(NumberFormatException nfe) {
            JOptionPane.showMessageDialog(null,"Input must be an integer!",
                "Error", JOptionPane.ERROR_MESSAGE);

            throw new NumberFormatException("Input must be an integer.");
        }

        JOptionPane.showMessageDialog(null,
                factorialNumber + " factorial is " +recur(factorialNumber) +".",
                "Result", JOptionPane.PLAIN_MESSAGE);
    }

    public static int recur(int n) {
        int result;
        if (n < 0) {
            JOptionPane.showMessageDialog(null,"n must be >= 0 but was " + n,
                "Error", JOptionPane.ERROR_MESSAGE);

            throw new IllegalArgumentException("n must be >= 0 but was " + n);
        }
        if (n < 2) {
            return 1;
        }

        result = recur(n - 1) * n;
        return result;
    }
}


texts: Parsing latitude and longitude, using Try[T] to ignore errors

texts:
I wrote this question asking about how to implement my error handling while still maintaining functional code and based on 200_success's very interesting note on the spaces, I decided to trim() the String first, but I wanted to avoid using try/catch blocks and use more of Scala's specific features, so I thought of a solution with the Try type:

private def tryParseDouble(value: String) = Try(value.toDouble)

def toCoordinates(coordinates: String): Seq[Coordinate] = {
  val coordinatesList = coordinates.split(",")
  coordinatesList flatMap { coordinate =>
    coordinate.trim().split("\\s+").map(tryParseDouble) match {
      case Array(Success(lat), Success(lon)) => Some(Coordinate(lat, lon))
      case _                                 => None
    }
  }
}

Would this be an acceptable way to implement error handling? Or am I overthinking this and a simple try/catch would be just as good?


texts:
I'm familiar with JS, however just today started TypeScript. Experimenting with the type system and generics, I thought to implement a comparator yielding 3 distinct results and created the following:

export function compare<T>(s1: T, s2: T): number {
    let equal = 0;
    let greater = 1;
    let lesser = -1

    // Special cases: consider "undefined" and "null" to be less than defined
    if (nullOrUndefined(s1) && nullOrUndefined(s2)) {
        return equal;
    } else if (nullOrUndefined(s1) ^ nullOrUndefined(s2)) {
        return nullOrUndefined(s2) ? greater : lesser;
    }

    // Ignore case for strings
    if (typeof s1 === 'string') {
        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();
    }

    // Use JS default
    return s1 === s2 ? equal : s1 > s2 ? greater : lesser;
}

export function nullOrUndefined(input: any): boolean {
    return input === undefined || input === null;
}

My questions are:

Are the variables necessary? I keep going back and forth on this / wonder if it aids clarity in any way. Sometimes feel like it's intuitive, but I even wonder if an enumeration representing comparison results outside could be superior.
My first implementation used the any type, but it feels more appropriate to apply it this way since it should always compare like-items. This feels like a sensical assumption, but would any prove more handy and 'generic' in any case?
For any unfamiliar with JS weirdness, see this article.


texts: Total number of stops for an elevator to serve certain people

texts:
I have seen this question asked around a bit, such as this Code Review question in Java:

  Write an optimal program that would determine the total number of stops
  a elevator has taken to serve X number of people. There is a elevator
  in a building with M floors. This elevator can take a max of X people
  at a time or max of total weight Y. Given that a set of people has
  arrived and their weight and the floor they need to stop given how
  many stops has the elevator taken to serve all the people. Consider
  elevator serves in the first come first serve basis. (N people in Queue)

I am making this code review request to see if I can get any feedback on my C++ implementation.

const int max_number_of_ppl = 3; // X
const float max_weight = 250.0;  // Y
const int number_of_floors = 5; // M

// assume person array is 0,1,....N-1 -> so N people
// people are in a queue , find total number of stops
int solution(const int &N,const std::vector<int> &weight,const std::vector<int> &floor)
{
    int idx = 0;
    float last_weight = 0.0;
    int last_count = 0;
    std::set<int> stops;
    int stop_count = 0;
    while(idx < N)
    {
        //lift full, dont put any more ppl
        if(last_count + 1 > max_number_of_ppl || last_weight + weight[idx] > max_weight)
        {
            stop_count += static_cast<int>(stops.size());
            stops.clear();
            last_weight = 0.0;
            last_count = 0;

        }

        //fill lift with the person
        stops.insert(floor.at(idx));
        last_count++;
        last_weight += weight.at(idx);

        //fetch next person
        idx++;
    }

    //handle last lift session
    if(stops.size() >0)
    {
        stop_count += static_cast<int>(stops.size());
    }

    return stop_count;
}

Simple test:

int main()
{
    int N = 6;
    std::vector<int> weight;
    std::vector<int> stops;
    weight.emplace_back(100);
    weight.emplace_back(70);
    weight.emplace_back(60);
    weight.emplace_back(190);
    weight.emplace_back(100);
    weight.emplace_back(10);

    stops.emplace_back(5);
    stops.emplace_back(5);
    stops.emplace_back(5);
    stops.emplace_back(4);
    stops.emplace_back(3);
    stops.emplace_back(3);

    std::cout<<solution(N,weight,stops);

    return 0;
}


texts: Cancelling A Task Without Cancellation Token

texts:
Some Task methods don't take cancellation tokens. This is a problem because some long-running tasks may never finish and there is no way to send them a cancellation request. This seems a bit dodgy to me but this is a workaround. Is there anything wrong with this? Is there a better way?

public static Task<T> SynchronizeWithCancellationToken<T>(this Task<T> task, int delayMilliseconds = 10, CancellationToken cancellationToken = default)
{
    if (task == null) throw new ArgumentNullException(nameof(task));

    while (!task.IsCompleted && !task.IsFaulted && !task.IsCanceled)
    {
        Thread.Sleep(delayMilliseconds);

        if (cancellationToken.IsCancellationRequested)
        {
            return Task.FromCanceled<T>(cancellationToken);
        }
    }

    return task;
}

Example

The methods where this is a problem tend to be obscure APIs that haven't had much love in a long time or APIs that are wrappers for other platforms. One example is RequestWaitAsync on UsbDeviceConnection. It's a wrapper for an Android USB API . The issue can be worked around like so:

var buffers = await GetReadResultAsync(bufferLength, byteBuffer).SynchronizeWithCancellationToken(cancellationToken);

Another way to workaround the issue might be with Task.Run

public async Task<ReadResult> ReadAsync(uint bufferLength, CancellationToken cancellationToken = default)
{
    return await Task.Run(async () =>
    {
        try
        {

            //...

            return await GetReadResultAsync(bufferLength, byteBuffer);

        }
        catch (Exception ex)
        {
            //...
        }
    }, cancellationToken);
}

Which of these two work arounds are the safest?

Unit Test

This is a pathetic attempt at a unit test. It passes:

[TestMethod]
public async Task TestSynchronizeWithCancellationToken()
{
    var stopWatch = new Stopwatch();
    stopWatch.Start();

    var completed = false;

    var task = Task.Run<bool>(() =>
    {
        //Iterate for one second
        for (var i = 0; i < 100; i++)
        {
            Thread.Sleep(10);
        }

        return true;
    });

    var cancellationTokenSource = new CancellationTokenSource();

    //Start a task that will cancel in 500 milliseconds
    var cancelTask = Task.Run<bool>(() =>
    {
        Thread.Sleep(500);
        cancellationTokenSource.Cancel();
        return true;
    });

    //Get a task that will finish when the cancellation token is cancelled
    var syncTask = task.SynchronizeWithCancellationToken(cancellationToken: cancellationTokenSource.Token);

    //Wait for the first task to finish
    var completedTask = (Task<bool>) await Task.WhenAny(new Task[]
    {
        syncTask,
        cancelTask
    });

    //Ensure the task didn't wait a long time
    Assert.IsTrue(stopWatch.ElapsedMilliseconds < 1000);

    //Ensure the task wasn't completed
    Assert.IsFalse(completed);
}


texts: Read through a log file to find "Fail" lines

texts:
Please bear with me, I'm only about a week into Python.

This code is something that I wanted to do once I completed the chapters dealing with opening and reading files, and RegEx. I always feel like I'm over complicating the code. Please take a look and let me know if this is sound and where it can be improved. There are a lot of concepts I haven't learned yet. I'm teaching myself out of a book.

This code is meant to open a log file (will eventually be retrieved real-time), go through it line by line using RegEx to find "Fail", add those lines reporting failures to a list and return the completed list as a string joined with new lines.

#!/usr/bin/python

import os
import re

myFile = '/home/nick/python/chap8ReadingWritingFiles/15Jan2016_000000.txt'

def RegEx(file):
    openFile = open(myFile, 'r')
    myResList = []
    myList = openFile.readlines()
    myReg = re.compile(r'Fail')
    for i in (myList):
            #print(i, end='')
            result = myReg.search(i)
            if result != None:
                    #print(i, end='')
                    myResList.append(i.rstrip())
    final = '\n'.join(myResList[:])
    return final

print()
print('Results:')
print(RegEx(myFile))
print()


texts: Simple string joiner in modern C++ - follow-up

texts:
(See the previous iteration.)

Now, I have defined an iterator for dumping contents of a sequence such that the last element is not followed by the separator string.

main.cpp:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::for_each;
using std::vector;

using namespace std;

template <typename T, typename charT=char, typename traits=char_traits<charT>>
class my_ostream_iterator :
public iterator<output_iterator_tag, void, void, void, void>
{
    std::ostringstream* oss;
    std::string* separator;
    bool first_value_appended;

public:

    my_ostream_iterator(std::ostringstream* oss_, std::string* separator_)
    :
    oss{oss_},
    separator{separator_},
    first_value_appended{false}
    {}

    my_ostream_iterator<T,charT,traits>& operator= (const T& value) {
        if (!first_value_appended)
        {
            *oss << value;
            first_value_appended = true;
        }
        else
        {
            *oss << *separator << value;
        }

        return *this;
    }

    my_ostream_iterator<T,charT,traits>& operator*()     { return *this; }
    my_ostream_iterator<T,charT,traits>& operator++()    { return *this; }
    my_ostream_iterator<T,charT,traits>& operator++(int) { return *this; }
};

template<typename InputIt>
std::string join(InputIt begin,
                 InputIt end,
                 const std::string& separator =", ",
                 const std::string& concluder ="")
{
    std::ostringstream ss;
    std::string sep = separator;
    using value_type = typename std::iterator_traits<InputIt>::value_type;

    std::copy(begin,
              end,
              my_ostream_iterator<value_type>(&ss, &sep));

    ss << concluder;
    return ss.str();
}

int main() {
    vector<vector<int>> matrix = {
        { 1, 2, 3 },
        { 4, 5 },
        { },
        { 10, 26, 29 }
    };

    for_each(matrix.cbegin(),
             matrix.cend(),
             [](std::vector<int> a) {
                 cout << join(a.cbegin(), a.cend()) << endl;
             });
}

As always, any critique is much appreciated.


texts:
It compiles, works well, solves my problem of zipping old or big log files and removes them from a hard drive. However, following this answer, I would like to know what was wrong with the code.

Dir.foreach(FileUtils.pwd()) do |f|
    if f.end_with?('log')
        File.open(f) do |file|
            if File.size(f) > MAX_FILE_SIZE
                puts f
                puts file.ctime
                puts file.mtime

                # zipping the file
                orig = f
                Zlib::GzipWriter.open('arch_log.gz') do |gz|
                  gz.mtime = File.mtime(orig)
                  gz.orig_name = orig
                  gz.write IO.binread(orig)
                  puts "File has been archived"
                end

                #deleting the file
                begin
                  File.delete(f)
                  puts "File has been deleted"
                rescue Exception => e
                  puts "File #{f} can not be deleted"
                  puts "       Error #{e.message}"
                  puts "======= Please remove file manually =========="
                end
            end
        end
    end
end


texts: Converting data in a Rails Migration using the model

texts:
Lets imagine we have an Article entity, with data imported from a legacy database. It contains an appendix column with type integer. This column is always filled with values 0, 1 or nil, so we decide to call it in_appendix with type boolean. We want to preserve all existent data so we convert the data like this:

class ChangeTypeAppendixColumn < ActiveRecord::Migration
  def up
    add_column :article, :in_appendix, :boolean

    f  = Article.update_all({ in_appendix: false }, { appendix: nil })
    f += Article.update_all({ in_appendix: false }, { appendix: 0 })
    t  = Article.update_all({ in_appendix: true  }, { appendix: 1 })

    remove_column :article, :appendix
  end

  def down
    ...
  end
end

The problem is, if someday the Article model changes radically or ceases to exist, these migrations won't run anymore. My current solution is to create an AuxArticle class like this:

class AuxArticle < ActiveRecord::Base
  self.table_name = :article
end

class ChangeTypeAppendixColumn < ActiveRecord::Migration
  def up
    add_column :article, :in_appendix, :boolean

    f  = AuxArticle.update_all({ in_appendix: false }, { appendix: nil })
    f += AuxArticle.update_all({ in_appendix: false }, { appendix: 0 })
    t  = AuxArticle.update_all({ in_appendix: true  }, { appendix: 1 })

    remove_column :article, :appendix
  end

  def down
    ...
  end
end

It works but I would like to know about more elegant ways to keep existing data and at the same time prevent coupling between migrations and models.


texts: Using deferToThread in Twisted to run multiple tasks

texts:
I have a list of strings and for each string in the list I need to do some processing work.

The selection of strings isn't just using a for loop. Instead, in my case I need to pick up the strings randomly one after another. The interval is 1 second. As soon as all the strings in the list is selected (at least once), the selection work stops.

After being selected, a string is passed to a processing function. Processing a string takes up a random time (up to 5 seconds). The process work involves network connection and file operation, but in the code I just use a sleep function to simulation it.

In order to prevent the processing tasks block the selection of strings, I used deferToThread in Twisted. However I am not sure if this is the most appropriate option in my case.

The code is as follows:

from random import randint
import json
import time
from twisted.internet import reactor, threads

def process(string):
    print "Processing", string, "\n"
    """
    simulate processing on string by calling time.sleep()
    the actual processing involves network connection and writing result to files
    """
    time.sleep(randint(0, 5))
    print string, "processed\n"

string_list = ["AAAA", "BBBB", "CCCC", "XXXX", "YYYY", "ZZZZ"]

# choose a string randomly from the list every second
selected_string = []
while len(set(selected_string)) != len(string_list):
    time.sleep(1)
    random_index = randint(0, len(string_list)-1)
    selected_string.append(string_list[random_index])
    threads.deferToThread(process, string_list[random_index])

reactor.run()


texts:
I'm trying to build this simple tree:

Multiverse
|
|--- Universe
    |
    |--- Supercluster
        |
        |--- Galaxy
            |
            |--- Andromeda
            |
            |--- Milky way

I came up with this simple method which recursively walk a tree:

/**
 * recursively walk a tree structure
 */
public static void recursive(TreeViewItem treeNode){

        System.out.println(treeNode.getText());

        Iterator<TreeViewItem> itr = treeNode.getItems().iterator();

        while (itr.hasNext()) {
            TreeViewItem item = (TreeViewItem) itr.next();
            recursive(item);
        }
}

Is there a better way or more elegant way to do this?


texts:
In PHP, I'm getting multiple series and dumping various bits of information into an array. I will be left with 180 items (if I put in 30 series details that have 6 events per series)

$eventsArray = explode(',', $events); // This gets passed in via a param
\load_curl();
$array = Array();
$curl_array = array();

$ch = curl_multi_init();
foreach($eventsArray as $count => $id) {
    $curl_array[$count] = curl_init("https://www.eventbriteapi.com/v3/series/".$id."/events/?expand=ticket_classes&token=XXX");
    curl_setopt($curl_array[$count], CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_array[$count], CURLOPT_VERBOSE, true);
    curl_setopt($curl_array[$count], CURLOPT_SSL_VERIFYPEER, false);
    curl_multi_add_handle($ch, $curl_array[$count]);
}

do {
    curl_multi_exec($ch, $exec);
} while($exec > 0);

foreach($eventsArray as $count => $id) {
    $returned = curl_multi_getcontent($curl_array[$count]);
    $json = \json_decode($returned,true);
    foreach ( $json["events"] as $event) {
        $remaining = $event["ticket_classes"][0]["quantity_total"] - $event["ticket_classes"][0]["quantity_sold"];
        $array[] = Array('id'=>$event["id"],
                         'url'=>$event["url"],
                         'status'=>$event["status"],
                         'remaining'=>$remaining,
                         'start'=>date('l, jS F Y', strtotime($event["start"]["local"]))
                   );
    }
}

foreach($eventsArray as $count => $id) {
    curl_multi_remove_handle($ch, $curl_array[$count]);
}

curl_multi_close($ch);

foreach($eventsArray as $count => $id) {
    curl_close($curl_array[$count]);
}

$array = array_chunk($array, 30);
$array = json_encode($array);
return $array;

I then use EJS to display the information like below. The first item in each chunk is displayed in a row, then second item of each chunk in the next row etc.

<% for(var i=0; i<30; i++) { %>

        <%= this[0][i]['start'] %>
    <% for (var x=0; x<6; x++) {

    if (this[x][i]['status'] == 'live') {
        if (this[x][i]['remaining']<=0) {
            status='FULL';
            style = 'class="danger"';
        }
        else {
            status ='Book now
'+this[x][i]['remaining']+' AVAILABLE';
            style = 'class="success"';
        }
    }
    else {
            status='COMPLETE';
            style = 'class="warning"';
    }

    %>
        <td <%=style%>> <%=status%>
    <% } %>

<% } %>

It works but takes about 5 seconds to run. What could I do to make it faster? Is there much improvement that could be made?


texts:
This code basically saves an uploaded file to the server. I am wondering if there is  anything that I can do to tighten this code up.  I am very new to F# so I'm still having trouble breaking away from the C# way of doing things.

/// Create file paths
/// Returns a tuple (server path * link path * file number)
let createPath (file : HttpPostedFileBase) =

    // server directory path
    let serverDirPath =
        HttpContext.Current.Server.MapPath(@"~/Uploads")

    // get the file name
    let origFileName = file.FileName

    // get the extension
    let extension = Path.GetExtension(origFileName)

    // get the file size in bytes
    let fileSize = file.ContentLength

    // directory check
    let pathExists() = Directory.Exists(serverDirPath)

    // create directory
    let createDir() =
        if not (pathExists()) then
            Directory.CreateDirectory(serverDirPath) |> ignore
    createDir()

    // find current file name
    let findCurrentFileName() =

        // check if row exist
        let rowCount =
            query{
                for row in db.Uploads do
                select row
                count
            }

        // get file number
        let fileNumber =
            if rowCount < 1
                then
                    1
                else
                    query{
                        for row in db.Uploads do
                        select (row.FileNumber + 1)
                        head
                    }

        // final path
        let finalServPath =
            serverDirPath + @"\" + fileNumber.ToString() + extension

        // download link
        let linkPath =
            finalServPath.Replace(serverDirPath + @"\", @"~/Uploads/")

        finalServPath, linkPath, fileNumber

    findCurrentFileName()

/// Save file to server and path to db.
let SaveUpload (file: HttpPostedFileBase) (title : string) =

    // create the path including filename
    let servPath, linkPath, fileNumber = createPath file

    // save file to server
    file.SaveAs(servPath)

    // create new row for db table
    let newUpload =
        new dbSchema.ServiceTypes.Uploads(Title = title,
                                            FilePath = servPath,
                                            Size = file.ContentLength.ToString(),
                                            FileNumber = fileNumber,
                                            LinkPath = linkPath)
    // insert new row
    insertRowIn db.Uploads newUpload

    // save to db
    saveToDb()


texts: Extending an array to a specified length, alternating directions

texts:
I am working on golang and trying to understand to write good code not translated from another language, so I have written this program just for learning.

I want to perform operation on this array [1,2,3,4] with limit of 10, so that i get this output [1,2,3,4, 4,3,2,1, 1,2].

This function working correctly but I want to see suggestions for optimizations and improvements.

package main

import "fmt"

func arrayExm(array []int, limit int) []int {
    var res []int

    length := len(array)

    for i:=0; i < limit; i++ {

        if(i/length)%2 == 0{
            res = append(res,array[i%length])

        } else {
            res = append(res, array[length -i % length - 1])
        }
    }

    return res

}
func main() {
 fmt.Println(" Array with limit", arrayExm([]int{1,2,3,4},10))
}


texts:
Given positive integers a,b,c and limit, I want to generate all products having the form
$$p^aq^br^c \leq limit$$ less than limit (where p,q,r are distinct primes). a,b and c are not necessary distinct.

I tried something like:

primes= [ 2,3,5,...] # primes up to 10**8
[ (p**a)*(q**b)*(r**c) for p in primes for q in primes for r in primes if (p**a)*(q**b)*(r**c) <= limit ]

But it is very slow because len(primes)(=5761455) is high.

Then I tried a very ugly code for printing values.
It generates all values for p < q < r (p, q, r primes)

def generate3(a,b,c,limit):
    global primes
    i1 = 0
    i2 = 1
    i3 = 2
    while i1 < len(primes) and i2 < len(primes) and i3 < len(primes) and (primes[i1]**a)*(primes[i2]**b)*primes[i3]**c < limit:
        print(str(i1)+" "+str(i2)+str(i3))
        while i1 < len(primes) and i2 < len(primes) and i3 < len(primes) and (primes[i1]**a)*(primes[i2]**b)*primes[i3]**c< limit:
            while i1 < len(primes) and i2 < len(primes) and i3 < len(primes) and (primes[i1]**a)*(primes[i2]**b)*primes[i3]**c< limit:
                print(str(primes[i1])+" "+str(primes[i2])+" "+str(primes[i3])+" "+str((primes[i1]**a)*(primes[i2]**b)*(primes[i3]**c)))
                i3 = i3 + 1
            i2 = i2 +1
            i3 = i2 +1
        i1 = i1 + 1
        i2 = i1 + 1
        i3 = i2 + 1

Is there a more pythonic way to do this?
Is there a better method for generating these products of powers quickly?


texts:
This is the second version of my lotto game, based on this thread before. I hope I used all the tips I was given, also I fixed it using only functions as promised.

Game rules

  Each player is given 15 numbers, in increasing order. This is why I
  use sorted() on the lists of player and computer. Also there is a
  common list with numbers in it from 1 to 90.

  A random number is picked and removed from this list and printed to
  players. The player who has this number in his card crosses it out or
  skips its turn. This continues until either player or computer crosses
  out all his numbers, or for some strange reason they are out of
  numbers. I think in other parts of the world it is also called BINGO
  but I might be wrong.

import random
import os

number_pool = list(range(1, 11))  # 1 , 101
player_card = sorted(random.sample(number_pool, 3))  # 15
computer_card = sorted(random.sample(number_pool, 3))  # 15

def random_choice(num_pool):
    choice = random.choice(num_pool)
    num_pool.remove(choice)
    # print("Current lotto: " + str(choice))
    return choice

def game_status_check():
    if len(player_card) == 0 or len(computer_card) == 0:
        print("Game over !")
        return True
    else:
        return False

def printout_cards():
    print("######################################\n")
    print("Player card: " + str(player_card))
    print("\n######################################\n")
    print("Computer card: " + str(computer_card))

def end_game():
    answer = input("Do you want to restart the game [y or n] ?: ")
    if answer == "y":
        main()
    elif answer == "n":
        print("Thank you for playing ! ")
        exit()
    else:
        print("Enter y or n !")

def main():
    while not game_status_check():
        printout_cards()
        random_number = random_choice(number_pool)
        print("Random lotto is: {}".format(random_number))
        answer = input("Do you want to cross out number [y or n]: ")
        if answer == "y":
            player_card.remove(random_number)
            if random_number in computer_card:
                computer_card.remove(random_number)
        elif answer == "n":
            if random_number in player_card:
                print("The number was in your card, you missed it and lost !")
                end_game()
            elif random_number in computer_card:
                computer_card.remove(random_number)
        os.system("cls")
        game_status_check()

if __name__ == '__main__':
    main()


texts: Best way to create SVG from database? (Using PHP)

texts:
I've got a SQL database that keeps track of which services a client has.  I need to create an image using SVG that only displays the services that the client has.  The database stores the services in the format 1,2,3,6,7,9.  Here's what I have:

 <?php
    header("Content-type: image/svg+xml");
    $db = new PDO(**[redacted]**);
    $grabServices = $db->prepare("SELECT services FROM *** where name= :name");
    $grabServices->execute(array(":name" => "test" ));
    $services = $grabServices->fetchAll();
    $services = explode(",", $services[0][services]);
    var_dump($services);
?>

//snip...

<?php if(in_array(1, $services)){?>
    <line x1="820" y1="120" x2 ="790" y2="180" class="SaaS"/>
<?php }?>
<?php if(in_array(2, $services)){?>
    <line x1="905" y1="180" x2 ="700" y2="370" class="PM"/>
<?php }?>
//etc, etc,

This seems incredibly tedious to me.  The only other way I can think to do this would have all the SVG elements created in a PHP array, but that seems even more wasteful.  Is there a better way to do this?


texts:
I've implemented merge sort an integer array. Is it okay to use i,j,k as variable name for looping? Should I change them to more meaningful names? Overall, any further suggestions on this code?

MergeSort.java

import java.util.Arrays;

public class MergeSort {

    public static void main(String[] args) {

    }

    public static void mergeSort(int[] inputArray) {
        int size = inputArray.length;
        if (size < 2)
            return;
        int mid = size / 2;
        int leftSize = mid;
        int rightSize = size - mid;
        int[] left = new int[leftSize];
        int[] right = new int[rightSize];
        for (int i = 0; i < mid; i++) {
            left[i] = inputArray[i];

        }
        for (int i = mid; i < size; i++) {
            right[i - mid] = inputArray[i];
        }
        mergeSort(left);
        mergeSort(right);
        merge(left, right, inputArray);
    }

    public static void merge(int[] left, int[] right, int[] arr) {
        int leftSize = left.length;
        int rightSize = right.length;
        int i = 0, j = 0, k = 0;
        while (i < leftSize && j < rightSize) {
            if (left[i] <= right[j]) {
                arr[k] = left[i];
                i++;
                k++;
            } else {
                arr[k] = right[j];
                k++;
                j++;
            }
        }
        while (i < leftSize) {
            arr[k] = left[i];
            k++;
            i++;
        }
        while (j < leftSize) {
            arr[k] = right[j];
            k++;
            j++;
        }
    }
}

MergeSortTest.java

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;

public class MergeSortTest {

    @Test
    public void reverseInput(){
        int[] arr={22,21,19,18,15,14,9,7,5};
        MergeSort.mergeSort(arr);
        assertEquals("[5, 7, 9, 14, 15, 18, 19, 21, 22]", Arrays.toString(arr));

    }
    @Test
    public void emptyInput(){
        int[] arr={};
        MergeSort.mergeSort(arr);
        assertEquals("[]", Arrays.toString(arr));
    }

    @Test
    public void alreadySorted(){
        int[] arr={1,2,3,4,5,6,7,8,9,10};
        MergeSort.mergeSort(arr);
        assertEquals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", Arrays.toString(arr));
    }

}


texts:
I'm a bit new to working with Numba, but I got the gist of it. I wonder if there any more advanced tricks to make four nested for loops even faster that what I have now. In particular, I need to calculate the following integral:

$$
G_B(\mathbf X, T) = \Lambda \int_\Omega G(\mathbf X, \mathbf X', T) W(\mathbf X', T) \ d\mathbf X' \\
G(\mathbf X, \mathbf X', T) = \frac{1}{2\pi S_0^2} \exp\left[-\frac{\left| \mathbf X -\mathbf X'\right|^2}{2[S_0(1+EB(\mathbf X, T))]^2}\right]
$$

Where \$B\$ is a 2D array, and \$S_0\$ and \$E\$ are certain parameters. My code is the following:

import numpy as np
from numba import njit, double

def calc_gb_gauss_2d(b,s0,e,dx):
    n,m=b.shape
    norm = 1.0/(2*np.pi*s0**2)
    gb = np.zeros((n,m))
    for i in range(n):
        for j in range(m):
            sigma = 2.0*(s0*(1.0+e*b[i,j]))**2
            for ii in range(n):
                for jj in range(m):
                    gb[i,j]+=np.exp(-(((i-ii)*dx)**2+((j-jj)*dx)**2)/sigma)
            gb[i,j]*=norm
    return gb

calc_gb_gauss_2d_nb = njit(double[:, :](double[:, :],double,double,double))(calc_gb_gauss_2d)

For and input array of size 256×256 the calculation speed is:

In [4]: a=random.random((256,256))

In [5]: %timeit calc_gb_gauss_2d_nb(a,0.1,1.0,0.5)
The slowest run took 8.46 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 1min 1s per loop

Comparison between pure Python and Numba calculation speed give me this picture:

Is there any way to optimize my code for better performance?


texts: Django turn ChoiceField into a submit button

texts:
I have made a ChoiceField into a select and submit button and wondered if this is the correct approach.

forms.py

class PortfolioForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(PortfolioForm, self).__init__(*args, **kwargs)

        portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]

        self.fields['portfolios'] = forms.ChoiceField(
                    widget=forms.Select(),
                    choices=portfolios,
                    required=False,
                    )

views.py

class PortfolioView(View):

    form_class = PortfolioForm
    template_name = 'portfolio.html'

    def get(self, request):
        form = self.form_class()

        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(self.request.POST)

        if form.is_valid():
            selected_portfolio = form.cleaned_data.get('portfolios')
            print(selected_portfolio)
            form = self.form_class(initial={'portfolios': selected_portfolio})

        else:
            form = self.form_class(initial={'portfolio_name': ''})

        return render(self.request, self.template_name, {'form': form})

and most of the trickery in the template. I use elements of form.portfolios to make the buttons, but it seems I have to include form.portfolios in the template to make it all work. In order not to show I put this in a hidden  tag.

{% block content %}
  <form id="id_portfolio" method="post">
    {% csrf_token %}
    {{ form.portfolios }}
    {% for portfolio in form.portfolios %}

      {% if portfolio.data.selected %}
        <button type="button">{{ portfolio.choice_label }}</button>

      {% else %}
        <button type="submit" value="{{ portfolio.data.value }}"
          name="{{ portfolio.data.name }}">{{ portfolio.choice_label }}</button>

      {% endif %}

    {% endfor %}
{% endblock content %}


texts:
I'm new to programming in Python, and I am trying to create a multiplication exercise generator. I've got the following code for the solution, but I'm wondering if there is any more elegant solutions than this one.
Note: I have not covered lists, tuples, or dictionaries as of yet so I'm using the absolute basics to create this program.

#solution.py
#A script that allows a student to learn multiplication using the random
#module. Answers will be made and the script must display to try again
#or to present the next questions.

from random import randrange
answer = 0

def generate_question() :
    global answer

    #Random numbers
    number_one = randrange(1, 13)
    number_two = randrange(1, 13)

    #Correct answer
    answer = number_one * number_two

    #Display question
    print "What is %d times %d?" % (number_one, number_two)

def check_answer(user_input) :
    global answer

    #Answer check
    if user_input == answer :
        print "Very good!"
        generate_question()
    else :
        print "Try again!"

#Script Section
generate_question()

while True :
    #Answer to question
    user_input = int(raw_input("Answer: "))
    check_answer(user_input)


texts:
I wrote the following implementation of the k-nearest neighbor algorithm (for a binary classification task). I am not familiar with OCaml's built in functions, I have the feeling that some of them somehow reinvent the wheel :

predict should just return the most common label among the neighbors, which would make the method more generic
finding the indices of the smallest elements get_smallest_elements_i of an array should not require that much coding !
Defining let sum a b = a +. b in to call it in Array.fold seems really clumsy

Is there a more idiomatic syntax for the following operations ?

let get_smallest_elements_i input_array k =
  let n = Array.length input_array in
  let indices = Array.init n (fun x -> x) in
  for i = 0 to (k-1) do
    for j = (n-1) downto 1 do
      if input_array.(indices.(j-1)) > input_array.(indices.(j)) then begin
        let b = indices.(j-1) in
        indices.(j-1) <- indices.(j);
        indices.(j) <- b;
      end
    done;
  done;
  Array.sub indices 0 k ;;

let find_nearest_neighbours current_point all_points k distance =
  let distances = Array.map (fun x -> distance x current_point) all_points in
  get_smallest_elements_i distances k ;;

let predict nearest_neighbours labels =
  let sum a b = a +. b in
  let k = Array.length nearest_neighbours in
  if Array.fold_left sum 0. (Array.init k (fun i -> labels.(nearest_neighbours.(i)))) > 0. then 1. else ~-.1. ;;

An example of (Euclide) distance that can be fed to the algorithm is the following :

let euclide_distance x y =
  let sum a b = a +. b in
  let squares_diff = Array.init (Array.length x) (fun i -> (x.(i) -. y.(i))**2.) in
  Array.fold_left sum 0. squares_diff ;;

Note : I am using OCaml 4.02, but I could upgrade it to 4.03, especially for the Array.map2 methods.


texts:
How can I refactor this with less code? This is homework and is cracking a Caesar cipher-text using frequency distribution.

I have completed the assignment but would like it to be cleaner.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define TEXT_SIZE 100000  // Note, the longer the text the more likely you will get a good decode from the start.
#define ALEN 26         // Number of chars in ENGLISH alphabet
#define CHFREQ "ETAONRISHDLFCMUGYPWBVKJXQZ" // Characters in order of appearance in English documents.
#define ALPHABET "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

/* Decode the given text using the given map and store the result in newtext */
void decode_text(char* text, char* newtext, char map[][2]) {
int i, j;

for (i = 0; i < strlen(text); i++) {
    // If the current character in text is not a letter, copy it to newtext as punctuation and digits should be maintained.
    if (!isalpha(text[i])) {
        newtext[i] = text[i];
        continue;
    }
    for (j = 0; j < ALEN; j++) {
        if (text[i] == map[j][1]) {
            newtext[i] = map [j][0];
        }
    }
}
}

char upcase(char ch){
    if(islower(ch))
    ch -= 'a' - 'A';
  return ch;
}

int main(int argc, char **argv){

// first allocate some space for our input text (we will read from stdin).

char* text = (char*)malloc(sizeof(char)*TEXT_SIZE+1);
char textfreq[ALEN][2];
char map[ALEN][2];
char newtext[TEXT_SIZE];
char ch, opt, tmpc, tmpc2;
int i, j, tmpi;

// Check the CLI arguments and extract the mode: interactive or dump and store in opt.

if(!(argc == 2 && isalpha(opt = argv[1][1]) && (opt == 'i' || opt == 'd'))){
    printf("format is: '%s' [-d|-i]\n", argv[0]);
    exit(1);
}

// Now read TEXT_SIZE or feof worth of characters (whichever is smaller) and convert to uppercase as we do it.

for(i = 0, ch = fgetc(stdin); i < TEXT_SIZE && !feof(stdin); i++, ch = fgetc(stdin)){
    text[i] = (isalpha(ch)?upcase(ch):ch);
}
text[i] = '\0'; // terminate the string properly.

// Assign alphabet to one dimension of text frequency array and a counter to the other dimension
for (i = 0; i < ALEN; i++) {
    textfreq[i][0] = ALPHABET[i];
    textfreq[i][1] = 0;
}

// Count frequency of characters in the given text
for (i = 0; i < strlen(text); i++) {
    for (j = 0; j < ALEN; j++) {
        if (text[i] == textfreq[j][0]) textfreq[j][1]+=1;
    }
}

//Sort the character frequency array in descending order
for (i = 0; i < ALEN-1; i++) {
    for (j= 0; j < ALEN-i-1; j++) {
        if (textfreq[j][1] < textfreq[j+1][1]) {
            tmpi = textfreq[j][1];
            tmpc = textfreq[j][0];
            textfreq[j][1] = textfreq[j+1][1];
            textfreq[j][0] = textfreq[j+1][0];
            textfreq[j+1][1] = tmpi;
            textfreq[j+1][0] = tmpc;
        }
    }
}

//Map characters to most occurring English characters
for (i = 0; i < ALEN; i++) {
    map[i][0] = CHFREQ[i];
    map[i][1] = textfreq[i][0];
}

// Sort the map lexicographically
for (i = 0; i < ALEN-1; i++) {
    for (j= 0; j < ALEN-i-1; j++) {
        if (map[j][0] > map[j+1][0]) {
            tmpc = map[j][0];
            tmpc2 = map[j][1];
            map[j][0] = map[j+1][0];
            map[j][1] = map[j+1][1];
            map[j+1][0] = tmpc;
            map[j+1][1] = tmpc2;
        }
    }
}

if(opt == 'd'){
    decode_text(text, newtext, map);
} else {
// do option -i
}

// Print alphabet and map to stderr and the decoded text to stdout
fprintf(stderr, "\n%s\n", ALPHABET);
for (i = 0; i < ALEN; i++) {
    fprintf(stderr, "%c", map[i][1]);
}
printf("\n%s\n", newtext);

return 0;
}


texts:
This a little pagination script that I am writing "Object Oriented" and I have no idea how to set the current page equal to total page, if the current page is greater.  I also would really like it if anyone can tell me how to improve my code.

class pagination extends Db_connection {

    public $per_page;
    public $current_page;
    public $sql;

    //put your code here
    function __construct($per = 3, $current = 1) {
        parent::__construct();
        $this->per_page = $per;
        $this->current_page = $current;
    }

    function execute_query($sql) {
        $this->sql = $sql;
        $q = $this->query($sql);
        return $q;
    }

    function total_pages() {
        $total = ceil($this->count_rows() / $this->per_page);
        return $total;
    }

    function current_page() {
        if (isset($_GET['page']) && is_numeric($_GET['page']))
            $this->current_page = intval($_GET['page']);

        return $this->current_page;
    }

    function offset() {
        $off = ($this->current_page() - 1) * $this->per_page;
        return $off;
    }
    public function previous_page(){
        //move to previous record by subtracting one into the current record
        return  $this->current_page - 1;
    }
    public function next_page(){
        //mvove to next record by incrementing the current page by one
        return  $this->current_page + 1;

    }

    function count_rows() {
        $nums = mysqli_fetch_row($this->execute_query("select count(post_id) from Post"));
        return $nums[0];
    }

    function results() {
        $off = $this->offset();
        $per = $this->per_page;
        $query = $this->execute_query("Select * from Post limit $off, $this->per_page");
        while ($result = mysqli_fetch_array($query)) {
            $data[] = $result;
        }
        return $data;
    }
}


texts:
I recently wrote an entry on my blog regarding unit testing using prime numbers as an example.

When I wrote the entry, I wrote my code keeping in minding that proposal SE-0007 has been accepted for Swift 3.0.  That is, C-style for loops will no longer be available in Swift as of 3.0, so I want to completely discontinue using them.

That is to say, where I might have written something like this:

for(int divisor = 7; divisor * divisor <= value; divisor += 30) {

I was instead stuck with some real ugliness in my prime loop.

func isPrime(value: Int) -> Bool {
    if value < 2 { return false }
    if value % 2 == 0 { return value == 2 }
    if value % 3 == 0 { return value == 3 }
    if value % 5 == 0 { return value == 5 }
    if value == 7 { return true }

    var divisor = 7
    while divisor * divisor <= value {
        if value % divisor == 0 { return false }
        if value % (divisor + 4) == 0 { return false }
        if value % (divisor + 6) == 0 { return false }
        if value % (divisor + 10) == 0 { return false }
        if value % (divisor + 12) == 0 { return false }
        if value % (divisor + 16) == 0 { return false }
        if value % (divisor + 22) == 0 { return false }
        if value % (divisor + 24) == 0 { return false }
        divisor += 30
    }

    return true
}

I am satisfied that this code works as I want.  I am also satisfied that is runs extraordinarily fast.

What I do not like about this is the very round-about way I have to achieve the same behavior a C-style for loop would have given me.  In particular, it is the termination point that concerns me.  I could easily get the same loop steps with the stride function:

for divisor in 7.stride(through: value, by: 30) {

But this doesn't allow for the same early stopping point:

divisor * divisior <= value

And making the first line of the loop check this isn't much better:

for divisor in 7.stride(through: value, by: 30) {
    if divisor * divisor > value { break }

And the biggest problem with the while loop which I'd like reviewed is that the divisor variable has a scope larger than I'd like, and the update statement doesn't come until the very end of the while loop (a problem that becomes more complex if your loop has any continue statements in it anywhere that allow iterations to break out early and jump to the next iteration).

So, in the end, I want a very, very fast isPrime() checker (it should be at least as fast as the above code), but I'd like the ugliness of my while loop to be significantly cleaned up.


texts: 8051 RFID reader for Atmel microcontroller

texts:
I am currently using an AT89S52 microcontroller for a major project that involves a use of an RFID reader that outputs data in a serial format (9600 baud, no parity, 8 data bits, 1 stop bit).

The only hardware UART embedded in the microcontroller is used for other purposes and I don't want to redesign my circuit board or pay higher dollars only for a second hardware UART so my only option is to use a software UART.

I made a routine employing the software UART technique that is able to constantly read data from an RFID card module. Fortunately I am able to read the data correctly (example: the 1st and last bytes of the data packet are correct).

The problem I have with this code is that it is synchronous because of all the halting loops (see the DJNZ lines).

The card reader (#RDM6300) produces at least 13 bytes of data per card.

Each bit at 9600bps is 0.1ms. which is 1.0ms/byte (due to adding the start and stop bit) which is 13.5ms delay for all 13 bytes (provided the reader module sends them all at once). I want to somehow modify my code so that I have a lower delay (1-2ms is more tolerable). There are also buttons on the board that users may press very fast and I don't want the buttons to appear frozen (unresponsive) only because the system is stuck in the middle of reading an RFID card.

What can I do to my code to improve it so that the required delay isn't large?

  ; crystal used = 22.1184Mhz
  ; micro used = AT89S52
  ; 1 clock cycle = 12 oscillator cycles

  ; Took calculation partly from
  ; https://www.8051projects.net/wiki/8051_Software_UART_Tutorial
  ; 1 bit time = (((crystal/baud)/12) - 5) / 2
  ; 1 bit time = ((22118400/9600/12) - 5) / 2 = 187
  ; was told on a forum to use half as full bit time...
  ; 187/2 = 93.5 = 5Dh
  ; 1/2 = 93.5 / 2 = 46.75 = 2Eh
  ; 1/2 bit time seemed to read correct data

  BITTIM equ 05Dh ;1 bit time for 9600 baud
  BITTIMH equ 2Eh ;1/2 bit time
  RX equ Px.x ;serial data

  main:

; -- insert asynchronous function here --

initserial:

;wait for serial start (data=0)
jb RX,$

;wait 1/2 bit time
mov R2,#BITTIMH
djnz R2,$

;If data isn't zero after 1/2 bit time
;we assume out of sync and start over
jb RX,initserial

mov R3,#8h ;setup to read 8 bits
clr A      ;and clear byte

readnextbit:

  ;wait 1 full bit time
  mov R2,#BITTIM
  djnz R2,$

  ;add 1 clock cycle waiting time (about .5uS)
  ; -- I'm trying to align data here --
  nop

  ;get bit and shift into accumulator
  mov C,RX
  RRC A

  ;continue until all 8 bits are read
DJNZ R3,readnextbit
;result stored in accumulator
  sjmp main


texts:
I am using ExcelDataReader to import an Excel file to a dataset.

Example Excel table:

//ID     Name     Display Order    Active
//1      John          1             1

ID, DisplayOrder and Active columns are read as double, so I have to convert them to long, int and bool types respectively. I need to create a list of type Category from the DataTable of the DataSet.

Will this code perform well? Any suggestions for a faster conversion of DataTable to List of class?

var list = result.Tables["Categories"].AsEnumerable()
.Skip(1)
.Select(dr =>
        new Category
            {
                Id = Convert.ToInt64(dr.Field<double>("ID")),
                Name = dr.Field<string>("Name"),
                DisplayOrder = Convert.ToInt32(dr.Field<double>("Display Order")),
                IsActive= dr.Field<double>("Active") == 1 ? true : false
            }
        ).ToList();


texts: General select statement to stored procedures

texts:
I'm trying to write a general function to several specific stored procedures, but I'm afraid that it will cause errors that I don't see now. The function is to get the name of the stored procedure as a string, and get a list of objects that contain the parameters of the stored procedure. Does it look good to you?

public static DataTable SelectQuery(string storedProcedureName, List<object> parameters)
    {
        DataTable dt = new DataTable();
        OleDbConnection con = WorkerDB.GetConnection();
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandText = storedProcedureName;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = con;
        for (int i = 0; i < parameters.Count; i++)
        {
            cmd.Parameters.AddWithValue("?", parameters[i]);
        }
        try
        {
            con.Open();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            da.Fill(dt);
            da.Dispose();
        }
        catch (Exception ex)
        {

            throw ex;
        }
        finally
        {
            con.Close();
        }

        return dt;
    }


texts:
How can I make this program run faster?  On enter, I have a string from the console.  For example:

1 1 7 3 2 0 0 4 5 5 6 2 1

On exit, it will be

6 20

Could you recommend a way to make this run faster?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        ArrayList<Integer> _arr = new ArrayList<Integer>();
        while((line=br.readLine())!= null){
                StringTokenizer tok = new  StringTokenizer(line);
                while (tok.hasMoreTokens()) {
                    _arr.add((Integer.parseInt(tok.nextToken())));
                }
            }
        Algorithm(_arr);
    }
    private static void Algorithm(ArrayList<Integer> arr) {
        int ascLength = 1,
            descLength = 1,
            ascSequenceStart = 0,
            descSequenceStart = 0,
            ascLongest = 1,
            descLongest = 1,
            summa = 0,
            tmp1, tmp2;
        for (int i = 1; i<arr.size(); i++) {
            tmp1 = arr.get(i-1);
            tmp2 = arr.get(i);
            if(tmp2>tmp1){
                ascLength++;
                descLength = 1;
            } else if (tmp2<tmp1) {
                descLength++;
                ascLength = 1;
            } else if (tmp1==tmp2){
                descLength++;
                ascLength++;
            }
            if (ascLength > ascLongest) {
                ascLongest = ascLength;
                ascSequenceStart = i - ascLength + 1;
            }
            if (descLength > descLongest) {
                descLongest = descLength;
                descSequenceStart = i - descLength + 1;
            }
        }
        if (ascLongest > descLongest) {
            for (int i = ascSequenceStart; i < (ascSequenceStart+ascLongest); i++) {
                summa += arr.get(i);
            }
            System.out.print(String.valueOf(ascLongest)+" "+String.valueOf(summa));
        } else {
             for (int i = descSequenceStart; i < (descSequenceStart+descLongest); i++) {
                 summa += arr.get(i);
             }
             System.out.print(String.valueOf(descLongest)+" "+String.valueOf(summa));
        }
    }
}


texts:
I have been coding Java for 5+ years and before that did a little professional C. Picking up C++ again for the fun of it and I feel like I am just writing Java in C++ rather than understanding the C++ way of doing things.

Anyway, I wanted some thoughts on my simple little class to make sure I am C++ing right.

This is my header:

#pragma once

#include <iostream>

#include <SDL.h>
#include <SDL_image.h>

class ImageResource final
{
    SDL_Surface* surface;

public:
    ImageResource(std::string& path);
    ~ImageResource();

    SDL_Surface* get_surface();
};

This is the implementation:

#include "ImageResource.h"
#include <SDL.h>
#include <SDL_image.h>

ImageResource::ImageResource(std::string& path)
{
    this->surface = IMG_Load(path.c_str());
    if (this->surface == NULL)
    {
        throw std::runtime_error{ std::string{"Unable to load image: "} + path };
    }
}

ImageResource::~ImageResource()
{
    SDL_FreeSurface(this->surface);
}

SDL_Surface * ImageResource::get_surface()
{
    return this->surface;
}

Things I don't know if I am doing right are const correctness (actually I am pretty sure I am doing it wrong because nothing is const), exception throwing, and general style. Any other comments are welcome.


texts: Preliminary draft of a data structure for a goodies tracker

texts:
My girlfriend and I are making a goodies tracker to enable us to keep better track of our stamp/gift cards. Right now we've got a super simple Object with some fields of what a stamp card has, and no support for modifying its fields (yet). I want to get some tips on if this is bad or good code, if there are any glaring bugs, and if possible if you'd know any good ways to look at how to integrate similar Objects like gift card and stamp card (inheritance, or composition?)

There are some dependencies which you can choose if you want to download. I'll include the output of the code here:

# -*- coding: utf-8 -*-
from tabulate import tabulate
# TODO: Put the dependencies into a venv so that it's easy to install
# TODO: add the amount of stamps we currently have vs. the stamp_capacity

class StampCard:
    # A stamp card for an establishment which contains a name and a capacity
    # Authors: Cody Antonio Gagnon & Chuan-Li Ojales Chang

    def __init__(self, card_name, card_description, stamp_capacity,
                 stamp_symbol, redeemable_location):
        """
        Initialize the stamp card with a:
            name
            description
            capacity
            symbol for stamping
            location to be redeemed
        """
        self.name = card_name
        self.description = card_description
        self.stamp_capacity = stamp_capacity
        self.stamp_symbol = stamp_symbol
        self.location = redeemable_location

    def get_name(self):
        """
        Return the name of the stampcard
        """
        return self.name

    def get_description(self):
        """
        Return the description of the stampcard
        """
        return self.description

    def get_capacity(self):
        """
        Return the capacity as a string.
        """
        return str(self.stamp_capacity)

    def get_symbol(self):
        """
        Return the capacity as a string.
        """
        return self.stamp_symbol

    def get_location(self):
        """
        Return the redeemable location as a string.
        """
        return self.location

    def print_stamps(self):
        """
        Print the stamps using the typical two-row approach.
        """
        stamps = []
        stamps_per_row = self.stamp_capacity / 2  # hardcoded rows for now...
        for x in range(1, 3):
            stamps.append([self.stamp_symbol] * stamps_per_row)
        print (tabulate(stamps, tablefmt="grid").encode('utf8', 'replace'))  # takes a list of lists or another tabular data type as the first argument, and outputs a nicely formatted table

def main():
    stamp = unicode("", 'utf8')
    oasis = StampCard("Oasis", "Bubble Tea", 10, stamp, "University District")
    print("Name: " + oasis.get_name() + ", Capacity: " + oasis.get_capacity())
    oasis.print_stamps()

main()


texts:
I have written a Python program to loop through a list of X files, open each one, read line by line, and write (append) to an output file. Being that these files are several GB each, it is taking very long.

I am looking for suggestions to improve the performance of this program. I have no formal CS training so it's likely I am missing the "obvious solution" to this problem; I have done some research but again, my limited knowledge (and other higher priority tasks) limits my ability to implement such.

for name in PR_files:
    with open(PR_path + name, 'r') as f:
        line = f.readline()
        while line:
            with open(PR_out_path, 'a') as g:
                g.write(line + '\n')
                line = f.readline()
    f.close()

The program will work but will have a blank line between each line in the output text file; this is because the first line of the next file began on the last line of the previous file (my solution to this problem was to add '\n' to each line being written to the output file. For that reason I wrote another block to remove all blank lines in the output file (yes I know, very inefficient).

# this removes all blank lines from out put file
with open(PR_out_path) as this, open(PR_out_path_fix, 'w') as that:
    for line in this:
        if not line.strip():
            continue
        that.write(line)

PLEASE NOTE: I attempted to do this, as oppose to reading line by line but I received a MemoryError.

with open(PR_out_path, 'a') as g:
    for name in PR_files:
        with open(PR_path + name, 'r') as f:
            g.write(f.read())


texts:
Currently, the code will generate a range of natural numbers from 1 to N and store it in a list. Then the program will iterate through that list, marking each multiple of a prime as 0 and storing each prime in a secondary list.

This is a translation of a TI-Basic program, shown here, so the same description still applies.

Here's an animation:

One of the main optimizations that I want to see implemented would be the actual removal of prime multiples from the list instead of simply setting them to 0. As it is currently written, this would be a challenge to perform without adding in another if statement. Any suggestions would be helpful.

def sieve(end):
    prime_list = []
    sieve_list = list(range(end+1))
    for each_number in range(2,end+1):
        if sieve_list[each_number]:
            prime_list.append(each_number)
            for every_multiple_of_the_prime in range(each_number*2, end+1, each_number):
                sieve_list[every_multiple_of_the_prime] = 0
    return prime_list

Here's a link to PythonTutor, which will visualize the code in operation.


texts: Doubly circular link list implementation

texts:
I am supposed to be creating a doubly circular linked list, but I am now have problems creating the actual linked list. Is there a problem with the classes? Also, for the assignment, the list is suppose to be a template class, but now I just want to get the code to work.

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

using namespace std;
//template <class Object>

//template <class Object>
class Node
{
    //friend ostream& operator<<(ostream& os, const Node&c);
public:
    Node( int d=0);
    void print(){
        cout<<this->data<<endl;
    }
//private:
    Node* next;
    Node* prev;
    int data;

    friend class LinkList;
};
Node::Node(int d):data(d)
{

}

//template <class Object>
class LinkList
{
void create();
public:
    //LinkList();
    LinkList():head(NULL),tail(NULL),current(NULL)
    {create();}
    int base;
    //LinkList(const LinkList & rhs, const LinkList & lhs);
    ~LinkList(){delete current;}

    const Node& front() const;//element at current
    const Node& back() const;//element following current
    void move();
    void insert (const Node & a);//add after current
    void remove (const Node &a);
    void print();
private:
    Node* current;//current
    Node* head;
    Node* tail;
};

void LinkList::print()
{
    Node *nodePt =head->next;
    while(nodePt != head)
    {
        cout<<"print function"<<endl;
        cout<<nodePt->data<<endl;
        nodePt=nodePt->next;
    }
}
//element at current

void LinkList::create()
{
    current = head = tail = new Node(0);
    current->next = current->prev = current;
}

const Node& LinkList::back()const
{
    return *current;
}
//element after current
const Node& LinkList::front() const
{
    return *current ->next;
}

void LinkList::move()
{
    current = current ->next;
}
//insert after current
void LinkList :: insert(const Node& a)
{
    Node* newNode= new Node();
    newNode->prev=current;
    newNode->next=current->next;
    newNode->prev->next=newNode;
    newNode->next->prev=newNode;
    current=newNode;
}
void LinkList::remove(const Node& a)
{
    Node* oldNode;
    oldNode=current;
    oldNode->prev->next=oldNode->next;
    oldNode->next->prev=oldNode->prev;
    delete oldNode;
}

//main file
#include <iostream>
#include <string>
#include <iomanip>
#include <stdio.h>
#include "LinkedList.h"

using namespace std;

int main()
{
    int n;
    cout<<"How many Nodes would you like to create"<<endl;
    cin>>n;

    LinkList list1 ;

    list1.print();
    for(int loop = 0;loop < n;++loop)
    {
        list1.insert(loop);
    }
    list1.print();
}


texts: Constructing a lexicon and frequency array from a long string

texts:
I have a dataset X_train, which is an array where each entry is an email (a string of characters). There are 11,314 emails, each of which is about 500 characters long. (X_train is a processed version of the training data in the newsgroups dataset.)

Ultimately, my goal is to build from scratch a tf-idf function (knowledge of which is probably not necessary for answering my question). To get there, I have constructed a lexicon which contains each unique word in X_train once and only once. My lexicon has 211441 elements. I also need an array where each entry frequency_train[i] is the number of emails in which a given term lexicon_train[i] appears.

I construct the frequency array as follows:

frequency_train = np.zeros(211441)
for i in range(211441):
    count = 0
    for email in X_train:
        if lexicon_train[i] in email:
           count = count + 1
    frequency_train[i] = count

In the same cell, I am also doing something similar with the testing data X_test. I've been running this in Jupyter notebook, and this process takes a while. A previous and very similar task took about 90 minutes. I suspect that I'm doing this task the slowest possible way. Is there a faster way of doing this? I would also welcome answers that explain why this process should take a long time.


texts:
I have this method which successfully sorts the incoming dictionary alphabetically:

private Dictionary<string, string> sortMacroDictionary(Dictionary<string, string> whichDictionary) {
    Dictionary<string, string> sortedDictionary = new Dictionary<string, string>();
    List<string> tempList = new List<string>();
    string outValue;

    if (whichDictionary.Count > 0) {
        foreach (var entry in whichDictionary) {
            tempList.Add(entry.Key);
        }

        tempList.Sort();

        foreach (string entry in tempList) {
            if (whichDictionary.TryGetValue(entry, out outValue)) {
                sortedDictionary.Add(entry, outValue);
            }
        }
    }

    return sortedDictionary;
}

It works as intended and I am not experiencing any issues with it. I'm just wondering if there is a way to improve this method? Maybe there are some issues with my current code that I haven't foreseen?


texts: Is this a workable UnitOfWork with Repository pattern design?

texts:
I am building a web app with using UOW and Repository pattern. I have seen many different samples and found each one to be different, so not sure which is the correct way to go. I have a basic understanding of both these patterns and I wanted to know if I should keep one UOW implementation for all the tables in my project or keep a separate one as per functionality like for:

public interface IHomeUOW
{
    IGenericRepository<User> Users { get; }
    IGenericRepository<TableA> Table_A { get; }
    IGenericRepository<TableB> Table_B{ get; }
}

public interface IBusinessCaseUOW
{

    IGenericRepository<TableA> Table_A { get; }
    IGenericRepository<TableXYZ> Table_XYZ{ get; }
}

As you can see, TableA is available in both Home UOW as well as a particular business case UOW. One UOW partially implemented as below:

public class UnitOfWork : IUnitOfWork
{

    private readonly ObjectContext _context;
    private UserRepository _userRepository;

    public UnitOfWork(ObjectContext Context)
    {

        if (Context == null)
        {
            throw new ArgumentNullException("Context wasn't supplied");
        }
        _context = Context;
    }

    public IGenericRepository<User> Users
    {
        get
        {
            if (_userRepository == null)
            {
                _userRepository = new UserRepository(_context);
            }

            return _userRepository;
        }
    }
 }

My repositories will be like so

public interface IGenericRepository<T>
    where T : class
    {
        //Fetch records
        T GetSingleByRowIdentifier(int id);
        T GetSingleByRowIdentifier(string id);

        IQueryable<T> FindByFilter(Expression<Func<T, bool>> filter);

        // CRUD Ops
        void AddRow(T entity);
        void UpdateRow(T entity);
        void DeleteRow(T entity);

    }

    public abstract class GenericRepository<T> : IGenericRepository<T>
            where T : class
    {
        protected IObjectSet<T> _objectSet;
        protected ObjectContext _context;

        public GenericRepository(ObjectContext Context)
        {
            _objectSet = Context.CreateObjectSet<T>();
            _context = Context;
        }

        //Fetch Data
        public abstract T GetSingleByRowIdentifier(int id);
        public abstract T GetSingleByRowIdentifier(string id);

        public IQueryable<T> FindByFilter(Expression<Func<T, bool>> filter)
        {
            //
        }

        //CRUD Operations implemented

    }

   public class UserRepository : GenericRepository<User>
   {
         public UserRepository(ObjectContext Context)
         : base(Context)
         {
         }

         public override User GetSingleByRowIdentifier(int id)
         {
          //implementation
         }

         public override User GetSingleByRowIdentifier(string username)
         {
          //implementation
         }
   }

What do you think? If this is not the correct implementation of UOW and Repository pattern for DDD, will it fail as just a bunch of code written to abstract the call to the EF tables?


texts: Tesing a simple calculator class with JUnit/JMock

texts:
I'm playing around with JMock and trying to understand whether I understand the idea correctly.

There's an interface Printer aimed to print integers somewhere. There's an interface Calculator aimed to perform math. There's a class CalculatingMachine aimed to connect Calculator and Printer: first, it calculates the result with Calculator and then this result is passed to Printer. Here's the code

public class CalculatingMachine {
    private final Printer printer;
    private final Calculator calculator;

    public CalculatingMachine(Printer printer, Calculator calculator) {
        this.printer = printer;
        this.calculator = calculator;
    }

    public void processAdd(int x, int y) {
        int result = calculator.add(x, y);
        printer.print(result);
    }

    public static interface Printer {
        void print(int x);
    }

    public static interface Calculator {
        int add(int x, int y);
    }
}

As far as I understand CalculatingMachine only requires one test: we need to make sure IT USES calculator to do the math and then we need to make sure IT USES printer to print the result. So, here's my test:

public class CalculatingMachineTest {
    @Test
    public void testCalculatingMachine() {
        Mockery context = new JUnit4Mockery();

        final Printer printer = context.mock(Printer.class);
        final Calculator calculator = context.mock(Calculator.class);

        context.checking(new Expectations() {{
            oneOf(calculator).add(1, 2);
            will(returnValue(3));

            oneOf(printer).print(3);
        }});

        CalculatingMachine machine = new CalculatingMachine(printer, calculator);
        machine.processAdd(1, 2);

        context.assertIsSatisfied();
    }
}

Pretty straightforward and does what it supposed to do. There are 2 points I'm curious about:

Is it the right approach even though CodePro says that CalculatingMachine itself has 19 lines of code, though test for it is 23 lines of code? I'm just not sure: is it normal to write more tests then code that does something?
Is there any other way to test all the same but with less code?


texts: Manipulating CSV files to regular text file

texts:
At my job, often I have to manually convert *.csv Files structured like:

number,number\n
number,number\n
number,number\n
...

To a regular *.txt file with the structure:

#1
double filename(number of columns, number of columns)
 number number
 number number
 number number
 ...

This file is an input to another program, and rather than spending the time to copy and paste the excel sheet into notepad and crop out all the commas and make sure there are spaces and such I decided to write a python script that would do it for me.

Now, to be fair, I am new to Python, and this script works perfectly (first try), I would just like some feedback on my methods, or ways to improve my quality of code.

# A simple program to create a formatted text file from a *.csv file.

csv_file = input('Enter the name of your input file: ')
txt_file = input('Enter the name of your output file: ')

try:
    my_input_file = open(csv_file, "r")
except IOError as e:
    print("I/O error({0}): {1}".format(e.errno, e.strerror))

if not my_input_file.closed:
    text_list = [];
    for line in my_input_file.readlines():
        line = line.split(",", 2)
        text_list.append(" ".join(line))
    my_input_file.close()

try:
    my_output_file = open(txt_file, "w")
except IOError as e:
    print("I/O error({0}): {1}".format(e.errno, e.strerror))

if not my_output_file.closed:
    my_output_file.write("#1\n")
    my_output_file.write("double({},{})\n".format(len(text_list), 2))
    for line in text_list:
        my_output_file.write("  " + line)
    print('File Successfully written.')
    my_output_file.close()


texts:
This time I made a quiz game, in which the player is asked questions and receives points for each question answered correctly. Some people told me I should learn about classes, so this is what I came up with.

import random
from Quiz_Questions import game_questions

questions = [*game_questions]
def game():
    print('-' * 20)
    player_score = 0
    right_answers = 0
    wrong_answers = 0
    while len(questions) > 0:
        question = random.choice(questions)
        questions.remove(question)
        print(question.text)
        user_answer = input('Insert answer (Yes or No): ')
        while user_answer not in ['yes', 'y', 'f', 'true', 'no', 'n', 'f', 'false']:
            print('Sorry, that is an invalid answer')
            user_answer = input('Please insert another answer (Yes or No): ')
        if user_answer.lower() in question.correct_answer:
            player_score += question.question_reward
            right_answers += 1
            print('You got it right! (+{} points)'.format(question.question_reward))
            print('You have {} points'.format(player_score))
        else:
            wrong_answers += 1
            print('You got it wrong, good luck next time!')
        print('-' * 20)
    print('Congratulations! You have answered all the questions!')
    print('Your final score is {} points'.format(player_score))
    print('You answered {} questions right'.format(right_answers))
    print('And {} questions wrong.'.format(wrong_answers))
game()

Quiz_Question.py

class Question():
    def __init__(self, text, correct_answer, question_reward):
        self.text = text
        if correct_answer == 'True':
            self.correct_answer = ['yes', 'y', 'f', 'true']
        elif correct_answer == 'False':
            self.correct_answer = ['no', 'n', 'f', 'false']
        self.question_reward = question_reward
game_questions = [Question('Russia has a larger surface area than Pluto.', 'True', 7),
                  Question('There are as many stars in space than there are grains of sand on every beach in the world.', 'False', 5),
                  Question('For every human on Earth there are 1.6 million ants.', 'True', 8),
                  Question('On Jupiter and Saturn it rains diamonds.', 'True', 9),
                  Question('Scotland’s national animal is the phoenix.', 'False', 4),
                  Question('A banana is a berry.', 'True', 8),
                  Question('An octopus has three hearts.', 'True', 4),
                  Question('There are 10 times more bacteria in your body than actual body cells.', 'True', 9),
                  Question('Rhode Island is the closest US state to Africa.', 'False', 3),
                  Question('Shakespeare made up the name “Sarah” for his play Merchant of Venice.', 'False', 3)]


texts: Comparing each item from dir with each item from another dir

texts:
The task is to compare students homework SQL files with mentors SQL files.

I've written two functions, which return a two-dimensional array (1st elements are an absolute path, 2nd are a relative).

Then I'm going to compare the relative path of students and mentors and execute SQL files (finding using absolute path) if these values are equal

Is there a more elegant implementation?

The folder structure of mentors dir:

Homework (folder)
  ├ 1 (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql
  ├ 2 (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql
  ├ n (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql

The folder structure of students dir:

├Students Homework (folder)
 ├Student1(folder)
  ├ 1 (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql
  ├ 2 (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql
  ├ n (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql
 ├Student2(folder)
  ├ 1 (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql
  ├ 2 (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql
  ├ n (folder)
  | ├ 1.sql
  | ├ 2.sql
  | └ n.sql

"Mentors" function:

def find_mentors_sql(config):

    mentors_sql_abs = []
    mentors_sql_rel = []

    for dirpath, subdirs, files in walk(config["MAIN_DIR"] + '\\Homework'):
        mentors_sql_abs.extend(path.join(dirpath, x) for x in files if x.endswith(".sql"))
        mentors_sql_rel.extend(path.join(path.basename(dirpath), x) for x in files if x.endswith(".sql"))

    mentors_sql = [[0] * 2 for i in range(len(mentors_sql_abs))]

    iter = 0
    for _ in mentors_sql_abs:
        mentors_sql[iter][0] = mentors_sql_abs[iter]
        iter += 1

    iter1 = 0
    for _ in mentors_sql_rel:
        mentors_sql[iter1][1] = mentors_sql_rel[iter1]
        iter1 += 1

    return mentors_sql

"Students" function (the logic is similar to the previous one:

def find_students_sql(config):

    students_sql_abs = []
    students_sql_rel = []

    for dirpath, subdirs, files in walk(config["MAIN_DIR"] + '\\Students Homework'):
        students_sql_abs.extend(path.join(dirpath, x) for x in files if x.endswith(".sql"))
        students_sql_rel.extend(path.join(path.basename(dirpath), x) for x in files if x.endswith(".sql"))

    students_sql = [[0] * 2 for i in range(len(students_sql_abs))]

    iter = 0
    for _ in students_sql:
        students_sql[iter][0] = students_sql_abs[iter]
        iter += 1

    iter1 = 0
    for _ in students_sql:
        students_sql[iter1][1] = students_sql_rel[iter1]
        iter1 += 1

    return students_sql
```


texts: OOD for reverse polish notation calculator

texts:
I am new to OOD and trying to implement a notation calculator in java with OOD concept, attached is my code. It works but I have feeling it's not good especially the factory method is not good. I will really grateful if you have any suggestion about revise the structure of code:

public class PolishNotationCalculator {
    public interface Token{
        public void func(Stack<Token> st);
    }

    class Operand implements  Token{
        private  int val;
        public Operand(String v){
            this.val = Integer.parseInt(v);  //should catch exception?
        }

        public int getVal(){
            return val;
        }

        public void func(Stack<Token> st){
            st.push(this);
        }
    }

    class Operator implements Token{
        public void func(Stack<Token> st){
            return;
        }
    }

    class Add extends Operator{
        public void func(Stack<Token> st){
            Operand o1 = (Operand)st.pop();
            Operand o2 = (Operand)st.pop();
            st.push(new Operand(""+(o1.getVal()+o2.getVal())));
        }
    }

    class Sub extends Operator{
        public void func(Stack<Token> st){
            Operand o1 = (Operand)st.pop();
            Operand o2 = (Operand)st.pop();
            st.push(new Operand(""+(o1.getVal()-o2.getVal())));
        }
    }

    class Mul extends Operator{
        public void func(Stack<Token> st){
            Operand o1 = (Operand)st.pop();
            Operand o2 = (Operand)st.pop();
            st.push(new Operand(""+(o1.getVal()*o2.getVal())));
        }
    }

    class Div extends Operator{
        public void func(Stack<Token> st){
            Operand o1 = (Operand)st.pop();
            Operand o2 = (Operand)st.pop();
            st.push(new Operand(""+o1.getVal()/o2.getVal()));
        }
    }

    class Factory{
        private Map<String, Operator> hm = new HashMap<>();
        public Factory (){
            hm.put("+", new Add());
            hm.put("-", new Sub());
            hm.put("*", new Mul());
            hm.put("/", new Div());
        }
        public Operand create(String s){
            return new Operand((s));
        }
    }

    Stack<Token> st = new Stack();
    public static void main(String[] args){
        PolishNotationCalculator pc = new PolishNotationCalculator();
        //["2", "1", "+", "3", "*"]
        String [] in = new String[5];
        in[0]="2"; in[1]="1"; in[2]="+"; in[3]="3"; in[4]="*";
        System.out.println(pc.RPN(in));
    }

    public int RPN(String[] rpn){
        Factory factory = new Factory();
        for(String s: rpn){
            if(factory.hm.containsKey(s))
                factory.hm.get(s).func(st);
            else factory.create(s).func(st);
     //super cast to child is impossible,call the empty func...how to fix?
        }
        return ((Operand)st.pop()).getVal();
    }
}


texts:
Below is my solution for this 'Team Split' problem.

In summary, the problem is to find relative strength of 2 teams by finding the difference between their total strength (individual strengths can be found using a quadratic expression of form ax2+bx+c).

The solution in Java manages to solve the problem, but I am regularly getting the Time Limit Exceeded issue.

Can anyone offer advice on how to reduce the complexity of this code?

import java.util.*;
import java.io.*;

public class Main {
    public static void main (String args[]) throws IOException{
        try{
            BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
            int not=Integer.parseInt(sc.readLine());
            int a,b,c,d;
            for(int i=0;i<not;i++){
                String s[]=sc.readLine().trim().split(" ");
                int r=Integer.parseInt(s[0]);
                a=Integer.parseInt(s[1]);
                b=Integer.parseInt(s[2]);
                c=Integer.parseInt(s[3]);
                d=Integer.parseInt(s[4]);
                long S[]=new long [r];
                S[0]=d;
                for(int k=1;k<r;k++){
                    S[k]=((a*S[k-1]*S[k-1])+(b*S[k-1])+c)%1000000;
                    //System.out.println(S[k]);
                }
                Arrays.sort(S);
                long so1=0;
                long so2=0;
                long t;
                for(int p=r-1,q=r-2;p>=0;p=p-2,q=q-2){
                    if(q>=-1){
                        so1=so1+S[p];
                        if(q>=0){
                            so2=so2+S[q];
                        }
                    }
                }
                // System.out.println(so1);
                // System.out.println(so2);
                t=so1-so2;
                if(t<0){
                    t=(-1)*t;
                }
                System.out.println(t);
                //sc.close();
            }
        }catch(NumberFormatException afe){
            System.out.println(afe);
        }
    }
}


texts: Swapping dynamically populated images on hover/touch

texts:
I'm using jQuery to swap images on hover. There's a main image, and a gallery of thumbs. When the thumb is hovered over/touched, the larger version of it populates the main image, and the smaller version of the original populates the thumb. This happens via swapping src and data- attributes.

This all works, but being relatively new to JS/jQuery, the code is probably a little clunky and could use a keener eye. I don't fully grasp callbacks (among other JS things) yet, so I imagine there'll be some streamlining/chuckling with that.

function large_to_thumb(imageHovered, mainLarge, mainThumb){
    $(imageHovered).attr('src', mainThumb).data('large', mainLarge);
}

function thumb_to_large(image, mainLarge, mainThumb){
    var mainImage = $('.main-image');
    // 1. put gallery image data-large into .main-large src
    mainImage.attr('src', $(image).data('large'));

    // 2. put gallery image src into .main-large data-gallery-image
    mainImage.data('gallery-image', $(image).attr('src'));
    large_to_thumb(image, mainLarge, mainThumb);
}

$('.product-gallery img').on('mouseenter touch', function(){
    var mainLarge = $('.product-image .main-image').attr('src');
    var mainThumb = $('.product-image .main-image').data('gallery-image');
    thumb_to_large(this, mainLarge, mainThumb);
});
li {
  display:inline;
}


texts: Packet process time simulation using queue

texts:
Here is my code for the below packet time simulation problem using queue. My code works correctly but it's slow, please help with suggestions to improve run time and other suggestions for performance improvement.

Problem: You are given a series of incoming packets in an array of [t_a, t_d] pairs (one pair for each packet) where t_a is arrival time of the packet and t_d is the processing time required for that packet. The processor has a buffer with a fixed size and when full, packets are dropped. For each packet, output either the start of process time or -1 if the packet is dropped. Processor only processes one packet at the time and packet arrival times are non-decreasing.

eg. input of [ [0, 2], [1, 4], [5, 3] ] with buffer size of 2 gives output equal to [0, 2, 6].

def process_packets(packets, buffSize):
    # base case for packet size or buffSize == 0
    if packets == [] or buffSize == 0:
        return []
    # initializing parameters:
    # ts_te is array of [ts,te] pairs where ts = start of packet process time
    # and te = end of packet process time
    # length of ts_te array is treated as buffer size
    ts_te = [  [ packets[0][0], packets[0][0] + packets[0][1] ]  ]
    # results is either start of packet process time (if packet makes it to buffer)
    # or -1 for packets when buffer is full at their arrival time
    results = [ ts_te[0][0] ]

    # since first packet is processed in initialization, I remove it
    packets = packets[1:]

    for packet in packets:
        packetArr = packet[0]
        packetDur = packet[1]
        # processor's start time is either end of last packet in buffer or
        # new packet's arrival time, whichever is bigger
        startTime = max ( ts_te[-1][1], packetArr )

        # removing all packets that have been processed from buffer when new
        # packet arrives
        for elem in ts_te:
            if packetArr >= elem[1]:
                ts_te.pop(0)

        # if there is room in the buffer, add new packets [ts,te] information
        # and append process time start to result
        if len(ts_te) < buffSize:
            ts_te.append( [startTime , startTime+packetDur] )
            results.append(startTime)
        else:
            results.append(-1)

    return results


texts: Finding root of strictly monotonic function by bisection

texts:
I need to find a root of strictly monotonic function f (only raising or only lowering). There is only a one root of a function.
If given range from a to b doesn't contain root (fabs(f(a)*f(b) is not lower or equal than 0), we need to change range, since the assumption is that there is a one root, so we need to move on x-axis to left or right and check again, if f(a).
If it is, then (f)*f(b) (e.g (-3)*2=-6, and that means there is a root between a and b).

I've made an solution and I would like to improve performance in terms of changing ranges (obviously adding +2 is not good for huge functions) vs halving ranges further, when finding f(c).

What would be the best strategy?
Also will there be any other problem to look on?
What can I do to avoid user epsilon to be smaller than DBL_EPSILON?
Any ideas to improve my code?

#include <iostream>
#include <cmath>

double f(double x)
{
    //double y = std::pow(2, x) - 6;
    double y = x - 10000;
    return y;
}

bool isRaising(double a, double b)
{
    if (f(a) > f(b)) return false;
    return true;
}

bool areBothNumbersPositive(double a, double b)
{
    if (f(a) > 0 && f(b) > 0) return true;
    return false;
}

void moveLeft(double &a, double &b)
{
    b = a;
    a = a - 2;
}

void moveRight(double& a, double& b)
{
    a = b;
    b = b + 2;
}

void changeRanges(double &a, double &b)
{
    if (!isRaising(a, b))
    {
        if (areBothNumbersPositive(a, b))
        {
            moveRight(a, b);
        }
        else
        {
            moveLeft(a, b);
        }
    }
    else
    {
        if (areBothNumbersPositive(a, b))
        {
            moveLeft(a, b);
        }
        else
        {
            moveRight(a, b);
        }
    }
}

double findRoot(double a, double b, double epsilon)
{
    if (epsilon < DBL_EPSILON) epsilon = DBL_EPSILON;
    if (a == b) throw std::exception("Range must be higher than zero!");

    double c;
    if (std::fabs(f(a)) < epsilon) return a;
    if (std::fabs(f(b)) < epsilon) return b;

    while (f(a) * f(b) > 0)
    {
        changeRanges(a, b);
    }
    if (std::fabs(f(a)) < epsilon) return a;
    if (std::fabs(f(b)) < epsilon) return b;
    do
    {
        c = (a + b) / 2;
        if (f(a) * f(c) > 0) a = c;
        else b = c;
    } while (!(std::fabs(f(c)) < epsilon));
    return c;
}

int main()
{
    //f(a) * f(b) > 0
    std::cout << findRoot(-100,  -300,   0.00000000001) << std::endl;
    std::cout << findRoot(100, 300, 0.00000000001) << std::endl;
    std::cout << findRoot(-300, -100,  0.00000000001) << std::endl;
    std::cout << findRoot(300, 100,  0.00000000001) << std::endl;

    //f(a) * f(b) <= 0
    std::cout << findRoot(-100, 300, 0.00000000001) << std::endl;
    std::cout << findRoot(100, -300, 0.00000000001) << std::endl;
    std::cout << findRoot(300, -100, 0.00000000001) << std::endl;
    std::cout << findRoot(-300, 100, 0.00000000001) << std::endl;
}