texts:
I am solving the following problem on code chef:

  \$N\$ Soldiers are lined up for a memory test. They are numbered from 0 to N-1 from left to right.
  In the test, there are \$M\$ rounds. In each round, Captain selects one position. Soldier at that position will be numbered 0. All the soldiers to the right of selected position will be numbered one greater than the soldier to his left. All the soldiers to the left of selected position will be numbered one greater than the soldier to his right.
  eg. if \$N = 6\$ and selected position is 3, then the numbering will be \$[3, 2, 1, 0, 1, 2]\$.

  After \$M\$ rounds, Captain asked each soldier to shout out the greatest number he was assigned during the \$M\$ rounds. In order to check the correctness, Captain asked you to produce the correct values for each soldier (That is the correct value each soldier should shout out).

  Input
  - The first line of the input contains an integer \$T\$ denoting the number of test cases.
  - First line of each test case contains two integers, \$N\$ and \$M\$
  - Second line of each test case contains \$M\$ integers, the positions selected by Captain, in that order.

  Output
  For each test case, output one line with \$N\$ space separated integers.

  Constraints:
  \$1 ≤ T ≤ 10^4\$
  \$1 ≤ N ≤ 10^5\$
  \$1 ≤ M ≤ 10^5\$
  \$1 ≤ \sum{N} ≤ 10^5\$
  \$1 ≤ \sum{M} ≤ 10^5\$
  \$0 ≤ {Positions\ selected\ by\ captain} ≤ N-1\$

  Example

  Input

2
4 1
1
6 2
2 3

  Output

1 0 1 2
3 2 1 1 2 3

I have solved the problem using Java and my code runs perfectly fine in my PC but unfortunately I am getting Time Limit Exceeded for this code:

import java.io.*;
class ANUARM{
  public static void main(String[] s) throws Exception{
  BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  int testCases = Integer.parseInt(input.readLine());
  for(int i = 0 ; i < testCases ; ++i){
     String[] num = input.readLine().split(" ");
     int n = Integer.parseInt(num[0]);
     int m = Integer.parseInt(num[1]);
     int[] array = new int[n];
     String[] pos = input.readLine().split(" ");
     for(int j = 0 ; j<m ; ++j){
      int temp = Integer.parseInt(pos[j]);
      for(int k = 0 ; k<n ; ++k){
       int posAquired = temp - k;
        if(k > temp)
         posAquired = k-temp;
         if(posAquired > array[k])
          array[k] = posAquired;
      }
     }
     for(int a : array){
      System.out.print(a+" ");
     }
     System.out.println();
    }
  }
}

First I was using Scanner but I saw in FAQ that Scanner is slow, so I used BufferedReader BUT still I am getting TLE. Can anyone tell me where I can optimize my code as well as the do's-and-don'ts of optimization?


texts:
database.config.php

<?php
class Database
{

    private $host = "localhost";
    private $db_name = "trial";
    private $username = "root";
    private $password = "";
    public $conn;

