Reddit Investigator-like JS app I am building a one-page JS app similar to redditinvestigator.com, and my goal is for it to be 100% done in JavaScript. Coming from a PHP/Java background, I'm more used to working in class oriented languages, so I just want to get a sense if I am implementing them correctly in JavaScript.

My code works as expected, and I am just hoping to get some feedback on if there is anything I technically am doing wrong, or if there is a better way to do some of the things I am implementing.

jsFiddle (the results are just in the console FYI)

var Comment = function(obj) {
    if (obj) {
        this.data = obj.body;
        this.created_utc = obj.created_utc;
        this.downs = obj.downs;
        this.gilded = obj.gilded;
        this.id = obj.id;
        this.link_id = obj.link_id;
        this.link_title = obj.link_title;
        this.name = obj.name;
        this.subreddit = obj.subreddit;
        this.ups = obj.ups;
    }
};

Comment.prototype.getBody = function() {
    return this.data;
};
Comment.prototype.getCreated = function() {
    return this.created_utc;
};
Comment.prototype.getDownvotes = function() {
    return this.downs;
};
Comment.prototype.getUpvotes = function() {
    return this.ups;
};
Comment.prototype.getScore = function() {
    return this.ups - this.downs;
};
Comment.prototype.isGilded = function() {
    return this.gilded;
};
Comment.prototype.getID = function() {
    return this.id;
};
Comment.prototype.getLinkID = function() {
    return this.link_id;
};
Comment.prototype.getLinkTitle = function() {
    return this.link_title;
};
Comment.prototype.getName = function() {
    return this.name;
};
Comment.prototype.getSubreddit = function() {
    return this.subreddit;
};

var RedditInterface = function(username) {
    this.userName = username;
    this.commentCount = 0;
    this.submissionCount = 0;
    this.lastCall = 0;
};

RedditInterface.prototype.getUsername = function() {
    return this.userName;
};

RedditInterface.prototype.sendQuery = function(endpoint, after, func) {
    var curDate = new Date().getTime();
    var timeSince = curDate - this.lastCall;
    if (timeSince < 5000)
        return null;
    this.lastCall = curDate;

    var urlD = '';
    if (after === '')
        urlD = "http://www.reddit.com/user/" + this.userName + "/" + endpoint + ".json?limit=100&jsonp=?";
    else
        urlD = "http://www.reddit.com/user/" + this.userName + "/" + endpoint + ".json?limit=100&after=" + after + "&jsonp=?";

    $.ajax({
        url: urlD,
        dataType: 'json',
        success: func
    });
};

RedditInterface.prototype.loadAllComments = function() {
    var here = this;
    var intervalHandle = window.setInterval(function() {
        here.sendQuery('comments', commentAfter, function(data) {
            if (data.data.children.length === 0) { //We've loaded all the comments reddit will give us
                console.log("Comments loaded. Total: " + commentLog.length);
                window.clearInterval(intervalHandle);
            }
            for (var point in data.data.children) {
                var ret = new Comment(data.data.children[point].data);
                var accept = true;
                for (var i = 0; i < commentLog.length; i++) {
                    if (commentLog[i].name == ret.name) {
                        console.log(i + ' (' + commentLog[i].name + ') is equal to current (' + ret.name + '), ommitting.');
                        accept = false;
                        break;
                    }
                }
                if (accept && typeof ret.name !== 'undefined') {
                    commentLog.push(ret);
                    commentAfter = ret.name;
                }
            }
            console.log(commentLog);
        });
    }, 5500);
    return intervalHandle;
};

//Begin Logic
var commentLog = [];
var submissionLog = [];
var commentAfter = '';

var ri = new RedditInterface("hueypriest");
var handle = ri.loadAllComments();

Your code is very clean, easy to understand and well written. My only comment for improving it would be to take advantage of a framework that does some of this lifting for you, such as:

KnockoutJS
BackboneJS
AngularJS

As well, coming from an OO background, you might be interested at looking at CoffeeScript, which is a higher level language that provides class constructs and such that compiles down into regular JavaScript.


C++ arithmetic on two numbers I need someone with experience to judge my first project to let me know what I have to work on. I recently started learning C++ using resources like Solo Learn and Bucky's tutorials on YouTube hoping to eventually gain enough experience to find a job in software development.

#include <iostream>
#include <string>
using namespace std;
//Functions

// addition function
int calc_sum(){
double x;
double y;
cout << "enter two numbers to get a sum" <<endl;
cin >> x >> y;
double sum = x+y;
cout <<"The sum is "<< sum <<"."<<endl;

}
// multiplication function
int calc_pro(){
double a;
double b;
cout<<"enter two numbers to find the product"<<endl;
cin>> a >> b;
double product = a * b;
cout<< "The product is "<< product <<"."<<endl;

}
// division function
int calc_div(){
double x;
double y;
cout<< "enter two numbers to divide."<<endl;
cin>> x >> y;
double div = x/y;
cout << "The quotient is "<< div <<"." <<endl;
}
// Subtraction function
int calc_sub() {
double a;
double b;
cout<< "Enter two numbers to subtract."<< endl;
cin>> a >> b;
double diff = a-b;
cout<< "The difference is "<< diff <<endl;

}

//core function

void core2(){
string choice;
cout<<"Would you like to multiply, divide, add, or subtract? (typer in lowercase)"<<endl;
cin>>choice;

if(choice=="add"){
calc_sum();
core2();
}
else if(choice=="subtract"){
calc_sub();
core2();
}
else if(choice=="multiply"){
calc_pro();
core2();
}
else if(choice=="divide"){
calc_div();
core2();
}
else{
cout<<"USER ERROR"<<endl<< "you typed in something wrong, try again."<<endl;
core2();
}
}

int main(){

core2();

}

Code formatting

Format your code to improve readability and hence maintainability.

DRY (Don't Repeat Yourself) Principle

You have a lot of places with duplicate code. You should try to avoid this.

First of all in your core2 method you have calls in all condition blocks, you should move it below to be executed in any case.

Also you have many duplicate code in your calc methods. You can move duplicate code to your core core2 method.

Inconsistent styles

Use the same style everywhere. If you are starting your sentences for output with uppercase then try to follow it everywhere. The same is true about comments and constructs like to get a sum, to find a product, to divide. Use single ubiquitous style for everything.

Function return types

If you don't want to return anything from your function it should be void. All your calc functions are ints (but you don't call return operator) and you are not using return values. So all your calc functions should be void.

Redundant core2 function

Also core2 function is not needed here, you can use main directly. But C++ specs prohibits this behaviour although this works fine in most compilers. So we can replace core2 recursion with infinite loop in main.

So if we take into account all above notes code will look like this

#include <iostream>
#include <string>
using namespace std;

// Now we have only primitive one-liner arithmetic functions
// with double return types

double add(double a, double b) { return a + b; }

double subtract(double a, double b) { return a / b; }

double multiply(double a, double b) { return a * b; }

double divide(double a, double b) { return a / b; }

void core2() {
    string choice;
    cout << "Would you like to multiply, divide, add, or subtract? (typer in lowercase)" << endl;
    cin >> choice;

    // Choosing correct action name to output
    string result_name;

    if (choice == "add") {
        result_name = "sum";
    } else if (choice == "subtract") {
        result_name = "difference";
    } else if (choice == "multiply") {
        result_name = "product";
    } else if (choice == "divide") {
        result_name = "quotient";
    } else { // This block also performs validation of input parameter
        result_name = ""; // Just to prevent compiler error due to undeclared variable
        cout << "USER ERROR" << endl << "you typed in something wrong, try again." << endl;
        return; // end execution here
    }

    // Entering numbers in single place
    double a;
    double b;
    cout << "Enter two numbers to get the "<< result_name << "." << endl;
    cin >> a >> b;

    double result;

    if (choice == "add") {
        result = add(a, b);
    } else if (choice == "subtract") {
        result = subtract(a, b);
    } else if (choice == "multiply") {
        result = subtract(a, b);
    } else {
        result = divide(a, b);
    }

    // Outputting result in single place
    cout << "The " << result_name << " is " << result << "." << endl;
}

int main() {
    while (true) {
        core2();
    }
}

Further improvement will use more advanced techniques and relatively new C++11 features.

You need some way to map string and function, so for this we will use std::map as dictionary and std::function as polymorphic function wrapper. Also lambdas will be use to pass anonymous functions here as parameters. struct will be here used as container to store calculation function and result description.

#include <iostream>
#include <string>
#include <functional>
#include <map>
using namespace std;

struct CalculationTechnique {
    std::function<double (double,double)> Function;
    string ResultName;
};

void core2() {
    string choice;
    cout << "Would you like to multiply, divide, add, or subtract? (typer in lowercase)" << endl;
    cin >> choice;

    // Filling our dictionary
    std::map<string, CalculationTechnique> calculation_mapping = {
        { "add", CalculationTechnique { [](double a, double b) -> double { return a + b; }, "sum" } },
        { "subtract", CalculationTechnique { [](double a, double b) -> double { return a - b; }, "difference" } },
        { "multiply", CalculationTechnique { [](double a, double b) -> double { return a * b; }, "product" } },
        { "divide", CalculationTechnique { [](double a, double b) -> double { return a / b; }, "quotient" } }
    };

    // if no value found in dictionary
    if (calculation_mapping.count(choice) == 0) {
        cout << "USER ERROR" << endl << "you typed in something wrong, try again." << endl;
        return;
    }

    CalculationTechnique technique = calculation_mapping.at(choice);

    double a;
    double b;
    cout << "Enter two numbers to get the "<< technique.ResultName << "." << endl;
    cin >> a >> b;

    cout << "The " << technique.ResultName << " is " << technique.Function(a, b) << "." << endl;
}

int main() {
    while (true) {
        core2();
    }
}


Simple Registration Form. I would like to get rid of code duplications I don't like my current code, because of duplications. What's the best way to leverage Kotlin to make it more concise. I have simple registration form

data class RegisterForm @JvmOverloads constructor(
        val email: String = "",
        val emailError: String = "",

        val lastName: String = "",
        val lastNameError: String = "",

        ...
)

In my ViewModel I'm reacting to my TextWatcher. I set my state by updating my RegisterForm data class

fun onEmailChanged(email: String) {
    setState {
        copy(registerForm = registerForm
                .copy(email = email, emailError = validateEmail(email))
        ) }
}

fun onFirstNameChanged(text: String) {
    setState {
        copy(registerForm = registerForm
                .copy(firstName = text, firstNameError = validateFirstName(text))
        ) }
}

As you can see, I need to copy paste the code in my ViewModel every time I'm adding the new input field. How can I leverage Kotlin to get rid of these duplications?

