Python subclass method decoration Is this code Pythonic?

def emit_decorator(method, signal_name):
    def decorated(self, *args, **kwargs):
        retval = method(self, *args, **kwargs)
        getattr(self, signal_name).emit()
        return retval
    return decorated

class Model(base.Transformer, Node):
    """
    Transformer subclass that implements the Model of the Model-View-Controller
    paradigm.
    """
    def __init__(self, *args, **kwargs):
        super(Model, self).__init__(*args, **kwargs)

    modelChanged = pyqtSignal()

    def create_view(self, parent=None):
        return View(self, parent)

for x in ('importance_changed',
          'evidence_changed',
          ):
    setattr(Model, x,
            emit_decorator(getattr(Model, x), 'modelChanged'))

Final decorator code:

from functools import update_wrapper

def method_emit_decorator(signal_name):
    def method_decorator(method):
        def decorated(self, *args, **kwargs):
            retval = method(self, *args, **kwargs)
            getattr(self, signal_name).emit()
            return retval
        return update_wrapper(decorated, method)
    return method_decorator

def class_emit_decorator(signal_name_to_method_names_dict):
    def class_decorator(cls):
        retval = cls
        for signal_name, method_names in (
            signal_name_to_method_names_dict.items()):
            for method_name in method_names:
                method = method_emit_decorator(signal_name)(
                    getattr(cls, method_name))
                setattr(retval, method_name, method)
        return retval
    return class_decorator

Modifying the class after defining it smells. That is, its not necessarily a bad idea but one should explore options before resorting to it.

When "decorating" a function you should use the functools.wraps decorator. It will make the decorated function look more like the original.

The code you are replacing looks like:

def importance_changed(self):
    return_value = super(Model, self).importance_changed()
    self.modelChanged.emit()
    return return_value

Your code is harder to read and longer then just writing those two functions. Its not really worth implementing what you've done just for two functions. However, if you have a lot of functions then the situation changes.

Your emit_decorator function isn't a decorator. Dectorators have to take exactly one argument, (the function they are wrapping) to be used with the @syntax.


JSON-ification and processing of data with Python My script looks like this:

with open('toy.json', 'rb') as inpt:

    lines = [json.loads(line) for line in inpt]

    for line in lines:
        records = [item['hash'] for item in lines]
    for item in records:
        print item

What it does is read in data where each line is valid JSON, but the file as a whole is not valid JSON. The reason for that is because it's an aggregated dump from a web service.

The data looks, more or less, like this:

{"record":"value0","block":"0x79"}
{"record":"value1","block":"0x80"}

The code works, it allows me to interact with the data as JSON, but it's so slow that it's essentially useless. Is there a good way to speed up this process?

It's slow because of this line:

for line in lines:
    records = [item['hash'] for item in lines]

Notice that records will be overwritten for each line.
And in fact it's overwritten with the exact same value for each line.
In fact you could replace this loop with just this line:

records = [item['hash'] for item in lines]

That should already solve the problem with the slowness.
But I would go one step further and get records in one step,
by getting hash directly during the first pass over the input lines:

with open('toy.json', 'rb') as input:
    records = [json.loads(line)['hash'] for line in input]

    for item in records:
        print item


Queue Implemented as Single Linked List Note: I do know that Python libraries provide a Linked list and Stack. This implementation has been done to practice Python and some of the data structures and algorithms.

I have implemented Queue as a Single linked list. Feel free to make suggestions. Note: The code works.

Targeted Big O:

Search: O(n), EnQueue and DeQueue: O(1)

Methods:

en_queue(value): insert values
de_queue(): remove values
is_empty(): check to see if Queue is empty
peek_front(): look at what head points to without removing
peek_back(): look at what tail points to without removing
search(value): check to see if a value is in the Queue
length(): return size

Classes:

class Node:
    def __init__(self, value):
        self.data = value
        self.front = None

class Queue:
    def __init__(self):
        self.head = None
        self.tail = None
        self.count = 0

    def en_queue(self, value):
        new_node = Node(value)

        if self.tail is not None:
            # make the front attribute of old node point to new node
            self.tail.front = new_node

        else:
            # if first ever node in Queue both front and tail will point to it
            self.head = new_node

        self.tail = new_node
        self.count += 1

    def de_queue(self):
        if not self.is_empty():
            # point head to next node
            self.head = self.head.front
            print("sucess")
            self.count -= 1
        else:
            print("Empty QUEUE")

    def __iter__(self):
        node = self.head
        while node:
            yield node
            node = node.front

    def is_empty(self):
        if self.head is None and self.tail is None:
            return True
        else:
            return False

    def peek_front(self):
        return self.head.data

    def peek_back(self):
        return self.tail.data

    def queue_search(self, value):
        # start from the head
        p = self.head
        while p is not None:
            # make p reference to next node
            if p.front is not None:
                if p.data == value:
                    print("Found value")
                    return p.data
                p = p.front
            else:
                print("fail")
                return 0

    def length(self):
        return self.count

Test:

from stack_Queue import Queue

def main():

    print("-------Test Queue---------")
    print("-------Test En Queue------")
    my_queue = Queue()
    test_list = [1, 2, 3, 4, -2000000, 'a', 500000, 50]

    for i in test_list:
        my_queue.en_queue(i)
    print("-------En Queue Done-------")
    for i in my_queue:
        print(i.data)
    print("------Queue Print Done-----")
    print("------Queue Print Done-----")
    print(my_queue.peek_back())
    print(my_queue.peek_front())
    print("----------De Queue---------")
    my_queue.de_queue()
    print("--------De Queue Done------")
    for i in my_queue:
        print(i.data)
    print("-----Queue Print Done------")
    print("-----Test search-------")
    x = my_queue.queue_search('a')
    print(x)
    print("-------Full De Queue-------")
    while my_queue.length() != 0:
        my_queue.de_queue()
    print("--------De Queue Done------")
    for i in my_queue:
        print(i.data)
    print("-----Queue Print Done------")

if __name__ == "__main__":
    main()

Result:

-------Test Queue---------
-------Test En Queue------
-------En Queue Done-------
1
2
3
4
-2000000
a
500000
50
------Queue Print Done-----
------Queue Print Done-----
50
1
----------De Queue---------
sucess
--------De Queue Done------
2
3
4
-2000000
a
500000
50
-----Queue Print Done------
-----Test search-------
Found value
a
-------Full De Queue-------
sucess
sucess
sucess
sucess
sucess
sucess
sucess
--------De Queue Done------
-----Queue Print Done------

Process finished with exit code 0

In addition to the points I had mentioned in my previous answer to your Stack implementation.

Your Queue is not introspectable right now as it lacks __repr__ method. Due to this you won't be able to view its items easily. Hence you could add __repr__ to both Node and Queue class(same applicable to your Stack class in other question).

class Node:
    def __init__(self, value):
        self.data = value
        self.front = None

    def __repr__(self):
        return repr(self.data)

class EmptyQueueException(Exception):
    pass

class Queue:
    def __init__(self):
        self.head = None
        self.tail = None
        self.count = 0

    def en_queue(self, value):
        new_node = Node(value)

        if self.tail is not None:
            # make the front attribute of old node point to new node
            self.tail.front = new_node
        else:
            # if first ever node in Queue both front and tail will point to it
            self.head = new_node

        self.tail = new_node
        self.count += 1

    def de_queue(self):
        if self:
            # point head to next node
            self.head = self.head.front
            self.count -= 1
        else:
            raise EmptyQueueException()

    def peek_front(self):
        if self:
            return self.head.data
        raise EmptyQueueException()

    def peek_back(self):
        if self:
            return self.tail.data
        raise EmptyQueueException()

    def __iter__(self):
        node = self.head
        while node is not None:
            yield node
            node = node.front

    def __bool__(self):
        return not (self.head is None and self.tail is None)

    def __contains__(self, value):
        return value in (node.data for node in self)

    def __len__(self):
        return self.count

    def __repr__(self):
        return 'Queue<{nodes}>'.format(nodes=', '.join(repr(node) for node in self))

Demo:

>>> my_queue
Queue<1, 2, 3, 4, -2000000, 'a', 500000, 50>
>>> my_queue.de_queue()  # Probably want to return the value as well?
>>> my_queue
Queue<2, 3, 4, -2000000, 'a', 500000, 50>
>>> my_queue.peek_back()
50
>>> 'a' in my_queue
True
>>> 'spam' in my_queue
False
>>> bool(my_queue)
True
>>> len(my_queue)
7
>>> len(Queue())
0
>>> bool(Queue())
False
>>> Queue().peek_back()
---------------------------------------------------------------------------
EmptyQueueException                       Traceback (most recent call last)
...


Divide and conquer approach in search for max element Continuing the Algorithm in a Nutshell series, here is the code:

trait MaxElem<T> {
    fn max_elem<'a>(&'a self) -> &'a T;
}

impl<T> MaxElem<T> for Vec<T> where T: PartialOrd {
    fn max_elem<'a>(&'a self) -> &'a T {
        max_elem_helper(self, 0, self.len())
    }
}

fn max_elem_helper<'a, T>(vec: &'a Vec<T>, left: usize, right: usize) -> &'a T
    where T: PartialOrd
{
    if right - left == 1 {
        return &vec[left];
    }
    let mid = (left + right) / 2;
    let max1 = max_elem_helper(vec, left, mid);
    let max2 = max_elem_helper(vec, mid, right);
    if max1 > max2 {
        max1
    } else {
        max2
    }
}

#[cfg(test)]
mod test {
    use max_elem::MaxElem;
    #[test]
    fn test_max_elem() {
        let vec = vec![11, 2, 9, 1, 3, 88];
        let m = *vec.max_elem();
        assert_eq!(m, 88);
    }
}

It's a simple algorithm that divide a vector into two parts and recursively search for the maximum.

All suggestions are welcome.

First of all I'm not sure why you use a divide and conquer approach here, given that just walking over the entire list once and getting the maximum element is both shorter and more efficient.

Secondly I would use the more general &[T] instead of &Vec<T>.

Your implementation will recurse forever and crash with a stack overflow when the input is empty.

Because you demand PartialOrd rather than Ord, the result you get from max_elem will depend on the order of the list. For instance, a list with floating point numbers may get inconsistent results when NaN is present: if the list ends with NaN then than will be the maximum element. If it begins with NaN but also contains other numbers, then a different number will be the maximum element. It is even possible for NaN to hide the maximum number, and make the method return a number that is not the largest. A demonstration:

fn show(v: Vec<f64>) {
    println!("Max element of {:?} is {}", v, v.max_elem());
}
show(vec![1.0, std::f64::NAN]); // the max is NaN
show(vec![std::f64::NAN, 1.0]); // the max is 1
show(vec![10000.0, std::f64::NAN, 1.0, 1.0]); // the max is 1

