texts: Load balancing consumer and producer with multiprocessing

texts:
Tasks are distributed to producer in multiple worker process. Results from workers are sent through Queue to a Consumer at the main process. The consumer uses less time per task than the worker.

The manual counting of tasks seems unsatisfying ... Can imap or anything else make that simpler?

By the way, I guess my rough representation of time for hard disk reading is not quite correct because hard disk reads are buffered.

import multiprocessing as mp
import time
from datetime import datetime

def log(msg):
    d = datetime.utcnow().strftime('%M:%S.%f')[:-3]
    print(d + ' %s' % msg)

def main():
    n_proc = 3
    p = mp.Pool(n_proc)
    m = mp.Manager()
    q = m.Queue()
    size = 20
    c = Consumer(q, size, n_proc)
    for i in range(size):
        log("Main Loop %d" % i)
        # 0.01 sec for (buffered) reading of hard-disk for arrays.
        # values are not 0, 1, 2 ... in the actual program.
        hd_arr = i  # "array from hard disk"
        time.sleep(0.1)
        p.apply_async(producer, args=(hd_arr, q))
        c.invoke()
    log("Processsing remaining tasks")
    p.close()
    p.join()
    c.flush()
    log(c.data)

def producer(x, q):
    time.sleep(1)
    result = (x, x*x)
    q.put(result)

class Consumer():
    def __init__(self, queue, size, n_proc):
        self.queue = queue
        # 1.0 / (0.1 + 0.1) = 5
        self.lb_factor = 5 * n_proc
        self.data = [None] * size
        self.task_count = 0

    def invoke(self, task_increment = 1):
        log("  Consumer checks:")
        self.task_count += task_increment
        if self.task_count == self.lb_factor:
            self.flush()

    def flush(self):
        log("    # Consumer flushes #")
        for i in range(self.task_count):
            x, x2 = self.queue.get()
            self.data[x] = x2
            time.sleep(0.1)
        self.task_count = 0

if __name__ == "__main__":
    main()

Result:

32:45.796 Main Loop 0
32:45.896   Consumer checks:
32:45.897 Main Loop 1
32:45.997   Consumer checks:
32:45.997 Main Loop 2
32:46.098   Consumer checks:
32:46.098 Main Loop 3
32:46.198   Consumer checks:
32:46.199 Main Loop 4
32:46.299   Consumer checks:
32:46.299 Main Loop 5
32:46.400   Consumer checks:
32:46.400 Main Loop 6
32:46.500   Consumer checks:
32:46.500 Main Loop 7
32:46.601   Consumer checks:
32:46.601 Main Loop 8
32:46.701   Consumer checks:
32:46.701 Main Loop 9
32:46.802   Consumer checks:
32:46.802 Main Loop 10
32:46.903   Consumer checks:
32:46.903 Main Loop 11
32:47.003   Consumer checks:
32:47.003 Main Loop 12
32:47.104   Consumer checks:
32:47.104 Main Loop 13
32:47.204   Consumer checks:
32:47.205 Main Loop 14
32:47.305   Consumer checks:
32:47.305     # Consumer flushes #
32:51.243 Main Loop 15
32:51.343   Consumer checks:
32:51.344 Main Loop 16
32:51.444   Consumer checks:
32:51.444 Main Loop 17
32:51.545   Consumer checks:
32:51.545 Main Loop 18
32:51.645   Consumer checks:
32:51.646 Main Loop 19
32:51.746   Consumer checks:
32:51.746 Processsing remaining tasks
32:53.497     # Consumer flushes #
32:54.001 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

Simulation of Multiple Producer Consumer: Setting the boundary between consumer, producer, and monitor.


texts: Pairwise swap elements of a given linked list by changing links

texts:
GeeksForGeeks challenge:

  Given a singly linked list, write a function to swap nodes pairwise.

  For example :

  if the linked list is 1->2->3->4->5->6->7 then the function should
  change it to 2->1->4->3->6->5->7, and if the linked list is
  1->2->3->4->5->6 then the function should change it to
  2->1->4->3->6->5

#include <iostream>

// structure of a Node in the linked list
struct Node {
    int data;
    Node *next;
};

// append data to end of linked list
Node *append(Node *head, int data) {
    auto newNode = new Node{data, nullptr};
    if (head == nullptr)
        return newNode;

    auto temp{head};
    while (temp->next)
        temp = temp->next;
    temp->next = newNode;

    return head;
}

//  display the list

void display(Node *head) {
    std::cout << "The list : \t";
    while (head != nullptr) {
        std::cout << head->data << " ";
        head = head->next;
    }
    std::cout << std::endl ;
}

//  pairwise swap of the elements in the given linked lists
void pairwiseSwap(Node **head_ref) {

    if(((*head_ref) == nullptr) || ((*head_ref)->next == nullptr))
        return ;

    Node *temp1 = nullptr, *temp2 = nullptr ;
    Node *prev = nullptr, *curr =(*head_ref) ;

    while(curr != nullptr) {

        //  temp1 : first element of the pair
        //  temp2 : second element of the pair
        temp1 = curr;
        temp2 = curr->next;

        //  if the the 2nd element in the pair is nullptr, then exit the loop
        if(temp2 == nullptr){
            break ;
        }
//      curr = curr->next->next ;

        //  if the current element is head, then previous one must be nullptr
        //  In either case swapping the nodes
        if(prev == nullptr){
            prev = temp1;
            temp1->next = temp2->next;
            temp2->next = temp1;
            (*head_ref) = temp2 ;
        }
        else {
            temp1->next = temp2->next;
            temp2->next = temp1;
            prev->next = temp2;
            prev = temp1;
        }

        //  moving to the next pair of nodes
        curr = temp1->next ;
    }
}

//  Driver function
int main() {
    Node *a = nullptr ;

    // for odd number of nodes
    a = append(a, 15);
    a = append(a, 10);
    a = append(a, 5);
    a = append(a, 20);
    a = append(a, 3);
//  a = append(a, 2);

    pairwiseSwap(&a);

    display(a);

   // for even number of nodes
    a = append(a, 15);
    a = append(a, 10);
    a = append(a, 5);
    a = append(a, 20);
    a = append(a, 3);
    a = append(a, 2);

    pairwiseSwap(&a);

    display(a);
}


texts:
I've tried to solve AoC day 2 challenge in Haskell (here - don't worry, it's not a competition so sharing a solution here is OK).

The goal is to implement a very simple VM with opcodes 1 (add), 2 (mult) and 99 (exit).