In functional programming terms, using Lenses could help you modify nested object elegantly. There are no native supported lenses in kotlin language but some libraries provided. Check klenses or arrow.


Brute force password cracker in Python I made a brute force password cracker with Python, but it's extremely slow. How can I make it faster?

import itertools
import string
import time

def guess_password(real):
    chars = string.ascii_uppercase + string.digits
    password_length = 23
    start = time.perf_counter()
    for guess in itertools.product(chars, repeat=password_length):
        guess = ''.join(guess)
        t = list(guess)
        t[5] = '-'
        t[11] = '-'
        t[17] = '-'
        tg = ''.join(t)
        if tg == real:
            return 'Scan complete. Code: \'{}\'. Time elapsed: {}'.format(tg, (time.perf_counter() - start))

print(guess_password('E45E7-BYXJM-7STEY-K5H7L'))

As I said, it's extremely slow. It takes at least 9 days to find a single password.

You should exploit the structure of the password, if it has any. Here you have a 20 character password separated into four blocks of five characters each, joined with a -. So don't go on generating all combinations of length 23, only to throw most of them away.

You also str.join the guess, then convert it to a list, then replace the values and str.join it again. You could have saved yourself the first str.join entirely by directly converting to list.

You know the length of the password, so no need to hardcode it. Just get it from the real password (or, in a more realistic cracker, pass the length as a parameter).

With these small changes your code would become:

def guess_password(real):
    chars = string.ascii_uppercase + string.digits
    password_format = "-".join(["{}"*5] * 4)
    password_length = len(real) - 3
    for guess in itertools.product(chars, repeat=password_length):
        guess = password_format.format(*guess)
        if guess == real:
            return guess

Here I used some string formatting to get the right format.

Note also that the timing and output string are not in there. Instead make the former a decorator and the latter part of the calling code, which should be protected by a if __name__ == "__main__": guard to allow you to import from this script without running the brute force cracker:

from time import perf_counter
from functools import wraps