Basically you should just use .iter().max() when you want the maximum element of some iterable structure, which avoids all of these problems.


Storing values in an N x N grid I am trying to write a program to store/display a grid of size N x N with cells containing either a 1 or a 0 in preparation for further computation:

module Board where

import Data.List as List

data CellState = One | Zero deriving (Eq, Ord)

data Cell = Cell {cellPos :: (Int, Int), cellState :: CellState} deriving (Eq, Ord)

type Board = [Cell]

instance Show CellState where
  show One = "1"
  show Zero = "0"

instance Show Cell where
  show (Cell c x) = show (c,x)

genPositions :: Int -> [(Int, Int)]
genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

genCellState :: Int -> CellState
genCellState 0 = Zero
genCellState 1 = One

newBoard :: Int -> [Int] -> Board
newBoard i [x] = [Cell (round $ sqrt(fromIntegral i), round $ sqrt(fromIntegral i)) (genCellState x)]
  where positions = genPositions $ round $ sqrt(fromIntegral i)
newBoard i (x : xs) = [Cell (positions!!(i - 1 - length xs)) (genCellState x)] ++ newBoard i xs
  where positions = genPositions $ round $ sqrt(fromIntegral i)

What improvements can I make to this, both in terms of good practises and performance? I don't like Board being a list of Cells. I posted this on Stack Overflow by accident (have since deleted it) and someone recommended changing type Board = [Cell] to newtype Board = Board { getBoard :: Array (Int,Int) CellState } but I'm not too familiar with arrays in Haskell so not sure how this would work exactly. From what I have read they apply a function to the elements in the range [Int..Int] and return a list of tuples with the input and output.

By defining r = round . sqrt . fromIntegral, newBoard fits on the screen. positions doesn't appear to be used in newboard's first case.

Half the code disappears if we interpret Cell as ((Int, Int), Int).

newBoard's first case can be pushed one recursion call deeper, mapping [] to [] instead of [x] to the current right hand side.

[_] ++ _ should be simplified as _ : _.

positions is only used once, therefore I inline it.

type Cell = ((Int, Int), Int) -- (position, state)

genPositions :: Int -> [(Int, Int)]
genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

r = round . sqrt . fromIntegral

newBoard :: Int -> [Int] -> [Cell]
newBoard i [] = []
newBoard i (x : xs) = (genPositions (r i)!!(i - 1 - length xs), x) : newBoard i xs

Successive elements of the list returned by genPositions and xs are zipped together; zip captures this pattern. i is now not needed in its non-rooted form and I recommend changing the interface to take N as an argument instead. Non-square arguments can currently crash !! anyway. genPositions is only used once, therefore I inline it.

type Cell = ((Int, Int), Int) -- (position, state)

newBoard :: Int -> [Int] -> [Cell]
newBoard n = zip $ liftA2 (,) [0..n-1] [0..n-1]

For type Board = Array (Int, Int) Int, Data.Array allows newBoard n = listArray ((0,0),(n-1,n-1)).


Exercise to fetch data from JSON files using ES6 promises I did an exercise (self-imposed) promise fetching some data from placeholder JSON files on https://jsonplaceholder.typicode.com/. The exercise in my opinion is finished, but I can't shake the feeling that the code is as dirty as code can be. Please check it out and point me into the right direction and tell me what I did wrong.

The exercise can be found here: http://codepen.io/kresimircoko/pen/vggPmJ

'use strict';
const root = 'https://jsonplaceholder.typicode.com/';
const postList = document.querySelector('#post-list');
console.clear();

const commentsPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'comments');
    xhr.send();
});

const usersPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'users');
    xhr.send();
});

const postsPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'posts');
    xhr.send();
});

// Posts
postsPromise
    .then(data => {
        const posts = JSON.parse(data); // Contains our posts

        usersPromise
            .then(data => {
                const users = JSON.parse(data); // Contains our users
                commentsPromise
                    .then(data => {
                        const comments = JSON.parse(data);
                        displayPosts(posts, users, comments);
                    });
            });
    }).catch(error => { console.log(error); });

// Users

function displayPosts(posts ,users, comments) {
    let output = '';
    posts.map(post => {
        output += `

 ${displayUserName(users, post)}

 ${post.title}

 ${post.body}

 ${displayCommentAmount(comments, post)} comments

        `;
    });
    postList.innerHTML = output;
}

function displayUserName(users, post) {
    return users.map(user => {
        if (user.id === post.userId) {
            return user.name;
        }
    }).join('');
};

function displayCommentAmount(comments, post) {
     const commentArray = comments.filter(comment => {
        return comment.postId === post.id;
    });
    return commentArray.length;
}

There are lots of things you can do:

Use a parameterized function to create the XHR promises, since your three functions are identical other than what they're requesting
Use Promise.all, since none of the requests relies on information from previous requests and they can run in parallel
Move the JSON parsing into the functions retrieving the data, rather than making the consumer of them do it

And a bugfix, I think: The response text is this.responseText, not this.response, in the XHR load callback.

That would let us replace all of this:

const commentsPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'comments');
    xhr.send();
});

const usersPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'users');
    xhr.send();
});

const postsPromise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(this.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', root + 'posts');
    xhr.send();
});

// Posts
postsPromise
    .then(data => {
        const posts = JSON.parse(data); // Contains our posts

        usersPromise
            .then(data => {
                const users = JSON.parse(data); // Contains our users
                commentsPromise
                    .then(data => {
                        const comments = JSON.parse(data);
                        displayPosts(posts, users, comments);
                    });
            });
    }).catch(error => { console.log(error); });

with this:

const requestJSON = objType => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = function() {
            try {
                resolve(JSON.parse(this.responseText));
            }
            catch (e) {
                reject(e);
            }
        };
        xhr.onerror = reject;
        xhr.open('GET', root + objType);
        xhr.send();
    });
};

Promise.all([requestJSON('posts'), requestJSON('users'), requestJSON('comments')])
    .then(results => {
        displayPosts(...results);
    })
    .catch(error => {
        console.log(error);
    });

So shorter, simpler, and more centralized for debugging, not repeating yourself, etc.

If you want the requests done in series instead of in parallel even though they don't have to be, just change the Promise.all part to:

requestJSON('posts')
    .then(posts => requestJSON('users')
        .then(users => requestJSON('comments')
            .then(comments => {
                displayPosts(posts, users, comments);
            })
        )
    )
    .catch(error => {
        console.log(error);
    });

(I tried to keep that in line with your line break/indentation style...)

Final result (with parallel requests):

'use strict';
const root = 'https://jsonplaceholder.typicode.com/';
const postList = document.querySelector('#post-list');
console.clear();

const requestJSON = objType => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = function() {
            try {
                resolve(JSON.parse(this.responseText));
            }
            catch (e) {
                reject(e);
            }
        };
        xhr.onerror = reject;
        xhr.open('GET', root + objType);
        xhr.send();
    });
};

Promise.all([requestJSON('posts'), requestJSON('users'), requestJSON('comments')])
    .then(results => {
        displayPosts(...results);
    })
    .catch(error => {
        console.log(error);
    });

// No changes from here on out...

function displayPosts(posts ,users, comments) {
    let output = '';
    posts.map(post => {
        output += `

 ${displayUserName(users, post)}

 ${post.title}

 ${post.body}

 ${displayCommentAmount(comments, post)} comments

        `;
    });
    postList.innerHTML = output;
}

function displayUserName(users, post) {
    return users.map(user => {
        if (user.id === post.userId) {
            return user.name;
        }
    }).join('');
};

function displayCommentAmount(comments, post) {
     const commentArray = comments.filter(comment => {
        return comment.postId === post.id;
    });
    return commentArray.length;
}


Simple sum calculator I'm looking to optimize a simple sum calculator used in Project Euler+. The premise is simple: Find the sum of all the numbers divisible by 3 or 5 under X.

At first I did it like so:

def main(testCases):
    final_answer = []
    for x in range(testCases):
        answer = 0
        test = long(input())
        for num in range(test):
            if (num % 5 == 0 or num % 3 == 0):
                print(num)
                answer += num
        final_answer.append(str(answer))
    print('\n'.join(final_answer))
main(input())

Which worked alright. Then I realized it couldn't handle anything like 10,000,000,000 at all, which was bad, so I tried:

def main(testCases):
    for x in range(testCases):
        answer = 0
        num = input()

        Temp = (num - 1) // 3
        answer += (Temp * (3 + Temp * 3)) // 2
        Temp = (num - 1) // 5
        answer += (Temp * (5 + Temp * 5)) // 2
        Temp = (num - 1) // 15
        answer -= (Temp * (15 + Temp * 15)) // 2
        print answer
main(input())

Which was way faster / capable of giant numbers. However, it seems really ugly and unoptimized, but maybe it's in my head. Can anyone help me optimize my answer?

Sample

Input:

2
10
100

Output:

23
2318

One way would be to find the sum of all numbers divisible by three, five and fifteen. To do this define another function that calculates the sum of first n number using the formula  \$\sum\limits_{k=1}^n k = \frac{n(n+1)}{2}\$. Now to find the sum of all number divisible by three all we need to do is pass the quotient of num // 3 to sum_of_n_numbers and multiple its result by 3, same thing of five and fifteen as well.

In the end we simply subtract the sum of all fifteen from sum of five and three because we counted those twice.

def sum_of_n_numbers(n):
    return (n*(n+1))/2.0