I feel like my solution is incredibly verbose. That maybe be because I rely heavily on the state monad (my background is imperative programming, so there's that). Is there anything I could improve without rewriting the whole solution?

Here's my code, thanks for all suggestions:

import Data.Sequence
import Control.Monad.State
import Data.List.Split

data Machine = Machine {
    mState :: Seq Int,
    mPos :: Int,
    isDone :: Bool
}

opReadHead :: State Machine Int
opReadHead = do
    machine <- get
    return $ index (mState machine) (mPos machine)

opReadAt :: Int -> State Machine Int
opReadAt target = do
    machine <- get
    return $ index (mState machine) target

opForward :: State Machine ()
opForward = do
    machine <- get
    put $ machine { mPos = mPos machine + 1 }

opWrite :: Int -> Int -> State Machine ()
opWrite target what = do
    machine <- get
    put $ machine { mState = update target what (mState machine) }

opReadNext :: State Machine Int
opReadNext = do
    a <- opReadHead
    opForward
    return a

opAdd :: State Machine ()
opAdd = do
    aPtr <- opReadNext
    a <- opReadAt aPtr
    bPtr <- opReadNext
    b <- opReadAt bPtr
    target <- opReadNext
    opWrite target (a + b)

opMult :: State Machine ()
opMult = do
    aPtr <- opReadNext
    a <- opReadAt aPtr
    bPtr <- opReadNext
    b <- opReadAt bPtr
    target <- opReadNext
    opWrite target (a * b)

opExit :: State Machine ()
opExit = do
    current <- get
    put $ current { isDone = True }

isMachineDone :: State Machine Bool
isMachineDone = do
    get >>= (return . isDone)

opcode :: Int -> State Machine ()
opcode 1 = opAdd
opcode 2 = opMult
opcode 99 = opExit

opExecuteNext :: State Machine ()
opExecuteNext = do
    opValue <- opReadNext
    opcode opValue

runCode :: State Machine ()
runCode = do
    done <- isMachineDone
    if done
    then return ()
    else opExecuteNext >> runCode

evalWith :: Machine -> Int -> Int -> Int
evalWith machine noun verb = do
    fst $ runState (do
        opWrite 1 noun
        opWrite 2 verb
        runCode
        opReadAt 0
        ) machine

main :: IO()
main = do
    fileData <- readFile "input"
    let memory = map read $ splitOn "," fileData
    let machine = Machine {
        mState = fromList memory,
        mPos = 0,
        isDone = False
    }
    let outputs = [(evalWith machine x y, (x, y)) | x <- [0..99], y <- [0..99]]
    print $ snd $ head $ Prelude.filter ((== 19690720) . fst) outputs
```


texts: Determine a list contains two elements with a given sum

texts:
On interview I was asked to write method with following contract:

boolean checkList(List<Long> list, long sum){...}

for example it has to return true for arguments:
 ({1,2,3,4,5,6}, 9)  because 4+5 = 9

and it have to return false for arguments:

({0,10,30}, 11)  because there are no combination of 2 elements with sum 11

I suggested code like this:

boolean checkList(List<Long> list, long expectedSum) {
    if (list.size() < 2) {
        return false;
    }
    for (int i = 0; i < list.size() - 1; i++) {
        for (int k = i; k < list.size(); k++) {
            if ((list.get(i) + list.get(k)) == expectedSum) {
                return true;
            }
        }
    }
    return false;
}

But interviewer asked me to improve the solution. How?


texts:
This is my first attempt to model a day's time interval and the fact that the start and end are either inclusive or not:

public class UtcTimeOfDay
{
    public int HourOfDay { get; set; }
    public int MinuteOfDay { get; set; }
    public int SecondOfDay { get; set; }
}

public class UtcTimeInterval
{
    public UtcTimeOfDay StartUtcTimeOfDay { get; set; }
    public UtcTimeOfDay EndUtcTimeOfDay { get; set; }
    public bool StartInclusive { get; set; }
    public bool EndInclusive { get; set; }
}

Any suggestions for improvement?


texts: Allocating a contiguous block of memory for an array

texts:
I try to work with a contiguous block of memory, to create an array (2D) whose SIZE is not known at compile time (before c99) so no variable-length arrays are involved here.

I came up with the following:

#include <stdio.h>
#include <stdlib.h>

int main(void){
    unsigned int row, col,i, j, k;
    int l = 0;
    int *arr;

    printf("Give the ROW: ");
    if ( scanf("%u",&row) != 1){
        printf("Error, scanf ROW\n");
        exit(1);
    }

    printf("Give the COL: ");
    if ( scanf("%u",&col) != 1){
        printf("Error, scanf COL\n");
        exit(2);
    }

    arr = malloc(sizeof *arr * row * col);
    if(arr == NULL){
        printf("Error, malloc\n");
        exit(3);
    }

    for ( i = 0; i < row ; i++){
        for ( j = 0 ; j < col ; j++){
            arr[i * col + j] = l;
            l++;
        }
    }

    for (k = 0 ; k < (row * col) ; k++){
        printf("%d ",arr[k]);
    }

    free(arr);
}

Which gives me the following:

Give the ROW: 6
Give the COL: 3
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

Is this the right approach?


texts:
This is an implementation of Quick Sort in JS. Can this implantation of Quick Sort be more concise and efficient while still remaining expressive?

function quickSort(list){
   if( list.length < 2 ) {
    return list;
}
var leftList = [];
var rightList = [];
for( var i = 1; i < list.length; i++ ){
    if(list[i] >= list[0]){
       rightList.push(list[i]) ;
    }else{
       leftList.push(list[i]);
    }
}

var sortedLeft = quickSort(leftList);
var sortedRight = quickSort(rightList);
var combined = sortedLeft.concat(list[0]).concat(sortedRight);
console.log(combined.join(' '));
return combined;
}

var array=[9,8,7,6,5,4,3,2,1];
quickSort(array);

Example 2 works with randomly selected pivots, filters, and recursion. This example is more efficient than the first while still remaining as just as expressive. Unfortunately, both perform horribly compared to in place and nonrecursive approaches.

function quicksort(arr,len=arr.length) {
    if (len <= 1) return arr;
        else
        var randomIndex = Math.floor(Math.random() * len),
        pivot = arr.splice(randomIndex, 1),
        lesserHalf = arr.filter(el =>el <= pivot)
        biggerHalf = arr.filter((el)=> el > pivot)
        return ((lesserHalf, pivot, biggerHalf) =>
        [].concat(quicksort(lesserHalf), pivot, quicksort(biggerHalf)))
        (lesserHalf, pivot, biggerHalf)
}

var arr =[9,8,7,6,5,4,3,2,1];
console.log(quicksort(arr));

Example 3 is the shortest I've seen using spread and inspired by Haskel

const quickSort = ([x = [], ...xs]) => {
  if (x.length === 0) return [];
  return [
    ...quickSort(xs.filter(y => y <= x)),
    x,
    ...quickSort(xs.filter(y => y > x))
  ];
}

var arr= [9,8,7,6,5,4,3,2,1];

console.log(quickSort(arr))


texts: Extracting opening and closing times for each day of the week

texts:
I have these two methods:

private static OpeningDay GetUsallyOpeningHour(List<OpeningDay> openingHoursDaily, DayOfWeek dayOfWeek)
{
    var listOfSpecificDayOfWeek = openingHoursDaily.Where(x => x.DateTime.DayOfWeek == dayOfWeek);

    if(listOfSpecificDayOfWeek.Any())
        return listOfSpecificDayOfWeek.GroupBy(x => x.From).OrderByDescending(x => x.Count()).ThenByDescending(x => x.Key).First().First();

    return new OpeningDay { From = new TimeSpan(0, 0, 0), To = new TimeSpan(0, 0, 0), DateTime = DateTime.Now };
}

private static OpeningDay GetUsallyClosingHour(List<OpeningDay> openingHoursDaily, DayOfWeek dayOfWeek)
{
    var listOfSpecificDayOfWeek = openingHoursDaily.Where(x => x.DateTime.DayOfWeek == dayOfWeek);

    if (listOfSpecificDayOfWeek.Any())
        return listOfSpecificDayOfWeek.GroupBy(x => x.To).OrderByDescending(x => x.Count()).ThenByDescending(x => x.Key).First().First();

    return new OpeningDay { From = new TimeSpan(0, 0, 0), To = new TimeSpan(0, 0, 0), DateTime = DateTime.Now };
}

The only difference between them is that one is grouping by x.From and other by x.To, and I was wondering how I can improve this code.

Basically, I can a create method which takes lambda, but how long? At first I was thinking to pass this:

GroupBy(x => x.To).OrderByDescending(x => x.Count()).ThenByDescending(x => x.Key)

as a lambda parameter. But this would take me ending with function that takes a lambda and then returns sth like lambda.First().First().

What do you recommend? Are there some other improvements?


texts:
Recently I started to learn Haskell. I did this by making exercises on the Internet. The problem of making these exercises is that I never know if I solved it the correct way. I currently wrote a function which I think looks really ugly, but I don't know how to improve it. I hope that someone could give me some tips to improve it.

In this exercise I need to make a Tic-Tac-Toe game.

The question of the function I wrote is as follows:

  Exercise 8. Write a function moves :: Player -> Board -> [Board] that,
  given the current player and the current state of the board, returns
  all possible moves that player can make expressed as a list of
  resulting boards. (For now, you should continue making moves, even if
  one of the players has already won.)

I wrote the following code:

moves :: Player -> Board -> [Board]
moves p ((a,b,c),(d,e,f), (g,h,i)) = (moves' a (((symbol p),b,c), (d,e,f), (g,h,i))) ++
                                     (moves' b ((a,(symbol p),c), (d,e,f), (g,h,i))) ++
                                     (moves' c ((a,b,(symbol p)), (d,e,f), (g,h,i))) ++
                                     (moves' d ((a,b,c), ((symbol p),e,f), (g,h,i))) ++
                                     (moves' e ((a,b,c), (d,(symbol p),f), (g,h,i))) ++
                                     (moves' f ((a,b,c), (d,e,(symbol p)), (g,h,i))) ++
                                     (moves' g ((a,b,c), (d,e,f), ((symbol p),h,i))) ++
                                     (moves' h ((a,b,c), (d,e,f), (g,(symbol p),i))) ++
                                     (moves' i ((a,b,c), (d,e,f), (g,h,(symbol p))))

moves' :: Field -> Board -> [Board]
moves' c m = if c == B then [m] else []

Is there a way to improve my code?


texts: Optimizing a problem that test all permutations of 1 array with other fixed array

texts:
I'm trying to solve this question on a contest programming judge.

Description of the problem:

  There are N birds in a forest, each in their respective tree. There are N tired crows in this forest, and they wish to land in different trees as soon as possible (crows are extremely quarrelsome and they can't share the same tree). Every Pi minutes, the i-th bird leaves the tree to fly a little bit, and you can consider that it returns immediately. Every Ci minutes, the i-th crow can try to land in a tree which there's no bird or can just keep flying. You can consider that crows are faster than birds and if the bird leaves the tree at the same minute that a crow tries to land in it, the crow will land faster. Given an optimal strategy between the crows, what is the earliest time in which every crow will be relaxing, each one in a different tree?

Description of the input:

  The first line contains an integer T (1 ≤ T ≤ 100), the number of test cases. Each test case starts with an integer N (1 ≤ N ≤ 9), the number of birds and crows. The second line contains N integers Pi (1 ≤ Pi ≤ 10⁴), as described in the problem statement. The third and last line of each test case contains N integers Ci (1 ≤ Ci ≤ 10⁴), as also described in the problem statement.

Description of the output:

  For each test case print “Caso #X: Y”, where X is the number of the current case, starting at 1, and Y is the answer to the problem.

Example of Input:

  2
  2
  1 3
  2 2
  1
  1
  1

Example of output:

  Caso #1: 6
  Caso #2: 1

To solve this problem, I observed that the minimum time of waiting can be obtained with a combination of the birds array with the crows array in which the LCM (least common multiple) would be the minimum one.

My solution generates all permutations of the birds array and compare with the crows array and from all the combinations takes the maximum LCM and for all the maximum LCM choose the minimum one. The limit of this problem is small. This made me think that the solution must be a brute force like this. But my solution is exceeding the time limit.

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

typedef long long lld;

lld gcd(lld a, lld b)
{
    return (b ==  0) ? a : gcd(b, a % b);
}

lld lcm(lld a, lld b){
    return a*b/gcd(a,b);
}

lld permute(lld *birds, lld *crows, lld n, lld index){
    if(index == n){
        //choose the maximum lcm and return it
        lld aux = 1;
        for (int i = 0; i <= n; ++i)
            aux = fmax(aux,lcm(birds[i], crows[i]));
        return aux;
    }

    lld t,ret = LONG_LONG_MAX;
    for (lld i = index; i <= n; ++i) {
        t = birds[index];
        birds[index] = birds[i];
        birds[i] = t;

        //from all combinations ... select the one which has the lowest maximum lcm
        ret = fmin(ret,permute(birds, crows, n, index+1));

        t = birds[index];
        birds[index] = birds[i];
        birds[i] = t;
    }

    return ret;
}

int main(){
    lld t,n,birds[10],crows[10];
    scanf("%lld",&t);
    for (int i = 1; i <= t; ++i) {
        scanf("%lld",&n);
        for (int i = 0; i < n; ++i)
            scanf("%lld",birds+i);

        for (int i = 0; i < n; ++i)
            scanf("%lld",crows+i);

        lld ret = permute(birds, crows, n-1, 0);
        printf("Caso #%d: %lld\n",i,ret);

    }
}

Some people just made it on 0 secs. Is there some way to optimize this?


texts:
I'm trying to wrap my head around OOP, and am fairly new to PHP in general, so please forgive me if the following makes you cringe.

I've decided to try and create a basic database wrapper using PDO. Here's what I've done so far.

class DB {
    protected $db_user = 'root';
    protected $db_pass = '';
    protected $db_host = 'localhost';
    protected $db_name = 'login';

    private $dbh;
    private $sth;

    public function __construct() {
        $this->dbh = new PDO('mysql:host='.$this->db_host.'; dbname='.$this->db_name, $this->db_user, $this->db_pass);
    }

    public function select($get, $table, $where){
        $this->sth = $this->dbh->prepare('SELECT '.$get.' FROM '.$table.' WHERE '.$where);
    }

    public function bindSTR($name, $replacement) {
        $this->sth->bindParam($name, $replacement, PDO::PARAM_STR);
    }

    public function execute(){
        $this->sth->execute();
    }

    public function fetch(){
        return $this->sth->fetch(PDO::FETCH_ASSOC);
    }
}

And here is the usage:

$DB = new DB();
$DB->select('user_id, email', 'users', 'email = :email');
$DB->bindSTR(':email', 'example@domain.com');
$DB->execute();
$results = $DB->fetch();

Now before I go ahead and start adding more functionality to the class, can anyone give me some feedback?

Is this a good way to go?
How can I improve the class?
Any suggestions in general?


texts: Non-recursive implementation of MergeSort

texts:
I've been trying to internalize some of the basic sorting algorithms recently, and to do so I've been looking at their wikipedia pages to refresh myself with how they work, and then coding my own "version" of the algorithm from there.

I did this with MergeSort recently, and I got an algorithm that for what I can tell works but I'm not sure it runs in \$O(n \log{n})\$ time like MergeSort does.

def mergeSortAlgorithm(x):

    listOfLists = []

    for i in range(len(x)):
        temp = [x[i]]
        listOfLists.append(temp)                          #I first put every item in the array into
                                                      #its own list, within a larger list -> divide step

                                                      #so long as there is more than one sorted list, then we need to keep merging
    while(len(listOfLists) != 1):
        j = 0

                                                      #for every pair of lists in the list of lists, we need to merge them
        while(j < len(listOfLists)-1):
            tempList = merge(listOfLists[j], listOfLists[j+1])
            listOfLists[j] = tempList
            del listOfLists[j+1]                          #I shift the new list to index j, and delete the second list from the now-merged pair at index j+1
            j = j+1                                       #increment the value of j, basically a counter
        print(listOfLists)

    print(listOfLists[0], "is sorted!")

def merge(a, b):                                          #function to merge two lists in order
    newList = []
    count1, count2 = 0, 0

                                                      #basically, walk through each list, adding whichever element is smallest
    while((count1 < len(a)) and (count2 < len(b))):

        if(a[count1] > b[count2]):
            newList.append(b[count2])
            count2 = count2 + 1                           #update the counter along b

        elif(a[count1] < b[count2]):
            newList.append(a[count1])
            count1 = count1 + 1                           #update the counter along a

        elif(a[count1] == b[count2]):                     #if they're equal, add the value from a first
            newList.append(a[count1])
            newList.append(b[count2])
            count1, count2 = count1 + 1, count2 + 1       #update the counter on each

    if(count1 < len(a)):                                  #if the while loop exited with left-over values in a, add them
        for f in range(count1, len(a)):
            newList.append(a[f])
    elif(count2 < len(b)):                                #do the same for b - the values are already in order so you're good
        for k in range(count2, len(b)):
            newList.append(b[k])

    return newList

The algorithm correctly sorts what I give it, but I'm thinking that the runtime is more like \$O(\log{n} * \log{n} * n)\$ because the outer while loop in mergeSortAlgorithm() will do \$log(n)\$ passes, as will the inner while loop, and the merge() algorithm will take in total \$n\$ operations.

Is that right?  If so, in what respect does my algorithm differentiate from MergeSort? (i.e. where am I going wrong?)


texts:
So, I wrote this small library for fast DOM building with API tailored for CoffeeScript

I feel like the code overall can be made better/smaller/faster.

I am also not particularly happy about a few functions, namely:

  # Parses out css classes and id from string like:
  #   p#warning.big.yellow # => p   # attr {"id": "warning", "class": ['big', 'yellow']}
  #   #container           # => div # attr {"id": "container"}
  # @returns node name (e.g. "span")
  dotHashRe = /[.#]/
  parseElem = (elem, attr) ->
    return elem unless dotHashRe.test elem
    attr['class'] ||= []
    attr['class'] = [attr['class']] if typeof attr['class'] == 'string'
    elem     = "div#{elem}" if dotHashRe.test(elem.charAt(0))
    pieces   = elem.split(dotHashRe)
    elemType = pieces.shift()
    pos      = elemType.length
    classes  = attr['class']
    for piece in pieces
      if elem.charAt(pos) == '#'
        attr['id'] = piece
      else
        classes.push(piece)
      pos += piece.length + 1
    delete attr['class'] unless attr['class'].length
    elemType

It is fast, but it looks like the code can be made a lot nicer

The library (~100 LOC with comments): https://github.com/glebm/DOMBrew/blob/master/dombrew.js.coffee

Looking forward to the suggestions! :)


texts:
I have a dataframe:
>>> import pandas as pd
>>> import plotly.express as px
>>> df = pd.DataFrame({
...     'P': ['P1', 'P2', 'P3'],
...     'Q1': [1, 2, 3],
...     'Q2': [3, 1, 2],
... })
>>> df
    P  Q1  Q2
0  P1   1   3
1  P2   2   1
2  P3   3   2
>>>

For each row, I should sort Qx columns in descending order, and than do plots but each Qx column should have the same color. Something like this:
qcols = [col for col in df.columns if col.startswith('Q')]

# I have to define colors in advance
color_dict = {col: color for col, color in zip(
    qcols,
    px.colors.qualitative.Plotly[:len(df)]
)}

for p in df.P.unique():
    # Transformation needed for sorting columns descending
    dfp = df.query("P == @p").set_index('P').T.sort_values(p, ascending=False).T.reset_index().melt(id_vars='P', var_name='Q', value_name='val')
    fig = px.bar(data_frame=dfp, x='Q', y='val', color='Q', color_discrete_map=color_dict, width=300, height=300)
    fig.show()

It looks quite complicated to me.
Can it be done in a simpler way?


texts:
I'm looking for feedback to improve this function. The purpose is to pass a noun and append the appropriate indefinite article ("a" or "an").

A known issue with this code is that it doesn't address words with a vowel sound but a consonant first letter, such as "honor" or "hour". I cannot include 'h' in the list of vowels, though; words like "home" or "horror" have a harder 'h' sound and use the article "a".

function aan ($string) {
    return (
        in_array(
            strtolower(substr($string, 0, 1)),
            array('a','e','i','o','u')
        ) ? 'an' : 'a'
    ).' '.$string;
}

Current output:

print 'Become '.aan('All-access').' member'; // Become an All-access member
print 'Become '.aan('Basic').' member'; // Become a Basic member
print 'It has been '.aan('interesting').' experience'; // It has been an interesting experience


texts: LINQ Query returning all original objects

texts:
I'm just refactoring some code I've come across whilst fixing a bug, but just wanted a quick sanity check to make sure I'm not missing any reason for keeping what I'm going to remove.

The current code:

uxButton.Enabled = ((from a in actions select a).Distinct().Count() == 1);

There really doesn't seem to be a need for the LINQ query, so:

uxButton.Enabled = actions.Distinct().Count() == 1;

Should do the trick, right?


texts: Retrieving mail attachments given criteria with VBA

texts:
Scenario: I (together with great help from SO) finished this piece of code which downloads attachments from an e-mail account (outlook) with VBA.

Issue: Given the internal functioning of the code, and the sheer amount of e-mails to check (more than 800k) the code cannot function in available time. Last time I tried to run it, it went on for 8 days and then just stopped.

Question: Does anyone have any ideas on how to improve the efficiency of this code?

Obs: The code goes through a secondary e-mail account specified (first criteria), loops through the emails if they are from a certain sender (second criteria), opens file ad check if there are worksheets names "alpha" and "beta" (very smart idea given to me in SO, to find the third criteria), and if it does, saves the file in a final location.

Code:

Sub Get_Mail_Attachments()

Application.ScreenUpdating = False

Dim olApp As New Outlook.Application
Dim olNameSpace As Object
Dim olMailItem As Outlook.MailItem
Dim olFolder As Object
Dim olFolderName As String
Dim olAtt As Outlook.Attachments
Dim strName As String
Dim sPath As String
Dim i As Long
Dim j As Integer
Dim olSubject As String
Dim olSender As String
Dim sh As Worksheet
Dim LastRow As Integer

Dim TempFolder As String: TempFolder = VBA.Environ$("TEMP")
Dim wB As Excel.Workbook

'delete content except from row 1
ThisWorkbook.Worksheets("FileNames").Rows(2 & ":" & ThisWorkbook.Worksheets("FileNames").Rows.count).Delete

'set foldername and subject
olFolderName = ThisWorkbook.Worksheets("Control").Range("D10")
olSender = ThisWorkbook.Worksheets("Control").Range("D16")

sPath = Application.FileDialog(msoFileDialogFolderPicker).Show
sPathstr = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)

Set olNameSpace = olApp.GetNamespace("MAPI")

'check if folder is subfolder or not and choose olFolder accordingly
Set olFolder = olNameSpace.Folders("email@email.com").Folders("Inbox")

If (olFolder = "") Then
    Set olFolder = olNameSpace.Folders("email@email.com").Folders("Inbox")
End If

'loop through mails
h = 2
For i = 1 To olFolder.Items.count

'check to see if it is an e-mail
If olFolder.Items(i).Class <> olMail Then
Else
Set olMailItem = olFolder.Items(i)

'check if the search name is in the email subject
    If (InStr(1, olMailItem.Sender, olSender, vbTextCompare) <> 0) Then

        With olMailItem

        For j = 1 To .Attachments.count

            strName = .Attachments.Item(j).DisplayName

'check if file already exists
            If Not Dir(sPathstr & "\" & strName) = vbNullString Then
                strName = "(1)" & strName
            Else
            End If

'Save in temp
            .Attachments(j).SaveAsFile TempFolder & "\" & strName
            ThisWorkbook.Worksheets("FileNames").Range("A" & h) = strName

'Open file as read only
            Set wB = Workbooks.Open(TempFolder & "\" & strName, True)
            DoEvents

'Start error handling
            On Error Resume Next
            Set sh = wB.Sheets("alpha")
            Set sh = wB.Sheets("beta")
            If Err.Number <> 0 Then

'Error = At least one sheet is not detected
            Else

'No error = both sheets found
                .Attachments(j).SaveAsFile sPathstr & "\" & strName
            End If
            Err.Clear
            Set sh = Nothing
            wB.Close
            On Error GoTo 0

            h = h + 1

        Next j

    End With

    End If

End If

Next i

Application.ScreenUpdating = True
MsgBox "Download complete!", vbInformation + vbOKOnly, "Done"

End Sub


texts: Iterating over an object that contains arrays

texts:
I have an object that has an array inside with another object inside.  I iterate over the object and array to print out the first name and last name of the people inside the array of objects.  I am wondering if there is a better way to do this.
Without having to use obj[i].first_name + " " + obj[i].last_name

Here is my code

    var users = {
 'Students': [
     {first_name:  'Michael', last_name : 'Jordan'},
     {first_name : 'John', last_name : 'Rosales'},
     {first_name : 'Mark', last_name : 'Guillen'},
     {first_name : 'KB', last_name : 'Tonel'}
  ],
 'Instructors': [
     {first_name : 'Michael', last_name : 'Choi'},
     {first_name : 'Martin', last_name : 'Puryear'}
  ]
 }
    for(item in users)
    {
        console.log(item);
        var obj = users[item]
        for(var i = 0; i < obj.length; i++)
        {
            var obj2 = obj[i];
      var name = "";
            for(j in obj2)
            {
          name += obj2[j] + " ";
            }
      console.log(name);
      name ="";
        }
    }


texts: Euler's Totient Function in x86 assembly (MASM)

texts:
My task was to implement Euler's totient function, and I'm looking for any and all criticism.

.386
.model flat, stdcall
.stack 4096

ExitProcess PROTO, dwExitCode:DWORD

.code
;------------------------------------------------------------------------------
; _phi@4 (int x)
;
; Calculates Euler's totient function using the product formula.
;
; param:
  x     TEXTEQU <[ebp+8]>       ;integer argument
;
; Exit: The result is stored in eax
;------------------------------------------------------------------------------
_phi@4:
        push    ebp             ; setup stack, save regs
        mov     ebp, esp
        push    ebx
        push    ecx
        push    edx

        mov     ecx, x          ; init result as x

; Consider the prime factors of x and subtract their multiples
; from the result
        mov     ebx, 2          ; initialize loop counter p
L3:     mov     eax, ebx
        mul     ebx
        cmp     DWORD PTR x, eax ; loop if( x >= p * p)
        jnge    endL3;

; Check if p is a prime factor
        cdq
        mov     eax, x
        div     ebx
        cmp     edx, 0          ; if(x % p == 0)
        jne     noprime

;if yes, update x and result
L2:     cdq
        mov     eax, x
        div     ebx
        cmp     edx, 0          ; if(x % p == 0)
        jne     endL2
        mov     x  , eax        ; x /= p
        jmp     L2
endL2:
        cdq
        mov     eax, ecx
        div     ebx
        sub     ecx, eax        ;result -= result / p
noprime:
        inc     ebx
        jmp     L3
endL3:

; If x has a prime factor greater than sqrt(x)
        cmp     DWORD PTR x, 1
        jle     finish
        cdq
        mov     eax, ecx
        div     DWORD PTR x
        sub     ecx, eax
finish:
        mov     eax, ecx

        pop     edx
        pop     ecx
        pop     ebx
        pop     ebp
        ret     4

main:
        push    100
        call    _phi@4
        INVOKE  ExitProcess, 0

        END     main

Is there any way I can make the code more efficient? - possibly with fewer instructions? Also, I'm looking for pointers on style. Is the code readable?


texts: Determine objects to delete from a database

texts:
I have the following method which determines which cars I need to delete from the DB.

private List<CarDTO> BuildCarsToDelete(IList<CarDTO> newCars, IList<CarDTO> existingCars)
{
    var missingCars = new List<CarDTO>();

    var cars = newCars.Select(c => c.CarId);
    var newCarIds = new HashSet<int>(cars);

    foreach (var car in existingCars)
    {
        //If there are no new cars then it had some and they have been removed
        if (newCars.Count() == 0)
        {
            missingCars.Add(car);
        }
        else
        {
            if (!newCarIds.Contains(car.CarId))
            {
                missingCars.Add(car);
            }
        }
    }

    return missingCars;
}

This works as expecting - but if I want to achieve the same functionality for Customers or Apartments of other DTOs I will be copying a pasting the code but only changing the variable names and the Type of DTO around - is there a nicer way possible using generics which would keep the algorithm and logic as it is but allow me to use on any DTO?


texts: Depth First Search (Adjacency List) in JavaScript

texts:
I am trying to implement a DFS search and graphs. How can I make it better?

/**
 * Depth First Search iterative implementation
 * @param: graph to traverse and the starting node
 * @return
 */
let DfsSearch = function(graph,startNode){
        let stack =  [];
        stack.push(startNode);

        while(stack.length >0){
            let node = stack.pop();
             console.log('visiting node',graph[node].value);
            if(graph[node].isVisited == false){

               graph[node].isVisited = true;
                for(currentNode in graph[node].edges){
                    stack.push(graph[currentNode].value);
                }
            }

        }

}

module.exports = DfsSearch;

const  DFSSearch= require('./DFS');
/**
 * @description: outputs a new graph , in form of adjancency list
 * inspired from https://medium.freecodecamp.com/a-gentle-introduction-to-data-structures-how-graphs-work-a223d9ef8837#.4voil9gg6
 */
let makeGraphs = () => {
    let graph = {};

    //add vertex
    graph.addVertex = (node) => {
        graph[node] = { edges: {} };
        graph[node].isVisited = false;
        graph[node].value = node;
    }
    //addedges
    graph.addEdge = (startNode, endNode) => {
        if (graph.contains(startNode) && graph.contains(endNode)) {

            graph[startNode].edges[endNode] = true;
            graph[endNode].edges[startNode] = true;
        }
    }

    //check if it contains the node
    graph.contains = (node) => {
        if (graph[node]) {
            return true;
        }
        else {
            return false;
        }
    }
    graph.removeEdge = (startNode, endNode) => {
        if (graph.contains(startNode) && graph.contains(endNode)) {
            delete graph[startNode].edges[endNode];
            delete graph[endNode].edges[startNode];
        }
    }
    graph.removeVertex = (node) => {
        if (graph.contains(node)) {
            for (connectedNodes in graph[node].edges) {
                graph.removeEdge(node,connectedNodes);
            }
        }
        delete graph[node];
    }
return graph;
}

let dfsGraph = makeGraphs();
dfsGraph.addVertex(1);
dfsGraph.addVertex(2);
dfsGraph.addVertex(3);
dfsGraph.addVertex(4);
dfsGraph.addVertex(5);
dfsGraph.addEdge(1,2);
dfsGraph.addEdge(1,3);
dfsGraph.addEdge(2,4);
dfsGraph.addEdge(2,5)
DFSSearch(dfsGraph,1);
module.exports= makeGraphs();


texts: Loading, parsing, and displaying a JSON file

texts:
I recently have been working on loading a local JSON file parsing it and displaying it using Javascript and I think I got it to where I really like it. I would like to know if anyone knows if there is a "purer" way of doing this using just Javascript without libraries.

<!DOCTYPE html>
<meta charset="UTF-8" />
<input type="file" id="files" name="files" accept=".json"/>
<output id="list"></output>


texts: A few sorting algorithms implemented in C

texts:
I was reading about the elementary sorting algorithms like insertion Sort, selection sort and bubble Sort in Introduction to Algorithms by Cormen and I decided to try and implement it in C.

#include<stdio.h>
#define MAXSIZE 100  //  Maximum number of elements permissible in array

void swap(int*,int*);
void print(int*,int);

int main(void) {
    int arr[MAXSIZE],n,i,j,ch,ord;
    void insertion(int*,int,int),selection(int*,int,int),bubble(int*,int,int);
    printf("\nEnter number of elements for array = ");
    scanf("%d",&n);
    printf("\n\nEnter the array elements one by one : \n\n");
    for(i=0;i<n;i++){
        scanf("%d",&arr[i]);
    }
    printf("\n\nWhat sorting you want to use ?\n\n Insertion (1) , Selection (2) or Bubble (3)\n\nEnter choice = ");
    scanf("%d",&ch);
    printf("\n\nSorting order ? \n\n Ascending (1) or Descending (2)\n\nEnter choice = ");
    scanf("%d",&ord);
    printf("\n\n");
    switch(ch){
        case 1:
            insertion(arr,n,ord);
            break;
        case 2:
            selection(arr,n,ord);
            break;
        case 3:
            bubble(arr,n,ord);
    }
    print(arr,n);
printf("\n\n");
return 0;
}

void swap(int *x,int *y){
    int t=*x;
    *x=*y;
    *y=t;
}

void insertion(int *a,int l,int ord){
    int i,j;
    for(i=1;i<l;i++){
        for(j=i;j>0;j--){
            if((ord==1 && a[j]<a[j-1]) || (ord==2 && a[j]>a[j-1]))
                swap(&a[j],&a[j-1]);
            else
                break;
        }
    }
}

void selection(int *a,int l,int ord){
    int index,i,j;
    for(i=0;i<l;i++){
        index=i;
        for(j=i;j<l;j++){
            if((ord==1 && a[j]<a[index]) || (ord==2 && a[j]>a[index]))
                index=j;
        }
    swap(&a[i],&a[index]);
    }
}

void bubble(int *a,int l,int ord){
    int i,j;
    for(i=l;i>0;i--){
        for(j=0;j<i-1;j++){
            if((ord==1 && a[j]>a[j+1]) || (ord==2 && a[j]<a[j+1]))
                swap(&a[j],&a[j+1]);
        }
    }
}

void print(int *a,int l){
    int i;
    for(i=0;i<l;i++)
        printf("%d\t",a[i]);
}

I'm looking for feedback / improvements on my code and whether the implementation of the sorting algorithms in the respective function definitions are proper or not.


texts: Menu traversing on next and prev button click up and down

texts:
Can anyone optimize this code?  I am new to jQuery.

I want add class on next and previous button click.  I wrote this code that works for me, but could anyone optimize it using jQuery predefined methods?  That would be helpful.

$(document).ready(function () {
    var length = $('#slides li').size() - 1;
    var curren = 0;
    console.log(length);
    $('.next').on('click', function () {
        if (curren >= 0 && curren < length) {
            curren++;
            $('.selected').removeClass('selected');
            $('#slides li:eq(' + curren + ')').addClass('selected');
        }
    });
    $('.prev').on('click', function () {
        if (curren >= 1) {
            curren--;
            $('.selected').removeClass('selected');
            $('#slides li:eq(' + curren + ')').addClass('selected');
        }
    });
});

My HTML code:

first

second

third

fourth

five

six

CSS code:

.selected{
color:red;
}


texts: Binary search tree in Java with only one class

texts:
I have written a BST using one class. Is my code okey or something could be better?

/**
* BST using one class
* @author Mateusz Stankiewicz
*/
public class Node {
private Comparable data;
private Node left;
private Node right;

private static Node root;

/**
 * Tree constructor
 */
public Node() {
    root = null;
}

/**
 * Node constructor
 */
private Node(Comparable data) {
    this.data = data;
    left = null;
    right = null;
}

/**
 * Tree method to add new element
 *
 * @param data is a new data we want to add to a tree
 */
public void addToTree(int data) {
    if (root == null)
        root = new Node(data);
    else
        add(root, data);
}

// Private method that add new element
private void add(Node target, Comparable data) {
    if (data.compareTo(target.data)<0) {
        if (target.left == null)
            target.left = new Node(data);
        else
            add(target.left, data);
    } else {
        if (target.right == null)
            target.right = new Node(data);
        else
            add(target.right, data);
    }

}

/**
 * Prints out tree nodes
 */
public void printTree() {
    print(root);
}

// Private recursive method to print a tree
private void print(Node n) {
    if (n.left != null)
        print(n.left);
    System.out.println(n.data);
    if (n.right != null)
        print(n.right);
}

public static void main(String[] args) {
    Node tree = new Node();
    tree.addToTree(1);
    tree.addToTree(7);
    tree.addToTree(3);
    tree.addToTree(4);
    tree.addToTree(2);
    tree.printTree();
}
}


texts: Using keywords async/await in database queries (Windows Phone 8)

texts:
I have a local database in Windows Phone 8 app. The app includes a lot of queries to the database and I don't want bad effect on the responsiveness of UI.

For example I have a table of users and method to get a user from database by id.

Current variant

public class CacheDataContext : DataContext
{
    public static string DBConnectionString = "Data Source=isostore:/Cache.sdf";

    public CacheDataContext(string connectionString)
            : base(connectionString) { }

    public static AutoResetEvent OperationOnDatabaseUser = new AutoResetEvent(true);

    public Table<User> UserItems;
}

public class CacheDataContextUser : CacheDataContext
{
    public CacheDataContextUser(string connectionString)
        : base(connectionString) { }

    public User GetUser(string id)
    {
        try
        {
            OperationOnDatabaseUser.WaitOne();
            using (CacheDataContext context = new CacheDataContext(DBConnectionString))
            {
                //find user in the data base and return
            }
        }
        finally
        {
            OperationOnDatabaseUser.Set();
        }
    }
}

I need ensure safety of the data if at the same time on database wallow different requests to add, modify, delete data. For this I use AutoResetEvent. Not sure what I'm doing it right, but so far no problems.

I can get user from the database:

using (DataBaseUser = new CacheDataContextFriends(ConnectionString))
{
   var user = DataBaseUser.GetUser(id);
}

Async/await

But I want work with the database using keywords async/await.

public class CacheDataContextUser : CacheDataContext
{
    public CacheDataContextUser(string connectionString)
        : base(connectionString) { }

    private object threadLock = new object();

    public Task<User> GetUser(string id)
    {
        using (CacheDataContext context = new CacheDataContext(DBConnectionString))
        {
            var result = await Task<User>.Factory.StartNew(() =>
                {
                    lock (threadLock)
                    {
                       //find user in the data base and return
                    }
                });
            return result;
        }
    }
}

I'm afraid to rewrite the method as described above, because I'm not sure it's right. Please tell me what the problem may be. My main goal is to improve the responsiveness of the app.


texts:
I have an array of BlockingCollections that i have initiated like this:

BlockingCollection<FxDataMapper>[] _fxDataByPair ;
arrayOfBlockingCollection = new BlockingCollection<MyClassInstance>[4];
            for (int i = 0; i < 4; i++)
                _arrayOfBlockingCollection[i] = new BlockingCollection<MyClassInstance>();

Now it want to iterate the array and extract each of the array elements and consume the BlockingCollections elements My code is this and although it works i think its not the best one

private void testArrayConsuming()
{
    Task processor = Task.Factory.StartNew(() =>
    {
        foreach (var x in arrayOfBlockingCollection )
        {
            Task processor2 = Task.Factory.StartNew(() =>
            {
                foreach (var y in x.GetConsumingEnumerable())
                        Console.WriteLine(x.Element.Value.ToString());

            });
        }
    });
}


texts: Drawing 800+ circles in a space-themed shoorter game

texts:
I am making a space-themed shooter game, and I need to render many "lasers" at the same time. I am using the library Slick2D, a wrapper around lwjgl. Unfortunately, when there are a lot of these "lasers" on the screen at one time, the game drops from its usual 60 FPS to around 30 or even 20.

Things I've noticed:

Not calling drawSelf = no lag
Not calling .fill = no lag
As is = lag as stated in title

public void drawSelf(Graphics g){
    int[] pos = tr.toSlick(blast.getPosition());
    g.setColor(Color.green);
    Circle circle = new Circle(pos[0], pos[1], tr.xscale/2);
    g.fill(circle);
}

public int[] toSlick(float x, float y){
    int [] output = new int[2];
    output[0] = (int)(x*xscale+width/2);
    output[1] = (int)(-1*y*yscale+height/2);
    return output;
}

tr is the coordinate transformer object (I'm using jbox2d physics, but that's not impacting anything), and blast is the "Body".

Can I have some suggestions on making this code faster or am I stuck because of Slick's internals?


texts:
I've just done something that works, but I have the feeling it's not correct. I made a class derived from list. I use a generic type to search the list using one of the properties of the list type as the index. Does this look right to you?

public class IndexableCollection<TCollection, TIndex> : List<TCollection>
{
    public IndexableCollection() : base() {}

    public TCollection this[TIndex index]
    {
        get
        {
            return base.Find(t => t.GetType().GetProperty(index.GetType().Name).GetValue(t).Equals(index));
        }
    }

    public List<TCollection> GetList()
    {
        return this as List<TCollection>;
    }

}

The intention is to have a collection where I can do this:

public class MyClass
{
    public int MyIntProperty { get; set; }
    public string MyStringProperty { get; set; }
    public MyEnumProperty MyEnumProperty { get; set; }
}

public void Main()
{
    var myCollection = new IndexableCollection<MyClass, MyEnumProperty>();

    var element = myCollection[MyEnumProperty.Option1];
}


texts:
I have the following problem:

Given an Array, apply a certain method x to each Array element (yielding a new Array), with the restriction that array elements which are nil, should be mapped to some default value. Method and default element are parameters. Example:
Array: ['abc',nil,'defg']
Method: :size
Default element: -1
Expected result: [3, -1, 4]

I implemented this by adding a method map_with to the Array class:
class Array
  def map_with(accessor, default_value=nil)
    map {|e| e.nil? ? default_value : e.send(accessor) }
  end
end

['abc',nil,'defg'].map_with(:size, -1)

I'm looking for an improvement of my current solution. Can the solution be improved in the following sense?

Provide the same result with simpler code
Make the function more flexible (more generally useful) by not adding too much code


texts:
I would like to use code below for general purpose dynamic array implementation in my future code. How does it look?

array.h:

#include <stdlib.h>

/* This file describes structures and functions
   for general purpose dynamic array.
*/

struct array {
    void *data;       /* Points to where the data is */
    int numElements;  /* Number of elements */
    int sizeElem;     /* Size of a single elements */
    int capacity;     /* Current total space in number of elements */
};

/* macros for accessing array internals */
#define array_index(ARRAY, INDEX) (void *)((unsigned)((ARRAY)->data)+(INDEX*((ARRAY)->sizeElem)))
#define array_len(ARRAY) (ARRAY)->numElements
#define array_cap(ARRAY) (ARRAY)->capacity

static inline void array_init(struct array *arr, int capacity, int sizeElem) {
    arr->data = malloc(capacity * sizeElem);
    arr->capacity = capacity;
    arr->sizeElem = sizeElem;
    arr->numElements = 0;
}

/* Add an element to array. Expand array if necessary. */
static inline void array_add(struct array *arr, void *data) {
    if (arr->capacity <= arr->numElements) {
        int new_capacity = 2 * arr->capacity;
        arr->data = realloc(arr->data, new_capacity * arr->sizeElem);
        arr->capacity = new_capacity;
    }
    memcpy(array_index(arr,arr->numElements), data, arr->sizeElem);
    arr->numElements++;
}

/* Macro for traversing array elements. */
#define array_for_each(TYPE, ELEM, ARRAY) \
    for (TYPE *ELEM=(ARRAY)->data; (ELEM - (TYPE *)(ARRAY)->data) < (ARRAY)->numElements; ELEM++)

/* Removes the element at given index and moves other elements if necessary. */
static inline void array_delete_index(struct array *arr, int index) {
    int movables = arr->numElements - index - 1;
    memcpy(array_index(arr, index),
           (void *)((unsigned)array_index(arr, index) + arr->sizeElem),
           movables * arr->sizeElem);
    arr->numElements--;
}

/* If array capacity is too much compared to number of elements,
   reduce array capacity
*/
static inline void array_free_capacity(struct array *arr) {
    if (arr->capacity > 2*arr->numElements) {
        int new_capacity = arr->capacity / 2;
        arr->data = realloc(arr->data, new_capacity * arr->sizeElem);
        arr->capacity = new_capacity;
    }
}

/* Probably useless macro */
#define array_free(ARRAY) free((ARRAY)->data)

/* Search for an element and return an index if found. Otherwise, return -1
   Comparison function should return 0 if two items should be considered equal.
*/
static inline int array_search(struct array *arr, void *target, int (*cmp)(void *first, void *second)) {
    for(int i=0; i<arr->numElements; i++) {
        if(cmp(array_index(arr, i), target) == 0) return i;
    }
    return -1;
}

/* Returns a pointer to the element at given index, if it doesn't
    exist, return NULL
*/
static inline void *array_get_index(struct array *arr, int index) {
    if (index > (arr->numElements - 1)) return NULL;
    return array_index(arr, index);
}

How the code is used:

First you initialize the array with a data type and the initial array capacity, measured in the number of elements that the array can hold.

After that, the functions in array.h can be used to add, remove, traverse the array, and more.

Example:

struct task {
    char *task_name;
    int task_id;
};

struct array my_tasks;
/* Define an dynamic array of struct tasks */
array_init(&my_tasks, 2, sizeof(struct task));


texts:
I have the following code in PHP that appends a file path with a timestamp of when it was last modified:

function AssetTimestamp($filename)
{
    if (file_exists($filename)) {
        return $filename . '?' . @filemtime($filename);
    } else {
        return $filename;
    }
}

I have written the equivalent in C#

public static string AssetTimestamp(string filename)
    {
        if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(filename)))
        {
            DateTime dt = System.IO.File.GetLastWriteTimeUtc(HttpContext.Current.Server.MapPath(filename));
            Int32 unixTimestamp = (Int32)(dt.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            return System.Web.VirtualPathUtility.ToAbsolute(filename) + "?" + unixTimestamp;
        }
        else
        {
            return System.Web.VirtualPathUtility.ToAbsolute(filename);
        }
    }

But as you can see, the code is HUGE in comparison! Can anyone suggest some better ways to handle this, as I can't believe that PHP can do all of that in just one line compared to all the crazy MapPath and converting of dates etc.


texts: Overwriting native console.log function in JavaScript

texts:
I want to override the console.log function in order to save the data other scripts log. My script executes before any other script, so I have full control over the environment. This is my current function for overwriting console.log:

+function(){
    var a = Function.prototype, b = 'toString', c = a[b], d = c.apply(c).split(c.name), e = [], f = [], g = function(a, b){
        e.push(a);
        f.push(b);
        return a;
    }, _ = [];

    a[b] = function(h){
        return g(function toString(){
            var i = e.indexOf(this);
            return i != -1 ? f[i] || d.join(this.name) : h.apply(this);
        });
    }(c);

    console.log = function(a){
        return g(function log(){
            var b = [], i;
            for(i in arguments) b.push(arguments[i]);
                _.push(b.slice());
            return a.apply(this, arguments);
        });
    }(console.log);
}();

My question is simple: is it possible that some script executed after this can reveal that I have an overwritten console.log function?

I will use it for debugging scripts sent from users to my Node.js server application. I am using vm module, so I need to overwrite sandbox the object's console.log function in order to trace what users log to console in received scripts.

If this code looks obfuscated, here is a better version.


texts:
I have a class that takes an array of integers and produces a multiplication table.

class MultiplicationTable
  def initialize(num_ary)
    @num_ary = num_ary.to_a
  end

  def generate
    a1 = @num_ary.clone
    a2 = @num_ary.clone

    rows = []
    rows << a1

    a2.shift

    a2.each do |x|
      cols = [x]
      a1[1..-1].each do |y|
        cols << (x * y)
      end
      rows << cols
    end

    rows
  end
end

So this:

MultiplicationTable.new(1.upto(5)).generate

produces this output:

[
  [1, 2, 3, 4, 5],
  [2, 4, 6, 8, 10],
  [3, 6, 9, 12, 15],
  [4, 8, 12, 16, 20],
  [5, 10, 15, 20, 25]
]

Here are my results from benchmarking:

                         user     system      total        real
100 entry table      0.000000   0.000000   0.000000 (  0.001295)
1,000 entry table    0.120000   0.010000   0.130000 (  0.132325)
10,000 entry table  15.290000   0.380000  15.670000 ( 15.747799)

Is there anything I can do to speedup/improve up this code?


texts:
I used this script to sending status report to my team lead. It will read the status from the file Readme.md. Here i already wrote my status. if this script execute on target_time or greater than it will execute the mailer function otherwise ask for confirmation

# importing messagebox for confirmation diaglog box
import tkMessageBox
import smtplib

from time import gmtime, strftime

def mail_send():
    target_time = 02
    # By using strftime we only current time in hours, it returns string like
    # "12"
    current_Time = strftime("%H")
    print current_Time

    # convert str to number
    cTime = int(current_Time)

    def sub_mailer():

        print "Mailer loading ...."
        s = smtplib.SMTP('smtp.gmail.com', 587)
        s.starttls()
        s.login('myuser@gmail.com', 'anypass')
        f = open('Readme.md', 'r')
        filedata = f.read()
        subject = "Today Update"
        msg = 'Subject:{}\n\n{}'.format(subject, filedata)
        s.sendmail('myuser@gmail.com', 'teamlead@Gmail.com',
                   msg)
        s.quit()
        f.close()

    # get time using time module
    if target_time <= cTime:
        sub_mailer()
    else:
        status = tkMessageBox.askquestion(
            "Shift hours is not completed. Shall i  send a mail", icon="warning")
        if status == "yes":
            sub_mailer()
        else:
            print "Mail sending process was canceled by user"


texts: Does this code fall into a design pattern?

texts:
CustomDialog is the parent abstract class for OkExclamationDialog and ExclamationDialog with abstract method displayDialog() being overriden.

Does this fall into a design pattern?  Can this design be improved upon?

JudgeButton controls the other classes.

public class JudgeButton {
    private int typeCode;

    private void initialise(){
        setTypeCode();
        if(typeCode == 0){
            c = new ExclamationDialog("Episode not started");
            c.displayDialog();
        }
        else if(typeCode == 1){
            c = new OkExclamationDialog("Episode Finished, you will now be redirected");
            c.displayDialog();
        }
    }

    private void setTypeCode(){
        wrapperJsonObject = Utils.getCurrentWrapperJsonObjectFromServer();
        jsonObject = wrapperJsonObject.getJsonObject();
        NextRatingsScreen n = new NextRatingsScreen(jsonObject);
        RatingsCountDownTime r = new RatingsCountDownTime();

        if(!n.isEpisodeStarted()){
            typeCode = 0;
        }
        else if(!n.isPerformanceStarted()){
            typeCode = 1;
        }
    }
}

public class OkExclamationDialog extends CustomDialog{
    public OkExclamationDialog(String text) {
        super(text);
    }

    public void displayDialog() {
        DialogType dialogType = new DialogType();
        DialogBuilder dialogBuilder = new DialogBuilder();
        AbstractDialogFactory abstractDialogFactory = dialogType.getDialogType(DialogEnum.EXCLAMATION_DIALOG);
        Dialog nextScreen = dialogBuilder.buildDialog(abstractDialogFactory, super.getText());
        int result = nextScreen.doModal();
        ScreenController.displayNextScreenFadeTransition(nextScreen);

        if(result==Dialog.OK)
        {
            ScreenController.displayNextScreenFadeTransition(new ContestantsScreen());
        }
    }
}

public class ExclamationDialog extends CustomDialog{
    public ExclamationDialog(String text) {
        super(text);
    }

    public void displayDialog() {
        DialogType dialogType = new DialogType();
        DialogBuilder dialogBuilder = new DialogBuilder();
        AbstractDialogFactory abstractDialogFactory = dialogType.getDialogType(DialogEnum.EXCLAMATION_DIALOG);
        Dialog nextScreen = dialogBuilder.buildDialog(abstractDialogFactory, super.getText());

        ScreenController.displayNextScreenFadeTransition(nextScreen);
    }
}

public abstract class CustomDialog {
    private String text;

    public CustomDialog(String text){
        this.text = text;
    }

    public String getText(){
        return this.text;
    }

    public abstract void displayDialog();
}


texts: Staircase problem solved using recursion

texts:
Problem
Question taken from here.

I want to go up a flight of stairs that has n steps. I can either take 1 or 2 steps each time. How many different ways can I go up this flight of stairs? Write a function count_stair_ways that solves this problem for me.
def count_stair_ways(n):

Solution:
def count_stair_ways(n):
    if n == 1: # 1 way to flight 1 stair case step
        return 1
    if n ==2: # 2 ways to flight 2 stair case steps(1+1, 2)
        return 2
    return count_stair_ways(n-1) + count_stair_ways(n-2)

Can we improve this code?


texts:
I don't know how could I write smarter/more elegant code for the add function , it just seems so meaty and hard to read.
This trie only stores words and marks their end with a bool.

type trie = Node of bool * (char * trie) list
let empty = Node (false, [])

let rec add w tr = match w, tr with
    | [], Node (_, lvl_l) -> Node (true, lvl_l)
    | wh :: wt, Node (b, lvl_l) ->
        try let ins_point = (List.assoc wh lvl_l) in
        Node(b, (wh, add wt ins_point)::(List.remove_assoc wh lvl_l))
        with Not_found -> Node (b, (wh, add wt empty)::lvl_l)

let explode word =
       let rec explode' i acc =
           if i < 0 then acc else explode' (i-1) (word.[i] :: acc)
            in explode' (String.length word - 1) []

Output Example :

# let x = add (explode "horror") empty;;
val x : trie =
  Node (false,
   [('h',
     Node (false,
      [('o',
        Node (false,
         [('r',
           Node (false,
            [('r',
              Node (false, [('o', Node (false, [('r', Node (true, []))]))]))]))]))]))])
# let x = add (explode "horrific") x;;
val x : trie =
  Node (false,
   [('h',
     Node (false,
      [('o',
        Node (false,
         [('r',
           Node (false,
            [('r',
              Node (false,
               [('i',
                 Node (false,
                  [('f',
                    Node (false,
                     [('i', Node (false, [('c', Node (true, []))]))]))]));
                ('o', Node (false, [('r', Node (true, []))]))]))]))]))]))])


texts:
Here is my module for statistics:

import numpy as np
import scipy.stats as st

class Statistics():

    def sterm_and_leaf(self,data):
        graph={}
        for i in data:
            x=str(i)
            if len(x)>1:
                if int(x[0]) in graph.keys(): graph[int(x[0])].append(int(x[1:]))
                else : graph[int(x[0])]=[int(x[1:])]
            elif len(x)==1:
                if 0 in graph: graph[0].append(int(x))
                else : graph[0]=[int(x)]

        for v in graph.values():  v.sort()

        for k in sorted(graph.keys(),reverse=True):
            print(k,':',' '.join([str(i) for i in graph[k]]))

        return graph

    def hystogram(self,data):

        import matplotlib.pyplot as plt
        plt.hist(data)

        plt.xlabel("Value")
        plt.ylabel("Frequency")

        plt.show()

    def trimean(self,data):
        from numpy import percentile
        return (percentile(data,25)+2*percentile(data,50)+percentile(data,75))/4

    def trimmed_mean(self,data,percent):
        sorted_data = sorted(data) #uncomment to use plain python sorted
        n = len(sorted_data)
        outliers = n*percent//100 #may want some rounding logic if n is small
        trimmed_data = sorted_data[outliers: n-outliers]
        #from numpy import percentile
        #if percent<50: data_trimmed=[i for i in data if i>percentile(data,percent)and i<percentile(data,100-percent)]
        #else: data_trimmed=[i for i in data if i<percentile(data,percent)and i>percentile(data,100-percent)]
        return sum(trimmed_data)/float(len(trimmed_data))

    def variance(self,data):
        mean=sum(data)/float(len(data))
        var=[(i-mean)**2 for i in data]
        return round(sum(var)/float(len(var)-1),4)

    def pearson_correlation_coefficient(self,X,Y):
        mean_x=sum(X)/len(X)
        mean_y=sum(Y)/len(Y)
        x=[(i-mean_x) for i in X]
        y=[j-mean_y for j in Y]
        z=[x[i]*y[i] for i in range(len(x))]
        return round(sum(z)/((sum([k**2 for k in x])*sum([v**2for v in y]))**0.5),3)

    def confidence_interval(self,data,alpha):
        import numpy as np
        import scipy.stats as st
        g=st.t.interval(alpha, len(data) - 1, loc=np.mean(data), scale=st.sem(data))
        return([round(i) for i in g])

    def scatter_plot(self,x,y):
        import matplotlib.pyplot as plt
        plt.scatter(x,y)
        plt.show()

    def get_points_from_scatter(self,x,y,n):
        from pylab import ginput,plot,scatter

        scatter(x,y)
        z = ginput(n)

        return z

Please look for full version on Github
Any hint on improving the code?
Module was created for statistical analysis of data:
- finding mean, median, mode, trimmed mean
- finding range, variance, standard deviation, correlation coefficient
- various visual representations of data: histogram, stern-and-leaf display, scatter plot.


texts:
I've been implementing functional linked lists in different languages, just as a learning exercise. I'm looking for feedback in general: code correctness, best practices, design patterns; everything you think about this. Is it bad code? Where can it be improved?

/**
*
* Constructing Linked Lists
*
* Our linked list data structure consists of two fundamental building blocks: Nil and cons. Nil represents the
* empty list and serves as a sentinel for more complex lists. The cons operation extends a list at the front by
* inserting a new value.
*
* The lists we construct using this method consist internally of nested arrays of 2 items. For example, the list [1, 2, 3]
* is represented by the expression cons(1, cons(2, cons(3, Nil))) which evaluates to the nested arrays [1, [2, [3, Nil]]].
*
*/

var Nil = "Nil";

/** Extends a list at the front by inserting a new value. */
function cons(head, tail) {
    tail = typeof tail === "undefined" ? Nil : tail;
    return [head, tail];
}

/**
* Define list instances using a more convenient syntax and without deeply nested cons calls.
* lst() === Nil
* lst(1, 2, 3) === [1, [2, [3, Nil]]]
*/
function lst() {
    var arg_array = Array.prototype.slice.call(arguments);  // arguments cast from object to array
    if (arg_array.length === 0) return Nil;
    else return cons(arg_array[0], lst.apply(this, arg_array.slice(1)));
}

/** Returns the first element of a list */
function head(xs) {
    return xs[0];
}

/** Returns a list containing all elements except the first. */
function tail(xs) {
    return xs[1];
}

/** Returns True if the list contains zero elements. */
function isEmpty(xs) {
    return xs === Nil;
}

/** Returns number of elements in a given list. */
function length(xs) {
    if (isEmpty(xs)) return 0;
    else return 1 + length(tail(xs));
}

/** Concatenates two lists. */
function concat(xs, ys) {
    if (isEmpty(xs)) return ys;
    else return cons(head(xs), concat(tail(xs), ys));
}

/** Returns the last element of a non-empty list. */
function last(xs) {
    if (isEmpty(tail(xs))) return head(xs);
    else return last(tail(xs));
}

/** Returns all elements except the last one. */
function init(xs) {
    if (isEmpty(tail(tail(xs)))) return cons(head(xs));
    else return cons(head(xs), init(tail(xs)));
}

/** Returns the input list, reversed. */
function reverse(xs) {
    if (isEmpty(xs)) return xs;
    else return concat(reverse(tail(xs)), cons(head(xs), Nil));
}

/** Returns the first n elements of the given list. */
function take(n, xs){
    if (n < 1) return Nil;
    else return cons(head(xs), take(n - 1, tail(xs)));
}

/** Returns a copy of input list, without the first n elements. */
function drop(n, xs){
    if (n < 1) return xs;
    else return drop(n - 1, tail(xs));
}

/**  Returns a subset of the input list that includes the items in the range from, to. */
function piece(from, to, xs){
    return take(to - from, drop(from, xs));
}

/** Removes the element of the list at given index */
function removeOne(index, xs){
    return concat(take(index - 1, xs), drop(index, xs));
}


texts:
I am playing around with building my own back end with python 2.7 and jinja2/cgi. Originally I was defining some of my environment and loader variables at the top but figured this was not the best practice. I then defined functions for each, but they'd only get called once or twice depending on which route it decided to execute. I came up with this class idea instead that I pass into my dispatch function, which in turn passes it into whatever rendering function happens to be being executed. Is this the proper 'pythonic' way to approach having a template loader, and if not would anyone have any suggestions?

class Template(object):
    def __init__(self):
        self._environment = None

    def __call__(self, temp_name):
        return self.get_env.get_template(temp_name)

    @property
    def get_env(self):
        return self._environment

    @get_env.getter
    def get_env(self):
        if not self._environment:
            self._loader = jinja2.FileSystemLoader(searchpath=os.path.join(
              os.path.dirname(os.path.abspath(__file__)), '../templates/madlib/'))
            self._environment = jinja2.Environment(loader = self._loader)

        return self._environment

This class then allows me to just call template('templateFileName.j2') and be returned that jinja template object. If the environment is not created, the getter will create one for me.


texts: Looping through a string finding nested brackets

texts:
So I've been trying to check through a string, looping for, [ (start) and ] (end).

In this, I also have to check for nested brackets.

My expected output, given input [depth1[depth2]] is as follows:

depth2
depth1[depth2]

To achieve this, I wrote this little snippet of code, which uses a Dictionary<int, int> to store the initial bracket's position at a given depth. If it finds another opening bracket, the depth will increase (and the position will be recorded). It will look for the next ending bracket (with respect to any other opening brackets), and get the initial position of the bracket for that depth. (Thus we get both the beginning and ending of that nested string)

    var depthItems = new Dictionary<int, int>();
    int depth = 0;

    string input = "[depth1[depth2]]";

    for (int i = 0; i < input.Length; i++) {
        if (input[i] == '[') {
            depth++;
            depthItems.Add(depth, i);
        } else if (input[i] == ']') {
            int item = depthItems[depth];
            depthItems.Remove(depth);
            depth--;
            Console.Write($"Found item at ({item}, {i}) -> ");
            Console.WriteLine(input.Substring(item + 1, i - item - 1));
        }
    }

I'm not sure how viable this would be when looking up against large strings with lots of nested brackets - I think it's a start, at least.

I will note that I was first surprised that higher "depths" were returned first, but then realised that in order for the lower ones to complete, the higher ones should have been returned first. Not a bad thing, but curious to note.

So how could this be improved, especially in terms of memory (i.e. large strings)?


texts:
Objective: Crop the image so only the number stays in the image

Problem: Slow Performance

I have code that crops an image.
The image pixels are 0 or 255. There are no values between.

The background is 0 (black) and the letter/number is between 0 (not-inclusive) - 255 (white).

This code is being used to crop a Mnist Digit of the Mnist Dataset.

Image Source

The code does it, however, it does with 2 fors and it takes a long time! How can I optimize it?

def crop_image(data_to_crop):
    cropped_data = []

    for z in xrange(data_to_crop.shape[0]):

        img = data_to_crop[z]
        img = img.reshape(data_to_crop.shape[0], data_to_crop.shape[1])

        rx = -1
        upy = -1

        lx = -1
        by = -1

        for x in xrange(data_to_crop.shape[0]):
            for y in xrange(data_to_crop.shape[1]):

                px = img[x, y]

                if px > 0:

                    if rx == -1 or x > rx:
                        rx = x

                    if lx == -1 or x < lx:
                        lx = x

                    if upy == -1 or y > upy:
                        upy = y

                    if by == -1 or y < by:
                        by = y

        img = img[lx:rx, by:upy]

        cropped_data.append(img)

    return cropped_data


texts:
I am making a 2D Java game at school, and at the movement I use a switch. The code works, however, my teacher won't sign my code until I have removed code duplication.

Short info: My Keyactionlistener sends a String of direction that is used in the switch to move. Inside that very same switch I also check the object in the next field to see if it can be picked up or can move through. However, the code is really long this way and I need to shorten it down somehow.

public void checkAndMove(String direction) {
        switch (direction) {

            case "up":
                if (!field.checkIfBlocked(getfieldX(), getfieldY() - 1)) {
                    if (field.checkIfItem(getfieldX(), getfieldY() - 1).equals("friend")) {
                        showEndMessage = true;
                    }
                    if (field.checkIfItem(getfieldX(), getfieldY() - 1).equals("bazooka")) {
                        plusAmmo();
                        levelmaker.removeBazooka();
                    }
                    if (field.checkIfItem(getfieldX(), getfieldY() - 1).equals("helper")) {
                        showShortestRoute();
                    }
                    move(0, -1);
                    if(showEndMessage == true){
                        endMessage();
                    }
                    levelmaker.scorePlusPlus();
                    changeImage("imgUp");
                    break;
                } else {
                    break;
                }
            case "down":
                if (!field.checkIfBlocked(getfieldX(), getfieldY() + 1)) {
                    if (veld.checkIfItem(getfieldX(), getfieldY() + 1).equals("friend")) {
                        endMessage();
                    }
                    if (field.checkIfItem(getfieldX(), getfieldY() + 1).equals("bazooka")) {
                        plusAmmo();
                        LevelMaker.removeBazooka();
                    }
                    if (field.checkIfItem(getfieldX(), getfieldY() + 1).equals("helper")) {
                        showShortestRoute();
                    }
                    move(0, 1);
                    levelmaker.scorePlusPlus();
                    changeImage("imgDown");
                    break;
                } else {
                    break;
                }
            case "left":
                if (!field.checkIfBlocked(getfieldX() - 1, getfieldY())) {
                    if (field.checkIfItem(getfieldX() - 1, getfieldY()).equals("friend")) {
                        endMessage();
                    }
                    if (field.checkIfItem(getfieldX() - 1, getfieldY()).equals("bazooka")) {
                        plusAmmo();
                        LevelMaker.removeBazooka();
                    }
                    if (field.checkIfItem(getfieldX() - 1, getfieldY()).equals("helper")) {
                        showShortestRoute();
                    }
                    move(-1, 0);
                    levelmaker.scorePlusPlus();
                    changeImage("imgLeft");
                    break;
                } else {
                    break;
                }
            case "right":
                if (!field.checkIfBlocked(getfieldX() + 1, getfieldY())) {
                    if (field.checkIfItem(getfieldX() + 1, getfieldY()).equals("friend")) {
                        endMessage();
                    }
                    if (veld.checkIfItem(getfieldX() + 1, getfieldY()).equals("bazooka")) {
                        plusAmmo();
                        LevelMaker.removeBazooka();
                    }
                    if (field.checkIfItem(getfieldX() + 1, getfieldY()).equals("helper")) {
                        showShortestRoute();
                    }
                    move(1, 0);
                    levelmaker.scorePlusPlus();
                    changeImage("imgRight");
                    break;
                } else {
                    break;
                }
        }


texts:
The soundex algorithm maps several spellings of a name to a 4 character term. (hopefully mapping all different transcriptions to the same term) The steps as described in Introduction to information retrieval are:

Keep first Letter for the rest:
Change any of 'A', 'E', 'I', 'O', 'U', 'H', 'W', 'Y' to zero
Change all other characters to 1-6, see below
remove consecutive doubles
remove all zeros, right pad with 0s, keep first 3

I implemented a working solution, but can it be implemented more readable?

import Data.Char

soundex :: String -> String
soundex []      = []
soundex (n:ame) = result
  where
    compr  = map (compress . toUpper) ame
    noDoub = remDoubles compr
    noZero = filter (/='0') noDoub
    result = n: take 3 (noZero++"000")

remDoubles :: String -> String
remDoubles []       = []
remDoubles (a:[])   = [a]
remDoubles (a:b:bs) | a==b      = remDoubles   (b:bs)
                    | otherwise = a:remDoubles (b:bs)

compress :: Char -> Char
compress char | char `elem` "AEIOUHWY" = '0'
              | char `elem` "BFPV"     = '1'
              | char `elem` "CGJKQSXZ" = '2'
              | char `elem` "DT"       = '3'
              | char `elem` "L"        = '4'
              | char `elem` "MN"       = '5'
              | char `elem` "R"        = '6'
              | otherwise              = char


texts:
I have written a little program that calculates the time by given strings.

A time string in the context of this program consists of a number and a following letter that can be s, m, h, or d.

You can enter something like this:

java TimeCalculator 443432s 34234m 34323m 32344234s 8h 23d 12h

It than calculates the time and prints it out in an readable format:

450 days 22 hours 18 minutes 6 seconds

I want to ask you, how I can improve the readability and maybe also the performance. I dont tried to design the program object oriented because I think the program is to small for that. But if you have another opinion on that, please let me know!

public class TimeCalculator {
    private static final int MINUTE_IN_SECONDS = 60;
    private static final int HOUR_IN_SECONDS = 3600;
    private static final int DAY_IN_SECONDS = 86400;

    private static int seconds = 0;

    public static void main(String[] args) {
        if (args.length == 0 || args[0].contains("help")) {
            showHelp();
            return;
        }

        for (String arg : args) {
            timeStringToSeconds(arg);
        }

        printNewTimeString();
    }

    private static void timeStringToSeconds(String timeString) {
        if (timeString.contains("s")) {
            timeString = timeString.replace("s", "");
            seconds += Integer.parseInt(timeString);
        } else if (timeString.contains("m")) {
            timeString = timeString.replace("m", "");
            seconds += Integer.parseInt(timeString) * MINUTE_IN_SECONDS;
        } else if (timeString.contains("h")) {
            timeString = timeString.replace("h", "");
            seconds += Integer.parseInt(timeString) * HOUR_IN_SECONDS;
        } else if (timeString.contains("d")) {
            timeString = timeString.replace("d", "");
            seconds += Integer.parseInt(timeString) * DAY_IN_SECONDS;
        }
    }

    private static void printNewTimeString() {
        String newTimeString = new String();
        // calculate days
        int days = 0;
        while (seconds >= DAY_IN_SECONDS) {
            days++;
            seconds -= DAY_IN_SECONDS;
        }
        if (days > 0) {
            newTimeString += days + " days ";
        }

        // calculate hours
        int hours = 0;
        while(seconds >= HOUR_IN_SECONDS) {
            hours++;
            seconds -= HOUR_IN_SECONDS;
        }
        if (hours > 0) {
            newTimeString += hours + " hours ";
        }

        // calculate minutes
        int minutes = 0;
        while (seconds >= MINUTE_IN_SECONDS) {
            minutes++;
            seconds -= MINUTE_IN_SECONDS;
        }
        if (minutes > 0) {
            newTimeString += minutes + " minutes ";
        }

        // calculate seconds
        if (seconds > 0) {
            newTimeString += seconds + " seconds ";
        }

        System.out.println(newTimeString);
    }

    private static void showHelp() {
        System.out.println("This Program converts time strings to an ordered string that makes the time");
        System.out.println("information better understandable\n");
        System.out.println("You can enter something like this: ");
        System.out.println("java TimeCalculator 534s 400d 32453s 234h");
        System.out.println("The output will be this: ");
        System.out.println("410 days 3 hours 9 minutes 47 seconds");
        System.out.println("Available characters: d, h, m, s");
    }
}


texts:
I have written an isRotation function that calls on isSubstring only once(I am allowed to call it only once). I have implemented my own version of isSubstring as well. Any advice is much welcome!

//Checks if one string is a rotation of the other
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isRotation(char *, char *);
bool isSubstring(char *, char *);

int main(int argc, char **argv)
{
    if(argc == 3)
    {
        printf("%s %s a rotation of %s.\n", argv[2], isRotation(argv[1], argv[2])
            ? "is" : "is not", argv[1]);
    }
    else
    {
        fprintf(stderr, "Incorrect number of inputs\n");
        return -1;
    }

    return 0;
}

bool isRotation(char* s1, char* s2)
{
    size_t len1 = strlen(s1);
    size_t len2 = strlen(s2);

    if(len1 != len2 || len1 == 0 || len2 ==0)
        return 0;

    char s3[len2*2];

    bool secondCopy = false;
    int j = 0;

    /*copying 2*s2 into s3. If s2 is a rotation of s1,
      then s1 has to be found somewhere inside s3.*/
    for(size_t i = 0; i < (2*len2); i++)
    {
        s3[i] = s2[j];
        if(s2[j+1] == '\0' && secondCopy == false)
        {
            secondCopy = true;
            j = 0;
            continue;
        }
        j++;
    }

    s3[len2*2] = '\0';

    //pass the longer string to the first param
    return isSubstring(s3, s1);
}

bool isSubstring(char* s1, char* s2)
{
    //is s2 a substring of s1?
    size_t len2 = strlen(s2);
    if(len2 == 0)
        return true;

    int j = 0;
    int i = 0;
    while(s1[i] != '\0')
    {
        if(s2[j] == s1[i])
            j++;

        i++;
    }

    return j == len2;
}


texts: Squashing multiplication identity in an expression

texts:
I'm learning Haskell, and one exercise was to implement squashing of identity-multiplications, e.g.:

\$5 + (2*1) => 5 + 2\$

Here is my implementation:

squashMulId :: (Ring a, Eq a) => RingExpr a -> RingExpr a
squashMulId (Mul x y)
    | x == (Lit (mulId))    = squashMulId y
    | y == (Lit (mulId))    = squashMulId x
    | otherwise             = if sqX == x && sqY == y then (Mul sqX sqY) else squashMulId (Mul sqX sqY)
                              where sqX = squashMulId x
                                    sqY = squashMulId y
squashMulId (AddInv x)      = (AddInv (squashMulId x))
squashMulId (Add x y)       = (Add (squashMulId x) (squashMulId y))
squashMulId x               = x

squashMulIdInt :: RingExpr Integer -> RingExpr Integer
squashMulIdInt = squashMulId

tests_squash = test [
                      "right" ~: (Add (Lit 5) (Lit 2)) ~=? squashMulIdInt (Add (Lit 5) (Mul (Lit 2) (Lit 1)) )
                     ,"left" ~: (Add (Lit 5) (Lit 2)) ~=? squashMulIdInt (Add (Lit 5) (Mul (Lit 1) (Lit 2)) )
                     ,"recursive" ~: (Add (Lit 5) (Lit 2)) ~=? squashMulIdInt (Add (Lit 5) (Mul (Lit 1) (Mul (Lit 2) (Mul (Lit 1) (Lit 1)))))
                    ]

How can I improve on this implementation? Is it idiomatic? Can it be written in a more succinct way?

The following code/definitions were given:

{-# OPTIONS_GHC -Wall #-}
module SQMULID where

import Data.Char
import Data.List
import Data.Maybe
import Test.HUnit
import Test.QuickCheck
import Test.QuickCheck.Gen

class Ring a where
  addId  :: a            -- additive identity
  addInv :: a -> a       -- additive inverse
  mulId  :: a            -- multiplicative identity

  add :: a -> a -> a     -- addition
  mul :: a -> a -> a     -- multiplication

-- | A datatype for storing and manipulating ring expressions.
data RingExpr a = Lit a
                | AddId
                | AddInv (RingExpr a)
                | MulId
                | Add (RingExpr a) (RingExpr a)
                | Mul (RingExpr a) (RingExpr a)
  deriving (Show, Eq)

instance Ring (RingExpr a) where
  addId  = AddId
  addInv = AddInv
  mulId  = MulId

  add = Add
  mul = Mul

-- The canonical instance for integers:
instance Ring Integer where
  addId  = 0
  addInv = negate
  mulId  = 1

  add = (+)
  mul = (*)


texts:
Before I start writing my first MVC framework, I want to improve my code quality as much as I can, can anyone give me some constructive criticism on how I can improve this?

It is a simple router, built for simple use. It should be pretty simple what's going on, and the usage should be easy to picture. It's nothing major but works well for simple functionality using it.

<?php

class Router {

    public $routes = [];
    public $routeMethods = [];

    public function get($route, $settings) {
        $this->add($route, $settings, ['GET']);
    }

    public function post($route, $settings) {
        $this->add($route, $settings, ['POST']);
    }

    public function add($route, $settings, $methods) {
        $this->routes[$route] = $settings;
        $this->routeMethods[$route] = $methods;
    }

    public function dispatch() {
        $requestUrl = $_SERVER['QUERY_STRING'];

        if (array_key_exists($requestUrl, $this->routes)) {
            $route = $this->routes[$requestUrl];
            $methods = $this->routeMethods[$requestUrl];
            $method = $_SERVER['REQUEST_METHOD'];

            if (!in_array($method, $methods)) {
                echo 'Method ' . $method . ' not allowed.';
            }
            else {
                $controller = $route['controller'];

                if (class_exists($controller)) {
                    $class = new $controller(); // grab from di cache when we have one
                    $action = $route['action'];

                    if (method_exists($class, $action)) {
                        $class->$action();
                    }
                    else {
                        echo 'We couldn\'t find action \'' . $action . '\ in controller \'' . $controller . '\'';
                    }
                }
                else {
                    echo 'We couldn\'t find controller \'' . $controller . '\'';
                }
            }
        }
        else {
            echo '404 not found';
        }
    }

}


texts: Simple DNA sequence finder w/ mismatch tolerance

texts:
The goal with this function is to find one DNA sequence within another sequence, with a specified amount of mismatch tolerance.  For example:

dnasearch('acc','ccc',0) shouldn't find a match, while
dnasearch('acc','ccc',1) should find one.

EDIT: Function should also be able to find pat sequence in a sequence larger than the pat sequence; furthermore it should be able to find multiple matches within that sequence if they exist.  For example, dnasearch('acc','acaaatc',1) would find two matches: 'aca' and 'act'.  Thanks to @weronika for pointing this out.

Here's my working draft:

def dnasearch(pat,seq,mismatch_allowed=0):
patset1=set([pat])
patset2=set([pat])
for number in range(mismatch_allowed):
    for version in patset1:
        for a in range(len(version)):
            for letter in 'actg':
                newpat=version[:a]+letter+version[a+1:]
                patset2.add(newpat)
    patset1|=patset2
for n in patset1:
    if seq.find(n) != -1: print 'At position', seq.find(n),\
       'found',n

I was wondering how to write this function:

With fewer for-loops.
Without the second patset.  Originally I tried just adding new patterns to patset1, but I got the error: RuntimeError: Set changed size during iteration.
Simpler in any other way.


texts: Asking and checking if the answer is correct

texts:
So I'm very new if JavaScript and my question is this a right way to implement this functionality? How could I improve this code.
<!DOCTYPE html>

        <title>TEST</title>

TEST

How many times can you subtract 6 from 30?

                <button class="incorrect">ДВА РАЗA</button>
                <button class="incorrect">ЧЕТЫРЕ РАЗA</button>
                <button class="incorrect">ТРИ РАЗA</button>
                <button class="incorrect">ШЕСТЬ РАЗ</button>
                <button class="correct">ПЯТЬ РАЗ</button>

Сколько раз вы можете вычесть 6 из 30?

What number should be subtracted from each of 50, 61, 92, 117 so that the numbers, so obtained in this order, are in proportion ?

                <input type="text"></input>
                <button class="check">Check</button>

Какое число нужно вычесть из 50, 61, 92, 117, чтобы числа, полученные в таком порядке, были пропорциональны?


texts: Function to lock a file using memcache, Version 2

texts:
Based on suggested reviews for Function to lock a file using memcache, I have modified the code to

import os
import shutil
import memcache

def addToCart(filename, username):
    ableToLock = memcache.add(filename, username)
    if ableToLock:
        # "ableToLock" can happen if the file is still present
        # or if it was already processed.
        if os.file.ispath(filename):
            # I have a lock and file exists. Think of Cart as a
            # JS Object from where you can pick items to "process".
            return "Added To Cart"
        else:
            # I have a lock but looks like file was processed already.
            # So removing the residual "key" created.
            memcache.delete(filename)
            return "Processed by another user."
    else:
        # "add" can also fail if remote server is down,
        # but now we are not handling that now. It will
        # block the user's ability to process anything.
        user = memcache.get(filename)
        if user and os.file.ispath(filename):
           # I try my best to show the user processing it.
           print "Being processed by %s" % user
        else:
           # But lost the race to find that.
           print "Processed by another user."

def process(source):
    shutil.move(source, destination)
    filename = os.path.basename(source)
    memcache.delete(filename)

Directly calling process is not considered valid as it can only be done from user's Cart and by that user. If the logic is correct, Cart will only have valid files at any point of time and no two Carts would be having the same file ever. If a request from Cart comes to process a filename and it doesn't exist in the file-system then it is considered flawed.

Are there any race conditions or logical flaws that still exists?


texts:
I have this PHP script below that requests data from the Twitter API. The script then displays it on a page according to the information that I have in my local database. I stored Twitter real usernames so I can pass them to the API and display the profile images of those twitter users. The script works fine to display my request from the API but it is awfully slow, so I was wondering what could cause the script to be so slow.

The first part of my script seems to execute fine.

/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$url = $connection->get('statuses/user_timeline', array('screen_name' => $row['Twitter'],count=>'1'));
         $results  = json_encode($url);
         $data = json_decode($results, true);
         $image = '';
         if(is_array($data)){
         $image = $data[0]['user']['profile_image_url'];
         $image_bigger = str_replace('_normal', '_bigger',$image);
 }
 echo "
 $name Vs Opposition
";
 echo "";
?>

This part of the script below seems to be the culprit of the page. It takes lot of time to display the info because it loops through all the Twitter IDs returned by the query in order to display the images of the API's requested authors. The $data2 variable is a very long array of info regarding the Twitter user. From that array, I pick the key of the array containing the value that stores the picture of every Twitter user inside a loop.

How could I dynamically optimize this so the page can load faster?

 <?php
    $select2  = "SELECT * FROM AUTHORS WHERE ID <> $id";
    $result2 = mysql_query($select2);
    $result_count = mysql_num_rows($result2);
    $image_array = array();
    $unique_id = array();
    $counter = 0;
    if($result_count > 0) {
    while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
    array_push($unique_id, $row2['ID']);
    $url2 = $connection->get('statuses/user_timeline', array('screen_name' => $row2['Twitter'],count=>'1'));
             $results2  = json_encode($url2);
             $data2 = json_decode($results2, true);   // data through is a very long array
              $image2 = $data2[$counter]['user']['profile_image_url'];
              $image3 = str_replace('_normal', '_bigger',$image2);
              array_push($image_array,$image3);

           }
     }
     // the while loop above seems to be the culprit in the page taking too long to load.  Is there anyway I could optimize this?
    ?>

    <?php
     $unique_image = array_unique($image_array);
     $id_array = array_unique($unique_id);
      $i = 0;
      foreach($unique_image as $content) {
     echo "";
     $i++;
    }
    ?>


texts: Inserting a node to a given position in a linked list

texts:
Given

  You’re given the pointer to the head node of a linked list, an integer to add to the list and the position at which the integer must be inserted. Create a new node with the given integer, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty.

Solution

Node InsertNth(Node head, int data, int position) {
    Node newNode = new Node();
    newNode.data = data;
    newNode.next = null;

    if (head == null) {
        return newNode;
    }
    if (position == 0) {
        newNode.next = head;
        head = newNode;
        return head;
    }
    Node prev = null;
    Node current = head;
    int i = 0;
    while (current !=null && i < position) {
        prev = current;
        current = current.next;
        i++;
    }
    newNode.next = prev.next;
    prev.next = newNode;
    return head;
}

The code works fine. But I strongly feel that there is a chance of improvement. I see a lot of checks here, how can I reduce those and make my code more readable and covering all the edge cases?

Also, is there any recursive version possible for the given code because list is a recursive data structure hence, there should be some recursive way, right?


texts:
I have incremented an integer in the function nextpalin() and converted it into a std::string for finding whether it's a palindrome or not.

If it is a palindrome I return it. The code is giving TLE on SPOJ but working fine on other online IDEs; how to make this code more efficient?

#include <iostream>
#include <string.h>
using namespace std;
int nextpalin (int num){
    while (num++) {
        string str = to_string (num); /// int to string conversion
        int l = str.length()-1;
        int s = 0;
        while( s<l ){
              if (str[s]!=str[l]) break;
              else {
                    s++;
                    l--;
                    }
        if (s>=l) return num;}
                }
   }

int main () {
    int t;
    cin >> t;
    while (t--){
    int num;
    cin >> num;
    if (num==0)  cout << "1" << endl;
   else {
       if (num<9)  cout << num+1 << endl;
       else  cout << nextpalin( num) << endl;}
     }
}


texts:
I try to handle or catch possible errors with PHP/MySQL for security reasons and would like to know if I'm doing it right.

The first case, connection: I use it as a function and call it always when I need a database connection:

function pdo () {
  try {
    $pdo = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pw');
  }
  catch(PDOException $e) {
    header("Location: handle_error.php");
    exit;
  }
  return ($pdo);
}

The second case, a query: I am not sure how to handle it. I put all prepared statements in IF conditions but that's pretty awkward. And what about $stmt->execute? This could also fail or not? To handle this also in an if condition can really get confusing. I hope there is a better way to go.

if ($stmt = $pdo->prepare("SELECT a FROM b WHERE c = :c")) {
  $stmt->execute(array(':c' => $c));
  $result = $stmt->fetch();
  echo 'All fine.';
}
else {
  echo 'Now we have a problem.';
}

Later, I would like to report the errors properly so the admin can check what's going on.