def timeit(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = perf_counter()
        ret = func(*args, **kwargs)
        print(f"Time elapsed: {perf_counter() - start}")
        return ret
    return wrapper

@timeit
def guess_password(real):
    ...

if __name__ == "__main__":
    real_password = 'E45E7-BYXJM-7STEY-K5H7L'
    if guess_password(real_password):
        print(f"Scan completed: {real_password}")

On my machine this takes 9.96 s ± 250 ms, whereas your code takes 12.3 s ± 2.87 s for the input string "AAAAA-AAAAA-AAAAA-FORTN".

But in the end you will always be limited by the fact that there are a lot of twenty character strings consisting of upper case letters and digits. Namely, there are \$36^{20} = 13,367,494,538,843,734,067,838,845,976,576\$ different passwords that need to be checked (well, statistically you only need to check half of them, on average, until you find your real password, but you might get unlucky). Not even writing your loop in Assembler is this going to run in less than days.


Sum Lists function in Scala Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in
  reverse order, such that the 1 's digit is at the head of the list.
  Write a function that adds the two numbers and returns the sum as a
  linked list.

  EXAMPLE

  Input: (7-> 1 -> 6) + (5 -> 9 -> 2).That is,617 + 295

  Output: 2 -> 1 -> 9. That is, 912

Is there any way to improve the code?

def sumList(list1:List[Int], list2:List[Int], curry: Int):List[Int]= (list1.size,list2.size) match {
    case (0,0)=>List.empty
    case (0, b) =>sumList(List.empty, list2.tail, if(list2.head+curry>10)(list2.head+curry)/10 else 0):::List((list2.head+curry)%10)
    case (a,0)  =>sumList(list1.tail,List.empty , if(list1.head+curry>10)(list1.head+curry)/10 else 0):::List((list1.head+curry)%10)
    case (a,b) =>sumList(list1.tail,list2.tail, if(list1.head+list2.head+curry>10)(list1.head+list2.head+curry)/10 else 0):::List((list1.head+list2.head+curry)%10)
  }

Naming

Use something shorter and more generic, like a and b, instead of list1 and list2
curry is mispelled -- should be carry

You are repeating yourself a lot.  For example, except in the case where both lists are empty:

In each case, you have three adds that are exactly the same.
All three cases have a very similar structure -- the only difference is basically which numbers are being added

Consider defining a class to represent numbers.  That way, you can easily change the representation in the future.
I don't think your implementation is tail-recursive.  This will lead to stack-overflows for large lists.  This might or might not be a problem, depending on your application.
Use "word-at-a-time" thinking only as a last resort.  In this case, you are directly recursing over the lists -- one element ("word") at a time.  Try to find a higher-level abstraction, such as map, that you can use.

In this particular case, in order to handle the carries, you really need some sort of "map plus accumulator" abstraction.  To my knowledge, there is no such function built-in to Scala.  So you might have to write your own.  Still, I would suggest implementing a generic, higher-order function to do this.  That way, you can reuse that function later for other things.
Try to decompose your problem.  In this case, the problem is already fairly simple.  Still, you might (or might not -- I'm not sure) benefit from drawing inspiration from hardware adders.


Sorting algorithms - Insertion sort This is a follow-up question to Sorting algorithms - Bubble sort

Again, for practice purposes only, I took on an implementation of the well known insertion sort as a method to be used similarly to std::sort.

As expected, the code lives inside a header file called insertion_sort.h:

#pragma once

#include <iterator>
#include <algorithm>

namespace sorting_algorithms {
    template <typename BidirectionalIterator,
            typename Comparator = std::less<>>
    void insertion_sort(BidirectionalIterator begin, BidirectionalIterator end,
            Comparator cmp = {}) {

        if (std::distance(begin, end) < 2) {
            return;
        }

        for (auto current_element = std::next(begin); current_element != end;
                ++current_element) {
            for (auto i = std::prev(current_element), i_next = current_element;
                    i_next != begin; --i, --i_next) {
                auto& i_val = *i;
                auto& i_next_val = *i_next;
                if (cmp(i_val, i_next_val)) {
                    break;
                }
                std::iter_swap(&i_val, &i_next_val);
            }
        }
    }
}

I tried to follow most hints and suggestions I received for my previous question about bubble sort. I am aware of the fact that the algorithm can also be implemented in a way that only requires forward iterators, but I decided to require bidirectional iterators here for ease of implementation.

Again, I also provide you a main file for simple compilation and testing purposes:

#include <random>
#include <vector>
#include <iostream>
#include <iomanip>
#include <chrono>
#include <algorithm>

#include "insertion_sort.h"

int main() {
    unsigned seed =
        std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine engine(seed);
    std::uniform_int_distribution<unsigned> distribution(0, 10000);

    std::vector<unsigned> vec;
    for (std::size_t i = 0; i < 100; ++i) {
        unsigned num = distribution(engine) + 1;
        std::cout << num  << ' ';
        vec.push_back(num);
    }
    std::cout << "\n\n";

    sorting_algorithms::insertion_sort(vec.begin(), vec.end());

    for (const auto& e : vec) {
        std::cout << e << ' ';
    }

    std::cout << std::boolalpha;
    std::cout << "\nSorted? " << std::is_sorted(vec.begin(), vec.end())
        << "\n\n";

    sorting_algorithms::insertion_sort(vec.begin(), vec.end(),
            [] (const auto& v0, const auto& v1) {
                return v0 > v1;
            });

    for (unsigned e : vec) {
        std::cout << e << ' ';
    }
    std::cout << "\nSorted (in reverse order)? "
        << std::is_sorted(vec.begin(), vec.end(),
            [] (const auto& v0, const auto& v1) {
                return v0 > v1;
            }) << '\n';
}

Important stuff:

Missing header:

The std::less<> is from <functional>.

Relying on type deduction:

Although it is generally good, the lines

            auto& i_val = *i;
            auto& i_next_val = *i_next;

seem somewhat dangerous to me. For std::vector<bool>, for example. I think it should be at least const auto&, or even better, the comparison could be called without them:

cmp(*i, *i_next);

Dangerous swap:

        auto& i_val = *i;
        auto& i_next_val = *i_next;
        if (cmp(i_val, i_next_val)) {
            break;
        }
        std::iter_swap(&i_val, &i_next_val);

The swap assumes that types didn't overload operator&. It is pretty rare these days, but still exist. The swap should just be std::iter_swap(i, i_next).

Style:

Complicated inner loop:

The control flow inside of the loop is very hard to follow. This is the version in my library:

        auto j = i;
        while (std::prev(j) != first && !cmp(*std::prev(j), *j))
        {
            std::iter_swap(std::prev(j), j);
            --j;
        }

The i is the iterator of the outer loop. It might not be that descriptive, but I think it is ok. The main idea here is that while loop is used and the condition is inside of the condition brackets, which closely follows plain english description of an algorithm.

Naming:

Usually range is denoted by [first, last). At least this is what I see quite frequently on cppreference. Also, the concept is called Compare, so it might be worth sticking to it, although it is somewhat confusing.

Testing:

There is std::greater template function object which could be used instead of handwritten lambda.


isPrime functions in Python and Java This Python code looks messy to me. Am I doing any wrong style, or is this how Python looks like?

def is_prime(number):
    """check whether the @param number is a prime number"""
    is_prime = True
    for i in range(2, (number - 1)):
        is_prime = ((number % i) != 0)
        if not is_prime:
            return is_prime
    return is_prime

This Java code looks more clean, maybe due to a lot of empty lines generated due to the { } brackets:

private boolean isPrime(int toCheck)
{
    boolean isPrime = true;

    for (int i = 2; i < toCheck; i++)
    {
        isPrime = ((toCheck % i) != 0);
        if (!isPrime)
        {
            return isPrime;
        }
    }

    return isPrime;
}

Python version 2.6.

This is a pretty literal translation of the algorithm. Let's first review the code itself and then check how we could reimagine it in python:

I'm not sure why there is a declaration for is_prime or isPrime respectively. It can be inlined, making the code look as follows:

for i in range(2, (number - 1)):
    if (number % i) == 0:
        return False
return True

This uses some minor formatting simplifications, like dropping extraneous parentheses.
The next step is then to actually optimize the program.
In this instance, using xrange over range is preferred, since you don't need to store the whole list of numbers before iterating over it, which is what range does. Note that this only applies for python 2.x, since xrange is not available for python 3.x
Mathematically it's proven, that the first prime divisor of a non-prime number appears before (or athat tip to jwodder) the square root of said number. This can vastly reduce your searchspace:

for i in xrange(2, math.sqrt(number) + 1):

Peilonrayz correctly added in a comment that the full code can be reformulated as a generator-comprehension using all, which is basically the "most python-y" implementation I've seen yet:

all(number % i for i in range(2, int(number ** 0.5) + 1))

Overall the code is stylistically fine. The Docstring could use a bit of love and the algorithm chosen doesn't lend itself well to python's idea of generators (research this concept, it's key to writing idiomatic and fast python).

Finally: Your java code looks messy to me, since it doesn't conform to the standard egyptian bracing style and is very spacious vertically.
In the end this seems to boil down to personal preference of vertical space in code.


Scraping PubMed query results: follow-up I recently posted a question looking for feedback on a script I wrote (see: Scraping PubMed query results)

Since then I have re-written it into a class, which I have posted below.  How does it look?  How can I improve upon it?

class PubMedQuery {

private $query;
private $searchParameters;
private $searchURL;
private $fetchParameters;
private $fetchURL;
private $searchResults;
private $fetchResults;
private $matches;
private $matchRegex;
private $emailAddresses;

public function __construct($query) {
    $this->query = $query;
}

public function setSearchParameters() {
    $this->searchParameters = array(
        'db'         => 'pubmed',
        'term'       => $this->query,
        'retmode'    => 'xml',
        'retstart'   => '0',
        'retmax'     => '1000',
        'usehistory' => 'y'
    );
}

public function getSearchParameters() {
    return $this->searchParameters;
}

public function setFetchParameters() {
    $this->fetchParameters = array(
        'db'        => 'pubmed',
        'retmax'    => '1000',
        'query_key' => (string) $this->searchResults->QueryKey,
        'WebEnv'    => (string) $this->searchResults->WebEnv
    );
}

public function getFetchParameters() {
    return $this->fetchParameters;
}

public function setSearchURL() {
    $this->baseSearchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?';
    $this->searchURL = $this->baseSearchURL . http_build_query($this->getSearchParameters());
}

public function getSearchURL() {
    return $this->searchURL;
}

public function setFetchURL() {
    $this->baseFetchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';
    $this->fetchURL = $this->baseFetchURL . http_build_query($this->getFetchParameters());
}

public function getFetchURL() {
    return $this->fetchURL;
}

public function setSearchResults() {
    $this->setSearchParameters();
    $this->setSearchURL();
    $this->searchResults = simplexml_load_file($this->getSearchURL());
}

public function getSearchResults() {
    $this->setFetchParameters();
    $this->setFetchURL();
    return file_get_contents($this->getFetchURL());
}

public function setEmailAddresses() {
    $this->matches = array();
    $this->matchRegex = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/';
    preg_match_all($this->matchRegex, $this->getSearchResults(), $this->matches);
    $this->emailAddresses = array_unique(array_values($this->matches[0]));
}

public function getEmailAddresses() {
    $this->setSearchResults();
    $this->getSearchResults();
    $this->setEmailAddresses();
    return $this->emailAddresses;
}
}

//Example using search term "psoriasis"
$query  = new PubMedQuery('psoriasis');
echo implode('<br />', $query->getEmailAddresses());

The first thing I might do is get rid of the email regex matching.  PHP has this awesome functionality called filter_var that will take care of a lot of cool things for you, like validating a string as an email address.  This is a better solution because you're less likely to get back false positives where the email is valid, but doesn't match the regex.

Next, I'm not sure I like the search/fetch parameters being set at various places throughout the code.  This feels like something that should be done in the constructor; setup all the data you need to complete the responsibility of the class in the constructor.  If you ever add a new method or make some changes you always have to keep in the back of your mind "Have I set $x yet?".  Well, do it in __construct() and you'll know you have.

Finally, I noticed you were calling some get* functions but not assigning the return value to any variable.  If you don't use the return value you don't need to use the get* function and if you don't use the get* function you don't need it in the class.

Overall I like the API, the method names are fairly self explanatory.  I'm not sure that they should all be public as your use case only has one method actually being used from calling code.  In addition, I might change the properties from private to protected for extensibility but that is certainly not mandatory and is as much a preference as anything else.  I would also prefer to see some kind of documentation, even if it is just the responsibility of the class and your though processes behind why you solved the problem this way.


Comparing strings, ignoring case, punctuation, and whitespace I have built a search function that will compare strings regardless of punctuation and whitespace. It is case insensitive.

Here is my current function:

var itemsToFilter = MPMediaQuery.songs().items!

func searchForItemsWithString(_ searchText: String) {
    if searchText != "" {
            let filteredItems = itemsToFilter.filter { item in
                let filterStr = item.title

                if filterStr == nil {
                    return false
                }

                let punctuation = CharacterSet.punctuationCharacters
                let whitespace = CharacterSet.whitespaces
                let unwanted = punctuation.union(whitespace)
                let filterStringContainsSearchText = filterStr!.components(separatedBy: unwanted).joined(separator: " ")

                return filterStringContainsSearchText.contains(searchText)
            }

    }
}

This works, but it is very slow. How can I optimise it?

What else can I improve?

You might want to create a combined CharacterSet of punctuation and whitespace first and then apply this set using a single operation. This should speed things up. Please have a look at this code snippet:

let punctuation = CharacterSet.punctuationCharacters
let whitespace = CharacterSet.whitespaces
let unwanted = punctuation.union(whitespace)
let components = filterString.components(separatedBy: unwanted).joined(" ")
let filterStringContainsSearchText = components.contains(searchText)


Connect Four game without diagonals check or validation This is a simple implementation of Connect four in Java. It is working correctly so far.
 What I haven't done yet are the diagonals check and input validation.

package game;

import java.util.Scanner;
//TODO check for diagonals, input validation

public class Game {
    private char[][] gameBoard;
    private State gameState;
    private Turn turn;
    private int[] possiblePositions;
    private static final int BOARD_HEIGHT = 6;
    private static final int BOARD_WIDTH = 7;

    enum Turn {
        PLAYER_ONE, PLAYER_TWO
    }

    enum State {
        PLAYER_1_WIN, PLAYER_2_WIN, RUNNING
    }

    public Game() {
        gameBoard = new char[BOARD_HEIGHT][BOARD_WIDTH];
        for (int row = 0; row < BOARD_HEIGHT; row++) {
            for (int col = 0; col < BOARD_WIDTH; col++) {
                gameBoard[row][col] = '□';
            }
        }
        turn = Turn.PLAYER_ONE;
        gameState = State.RUNNING;
        possiblePositions = new int[] { 5, 5, 5, 5, 5, 5, 5 };
    }

    public void playerMove(int column) {
        switch (turn) {
        case PLAYER_ONE:
            gameBoard[possiblePositions[column]][column] = '■';
            turn = Turn.PLAYER_TWO;
            break;
        case PLAYER_TWO:
            gameBoard[possiblePositions[column]][column] = '⊠';
            turn = Turn.PLAYER_ONE;
            break;
        }
        possiblePositions[column]--;
    }

    public void printBoard() {
        System.out.println("0 1 2 3 4 5 6");
        for (int row = 0; row < BOARD_HEIGHT; row++) {
            for (int col = 0; col < BOARD_WIDTH; col++) {
                System.out.print(gameBoard[row][col] + " ");
            }
            System.out.println();
        }
    }

    public void checkRowAndCol() {
        int chainLength = 1;
        for (int row = 0; row < BOARD_HEIGHT - 1; row++) {
            for (int col = 0; col < BOARD_WIDTH - 1; col++) {
                if (gameBoard[row][col] == gameBoard[row][col + 1] && gameBoard[row][col] != '□') {
                    ++chainLength;
                    if (chainLength == 4) {
                        switch (gameBoard[row][col]) {
                        case '■':
                            gameState = State.PLAYER_1_WIN;
                            break;
                        case '⊠':
                            gameState = State.PLAYER_2_WIN;
                            break;
                        }
                    }
                } else {
                    chainLength = 1;
                }
            }
            chainLength = 1;
        }

        for (int col = 0; col < BOARD_WIDTH - 1; col++) {
            for (int row = 0; row < BOARD_HEIGHT - 1; row++) {
                if (gameBoard[row][col] == gameBoard[row + 1][col] && gameBoard[row][col] != '□') {
                    ++chainLength;
                    if (chainLength == 4) {
                        switch (gameBoard[row][col]) {
                        case '■':
                            gameState = State.PLAYER_1_WIN;
                            break;
                        case '⊠':
                            gameState = State.PLAYER_2_WIN;
                            break;
                        }
                    }
                } else {
                    chainLength = 1;
                }
            }
            chainLength = 1;
        }
    }

    public void start() {
        Scanner reader = new Scanner(System.in);
        printBoard();
        while (gameState == State.RUNNING) {
            playerMove(reader.nextInt());
            checkRowAndCol();
            printBoard();
        }
        System.out.println(gameState);
        reader.close();
    }
}

Magic values

The implementation is mostly fine, except for the widespread magic values that would be better as constants, for example:

private static final char SYMBOL_EMPTY = '□';
private static final char SYMBOL_PLAYER1 = '■';
private static final char SYMBOL_PLAYER2 = '⊠';

Similarly, instead of initializing possiblePositions with new int[] { 5, 5, 5, 5, 5, 5, 5 }, it would be better to derive the correct value from the BOARD_WIDTH and BOARD_HEIGHT constants.

Code duplication

This snippet is duplicated in checkRowAndCol:

if (chainLength == 4) {
    switch (gameBoard[row][col]) {
        case '■':
            gameState = State.PLAYER_1_WIN;
            break;
        case '⊠':
            gameState = State.PLAYER_2_WIN;
            break;
    }
}

It would be better to move this to a helper method.

Unnecessary execution

When a player wins,
you could return immediately from checkRowAndCol,
no need to continue checking all rows and columns.

The helper method I mentioned in the previous section could return a boolean,
with a true value if there is a winner.
When the returned value is true,
the caller in checkRowAndCol could return immediately.

Code organization

Instead of checkRowAndCol, it would be better to separate to checkRow and checkCol methods.
You could still have a checkRowAndCol method that calls the other two,
but there's no reason for these two independent aspects to be implemented in the same method.


Read partial socket message I've written some code that is suppose to read socket all the time and when needed return the partial data from it. I just want the response to send a command. It works, but this is a bit messy implementation.

Is it possible to write it better?

public StringBuilder message = new StringBuilder();
private BufferedReader reader;
private Socket socket;
public boolean writing = true;
public boolean wantToRead = false;

public String getMessage() {
        synchronized (message) {
            while (writing) {
                try {
                    System.out.println("waiting");
                    wantToRead = true;
                    message.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("take the resource");
            writing = true;
            return message.toString().substring(0, message.toString().lastIndexOf("\n"));
        }
    }

@Override
    public void run() {
        int c;
        try {
            while((c = reader.read()) != -1) {
                synchronized(message) {
                    message.append(Character.toString((char) c));
                    if(!reader.ready()) {
                        System.out.println("end of response");
                        if(wantToRead) {
                            writing = false;
                            wantToRead = false;
                            message.notify();
                        }
                    }
                }
            }
            System.out.println("zamykam socket");
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

You are locking on a public field message which might cause a deadlock. If locking is needed, then do it on a private field.

private final Object SYNC_OBJECT = new Object();
...
synchronized(SYNC_OBJECT){
}

Your class extends Thread apparently, and the rule is : favor composition over inheritance.

  private Runnable runnable;

  public void startListening(){
    // use the runnable
  }

Moreover, you barely need to use threads, use Executors instead


Simple TCP Listener class This is my first winsock TCP listener ever written. I can use it for a small framework.

tcp_listener.h:

#pragma once
#include <WinSock2.h>
#include <thread>
class tcp_listener
{
public:
    tcp_listener(std::function< void(SOCKET) > callback);
    void start(unsigned short port);
private:
    SOCKET server;
    std::thread accept_thread;

    std::function< void(SOCKET) > callback;
};

tcp_listener.cpp:

#pragma comment(lib, "Ws2_32.lib")

#include "tcp_listener.h"
#include <iostream>
tcp_listener::tcp_listener(std::function< void(SOCKET) > callback)
{
    this->callback = callback;

    WSADATA wsa;

    if (WSAStartup(MAKEWORD(2, 2), &wsa) == SOCKET_ERROR)
    {
        std::cerr << "Cannot startup WSA: " << WSAGetLastError() << std::endl;
    }
    else
    {
        server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    }
}

void tcp_listener::start(unsigned short port)
{
    if (server != SOCKET_ERROR)
    {
        SOCKADDR_IN sock_addr;
        sock_addr.sin_port = htons(port);
        sock_addr.sin_family = AF_INET;
        sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);

        if (bind(server, (SOCKADDR*)&sock_addr, sizeof(sock_addr)) == SOCKET_ERROR)
        {
            std::cerr << "Cannot bind socket on port " << port << std::endl;
            return;
        }

        if (listen(server, 10) == SOCKET_ERROR)
        {
            std::cerr << "Cannot listen to socket." << std::endl;
            return;
        }

        accept_thread = std::thread([&]() {
            SOCKET client = SOCKET_ERROR;

            while (client == SOCKET_ERROR)
            {
                client = accept(server, NULL, NULL);

                if (client != SOCKET_ERROR)
                {
                    callback(client);

                    client = SOCKET_ERROR;
                }
            }
        });

        accept_thread.detach();
    }
    else
    {
        std::cerr << "Socket not set." << std::endl;
    }
}

How to use it:

#include <iostream>
#include "tcp_listener.h"

void on_accept(SOCKET client)
{
    std::cout << "blabla new connection" << std::endl;

}

int main()
{
    tcp_listener* listener = new tcp_listener(on_accept);
    listener->start(1232);

    getchar();

    return 1;
}

I still have to make a new class where the SOCKET is stored and the IP etc. like system.net.sockets.Socket and use that as callback.

Also I'd like to get a review on my naming convention.

Naming

I think you're naming convention is OK, it seems consistent which is the most important thing.  Some of your names could be a bit more specific:

std::function< void(SOCKET) > callback

callback doesn't tell me what the callback is for.  new_connection_callback might be more appropriate.

Shutdown

There's no obvious way to shutdown your server.  You just allow the object to be destroyed and hope for the best.  I'd usually add a shutdown to a class like this so that the listen thread can be shutdown cleanly.  The accept thread itself has a loop while (client == SOCKET_ERROR) which is a condition that is always true.  You may as well be saying while(1).

Startup

Since the class has no concept of state it doesn't know whether or not it's running.  This means you can't check if it's running when startup is called, so you get a strange error 'can't bind to socket' if you try to start the server on two different ports.  Usually you'd encounter this error if the port was already in use.  However, since the server port is an instance variable you get it because the SOCKET itself is already in use.

Constructor errors

This is a critical error:

if (WSAStartup(MAKEWORD(2, 2), &wsa) == SOCKET_ERROR)

If you can't get a socket, your application is in trouble.  Don't just write to the log, throw an exception so that the caller is aware that there has been a problem and they can stop processing.

Callbacks

It's often useful to pass an additional piece of data into a callback method (for example a pointer to an instance of a collection to add the new socket to).  With that in mind, I'd consider adding an extra parameter (usually a void*) to the callback.  You also might want to consider typedefing the callback to make it easier to update in one place (if you decide to in the future).

Something like:

typedef std::function<void(SOCKET)> accept_callback;

makes the function signatures more descriptive and concise:

tcp_listener(accept_callback callback);


Python program for "0-1 knapsack problem" Here is what a knapsack/rucksack problem means (taken from Wikipedia):

  Given a set of items, each with a weight and a value, determine the
  number of each item to include in a collection so that the total
  weight is less than or equal to a given limit and the total value is
  as large as possible. It derives its name from the problem faced by
  someone who is constrained by a fixed-size knapsack and must fill it
  with the most valuable items.

With reference to - https://en.wikipedia.org/wiki/Knapsack_problem - this is the definition of a 0-1 knapsack or a 0-1 rucksack problem:

Here is my version of the "0-1 knapsack problem" in python:

def knapsack(capacity, items, weights, values):

    grid = [[0] * (capacity + 1)]
    for item in range(items):
        grid.append(grid[item].copy())
        for k in range(weights[item], capacity + 1):
            grid[item + 1][k] = max(grid[item][k], grid[item][k -weights[item]] + values[item])

    solution_value = grid[items][capacity]
    solution_weight = 0
    taken = []
    k = capacity
    for item in range(items, 0, -1):
        if grid[item][k] != grid[item - 1][k]:
            taken.append(item - 1)
            k -= weights[item - 1]
            solution_weight += weights[item - 1]

    return solution_value, solution_weight, taken

NOTES - The total weight of the taken items cannot exceed the capacity of the knapsack. The total weight of the items in the knapsack is called “solution weight”, and their total value is the “solution value”.

Here are some example input values,

values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
items = len(values)

print(knapsack(capacity, items, weights, values))
print('knapsack() Time: ' + str(timeit.timeit('knapsack(capacity, items, weights, values)', setup = 'from __main__ import knapsack, capacity, items, weights, values')))

where my budget ($50) is the sack’s capacity, the shares are the items to be packed, the current prices are the weights and the price estimates are the values.

Here is an example output,

(220, 50, [2, 1])
knapsack() Time: 54.669268087000006

NOTE - knapsack() Time is in milliseconds.

So I would like to know whether I could make this code shorter and more efficient.

Any help would be highly appreciated.

The code is well written in terms of style and readability, there is only a few things we could improve there.

The algorithm is also optimal for runtime, but the memory usage/allocation could be improved a little which could speed things up.

Readability

Variable naming: some of the variables are not very descriptive:

grid which represents the dynamic-programming array, it needs a comment
either way but maybe best_value is better.
items usually means the actual array, since it represents the count, it's
better to name it items_count. Actually, this variable is not needed since
the function could use len(weights) or len(values)

You could use a named-tuple (or just tuple) to group the item weights and values.

Algorithm

You can reduce the 2d array to a 1d array saving the values for the current iteration. For this to work, we have to iterate capacity (inner for-loop)
in the opposite direction so we that we don't use the values that were updated in the same iteration (you can try the other way and see what goes wrong).

Incorporating these changes we get the following code:

from collections import namedtuple
from timeit import timeit

Item = namedtuple('Item', ['value', 'weight'])

def knapsack(capacity, items):
    # A DP array for the best-value that could be achieved for each weight.
    best_value = [0] * (capacity + 1)
    # The previous item used to achieve the best-value for each weight.
    previous_item = [None] * (capacity + 1)
    for item in items:
        for w in range(capacity, item.weight - 1, -1):
            value = best_value[w - item.weight] + item.value
            if value > best_value[w]:
                best_value[w] = value
                previous_item[w] = item

    cur_weight = capacity
    taken = []
    while cur_weight > 0:
        taken.append(previous_item[cur_weight])
        cur_weight -= previous_item[cur_weight].weight

    return best_value[capacity], taken

items = [Item(60, 10), Item(100, 20), Item(120, 30)]
capacity = 50

print(knapsack(capacity, items))
print('knapsack() Time: ' + str(
      timeit('knapsack(capacity, items)',
             setup = 'from __main__ import knapsack, capacity, items')))

This change resulted in a good improvement in runtime. On my machine, it decreased the execution time (1,000,000 iterations) from 37s to 24s.


.Net core string symmetric encryption I need to store sensitive strings in DB, so decided to encrypt it in a DB and decrypt it at the application layer. And noticed that it is not so easy to find ready to use an example.  Please check my code below. It is based on this damienbod's topic, but I included IV to the string itself and also want to know if it is production-ready. And a somewhat unrelated question: probably I should use an old Rijndael solution like this?
public class SymmetricEncryptDecrypt
{
    private const int ivBytes = 128;

    public (string Key, string IVBase64) InitSymmetricEncryptionKeyIV()
    {
        var key = GetEncodedRandomString(32); // 256
        using (Aes cipher = CreateCipher(key))
        {
            cipher.GenerateIV();
            var IVBase64 = Convert.ToBase64String(cipher.IV);
            return (key, IVBase64);
        }
    }

    private byte[] GetNewIv()
    {
        using (Aes cipher = CreateCipher(GetEncodedRandomString(32)))
        {
            cipher.GenerateIV();
            return cipher.IV;
        }
    }

    /// <summary>
    /// Encrypt using AES
    /// </summary>
    /// <param name="text">any text</param>
    /// <param name="IV">Base64 IV string/param>
    /// <param name="key">Base64 key</param>
    /// <returns>Returns an encrypted string</returns>
    public string Encrypt(string text, string key)
    {
        var iv = this.GetNewIv();

        using (Aes cipher = CreateCipher(key))
        {
            cipher.IV = iv;

            ICryptoTransform cryptTransform = cipher.CreateEncryptor();
            byte[] plaintext = Encoding.UTF8.GetBytes(text);
            byte[] cipherText = cryptTransform.TransformFinalBlock(plaintext, 0, plaintext.Length);

            return Convert.ToBase64String(iv.Concat(cipherText).ToArray());
        }
    }

    /// <summary>
    /// Decrypt using AES
    /// </summary>
    /// <param name="text">Base64 string for an AES encryption</param>
    /// <param name="key">Base64 key</param>
    /// <returns>Returns a string</returns>
    public string Decrypt(string encryptedText, string key)
    {
        var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(encryptedText);

        var ivStringBytes = cipherTextBytesWithSaltAndIv.Take(ivBytes / 8).ToArray();
        // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip(ivBytes / 8).Take(cipherTextBytesWithSaltAndIv.Length - (ivBytes / 8)).ToArray();

        using (Aes cipher = CreateCipher(key))
        {
            cipher.IV = ivStringBytes;

            ICryptoTransform cryptTransform = cipher.CreateDecryptor();
            byte[] plainBytes = cryptTransform.TransformFinalBlock(cipherTextBytes, 0, cipherTextBytes.Length);

            return Encoding.UTF8.GetString(plainBytes);
        }
    }

    private string GetEncodedRandomString(int length)
    {
        var base64 = Convert.ToBase64String(GenerateRandomBytes(length));
        return base64;
    }

    /// <summary>
    /// Create an AES Cipher using a base64 key
    /// </summary>
    /// <param name="key"></param>
    /// <returns>AES</returns>
    private Aes CreateCipher(string keyBase64)
    {
        // Default values: Keysize 256, Padding PKC27
        Aes cipher = Aes.Create();
        cipher.Mode = CipherMode.CBC; // Ensure the integrity of the ciphertext if using CBC
        cipher.Padding = PaddingMode.ISO10126;
        cipher.Key = Convert.FromBase64String(keyBase64);
        return cipher;
    }

    private byte[] GenerateRandomBytes(int length)
    {
        var byteArray = new byte[length];
        RandomNumberGenerator.Fill(byteArray);
        return byteArray;
    }
}

This code looks complicated for me. Not because I don't know how to use AES encrypter but it contains a lot of redundancy. From setting CipherMode.CBC which is default to GetNewIv() which is random by default.
Is a lot of code is targeting the a security improvement? If it is, you have a breach storing key in a string. I can easily get the key from App's memory even if it currently not in use because string is immutable and can be stored in memory for undefined period of time. Storing key in byte[] array allows to cleanup the array at any moment.
If security on DB side is enough then you may simplify the code as following two methods.
I use streams because it more friendly for me. As a bonus the code can be easily ported to streams use.
private static string Encrypt(string text, byte[] key)
{
    using AesManaged aes = new AesManaged() { Key = key };
    using MemoryStream ms = new MemoryStream();
    ms.Write(aes.IV);
    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))
    {
        cs.Write(Encoding.UTF8.GetBytes(text));
    }
    return Convert.ToBase64String(ms.ToArray());
}

private static string Decrypt(string base64, byte[] key)
{
    using MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64));
    byte[] iv = new byte[16];
    ms.Read(iv);
    using AesManaged aes = new AesManaged() { Key = key, IV = iv };
    using CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
    using MemoryStream output = new MemoryStream();
    cs.CopyTo(output);
    return Encoding.UTF8.GetString(output.ToArray());
}

Demo
string text = "Hello world";
byte[] key = Enumerable.Range(0, 32).Select(x => (byte)x).ToArray(); // just for example :)
string base64 = Encrypt(text, key);
Console.WriteLine(base64);
Console.WriteLine(Decrypt(base64, key));

Output
Qh+XfnIuIdgllOiKFgzCpTURW+bUuj91S91zA1przRQ=
Hello world

I think that's enough to keep it secure on DB side. Btw, you may keep the Key generator methods if you need it.
P.S. old Rijndael solution - Rijndael was superseded by Aes in .NET, i don't remember the exact reason but something like Rijndael has a padding issue and Aes fixed it.

One more tip. If you're on Windows and the encrypted data is allowed to be lost (in case of emergency), you can use DPAPI to protect the key (MS NuGet package exists, Current User/Local Machine protecting modes available) and store protected key in DB in the same sequence as IV. Then you can use totally random key for each Encrypt() call and store it with data. The data may be lost on Windows reinstall or moving the ASP.NET server to other machine, because DPAPI uses key associated with Current User credentials or Local Machine ID. But protected data can't be restored if DB was stolen or in any other way on other PC. Anyway learn how DPAPI works, it may be useful if the server runs under Windows.


Splitting a string in an SQL query BudgetCode is in the format 'xxxx-yyyyy-zzzzz'. This splits it correctly but I think that there has to be a more efficient way.

Select
       substring(pc.BudgetCode,1, CHARINDEX('-',pc.BudgetCode)-1) as Cost_Center,
       substring(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)),1, CHARINDEX('-',Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))-1) as Account_Code,
       Substring(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)),Charindex('-',Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))+1,len(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))) as Slid_Code