def ashwch(test_cases):
    for _ in xrange(test_cases):
        num = int(raw_input()) - 1
        sum_of_threes = 3 *  sum_of_n_numbers(num//3)
        sum_of_fives = 5 *  sum_of_n_numbers(num//5)
        sum_of_fifteenes = 15 *  sum_of_n_numbers(num//15)
        print sum_of_three + sum_of_fives - sum_of_fifteenes

Few other points:

Don't use variable names that start with capital letter for normal variables, such variable names are recommended for class names.
In case number of test-cases are huge you will end up creating a huge list in memory because range() returns a list in Python 2. This applies to your first code as well where you've used range() for the number itself, so your computer will crash with inputs like 10,000,000,000. So, better use xrange() in Python 2.
I have used the // operator instead of / because it will round down the number in both Python 2 and 3.
As this is from a programming challenge you may not need to worry about malicious inputs, but try not to use input() in Python 2 as it evals anything that user enters. So an input like __import__('os').system('ls -l') can be deadly if you replace ls -l with something else. So, use raw_input with int().

>>> input()
__import__('os').system('ls -l')
total 586952
-rw-rw-r-- 1 ashwini ashwini   3468213 Jan 27 02:54 1.txt
-rw-rw-r-- 1 ashwini ashwini   3467213 Jan 27 03:10 4.txt


CSV Splitter in Bash I am splitting a csv file where the first 3 columns will be common for all the output files.

input file:

h1 h2 h3 o1 o2 ....
a  b  c  d  e  ....
a1 b1 c1 d1 e1 ....

output files:

o1.csv:

h1 h2 h3 o1
a  b  c  d
a1 b1 c1 d1

o2.csv:

h1 h2 h3 o2
a  b  c  e
a1 b1 c1 e1

So if there are n columns in the input file , the code creates n-3 output files.
However my code is inefficient and is quite slow. It takes 20 seconds for 50000 rows.

old_IFS=$IFS
START_TIME=`date`
DELIMITER=,

# reading and writing headers
headers_line=$(head -n 1 "$csv_file")
IFS=$DELIMITER read -r -a headers <<< $headers_line
common_headers=${headers[0]}$DELIMITER${headers[1]}$DELIMITER${headers[2]}

for header in "${headers[@]:3}"
do
   # writing headers to every file
   echo $common_headers$DELIMITER$header > "$header$START_TIME".csv
done

# reading csv file line by line
i=1
while IFS=$DELIMITER read -r -a row_data
do
    test $i -eq 1 && ((i++)) && continue      # ignoring headers

    j=0

    common_data=${row_data[0]}$DELIMITER${row_data[1]}$DELIMITER${row_data[2]}
    for val in "${row_data[@]:3}"
    do
        #  appending row to every new csv file
        echo $common_data$DELIMITER$val >> "${headers[(($j+3))]}$START_TIME".csv
        ((j++))
    done

done < $csv_file
IFS=${old_IFS}

Any suggestions are appreciated.

Bash is not efficient for processing large files line by line. For small data it's fine, but when a script starts to feel heavy, it's good to look for other alternatives. Also note that the line by line processing and breaking into columns is not easy to get right, I bet you spent quite some time on this. You wrote it well, but the result is not particularly easy to read, and I'm afraid this is as good as it gets with Bash.

So what's the alternative? Try with cut in a loop. Yes that will imply reading the file n-3 times, but I bet it will be faster than the pure Bash solution. And it will be nicely readable too, which is an extremely important benefit.

A few notes about technique:

Use $(...) instead of `...`
You took care to save IFS and then restore at the end, but it was unnecessary: when you do var=... somecmd, the value of var is only set in the environment of somecmd, it is unchanged for the current script. That being said, what you did is safe, so it's fine.
The incrementing i variable in the loop is a bit misleading, because i is a common name in counting loops, and at first I thought the count itself has some purpose. But it doesn't, this variable is used only to distinguish the first line from the others. I would write differently, to make the intention perfectly obvious.


Linked list using dynamic memory I created a simple linked list to test what I've learned so far and if I manage everything correctly. If you see syntax errors is't because of copy-paste. I just want to know if i'm making everything in the right way without
having leak and memory problems.

Node class

#include "Node.h"

//Constructor.
Node::Node(int v)
:next(nullptr), value(v)
{
}

//Deconstrucor (not in use).
Node::~Node()
{
}

//Set next.
void Node::set_next(Node *new_node)
{
    this -> next = new_node;
}

//Set previous.
void Node::set_prev(Node *new_node)
{
    this -> prev = new_node;
}

//Set value.
void Node::set_value(int v)
{
    this -> value = v;
}

//Get next.
Node *Node::get_next()
{
    return this -> next;
}

//Get previous.
Node *Node::get_prev()
{
   return this -> prev;
}

//Get value
int Node::get_value()
{
    return this -> value;
}

LinkedList class

#include "LinkedList.h"
#include "Node.h"
#include <new>
#include <iostream>

//Constructor.
LinkedList::LinkedList()
:head(nullptr), tail(nullptr), moving_ptr(nullptr)
{
}

//Deconstrucor (not in use).
LinkedList::~LinkedList()
{
}

//Append a new item on the list.
void LinkedList::append(int v)
{

    //Allocate a new node.
    Node *new_node = new (std::nothrow)Node(v);

    //If memory is full, exit the program.
    if (new_node == nullptr){
        std::cout << "Memory is full, program will exit." << std::endl;
        exit(0);
    }

    //If this is the first node.
    if (head == nullptr || tail == nullptr)
        {
            head       = new_node;
            tail       = new_node;
            moving_ptr = new_node;
        }

    //Append other node.
    else
        {
            tail -> set_next(new_node); //Link it after the tail of the list.
            new_node -> set_prev(tail); //Set the previous node.
            tail = new_node;            //Update the tail pointer.
        }
}

//Remove a node from the list.
bool LinkedList::remove_item(int v)
{

    //Starting node.
    Node *curr = head;

    //----Find the node that contains v----//
    while (curr != nullptr)
    {

        //Found.
        if (curr -> get_value() == v)
            break;

        //Keep going.
        else
            curr = curr -> get_next();
    }
    //----Find the node that contains v----//

//The item was not found into the list.
if (curr == nullptr)
    return false;

//Make necessary links!!!
curr -> get_prev() -> set_next( curr -> get_next() );

//Delete current node.
delete curr;

return true;
}

//Get the next item.
int LinkedList::nextItem()
{

    //Temp that hold current value.
    int temp = moving_ptr -> get_value();

    //Move to the next node.
    moving_ptr = moving_ptr -> get_next();

    //Return the value.
    return temp;
}

//Return true if moving_ptr is not null.
bool LinkedList::hasNext()
{
    return moving_ptr != nullptr;
}

//Reset moving_ptr.
void LinkedList::reset()
{
    moving_ptr = head;
}

Am I handling everything correctly? I also tried to fill all my memory with an infinite loop to see what happens and everything run's smoothly. The program terminates when memory is full.

Memory Leaks

You aren't cleaning up after your LinkedList.  When the class is destroyed you want to make sure that all of the memory it has allocated is cleaned up.  At a minimum, you're going to want to:

LinkedList::~LinkedList()
{
    delete head;
}

However you also need to consider each node in the list.  You can either have ~Node delete it's next, or you can put a loop in to delete all the items in the list from the tail backwards.  Usually you would also implement this in a public function like clear or flush so that the whole list can be easily emptied.  For example, something like this would clear up the list:

void clearList() {
    Node *tmp = head;
    while(tmp) {
        head = tmp->get_next();
        delete tmp;
        tmp = head;
    }
}

Exit

You exit if there is insufficient memory to allocate a node.  The exitcode 0 is usually reserved for a successful program exit.  You should be passing a different value to exit (usually a negative number) to indicate failure.

Heads or Tails

In your remove_item method, you're not updating your tail pointer, what is going to happen if the tail happens to be pointing at the node that contains the value you remove?  Similarly, what happens if moving_ptr is pointing at the node that's removed?

reset

I'd honestly expect this to clear/flush/empty the list, not just reset the pointer that's used for iterating over items in the list.  This is likely to be confusing.

templates

Depending on what it is you're practising for, a good next step would be to adapt your Node so that it can support a templated value type.  You could then extend the list to store and retrieve values of any type.


Remove duplicates in list of lists where an item in each list is ignored when determining duplicity I have lines_list_copy of the form:

[['a1', 'b1', 'c1', 'd1', 'e1'], ['a2', 'b2', 'c2', 'd2', 'e2'], ... ]

I needed to remove all duplicate entries where a,b,c,d are identical. So note that I don't care about what value e has. So for example, If lines_list_copy = [['a1', 'b1', 'c1', 'd1', 'e1'], ['a2', 'b2', 'c2', 'd2', 'e2'], ['a1', 'b1', 'c1', 'd1', 'e1'], ['a1', 'b1', 'c1', 'd1', 'e2']] we have three values that are the same, namely lines_list_copy[0], lines_list_copy[2] and lines_list_copy[3] and any 2 of them need to be deleted which will give us the value of lines_list. At the end deleting any two results in a valid outputs for lines_list

lines_list_copy has lengths typically exceeding 200000 and realistically will eventually exceed 500000 with the amount of data we are collecting. Thus I needed a way to remove duplicates fast. I found a way to efficiently remove all duplicates, but the method would take e into account and thus wouldn't give me what I need. Therefore, I delete all the e values in each list first like so:

for x in lines_list_copy:
  del x[cfg.TEXT_LOC_COL]
lines_list_copy = [list(x) for x in set(tuple(x) for x in lines_list_copy)]

After which I have lines_list_copy as I need it. All I need to do is re-add any one of the e values for each list. My double for loop is admittedly naive and more so that I didn't think it would bring my program to a crawl.

    for line_copy_ind in range(len(lines_list_copy)):
        for line_ind in range(len(lines_list)):
            if lines_list_copy[line_copy_ind][cfg.TIME_COL] == lines_list[line_ind][cfg.TIME_COL] and \
                    len(lines_list_copy[line_copy_ind]) == 4:
                lines_list_copy[line_copy_ind].append(lines_list[line_ind][cfg.TEXT_LOC_COL])
    lines_list = lines_list_copy

I looked into vectorizing and using filter but just cant seem to reverse engineer solutions to other problems and make them work for my problem of adding e back on the end of each list in lines_list_copy. Maybe there's an elegant way for me to instead not delete the e column and still remove duplicates efficiently without considering the e values?

Maybe there's an elegant way for me to instead not delete the e column and still remove duplicates efficiently without considering the e values?

Your set-based approach almost works, and should be more efficient than the nested loops. Try storing only the first 4 items in the set, as opposed to the entire row:

def unique_by_first_n(n, coll):
    seen = set()
    for item in coll:
        compare = tuple(item[:n])    # Keep only the first `n` elements in the set
        if compare not in seen:
            seen.add(compare)
            yield item

filtered_list = list(unique_by_first_n(4, lines_list_copy))

Here I've adapted your set approach to consider only the first n items when comparing rows, but then to yield the entire row if it hasn't been seen yet. yield could also be replaced by first defining an empty output list and appending to it, like in your second solution.

We get around the del e problem by not deleting anything, just returning all of the rows where the first n columns have not been seen yet.


Using Dictionary of int and list of tuple in C# I have implemented mathematical functions using a C# library. I basically need to output data by the RiskMatrixByFunds in the following format.

Key will contain Id and value will contain collection of string, double, double

For example:

Id 1

value

{'ArithmeticMean', 12.34, 3.44},
{'AverageGain', 12.35, 3.45},
{'AverageLoss', 12.36, 3.46},

I have used a Dictionary structure that will contain the int and list of tuple collection.

Let me know if it can be enhanced, any ideas on magic strings used, a better way to implement it.

public class RiskMatrix : IRiskMatrix
{

    public (double Monthly, double Annual) ArithmeticMean(IEnumerable<double> ReturnsList)
    {
        double returnList = ReturnsList.Mean();
        return (Monthly: returnList, Annual: returnList * Math.Pow(12, 0.5));
    }

    public (double Monthly, double Annual) AverageGain(IEnumerable<double> ReturnsList)
    {

        double returnList = ReturnsList.GainMean();
        return (Monthly: returnList, Annual: returnList * Math.Pow(12, 0.5));
    }

    public (double Monthly, double Annual) AverageLoss(IEnumerable<double> ReturnsList)
    {
        double returnList = ReturnsList.LossMean();
        return (Monthly: returnList, Annual: returnList * Math.Pow(12, 0.5));
    }

    public Dictionary<int, List<Tuple<string,double, double>>> RiskMatrixByFunds(Dictionary<int, IEnumerable<double>> ReturnsList)
    {
        Dictionary<int, List<Tuple<string ,double, double>>> returnsList = new Dictionary<int, List<Tuple<string,double, double>>>();
        List <Tuple<string, double, double>> list = null;

        foreach (KeyValuePair<int, IEnumerable<double>> entry in ReturnsList)
        {
            list = new List<Tuple<string, double, double>>();
            (double Monthly, double Annual) arithmeticMeanResult = ArithmeticMean(entry.Value);
            list.Add(new Tuple<string, double, double>("ArithmeticMean", arithmeticMeanResult.Monthly, arithmeticMeanResult.Annual));
            (double Monthly, double Annual) averageGainResult = AverageGain(entry.Value);
            list.Add(new Tuple<string, double, double>("AverageGain", averageGainResult.Monthly, averageGainResult.Annual));
            (double Monthly, double Annual) averageLossResult = AverageLoss(entry.Value);
            list.Add(new Tuple<string, double, double>("AverageLoss", averageLossResult.Monthly, averageLossResult.Annual));
            (double Monthly, double Annual) betaCorrelationresult = BetaCorrelation(entry.Value);

           returnsList.Add(entry.Key, list);
        }
        return returnsList;
    }
}

There might be a reason why you used a List<Tuple<string ,double, double>>. E.g. if you need to pass the data to an existing library or your UI needs to bind to a list. Otherwise I would recommend to create a dedicated class

public class RiskStatistics
{
    public double ArithmeticMeanMonthly { get; set; }
    public double ArithmeticMeanAnnual { get; set; }

    public double AverageGainMonthly { get; set; }
    public double AverageGainAnnual { get; set; }

    public double AverageLossMonthly { get; set; }
    public double AverageLossAnnual { get; set; }
}

Since the properties are named, there's no need for magic strings. This makes the creation and usage of the risk matrix less convoluted:

public Dictionary<int, RiskStatistics> RiskMatrixByFunds(
    Dictionary<int, IEnumerable<double>> returnsLists)
{
    var riskMatrixDict = new Dictionary<int, RiskStatistics>();

    foreach (KeyValuePair<int, IEnumerable<double>> entry in returnsLists) {
        var risk = new RiskStatistics();
        (risk.ArithmeticMeanMonthly, risk.ArithmeticMeanAnnual) = ArithmeticMean(entry.Value);
        (risk.AverageGainMonthly, risk.AverageGainAnnual) = AverageGain(entry.Value);
        (risk.AverageLossMonthly, risk.AverageLossAnnual) = AverageLoss(entry.Value);
        riskMatrixDict.Add(entry.Key, risk);
    }
    return riskMatrixDict;
}

You could also calculate the annual values on the fly. This would make the creation even easier. Here the adapted average gain properties as an example:

private static readonly double Sqrt12 = Math.Pow(12, 0.5);

public double ArithmeticMeanMonthly { get; set; }
public double ArithmeticMeanAnnual => ArithmeticMeanMonthly * Sqrt12;

With this adapted RiskStatistics class, you could directly assign from the extension methods and skip the methods returning tuples.

var risk = new RiskStatistics {
    ArithmeticMeanMonthly = entry.Value.Mean(),
    AverageGainMonthly = entry.Value.GainMean(),
    AverageLossMonthly = entry.Value.LossMean()
};
riskMatrixDict.Add(entry.Key, risk);

The annual values are read-only and need not to be assigned.


Setting a variable during an if loop I've seen the pattern:

<?php
  if ($node = node_load(30) && $node->type == 'bogus') {
    print $node->title . 'is bogus';
  }

But when I tried to use it I got a warning: variable not defined... Has this pattern of declaring variables while you loop in an if been deprecated?

I have created the following function and class to test your code with:-

function node_load($load)
{
    return new node();
}

class node
{
    public $type = 'bogus';
    public $title = 'Node title ';
}

Let's take a look at your code step by step, so we can work out what is wrong with it.

First let's see what happens if we var_dump the output of node_load():-

$node = node_load(1);
var_dump($node);

Output:-

object(node)[35]
  public 'type' => string 'bogus' (length=5)
  public 'title' => string 'Node title ' (length=11)

That looks about right, so let's see what happens if we put it in an if statement.

if($node = node_load(1)){
        var_dump($node);
    }

Output:-

object(node)[36]
  public 'type' => string 'bogus' (length=5)
  public 'title' => string 'Node title ' (length=11)

There doesn't seem to be any problem there either. So, lets try the compound if statement you have:-

if($node = node_load(1) && $node->type = 'bogus' ){
    var_dump($node);
}

Output:-

boolean true

Hmm, what's happened here? Well if you take a look at how logical operators work, you'll see that the result of a logical statement like node_load(1) && $node->type = 'bogus' is a boolean true or false, which you've just assigned to the variable $node. You've lost the object that was previously referenced by that variable. Hence when you try to do:-

print $node->title . 'is bogus';

you will get a "Warning: Attempt to assign property of non-object " as $node is now a boolean and not the object you were expecting.

That seems to me to be a pretty good reason for not assigning variable in an if statement as you are doing. Assign before the if statement and then test:-

$node = node_load(30);
if ('bogus' === $node->type) {
    print $node->title . 'is bogus';
}

Output:-

  Node title is bogus

Which is what is wanted. I'm sure you'll agree the re-factored code is much easier to read and as an added bonus, it works!

You may notice that I have reversed the normal order of the comparison, using 'bogus' === $node->type rather than $node->type === 'bogus'. This will raise an exception if you type '=' instead of '==' or '===' by mistake and make debugging much easier. It is a good habit to get into, as is using strict type comparisons with '===' rather than loose comparisons with '=='.

I might add that doing little step by step tests like this is a good way of working out what code actually does and reinforces the concepts of programming in your mind. I always do it when I come across functions/concepts that are new to me.


Count the number of combinations with gap-restriction for every pair of values A lottery draw consists of choosing 6 different values from 1 to 50.

I want to calculate the number of combinations with gaps of at least 3 between every pair of values.

I have used the following Python 2.7 script:

def func(array,length,min,max,gap):
    if len(array) == length:
        # print array
        return 1
    count = 0
    for n in range(min,max+1):
        count += func(array+[n],length,n+gap,max,gap)
    return count;

print func([],6,1,50,3)

Questions:

Are there any coding improvements that I can apply?
Is there a different method with which we can do it more efficiently?
Although more suitable for math.stackexchange.com, is there a straightforward formula?

There's no docstring. How do I use this function? What arguments do I pass? What does it return?
It would be very easy to make this code portable to Python 3: just put parentheses around the argument to print.
There's no need to terminate a statement with a semicolon in Python.
The name func does not give any hint as to what the function might do. A name like combinations_with_gap would be clearer.
When you have code that accumulates a sum like this:

count = 0
for n in A:
    count += B

you can use the built-in sum:

count = sum(B for n in A)

If you're just counting combinations (rather than generating the combinations themselves), then you don't need the array variable, just its length.
Presumably the caller is supposed to always pass the empty list [] for array and 1 for min. In that case, why make them do it? It would be easier for the caller if the function just took the arguments you need, and used a local function to do the work, like this:

def combinations_with_gap(k, max, gap):
    """Return the number of ways of choosing k of the numbers from 1 to
    max such that no two numbers are closer than gap.

    """
    def c(length, min):
        if length == k:
            return 1
        return sum(c(length + 1, n + gap) for n in range(min, max + 1))
    return c(0, 1)

This runs in just over 4 seconds on my computer:

>>> from timeit import timeit
>>> timeit(lambda:combinations_with_gap(6, 50, 3), number=1)
4.182408502034377

Where is it spending its time? If you trace the calls to the inner function c, you'll see that the same values for length and min occur many times. This is a waste of effort: having computed c(5, 44), say, it would be a good idea to remember the result and reuse it instead of computing it again.

One way to do this is to memoize the function, for example using the @functools.lru_cache decorator:

from functools import lru_cache

def combinations_with_gap(k, max, gap):
    """Return the number of ways of choosing k of the numbers from 1 to
    max such that no two numbers are closer than gap.

    """
    @lru_cache(maxsize=None)
    def c(length, min):
        if length == k:
            return 1
        return sum(c(length + 1, n + gap) for n in range(min, max + 1))
    return c(0, 1)

This version takes just a couple of milliseconds:

>>> timeit(lambda:combinations_with_gap(6, 50, 3), number=1)
0.0017554410151205957


Get resulting rectangle from two overlapping rectangles I have a function that creates a rectangle from two rectangles that overlap, I was wondering if there is a smarter way to do it purely mathematically rather than lots of if statements to check min and max the way I currently have setup.

This is my function

    public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)
    {
        result = new Bounds();
        //they don't overlap
        if (!a.Intersects(bounds)) return false;

        float minX;
        float maxX;
        float minZ;
        float maxZ;

        if (a.min.x > bounds.min.x)
            minX = a.min.x;
        else
            minX = bounds.min.x;

        if (a.max.x < bounds.max.x)
            maxX = a.max.x;
        else
            maxX = bounds.max.x;

        if (a.min.z > bounds.min.z)
            minZ = a.min.z;
        else
            minZ = bounds.min.z;

        if (a.max.z < bounds.max.z)
            maxZ = a.max.z;
        else
            maxZ = bounds.max.z;

        // using XZ plane for debug
        Vector3 min = new Vector3(minX,0,minZ);
        Vector3 max = new Vector3(maxX,0,maxZ);
        result.SetMinMax(min,max);
        return true;
    }

Here it is in action

float minX;
float maxX;
float minZ;
float maxZ;

The declarations can be inlined so that it is clearer when they are being set. However, in geometry and other applications it may be preferable to declare them like this.

if (a.max.x < bounds.max.x)
            maxX = a.max.x;
        else
            maxX = bounds.max.x;

These conditions can be replaced with calls to Math.max and Math.min.

The variable names such as minX and maxX seem to be reversed; minX seems to be referring to maxX and vice-versa. I am not very familiar with geometry so I don't know if my suggestion is correct to swap the names.

After applying these suggestions, the method becomes the following:

  public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)
    {
        result = new Bounds();
        //they don't overlap
        if (!a.Intersects(bounds)) return false;

        float minX = Math.Max(a.min.x, bounds.min.x);
        float maxX = Math.Min(a.max.x, bounds.max.x);

        float minZ = Math.Max(a.min.z, bounds.min.z);
        float maxZ = Math.Min(a.max.z, bounds.max.z);

        // using XZ plane for debug
        Vector3 min = new Vector3(minX, 0, minZ);
        Vector3 max = new Vector3(maxX, 0, maxZ);
        result.SetMinMax(min, max);
        return true;
    }

Edit: to respond to the comment (minimizing if statements), it could be expressed as:

  public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)
    {
        result = new Bounds();

        float minX = Math.Max(a.min.x, bounds.min.x);
        float maxX = Math.Min(a.max.x, bounds.max.x);

        float minZ = Math.Max(a.min.z, bounds.min.z);
        float maxZ = Math.Min(a.max.z, bounds.max.z);

        // using XZ plane for debug
        Vector3 min = new Vector3(minX, 0, minZ);
        Vector3 max = new Vector3(maxX, 0, maxZ);
        result.SetMinMax(min, max);
        return !a.Intersects(bounds);
    }