    public function dbConnection()
    {

        $this->conn = null;
        try
        {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $exception)
        {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>

class.php

<?php
include_once 'database.config.php';
class USER
{
    private $conn;

    public function __construct()
    {
        $database = new Database();
        $db = $database->dbConnection();
        $this->conn = $db;
    }

    public function runQuery($sql)
    {
        $stmt = $this->conn->prepare($sql);
        return $stmt;
    }
}
?>

index.php

<?php
require_once 'class.php';
$user = new USER();

$teacher_fetch = $user->runQuery("SELECT * FROM teacher WHERE Id=:_id");
$teacher_fetch->execute(array(":_id"=>$_SESSION['teacher_id']));
$fetch_teacher = $teacher_fetch->fetch(PDO::FETCH_ASSOC);

echo $fetch_teacher['Name'];
?>

As it's a best practice to use close() in last where should I use it in the index.php file?

Option 1

$teacher_fetch->execute(array(":_id"=>$_SESSION['teacher_id']));

//close connection here

$fetch_teacher = $teacher_fetch->fetch(PDO::FETCH_ASSOC);
echo $fetch_teacher['Name'];

Option 2

$teacher_fetch->execute(array(":_id"=>$_SESSION['teacher_id']));
$fetch_teacher = $teacher_fetch->fetch(PDO::FETCH_ASSOC);

//close connection here

echo $fetch_teacher['Name'];

Option 3

$teacher_fetch->execute(array(":_id"=>$_SESSION['teacher_id']));
$fetch_teacher = $teacher_fetch->fetch(PDO::FETCH_ASSOC);
echo $fetch_teacher['Name'];

//close connection here

Or Somewhere else?

Also, how should I close it?

$user->close(); OR $teacher_fetch->close(); OR $fetch_teacher->close(); OR Something else?


texts: Finding if there is a subset that sums to a target value from an array of integers

texts:
I came across this problem.

  Problem Statement:

  Given an array of ints, is it possible to choose a group of some of
  the ints, beginning at the start index, such that the group sums to
  the given target? However, with the additional constraint that all 6's
  must be chosen.

  groupSum6(0, {5, 6, 2}, 8) → true
  groupSum6(0, {5, 6, 2}, 9) → false
  groupSum6(0, {5, 6, 2}, 7) → false

Below is my code:

public boolean groupSum6(int start, int[] nums, int target) {
if(nums.length==0)
  return target==0;

   if(start==nums.length-1)
    return target==nums[nums.length-1]||(target==0&&!(nums[nums.length-1]==6));

    if(target==0&&nums[start]==6)
    return false;
    if(target==0&&!(nums[start]==6))
      return groupSum6(start+1, nums, 0);

      if(groupSum6(start+1, nums, target-nums[start])||nums[start]==6)
      return groupSum6(start+1, nums, target-nums[start]);

      return groupSum6(start+1, nums, target);
}

Please feel free to review, or if you have a better solution in mind which uses lesser number of ifs, you can share it in your review.

EDIT: The code was written using a plain text editor so it's less readable, for a readable version of code you may have a look here As there is already one review which explains about readability so request to review keeping the code optimization in view.


texts:
This function checks if a file name is valid or not.  I think it's not good enough for integration (not optimized, maybe I forgot about some checks), so need your comments.

static
int ReservedName( const char * name )
{
    char * reservedFileNames[] = { "CON",  "PRN",  "AUX",  "NUL",
                                   "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
                                   "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" };

    char * reservedFileNamesWithDot[] = { "CON.",  "PRN.",  "AUX.",  "NUL.",
                                          "COM1.", "COM2.", "COM3.", "COM4.", "COM5.", "COM6.", "COM7.", "COM8.", "COM9.",
                                          "LPT1.", "LPT2.", "LPT3.", "LPT4.", "LPT5.", "LPT6.", "LPT7.", "LPT8.", "LPT9." };

    int i;
    int n = sizeof( reservedFileNames ) / sizeof( reservedFileNames[0] );

    for( i = 0; i < n; i++ )
    {
        if( stricmp( reservedFileNames[i], name ) == 0 )
        {
            return 1;

        }else{

            if( strnicmp( reservedFileNamesWithDot[i], name, strlen( reservedFileNamesWithDot[i] ) ) == 0 )
            {
                return 1;
            }
        }
    }

    return 0;
}

static
int GetCharsNumInPath( IN const char * path )
{
    int i, cnt;

    for( i = 0; path[i]; i++ )
    {
        if( ( path[i] < 0x80 ) || ( path[i] > 0xbf ) )
            cnt++;
    }

    return cnt;
}

int ValidName( const char * name )
{
    if( name != NULL )
    {
        if( GetCharsNumInPath( path ) <= MAX_PATH )
        {
            if( ! ReservedName( name ) )
            {
                int i;
                int n = strlen( path );

                for( i = 0; i < n; i++ )
                {
                    switch( path[i] )
                    {
                        // ? " / < > * |
                        // these characters can not be used in file or folder names
                        //
                        case '<':
                        case '>':
                        case '/':
                        case '\\':
                        case '\"':
                        case '?':
                        case '*':
                        case '|':
                            return 0;

                        case ' ':
                        case '.':
                        {
                            if( ( i + 1 == n ) )
                            {
                                return 0;

                            }else{

                                continue;
                            }
                        }
                    }
                }

                return 1;

            }else{ // if( ! ReservedName( name ) )

                return 0;
            }

        }else{ // if( GetCharsNumInPath( IN path ) <= MAX_PATH_LEN )

            return 0;
        }

    }else{ // if( name != NULL )

        return 0;
    }
}


texts: Correctly using promises with node-mysql

texts:
I have been trying to do a simple query and return the results with node-mysql however I had several problems. Originally I wrote it where there was no promise, but if I tried to access user after just doing a query if returned undefined
The solution I came up with is the following, is this a good way of doing it? I need to wait until the results come back so I can then send a signal to the frontend to say the player is loaded and can play. Do I need to create a new promise for each query? I have a few tables I need to get data from (That can't be done with joins)
class Player {
    constructor(user_id, socket, connection) {
        this.socket = socket;
        this.connection = connection;

        this.loadUser(user_id)
            .then(() => {
                console.log("loaded user", this.user);
            });
    }

    async loadUser(user_id) {
        let _self = this;
        return new Promise((resolve, reject) => {
            _self.connection.query(`SELECT * FROM users WHERE id = ${user_id}`, (err, res) => {
                this.user = res[0];
                resolve()
            });
        })
    }
}
```


texts: Recurrent merge sort (without recursion)

texts:
For educational purpose I implement recurrent merge sort without recursion. The algorithm idea seems absolutely clear but my implementation appears to be really slow:

5 seconds to sort 10,000 values;
6 minutes to sort 100,000 values;
it was not able to finish 10,000,000 in several hours (while lib sort() function does it in aboit 6 seconds);

I guess, the problem is in my understanding of how C++ works. Maybe, I must not copy vectors to funtion and use pointers insted?

#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>

void check_sort(std::vector<int> array); //test sorted arrays
void merge_sort(std::vector<int> array); //recurrent merge sort
std::vector<int> merge(std::vector<int> array, unsigned int b, unsigned int c, unsigned int e);

int main()
{
    unsigned int size;
    std::cout << "Please enter the size of your array:" << std::endl;
    std::cin >> size;

    std::vector<int> initial_array(size); //array of random elements

    //prefill arrays
    srand(time(0));
    for (unsigned int i; i < initial_array.size(); ++i) {
        initial_array[i] = rand();
    }

    merge_sort(initial_array);

 /* DEBUGGER
    std::cout << "initial array" << std::endl;
    for (unsigned int i = 0; i < initial_array.size(); ++i) {
        std::cout << initial_array[i] << " ";
    }
    std::cout << std::endl;
*/

    return 0;
}

void merge_sort(std::vector<int> array)
{
    std::cout << "merge sort" << std::endl;
    check_sort(array);
    /* DEBUGGER
    std::cout << "initial array" << std::endl;
    for (unsigned int i = 0; i < array.size(); ++i) {
        std::cout << array[i] << " ";
    } */

    float start_time =  clock();
    unsigned int n = array.size();
    for (unsigned int s = 1; s < n; s *= 2)
    {
        for (unsigned int b = 0; b < n; b += s*2)
        {
            unsigned int c = std::min(b + s - 1, n - 1);
            unsigned int e = std::min(c + s, n - 1);
            array = merge(array, b, c, e);
        }
    }
    float end_time = clock() - start_time;
    /* DEBUGGER
    for (unsigned int i = 0; i < array.size(); ++i) {
        std::cout << array[i] << " ";
    } */
    check_sort(array);
    std::cout << "time: " << end_time/1000 << std::endl;
}

std::vector<int> merge(std::vector<int> array, unsigned int b, unsigned int c, unsigned int e) {
    std::vector<int> C(array);
    unsigned int i1 = b; unsigned int i2 = c + 1; //start point in each piece
    unsigned int n1 = c; unsigned int n2 = e; //end point of each piece
    for (unsigned i = b; i <= e; ++i)
    {
        if (i1 > n1) //
        {
            C[i] = array[i2];
            ++i2;
        }
        else if (i2 > n2)
        {
            C[i] = array[i1];
            ++i1;
        }
        else if (array[i1] <= array[i2]) {
            C[i] = array[i1];
            ++i1;
        }
        else
        {
            C[i] = array[i2];
            ++i2;
        }
    }
    return C;
}

void check_sort(std::vector<int> array)
{
    for (unsigned int i = 0; i < (array.size() - 1); ++i)
    {
        if (array[i] > (array[i + 1]))
        {
            std::cout << "unsorted" << std::endl;
            return;
        }
    }
    std::cout << "sorted" << std::endl;
}


texts: Find k-distinct partitions which contain at least two perfect squares

texts:
Problem Statement:

  A k-distinct-partition of a number \$n\$ is a set of \$k\$ distinct positive integers that add up to \$n\$. For example, the 3-distinct partitions of 10 are

  \$1+2+7\$
  \$1+3+6\$
  \$1+4+5\$
  \$2+3+5\$

  The objective is to count all k-distinct partitions of a number that have at least two perfect squares in the
  elements of the partition.
  Note that 1 is considered a perfect square.

Constraints

  \$k<N<200\$, so that at least one k-distinct partition exists.

Input Format

  The input consists of one line containing of \$N\$ and \$k\$ separated by a comma.

Output

  One number denoting the number of k-distinct partitions of N that have at least two perfect squares in the
  elements of the partition.

Explanation

  Example 1

  Input

  10, 3

  Output

  1

  Explanation: The input asks for 3-distinct-partitions of 10. There are 4 of them (1+2+7, 1+3+6, 1+4+5 and
  2+3+5). Of these, only 1 has at least two perfect squares in the partition (1+4+5).

  Example 2

  Input

  12, 3

  Output

  2

  Explanation
  The input asks for 3-distinct partitions of 12. There are 7 of them (9+2+1, 8+3+1,7+4+1,7+3+2,6+5+1,
  6+4+2, 5+4+3). Of these, two, (9+4+1, 7+4+1) have two perfect squares. Hence, the output is 2.

My code hangs when the numbers are big,  e.g. when N = 150 and k = 30

The code

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

int a[200];
int count=0;
int n,k;
int i,sum,perf;

void func(int,int);
int perfect(int number);

int main()
{
    scanf("%d,%d",&n,&k);
    func(0,1);
    printf("%d",count);

    return 0;
}

void func(int index,int val){
    sum=0,perf=0;
    if(index==k){
        for(i=0;i<k;i++){
            sum=sum+a[i];
        }
        if(sum==n){
            for(i=0;i<k;i++){
                if(perfect(a[i])){
                    perf++;
                }
            }
            if(perf>=2){
                count++;
            }
        }
    }
    else{
        a[index]=val;
        for(i=a[index];a[index]<n;a[index]++){
            func(index+1,a[index]+1);
        }
    }
}

int perfect(int number)
{
    int iVar;
    float fVar;

    fVar=sqrt((double)number);
    iVar=fVar;

    if(iVar==fVar) return 1;
    else return 0;
}


texts: Find combinations of items in a nested collection

texts:
It's a very typical problem that I come across here and there. Imagine that you have a collection of items of any type, and sometimes items are collections themselves; you then need to "expand" them and thus multiply the number of items in the result by number of items in that collection. An example would explain it better; consider input/output pairs:

[] -> [[]]
[1] -> [[1]]
[1 2 3 4 5] -> [[1 2 3 4 5]]
[[1 2] 3 4 5] -> [[1 3 4 5] [2 3 4 5]]
[[1 2] 3 [4 5]] -> [[1 3 4] [2 3 4] [1 3 5] [2 3 5]]

so, an entirely one-dimensional collection resolves into itself; a collection where some items are collections of M, N, O items result in a collection of order M×N×O.

The code I've come up with so far is this:

(defn smash [xs ys]
  (if-not (coll? ys)
    (map conj xs (repeat (count xs) ys))
    (mapcat #(smash xs %) ys)))

(defn extrusion [input]
  (loop [result [[]]
         xs input]
    (if (empty? xs)
      result
      (recur (smash result (first xs))
             (rest xs)))))

It gives me the result I need:

user=> (extrusion [])
[[]]
user=> (extrusion [1])
([1])
user=> (extrusion [1 2 3 4 5])
([1 2 3 4 5])
user=> (extrusion [[1 2] 3 4 5])
([1 3 4 5] [2 3 4 5])
user=> (extrusion [[1 2] 3 [4 5]])
([1 3 4] [2 3 4] [1 3 5] [2 3 5])

as well as it works for any number of layers.

Now, I have a very strong sensation that there is a way better solution; perhaps a function from clojure.combinatorics that I'm missing. I'm not talking about time-efficiency at this point, it's purely about lines of code.

If there's a shorter way to express this solution, I'd be super happy to know it. Thanks!


texts: Ideas for reducing repetition in control binding

texts:
I have seven checkboxes on a data maintenance WinForm, which indicate the days of the week that are "valid" for a particular operation to be performed. These "map" to a list of DayOfWeek enum values on the backing domain object; if the value is present in the list, the box should be checked, otherwise not. Any combination of boxes can be checked. In the "bind" method that sets the UI controls to the proper values of the domain object, here's how those checkboxes are set:

chkValidDayMon.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Monday);
chkValidDayTue.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Tuesday);
chkValidDayWed.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Wednesday);
chkValidDayThu.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Thursday);
chkValidDayFri.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Friday);
chkValidDaySat.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Saturday);
chkValidDaySun.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Sunday);

The code to read the UI controls' state back out to the domain object is similar; if the box is checked, add the corresponding value to a "clean" (initially empty) list and assign it to the object.

This smells. I was thinking of adding a Dictionary containing the checkboxes and keyed to their corresponding DayOfWeek. But, that sounds like a bit much as well (it certainly wouldn't save many LoC). Any other suggestions?


texts: Two solutions with min max values - which should be slower?

texts:
While practicing at codinbat.com on the assignment:

  Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in Math.min(v1, v2) and Math.max(v1, v2) methods return the smaller or larger of two values.

I wrote a solution (1):

public int bigDiff(int[] nums)
{
    int min = nums[0];
    int max = nums[0];

    for (int i = 1 ; i < nums.length; i++)
    {
        if (nums[i] < min)
        {
            min = nums[i];
        }
        if (nums[i] > max)
        {
            max = nums[i];
        }
    }

    return max - min;
}

You can see it has no Math.min or Math.max calls. So then I rewrote the solution to see how it looks with Math.min and Math.max:

public int bigDiff(int[] nums)
{
    int min = nums[0];
    int max = nums[0];

    for (int i = 1 ; i < nums.length; i++)
    {
        min = Math.min(nums[i],min);
        max = Math.max(nums[i],max);
    }

    return max - min;
}

The solution became a little shorter, but I think it makes unnecessary assignments when going through the array.

Is solution (2) in general slower than solution (1)?


texts:
I've been practicing implementing a linked list from scratch. Can someone help review my code?

class Node {
    Node next;
    int num;

    public Node(int val) {
        num = val;
        next = null;
    }
}

public class LinkedList {

    Node head;

    public LinkedList(int val) {
        head = new Node(val);
    }

    public void append(int val) {
        Node tmpNode = head;
        while (tmpNode.next != null) {
            tmpNode = tmpNode.next;
        }
        tmpNode.next = new Node(val);
    }

    public void insert(int val) {
        Node currentNode = head;
        Node nextNode = head.next;

        if (currentNode.num > val) {
            Node tmpNode = head;
            head = new Node(val);
            head.next = tmpNode;
            return;
        }

        if (nextNode != null && nextNode.num > val) {
            currentNode.next = new Node(val);
            currentNode.next.next = nextNode;
            return;
        }

        while (nextNode != null && nextNode.num < val) {
            currentNode = nextNode;
            nextNode = nextNode.next;
        }

        currentNode.next = new Node(val);
        currentNode.next.next = nextNode;
    }

    public void delete(int val) {
        Node prevNode = null;
        Node currNode = head;

        if (head.num == val) {
            head = head.next;
            return;
        }

        while (currNode != null && currNode.num != val) {
            prevNode = currNode;
            currNode = currNode.next;
        }

        if (currNode == null) {
            System.out.println("A node with that value does not exist.");
        }
        else {
            prevNode.next = currNode.next;
        }

    }

    public void print() {
        Node tmpNode = head;
        while (tmpNode != null) {
            System.out.print(tmpNode.num + " -> ");
            tmpNode = tmpNode.next;
        }
        System.out.print("null");
    }

    public static void main(String[] args) {
        LinkedList myList = new LinkedList(5);
        myList.append(7);
        myList.append(16);
        myList.insert(9);
        myList.insert(4);
        myList.insert(6);
        myList.insert(17);
        myList.delete(16);
        myList.delete(5);
        myList.delete(4);
        myList.delete(17);
        myList.delete(34);
        myList.print();
    }
}


texts:
At the moment I try to get used to SQLite and Python. I started with insert, select and so on. But now i want to get a bit further.
Now I have a DB with 200 rows for testing and in want to update two values of each row in this case called "Test2" and "Test3". My problem is that those two values should be the value that they have +200 and +400 so i have to make an select before updating them (at least with my knowledge).

I added a simple time measurement to my code to see if i will be able to make my code more efficient and faster!

At the moment it takes 0.7344 seconds for me to edit 200 rows of data. Which is pretty slow! Especially if i think to do it for bigger DB's.

Things I want to achieve:

Is it really necessary to make the select or could I use the present Data in any other way?
Make things faster! Is it possible to edit multiple rows at the same time? Like parallelized tasks?

Any other tips are welcome, as i try to improve myself!

Here is my code so far:

import sqlite3
import time

def database_test():
    # Open Database
    conn = sqlite3.connect('SQLite_Test.db')
    c = conn.cursor()

    i = 0

    for i in range(200):
        c.execute('SELECT Test2, Test3 FROM Test WHERE Test1 = ?',  (i,))

        DB_Values = []
        DB_Values = c.fetchone()

        Value1 = DB_Values[0]+200
        Value2 = DB_Values[1]+400

        c.execute('''UPDATE Test SET Test2 = ?, Test3 = ? WHERE Test1= ?''', (Value1, Value2, i))
        i += 1

    # Save (commit) the changes
    conn.commit()

start_time = time.time()
database_test()
print("--- %s seconds ---" % round((time.time() - start_time),4))


texts: Criticism on x86_64 nasm assembly strToInt and printInt implementation

texts:
I am pretty new to assembly I would like criticism on two "methods" I have written. One converts string to int and the other prints an int to stdout. Any advise helps out.
bits 64

section .data
endl db 10, 0
endlLength equ $ - endl

section .bss
   string resb 100

section .text
global _start
global _strToInt
global _printInt

_start:
   mov rbp, rsp

   ;get int from user
   mov rax, 0
   mov rdi, 0
   lea rsi, [string]
   mov rdx, 100
   syscall

   ;make string to int
   push string
   call _strToInt
   pop r8

   push rax
   call _printInt
   pop  rax

   mov rax, 1
   mov rdi, 1
   mov rsi, endl
   mov rdx, endlLength
   syscall

   mov rax, 60
   mov rbx, 0
   syscall

   ;last value pushed to stack must be address to string. stores int in rax
_strToInt:
  ;prolog
  push rbp
  mov rbp, rsp
  ;save registers
  push rbx

  ;actual code
  xor rax, rax
  mov rbx, 10          ;will be used to multiply by 10 later

  mov rcx, [rbp + 16]
  cmp byte[rcx], '-'   ;check to see if value is negetive
  jne _convertStringLoop
  inc rcx              ;increment the address

  _convertStringLoop:
     xor rdx, rdx      ;clear rdx
     mul rbx           ;multiply rax by 10
     mov dl, [rcx]     ;get 1 byte from rcx address
     sub dl, '0'       ;seb by '0' to get actual value
     add rax, rdx      ;add it to rax
     inc rcx
  cmp byte[rcx], 10    ;see if new line char. exit if new line char
  je _exitConvertStringLoop
  cmp byte[rcx], 0     ;see if end of line char. exit if end of line
  jne _convertStringLoop

  _exitConvertStringLoop:
  mov rcx, [rbp + 16]
  cmp byte[rcx], '-'   ;if not negetive jump
  jne _exitStrToInt
  not rax              ;1's complement (make negetive)
  inc rax              ;2's complement (make negetive)

  _exitStrToInt:
  ;restore registers
  pop rbx
  ;epilog
  pop rbp
  ret

;last value pushed to stack will be printed
_printInt:
  ;prolog
  push rbp
  mov rbp, rsp
  ;save registers
  push rbx

  ;actual code
  mov rsi, rsp
  mov rax, [rbp + 16] ;get the value that user wants to print
  mov rbx, 10         ;will be used to divide by 10 later
  xor rcx, rcx

  cqo
  cmp rdx, -1         ;check to see if negetive
  jne _divisionLoop   ;if not negetive jump

  ;print negetive sign
  mov [rsi + 1], byte '-'
  mov rax, 1
  mov rdi, 1
  inc rsi
  mov rdx, 1
  syscall
  dec rsi

  ;convert to positive number
  mov rax, [rbp + 16]
  ;imul rax, -1
  dec rax
  not rax
  xor rcx, rcx

  _divisionLoop:
     xor rdx, rdx
     div rbx        ;divides number by 10 to move over last digit into rdx reg
     add dl, '0'
     dec rsi
     mov [rsi], dl
     inc rcx        ; count for how many digits added to stack
  cmp rax, 0
  jnz _divisionLoop ;jump if the division did not result in a zero

  ;print all the values
  mov rax, 1
  mov rdi, 1
  mov rdx, rcx
  syscall

  ;restore register
  pop rbx
  ;epilog
  pop rbp
  ret

One more thing I wanted to ask was is it better to do
     mov rax, -20
     mov rbx, -1
     imul rbx

or
     mov rax, -20
     dec rax
     not rax

when I know a number is negetive and I want to turn it to a positive.


texts:
I have written two queries for searching, but I want to simplify them as it seems needed.

def searching(term: String): List[String] = {
    DB.withConnection { implicit c =>
      var list = List[String]()
      val pinfo = SQL("SELECT body FROM tableName WHERE body like {term} limit 0,14 ").on("term" -> ("%" + term + "%"))()
      pinfo.map {
        row =>
          list ::= row[String]("body")
      }
      val res = SQL("SELECT body FROM tableName WHERE MATCH (body) AGAINST ({term} IN BOOLEAN MODE) limit 0,14 ").on("term" -> term)()
      res.map {
        row =>
          list ::= row[String]("body")
      }
      return list.distinct
    }
  }


texts: Desktop Notifications for Queue Items - Updated Code

texts:
A while ago I took one of @Simon's scripts and updated it to make it more geared towards normal users (no offense mods) and this Question was created. But the link to the Github is no longer correct and the code has changed quite a bit to get it to work on Firefox and Chrome (and Opera and IceDragon and Safari).

I would like to know if my code is following UserScript and JavaScript standards and if there is anything that I can do to improve the efficiency of the code itself.

Here is the current Next version

Notification.requestPermission();

var KEY_NEXT = 'NextReload';
var DELAY =  120 * 1000; //120,000 milliseconds = 2 Minutes
var currentTime = Date.now ? Date.now() : new Date().getTime();
var lastTime = GM_getValue(KEY_NEXT, 0);
var nextTime = currentTime + DELAY;
GM_setValue(KEY_NEXT, nextTime);

var timeDiff = Math.abs(lastTime - currentTime);
setTimeout(function(){
    window.location.reload();
}, DELAY);

var notificationTitle = (document.title.split(' - ')[1] + ' Review Queue').replace(' Stack Exchange', '.SE');

// a way to detect that the script is being executed because of an automatic script reload, not by the user.
if (timeDiff <= DELAY * 2) {
    var reviewCount = 0;
    var reviewItems = document.getElementsByClassName('dashboard-num');

    for (var i = 0; i < reviewItems.length; i++){
        if (reviewItems[i].parentNode.className != 'dashboard-count dashboard-faded'){
            reviewCount += parseInt((reviewItems[i].getAttribute("title")).replace(',', ''), 10);
            console.log(reviewItems[i]);
        }
    }
    console.log(reviewCount);

    if (reviewCount > 0) {
        var details = {
            body: reviewCount + ' Review Items',
            icon: 'https://github.com/malachi26/ReviewQueueNotifier/raw/master/Resources/Icon2.jpg'
        }
        var n = new Notification(notificationTitle, details);
        n.onclick = function(){
            window.focus();
            this.cancel();
        }
        setTimeout(n.close.bind(n), 100000); // Magic number is time to notification disappear
    }
}

You can follow development or participate in development at Github as well.

Review Queue Notifier


texts:
I'm investigating Go for use in our internal network / office project management system, and need a way to check and edit the color tags that you can set in Finder on files or folders (extended attributes, xattrs).  This is my first Go code.  Is this a reasonable way to go about it, and is the interface something that makes sense?

Using a const() "fake enum" type thing, with a type TagColor like this - is this going to annoy users who just want a straight int, or is it actually helpful for keeping things typed?  Likewise putting a String() method for the type - I find it pretty helpful, but is this just making things needlessly bloated?

I want it to be a friendly interface to work with, and not be over-engineered or over-complex.

This is currently just this one file:

/*
 * OSX Tags
 * (C) 2014 Daniel Fairhead
 * MIT Licence
**/

package osxtags

import "fmt"

import "github.com/AlexSi/xattr"
import "howett.net/plist"

type TagColor int

const (
    None   TagColor = 0
    Gray   TagColor = 1
    Green  TagColor = 2
    Purple TagColor = 3
    Blue   TagColor = 4
    Yellow TagColor = 5
    Red    TagColor = 6
    Orange TagColor = 7
)

func (t TagColor) String() string {
    switch t {
    case None:
        return "None"
    case Gray:
        return "Gray"
    case Green:
        return "Green"
    case Purple:
        return "Purple"
    case Blue:
        return "Blue"
    case Yellow:
        return "Yellow"
    case Red:
        return "Red"
    case Orange:
        return "Orange"
    }
    return "unknown"
}

type ColorTag struct {
    Color TagColor
    Name  string
}

func GetColors(filename string) ([]ColorTag, error) {

    // pull out the raw metadata:

    colormeta, err := xattr.Get(filename, "com.apple.metadata:_kMDItemUserTags")

    if err != nil {
        return nil, err
    }

    // decode it from a binary plist:

    colList := []string{}

    _, err = plist.Unmarshal(colormeta, &colList)

    if err != nil {
        return nil, err
    }

    // split the stupid "\n" items into (color, name) pairs.

    toReturn := make([]ColorTag, len(colList), len(colList))

    for i, col := range colList {
        fmt.Sscanf(col, "%s\n%d", &toReturn[i].Name, &toReturn[i].Color)
    }

    return toReturn, nil

}


texts: Using enum to create, subscript and loop an array of structs in Swift 5.0

texts:
I'm trying to "build" a few "spaceships" in my code. I'm feeling it's a good idea to enumerate all the spaceships and use that as a subscript to build and use an array that holds the spaceships' properties. After researching Stack Overflow and other places, I found a solution that works, but I'm feeling it's not very elegant and I'm probably not making good use of the Swift language. I'm also unhappy with having to define the name (string) of the spaceship again (and not using the enum case for that).

Do I miss the obvious cleaner solution? Any suggestions for a better solution?

enum SpaceshipName: Int, CaseIterable {
  case Orion
  case Vega
  case Gemini
}

struct SpaceshipProperties {
  var name: String = "TBD"
  var fuel: Int = 0
  var speed: Int = 0
}

// Initialize the spaceships:

var spaceShips = [SpaceshipProperties]()

for s in SpaceshipName.allCases {
  spaceShips.append(SpaceshipProperties())
}

// Now start using the spaceships:

spaceShips[SpaceshipName.Orion.rawValue].name = "Orion"
spaceShips[SpaceshipName.Orion.rawValue].fuel = 100
spaceShips[SpaceshipName.Gemini.rawValue].speed = 2200
// ... and so forth

// Ultimately, I want to iterate through the spaceships in the following manner:

for s in SpaceshipName.allCases {
  // Perform calculations with all the spaceships here, for example:
  let newSpeed = spaceShips[s.rawValue].speed + 10
  spaceShips[s.rawValue].speed = newSpeed
}
```


texts:
I have polylines in a GIS database. The polylines are stored using a user-defined type called ST_GEOMETRY.

ST_GEOMETRY has lots of spatial functions. However, it does not have a polyline midpoint function.

Therefore, I have written a custom PL/SQL midpoint function to fill this gap.

As a novice programmer, I'm wondering, how can the code be improved to be as fast and robust as possible?

-- execute this as the SDE user
create or replace function ST_MidPoint
   (line_in IN sde.st_geometry)
   RETURN sde.st_geometry
IS midpoint sde.st_geometry;
  srid integer;
  line_length number(38);
  num_parts integer;
  num_points integer;
  partNum integer;
  distanceAlong number(38);
  segmentLength number(38);
  part sde.st_geometry;
  p1 sde.st_geometry;
  p2 sde.st_geometry;
  x1 double precision;
  y1 double precision;
  x2 double precision;
  y2 double precision;
BEGIN
  -- get the SRID of the line for later use in constructing the midpoint geometrey
  select sde.st_srid (line_in)
  into srid
  from dual;

  -- calculate the total length of the line
  select sde.st_length(line_in)
  into line_length
  from dual;

  -- get the number of parts that make up the line
  select sde.st_numgeometries(line_in)
  into num_parts
  from dual;

  distanceAlong := 0;
  for partNum in 1..num_parts loop
    --dbms_output.put_line(partNum);
    -- get the geometry for this part
    select sde.st_geometryn(line_in, partNum)
    into part
    from dual;

    -- get the number of points that make up this part
    select sde.st_numpoints(part)
    into num_points
    from dual;
    --dbms_output.put_line(num_points);

    -- get the first point (the "from" point) for the part
    select sde.st_pointn (part, 1)
    into p1
    from dual;

    -- iterate along the line until the section that contains the midpoint is found
    for pointNum in 2..num_points loop
      -- get the "to" point of the segment
      select sde.st_pointn(part, pointNum)
      into p2
      from dual;

      -- calculate the distance between the from point and the to point
      select sde.st_distance(p1, p2)
      into segmentLength
      from dual;

      -- add the distance along this segment to the running total
      distanceAlong := distanceAlong + segmentLength;
      --dbms_output.put_line(distanceAlong);
      -- check to see if the running total is past the midpoint
      if distanceAlong >= line_length/2.0 then
        -- the two current points encompass the midpoint of the line
        -- determine the midpoint geometry and return it
        select sde.st_x(p1)
        into x1
        from dual;
        select sde.st_y(p1)
        into y1
        from dual;
        select sde.st_x(p2)
        into x2
        from dual;
        select sde.st_y(p2)
        into y2
        from dual;
        select sde.st_point((x1+x2)/2.0, (y1+y2)/2.0, srid)
        into midpoint
        from dual;
        -- the midpoint has been found, not need to interogate the rest of the line
        RETURN midpoint;
      end if;
      -- save the endpoint as the first point and continue down the line looking for the midpoint
      p1:=p2;
    end loop;
  end loop;

  return null;

EXCEPTION
WHEN OTHERS THEN
   raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END;
/
grant execute on ST_MidPoint to public;

--select objectid,sde.ST_MidPoint(shape) geom
--from gis.line_test
--order by objectid;

Update:

I have abandoned this function. It works, but it's horrendously inefficient because it's not possible to use the SDE functions & operators to directly assign values to variables. I needed to wrap them in queries instead.

More information here:
Use SDE.ST_GEOMETRY functions in a custom function

Originally, I had thought that the code could be improved. However, now I realize that this is not possible--due to the aforementioned problem.

It would be my preference that this question be deleted (I tried but couldn't because there's an answer).


texts: Optimizing jQuery addclass / removeclass on scroll

texts:
I have a scroll event and add class and remove classes for different elements. As you can see the code is a bit big. Is this method ok or is there a more efficient one?

I mean, you can see that there are no child elements. I could use .siblings() for some but, as you can see, I also serve unique classes.

Any idea? I know it looks bad but I think it is the only way.

 $(document).ready(function () {
        $(window).scroll(function () {
            var scroll = $(window).scrollTop();

            if (scroll >= 50) {
                $("nav ul li").addClass("list-mini");
                $("nav").addClass("nav-mini");
                $("nav ul li a").addClass("nav-recolor");
                $("nav img").removeClass("zoomOutLeft");
                $("nav img").addClass("zoomInUp");
                $("nav img").addClass("logo-mini-active");
                $("nav ul").addClass("margin-transition");
                $("ul").addClass("ul-active");
                $("nav ul li a span").addClass("text-removed");
                $("nav ul li a").addClass("nav-font");
                $("nav ul li a span").addClass("transition-02s");
                $(".fa-shopping-cart").addClass("fa-shopping-cart-mini");
                $(".fa-globe").addClass("fa-globe-mini");
                $(".fa-info").addClass("fa-info-mini");
                $(".fa-circle-o-notch").addClass("fa-circle-o-notch-mini");
                $(".fa-envelope-o").addClass("fa-envelope-o-mini");
            } else {
                $("nav ul").removeClass("margin-transition");
                $("nav ul li").removeClass("list-mini");
                $("nav").removeClass("nav-mini");
                $("nav ul li a").removeClass("nav-recolor");
                $("nav img").removeClass("zoomInUp");
                $("nav img").addClass(" zoomOutLeft");
                $("ul").removeClass("ul-active");
                $("nav ul li a span").removeClass("text-removed");
                $("nav ul li a").removeClass("nav-font");
                $("nav ul li a span").removeClass("transition-02s")
                $(".fa-shopping-cart").removeClass("fa-shopping-cart-mini");
                $(".fa-globe").removeClass("fa-globe-mini");
                $(".fa-info").removeClass("fa-info-mini");
                $(".fa-circle-o-notch").removeClass("fa-circle-o-notch-mini");
                $(".fa-envelope-o").removeClass("fa-envelope-o-mini");
            }
        });
    });


texts: Function which returns the smallest / largest numbers in a nested array structure

texts:
Given is an array which contains sub-arrays. The elements in this sub-arrays are numbers.

The task is to implement a JavaScript-function which returns an array with the smallest / largest numbers in the single arrays.

I have figured out this solution:

// Returns the smallest / largest
//   numbers contained in a
//   set of arrays.

// Parameter ---------------------
// 1.: Array - Containing other arrays.
// 2.: Function - Either Math.max or
//  Math.min

// Return -------------------------
// Array - Containing numbers in case
//  of success.
//  Containing 'undefined' in case
//  of elements which aren't arrays.
//  Containing NaN in case of elements
//  which aren't numbers.

function getExtrema(structure, funct) {

  var ret = structure.map(function(value) {
    if (Array.isArray(value)) {
      return funct.apply(null, value);
    }
  });

  return ret;
}

Complete code (with examples) on CodePen: http://codepen.io/mizech/pen/bEBMaW?editors=101

Are there better ways to solve the described task?


texts:
This is what the function is doing: it gets two arrays of tuples with 5 items each - hand = [H1,H2,H3,H4,H5] and board = [B1,B2,B3,B4,B5]

What I need to do is check all arrays formed by 2 items from hand and 3 items from board, like combination = [Hn,Hm,Bi,Bj,Bk] (100 combinations in total)

Then I need to compare each one of the combinations against a dictionary to get the combination rank, and then return the best array (best rank) and the rank itself:

def check_hand(hand, board, dictionary_A, dictionary_B):

 best_hand = []
 first_int = True

 for h1 in range (0, 4):
  for h2 in range (h1+1, 5):
   for b1 in range (0, 3):
    for b2 in range (b1+1, 4):
     for b3 in range (b2+1, 5):
      hand_check = []
      hand_check.append(hand[m1])
      hand_check.append(hand[m2])
      hand_check.append(board[b1])
      hand_check.append(board[b2])
      hand_check.append(board[b3])
      hand_check = sort(hand_check) #Custom sort for my array of objects
      hand_ranks = "".join([str(hand_check[0].rank),str(hand_check[1].rank),str(hand_check[2].rank),str(hand_check[3].rank),str(hand_check[4].rank)])

      if (hand_check[0].suit == hand_check[1].suit and hand_check[1].suit == hand_check[2].suit and hand_check[2].suit == hand_check[3].suit and hand_check[3].suit == hand_check[4].suit):
       control = [dictionary_A[hand_ranks][0],dictionary_A[hand_ranks][1]]
      else:
       control = [dictionary_B[hand_ranks][0],dictionary_B[hand_ranks][1]]

      if first_int:
       best_hand = hand_check
       rank = control
       first_int = False
      elif (int(control[0]) > int(rank[0])):
       rank = control
       best_hand = hand_check
      elif (int(control[0]) == int(rank[0])):
       if (int(control[1]) > int(rank[1])):
        rank = control
        best_hand = hand_check

 return best_hand, rank[0]

I need to run this check for 2 million different hands and interact over 1000 times for every hand (Ideally I would run it for at least 100000 times for every hand, for a more statistically accurate result).
Any ideas on how to make it more efficient?

Examples:
I added some "prints" on the way for better understanding:

Hand: Q♥K♥Q♠K♠3♦
Board: 2♣2♥J♦6♥4♦

2♣2♥J♦Q♥K♥ - 2♣2♥6♥Q♥K♥ - 2♣2♥4♦Q♥K♥ - 2♣6♥J♦Q♥K♥ - 2♣4♦J♦Q♥K♥ -
   2♣4♦6♥Q♥K♥ - 2♥6♥J♦Q♥K♥ - 2♥4♦J♦Q♥K♥ - 2♥4♦6♥Q♥K♥ - 4♦6♥J♦Q♥K♥ -
   2♣2♥J♦Q♥Q♠ - 2♣2♥6♥Q♥Q♠ - 2♣2♥4♦Q♥Q♠ - 2♣6♥J♦Q♥Q♠ - 2♣4♦J♦Q♥Q♠ -
   2♣4♦6♥Q♥Q♠ - 2♥6♥J♦Q♥Q♠ - 2♥4♦J♦Q♥Q♠ - 2♥4♦6♥Q♥Q♠ - 4♦6♥J♦Q♥Q♠ -
   2♣2♥J♦Q♥K♠ - 2♣2♥6♥Q♥K♠ - 2♣2♥4♦Q♥K♠ - 2♣6♥J♦Q♥K♠ - 2♣4♦J♦Q♥K♠ -
   2♣4♦6♥Q♥K♠ - 2♥6♥J♦Q♥K♠ - 2♥4♦J♦Q♥K♠ - 2♥4♦6♥Q♥K♠ - 4♦6♥J♦Q♥K♠ -
   2♣2♥3♦J♦Q♥ - 2♣2♥3♦6♥Q♥ - 2♣2♥3♦4♦Q♥ - 2♣3♦6♥J♦Q♥ - 2♣3♦4♦J♦Q♥ -
   2♣3♦4♦6♥Q♥ - 2♥3♦6♥J♦Q♥ - 2♥3♦4♦J♦Q♥ - 2♥3♦4♦6♥Q♥ - 3♦4♦6♥J♦Q♥ -
   2♣2♥J♦Q♠K♥ - 2♣2♥6♥Q♠K♥ - 2♣2♥4♦Q♠K♥ - 2♣6♥J♦Q♠K♥ - 2♣4♦J♦Q♠K♥ -
   2♣4♦6♥Q♠K♥ - 2♥6♥J♦Q♠K♥ - 2♥4♦J♦Q♠K♥ - 2♥4♦6♥Q♠K♥ - 4♦6♥J♦Q♠K♥ -
   2♣2♥J♦K♥K♠ - 2♣2♥6♥K♥K♠ - 2♣2♥4♦K♥K♠ - 2♣6♥J♦K♥K♠ - 2♣4♦J♦K♥K♠ -
   2♣4♦6♥K♥K♠ - 2♥6♥J♦K♥K♠ - 2♥4♦J♦K♥K♠ - 2♥4♦6♥K♥K♠ - 4♦6♥J♦K♥K♠ -
   2♣2♥3♦J♦K♥ - 2♣2♥3♦6♥K♥ - 2♣2♥3♦4♦K♥ - 2♣3♦6♥J♦K♥ - 2♣3♦4♦J♦K♥ -
   2♣3♦4♦6♥K♥ - 2♥3♦6♥J♦K♥ - 2♥3♦4♦J♦K♥ - 2♥3♦4♦6♥K♥ - 3♦4♦6♥J♦K♥ -
   2♣2♥J♦Q♠K♠ - 2♣2♥6♥Q♠K♠ - 2♣2♥4♦Q♠K♠ - 2♣6♥J♦Q♠K♠ - 2♣4♦J♦Q♠K♠ -
   2♣4♦6♥Q♠K♠ - 2♥6♥J♦Q♠K♠ - 2♥4♦J♦Q♠K♠ - 2♥4♦6♥Q♠K♠ - 4♦6♥J♦Q♠K♠ -
   2♣2♥3♦J♦Q♠ - 2♣2♥3♦6♥Q♠ - 2♣2♥3♦4♦Q♠ - 2♣3♦6♥J♦Q♠ - 2♣3♦4♦J♦Q♠ -
   2♣3♦4♦6♥Q♠ - 2♥3♦6♥J♦Q♠ - 2♥3♦4♦J♦Q♠ - 2♥3♦4♦6♥Q♠ - 3♦4♦6♥J♦Q♠ -
   2♣2♥3♦J♦K♠ - 2♣2♥3♦6♥K♠ - 2♣2♥3♦4♦K♠ - 2♣3♦6♥J♦K♠ - 2♣3♦4♦J♦K♠ -
   2♣3♦4♦6♥K♠ - 2♥3♦6♥J♦K♠ - 2♥3♦4♦J♦K♠ - 2♥3♦4♦6♥K♠ - 3♦4♦6♥J♦K♠ -

Best Hand: 2♣2♥J♦K♥K♠ Rank: 3

Just wondering if there is a way to run the piece of code below more efficiently. I just started to get acquainted with parallel program and think this might be an answer? But I have no idea how to do it using imap or processes.


texts:
I'm a complete beginner at python and I know I'm probably approaching this the wrong way but I've tried making a quiz and can't work out how to make it more concise and work with longer lists of questions and answers without having to use lots of "if" statements. Here's the code:

import random

score = 0

questions = ["In which year did Diego Maradona score a goal with his hand?\n->",
             "In which sport can you win the Davis Cup?\n->",
             "How many minutes is a rugby match?\n->",
             "In which country were the first Olympic Games held?\n->",
             "In which country is the Interlagos F1 circuit?\n->"]
answers = ["1986","tennis","80","greece","brazil"]

print("---------------------------------")
print("You are running Ben's sports quiz")
print("---------------------------------\n")

question = random.sample(range(1,6),5)

for num in question:
    if num == 1:
        user_answer_1 = input(questions[0])
        if user_answer_1.lower() == answers[0]:
            print("Correct\n")
            score = score + 1
        else:
            print("Incorrect\n")
    if num == 2:
        user_answer_2 = input(questions[1])
        if user_answer_2.lower() == answers[1]:
            print("Correct\n")
            score = score + 1
        else:
            print("Incorrect\n")
    if num == 3:
        user_answer_3 = input(questions[2])
        if user_answer_3.lower() == answers[2]:
            print("Correct\n")
            score = score + 1
        else:
            print("Incorrect\n")
    if num == 4:
        user_answer_4 = input(questions[3])
        if user_answer_4.lower() == answers[3]:
            print("Correct\n")
            score = score + 1
        else:
            print("Incorrect\n")
    if num == 5:
        user_answer_5 = input(questions[4])
        if user_answer_5.lower() == answers[4]:
            print("Correct\n")
            score = score + 1
        else:
            print("Incorrect\n")

print("Your final score is",score,"out of 5\n")

input("Press ENTER to exit")

Any help would be greatly appreciated.


texts: Optimizing a Java solution to Project Euler Problem 23

texts:
I've tried to make something optimized for the Project Euler problem 23, named "Non-abundant sums".

I've fine-tuned my solution to the following:

I added divisors to the slots of each number to compute all the sums instead of checking if a number is abundant without using the modulo definition. This was my first big win.
I tried to minimize the number of loops, especially the outer loops (which I could reduce to 1).
Since the number of candidates is rather small (28123), I decided to work with arrays indexed by the candidates. This means that I compute the sum of divisors (div in the code) and I keep each encountered sum of abundants directly based on the index.
Since I have abundant numbers, it's easy to compute the sum of sum of (intended) abundant numbers, it's much less easy to compute non-abundant numbers, so I compute the absolute max value and subtract sum of abundant numbers from it.

This code is already running very fast (under 60 ms), but I'm wondering if its performance can still be drastically improved. More likely by using other lateral thinkings rather than small optimizations.

Now, here's my implementation of it.

public class Problem23 extends AbstractProblem {
  @Override public Object solve() {

    // Limit as defined by the problem.
    final int N = 28123;

    // [n] -> sum of the proper divisors of n
    int[] sumsOfDivisors = new int[N + 1];

    // A list of abundant numbers.
    int[] abundants = new int[N + 1];
    int abundantsSize = 0;

    // [n] -> is n sum of two abundants
    boolean[] sumsOfAbundants = new boolean[N + 1];

    // Total from which we're gonna subtract abundants to get the sum of non-abudant numbers.
    int totalSumOfAbundants = (N * (N + 1)) / 2;

    for (int i = 1; i <= N; i++) { // main loop

      // Build the sums of divisors by adding i to all of its multiples.
      // This avoids performing costly division/modulos.
      for (int j = i << 1; j < N; j += i) {
        sumsOfDivisors[j] += i;
      }

      // Since we're increasing i, sumsOfDivisors[i] won't change anymore and we check in the same big loop if it's an abundant number
      if (sumsOfDivisors[i] > i) { // i is abundant

        // Add i to the list of abundants.
        abundants[abundantsSize++] = i;

        // For each previously found abundant number.
        for (int j = 0, soa; j < abundantsSize && (soa = i + abundants[j]) <= N; j++) {

          // If their sum isn't already marked as a sum of abundants, mark it as such and subtract it from the total.
          if (!sumsOfAbundants[soa]) {
            sumsOfAbundants[soa] = true;
            totalSumOfAbundants -= soa;
          }
        }
      }
    }
    return totalSumOfAbundants;
  }
}


texts: Exercise for ordering pizzas with user input

texts:
I've only been learning Java for two weeks, and I had to complete this task as part of my course. My instructor could not give specific feedback as answer file is already provided, the code works but I am just wondering what some of you might think of my code if it can be refined. It's a basic pizza ordering program.
The requirements were:
able to specify pizzas one at a time using an loop.
loop can end or not based on input.
order viauser input using the Scanner class.
format currency with NumberFormat
Thank you for your time and wisdom.
import java.util.Scanner;
import java.text.NumberFormat;

public class PizzaOrder {

    public static void main(String[] args) {
        //defining and initialising variables.
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        Scanner keyboard = new Scanner(System.in);
        int pizzaquantity=0;
        int numberoftoppings = 0;
        double toppingtotalprice =0;
        char ordermore = 'n';
        double runningtotal = 0;
        final double stp = 1.0, ltp = 1.5, ftp = 2.0;
        final double s = 8.0, l = 11.0, f = 14.0;

        //using a do while loop, because condition to stop is at the end.
        do{

            System.out.println("Please place the order for your pizza.");
            System.out.println("Size (s = small, l = large, f = family):");
            char pizzasize = keyboard.next().charAt(0);
            //if else-else if nested inside loop
            //one iteration of the conditional statement for pizza size type.
            //number format is applied to every iteration of cost.
            if (pizzasize == 's')
            {
                System.out.println("Number of toppings?:");
                numberoftoppings = keyboard.nextInt();
                toppingtotalprice = (numberoftoppings * stp);
                System.out.println("Pizza Quantity:");
                pizzaquantity = keyboard.nextInt();
                runningtotal = (pizzaquantity * toppingtotalprice * s);
                System.out.println("Cost is: " + nf.format(runningtotal));

            }
            else if (pizzasize == 'l')
            {
                System.out.println("Number of toppings?:");
                numberoftoppings = keyboard.nextInt();
                toppingtotalprice = (numberoftoppings * ltp);
                System.out.println("Pizza Quantity:");
                pizzaquantity = keyboard.nextInt();
                runningtotal = (pizzaquantity * toppingtotalprice * l);
                System.out.println("Cost is:" + nf.format(runningtotal));

            }
            else if   (pizzasize == 'f')
            {
                System.out.println("Number of toppings?:");
                numberoftoppings = keyboard.nextInt();
                toppingtotalprice = (numberoftoppings * ftp);
                System.out.println("Pizza Quantity:");
                pizzaquantity = keyboard.nextInt();
                runningtotal = (pizzaquantity * toppingtotalprice * l);
                System.out.println("Cost is:" + nf.format(runningtotal));

            }
            else
            {
            }
                System.out.println("Order more? (y/n):");
                ordermore = keyboard.next().charAt(0);
        }
        while (ordermore != 'n');

        System.out.println("Total cost is: " + nf.format(runningtotal += runningtotal));
        System.out.println("Thank you for your order!");
    }

}


texts: Recursive LAMBDA() function to create a formula that adds internal separators to a string in Excel

texts:
I have created a named function with signature PadInternal(base, width, paddingStr) where:

base is a string you want to add padding to
width is the length of the individual chunks
paddingStr is the string to pad with

called from a cell like:

PadInternal("Hello", 1, " ") = "H e l l o"
PadInternal("World", 3, "**") = "Wor**ld"

And here's the function:

Tag
Description

Name
PadInternal

Scope
Workbook

Comment
base : a string you want to add padding to | width : the length of the individual chunks | paddingStr : the string to pad with

Refers To
=LAMBDA(base,width,paddingStr, IF(LEN(base)<=width, base, LET(LHS, LEFT(base, width), RHS, RIGHT(base, LEN(base) - width), LHS & paddingStr & PadInternal(RHS,width,paddingStr))))

=LAMBDA(
    base,
    width,
    paddingStr,
    IF(
        LEN(
            base
        ) <= width,
        base,
        LET(
            LHS,
            LEFT(
                base,
                width
            ),
            RHS,
            RIGHT(
                base,
                LEN(
                    base
                ) - width
            ),
            LHS & paddingStr &
            PadInternal(
                RHS,
                width,
                paddingStr
            )
        )
    )
)

Questions
As this is my first time using recursive Lambda functions in Excel, I'd like some feedback. In particular:

Is my algorithm efficient - I was thinking something with TEXTJOIN may be faster?
How could this be improved to take a dynamic array as "base"?
Can I have default values for the arguments?
What about meta data (formatting of the tooltip, scope etc), are there other ways to make my function more accessible?


texts: Parse JSON array into different Object using Reduce

texts:
I have an script that is receiving some JSON and then I am parsing it out using reduce.  I am sure there is a more elegant way to do it.

JSON

 var request = {
    "operation":"rate_request",
    // JSON removed to make more readable.
    "freight":
    {
        "items":
        // here is the array I am targeting
        [{
            "item":"7205",
            "qty":10,
            "units":10,
            "weight":"19.0000",
            "paint_eligible":false
        },
        {
            "item":"7677",
            "qty":10,
            "units":4,
            "weight":"5.0000",
            "paint_eligible":false
        }],
    // more JSON removed
}

Here is function to parse out and then loop through:

function parseItems(json){
    var resultsReduce = new Object()
    var itemKeys = ['item','qty', 'units','weight', 'paint_eligable']
    itemKeys.forEach(function(item){
        if (item){
            resultsReduce[item] = json.freight.items.reduce(function(array, object) {
                   return array.concat(object[item])
            }, [])
        }
    })
    var itemXML = ''

    for(var i = 0; i < resultsReduce.item.length; i++){
        var weight = Number(resultsReduce['weight'][i])
        var qty = Number(resultsReduce['qty'][i])
        var units = Number(resultsReduce['units'][i])
        itemXML += '<LineItem>'
                + '<PieceCount>' + units * qty + '</PieceCount>'
                + '<NetWeight UOM="Lb">' + weight * qty + '</NetWeight>'
                +'<GrossWeight UOM="Lb">' + weight * qty + '</GrossWeight>'
                + '<FreightClassification>' + '50' + '</FreightClassification>'
                +'</LineItem>'
    }
    return itemXML
}

The parseItems function turn the JSON into an object with arrays:

  {
 "item": [7205,7677],
 "qty": [10,10],
 "units": [10,4],
 "weight": ["19.0000","5.0000"],
 "paint_eligible": [false, false]
 }

Then the function loops through the object (manually by targeting the keys) and loops through the loop of the array. Like I mentioned, I am sure it can be more elegant. Any thoughts on how you would make it cleaner?


texts:
I'm new to template meta-programming and wrote some code to determine if a number is a perfect square.  For example, in my program, SQUARE<1>::value and SQUARE<4>::value evaluate to true while SQUARE<5>::value is false.  I'm open to any suggestions on how I could implement this better, cleaner, or make use of standard library functions.  Also, please point out any meta-programming conventions I may have overlooked.

template<bool condition, bool Then, bool Else>
struct IF {
   static const bool ret = Then;
};

template<bool Then, bool Else>
struct IF<false, Then, Else> {
   static const bool ret = Else;
};

template<size_t v1, size_t v2>
struct GREATER {
   static const bool ret = v1 > v2;
};

template<size_t n, size_t r>
struct IS_SQUARE {
   static const bool value = IF<n == r*r,
                true,
                IF<GREATER<n, r*r>::ret,
                   IS_SQUARE<n, r+1>::value,
                   false>::ret
                >::ret;
};

template<size_t n>
struct IS_SQUARE<n, n> {
   static const bool value = false;
};

template<size_t n>
struct SQUARE {
   static const bool value = IS_SQUARE<n, 1>::value;
};

template<>
struct SQUARE<1> {
   static const bool value = true;
};

// example usage
int main() {
   static_assert(SQUARE<1>::value, "must be square");
   static_assert(SQUARE<4>::value, "must be square");
   static_assert(SQUARE<5>::value, "must be square"); // compile error
}


texts:
I'm working on this exercise:

There is a classroom which has M rows of benches in it. Also, N students will arrive one-by-one and take a seat.

Every student has a preferred row number(rows are numbered 1 to M and all rows have a maximum capacity K. Now, the students come one by one starting from 1 to
N and follow these rules for seating arrangements:

Every student will sit in his/her preferred row(if the row is not full).
If the preferred row is fully occupied, the student will sit in the next vacant row. (Next row for N will be 1)
If all the seats are occupied, the student will not be able to sit anywhere.

Monk wants to know the total number of students who didn't get to sit in their preferred row. (This includes the students that did not get a seat at all)

Input

First line contains 3 integers
N, M and K.
N - Number of students and
M - Number of rows and
K - maximum capacity of a row.

Next line contains N space separated integers Ai.
Ai - preferred row of ith student.

Output

Output the total number of students who didn't get to sit in their preferred row.

Constraints:

1≤N,M≤10^5

1≤K≤500

1≤Ai≤M

code:

public static void main(String[] args) throws Exception {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int M = sc.nextInt();
    int K = sc.nextInt();
    int[] a = new int[N+1];
    //int[] rows = new int[N+1];
    TreeMap<Integer, Integer> tree = new TreeMap<Integer, Integer>();
    //put student preferences in a, ordered as they enter one by one
    for(int i=1;i<=N;i++){
        a[i] = sc.nextInt();
    }
    //put in the tree the available rows as key,value: key:row number, value: available capacity
    for(int i=1;i<=M;i++){
        tree.put(i, K);

    }
    //count of students that didn't get a seat
    int c=0;
    for (int i=1;i<=N;i++){
        //check if prefered row is availbe
        //available capacity
        //case1: preferred seat is available
        if(tree.get(a[i])>0){
            tree.put(a[i], tree.get(a[i])-1);
        }
        else{
            //case 2: preferred seat is full, check next vacant row.
            if(tree.higherKey(a[i])!=null && tree.get(tree.higherKey(a[i]))>0){
                int nextRow = tree.higherKey(a[i]);
                tree.put(nextRow, tree.get(nextRow)-1);
            }
            // if preferred row is M, then check row 1
            if(a[i]==M && tree.get(1)>0){
                tree.put(1, tree.get(1)-1);
            }
            //increment count of students who didn't get to sit in their preferred row
            //(included those who didn't get a seat at all)
            c++;
        }
    }

    System.out.println(c);

}

I took into account all cases that are stated in the exercise. I want to know if I have anticipated all cases or am I missing a possible corner case.


texts: LINQ to Entities query of tests for my classes, with many subqueries

texts:
This MVC4 controller method, which uses EF6, is taking a long time to run (over 2 seconds). I've added verbose comments for the purpose of this post only.

public async Task<ActionResult> Index()
{
  // Get a list of all the classes I teach.
  var myClasses = await CurrentUser.GetClassesAsync(db);

  // Get a list of all tests...
  var tests = await db.Tests
    // Which are either authored by me or involve one of my classes...
    .Where(o => o.AuthorId == CurrentUser.Id || (o.Author.SchoolId == CurrentUser.SchoolId && o.Classes.Any(c => myClasses.Contains(c.ClassName))))
    // And for each one I want...
    .Select(o => new TestOverviewItem
    {
      // The ID, title and test status
      Id = o.Id,
      Title = o.Title,
      Status = o.Status,
      // A list of which of my classes are registered for the test
      Classes = o.Classes.Where(c => myClasses.Contains(c.ClassName)).Select(c => c.ClassName).ToList(),
      // An indication of whether any results exist for students in my classes
      AnyUploads = o.Results.Any(r => r.User.Classes.Any(c => myClasses.Contains(c.ClassName))),
      // How many unmarked results there are for students in my classes
      RemainingToMark = o.Results.Count(r => r.MarkedBy == null && r.QuestionNumber > 0 && r.User.Classes.Any(c => myClasses.Contains(c.ClassName))),
      // An indication of whether I created the test
      IsOwner = o.AuthorId == CurrentUser.Id
    })
    .OrderByDescending(o => o.Id).ToListAsync();
  return View("Index", new OverviewModel(CurrentUser, tests, myClasses));
}

There are about 50 tests in total which match the criteria, and each one has ~4 Classes and ~2000 Results. I understand that all the subqueries must be slowing it down, but I'm not sure how to optimise.


texts: Two strings to one containing distinct letters

texts:
I've been doing lately CodeWars and here's my working code for this challenge.

The challenge :

  Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string, the longest possible, containing distinct letters, - each taken only once - coming from s1 or s2.

My code :

public static String longest(String s1, String s2) {
    StringBuilder sb = new StringBuilder();
    sb.append(s1).append(s2);

    String s = sb.toString();
    String result = "";

    for (int i = 0; i < s.length(); i++) {
        if (!result.contains(String.valueOf(s.charAt(i)))) {
            result += s.charAt(i);
        }
    }
    char[] ch = result.toCharArray();
    Arrays.sort(ch);

    return String.valueOf(ch);

}

Is there a way to skip all the transformations to arrays and then back to a String? I found it quite useful to use Arrays.sort because I didnt have to do another loop to sort chars in a String (dont think there is a StringBuilder method to sort chars as String is immutable, right?) Saw other solutions and many of them use streams but I havent learned about them yet so not trying to use them. Also I think there is no point in assigning String s becasue I can use sb.length() if a for loop and avoid another variable, right?


texts: Reproduce Hashing and pbkdf in newer versions? (python2)

texts:
I found this old code in one of the old files of mine which I have converted into Python3 but not very much satisfied and cannot reproduce the whole thing especially decoding it in check_password function.
#!/usr/bin/python2.7
# Imports
from hashlib import sha256
from hmac import HMAC
import random

# random bytes function convert random number into random 64-bit bytes
def random_bytes(num_bytes):
  return "".join(chr(random.randrange(256)) for i in xrange(num_bytes))

# password based key derivation function with number of iterations
def pbkdf_sha256(password, salt, iterations):
  result = password
  for i in xrange(iterations):
    result = HMAC(result, salt, sha256).digest()  # use HMAC to apply the salt
  return result

NUM_ITERATIONS = 5000

#hashing password and producing hashed password as well as salt
def hash_password(plain_password):
  salt = random_bytes(8)  # 64 bits

  hashed_password = pbkdf_sha256(plain_password, salt, NUM_ITERATIONS)

  # return the salt and hashed password, encoded in base64 and split with ","
  return salt.encode("base64").strip() + "," + hashed_password.encode("base64").strip()

# check hashed_password that returns true if properly decoded
def check_password(saved_password_entry, plain_password):
  salt, hashed_password = saved_password_entry.split(",")
  salt = salt.decode("base64")
  hashed_password = hashed_password.decode("base64")

  return hashed_password == pbkdf_sha256(plain_password, salt, NUM_ITERATIONS)

password_entry = hash_password("mysecret")
# will print, for example: 8Y1ZO8Y1pi4=,r7Acg5iRiZ/x4QwFLhPMjASESxesoIcdJRSDkqWYfaA=
print password_entry
print check_password(password_entry, "mysecret")  # returns True


texts: Many onClick handlers that all append different text to one textarea

texts:
The script basically just appends the words based on the user's click/s on the textarea. I just need some help improving my code further using the .on("click", function{}) and making it shorter.

$(document).ready(function() {

        $("#add_user").on("click",function() {
            $("#textareaFixed").append("Lorem");
        });

        $("#add_disallow").on("click",function() {
            $("#textareaFixed").append("Ipsum");
        });

        $("#add_wild").on("click",function() {
            $("#textareaFixed").append("Dolor");
        });

        $("#add_comment").on("click",function() {
            $("#textareaFixed").append("Hey");
        });

        $("#add_bb").on("click",function() {
            $("#textareaFixed").append("World");
        });

        $("#add_gdrive").on("click",function() {
            $("#textareaFixed").append("Its Time");
        });

        $("#add_gimage").on("click",function() {
            $("#textareaFixed").append("To Move");
        });

        $("#add_gnews").on("click",function() {
            $("#textareaFixed").append("Again");
        });

        $("#add_bash").on("click",function() {
            $("#textareaFixed").append("Thats it");
        });
    })


texts: Polyglot array_extend() function for Javascript and PHP

texts:
This is a polyglot function I've made out of fun.

The goal is to grab n arrays (or Javascript Objects) and 'extend' them in order to obtain a single array with all the values.

This function runs both in Javascript and PHP.

Please, try to ignore some kludges on my code.

Here is my 'art':

function array_extend() {

    //Detects if we are running in Javascript or PHP
    //In PHP, this will be false because PHP only parses
    //escape sequences in double-quoted strings (except the sequence \')
    $javascript = '\0' == "\0";

    //PHP arrays support 'key=>value' pairs, JS arrays don't.
    $result = $javascript ? new Object() : array();

    $arguments = $javascript? arguments : func_get_args();

    $get_keys = function($elem){
        if('\0' == "\0")//PHP complains if I use the var $javascript
        {
            $object = Object;
            return $object['keys']($elem); //PHP doesn't like the Object.keys syntax
        }
        else
        {
            return array_keys($elem);
        }
    };

    for($j = 0, $length_args = $javascript? $arguments['length']: count($arguments); $j < $length_args; $j++)
    {
        $keys = $get_keys( $arguments[$j] );

        for($i = 0, $length_keys = $javascript? $keys['length']: count($keys); $i < $length_keys; $i++)
        {
            $result[$keys[$i]] = $arguments[$j][$keys[$i]];
        }
    }

    return $result;
}

Example of usage:

array_extend([1,2,3,4,5],[9,8,7,6,5,4,3,2,1,0]);
//should return the last elements in the array:

array_extend({'a':1, 'b':2, 'c':3},{test:'nice'});
//Javascript: returns {'a':1, 'b':2, 'c':3, test:'nice'}

array_extend(array('a'=>1, 'b'=>2, 'c'=>3), array('test'=>'nice'));
//PHP: returns array('a'=>1, 'b'=>2, 'c'=>3, 'test'=>'nice')

What do you guys think?

What can I improve? Where should I have done something better?


texts: Average of positive and negative part of numpy matrix

texts:
I’ve got a matrix of data and I want to take the average of the positive and negative parts of the values.
Is there a more Pythonic way of doing it?

from numpy import *

…

exposures = matrix([0]*numPaths*numExposures)
exposures.shape = numPaths, numExposures

… # fill matrix

@vectorize
def plusv(x): return max(x,0)

@vectorize
def minv(x): return min(x,0)

ee  = transpose(exposures.mean(axis=0))
epe = transpose(plusv(exposures).mean(axis=0))
ene = transpose(minv(exposures).mean(axis=0))


texts: colorprint - An ANSI Escape sequence console writer mini-library

texts:
I wrote this a long time ago. I came back to it and decided to clean it up a little.

It uses the preprocessor and C99 anon structs to make a flexible python-like API for calling its functions.

colorprint.c

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

#include "colorprint.h"

static const char *numch = "0123456789";

static void
apply_effect(char *out, enum fx fx)
{/*{{{*/
    char buf[3] = { numch[fx - 1], ';' };

    strcat(out, buf);
}/*}}}*/

static void
apply_fg(char *out, enum color c)
{/*{{{*/
    char buf[4] = { '3', numch[c - 1], 'm' };

    strcat(out, buf);
}/*}}}*/

static void
apply_bg(char *out, enum color c)
{/*{{{*/
    char buf[4] = { '4', numch[c - 1], ';' };

    strcat(out, buf);
}/*}}}*/

static void
apply_fx(char *out, enum fx *fx)
{/*{{{*/
    for(int i = 0; fx[i]; i++)
        apply_effect(out, fx[i]);
}/*}}}*/

static void
apply_colors(char *out, struct cpoptions *cpo)
{/*{{{*/
    if(cpo->bg)
        apply_bg(out, cpo->bg);

    if(cpo->fg)
        apply_fg(out, cpo->fg);
}/*}}}*/

void
_cprint(struct cpoptions *cpo)
{/*{{{*/
    char options[30] = "";

    apply_fx(options, cpo->fx);
    apply_colors(options, cpo);

    if(!cpo->fg && !cpo->bg && !cpo->fx[0])
         fputs(cpo->string, stdout);
    else
        printf("\e[%s%s\e[0m", options, cpo->string);
}/*}}}*/

void
_cputs(struct cpoptions *cpo)
{/*{{{*/
    _cprint(cpo);
    putchar('\n');
}/*}}}*/

colorprint.h

#define func(name, type, ...) \
    name(&(type){.header = 0, __VA_ARGS__})

enum color {
    color_invalid,
    color_black,
    color_red,
    color_green,
    color_yellow,
    color_blue,
    color_purple,
    color_aqua,
    color_white
};

enum fx {
    fx_invalid,
    fx_plain,
    fx_bold,
    fx_dark,
    fx_italic,
    fx_underline,
    fx_light,
    fx_light2,
    fx_reverse,
    fx_blink,
    fx_strike
};

struct cpoptions {
    char header;
    char *string;
    enum fx fx[10];
    enum color fg;
    enum color bg;
};

void _cprint(struct cpoptions *cpo);
void _cputs(struct cpoptions *cpo);

#define cprint(...) func(_cprint, struct cpoptions, __VA_ARGS__)
#define cputs(...) func(_cputs, struct cpoptions, __VA_ARGS__)

/* Example:
 *      cprint("Hello World", .fg = color_green, .fx = {fx_bold, fx_italic, fx_strike});
 * Or:
 *      struct cpoptions cpo = {
 *          .string = "Hello World",
 *          .fg = color_green,
 *          .fx = {
 *              fx_bold,
 *              fx_italic,
 *              fx_strike
 *          }
 *      };
 *      _cprint(&cpo);
 */

Its usage ranges in complexity from

cputs("Hello World"); // prints "Hello World\n"

to

cputs( .string = "Hello World",
       .fg = color_green,
       .bg = color_red,
       .fx = {
           fx_bold,
           fx_strike,
           fx_italic
        }
); // prints "\e[1;9;3;41;32mHello World\e[0m\n", which appears as "Hello World" with a red background, green foreground, with bold+strikethrough+italic effects

In my opinion, this method of function calling is far more type-safe and versatile than the horrid va_args. It's also nice because it allows colorful output without the overhead of ncurses or termcap.


texts: Observer pattern using a set of observers and delegated properties

texts:
The idea is to implement the observer pattern, with a separate notification method for each observed property of the observed object. Let me start with a simplified use case:

class Point {
    val observers: ObserverSet<PointObserver>()
    val x by observers.observe(0f, PointObserver::xChanged)
    val y by observers.observe(0f, PointObserver::yChanged)
}

interface PointObserver {
    fun xChanged(old: Float, new: Float)
    fun yChanged(old: Float, new: Float)
}

class PointView(point: Point) {
    init {
        point.observers.add(object : PointObserver {
            override fun xChanged(old: Float, new: Float) { ... }
            override fun yChanged(old: Float, new: Float) { ... }
        })
    }
}

I'm new to Kotlin, so I'd like some feedback on the following implementation:

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * A set of observers for a particular object, to easily implement the Observer Pattern without needing inheritance.
 *
 * This can be made a public property of the object. Call [observe] to create delegated properties for each property
 * that observers need to be notified about.
 *
 * @param O The type of the observers, typically an interface.
 */
class ObserverSet<O> {

    private val observers = mutableSetOf<O>()
    private val properties = mutableListOf<ObservedProperty<*>>()

    /**
     * Sets whether an observer is present in the set. If the observer was actually added to the set, its notification
     * methods will be called with the current value of the property.
     *
     * @param observer The observer.
     * @param present If true, the observer will be added to the set if not already there. If false, the observer will
     *   be removed from the set if it's there.
     */
    fun toggle(observer: O, present: Boolean) {
        if (present) {
            val wasPresent = observer in observers
            observers.add(observer)
            if (!wasPresent) {
                init(observer)
            }
        } else {
            observers.remove(observer)
        }
    }

    /**
     * Creates a delegate property with a callback that notifies each observer.
     *
     * @param V The type of the property.
     * @param initialValue The initial value of the property.
     * @param onChanged Function on the [O] interface that will be called with the old and new value after the
     *   property has been changed.
     */
    fun <V> observe(initialValue: V, onChanged: O.(old: V, new: V) -> Unit): ReadWriteProperty<Any?, V> {
        val property = ObservedProperty(initialValue, onChanged)
        properties.add(property)
        return property
    }

    private fun init(observer: O) {
        properties.forEach { property ->
            property.initObserver(observer)
        }
    }

    private inner class ObservedProperty<V>(initialValue: V, private val onChanged: O.(old: V, new: V) -> Unit) :
            ReadWriteProperty<Any?, V> {

        private var value = initialValue

        override fun getValue(thisRef: Any?, property: KProperty<*>): V {
            return value
        }

        override fun setValue(thisRef: Any?, property: KProperty<*>, value: V) {
            val oldValue = this.value
            this.value = value
            observers.forEach { observer ->
                observer.onChanged(oldValue, value)
            }
        }

        fun initObserver(observer: O) {
            observer.onChanged(value, value)
        }
    }
}

(The toggle method is the only one I need right now; regular add and remove could of course be implemented as well.)

I'm mainly interested in efficiency considerations, ways to make this more general, and following Kotlin best practices.


texts:
(This is the Non-const version, I have to implement the const one too).
Could someone please review this implementation? This is made for std::vector
I'm unsure whether I respected all requirements for LegacyRandomAccessIterator; so if I'm missing something, please do let me know.
namespace random_access
{
    template<typename Type>
    class iterator
    {
    private:
        Type* m_iterator;

    public:
        using value_type = Type;
        using reference = value_type&;
        using pointer = value_type*;
        using iterator_category = std::random_access_iterator_tag;
        using difference_type = std::ptrdiff_t;
        //using iterator_concept = std::contiguous_iterator_tag;

        constexpr iterator(Type* iter = nullptr) : m_iterator{ iter } {}

        constexpr bool operator==(const iterator& other) const noexcept { return m_iterator == other.m_iterator; }
        constexpr bool operator!=(const iterator& other) const noexcept { return m_iterator != other.m_iterator; }
        constexpr reference operator*() const noexcept { return *m_iterator; }
        constexpr pointer operator->() const noexcept { return m_iterator; }
        constexpr iterator& operator++() noexcept { ++m_iterator; return *this; }
        constexpr iterator operator++(int) noexcept { iterator tmp(*this); ++(*this); return tmp; }
        constexpr iterator& operator--() noexcept { --m_iterator; return *this; }
        constexpr iterator operator--(int) noexcept { iterator tmp(*this); --(*this); return tmp; }
        constexpr iterator& operator+=(const difference_type other) noexcept { m_iterator += other; return *this; }
        constexpr iterator& operator-=(const difference_type other) noexcept { m_iterator -= other; return *this; }
        constexpr iterator operator+(const difference_type other) const noexcept { return iterator(m_iterator + other); }
        constexpr iterator operator-(const difference_type other) const noexcept { return iterator(m_iterator - other); }
        constexpr iterator operator+(const iterator& other) const noexcept { return iterator(*this + other.m_iterator); }
        constexpr difference_type operator-(const iterator& other) const noexcept { return std::distance(m_iterator, other.m_iterator); }
        constexpr reference operator[](std::size_t index) const { return m_iterator[index]; }
        constexpr bool operator<(const iterator& other) const noexcept { return m_iterator < other.m_iterator; }
        constexpr bool operator>(const iterator& other) const noexcept { return m_iterator > other.m_iterator; }
        constexpr bool operator<=(const iterator& other) const noexcept { return m_iterator <= other.m_iterator; }
        constexpr bool operator>=(const iterator& other) const noexcept { return m_iterator >= other.m_iterator; }
    };
}

Thanks !


texts:
I'm currently a beginner with clojure and I thought I'd try building a web crawler with core.async.

What I have works, but I am looking for feedback on the following points:

How can I avoid using massive buffers when I don't want to lose values?
Am I using go blocks efficiently? Are there places where a thread would be more appropriate?
How can I better determine when I can finish crawling? Currently I have a timeout of 3 seconds on taking from the urls-chan and if the timeout wins, I assume we're done. This doesn't seem very efficient.

Here is the main part of the code:

(def visited-urls (atom #{}))
(def site-map (atom {}))

;; I've given massive buffers my two channels here because I don't want to drop
;; values. I'm not quite sure why they need to be so big, but anything smaller gives me:
;; Exception in thread "async-dispatch-1626" java.lang.AssertionError:
;;   Assert failed: No more than 1024 pending puts are allowed on a single channel. Consider using a windowed buffer.
;;   (< (.size puts) impl/MAX-QUEUE-SIZE)
(def urls-chan (chan 102400))
(def log-chan (chan 102400))

(def exit-chan (chan 1))

(defn get-doc
  "Fetches a parsed html page from the given url and places onto a channel"
  [url]
  (go (let [{:keys [error body opts headers]} (<! (async-get url))
            content-type (:content-type headers)]
        (if (or error (not (.startsWith content-type "text/html")))
          (do (log "error fetching" url)
              false)
          (Jsoup/parse body (base-url (:url opts)))))))

;; Main event loop
(defn start-consumers
  "Spins up n go blocks to take a url from urls-chan, store its assets and then
  puts its links onto urls-chan, repeating until there are no more urls to take"
  [n domain]
  (dotimes [_ n]
    (go-loop [url (<! urls-chan)]
             (when-not (@visited-urls url)
               (log "crawling" url)
               (swap! visited-urls conj url)
               (when-let [doc (<! (get-doc url))]
                 (swap! site-map assoc url (get-assets doc))
                 (doseq [url (get-links doc domain)]
                   (go (>! urls-chan url)))))
             ;; Take the next url off the q, if 3 secs go by assume no more are coming
             (let [[value channel] (alts! [urls-chan (timeout 3000)])]
               (if (= channel urls-chan)
                 (recur value)
                 (>! exit-chan true))))))

(defn -main
  "Crawls [domain] for links to assets"
  [domain]
  (let [start-time (System/currentTimeMillis)]
    (start-logger)
    (log "Begining crawl of" domain)
    (start-consumers 40 domain)
    ;; Kick off with the first url
    (>!! urls-chan domain)
    (<!! exit-chan)
    (println (json/write-str @site-map))
    (<!! (log "Completed after" (seconds-since start-time) "seconds"))))


texts: Another Conway's Game of Life in Haskell

texts:
Curious what people think about this implementation of Conway's Game of Life in Haskell.

{-# LANGUAGE QuasiQuotes #-}

module Test.Conway (
  conwayCalculateAge,
  conwayStep,
  conwayMakeRandom,
  conwayMakeRandomIO,
  conwayMakeEmpty
  ) where

import           Data.Array.Repa
import           Data.Array.Repa.Stencil
import           Data.Array.Repa.Stencil.Dim2
import           Data.Functor.Identity
import           System.Random

conwayNeighborsStencil :: Stencil DIM2 Int
conwayNeighborsStencil =
  [stencil2| 1 1 1
             1 0 1
             1 1 1 |]

conwayStep :: Array U DIM2 Int -> Array U DIM2 Int
conwayStep r =
  runIdentity . computeP . szipWith rules r .            -- Apply rules
  mapStencil2 (BoundConst 0) conwayNeighborsStencil $ r -- Find # neigbors
  where
    rules 1 2 = 1 -- Alive and has two neighbours
    rules _ 3 = 1 -- Alive or dead and has three neighbours
    rules _ _ = 0 -- All others are dead

conwayMakeRandom :: RandomGen g => g -> DIM2 -> Array U DIM2 Int
conwayMakeRandom g sh =
  fromListUnboxed sh $ take (size sh) $ randomRs (0, 1) g

Naturally, conwayMakeRandom creates the initial grid and conwayStep advances the evolution a grid.


texts:
No one in my team knows how to write BDD tests, so I started writing some and it's quite working well. I think the time has come to improve the code quality.

This contains a lot of duplicated code and unused features:

<?php
require_once ('core/v3/engine.php');
require_once 'PHPUnit/Extensions/Story/TestCase.php';

class cHelperValidationSpec extends PHPUnit_Extensions_Story_TestCase {

    /**
     * Check all the output for the right cases
     * @scenario
     */
    public function specForJobId() {
        $this->given('For a mValue (mixedValue) and we want to validate if it is an integer')
            ->when('sJobId is a positive integer', 123)
            ->then('return of positive integer should be', 'TRUE')
            ->when('sJobId is a negative integer', -123)
            ->then('return of a negative integer should be', 'FALSE')
            ->when('sJobId is a float', 1.23)
            ->then('return of a float should be', 'FALSE')
            ->when('sJobId is a string containing only digits', '123')
            ->then('return of a string (containing only digits) should be', 'TRUE')
            ->when('sJobId is a string containing not only digits', '123abc-?')
            ->then('return of a string (containing not only digits) should be', 'TRUE');
    }

    public function runGiven(&$world, $action, $arguments) {
        switch($action) {
            case 'For a mValue (mixedValue) and we want to validate if it is an integer': {
                $world['helper'] = new cHelperValidation();
            }
            break;

            default: {
                return $this->notImplemented($action);
            }
        }
    }

    public function runWhen(&$world, $action, $arguments) {
        switch($action) {
            case 'sJobId is a positive integer': {}
            case 'sJobId is a negative integer': {}
            case 'sJobId is a float': {}
            case 'sJobId is a string containing only digits': {}
            case 'sJobId is a string containing not only digits': {}
            break;

            default: {
                return $this->notImplemented($action);
            }
        }
    }

    public function runThen(&$world, $action, $arguments) {
        switch($action) {
            case 'return of positive integer should be': {
                $this->assertEquals(TRUE, $world['helper']->isId(123));
            }
            case 'return of a negative integer should be': {
                $this->assertEquals(FALSE, $world['helper']->isId(-123));
            }
            case 'return of a float should be': {
                $this->assertEquals(FALSE, $world['helper']->isId(1.23));
            }
            case 'return of a string (containing only digits) should be': {
                $this->assertEquals(TRUE, $world['helper']->isId('123'));
            }
            case 'return of a string (containing not only digits) should be': {
                $this->assertEquals(FALSE, $world['helper']->isId('123abc-?'));
            }
            break;
            default: {
                return $this->notImplemented($action);
            }
        }
    }

}

The only reference I'm using for BDD is here, so there is much potential for improving this code.


texts: Assigning defaults for Smarty using object-oriented style

texts:
I have a custom class for Smarty that was partially borrowed. This is how the only example reflects the basic idea of using it across my current project:

class Template {

    function Template() {
        global $Smarty;
        if (!isset($Smarty)) {
            $Smarty = new Smarty;
        }
    }

    public static function display($filename) {
        global $Smarty;
        if (!isset($Smarty)) {
            Template::create();
        }
        $Smarty->display($filename);
    }

Then in the PHP, I use the following to display templates based on the above example:

Template::display('head.tpl');
Template::display('category.tpl');
Template::display('footer.tpl');

I made the following example of code (see below) work across universally, so I wouldn't repeat the above lines (see 3 previous lines) all the time in each PHP file.

I would just like to set, e.g.:

Template::defauls();

that would load:

Template::display('head.tpl');
Template::display('template_name_that_would_correspond_with_php_file_name.tpl');
Template::display('footer.tpl');

As you can see Template::display('category.tpl'); will always be changing based on the PHP file, which name is corresponded with the template name, meaning, if for example, PHP file is named stackoverflow.php then the template for it would be stackoverflow.tpl.

I've tried my solution that have worked fine but I don't like it the way it looks (the way it's structured).

What I did was:

Assigned in config a var and called it $current_page_name (that derives the current PHP page name, like this: basename($_SERVER['PHP_SELF'], ".php"); ), which returned, for e.g.: category.
In my PHP file I used Template::defaults($current_page_name);.
In my custom Smarty class I added the following:

public static function defaults($template) {
    global $Smarty;

    global $msg;
    global $note;
    global $attention;
    global $err;

    if (!isset($Smarty)) {
        Templates::create();
    }

    Templates::assign('msg', $msg);
    Templates::assign('note', $note);
    Templates::assign('attention', $attention);
    Templates::assign('err', $err);

    Templates::display('head.tpl');
    Templates::display($template . '.tpl');
    Templates::display('footer.tpl');
}

Is there a way to make it more concise and well structured?


texts: A function that reverses a string of characters

texts:
My problem is in writing a function reverse(s) that reverses the character string s, a line at a time. My code here works, I write the line and it reverses the line. Is it a good solution?

#include <stdio.h>
#include <stdlib.h>
#define MAX 1000

void  reverse(char cad[] ,char cadenita[],int i);

int main() {
    int a ,i ;
    char cad[MAX] = {0,0};
    char cadenita[MAX];
    i= 0;
      while ((a = getchar()) != EOF) {
          if (a != '\n') {
             cad[i] = a;
              ++i;
          }
          else  {
              cad[i] = '\0' ;
             reverse(cad , cadenita, i);
              printf("%s\n",cadenita);
              i = 0;
          }
   }
    return (EXIT_SUCCESS);
}

void  reverse(char s[] ,char svol[], int i) {
    int a =0 ;
    // i is the amount characters in s

    while ((svol[a] = s[i-1]) != '\0' ){
        ++a;
        --i;
    }

}

Also in this part of code while ((svol[a] = s[i-1]) != '\0' ){ .
If I change to  ((svol[a] = s[i-1]) != '\n' ) it still works and gives the same result, but why? I think there is an issue. Can you explain? Also, where does it break?


texts:
Problems:

Wanting to check all checkboxes when the checkbox w/id=checkall is checked.
Wanting to uncheck the "checkall" box when any other checkbox is unchecked.

Solution:

$(document).ready(function () {
$('#checkall').on('click', function () {
if ($(this).is(':checked')) {
    $('input[type="checkbox"]').each(function () {
        console.log(this);
        this.checked = true;
    });
} else {
    $('input[type="checkbox"]').each(function () {
        this.checked = false;
    });
}
// Uncheck "Checkall" if any other checkbox is unchecked
if ($('#checkall').is(':checked')) {
    $('input[type="checkbox"]:not("#checkall")').click(function () {
        console.log(this);
        $('#checkall').attr('checked', false);
    });
}
});
});

I'm new with jQuery and I'm not sure if what I've written is really and truly "production value" code, but it is operational. It's not a matter of life and death, it's really just a personal project I'm working on that will likely be used by myself and some friends only. I am in the game to learn, though, and if the code can be improved upon please point me in the right direction to read about it more in depth. I've only been able to find bits and pieces on this topic.


texts:
I'm very new to backbone.js and JavaScript.  I would like to hear some reasonable critiques / advice against my JavaScript code based on backbone.js framework with backbone-forms.

The aim of this simple app is to present a user with a simple registration form (twitter bootstrap modal dialog) and upon clicking on registration button post the model to a RESTful web service.

Model:

var MemberModel = Backbone.Model.extend({
    schema: {
        name: {
            type:  'Text',
            title: 'Full Name',
            validators: [
                'required'
            ],
            editorAttrs: {
                'placeholder': 'Type in your full name...',
                'class':'input-xlarge'
            }
        },
        email: {
            dataType: 'email',
            title: 'E-mail address',
            validators: [
                'required',
                'email'
            ],
            editorAttrs: {
                'placeholder': 'Type in your email address...',
                'class':'input-xlarge'
            }
        },
        country: {
            type: 'Select',
            options: [
                {
                    val: 0,
                    label: 'Choose a country...'
                },
                {
                    val: 1,
                    label: 'Country #1'
                },
                {
                    val: 2,
                    label: 'Country #2'
                },
                {
                    val: 3,
                    label: 'Country #3'
                }
            ],
            editorAttrs: {
                'data-placeholder': 'Choose a country',
                'class': 'input-xlarge'
            }
        }
    },
    urlRoot: '/api/members',
    validate: function(attrs) {
        var errors = {};
    if ( attrs.country == 0 ) {
        errors.country = 'Choose a country from list';
    }
        if ( !_.isEmpty(errors) ) return errors;
    }
});

Create an instance of the model:

var member = new MemberModel();

The View:

var MemberSignUpView = Backbone.View.extend({
    name: "MemberSignUpView",
    model: MemberModel,
    el: $('#frontend'),
        initialize:
            function()
            {
                if ( ! ich['signup'] ) {
                    ich.addTemplate('signup', 'ajax:/media/js/tpl/frontend/' + this.name + '.html?' + (Math.random() * 1000000).toString());
                }
            },
        events:
            {
                "click #wndSignupClose": "onCloseClick",
                "click #wndSignupSubmit": "onSubmitClick"
            },
        onSubmitClick:
            function()
            {
                var errors = frmSignUp.commit();
                if ( _.isEmpty(errors) ) {
                    member.save();
                }
            },
        onCloseClick:
            function()
            {
                this.el.modal('hide');
                this.el.remove();
                this.undelegateEvents();
            },
        render:
            function()
            {
                this.el = ich.signup();
                if ( typeof window.frmSignUp == "undefined" ) {
                    window.frmSignUp = new Backbone.Form({
                        model: member
                    }).render();
                }
                $(this.el).find('.modal-body').append(window.frmSignUp.el);
                $(this.el).modal({
                backdrop: 'static',
                keyboard: false
            });
            return this;
        }
});

Create modal window uppon clicking on a button:

$(function() {
        $('#btnSignup').bind('click', function(){
            var wndSignUp;
            if ( typeof wndSignUp == "undefined" ) {
                wndSignUp = new MemberSignUpView().render().el;
            }
            $('#frontend').append(wndSignUp);
    wndSignUp.modal('show');
    });
});


texts: Enumerate k-combinations in Clojure (P26 from 99 problems)

texts:
I've been playing with Clojure for the last few evenings, going through the well known 99 problems (I'm using a set adapted for Scala).

  Problem 26

  Given a set S and a no. of items K, returns all possible
  combinations of K items that can be taken from set S.

Here's my solution:

(defn combinations [k s]
  (cond
    (> k (count s)) nil        ;not enough items in sequence to form a valid combination
    (= k (count s)) [s]        ;only one combination available: all items
    (= 1 k) (map vector s)     ;every item (on its own) is a valid combination
    :else (reduce concat (map-indexed
            (fn [i x] (map #(cons x %) (combinations (dec k) (drop (inc i) s))))
            s))))

(combinations 3 ['a 'b 'c 'd 'f])

My basic solution is to take each item from the given sequence (map-indexed) and recurse to generate combinations of size K - 1 from the remaining sequence. The termination conditions are described above.

I'm still a complete Clojure newbie and would welcome comments on structure, efficiency, readability, resemblance to idiomatic Clojure, etc. Feel free to be brutal, but please remember I've been doing Clojure for only a few hours :)

I'm less interested in alternative mathematical methods for generating k-combinations, more interested in feedback on whether this is passable Clojure.