from pc

Hmm... Not sure how much faster this will be, but it may be easier to wrap your head around.
You can use a recursive CTE:

WITH Splitter (id, start, e, section, original, num) as (
               SELECT id, 1, CHARINDEX('-', budgetCode), CAST('' AS VARCHAR(20)), budgetCode, 0
               FROM PC
               UNION ALL
               SELECT id, e + 1,
                      CASE WHEN CHARINDEX('-', original, e + 1) > 0
                           THEN CHARINDEX('-', original, e + 1)
                           ELSE LEN(original) + 1 END,
                      SUBSTRING(original, start, e - start),
                      original, num + 1
               FROM Splitter
               WHERE e > start)

Results:

SELECT *
FROM splitter

Makes a table that looks like this:

Id  BudgetCode
=====================
1   xxxx-yyyyy-zzzzz

Into this:

Id  Start  End   Section   Original           Num
1   1      5               xxxx-yyyyy-zzzzz   0
1   6      11     xxxx      xxxx-yyyyy-zzzzz   1
1   12     17    yyyyy     xxxx-yyyyy-zzzzz   2
1   18     17    zzzzz     xxxx-yyyyy-zzzzz   3

SQL Fiddle Example

You can then join to the result set multiple times based on Num or something to get the particular index you need.  It'll automatically handle any additional 'subfields' (to the limit of the recursion, of course).