This would be slightly less efficient; I don't know if this is valid as if the Vector3 class will accept input which did not pass .Intersects.


Determining if a possible new entry already exists in a dataset For example, if I have the following data table layout:

dt.Columns.Add("ticketid", typeof(Int32));
dt.Columns.Add("createtime", typeof(DateTime));
dt.Columns.Add("creator", typeof(string));
dt.Columns.Add("ticketText", typeof(string));

If I want to add a new entry I need to make sure that there exists none already that has the same primary key (ticketid, createtime, creator).

The check is as follows:

if (
    dt.Rows.Count <= 0 ||
    (
        dt.Rows.Count > 0 &&
                    null == dt.AsEnumerable().Where
                        (
                            r => r.Field<int>("ticketid") == newEntry.TicketId
                                && DateTime.Equals(r.Field<DateTime>("createtime"), newEntry.CreateTime)
                                && r.creator == newEntry.Creator
                         )
                         .FirstOrDefault()
   ))

The code does what it is meant for, BUT my problem is that it is SLOW. In my case I need to read 2 million entries from the file and put them into the database as fast as possible at which this code fails (as soon as I use the code the runtime goes from just 1 minute to over 30 minutes). Is there any faster way to do this?

Site-note: the datatable is read from a file and the above is a check to make sure the data is ok before it is bulk inserted into the db.