CSS3 Animated Loader I am fairly new to HTML and CSS and have been trying to make things with whatever knowledge I have. I created a 'loader', but I'm certain that I have done things in ways more complicated than they need to be. Is there an easier solution to centering my elements? Is there an easier solution to add a bounce class to all three elements? How can I simplify my code?

body{
  background: #0BCCCA;
}
.cont {
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px;
}

.element, .elem-1, .elem-2, .bounce, .bounce-2, .bounce-3 {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 50%;
  left: 50%;
  opacity: .6;
  background-color: #ffffff;
  border-radius: 50%;
  animation: big 2s infinite ease-in-out;
}
.elem-1, .bounce-2 {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 6%;
  left: 80%;
  background-color: #fff;
}
.elem-2, .bounce-3 {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 6%;
  left: 20%;
  background-color: #fff;
}
.elem-1{
  animation-delay: -0.5s;
}
.elem-2{
  animation-delay: -.75s;
}
.bounce{
  animation-delay: -1s;
}
.bounce-2{
  animation-delay: -1.5s;
}
.bounce-3{
  animation-delay: -1.75s;
}

@keyframes big {
  0%, 100%{transform: scale(0.0)}
  50% {transform: scale(1.75)}
}
<!DOCTYPE html>

I've looked at different works and read articles, but because I haven't practiced much, I find it difficult implementing what I learn into my code. This is one of my first completed code, which almost all of I have done myself, without looking at other people's work or reading articles for help. I want you to evaluate the code and suggest areas of improvement, specifically where the code might be overcomplicated.

There can be three ways to enhance this code, it mostly depends what you aim to create.

Very flexible HTML and CSS,
Flexible CSS, less flexible HTML,
Minimal HTML, CSS and class names (as a result minimum flexibility).

Minor change summary

CSS cleanup,
CSS animation  -  to make it more readable,
Class names - to make the logic evident,
HTML- to make it modular and reusable,

CSS cleanup

.element, .elem-1, .elem-2, .bounce, .bounce-2, .bounce-3 {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 50%;
    left: 50%;
    opacity: .6;
    background-color: #ffffff;
    border-radius: 50%;
    animation: big 2s infinite ease-in-out;
}
.elem-1, .bounce-2 {
    position: absolute; /*Already has position attribute*/
    width: 20px; /*Already has width attribute*/
    height: 20px; /*Already has height attribute*/
    top: 6%;
    left: 80%;
    background-color: #fff; /*Already has background-color attribute*/
}
.elem-2, .bounce-3 {
    position: absolute; /*Already has position attribute*/
    width: 20px; /*Already has width attribute*/
    height: 20px; /*Already has height attribute*/
    top: 6%;
    left: 20%;
    background-color: #fff; /*Already has background-color attribute*/
}
.elem-1{
    animation-delay: -0.5s;
}
.elem-2{
    animation-delay: -.75s;
}
.bounce{
    animation-delay: -1s;
}
.bounce-2{
    animation-delay: -1.5s;
}
.bounce-3{
    animation-delay: -1.75s;
}

@keyframes big {
    0%, 100%{transform: scale(0.0)}
    50% {transform: scale(1.75)}
}

CSS animation

Instead of

@keyframes big {
    0%, 100%{transform: scale(0.0)}
    50% {transform: scale(1.75)}
}

can be used

@keyframes big {
    0% { transform: scale(0);}
    100% {transform: scale(1);}
}

There is animation-direction which can have alternate value, this reverses the animation and gets the back effect this means there is no need for 50% key-frame, as one way animation can be altered beck.

Also when you use transform: scale() with greater than 1 value can cause element blurring in some browsers. to avoid this issue I multiplicated  20px height and width of the element with 1.75 and put 35px instead in order to use scale(1) instead of scale(1.75).

Classnames - to make the logic evident

As element, elem-1, elem-2, bounce, bounce-1, bounce-2 class names can be misleading. The meaning of these 6 classes is the animation states of each circle. in this case they can be bounceIn and bounceOut states and these states can be given to any element (in this case to any circle).
Also each circle has its own position and that's why I have created  pos-0,pos-1,pos-2 classes.

Centering

For centering elements there are many methods, the one that you used is a classic way and can be fully legitimate for this case (it will work even on IE6).

.cont {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
}

HTML

Instead of

Can be used

Or

Or

Which are much more readable and maintainable.

Solution 1: Very flexible HTML and CSS

You can add separate bouncing circles with different positions and different delays, or reuse same classes. or you can add 3-rd effect too (e.g. bounceIn, bounceOut, bounceLeft... etc.)

body {background: #0BCCCA;}

.cont {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
}

.circle {position: absolute;}

.pos-0 {
    top: 50%;
    left: 50%;
}
.pos-1 {
    top: 6%;
    left: 80%;
}
.pos-2 {
    top: 6%;
    left: 20%;
}

.bounceIn, .bounceOut {
    position: absolute;
    width: 35px;
    height: 35px;
    background-color: rgba(255, 255, 255, .6);
    border-radius: 50%;
    transform-origin: center center;
    animation: ease-in-out 1s infinite big alternate;
}

.bounceIn {animation-delay: 1000ms;}

.delay-0 .bounceIn {animation-delay: .75s;}
.delay-0 .bounceOut {animation-delay: -1.75s;}

.delay-1 .bounceIn {animation-delay: -0.5s;}
.delay-1 .bounceOut {animation-delay: -1.5s;}

.delay-2 .bounceIn {animation-delay: 0s;}
.delay-2 .bounceOut {animation-delay: -1s;}

@keyframes big {
    0% {transform: scale(0);}
    100% {transform: scale(1);}
}

Solution 2: Flexible CSS, less flexible HTML

This solution uses only :before and :after instead of bounceIn and bounceOut classes to minimize HTML.

body {background: #0BCCCA;}

.cont {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
}

.circle {position: absolute;}

.pos-0 {
    top: 50%;
    left: 50%;
}
.pos-1 {
    top: 6%;
    left: 80%;
}
.pos-2 {
    top: 6%;
    left: 20%;
}

.circle:after, .circle:before {
    content: '';
    position: absolute;
    width: 35px;
    height: 35px;
    background-color: rgba(255, 255, 255, .6);
    border-radius: 50%;
    transform-origin: center center;
    animation: ease-in-out 1s infinite big alternate;
}

.circle:after {animation-delay: 1000ms;}

.delay-0.circle:after {animation-delay: .75s;}
.delay-0.circle:before {animation-delay: -1.75s;}

.delay-1.circle:after {animation-delay: -0.5s;}
.delay-1.circle:before {animation-delay: -1.5s;}

.delay-2.circle:after {animation-delay: 0s;}
.delay-2.circle:before {animation-delay: -1s;}

@keyframes big {
    0% {transform: scale(0);}
    100% {transform: scale(1);}
}

Solution 3: Minimal HTML, CSS and class names

In addition to Solution 2 this one adds all necessary styles to one class.

body {
  background: #0BCCCA;
}

.cont {
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px;
}

.circle-0,
.circle-1,
.circle-2{
  position: absolute;
}

.circle-0{
  top: 50%;
  left: 50%;
}

.circle-1{
  top: 6%;
  left: 80%;
}

.circle-2{
  top: 6%;
  left: 20%;
}

.circle-0:after,
.circle-0:before,
.circle-1:after,
.circle-1:before,
.circle-2:after,
.circle-2:before{
  content:'';
  position: absolute;
  width: 35px;
  height: 35px;
  background-color: rgba(255,255,255, .6);
  border-radius: 50%;
  transform-origin: center center;
  animation: ease-in-out 1s infinite big alternate;
}

.circle-0:after,
.circle-1:after,
.circle-2:after{animation-delay: 1000ms;}

.circle-0:after{animation-delay: .75s;}
.circle-0:before{ animation-delay: -1.75s;}

.circle-1:after{animation-delay: -0.5s;}
.circle-1:before{animation-delay: -1.5s;}

.circle-2:after{animation-delay: 0s;}
.circle-2:before{animation-delay: -1s;}

@keyframes big {
  0% { transform: scale(0); }
  100% { transform: scale(1);}
}


Handling XPATH input from a user I want to design API which could handle XPATH input from a user. I currently model the XPATH input in the following way:

public interface ICondition {
    String getConditionString();
}

public class XPathCondition implements ICondition {

    private Class<? extends XPATHFunction> clazz = null;

    private Operator operator = null;

    private String compValue = null;

    private String param = null;

    public void setXPathFunction(Class<? extends XPATHFunction> clazz) {
        this.clazz = clazz;
    }

    public void setComparisionType(Operator operator) {
        this.operator = operator;
    }

    public void setComparisionValue(String value) {
        this.compValue = value;
    }

    public void setParam(String param) {
        this.param = param;
    }

    public String getConditionString() {
        XPATHFunction function = null;
        try {
            function = (XPATHFunction) clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return function.call(param) + operator.getOprValue() + compValue;
    }

    public static void main(String[] args) {
        XPathCondition xpathCond = new XPathCondition();
        xpathCond.setXPathFunction(CountFunction.class);
        xpathCond.setParam("/CPRRegistrationInfo/*");
        xpathCond.setComparisionType(Operator.GT);
        xpathCond.setComparisionValue("0");
        System.out.println(xpathCond.getConditionString());
    }
}

public interface XPATHFunction {

    public String call(String param);

}

public class CountFunction implements XPATHFunction {

    public String call(String param) {
        return "count(" + param + ") ";
    }

}

There could be other XPATH functions which have to implement and interface XPATHFunction and implement it in its way. The API just has to create XPATHCondition and set appropriate functions and call the getConditionString() method to get the final xpath.

Is there any better way in which I can model XPATH input?

Can I ask why you're trying to do this? If this is homework or a way to "practice Java/Object-Oriented programming", please say so. If it's a real question, the best way to represent XPath input is actually a string. XPath is way more complicated than what you've (XPath 2.0 even more so), and you would need a lot of more work to model this properly. If it's a subset of XPAth, then what subset?

Edit: A few examples.

Valid XPath expressions:

ancestor-or-self::*
../employee[@secretary and @assistant]
substring("12345", 1.5, 2.6)
child::para[position()=5][attribute::type="warning"]

Valid XPath 2.0 expressions:

($x div $y) + xs:decimal($z)
fn:error(xs:QName("app:err057"), "Unexpected value", fn:string($v))

Also note that you can evaluate XPath expressions using the standard javax.xml.xpath, thus not needing rolling your own. If you need something else, maybe reuse the source code of javax.xml.xpath to suit your needs?


Number to vector of its digits There is a function that returns digits as vector of given number. Is it idiomatic way to solve this problem in Rust? Can you suggest more concise solution?

#[allow(dead_code)]
fn num_digits(num: i32) -> Vec<i32> {
    let mut x = num;
    let mut result: Vec<i32> = Vec::new();

    loop {
        result.push(x % 10);
        x /= 10;
        if x == 0 {break}
    }

    result.reverse();
    result
}

#[test]
fn digits() {
    assert_eq!(num_digits(0), [0]);
    assert_eq!(num_digits(-1), [-1]);
    assert_eq!(num_digits(-123), [-1, -2, -3]);
    assert_eq!(num_digits(1), [1]);
    assert_eq!(num_digits(12), [1, 2]);
    assert_eq!(num_digits(456464), [4, 5, 6, 4, 6, 4]);
}

I would call this "more idiomatic" but I'm still not satisfied with it. Rust uses Iterators in a lot of ways, e.g. look at this implementation:

pub fn num_digits(num: i32) -> Vec<i32> {
    let mul = if num < 0 { -1 } else { 1 };
    num.to_string()
        .chars()
        .filter_map(|x| x.to_digit(10))
        .map(|x| (x as i32) * mul)
        .collect()
}

The mul variable is just for determining if you want negative or positive numbers.

Because i32 implements the Display trait you can call to_string on it, which will give you a String representation of the i32.
Next is just iterating of the characters of the String and trying to convert them to a digit. - will be ignored, because it is not a digit and filter_map will filter all Results, that will return a Err. The next thing is to convert the numbers to a i32 (because to_digit gives an u32) and either making them negative if the original number was negative or staying positive.

collect will put all the numbers into a collection, in this case a Vec because the type can be deduced by Rust (because of the return type)


Fast import of numbers stored in a CSV file I would like to efficiently import real numbers stored in CSV format into an array.  Is there a way to modify my code to make it faster?  Also, is there a way to scan the file and compute the number of rows and columns rather than having to provide these directly?

double * getcsv(string fname, int m, int n){
    double *a;
    a = (double *)malloc(n * m * sizeof(double));

    ifstream fs(fname.c_str());
    char buf[100];

    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            if (j < (n-1) ){
                fs.getline(buf,100,',');}
            else{
                fs.getline(buf,100);}
            stringstream data(buf);
            data>>a[(i*n)+j];

         }
     }

     return(a);
}

In C++, we usually avoid malloc - in this case, you could use a std::vector< double > in stead. Doing this, you will allow the user of your code to use RAII in stead of manually managing the allocated memory. You cal tell the vector how much to allocate by initializing it with the right size. The compiler will apply return value optimization to avoid copying the vector (by constructing it into the return value) so you shouldn't worry too much about that.
You don't preserve the values of m and n. I don't know if this is intentional but if you don't want to burden your client code with lugging it around, consider a struct or a class to carry it, and the values you read, around.
You don't check the return values of the methods you call on the fstream - you should.
You'd probably be better off reading the values from the fstream directly into the array, rather than reading them into a buffer, copying that buffer into a stringstream and then reading them from the stringstream to convert. You can save the use of the stringstream (and therefore eliminate it altogether).

Example program:

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

using namespace std;

struct Data
{
        Data(unsigned int width, unsigned int height)
                : width_(width)
                , height_(height)
                , data_(width * height)
        { /* no-op */ }
        unsigned int width_;
        unsigned int height_;
        vector< double > data_;
};

Data split(istream &is, unsigned int width, unsigned int height)
{
        Data retval(width, height);
        double d;
        int i(0);

        while (is >> d)
        {
                retval.data_[i++] = d;
                is.ignore(1, ',');
        }

        return retval;
}

int main()
{
        const char *test_string = ""
                "2.83, 31.26, 2354.3262, 0.83567\n"
                "12.3, 35.236, 2854.3262, 0.83557\n"
                "32.3, 33.26, 2564.3262, 0.83357\n"
                "27.3, 3.2869, 2594.3262, 0.82357\n";
        const unsigned int width = 4;
        const unsigned int height = 4;
        stringstream ss(test_string);
        Data data(split(ss, width, height));
        copy(data.data_.begin(), data.data_.end(), ostream_iterator< double >(cout, " "));
}


makefile dependency generation I need automatic dependency generation to be done in my makefile. So, I have tried to write one, after googling for similar ones. I have found some ways to do that, but the problem is that they are usually too complicated for me (because of usage of sed command etc. and I want a way for me to create a makefile without the need of refering to some other makefile).

Below is a makefile I hope should do the same job i.e. automatically find out all the dependencies of the object files and build them. Could you please review this makefile and point out cases where the build may fail when it should not have?

Gpp=g++
srcs=$(wildcard *.cpp)
objs=$(srcs:.cpp=.o)
deps=$(srcs:.cpp=.d)

default:test

%.o:%.d
    $(Gpp) -c $*.cpp

%.d:%.cpp
    echo -n "$*.d ">$*.d
    $(Gpp) -MM $*.cpp>>$*.d

test: $(objs)
    $(Gpp) $^ -o $@

-include $(deps)

.PHONY:clean default

clean:
    -rm -rf *.o test *.d

One place where the makefile fails is when for example a.cpp initially included a1.h but it has been updated to exclude a1.h and a1.h file has been deleted from file-system. So, except that is there any place that this makefile fails?

Not to be too blunt; but, you're going about this the wrong way. Look into the command line option -MMD for GCC, specify it when compiling your source; and, retain the inclusion statement for dependencies.

Also, no need for a default target. The first target is the default target.

An example:

Gpp = g++
srcs = $(wildcard *.cpp)
objs = $(srcs:.cpp=.o)
deps = $(srcs:.cpp=.d)

test: $(objs)
    $(Gpp) $^ -o $@

%.o: %.cpp
    $(Gpp) -MMD -MP -c $< -o $@

.PHONY: clean

# $(RM) is rm -f by default
clean:
    $(RM) $(objs) $(deps) test

-include $(deps)


Database layer class I'm trying to get familiar with database handling.  Can you point out my errors and what I should change?

I want to learn new methods, but just don't want to learn it the wrong way.

I do realize these things below, yet I wanted to make the code more clear:

I need to bind values for insert()
Use try/catch for error handling
Password hashing (did not use it to make example simpler)

<?php

class Query
{
    private $_sql;
    private $_sth;
    private $_db;

    public function __construct()
    {
        $this->_db = new PDO('mysql:host=localhost;dbname=mvc;', 'root', '');
        $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->_db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    }

    public function select($arg)
    {
        $this->_sql .= "SELECT {$arg}";
        return $this;
    }

    public function from($arg)
    {
        $this->_sql .= " FROM {$arg}";
        return $this;
    }

    public function insert($arg)
    {
        $this->_sql .= "INSERT INTO {$arg}";
        return $this;
    }

    public function columns($arg)
    {
        $this->_sql .= " ({$arg})";
        return $this;
    }

    public function values($arg)
    {
        $this->_sql .= " VALUES ({$arg})";
        return $this;
    }

    public function execute($data = null)
    {
        $this->_sth = $this->_db->prepare($this->_sql);
        $this->_sth->execute($data);
        $this->_sql = null;
        return $this;
    }

    public function fetch()
    {
        return $this->_sth->fetchAll();
    }

    public function getSql()
    {
        return $this->_sql;
    }
}

$query = new Query;

// inserts into database
$query->insert('users')
        ->columns('`username`,`password`')
        ->values('"test","tester"')
        ->execute();

// returns array of users
$query->select('username')
        ->from('users')
        ->execute()
        ->fetch()

?>

Passwords as plain text!?
If I were using an application or website that stored my password as plain text where anyone with access to the DB seeing this would make me feel very scared:
// inserts into database
$query->insert('users')
        ->columns('`username`,`password`')
        ->values('"test","tester"')
        ->execute();

For the love of your users, please consider password hashing!

Password hashing is one of the most basic security considerations that must be made when designing any application that accepts passwords from users. Without hashing, any passwords that are stored in your application's database can be stolen if the database is compromised, and then immediately used to compromise not only your application, but also the accounts of your users on other services, if they do not use unique passwords.

Redundancy
This:
public function insert($arg)
{
    $this->_sql .= "INSERT INTO {$arg}";
    return $this;
}

public function columns($arg)
{
    $this->_sql .= " ({$arg})";
    return $this;
}

public function values($arg)
{
    $this->_sql .= " VALUES ({$arg})";
    return $this;
}

And this:
// inserts into database
$query->insert('users')
        ->columns('`username`,`password`')
        ->values('"test","tester"')
        ->execute();

That seems redundant, unless you plan on inserting user names and passwords in different tables/columns. Why not shorten it like this:
public function insert($arg)
{
    $this->_sql .= "INSERT INTO users (`username`, `password`) VALUES ({$arg})";
    return $this;
}


Creating nxm index list of array a Here is the problem:

Given a numpy array 'a' that contains n elements, denote by b the set
of its unique values in ascending order, denote by m the size of
array b. You need to create a numpy array with dimensions  n×m , in
each row of which there must be a value of 1 in case it is equal to
the value of the given index of array b, in other places it must be 0.

import numpy as np

def convert(a):
    b = np.unique(sorted(a))
    result = []
    for i in a:
        result.append((b == i) * 1)
    return np.array(result)

a = np.array([1, 1, 2, 3, 2, 4, 5, 2, 3, 4, 5, 1, 1])
b = np.unique(sorted(a))
print(convert(a))

This is my solution. is there some improvments that I can make?
I'm not sure about declaring regular list to the result and then converting it into np.array.

Remove sorted
From the docs: numpy.unique returns the sorted unique elements of an array.
You can simply remove the call to sorted:
b = np.unique(sorted(a))

# produces the same result as

b = np.unique(a)

List comprehension
In most cases you can and should avoid this pattern of list creation:
result = []
for i in a:
    result.append((b == i) * 1)

It can be replaced by a concise list comprehension and directly passed to np.array:
result = np.array([(b == i) * 1 for i in a])

# or directly return it (if applicable)
return np.array([(b == i) * 1 for i in a])

List comprehensions are more pythonic and often faster. Generally, not mutating the list object is also less error-prone.

There might be a better way to map lambda x: (uniques == x) * 1 over the input array a. Here's a discussion on the topic on StackOverflow: Most efficient way to map function over numpy array. Seems like using np.vectorize should be avoided for performance reasons.
Using map might be similiar to the list comprehension performance-wise (I did not properly test performance here):
def convert_listcomp(a):
    uniques = np.unique(a)
    return np.array([(b == i) * 1 for i in a])

def convert_map(a):
    uniques = np.unique(a)
    return np.array(list(map(lambda x: (uniques == x) * 1, a)))


C++ object pool that returns a smart pointer on request template<typename T>
class object_pool {

public:
  explicit object_pool(std::size_t initial_size = 1048u);

  object_pool(const object_pool&) = delete;

  object_pool(object_pool&&) = delete;

  ~object_pool();

  object_pool& operator=(const object_pool&) = delete;
  object_pool& operator=(object_pool&&) = delete;

  template<typename... Args>
  std::unique_ptr<T, std::function<void(T*)>> request(Args&&... args);

private:
  std::deque<T*> _object_pool; // is deque the best container?

};

template<typename T>
object_pool<T>::object_pool(std::size_t initial_size) : _object_pool() {
  for (std::size_t i = 0; i < initial_size; ++i) {
    T* object = reinterpret_cast<T*>(::operator new(sizeof(T)));
    _object_pool.push_back(object);
  }
}

template<typename T>
object_pool<T>::~object_pool() {
  while (!_object_pool.empty()) {
    T* object = _object_pool.front();
    _object_pool.pop_front();
    ::operator delete(object);
  }
}

template<typename T>
template<typename... Args>
std::unique_ptr<T, std::function<void(T*)>> object_pool<T>::request(Args&&... args) {
  T* object = nullptr;

  if (!_object_pool.empty()) {
    object = new(_object_pool.front()) T(std::forward<Args>(args)...);
    _object_pool.pop_front();
  } else {
    object = new T(std::forward<Args>(args)...);
  }

  auto object_pointer = std::unique_ptr<T, std::function<void(T*)>>(object, [this](T* object){
    object->~T();
    _object_pool.push_back(object);
  });

  return object_pointer;
}

My goal is to write a very lightweight object pool for another project.
The _object_pool is supposed to just hold raw uninitialized pointers to T, which I then initialize when an object is requested. Likewise, i call the destructor on the returned instances before putting them back into the _object_pool so that resources used by them can be freed.
I am also allocating space for a set ammount of instances when I create the pool and only request new memory when all object from the _object_pool are in use.

unique_ptr ownership / lifetime issues:
Normally, std::unique_ptr indicates single ownership of an object and thus gives the user certain expectations of how they can safely use it. But here the object_pool "owns" the object (or at least the underlying memory), so the use of unique_ptr is rather misleading. Consider the following code:
{
    auto ptr = std::unique_ptr<int, std::function<void(int*)>>();

    {
        object_pool<int> pool;
        ptr = pool.request(5);
    }

    // uh oh...
}

We would normally expect the above code to work without problems. However, the custom unique_ptr deleter will attempt to call _object_pool.push_back(object) on a pool that doesn't exist any more.
At the very least, I'd suggest "hiding" the use of unique_ptr behind a typedef, and documenting thoroughly that it must go out of scope before the object pool:
template<class T>
using object_pool_ptr = std::unique_ptr<T, std::function<void(T*)>>;

This also means the user doesn't have to worry about typing out the custom deleter signature.
It would be even better to make object_pool_ptr a wrapper class around the unique_ptr to hide it completely.

object_pool destructor:
As a debugging feature, the object_pool could keep track of the total number of objects allocated. We could then check that our "free list" (the _object_pool deque) is the correct size in the object_pool destructor, rather than waiting until a pointer goes out of scope.
I don't think it's necessary to call pop_front() on individual elements in the destructor. We could call clear() after the loop, or allow the _object_pool to clean up naturally in its own destructor.

[Note: below this point are just possible things that might be useful, depending on what other features your object pool needs, and what you're actually using it for].

tracking allocated memory inside the pool:
This "object pool is a free-list" strategy is really clever... but maybe there are advantages to keeping track of all the allocated memory inside the object pool too?
We could use a std::deque<std::aligned_storage_t<sizeof(T)>> member variable allowing us to call push_back to add more elements without invalidating references (and hence pointers) to the original elements.
This also means we avoid the need to call global operators new and delete for every element.

manual lifetime (but not memory) management:
If the object pool keeps track of all allocated memory as above, perhaps it's ok to give the user a simple raw pointer to an allocated object and expect them to call an object_pool.destroy(ptr); function when they're done with it?
This isn't dangerous in terms of object lifetimes, since the object pool can still call the object destructors when necessary (and maybe issue a warning or assert() if desired). Although it would open up the possibility of pointers to destroyed objects being accidentally reused.
It also allows us to make the object_pool moveable, and add a clear() function.


115 line brainfuck interpreter written in C++ This is a simple brainfuck interpreter I've written in C++. It takes a path to a brainfuck source file as a command line argument. The program uses a tape size of 30000 and cell size of one byte. Decrementing a cell's value under 0 will wrap it to 255 and vice versa.

I would really appreciate any kind of feedback, especially on how the existing code could be improved.

I'm using Apple Clang/LLVM and I've been compiling with the command:

clang++ -pedantic -O3 -std=c++17 brainfuck.cpp -o brainfuck

brainfuck.cpp:

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

/* Read the source file into a char vector, and return the vector. */
std::vector<char> read_source(std::string&& file_path)
{
    std::ifstream file(file_path);

    std::vector<char> source;

    char c;
    while (file.get(c)) {
        source.push_back(c);
    }

    return source;
}

/* Remove all but chars, which don't have meaning in brainfuck, from the source file.
 * This removes whitespace, newlines and comment chars. */
void filter_chars(std::vector<char>& source)
{
    auto new_end = std::remove_if(source.begin(), source.end(),
                                  [](char c) { return !std::strchr("<>+-[],.", c); });

    source.erase(new_end, source.end());
}

/* The actual interpreter. Goes through the source char by char and
 * acts according to brainfuck's rules. */
void interpret(std::vector<char>& source)
{
    std::vector<unsigned char> tape(30000, 0);
    int h = 0;  // the tape head

    int brace_count = 0;  // keeps track of nested braces

    int i = 0;  // the index to read the source
    while (i < source.size()) {
        switch (source[i]) {
            case '<':
                --h;
                break;
            case '>':
                ++h;
                break;
            case '+':
                ++tape[h];
                break;
            case '-':
                --tape[h];
                break;
            case '.':
                std::cout << tape[h] << std::flush;
                break;
            case ',':
                std::cin >> tape[h];
                break;

            case '[':
                if (tape[h] == 0) {
                    ++brace_count;
                    while (source[i] != ']' || brace_count != 0) {
                        ++i;
                        if (source[i] == '[') {
                            ++brace_count;
                        }
                        else if (source[i] == ']') {
                            --brace_count;
                        }
                    }
                }
                break;

            case ']':
                if (tape[h] != 0) {
                    ++brace_count;
                    while (source[i] != '[' || brace_count != 0) {
                        --i;
                        if (source[i] == ']') {
                            ++brace_count;
                        }
                        else if (source[i] == '[') {
                            --brace_count;
                        }
                    }
                }
                break;

        }
        ++i;
    }
}

int main(int argc, char* argv[])
{
    if (argc > 1) {
        std::vector<char> source = read_source(argv[1]);
        filter_chars(source);
        interpret(source);
        return 0;
    }
    else {
        std::cout << "Expected a brainfuck source file as a command line argument.\n";
        std::cout << "Terminating the program." << std::endl;
        return 1;
    }
}

I see some things that may help you improve your program.

Use all of the required #includes

The function std::strchr is used but its declaration is in #include <cstring> which is not actually in the list of includes.

Be careful with signed and unsigned

In the interpret routine, the code compares an int i to a size_t (because that's what is returned from source.size()) but size_t is unsigned and int is signed.  Instead, declare i as size_t.

Copy and filter in one step

It's not wrong, by any means, but I'd be inclined to copy and filter all at once rather than as two separate steps.  Here's one way to do that:

std::vector<char> source;
std::copy_if(std::istream_iterator<char>(std::cin), std::istream_iterator<char>(),
             std::back_inserter(source),
             [](char c) { return std::strchr("<>+-[],.", c); }
            );

It's not critical, of course, but this way it minimizes the number of times the vector is resized.  Also note that I've altered the program to read from std::cin instead of a file.  This way, it's possible to take input from a unnamed pipe, for example, adding to the flexibility of the program.

Fix the bugs

The current implementation doesn't check to see if it runs off the end of the vector while processing a brace and it doesn't check to see that h doesn't go out of bounds.


Ring Timer Animation with Chasing Tail using CoreAnimation After a fair amount of trial and error, I have gotten the animation acting in the manner that I want it, as seen here. However, I always feel like I'm writing way too much and too sloppily when trying to use Core Animation.

The animation is as follows:

The view begins with a point of light at the top of the loop.
When the user initiates the timer, the glowing line takes the prescribed amount of time to fill the loop.
When complete, the loop stays lit until acknowledged by the user.
When acknowledged, the tail of the glowing line chases the head and returns to being a single point at the top of the screen.
Repeat

The code controlling the animation is all wrapped in a subclass of UIView:

class LoopView: UIView {
  //  ...

  lazy var path: UIBezierPath = initializedPath()
  lazy var animationLayer: CAShapeLayer = initializedAnimationLayer()

  override func draw(_ rect: CGRect) {
    layer.addSublayer(animationLayer)
    //  ...
  }

  //  ...
}

Here are the path and animation layer initializations:

  private func intializedPath() -> UIBezierPath {
    return UIBezierPath(ovalIn: bounds)
  }

  private func initializedAnimationLayer() -> CAShapeLayer {
    let layer = CAShapeLayer()
    let transform = CGAffineTransform(rotationAngle: 1.5 * CGFloat.pi).translatedBy(x: -bounds.width, y: 0)

    layer.path = path.cgPath
    layer.setAffineTransform(transform)

    layer.strokeColor = timerColor.cgColor
    layer.fillColor = UIColor.clear.cgColor
    layer.lineCap = kCALineCapRound
    layer.lineWidth = lineWidth

    layer.shadowColor = timerColor.cgColor
    layer.shadowRadius = 5.0
    layer.shadowOpacity = 1
    layer.shadowOffset = CGSize(width: 0, height: 0)

    layer.strokeEnd = CGFloat.leastNormalMagnitude

    return layer
  }

And finally, the meat of the animation:

func animateTimer(over duration: TimeInterval) {
    let head = CABasicAnimation(keyPath: "strokeEnd")
    head.fromValue = CGFloat.leastNormalMagnitude
    head.toValue = 1
    head.duration = duration
    head.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    head.fillMode = kCAFillModeForwards
    head.isRemovedOnCompletion = false

    animationLayer.add(head, forKey: "strokeEnd")
}

func animateTimerReset() {
    UIView.animate(withDuration: 0, animations: { self.animationLayer.strokeStart = 1 }) { (_) in
        self.animationLayer = self.initializedAnimationLayer()
        self.layer.addSublayer(self.animationLayer)
    }
}

Where I spent the most time on figuring it out was that I didn't want to discard the animationLayer every time I wanted to reset the animation. I also had to use different methods of defining the animation for the fill and the collapse, which feels wrong, but trying to use the same strategies wasn't getting the results I wanted.

For reference, the full class code is in this gist

There is one problem with your approach: Additional sublayers are added
in draw() and in animateTimerReset() and never removed. That can
cause memory problems and slower drawing eventually.

I would suggest to create and add only a single instance of the animation layer, this can for example be done in

override func awakeFromNib() {
    layer.addSublayer(animationLayer)
}

Then animate this single animation layer:

func animateTimer(over duration: TimeInterval) {
    animationLayer.removeAllAnimations()
    let head = CABasicAnimation(keyPath: "strokeEnd")
    head.toValue = 1
    head.duration = duration
    head.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    head.fillMode = kCAFillModeForwards
    head.isRemovedOnCompletion = false
    animationLayer.add(head, forKey: "strokeEnd")
}

func animateTimerReset() {
    let tail = CABasicAnimation(keyPath: "strokeStart")
    tail.toValue = 1
    tail.duration = 0.1
    tail.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    tail.fillMode = kCAFillModeForwards
    tail.isRemovedOnCompletion = false
    animationLayer.add(tail, forKey: "strokeStart")
}

Some further remarks: At several places the explicit type
annotation can be removed, e.g.

var trackColor: UIColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)
var trackShade: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
var trackLight: UIColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)

is shorter written as

var trackColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)
var trackShade = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
var trackLight = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)