Example with happenings:

if (
    dt.Rows.Count <= 0 ||
    (
        dt.Rows.Count > 0 &&
                    null == dt.AsEnumerable().Where
                        (
                            r => r.Field<int>("ticketid") == newEntry.TicketId
                                && DateTime.Equals(r.Field<DateTime>("createtime"), newEntry.CreateTime)
                                && r.creator == newEntry.Creator
                         )
                         .FirstOrDefault()
   ))
{
    // No duplicate found so insert the data into the data table
   dt.Rows.Add(new object[] {newEntry.TicketId, newEntry.CreateTime, newEntry.Creator});
}

Introduce a new object:

public class PrimaryKey
{
    public int TicketId { get; set; }
    public DateTime CreateTime { get; set; }
    public string Creator { get; set; }

    public PrimaryKey(int ticketId, DateTime createTime, string creator)
    {
        TicketId = ticketId;
        CreateTime = createTime;
        Creator = creator;
    }

    public override int GetHashCode()
    {
        int hash = 13;
        hash = (hash * 7) + TicketId.GetHashCode();
        hash = (hash * 7) + CreateTime.GetHashCode();
        hash = (hash * 7) + Creator.GetHashCode();
        return hash;
    }
    public override bool Equals(object value)
    {
        var other = value as PrimaryKey;
        return other != null
             && other.TicketId == TicketId
             // ... etc.
    }
}

Use this in a hashset:

// right at the beginning...
var dedupeList = new Hashset<PrimaryKey>();
// Populate hashset from data table

if (dedupeList.Add(new PrimaryKey(newEntry.TicketId, newEntry.CreateTime, newEntry.Creator))
{
    // New
}
else
{
    // Already added.
}

You wont have to search through the whole data table each time which should save a lot of time when the data table is large. However, you will use more memory.


explode textarea and commas Am attempting to recreate a common feature, where a user can type several items in to a textarea, separated by commas and newlines and then submit them, i.e. for multiple record entry.

The data does not come from a CSV file and is manually entered.

// data looks like this in the textarea:

Widget 1, 4, 10
Widget 2, 1.3, 10
Widget 3, 5.5, 15

Then submit the form:

$products = explode("\r\n", $_POST['productsTextarea']); // sanitize

$y = 0;
$productArray = array();

// explode and trim each product, assign values to an array
foreach($products as $product) :
    $product = array_map('trim', explode(',', $product));
    $productArray[$y]['name'] = $product [0];
    $productArray[$y]['cost'] = $product [1];
    $productArray[$y]['quantity'] = $product [2];
    $y++;
endforeach;

-

// desired output of $productArray
array(
    (int) 0 => array(
        'name' => 'Widget 1',
        'cost' => '4',
        'quantity' => '10',
    ),
    (int) 1 => array(
        'name' => 'Widget 2',
        'cost' => '1.3',
        'quantity' => '10',
    ),
    (int) 2 => array(
        'name' => 'Widget 3',
        'cost' => '5.5',
        'quantity' => '15',
    ),
)

I feel this isn't particularly extensible (i.e. the array keys are hard coded) and wonder how it would cope with a lot of items.

Name, Cost, Quantity, Colour, Location, Postcode // header row?
Widget 1, 4, 10, blue, Foo, Bar
Widget 2, 4, 10, red, Foo, Bar

Abstract class is ideal for this:

abstract class ProductsTextareaBase {

  protected abstract function getColumns();

  public function parse($productsTextarea) {
    $products = explode("\r\n", $productsTextarea); // sanitize

    $y = 0;
    $productArray = array();

    // explode and trim each product, assign values to an array
    foreach($products as $product) {
        $product = array_map('trim', explode(',', $product));
        $i = 0;
        $columns = $this->getColumns();
        foreach($product as $col) {
          $productArray[$y][$columns[$i]] = $col;
          $i++;
        }
        $y++;
    }
    return $productArray;
  }
}

class WidgetProductsTextarea extends ProductsTextareaBase {
  protected function getColumns() {
    return array('name', 'cost', 'quantity');
  }
}


Simple shared pointer I wrote a simple shared pointer, which I think works pretty well. I would like to see your review of it.

This is the header file:

#pragma once

#include <algorithm>

template <class T>
class SharedPointer
{
private:
    T* ptr;
    int* counter;

    void swapp(SharedPointer& first, SharedPointer& second);

public:
    SharedPointer(void);
    SharedPointer(T* val);
    SharedPointer(const SharedPointer& sp);

    T& operator*();
    T* operator->();
    SharedPointer& operator=(const SharedPointer& sp);
    ~SharedPointer(void);
};

template <class T>
void SharedPointer<T>::swapp(SharedPointer& first, SharedPointer& second)
{
    using std::swap;

    swap(first.ptr, second.ptr);
    swap(first.counter, second.counter);
}

template <class T>
SharedPointer<T>::SharedPointer(void)
{
    ptr = new T;
    counter = new int;
    *counter = 1;
}

template <class T>
SharedPointer<T>::SharedPointer(T* val) : ptr(val)
{
    counter = new int;
    *counter = 1;
}

template <class T>
SharedPointer<T>::SharedPointer(const SharedPointer& sp)
{
    ptr = sp.ptr;
    counter = sp.counter;
    ++(*counter);
}

template <typename T>
T& SharedPointer<T>::operator*()
{
    return *ptr;
}

template <typename T>
T* SharedPointer<T>::operator->()
{
    return ptr;
}

template <class T>
SharedPointer<T>& SharedPointer<T>::operator=(const SharedPointer& sp)
{
    SharedPointer temp(sp);
    swapp(*this,temp);

    return *this;
}

template <class T>
SharedPointer<T>::~SharedPointer(void)
{
    if(--(*counter) == 0)
    {
        delete ptr;
        delete counter;
    }
}

Foreword

When developing your own version of some standard library or tool, I suggest you to specify how close to the standard version is along with the purpose behind it.
So, for istance:

Is it standard compliant?
Does it address anything missing?

Interface

What I find missing:

How can I reset the pointer?
How can I know how many "visitors" there are(that is, how do I get counter)? Note: It could be useful, but don't go too far and break the encapsulation!
An efficient way to visit the object, that is an alternative to std::weak_ptr:
How do I allocate/deallocate particular objects?

Implementation

#pragma once is not standard. Although almost all compilers implement it and seems like to be faster than header guards, I recommend these last ones at least until it gets standardized.
Why counter is allocated dynamically?
I understand you may not name swapp swap; however, there are better names, such as:

m_swap
internal_swap

C++, unlike C, makes no difference between function() and function(void).
Yes, they're both correct; but the first one is much more common.
new can throw std::bad_alloc. Especially in the second constructor, if new threw when allocating/constructing counter, ptr would be leaked.


Find items that appear the same number of times in two collections Here is a Java collection puzzle I found online. I was wondering if anyone can provide me with suggestions on how Appearance and tests can be improved. Suggestions of any kind and scope are very welcomed. it would be even better if reasons can be provided along with the suggestions.

Problem:

Appearance class:

package assign1;

import java.util.*;

public class Appearances {

    public static <T> int sameCount(Collection<T> a, Collection<T> b) {

        Map<T, Integer> map1 = countItemsInCollection(a);
        Map<T, Integer> map2 = countItemsInCollection(b);

        return compareMapForMatchingKeyAndValue(map1, map2);
    }

    private static <T> Map<T, Integer> countItemsInCollection(Collection<T> collection) {

        Map<T, Integer> mapItemToNumberOfOccurance = new HashMap<>();

        for (T item : collection) {
            if (!mapItemToNumberOfOccurance.containsKey(item)) {
                mapItemToNumberOfOccurance.put(item, 1);
            } else {
                mapItemToNumberOfOccurance.put(item, mapItemToNumberOfOccurance.get(item) + 1);
            }
        }

        return mapItemToNumberOfOccurance;
    }

    private static <T> int compareMapForMatchingKeyAndValue(Map<T, Integer> map1, Map<T, Integer> map2) {
        Set<Map.Entry<T, Integer>> set1 = map1.entrySet();
        Set<Map.Entry<T, Integer>> set2 = map2.entrySet();

        Set<Map.Entry<T, Integer>> matchingSet = new HashSet<>(set1);

        matchingSet.retainAll(set2);

        return matchingSet.size();

    }

}

Test class:

package assign1;

import assign1.Appearances;
import static org.junit.Assert.*;
import org.junit.Test;

import java.util.*;

public class AppearancesTest {
    // utility -- converts a string to a list with one
    // elem for each char.

    private List<String> stringToList(String s) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < s.length(); i++) {
            list.add(String.valueOf(s.charAt(i)));
            // note: String.valueOf() converts lots of things to string form
        }
        return list;
    }

    @Test
    public void testSameCount1() {
        List<String> a = stringToList("abbccc");
        List<String> b = stringToList("cccbba");
        assertEquals(3, Appearances.sameCount(a, b));
    }

    @Test
    public void testSameCount2() {
        // basic List<Integer> cases
        List<Integer> a = Arrays.asList(1, 2, 3, 1, 2, 3, 5);
        assertEquals(1, Appearances.sameCount(a, Arrays.asList(1, 9, 9, 1)));
        assertEquals(2, Appearances.sameCount(a, Arrays.asList(1, 3, 3, 1)));
        assertEquals(1, Appearances.sameCount(a, Arrays.asList(1, 3, 3, 1, 1)));
    }

    @Test
    public void testSameCount3(){
        List<Double> a = Arrays.asList(2.2, 3.3, 4.4, 1.0, 4.4, 2.2, 3.3);
        assertEquals(1, Appearances.sameCount(a, Arrays.asList(2.2, 2.2, 3.3)));
    }
}