Also “implicit member expressions“ can be used if the type is inferred from the context, e.g.

layer.strokeEnd = CGFloat.leastNormalMagnitude

becomes

layer.strokeEnd = .leastNormalMagnitude


Massive file sorting algorithm I was trying to sort a massive file of successive chars in C. I did some research and found a few file sorting algorithms that look the same. Their main idea is to read an amount of data to memory, sort them using one of classic sort algorithms, write them to a new file, then repeat the process and merge the two files and so on. You can find more here

I tried to make a new algorithm that does not require a lot of memory. I ended up with this code that actually works and is inspired from Bubble sort algorithm:

#include<stdio.h>
int main()
{
char a,b;
FILE *f,*aux;

int sorted;//BOOLEAN
do
{
    f = fopen("ltr.txt","r"); //Assuming that the file exists
    aux = fopen("aux.txt","w+");
    a = getc(f);
    sorted = 1;
    while ( (b = getc(f)) != EOF )
    {
        if (b < a)
        {
            fputc(b, aux);
            sorted = 0;
        }
        else
        {
            fputc(a, aux);
            a = b;
        }
    }
    fputc(a, aux);
    fclose(f);
    fclose(aux);
    remove("ltr.txt");
    rename("aux.txt","ltr.txt");
}while(!sorted);
return 0; //EXIT_SUCCESS
}

The algorithm works but is improvable and can be optimized, however I'm asking for help by reviewing complexity, performance, read/write to disk, disk management, memory management and comparison to other sorting algorithms.

I can list some disadvantages:

requires disk space of file_size*2 (can be improved by deleting original char each time we write it to aux.txt)
file will be written to disk several times and the original will be deleted
execution time looks to be too long (yet I didn't measure it)

If you are certain that you only have standard ASCII characters in the file, it's more efficient to just map the whole space and print it out with a counting sort.

The idea is that you use the character itself (a number between 0 and 255) as the index of an array, count how many of those are in the file, and then write the array starting from the beginning.

This is some sample code. Please note that I cannot test it right now, but it should give you a basic idea on how to do it.

#include <stdio.h>

int main()
{
    //You may want to consider a 'long long' type
    long char_count[256];

    FILE *input_file, *output_file;

    input_file = fopen("ltr.txt","r"); //Assuming that the file exists
    output_file = fopen("aux.txt","w+");
    memset(char_count, -1, 256);
    char input_char;
    while (input_char = getc(input_file)) {
        char_count[input_char] = char_count[input_char] > 0 ? (char_count[input_char] + 1) : 1;
    }

    int index;
    for (index = 0; index < 255; index++) {
        if (char_count[input_char] > 0) {
            int char_index;
            //Can be optimized by building a format string and using fprintf
            for (char_index = 0; char_index < char_count[input_char]; char_index++) {
                fputc(char_count[input_char], output_file);
            }
        }
    }
    fclose(output_file);
    fclose(input_file);

    return 0;
}