Nicely done, an efficient solution to the problem, easy to read and unit tested. For the sake of completeness, it would be good to include time and space complexity analysis. My main objections are concerning the unit testing technique and naming.

Unit testing

Each test method should have a single, clear purpose. The test methods here essentially pick 3 example inputs, but it's not clear how you picked those examples.

In general, tests should aim to cover cases like:

Happy paths: simple execution paths that run with success
Interesting corner cases
Invalid paths: invalid, tricky, malicious inputs

All methods should have names that describe their purpose. In this particular example, it would be great to add test methods for these cases:

Should get 0 when the collections have nothing in common
Should get size if the collections have identical content
Should get 0 if either ecollection is empty
Should get size of collection if the other is superset

Btw I would use these statements as test method names, with spaces replaced with underscores.

Simplify

In the tests, instead of a List<String>, it would be slightly simpler to use a List<Character>.

Naming

Some of the names are a bit overcomplicated. I suggest some simplifications:

countItemsInCollection: as collection is already implied by the parameter type, I would drop that word from the name
compareMapForMatchingKeyAndValue: a method that starts with the name compare gives the impression that it might follow the contract of comparators, returning either of -1, 0, or 1. So it's a bit misleading. Since this method effectively calculates the intersection of map entries, I would call it intersectEntries, or even just simply intersect
mapItemToNumberOfOccurance: how about simply counts, or itemCounts


PHP Output Block Defining and Best Practices I've been rolling around several ideas or approaches in my head, and none seem any more useful or "right" than another. I'm sure this is extremely objective but I'm looking for a close-to-definitive answer on the object oriented approach to large block string storage and output in PHP. Given the following example, how could I change my approach in a way that might cause Zeev Suraski to pat me on the back and say Mazel Tov (beside using HTML5)?

<?php

class OutputConstructor extends ContentRetriever // Or whatever I decide to name it
{

    protected $htmlHeadBlock;

    public function __construct()
    {

        $this->setHtmlHeadBlock();

    }

    protected function setHtmlHeadBlock()
    {

        ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

        <title><?php echo $this->pageTitle; ?></title>

        <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
        <link rel="icon" href="images/favicon.ico" type="image/x-icon" />

        <meta name="description" content="<?php echo $this->pageDescription; ?>" />
        <meta name="keywords" content="<?php echo $this->pageKeywords; ?>" />

        <link type="text/css" rel="stylesheet" href="css/style.css" />
        <script type="text/javascript" src="js/functions.js"></script>
    </head>
<?php
        $this->htmlHeadBlock = ob_get_clean();

    }

    public function getHtmlHeadBlock()
    {

        return $this->htmlHeadBlock;

    }

} // End of OutputConstructor

?>

The general theme I'm going with in this example class is that on construction, html is stored in a variable via output buffer and then returned by a public method. When evaluating this code, consider that the html will not be static. Page title, description, keywords and the such will be subbed out with dynamic property references. My overall question is: In object oriented programming, ideally where should the output be stored? PHP's DOMDocument class, however useful, doesn't really answer this question for me. Also in this instance, is there any best practice trade-off between using an output buffer and heredoc syntax? Thanks in advance for your guidance!

The first problem i can see and many other's is that your hardcoding output data, why would you hard code output data on within a language that was built for dynamic content creation.

I would suggest that you restructure your class to combine several entites into one, for example, when creating a html web page, i usually is constructed of 5 major compoinants, for isntance:

Page

Head
Body

Header
Main
Footer

Taking this into consideration i would like to make my code so it would act in the same way, create 6 or so classes called:  HTMLPage, HTMLHead, HTMLBody, HTMLBodyHeader, HTMLBodyMain, HTMLBodyFooter

Now each class should be assigned to it's parent, for example:

The Head and Body belong to the Page, and the Header,Main and Fotter belong to the Body, this taken into consideration you should look at the following structure:

/*
 * Create a Page
*/
$Page = new Page("DOCTYPE");

/*
 *Create a Head
*/
$Head = new Head();
$Head->title = "My Practical Home Page";
$Head->addScript("http://google.com/example.js");
$Head->addStyle("http://google.com/example.css");
$Head->addMeta('blah','..blah..');

/*
 * Create a Body Object
*/
$Body = new Body("charset");
$Body->layout = new HTMLLayout("some_file_to_specifiy_the_layout");
$Body->SetContent('LeftBlock.Top','Hello World');

/*
 * Create Footer
*/
$Footer = new Footer('default_footer.php');

/*
 * Add all the segments to the main page!
*/
$Page->head = $Head;
$Page->body = $Body;
$Page->body->header = $Header;
$Page->body->main = "....";
$Page->body->footer= $Footer;

/*
 * Send the page to the browser!
*/
$Page->Display();

I will leave it down to you to figure out the classes


Calculating a payment price based on a selected phone The program shows three phones with prices, and you need to select one of them. The program will then calculate the price based on the payment type you selected.

I'm very new to the world of OOP, and because I'm studying OOP on my own (I actually go to school and we have a computer subject, but I'm taking advance lessons on my own), I have no one to judge my code. I can make programs run, but I'm not sure if I am coding well.

Is there a better way I could have written this simple program? What are the conventions that I did not follow? I did my best based on things I read though, but I'm not sure if I missed things.

package javaPackage;
import java.util.Scanner;
import java.text.DecimalFormat;
public class OopApproach
{
    private String model;
    private double price;
    private double discount;

    public OopApproach(String model,int price)
    {
        this.model=model;
        this.price=price;
    }
    public void setModel( String model )
    {
        this.model = model;
    }
    public void setPrice( double price )
    {
        this.price = price;
    }

    public static void main( String args[] )
    {
        DecimalFormat df = new DecimalFormat("##.00");

        Scanner input=new Scanner(System.in);
        int selection;

        OopApproach iPhone = new OopApproach( "iPhone 6s", 299);
        OopApproach samsung = new OopApproach( "Samsung s6", 199);
        OopApproach lg = new OopApproach( "LG", 99 );

        System.out.println("Press 1:" + iPhone.model+" = " + "$" + df.format(iPhone.price));
        System.out.println("Press 2:" + samsung.model+" = " + "$" +df.format(samsung.price));
        System.out.println("Press 3:" + cherry.model+" = "+ "$" + df.format(lg.price));

        selection=input.nextInt();

        switch(selection)
        {
        case 1:System.out.println( "Your item is " + iPhone.model + " with price of " + "$" + df.format(iPhone.price));
        System.out.println();
        calcPrice(iPhone.model, iPhone.price);
        break;
        case 2:System.out.println( "Your item is " + samsung.model + " with price of " + "$" + df.format(samsung.price));
        System.out.println();
        calcPrice(samsung.model, samsung.price);
        break;
        case 3:System.out.println( "Your item is " + lg.model + " with price of " + "$" + df.format(lg.price));
        System.out.println();
        calcPrice(cherry.model, lg.price);
        break;
        }
    }
        public static void calcPrice(String model,double price)
        {
            Scanner in=new Scanner(System.in);
            DecimalFormat dff=new DecimalFormat("##.00");
            int selec;
            double totalVal;

            System.out.println("Choose payment option");
            System.out.println("1:Cash - 5% discount");
            System.out.println("2:Installment, 3 months - 5% interest");
            System.out.println("3:Installment, 6 months - 10% interest");

            selec=in.nextInt();

            if(selec==1)
            {
                totalVal=price-(price*.05);
                System.out.print("You purchased " + model + " and the total cost is "+ "$" + dff.format(totalVal));
            }
            else if(selec==2)
            {
                totalVal=price+(price*.05);
                System.out.print("You purchased " + model + " and the total cost is "+ "$" + dff.format(totalVal));
            }
            else if(selec==3)
            {
                totalVal=price+(price*.10);
                System.out.print("You purchased " + model + " and the total cost is "+ "$" + dff.format(totalVal));
            }
    }
}

Output:

Press 1:iPhone 6s = $299.00
Press 2:Samsung s6 = $199.00
Press 3:LG = $99.00
1
Your item is iPhone 6s with price of $299.00

Choose payment option
1:Cash - 5% discount
2:Installment, 3 months - 5% interest
3:Installment, 6 months - 10% interest
1
 You purchased iPhone 6s and the total cost is $284.05

You have seemed to start off ok, by acknowledging that you need an object to hold the price and name of the phone.
You can separate this object's class, as others have mentioned, into another file and give it a more meaningful name (e.g. MobilePhone, Device, etc.)
Going back to the original problem, you need to calculate the final purchase price of a phone. According to your requirements, this final value might be influenced by the type of payment the user chooses (e.g Cash or Credit)
There's several ways you can approach your problem afterwards.
Example:
You can have an object that is responsible for calculating the final price of a phone based on the payment options. This might require you to create objects for the payment options as well.
(code below is missing some parts, like constructors, etc)
class PhonePriceCalculator {
    public double calcPrice(Phone phone, Cash cash) { }
    public double calcPrice(Phone phone, Credit cash) { }
}

// some classes to hold data
class Phone { }
class Cash { }
class Credit { }

Then, you just need to plug those objects in with your main() method. There are some improvements that you can make to code above.
For example, Cash is really just a type placeholder for calculating price. It never changes. Maybe you can model the Cash and Credit options through an enumeration. This will work just fine if there's only two credit types.
Another example:
Maybe modelling the price calculation through an object isn't so bad. But you didn't like the fact that we also have objects for the payment types (or an Enum if you decided to go for that instead). Well, you can simplify the price calculator by giving it a discount value instead:
class PhonePriceCalculator {
    public double calcPrice(Phone phone, double discount) { }
}

This way, this class doesn't need to know the payment type. Just the discount.
Final Considerations
I didn't touch private/public encapsulation because other users like Pimgd and Ethan Bierlien had already mentioned it. But again, it is wise to make fields inside an object private, and expose them through methods. Remember, the object is the owner of those fields. So it must choose to expose them (or not) consciously.
I know this is a toy example, but when you are dealing with money calculations in java, you're better of using the BigDecimal class instead of double. You can play with decimal scales, amongst other things.


Matching items in different arrays and performing operations on them I have a data structure that uses a Dictionary<ID,TimeSeries> to hold time series for different products. TimeSeries is implemented as something holding an array of Point, which contain a DateTime and a double.

Its interface is:

TimeSeries{
    int Length{ get; }
    Point ElementAt(int index);

    DateTime StartTime { get; }
    DateTime EndTime { get; }
}

Given a pair of elements of such data structure I need to find the first time instant where they diverge. For my definition of divergence, if a dictionary contains an element and the other doesn't I need to return the time of the first point of the TimeSeries I have.

This is the code I'm using to compute the difference and that I'd like you to review and comment:

bool TryFindFirstDivergenceTime(Dictionary<ID, TimeSeries> baseline, Dictionary<ID, TimeSeries> other, out DateTime firstDivergenceTime)
{
    firstDivergenceTime = default(DateTime);

    foreach(var baselineIDSeriesPair in baseline)
    {
        if(other.ContainsKey(baselineIDSeriesPair.Key))
        {
            firstDivergenceTime = Min(FindFirstDivergenceTime(baselineIDSeriesPair.Value, other[baselineIDSeriesPair.Key]), firstDivergenceTime);
        }
        else
        {
            firstDivergenceTime = Min(baselineIDSeriesPair.Value.Start, firstDivergenceTime);
        }
    }
    foreach(var otherIDSeriesPair in other)
    {
        if(!baseline.ContainsKey(otherIDSeriesPair.Key))
        {
            firstDivergenceTime = Min(otherIDSeriesPair.Value.Start, firstDivergenceTime);
        }
    }

    return firstDivergenceTime != default(DateTime);
}

public DateTime Min(DateTime first, DateTime second)
{
    if(first == default(DateTime))
        return second;
    if(second == default(DateTime))
        return first;
    return new DateTime(Math.Min(first.Ticks, second.Ticks));
}

DateTime FindFirstDivergenceTime(TimeSeries first, TimeSeries second)
{
    if(first.Length != second.Length)
    {
        throw new ArgumentException();
    }
    for(var i=0; i < first.Length; i++)
    {
        if(! first.ElementAt(i).Equals(second.ElementAt(i)))
        {
            return Min(first.ElementAt(i).Time, second.ElementAt(i).Time);
        }
    }
    return default(DateTime);
}

I have the feeling that I am not approaching the problem in the right way as the code contains the repetition of the logic to find the time of the first difference when I don't have the same product in both the dictionaries.

The other think that I don't particularly like is that I find myself breaking th symmetry and using for on dictionary Key and Value from its IEnumerable, while from the other I need to perform a lookup.

How would you address those issues?

Before getting to your question about reducing the duplication, there's another issue I'd like to point out first. The use of default(DateTime) as a check for the absence of a value is incorrect and misleading. default(DateTime) is a valid date. However unlikely it is that you will have a date that equals that value, it is misleading to use because anyone looking at your code that sees a DateTime variable will assume that it holds a proper date value because it has to. As a struct, it can't be represented as null, so it always holds a value. Enter nullable types. DateTime? clearly expresses that the variable can be in a state where it doesn't hold a date value.

That said, it appears you're trying to join the two dictionary and compare in these ways:

When there are matching keys.
When only one of the dictionaries holds a key.

Sounds like a Full Outer Join, which someone has kindly shared a Linq-esque extension method for over on Stack Overflow. Using this, you can concisely and expressively rewrite your methods like so to avoid duplication (note the use of DateTime?):

// Note: I think this is a bad method name (it's the same as the one below,
// which I think is better suited for the name). It should probably express
// the comparison between these Dictionary maps.
public static DateTime? GetEarliestDivergenceTime(Dictionary<int, TimeSeries> baseline, Dictionary<int, TimeSeries> other, DateTime? defaultEarliestDivergenceTime = null)
{
    // Omitting 'FullOuterJoin' code in StackOverflow link:
    var earliestDivergenceTimes = baseline.FullOuterJoin(
        other,
        b => b.Key,
        o => o.Key,
        (b,o) => GetEarliestDivergenceTimeOrDefault(b, o));

    return earliestDivergenceTimes.Min() ?? defaultEarliestDivergenceTime;
}

public static DateTime? GetEarliestDivergenceTime(TimeSeries ts1, TimeSeries ts2, DateTime? defaultEarliestDivergenceTime)
{
    DateTime? earliestDivergenceTime = null;

    if(ts1 != null && ts2 != null)
    {
        // Compare.
    }
    else if(ts1 != null && ts2 == null)
    {
        // Use ts1.
    }
    else if(ts1 == null && ts2 != null)
    {
        // Use ts2.
    }

    // earliestDivergenceTime will be null if both t1 and t2 are null.
    return earliestDivergenceTime ?? defaultEarliestDivergenceTime;
}


Intercept URL containing values or not I need to intercept a URL and go outside the WebView if the URL contains MAPS or DOCUMENTS constants. I must also go outside if url does not contain the value of DOMAIN and LOGIN_SALES_FORCE.

This is working nice, but seems ugly for me. Any ideas?

if ([request.URL.absoluteString rangeOfString:MAPS      ].location != NSNotFound ||
    [request.URL.absoluteString rangeOfString:DOCUMENTS ].location != NSNotFound)
{
    NSURL *url = [NSURL URLWithString:request.URL.absoluteString];
    return [[UIApplication sharedApplication] openURL:url];
} else if ([request.URL.absoluteString rangeOfString:DOMINIO           ].location == NSNotFound &&
           [request.URL.absoluteString rangeOfString:LOGIN_SALES_FORCE ].location == NSNotFound) {
    NSURL *url = [NSURL URLWithString:request.URL.absoluteString];
    return [[UIApplication sharedApplication] openURL:url];
}

Disclaimer: I don't know Objective-C. The proposed changes are quite basic, though, and should give the same result as your original code.

Intermediate variables

To shorten your expressions, you may want to use an intermediate variable:

NSString *absUrl = request.URL.absoluteString;

Then, you can group your conditions using boolean operators.

Boolean logic

if (   [absUrl rangeOfString:MAPS].location != NSNotFound
    || [absUrl rangeOfString:DOCUMENTS].location != NSNotFound
    || (    [absUrl rangeOfString:DOMINIO].location == NSNotFound
         && [absUrl rangeOfString:LOGIN_SALES_FORCE].location == NSNotFound))
{
    NSURL *url = [NSURL URLWithString:request.URL.absoluteString];
    return [[UIApplication sharedApplication] openURL:url];
}

Remarks

Reading this documentation, I find it strange that you are converting request.URL to url using URLWithString. I may be wrong, but you could use absoluteUrl to achieve the same effect.


Fisher-Yates modern shuffle algorithm I have implemented the shuffling algorithm of Fisher-Yates in C++, but I've stumbled across the modulo bias.  Is this random number generation by rand() correct for Fisher-Yates?

srand(time(NULL));
vector<int> elements;
// push numbers from 1 to 9 into the vector
for (int i = 1; i < 9; ++i)
{
    elements.push_back(i);
}

// the counter to be used to generate the random number
int currentIndexCounter = elements.size();
for (auto currentIndex = elements.rbegin(); currentIndex != elements.rend() - 1;
     currentIndex++ , --currentIndexCounter)
    {
        int randomIndex = rand() % currentIndexCounter;
        // if its not pointing to the same index
        if (*currentIndex != elements.at(randomIndex))
        {
            //then swap the elements
            swap(elements.at(randomIndex), *currentIndex);
        }
    }

@Loki Astari is correct in his comment:

  rand() is well know for its bad distribution. But you are using it correctly. Note: rand() % currentIndexCounter does not give you a perfect distribution unless currentIndexCounter is an exact divisor of RAND_MAX. You may want to look at C++11 random header and the generators provided inside.

Since you're using C++11, you should instead utilize the <random> library.  It includes things such as pseudo-random number generators and random number distributions.

Beyond that, I'll just point out some additional things:

With C++11, you should now be using nullptr instead of NULL.

This should be changed in srand():

std::srand(std::time(nullptr));

However, as mentioned above, you should not be using this with C++11.  But in any situation where you must stay with rand, the above would be recommended.
With C++11, you should also have access to initializer lists.  This will allow you to initialize the vector instead of calling push_back() multiple times:

std::vector<int> elements { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Also note that your push_back() was only pushing numbers 1-8 into the vector, despite what your comment said.  You've used < instead of <= in the loop statement, so the 9 was excluded.
currentIndexCounter should be of type std::vector<int>::size_type, which is the return type of size() (or you can just use auto).  This should've given you compiler warnings as it's a type-mismatch and a possible loss of data.  Make sure your compiler warnings are turned up high.
currentIndex is a misleading name because it's being used with iterators, not indices.

Here, auto gives currentIndex the type std::reverse_iterator from std::rbegin().  You could simply name this something like iter.  It's okay for iterator names to be short.
In the second for loop, you just need elements.rend(), without the - 1.  The iterator will already go through the entire vector and stop at the last reverse element.
The iterator increment should be prefix instead in order to improve performance a bit by avoiding a copy.  It's best to do this with all nontrivial types such as iterators.
I've tested this by giving randomIndex a value greater than elements.size(), causing an exception to be thrown.  Even if std::rand() or another RNG is guaranteed to give you an intended value, it may be best to handle this properly.

Here's the final version with my own given changes, which I've also ran here.  I've also included a concise way of displaying the vector before and after the shuffling.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>

int main()
{
    // seed the RNG
    std::random_device rd;
    std::mt19937 mt(rd());

    std::vector<int> elements { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    std::cout << "Before: ";
    std::copy(elements.cbegin(), elements.cend(),
        std::ostream_iterator<int>(std::cout, " "));

    auto currentIndexCounter = elements.size();

    for (auto iter = elements.rbegin(); iter != elements.rend();
        ++iter, --currentIndexCounter)
    {
        // get int distribution with new range
        std::uniform_int_distribution<> dis(0, currentIndexCounter);
        const int randomIndex = dis(mt);

        if (*iter != elements.at(randomIndex))
        {
            std::swap(elements.at(randomIndex), *iter);
        }
    }

    std::cout << "\nAfter: ";
    std::copy(elements.cbegin(), elements.cend(),
        std::ostream_iterator<int>(std::cout, " "));
}

Output:

Before: 1 2 3 4 5 6 7 8 9
After: 7 9 3 2 4 5 6 1 8


C++ Coding Exercise - Maximum unit to load into a truck given it size You are assigned to put some amount of boxes onto one truck. You are given a 2D vector of box_types where box_type[0] is the number of a type of box and box_type[1] is the units per box for that type. You are also given an integer value for the truck size, this the maximum boxes you can put in the truck. Return the maximum unit that can be put in a given truck.
Example
input : box_types = {{1, 3}, {2, 2}, {3, 1}}
truck_size = 4
output: 8
Explanation:
There are

1 box of type 0
2 box of type 1
3 box of type 2

where 0, 1, 2 is the index of the vector
You can take all the boxes of the first type, second type and one box from the third type
max_unit = (1 * 3) + (2 * 2) + (1 * 1) = 8
Here is my implementation
#include <iostream>
#include <algorithm>
#include <vector>

void sort_boxtypes(std::vector<std::vector<int>> &box_types)
{
    std::sort(
        box_types.begin(), box_types.end(),
        [](const std::vector<int>& a, const std::vector<int> &b)
        {return a[1] > b[1]; }
    );
}
int maximum_units(std::vector<std::vector<int>> box_types, int truck_size)
{
    sort_boxtypes(box_types);
    int max_unit = 0;
    for(const auto& box_type : box_types)
    {
        truck_size -= box_type[0];
        if(truck_size >= 0)
            max_unit += box_type[0] * box_type[1];
        else
        {
            max_unit += (box_type[0] + truck_size) * box_type[1];
            return max_unit;
        }
    }
    return max_unit;
}

int main()
{
    std::vector<std::vector<int>> box_types = {{5, 10}, {2, 5}, {4, 7}, {3, 9}};
    int max = maximum_units(box_types, 10);
    std::cout << max << '\n';

}

Names are better then indices. Consider
  struct box_type {
      int amount;
      int capacity;
  };

box.amount seems cleaner that box[0].

Along the same line, declaring such a structure would let you define
  friend bool box_type::operator <(const box_type& l, const box_type& r) {
      return l.capacity < r.capacity;
  }

and eliminate a lambda, as well as sort_boxtypes function.

I don't like max_units (it sounds like there are min_units somewhere). Similarly, truck_size is a truck size, a constant; consider a remaining_size or something like that.

It feels that a truck_size >= 0 comparison shall be done beforehand. Consider
  std::sort(boxes.begin(), boxes.end());
  for (auto box = boxes.rbegin(); box != boxes.rend(); ++box) {
      auto the_load = std::min(box.amount, remaining_size());
      units += box.capacity * box.amount;
      remaining_size -= the_load;
      if (remaining_size == 0) {
          break;
      }
  }
  return units;


Join two collections by date with no duplicate Data

I have 4 Collection objects of the following kind:

dates1=(12/01/02, 15/01/03, 17/01/03, 25/04/04...)
dates2=(15/02/02, 17/06/07, 10/05/10, ...)
numbers1 = (3,5,2,7,...)
numbers2 = (1,-3,-1,...)

The rules of the game are:

dates1 will always have the same length of numbers1, dates2 will always have the same length of numbers, but dates1 is not necessarily as long as dates2.
The dates into the two dates collections are always growing within the same collection, but not necessarily the first date of dates1 will be before the first date of dates2.

Problem in words

I would like to create a "merged" collection of these two. In particular,

The datesTot collection will have to contain only one date for each record. So, for example, if both "dates1" and "dates2" contain the 14/01/13, then this date will appear in the collection only once.
The numbersTot collection will have to contain the sum of the two "numbers" collection in case the date is a duplicate, otherwise only the single value.

For example:

numbers1 = (1,3,4)
numbers2 = (4,7,12)
dates1 = (13/01/14, 14/01/15, 16/01/17)
dates2 = (12/01/14, 14/01/15, 18/01/17)

will result in the following:

datesTot = (12/01/14, 13/01/14, 14/01/15, 16/01/17, 18/01/17)
numbersTot = (4, 1, 10, 4, 12) '<-- where 10 is the sum of 7+3, because they both are on 14/01/15

What I have tried so far

I have tried to stretch the human logic described above in a code:

Determining with which date the joint collection should start:

Do While (dates1Index <= dates1Index.Count) And (dates2Index <= dates2Index.Count)
If dates1(dates1Index) < dates2(dates2Index) Then '<-- to put in a while loop with some conditions check
    datesTot.Add dates1(dates1Index)
    numbersTot.Add numbers1(dates1Index)
    dates1Index = dates1Index + 1
ElseIf dates1(dates1Index) > dates2(dates2Index) Then
    datesTot.Add dates2(dates2Index)
    numbersTot.Add numbers2(dates2Index)
    dates2Index = dates2Index+1
Else
    datesTot.Add dates1(dates1Index)
    numbersTot.Add numbers1(dates1Index) + numbers2(dates2Index)
    dates1Index = dates1Index + 1
    dates2Index = dates2Index + 1
End If
Loop

The idea, hence, is to keep on looping through the elements like this with the separate indexes, by adding some controls (for the collections lengths) and once reached the shortest collection's length, keep on adding all the others of the longest collection.

My question

The more I look at this method, the less I'm convinced. It's heavy, dirty and (in my opinion) not the best algorithm ever. Is there any built in for collections in VBA to join the elements without duplicates and sort them (I've not found anything in the docs) hence? Or in general, how should I design my code to accomplish this purpose in a flexible way?

You've got a pretty big bug here. You don't actually end up with unique items in your final list. In fact, with the sample data you gave, 1/15/14 ends up in the final output twice. You should be entering that Else block, but you're not. This is because you're not comparing what's already stored in datesTot to that value in dates2, you're comparing it to what is at the current index of dates1. (By the way, don't shorten your variable names like that. datesTotal or dateTotals would be a much better name).

I think this stems from the fact that you don't loop all the way through the first collection, before you shift the index on the second. Your attempt at optimizing the performance of the code has led to a bug. A wise dev once told me:

  Make it work.
  Make it right.
  Then make it fast.

The second problem I see is your data structure. You're keeping related data in two separate, but parallel collections. That's a recipe for disaster. Why? Because you can't overwrite an item in a collection. You have to add the replacement to the collection and then remove the original. That leaves a ton of room to make a mistake.

A correct algorithm requires three loops.

For Each outerItem in outerCollecton

    For Each innerItem in innerCollection

        If outerItem = innerItem Then

            For Each resultItem In results
                If innerItem = resultItem then
                    resultItem.Count = resultItem.Count + innerItem.Count
                    Exit For
                Else
                    results.Add innerItem
                End If
            Next resultItem

        End If

    Next innerItem

Next outerItem

Implementing that in a clean way would be easier said than done though, because you can't overwrite a value in a collection. That means you will need to keep single collection of objects that represent your data structure. For simplicity's sake, you could create a class module as simple as this.

Option Explicit

Public DateValue As Date
Public Count As Long

Alternatively, assuming your original data that you want to merge has only one instance of each date, then a Scripting.Dictionary could be a great data structure to use. See my example below.

Public Sub test()

    Dim dates1 As New Scripting.Dictionary
    dates1.Add #1/14/2013#, 1
    dates1.Add #1/15/2014#, 3
    dates1.Add #1/17/2016#, 4

    Dim dates2 As New Scripting.Dictionary
    dates2.Add #12/1/2014#, 4
    dates2.Add #1/15/2014#, 7
    dates2.Add #1/17/2018#, 12

    ' first copy the first dict to a new one to return
    Dim results As New Dictionary

    Dim currentKey

    For Each currentKey In dates1.Keys
        results.Add currentKey, dates1(currentKey)
    Next

    ' second dict
    For Each currentKey In dates2.Keys

        If results.Exists(currentKey) Then
            results(currentKey) = results(currentKey) + dates2(currentKey)
        Else
            results.Add currentKey, dates2(currentKey)
        End If

    Next

    ' print the results
    For Each currentKey In results.Keys
        Debug.Print "Date: " & currentKey & vbTab & "Count: " & results(currentKey)
    Next

End Sub

Output:

Date: 1/14/2013 Count: 1
Date: 1/15/2014 Count: 10
Date: 1/17/2016 Count: 4
Date: 12/1/2014 Count: 4
Date: 1/17/2018 Count: 12


Settings Model to read multiple settings files and writes to one I am writing a Model to read, write and store settings.
I think my code is pretty good, but I am not 100% sure.
Any advice on how I could possibly improve it is welcome.

import ntpath

import yaml

class Settings:
    def __init__(self, paths=None, default_path=None):
        """Load, write and store settings

        This model manages setting files (YAML).

        Keyword Arguments:
            paths {list or None} -- list of full or relative
                                    paths with filenames (default: {None})
            default_path {str or None} -- path to user settings, read last
                                          and default for writing
                                          (default: {None})
        """
        paths = paths or []
        # Make sure paths are unique and sorted by file name
        self.paths = sorted(set(paths), key=lambda p: ntpath.basename(p))
        # Remove default_path from paths (look at next comment)
        try:
            self.paths.remove(default_path)
        except ValueError:
            pass
        # Readd default_path at the end to make sure it's loaded last
        if default_path is not None:
            self.paths.append(default_path)
        # Set remaining attributes
        self.default_path = default_path
        self.settings = {}

        # Load files
        self.reload()

    def reload(self):
        """Reload files into buffer

        Reloads the files specified in self.paths
        and writes them into the buffer.
        """
        # Clear settings to ensure no unwanted leftovers
        self.settings.clear()
        # Load every path (sorted by filename, self.default_path last)
        for path in self.paths:
            with open(path, 'r') as f:
                content = f.read()
            self.settings.update(yaml.load(content) or {})

    def write(self, key, value, path=None):
        """Write into file

        Writes key and value into the file specified
        by path (or self.default_path if None)

        Arguments:
            key {immutable} -- key to use (valid YAML key)
            value {ANY} -- value to save

        Keyword Arguments:
            path {str} -- path to save file (default: {None})
        """
        path = path or self.default_path
        assert path is not None

        with open(path, 'r') as f:
            settings = yaml.load(f.read()) or {}

        settings[key] = value
        self.settings[key] = value

        with open(path, 'w') as f:
            f.write(yaml.dump(settings, default_flow_style=False))

The module should import os.path instead of ntpath.

os.path is the cross-platform equivalent of ntpath, it automatically picks the appropriate path module for the OS your code is running on. So it will use ntpath behind the scenes when running on Windows, but you will also be able to use the code on more operating systems than just Windows.  (See the note at https://docs.python.org/3/library/os.path.html)