texts:
I implemented a simple Java JDBC wrapper in Kotlin with Arrow functional library.

/**
 * Executes simple SQL statement that takes no arguments.
 * E.g. "CREATE TABLE" statement.
 *
 * @return IO with either an exception or boolean result
 */
fun String.executeStatement(dataSource: DataSource): IO<Either<Throwable, Boolean>> {
    val connection = dataSource.connection
    return IO { connection.createStatement().execute(this) }.attemptAndCloseConnection(connection)
}

/**
 * Executes prepared SQL statement (a statement that takes arguments).
 * E.g. "INSERT, UPDATE, DELETE..." statements.
 *
 * @return IO with either an exception or with result of execution as an integer
 */
fun String.executePreparedStatement(dataSource: DataSource, vararg args: Any): IO<Either<Throwable, Int>> {
    val connection = dataSource.connection
    return IO {
        val preparedStatement = connection.prepareStatement(this)
        args.forEachIndexed() { idx, arg -> preparedStatement.setObject(idx + 1, arg) }
        preparedStatement.executeUpdate()
    }.attemptAndCloseConnection(connection)
}

/**
 * Executes SQL query
 */
fun <E> String.executeQuery(dataSource: DataSource, resultSetMapper: (ResultSet) -> E, vararg args: Any): IO<Either<Throwable, List<E>>> {
    val connection = dataSource.connection
    return IO {
        val list = mutableListOf<E>()
        val preparedStatement = connection.prepareStatement(this)
        args.forEachIndexed() { idx, arg -> preparedStatement.setObject(idx + 1, arg) }
        val resultSet = preparedStatement.executeQuery()
        while (resultSet.next()) {
            list.add(resultSetMapper(resultSet))
        }
        list.toList()
    }.attemptAndCloseConnection(connection)
}

private fun <A> IO<A>.attemptAndCloseConnection(connection: Connection?) =
        this.attempt().map { connection?.close(); it }

Every result of execution is wrapped in an instance of IO to represent side-effects.

Functions are invoked directly on strings which produces an instance of Either<Throwable, T> when run:

val dataSource = HikariDataSource()
// add config for data source...

"""CREATE TABLE cities (
            id INTEGER PRIMARY KEY AUTO_INCREMENT,
            name VARCHAR(255) NOT NULL);""".executeStatement(dataSource)
                .unsafeRunSync()

"INSERT INTO cities (name) VALUES (?)".executePreparedStatement(dataSource, "New York").unsafeRunSync()

My major concerns are:

Passing an instance of DataSource upon invocation of every function. E.g. with Scala, I could pass data source implicitly which would declutter invocations.
Mutable list in executeQuery function. Is it even ok?
Closing connection (attemptAndCloseConnection function) - is there some better way to do this?
Other proposals?


texts: Sequence-based enumeration of permutations with Heap's algorithm

texts:
Heap's algorithm
is an algorithm to generate all permutations of a given array. It

  ... generates each permutation from the previous one by interchanging a single pair of elements; the other n−2 elements are not disturbed.

Here is my attempt to implement this algorithm in Swift 4 as a Sequence,
so that all permutations of an array can be enumerated with for .. in
loops and related techniques:

/*
 * A sequence of all permutations of a given array. Based on the
 * non-recursive version of Heap's algorithm as described in
 * https://en.wikipedia.org/wiki/Heap%27s_algorithm
 */

struct HeapPermutationSequence<Element>: Sequence, IteratorProtocol {

    private var current: [Element]
    private var c: [Int]
    private var i = 0
    private var firstIteration = true

    init(elements: [Element]) {
        self.current = elements
        self.c = Array(repeating: 0, count: elements.count)
    }

    mutating func next() -> [Element]? {
        if firstIteration {
            firstIteration = false
        } else {
            while i < c.count {
                if c[i] < i {
                    if i % 2 == 0 {
                        current.swapAt(0, i)
                    } else {
                        current.swapAt(c[i], i)
                    }
                    c[i] += 1
                    i = 0
                    break
                } else {
                    c[i] = 0
                    i += 1
                }
            }
        }
        return i < c.count ? current : nil
    }
}

Example usage:

for p in HeapPermutationSequence(elements: [1, 2, 3]) {
    print(p, terminator: ", ")
}
print()

// Output:
// [1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1],

Several techniques from @Hamish's answer Sequence-based enumeration of permutations in lexicographic order could be
applied here as well to improve the performance:

Avoid the cost of copy-on-write by not mutating the current
array after it is returned as the next element.
Have a single exit point in the next() method.

Benchmark:

let N = 10
var count = 0
let start = Date()
for _ in HeapPermutationSequence(elements: Array(1...N)) { count += 1 }
let end = Date()
print(count, end.timeIntervalSince(start))

which takes about 0.03 seconds (on a 1.2 GHz Intel Core m5 MacBook, compiled in Release mode).

All feedback is welcome, such as (but of course not restricted to):

Performance improvements.
Better variable names (c and i are simply copied from the Wikipedia
pseudo-code).
Simplifying the code, or making it better readable/understandable.


texts: Function for most frequent level of string or factor categorical variable in R

texts:
I have a function that finds the most frequent level of string and factor variables. This is used in a data.table aggregation on Big Data, for non-numeric columns.

Right now the overall aggregation runs extremely slow. I'm trying to make improvements in other aspects as well (reducing observations and columns, etc) and I would like to see if there's a want to improve this function:

MaxTable <- function(InVec, mult = FALSE) {
  if (!is.factor(InVec)) InVec <- factor(InVec)
  A <- tabulate(InVec)
  if (isTRUE(mult)) {
    levels(InVec)[A == max(A)]
  }
  else levels(InVec)[which.max(A)]
}


texts: Simplifying calculation with min value in C#

texts:
We have to calculate a lot of different fixed factors with user input values.
Every single calculation has a different min value.

This block of code

result.Calculation_VK = input.km_past_year * 0.040m;
if (result.Calculation_VK <= 300)
    result.Calculation_VK = 300;
result.Calculation_VK *= Constant.MWST;

Is repeated over and over again with different constant factors and input variables. My question is, is it possible to simplify the lines

if (result.Calculation_VK <= 300)
    result.Calculation_VK = 300;

while still keeping the code readable?

We tried working with the ? Operator, but this doens't really clean up the code. Especially considering that these lines will be repeated over and over again.

result.Calculation_VK = input.km_past_year * 0.040m <= 300 ? 300 : result.Calculation_VK * 0.040m;
result.Calculation_VK *= Constant.MWST;

I thought about creating properties with default values inside the getters. But as we are using common and reusable objects that are shared over several classes and methods it would lead to creating objects for each single method.

For my understanding this would nullify the advantage of using objects to pass needed values into our calculations.


texts:
I'm working on a class, what will be able to send e-mails for our customers.  I need to help with review of my classes design. I'm trying to do it to be easy extendable in future. I'm thinking about using dependency injection to inject InputReaderInterface. But is it worth doing it?

InputReaderInterface - has method: getContent()
WebReader - for reading source e-mail HTML (implements InputReaderInterface)
ParamSetter - for setting different params for users (implements InputReaderInterface)
$smtp - class for saving access attributes for SMTP
Mailer - uses PHPMailer class for sending e-mails

In the future, params will be loaded from the database.

<?php
$reader1 = new WebReader($mailUrl);
$message = $reader1->getContent();

$params = array(
  "test@test.com" => array(
    "customer" => "Name Surname"
  )
);

$reader2 = new ParamSetter($message, $params);

$mailer = new Mailer($smtp, $from, $alias);

foreach($rows as $row) {
  $reader2->setParamsFor($row["email"]);
  $message = $reader2->getContent();

  $mailer->sendMail($row["email"], $subject, $message);
}
?>


texts: Can this localStorage login script be written more efficiently?

texts:
I understand that account details should be stored using a much more secure method, but this is only a demonstration script I've made to store login credentials and remember a user wishes to remain logged in using localStorage rather than sessionStorage.

Could anyone show me how I might write this more efficiently please? My main concern is code repetition, so I'd love to move toward a much more object oriented structure.

var bic = bic || {};

bic.checkLogin = function() {
    var loginUser = document.getElementById("loginUser").value;
    var loginPass = document.getElementById("loginPass").value;
    var storedUser = localStorage.Username;
    var storedUser2 = storedUser.replace(/"/g,''); // remove " for plain text display in loginForm
    var storedPass = localStorage.Password;
    var checked = document.getElementById("rememberLogin").checked;

    if(checked == true) {
        localStorage.setItem("loggedIn", "yes");
    } else {
        localStorage.setItem("loggedIn", "no");
    }

    // if Username key exists, and user/pass values match storage entries
    if(localStorage.Username) {
        if(storedUser.match(loginUser) && storedPass.match(loginPass)) {
            bic.notify("loginForm", "Logged in as: " + storedUser2 + "

Log out?");
            document.getElementById("logout").onclick = function(e){e.preventDefault();bic.logout();};
            console.log("Logged in as: " + localStorage.Username);
        } else {
            bic.loginFailed();
            bic.notify("loginStatus", "Login failed. Please try again.");
            console.log("Failed logins: " + localStorage.failedLogins);
        }
    }
}

// localStorage equiv of cookie
bic.isLoggedIn = function() {
    var a = localStorage.loggedIn;
    var storedUser = localStorage.Username;
    var storedUser2 = storedUser.replace(/"/g,''); // removing " as above

    // does a exactly equal "yes"?
    if(a === "yes") {
        bic.notify("loginForm", "Logged in as: " + storedUser2 + "

Log out?");
        document.getElementById("logout").onclick = function(e){e.preventDefault();bic.logout();};
        console.log("Logged in as: " + localStorage.Username);
    }
}

// logout and remove localStorage key
bic.logout = function() {
    document.getElementById("loginForm").innerHTML = "<input type='text' id='loginUser' placeholder='Username'>

<input type='password' id='loginPass' placeholder='Password'>

<button type='button' id='login'>Login</button> <button type='button' id='loginReg'>Register</button>

<input type='checkbox' id='rememberLogin' /> Stay logged in?
";
    bic.loginPrefill();
    bic.delete("loggedIn");
    console.log("Logged out");
}


texts:
Here is a variation on a theme: fizzbuzz. After providing this answer recently, I decided to practice some VueJS skills with outputting the values and conditionally applying styles based on the value. The specific styles are as follows:

red border for Fizz
blue border for Buzz
purple border for FizzBuzz

And then I decided to allow the user to change the height of the container, in case he/she wanted a smaller viewport.

What, if anything, would you change?

const getIndex = (number, index) => index + 1;
const app = new Vue({
  el: "#app",
  data: {
    numbers: new Array(100).fill(1).map(getIndex),
    height: 3000
  },
  filters: {
    getOutput: function(number) {
      if (number % 3 === 0 && number % 5 === 0) return 'FizzBuzz';
      if (number % 3 === 0) return 'Fizz';
      if (number % 5 === 0) return 'Buzz';
      return number;
    }
  },
  methods: {
    getClass: function(number) {
      const output = this.$options.filters.getOutput(number);
      if (isNaN(parseInt(output, 10))) {
       return output;
      }
      return '';
    }
  }
});
body {
  padding: 4px;
  font-family: serif;
}
h1 {
   font: 400 20px cursive;
}
input[type="range"] {
  width: 100%;
}
#listContainer {
  overflow-y: hidden;
}

li {
  background: #fff;
  color: #000000;
  border-radius: 4px;
  border: 2px solid #6a737c;
  padding: 3px;
}

li.FizzBuzz {
  border-color: #f800ff;
}

li.Fizz {
  border-color: #f80000;
}

li.Buzz {
  border-color: #0000ff;
}

    FizzBuzz with dynamic height container

   Height: {{ height }}

  <input type="range" min="200" max="3000" v-model="height" />

        {{ number | getOutput }}


texts: Actively writing an HTTPS webserver in Python 3

texts:
Please help me improving this existing, working code. I am not asking you to change what it does, as it handles connections already perfectly as designed by my own specs. I just want the code to be reviewed to be sure.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, ssl
from socketserver import ThreadingMixIn
from http.server import SimpleHTTPRequestHandler, HTTPServer

global sslcontext
sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
sslcontext.options |= ssl.OP_NO_TLSv1
sslcontext.options |= ssl.OP_NO_TLSv1_1
sslcontext.protocol = ssl.PROTOCOL_TLSv1_2
sslcontext.set_ciphers("ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305")
sslcontext.set_ecdh_curve("secp384r1")
sslcontext.load_cert_chain("/home/pi/keys/fullchain.pem", "/home/pi/keys/privkey.pem")

class HSTSHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
        SimpleHTTPRequestHandler.end_headers(self)

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    daemon_threads = True

def main():
    try:
        os.chdir("/media/external")#auto-change working directory
        SimpleHTTPRequestHandler.sys_version = "0.1"#display custom Python system version
        SimpleHTTPRequestHandler.server_version = "0.2"#display custom server software version
        my_server = ThreadedHTTPServer(('', 443), HSTSHandler)
        my_server.socket = sslcontext.wrap_socket(my_server.socket, server_side=True)
        print('Starting server, use <Ctrl-C> to stop')
        my_server.serve_forever()

    except KeyboardInterrupt:
        print(' received, shutting down server')
        my_server.shutdown()

if __name__ == '__main__':
    main()


texts:
I would like to get some helpful thoughts on this and if there is a way to break it. Is there any point to not use fgets in that form?

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

#define GETNAME_SIZE 100

char *getPhrase() {

    int size;
    char phrase[GETNAME_SIZE];
    char *phraseHolder;
    printf("Enter a phrase:");

    fflush(stdout);

    if (fgets(phrase,sizeof phrase,stdin) == NULL ) {
        return NULL;
    }

    size = strlen(phrase)+1;
    phraseHolder = malloc(size);
    if (phraseHolder == NULL) {
        return NULL;
    }
    strcpy(phraseHolder,phrase);
    phraseHolder[strcspn(phraseHolder,"\n")] = '\0';
    printf("The phrase you introduced is: <%s>\n", phraseHolder);

    return phraseHolder;

}

char *getChangedPhrase(char *phrase) {

    int size,i,codeSize;
    int j = 0;
    char *code;
    int pace;
    size = strlen(phrase)+1;
    if(size <2) {
        printf("Enter a bigger phrase!");
        return NULL;
    }

    code = malloc(size);
    if (code == NULL) {
        return NULL;
    }
    fflush(stdout);
    printf("Enter the code that you want to be used with your phrase!(only letters)\n");

    if (fgets(code,size,stdin) == NULL) {
        return NULL;
    }
    code[strcspn(code,"\n")] = '\0';
    codeSize = strlen(code);
    for(i = 0 ; i < size ; i++) {
            if(phrase[i] < 65 || (90 < phrase[i] && phrase[i] < 97) || 122<phrase[i] ) {
                continue;
            }
            else {
                while(code[j] < 65 || (code[j] > 90 && code[j] < 97) || code[j] > 122 ) {
                    j++;
            }
                pace = code[j];

            if(code[j] > 96 && code[j] < 123) {
            pace = pace - 97;

            if(phrase[i] + pace > 122 )
                phrase[i] = phrase[i] + pace - 26;
            else
                if( phrase[i] + pace > 90 && code[j] < 90)
                phrase[i] = phrase[i] + pace - 26;
            else
                if(phrase[i] + pace > 90 && code[j] > 96 && phrase[i] < 91 ) {
                   phrase[i] = phrase[i] + pace - 26;
                }
            else
                phrase[i] = phrase[i] + pace;

        }
            else if ( code[j] > 64 && code[j] <91 ) {
                pace = pace - 65;

                if((phrase[i] < 91 && (phrase[i] + pace) > 90) || (phrase[i] + pace) > 122 )
                    phrase[i] = (phrase[i] + pace - 26);

                else
                    phrase[i] = phrase[i] + pace;
            }

            j++;

            if(j == codeSize) {
                j = 0;
            }
        }

    }
    free(code);
    phrase[strcspn(phrase,"\n")] = '\0';
    return phrase;
}

int main() {
    char *phrase = getPhrase();
    char *modifiedPhrase = getChangedPhrase(phrase);
    printf("The changed phrase is: \n <%s> \n", modifiedPhrase);
    //free(phrase);
    printf("Press ENTER key to Continue\n");
    getchar();
    getchar();
}


texts: Project Euler # 52 Permuted multiples in Python

texts:
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits,
but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

from time import time

def is_permutation(n1, n2):
    """returns True if n1 is permutation of n2"""
    if n1 == n2:
        return False
    str1 = str(n1)
    str2 = str(n2)
    digits1 = {digit: str1.count(digit) for digit in str1}
    digits2 = {digit: str2.count(digit) for digit in str2}
    if not digits1 == digits2:
        return False
    return True

def check_multiples(n, start=10):
    """checks 2x, 3x, 4x, 5x, 6x and returns the numbers if they are permutations."""
    for x1 in range(start, n):
        x2 = x1 * 2
        if is_permutation(x1, x2):
            x3 = x1 * 3
            if is_permutation(x2, x3):
                x4 = x1 * 4
                if is_permutation(x3, x4):
                    x5 = x1 * 5
                    if is_permutation(x4, x5):
                        x6 = x1 * 6
                        if is_permutation(x5, x6):
                            return x1, x2, x3, x4, x5, x6

if __name__ == '__main__':
    start_time = time()
    print(check_multiples(1000000, 125000)[0])
    print(f'Time: {time() - start_time} seconds.')


texts: Design of genetic algorithm which would allow TDD

texts:
I'm implementing genetic algorithm in Java and I want to learn TDD with this project.

Currently I have this code:

package geneticAlgoritm;

import geneticAlgoritm.randomNumbers.IRandomGenerator;
import geneticAlgoritm.randomNumbers.RandomGenerator;
import lombok.Getter;
import lombok.NonNull;

import java.util.List;

public class Population {
    @NonNull private IRandomGenerator generator = new RandomGenerator();

    @Getter
    @NonNull
    private List<Chromosome> population;

    @NonNull final IFitnessCalculator calculator;

    public Population(int n, IFitnessCalculator calculator) {
        this.calculator = calculator;
        this.population = generatePopulation(n);
    }

    int nextGeneration() {

    }

    private List<Chromosome> generatePopulation(int n) {
        return null;
    }

    private Chromosome mutate(Chromosome chromosome, double probability) {
        return null;
    }

    private Chromosome crossover(Chromosome first, Chromosome second, double probability) {
        return null;
    }

    private List<Chromosome> pickBestOfPopulation(int n) {
        return null;
    }
}

Basically, I have Chromosome class, which is wrapper for byte[] array and fitness of that array.

nextGeneration generates new population with better traits. How I can change design to allow testing crossover, mutate etc functions?

nextGeneration is really inconvenient to test for all functionalities, especially with some randomness in each (I'm using custom interface to remove it).


texts:
This include was written for a Jekyll site I'm building. It generates nested HTML unordered lists to a given depth dynamically by parsing page urls. It works fine, but the code feels messy and it takes Jekyll upwards of 20 seconds to build the site (up from ~3 seconds before this navigation was implemented).

Basically the code goes through each page in the site, makes sure the page is at the right depth by examining how many levels are represented in the url (separated by depth), and outputs a link to the page if the page is indeed at the right length and its url contains the base url of its parent page.

nav.html include:

{% comment %} Init call with current_depth, max_depth. Both are zero-based. {% endcomment %}

{% assign current_lvl_url_length = include.current_depth | plus: 2 %}
{% assign next_lvl_url_length = current_lvl_url_length | plus: 1 %}
{% assign max_url_length = include.max_depth | plus: 2 %}
{% assign base_url = include.base_url %}

{% if include.base_url == nil %}
    {% assign base_url = '/' %}
    {{ base_url }}
{% endif %}

{% for node in site.pages %}
    {% assign node_url_parts = node.url | split: '/' %}
    {% assign filename = node_url_parts | last %}

    {% if node_url_parts.size == current_lvl_url_length and node.url contains base_url and filename != 'index.html' and filename contains 'html' %}

            {{node.title}}

            {% if next_lvl_url_length <= max_url_length %}
                {% assign node_base_url = node.url | replace: '.html' | append: '/' %}
                {% assign is_submenu = false %}
                {% for subnode in site.pages %}
                    {% assign subnode_url_parts = subnode.url | split: '/' %}
                    {% if subnode_url_parts.size == next_lvl_url_length and subnode.url contains node_base_url %}
                    {% assign is_submenu = true %}
                    {% break %}
                    {% endif %}
                {% endfor %}

                {% if is_submenu %}

                        {% assign next_depth = include.current_depth | plus: 1 %}
                        {% include nav.html current_depth=next_depth max_depth=include.max_depth base_url=node_base_url old_base_url=base_url %}

                        {% comment %} Reverse recursion state: {% endcomment %}

                        {% assign current_lvl_url_length = current_lvl_url_length | minus: 1 %}
                        {% assign next_lvl_url_length = next_lvl_url_length | minus: 1 %}
                        {% assign base_url = include.old_base_url %}
                        {% if include.old_base_url == nil %}
                            {% assign base_url = '/' %}
                        {% endif %}

                {% endif %}
            {% endif %}

    {% endif %}
{% endfor %}

header.html where nav.html is initially called:

    {{ site.title }}

        <svg viewBox="0 0 18 15">
          <path fill="#424242" d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.031C17.335,0,18,0.665,18,1.484L18,1.484z"/>
          <path fill="#424242" d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484 h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z"/>
          <path fill="#424242" d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z"/>
        </svg>

{% include nav.html current_depth=0 max_depth=2 %}


texts: Getting a random number between a min and a max

texts:
I have a function that gets a random number between a min and max.

I call the function on a variable as such:

let randomPage = getRandomIntInclusive(1, 5);

That expression is repeated several times in my code (let's say 5 to 10 times within different functions). Is there a way to refactor it further or call it in a better way?

The way I call it is like:

function a() {
  randomPage = getRandomIntInclusive(1, 5);
}

function b() {
  randomPage = getRandomIntInclusive(1, 5);
}

function c() {
  randomPage = getRandomIntInclusive(1, 5);
}

Full code:

$http({
  method: "GET",
  url: "URL"
})
.then(function mySuccess(response) {
  $scope.discoverMovie = response.data;
  /* console.log($scope.discoverMovie);
  console.log($scope.discoverMovie.results[0].id); */
  var i = getRandomIntInclusive(1, $scope.discoverMovie.results.length - 1);
  trailerKey = $scope.discoverMovie.results[i].id;
  getMovieDetail(trailerKey);

  $scope.nextMovie = function () {
    /* Get Movie to Next Movie Function */
    i = i + 1;
    if (i == $scope.discoverMovie.results.length) {
      randomPage = getRandomIntInclusive(1, 5);
      i = getRandomIntInclusive(1, $scope.discoverMovie.results.length - 1);
      getMovieList(randomPage);
    }
    trailerKey = $scope.discoverMovie.results[i].id;
    getMovieDetail(trailerKey);
  };

  $scope.previousMovie = function () {
    /* Get Movie to Next Movie Function */
    i = i - 1;
    if (i < 0) {
      randomPage = getRandomIntInclusive(1, 5);
      i = getRandomIntInclusive(0, $scope.discoverMovie.results.length - 1);
      getMovieList(randomPage);
    }
    trailerKey = $scope.discoverMovie.results[i].id;
    getMovieDetail(trailerKey);
  };
}, function myError(response) {
    $scope.discoverMovie = response.statusText;
 });


texts: Total beginner Tic Tac Toe game in Python

texts:
I've decided to learn Python about 2 weeks ago, been going through various books and videos, and I've decided to try my hand at programming a Tic Tac Toe game. I was somewhat successful (it doesn't recognize if there's already a mark in a certain spot and allows overwriting of already placed marks) and I was wondering if any more experienced programmers could give me some general feedback about how I could do things better, and how to prevent overwriting of previously placed mark.

board = ['-'] * 9

def print_board():
    print (board[0] + '|' + board[1] + '|' + board[2])
    print (board[3] + '|' + board[4] + '|' + board[5])
    print (board[6] + '|' + board[7] + '|' + board[8])

legalMoves = [1,2,3,4,5,6,7,8,9]
print_board()

turnCount = 0
def move():

    move = int(input('Pick a number 1-9:'))
    while move not in legalMoves:
        print('Illegal move')
        move = int(input('Pick a number 1-9:'))

    marks = ['X','O']

    if turnCount % 2 == 0:
        board[move - 1] = marks[1]
    else:
        board[move - 1] = marks[0]

while True:
    if board[0] == board[1] == board[2] == 'X'\
    or board[3] == board[4] == board[5] == 'X'\
    or board[6] == board[7] == board[8] == 'X'\
    or board[0] == board[3] == board[6] == 'X'\
    or board[1] == board[4] == board[7] == 'X'\
    or board[2] == board[5] == board[8] == 'X'\
    or board[0] == board[4] == board[8] == 'X'\
    or board[2] == board[4] == board[6] == 'X' \
    or board[0] == board[1] == board[2] == 'O' \
    or board[3] == board[4] == board[5] == 'O' \
    or board[6] == board[7] == board[8] == 'O' \
    or board[0] == board[3] == board[6] == 'O' \
    or board[1] == board[4] == board[7] == 'O' \
    or board[2] == board[5] == board[8] == 'O' \
    or board[0] == board[4] == board[8] == 'O':
        print('Victory')
        break

    else:
        move()
        print_board()
        turnCount = turnCount + 1


texts: C++ class for a flag register in a Chip8 emulator

texts:
In order to learn C++ I decided to code a Chip8 emulator following a tutorial. When I came across the idea of a flag register and decided it would be fun to implement in order to get familiar with bitwise operations. I'd like this review to center on what can be improved from the point of view of C++, but of course any other suggestions and improvements are welcome.

class FlagRegister {
private:
    unsigned char state = 0x00;
    enum Flag: unsigned char {
        CF = 0x01,
        PF = 0x02,
        AF = 0x04,
        ZF = 0x08,
        TF = 0x10,
        IF = 0x20,
        DF = 0x40,
        OF = 0x80
    };

    bool checkFlag(Flag flagToCheck) {
        return (bool) ((this->state >> (flagToCheck - 1)) % 2);
    }

    void setFlag(Flag flagToSet) {
        this->state = this->state | flagToSet;
    }

    void unsetFlag(Flag flagToUnset) {
        this->state = (this->state & (~flagToUnset));
    }

public:
    bool checkCF() {
        return this->checkFlag(CF);
    }

    void setCF() {
        this->setFlag(CF);
    }

    void unsetCF() {
        this->unsetFlag(CF);
    }
// Idem for all other flags.
};


texts:
Please have a look at these iterators which I use for my Sudoku solver. They behave slightly different from STL iterators and don't implement all functionality that would be needed to use them in a stl context. But the basic idea behind them was to clean up the code in the Sudoku program that makes heavy use of the three access patterns (row, col, block) that I implemented.

The most "important" iterator is the BlockIterator, since without that iterating over all nine fields in a block looked quite ugly. Iterating rows and columns wasn't that bad, but since I started writing the stuff I decided to create a complete set.

Some technical details:

The grid class holds an (evil) array of pointers to Field objects, that's one dimensional (I could have used a two dimensional array as well, but I often do it this way and feel quite comfortable with modulo operations). Maybe I will replace this with a vector later.

The grid class adds a few static functions to calculate offsets in the array based on row, col or block positions.

class Grid {
public:
    Grid();
    Grid(std::string s);

    class Iterator {
    public:
        Iterator(Grid* g) : grid(g), it(0){}
        Field* operator*(){return field;}
        void operator++(){
            ++it;
            if(it < 9) field = calc_field();
            else field = NULL;
        }
    protected:
        virtual Field* calc_field() = 0;
        Field* field;
        Grid* grid;
        int it;
    };

    class RowIterator : public Iterator {
    public:
        RowIterator(Grid* g, int row) : Iterator(g){
            row_offset = row * size; //Grid::block_offset(block);
            field = calc_field();
        }
        Field* calc_field(){
            int field_index = row_offset + it;
            return grid->field[field_index];
        }
    protected:
        int row_offset;
    };

    class ColIterator : public Iterator {
    public:
        ColIterator(Grid* g, int col) : Iterator(g){
            col_offset = col;
            field = calc_field();
        }
        Field* calc_field(){
            int field_index = it * size + col_offset;
            return grid->field[field_index];
        }
    protected:
        int col_offset;
    };

    class BlockIterator : public Iterator {
    public:
        BlockIterator(Grid* g, int block) : Iterator(g){
            block_offset = Grid::block_offset(block);
            field = calc_field();
        }
        Field* calc_field(){
            int field_index = block_offset + ((it / 3) * size) + (it % 3);
            return grid->field[field_index];
        }
    protected:
        int block_offset;
    };

    RowIterator& row_iter(int row){return *(new RowIterator(this, row));}
    ColIterator& col_iter(int col){return *(new ColIterator(this, col));}
    BlockIterator& block_iter(int block){return *(new BlockIterator(this, block));}

(...)

    static int block_offset(int block){return ((block / 3) * size * 3) + ((block % 3) * 3);}

protected:
        Field* field[grid_size];

Sample usage:

This function is called, when I set a value in a field. It goes through all fields, that would possibly be influenced by this field (same row, col or block)

void Field::do_exclusions(){
    // row
    for(Grid::RowIterator it = grid->row_iter(row); *it; ++it)
        (*it)->set_excluded(value);
    // col
    for(Grid::ColIterator it = grid->col_iter(col); *it; ++it)
        (*it)->set_excluded(value);
    // block
    for(Grid::BlockIterator it = grid->block_iter(block); *it; ++it)
        (*it)->set_excluded(value);
}

So please tell me, if something like this would be "acceptable" (not to mention "best practices"), even if it somehow takes a very free view on the iterator concept.

And of course every idea how this could be improved is welcome.

PS: I tried to add a tag "iterator" but I'm not allowed for too few reputation.


texts: Yet another implementation of malloc() in C

texts:
I'm really curious to know someone else's opinion on this implementation. Specifically, I would be interested to know the way you would have implemented it. Here the list of issues I've found with in this primitive implementation:

It's slow. You have to traverse the entire list in order to find a free block of memory.
Overuse of sbrk().
Very high possibility of internal fragmentation.

mem.h

#ifndef __MEM__
#define __MEM__
#include<stdio.h>
#include<stdlib.h>

typedef enum { false, true } bool;

typedef struct page
{
  size_t size;
  bool free;
  struct page* next;
  struct page* prev;
} page_t;

extern void* memalloc(size_t size);
extern void  memfree(void* pointer);

#endif

mem.c

#include "include/mem.h"
#include <assert.h>
#include <sys/types.h>
#include <unistd.h>

#define SBRK_ERROR (void*)(-1)
#define UNDEFINED 0

page_t* global;
page_t* last;

page_t* allocate(size_t size)
{
  page_t* node = sbrk(0);
  void* pointer = sbrk(size + sizeof(page_t));
  if(pointer == SBRK_ERROR)
    return NULL;
  if(last != NULL)
    last-> next = node;
  last = node;
  last-> size = size;
  last-> free = false;
  last-> next = NULL;
  return last;
}

void* search(size_t size)
{
  page_t* node = global;
  while(node != NULL){
    if(node-> size >= size || node-> size == UNDEFINED){
      if(node-> free)
        return node;
    }
    node = node-> next;
  }
  return NULL;
}

void* memalloc(size_t size)
{
  page_t* result = NULL;
  if(size >= 0){
    if(global != NULL){
      result = search(size);
      if(result == NULL)
        result = allocate(size);
    }else {
      global = allocate(size);
      result = global;
    }
  }
  return result != NULL ? (result + 1) : NULL;
}

page_t* to_page(void* pointer){
  return pointer - sizeof(page_t);
}

void memfree(void* pointer)
{
  if(pointer != NULL) {
    page_t* page = to_page(pointer);
    page-> size = UNDEFINED;
    page-> free = true;
  }
}

int main(int argc, char** argv)
{
  char* pointer = memalloc(5);
  memfree(pointer);
  return 1;
}

What are the most common techniques (implementations) to solve the issues above? Just rough ideas of it.


texts: Rsync script that does Daily, Weekly and Monthly backups with hard links

texts:
I have not been able to find a good implementation of using rsync to do daily, weekly and monthly backups with hard links anywhere. So I wrote my own and I am now looking for critique before I set it live on an unRAID production server. Anything I should fix?

#!/bin/bash
#
# Daily/Weekly/Monthly Backup
#
PROG_NAME=DailyWeeklyMonthlyBackup
BACKUPPOINT=/mnt/user
MOUNTPOINT=/mnt/disks/REDBackup
DAYOFWEEK_NAME=$(date +"%a")
DAYOFWEEK_NUMERAL_WEEKLY=$(date +"%u")
DAYOFWEEK_NUMERAL_MONTHLY=$(date +"%d")

logger Started -t$PROG_NAME $(date "+%m-%d-%Y %r")

if [ -d $MOUNTPOINT ]
then

    # Daily Backup START
    ############################
    rsync -a -v --delete $BACKUPPOINT/ $MOUNTPOINT/Daily/ 2>&1
    logger Daily REDBackup Completed -t$PROG_NAME $(date "+%m-%d-%Y %r")
    /usr/local/emhttp/webGui/scripts/notify -e "unRAID Server Notice" -s "Server Backup" -d "Daily REDBackup completed" -i "normal"

    # Weekly Sunday Backup START
    ############################
    if [ $DAYOFWEEK_NUMERAL_WEEKLY == 7 ]
    then
        rsync -avH --delete --link-dest=$MOUNTPOINT/Daily/ $BACKUPPOINT/ $MOUNTPOINT/Weekly/ 2>&1
        logger Weekly REDBackup Completed -t$PROG_NAME $(date "+%m-%d-%Y %r")
        /usr/local/emhttp/webGui/scripts/notify -e "unRAID Server Notice" -s "Server Backup" -d "Weekly REDBackup completed" -i "normal"
    fi

    # Monthly Backup START
    ############################
    if [ $DAYOFWEEK_NUMERAL_MONTHLY == 1 ]
    then
        rsync -avH --delete --link-dest=$MOUNTPOINT/Daily/ $BACKUPPOINT/ $MOUNTPOINT/Monthly/ 2>&1
        logger Monthly REDBackup Completed -t$PROG_NAME $(date "+%m-%d-%Y %r")
        /usr/local/emhttp/webGui/scripts/notify -e "unRAID Server Notice" -s "Server Backup" -d "Monthly REDBackup completed" -i "normal"
    fi

else

    logger REDBackup Drive Not Mounted -t$PROG_NAME $(date "+%m-%d-%Y %r")
    /usr/local/emhttp/webGui/scripts/notify -e "unRAID Server Notice" -s "Server Backup" -d "Daily REDBackup failed" -i "alert"

fi


texts: Caesar and Vigenère ciphers in Haskell, Take 2 (not so simple this time)

texts:
I've posted my simple ciphers on Code Review several days ago (link: here). I refactored my code and tried to define a more general "cipher" function, according to Zeta's excellent advice. I've split the code to make it more readable.

General cipher

This function takes an encoding function, "zero", list of keys and list of things to encode. The "zero" here is the character that shouldn't be encoded - e.g. a whitespace.

import Data.Char (toLower, ord, chr, isUpper)

cipher :: (Eq a) => (k -> a -> a) -> a -> [k] -> [a] -> [a]
cipher f z k = helper (cycle k)
  where
    helper _ [] = []
    helper (k:ks) (x:xs)
        | x == z = z : helper (k : ks) xs
        | otherwise = f k x : helper ks xs

Caesar's cipher

Notice the support for uppercase letters. I'm not sure it is right to include it, but it was a fun exercise nonetheless.

advanceBy :: Int -> Char -> Char -> Char
advanceBy n b c = chr $ (ord c - base + n) `mod` 26 + base
  where
    base = ord b

caesar, uncaesar :: Int -> String -> String
caesar n = cipher helper ' ' [n]
  where
    helper k x =
        let base = if isUpper x then 'A' else 'a'
        in advanceBy k base x

uncaesar n = caesar (26 - n)

Vigenère's cipher

I noticed  the helper of vigenere is almost the same as that of caesar. I could somehow extract that one out, but it wouldn't really help the readability very much and also I'd need to hack a little in the definition of caesar.
Also, unVigenere can be defined in terms of vigenere (similarly to how unCaesar is defined), but it isn't really nice nor elegant, so I do it traditionally instead.

vigenere, unVigenere :: String -> String -> String
vigenere = cipher helper ' '
  where
    helper k x =
        let base = if isUpper x then 'A' else 'a'
        in advanceBy (ord k - ord base) base x

unVigenere = cipher helper ' '
  where
    helper k x =
        let base = if isUpper x then 'A' else 'a'
        in advanceBy (26 - (ord k - ord base)) base x

Some other weird cipher

Here I want to showcase a cipher that encodes a list of integers using two keys. Because I don't know any legit ciphers apart from Caesar's and Vigenère's (I'd like to, though - be sure to link some if you know them), I had to create a new throwaway cipher.

(By the way, is this right? I don't like the fromIntegral and floor parts. It doesn't matter much here,  but it'd be nice to know how to write this properly.)

fancypher, unfancypher :: Int -> String -> [Int] -> [Int]
fancypher n = cipher helper 0
  where
    helper k x = n * x * ord k

unfancypher n = cipher helper 0
  where
    helper k x = floor $ fromIntegral x / fromIntegral (n * ord k)


texts: Canvas performance and stable frames per second

texts:
I'm sure this has probably been asked before (although I couldn't find a question akin to this one).

I have a canvas "app" that is refreshing persistently, but performance is awful on mobile devices. I just wondered if there was a nice alternative to requestAnimFrame() or the like.

Here is my "app":
http://www.barriereader.co.uk/Principality/

Here is the main rendering methods (I've removed the actual rendering - you can view that here http://www.barriereader.co.uk/Principality/System/Engine.js)

var fps = 0;
var oldtime = +new Date();
var time;

var Engine = {
    /** FOR DEBUGGING **/
    FPS: true,
    /*******************/

    Canvas : null,
    CTX : null,
    GameLooper : null,
    NodeSize : 10,
    MapSize : 32,
    Init : function (w, h) {
        Engine.Canvas = document.createElement('canvas');
        document.body.appendChild(Engine.Canvas);
        Engine.CTX = Engine.Canvas.getContext('2d');
        Engine.Canvas.width = w;
        Engine.Canvas.height = h;
        Engine.GameLoop();
    },
    Update : function (time) {
        fps = 1000/(time-oldtime)
        oldtime = time;
        Engine.Draw();
    },
    Draw : function () {
        Engine.CTX.save();
        Engine.CTX.setTransform(1, 0, 0, 1, 0, 0);
        Engine.CTX.clearRect(0, 0, Engine.Canvas.width, Engine.Canvas.height);
        Engine.CTX.restore();

        /**************DRAW_SCENE_HERE*****************/
            //A BUNCH OF RENDERING GOES HERE...
            //Performance is bad on mobiles :(
        /**********************************************/

        Engine.GameLoop();
    },
    GameLoop : function () {
        Engine.GameLooper = setTimeout(function () {
            requestAnimFrame(Engine.Update, Engine.Canvas);
        }, 10);
    },
};

window.requestAnimFrame = (function () {
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback, element) {
        window.setTimeout(callback(+new Date), 1000 / 60);
    };
}());

window.onload = function () {
    Engine.Init(320, 320);
};


texts:
Im curious how to improve this code. I don't like creating objects of four different types of reporters, because this could provide some problems with testing. How about the rest of this code, for example the if-statement below?

EDIT: This is a fragment of application to measure loading time of our website and few other competitors. If our site is slower than one of competitors application should send email, if our site is two times slower then application should send message via sms.

"""Module containing classes for comparing objects"""
import senders
import reporters

class Comparator:
    """Class for comparing objects"""

    def compare(self, compared, competitors):
        reporter = reporters.Reporter()
        rules = ComparatorExtensions(compared, competitors, reporter)

        send_with_email = senders.SendWithEmail()
        send_with_sms = senders.SendWithSms()
        save_to_file = senders.SendToFile()
        show_on_console = senders.ShowOnConsole()

        if rules.rule_valid_compared():
            if rules.rule_compared_smaller():
                send_with_email.send(reporter.format_report())

            if rules.rule_compared_two_times_smaller():
                send_with_sms.send(reporter.format_report())

        report = reporter.format_report()
        save_to_file.send(report)
        show_on_console.send(report)

class ComparatorExtensions:
    """Class for extensions for comparator class"""

    def __init__(self, compared, competitors, reporter):
        self.compared = compared
        self.competitors = (item for item in competitors if self.valid_item(item))
        self._reporter = reporter

    def valid_item(self, item):
        result = 'loading_time' in item
        if not result:
            self._reporter.report_invalid(item)
        return result

    def rule_compared_smaller(self):
        result = False
        for item in self.competitors:
            self._reporter.report_loading_time(item)
            if item.get('loading_time') < self.compared.get('loading_time'):
                self._reporter.report_smaller(self.compared, item)
                result = True

        return result

    def rule_compared_two_times_smaller(self):
        result = False
        for item in self.competitors:
            if (item.get('loading_time') * 2) <= self.compared.get('loading_time'):
                self._reporter.report_smaller_two_times(self.compared, item)
                result = True

        return result

    def rule_valid_compared(self):
        rule_valid = self.valid_item(self.compared)
        if rule_valid:
            self._reporter.report_loading_time(self.compared)
        return rule_valid

Full repository: https://github.com/adbo/benchmark


texts: Generate sample of permuted sequences with non-repeating elements

texts:
I have a very long sequence of letters (>20000 elements long).  I want to permute them so that I have another sequence using the same letters but in a different order but still with the property of no repeats.  e.g. ABABABA does not have repeats, but ABCDEEABCDE does as E is repeating itself in the middle.

I cannot accomplish this just yet for a sequence of >10000 or so.  I can do it for smaller sequences (e.g. 1000) but it's still really slow.

Sample data (the original population of letter codes):

x = read.table("https://gist.githubusercontent.com/jalapic/9f65738271dc86a5541f4d3ff843cb6a/raw/2098f6aeb3c016653552b11056ee22ef52ef6acb/seq",
               header=F, sep="", na.strings="NA",  strip.white=TRUE)

x <- as.character(x[[1]])
x <- gsub("Z", "", x) #remove Zs - they are spaces that should be removed
x

I have modified some suggested solutions to this.  It's all in R, but I have to think that a C++ solution may work better.

Here, I generate a subsample of 1000 elements drawn from the original population with probability of being drawn being the relative frequency of each letter in the original population:

uncollapsex <- function (x, n = 1) {substring(x, seq(1, nchar(x), n), seq(n,

probs = table(uncollapsex(x))

This is a series of loops that will do the following:

Generate a sample of 1000 elements drawn from the original population.
Attempt 5 times to find a way of putting the elements together but not allowing for repeats.
If a solution cannot be found, redo the sample and start again.
Repeat this process 10 times to try and get 10 solutions for 10 different samples of 1000 elements.

      Nres = 10

      res_list <- vector("list", Nres)  #results

    for (q in 1:Nres) {

    seq1 = sample(names(probs),prob=probs,1000,T)

    res_vec=NA

    counter=0

    while(is.na(res_vec[length(res_vec)]) | counter<=5) {

      counter = counter+1

      popul=seq1

      res_vec=rep(NA_character_,length(seq1))
new_draw=sample(popul,1)

      popul=popul[-match(new_draw,popul)]

      res_vec[1]=new_draw

      for (j in 2:length(seq1)) {

        while((new_draw==res_vec[j-1])&any(res_vec[j-1]!=popul)) {

            new_draw=sample(popul,1)

        }

        if (new_draw==res_vec[j-1]) {

          break

        }

        res_vec[j]=new_draw

        popul=popul[-match(new_draw,popul)]

      }

    }

    res_list[[q]] <- res_vec

    }

I'm really hoping that someone can identify a faster more efficient way of generating permuted sequences of non-repeating elements.  Either of length 1000 with the elements drawn from the original population, or to be able to actually permute the original population itself.

The aim is to generate 10,000 permuted samples (of either 1000 length or the original length) as part of a Monte Carlo simulation.


texts: Python server that only returns error 418

texts:
For this project, I'm using a small piece of Python code to return an error 418 to any request.  I'm interested in knowing if there is a much smaller piece of code that does the same thing.

#Modfied from code provided by Copyright Jon Berg , turtlemeat.com import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
            self.send_error(418,'I am a Teapot')

def main():
    try:
        server = HTTPServer(('', 80), MyHandler)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

PS - I considered putting this on Code Golf SE, but I wasn't sure if single-language-only requests are on-topic.


texts:
I'm building a date range selector, and while this works, I feel like I'm making it more complicated than it needs to be. Is there a more elegant way of writing this?

Possibly using computed values or watches?

<template>
<form>
    <select  @change="rangeSelection">
            <option
                v-for="(option, key) in rangeOptions"
                :key="key"
                :value="key">
                {{option.display}}
            </option>
    </select>
    </form>
</template>

<script>
import moment from 'moment';

export default {
  name: 'DateRangeChooser',
  data: () => {
    return {
        selectedRange: "last7Days",
        startDate: moment().subtract(8, 'days'),
        endDate: moment().subtract(1, 'days'),
        rangeOptions: {
            last7Days: {
                display: 'Last 7 Days',
                startDate: moment().subtract(8, 'days'),
                endDate: moment().subtract(1, 'days')
            },
            lastWeek: {
                display: 'Last Week',
                startDate: moment().startOf('week').subtract(1, 'week'),
                endDate: moment().endOf('week').subtract(1, 'week')
            },
            last30days: {
                display: 'Last 30 days',
                startDate: moment().subtract(31, 'days'),
                endDate: moment().subtract(1, 'days')
            }
        }
    }
  },
  methods: {
    rangeSelection: function(e){
        this.endDate = this.rangeOptions[e.currentTarget.value].endDate;
        this.startDate = this.rangeOptions[e.currentTarget.value].startDate;
    }
  }
};
</script>


texts:
I have written a function in XQuery 3.0 (using BaseX) which tests a base sequence against a test sequence, with the goal of determining if the items in the test sequence appear in the same order as the base sequence.

This is best illustrated with an example

E.G.
let $baseSequence := ('a','b','c'..'x','y','z')

Tested against

('a','b','c') => true appears in the same order in $baseSequence

('a','b','a') => false is not in the same order in $baseSequence

('c','h','x','y') => true appears in the same order in $baseSequence

I would like to know if there are any improvements on the function I have written for this, or is there a better way of doing this?

declare function local:testOrder($baseSequence, $testSequence, $position) {
    let $itemPosition :=
    if(count($testSequence) = 0) then (32768) else (index-of($baseSequence, head($testSequence)))
  return
    if ($itemPosition > $position) then (
      local:testOrder($baseSequence, tail($testSequence), $itemPosition)
    ) else (
      count($testSequence) = 0
    )
};

(:Test cases:)
let $baseSequence := ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
let $testAgainst := ('a','c','e','h','w')
return local:testOrder($baseSequence, $testAgainst, 0)

Would return true

let $baseSequence := ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
    let $testAgainst := ('f','d','l','m','n')
    return local:testOrder($baseSequence, $testAgainst, 0)

Would return false


texts:
I have the following function which I wrote in NASM to merge two sorted arrays. Its not a standalone, but its supposed to be compiled into a .o file and then linked to a .c file from which the function can be called with the following signature:

void merge(int* arr1, int size1, int* arr2, int size2, int* merged_array)

I have tested it and my code works as intended. However, I am somewhat new to assembly and I don't know if I'm following best practices with this code. Also, I timed it against a function that I wrote in C to do the same thing, and the C function consistently outperforms it for large arrays. So I'm wondering if there's any obvious sections of it I can rewrite to improve performance.

global merge

merge: ; entry point for function merge
    push ebp
    mov ebp, esp

    mov eax,[esp+8] ; pointer to array 1
    mov esi,[esp+12] ; length of array 1

    mov ebx,[esp+16] ; pointer to array 2
    mov edi,[esp+20] ; length of array 2

    mov edx,[esp+24] ; pointer to destination array (pre-allocated)

begin_merge:
    test esi,esi ; if we've run out of array 1
    jz copy2 ; just copy over array 2

    test edi,edi ; if we've run out of array 2
    jz copy1 ; just copy over array 1

    ;otherwise, compare the first elements
    mov ecx,[eax]
    cmp ecx,[ebx]
    jl merge_from_1 ; if eax > ebx, merge from array 1
    jmp merge_from_2; otherwise keep going for the merge from array 2

; merge a single element from an array
merge_from_2:
    mov ecx,[ebx]
    mov [edx],ecx
    add edx,4
    add ebx,4
    dec edi
    jmp begin_merge
merge_from_1:
    mov ecx,[eax]
    mov [edx],ecx
    add edx,4
    add eax,4
    dec esi
    jmp begin_merge

; copy over an entire array
copy1:
    test esi,esi ; if we've run out of array 1
    jz finish ; end
    ; otherwise, copy an element from array 1
    jmp merge_from_1 ; this will return to begin_merge, but thats okay
    ; because begin_merge will just forward it on to here again
copy2:
    test edi,edi ; if we've run out of array 2
    jz finish ; end
    ; otherwise, copy an element from array 2
    jmp merge_from_2 ; this will return to begin_merge, but thats okay
    ; because begin_merge will just forward it on to here again

finish:
    leave
    ret


texts:
I created a DAO class which is base class for all other DAO classes.

I use Spring Framework 4 and Hibernate 4.

Question: Is there anything that could be done better?

public class GenericDaoImpl<E, I extends Serializable> implements GenericDao<E, I> {
    private Class<E> entityClass;

    @Autowired
    private SessionFactory sessionFactory;

    public GenericDaoImpl(Class<E> entityClass) {
        this.entityClass = entityClass;
    }

    @Override
    public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<E> findAll() throws DataAccessException {
        return getCurrentSession().createCriteria(entityClass).list();
    }

    @Override
    @SuppressWarnings("unchecked")
    public E find(I id) {
        return (E) getCurrentSession().get(entityClass, id);
    }

    @Override
    public void create(E e) {
        getCurrentSession().save(e);
    }

    @Override
    public void update(E e)  {
        getCurrentSession().update(e);
    }

    @Override
    public void delete(E e) {
        getCurrentSession().delete(e);
    }

    @Override
    public void flush() {
        getCurrentSession().flush();
    }
}

Sample DAO class which extends base DAO class is for example this one:

@Repository("articleDao")
public class ArticleDaoImpl extends GenericDaoImpl<ArticleEntity, Long> implements ArticleDao {
    public ArticleDaoImpl(){
        super(ArticleEntity.class);
    }
}


texts:
I have written a small container class which groups a 3D position, a normal vector and a texture coordinate into one object. It uses the glm library for the actual data types (vec2 and vec3). This class is named Vertex. Here is the source:

Vertex.h

#ifndef CPP3D_VERTEX_H
#define CPP3D_VERTEX_H

#include <iostream>
#include <glm/glm.hpp>

namespace cpp3d {

class Vertex {

public:
    glm::vec3 position;
    glm::vec3 normal;
    glm::vec2 texCoord;
    Vertex();
    Vertex(const glm::vec3& position);
    Vertex(const glm::vec3& position, const glm::vec3& normal);
    Vertex(const glm::vec3& position, const glm::vec3& normal, const glm::vec2& texCoord);
    bool operator==(const Vertex& other);
};

std::ostream& operator<<(std::ostream &stream, const Vertex& vertex);
std::istream& operator>>(std::istream &stream, Vertex& vertex);

}

#endif

Vertex.cc

#include "Vertex.h"

namespace cpp3d {

using namespace glm;
using namespace std;

Vertex::Vertex() {
}

Vertex::Vertex(const vec3& position) :
        position(position) {
}

Vertex::Vertex(const vec3& position, const vec3& normal) :
        position(position), normal(normal) {
}

Vertex::Vertex(const vec3& position, const vec3& normal, const vec2& texCoord) :
        position(position), normal(normal), texCoord(texCoord) {
}

bool Vertex::operator ==(const Vertex& other) {
    return position == other.position && normal == other.normal && texCoord == other.texCoord;
}

ostream& operator<<(ostream &stream, const Vertex& vertex) {
    stream.write(reinterpret_cast<const char *>(&vertex), sizeof(vertex));
    return stream;
}

istream& operator>>(istream &stream, Vertex& vertex) {
    stream.read(reinterpret_cast<char *>(&vertex), sizeof(vertex));
    return stream;
}

}

As you can see I've overloaded the stream operators to write and read the data the object contains. For this I simply dump the whole object which results in writing eight float numbers so the output will be 32 bytes. I know that this is a very simple file format but I want to read the data as fast as possible so I don't want to parse text files. I also don't really care about different endiannesses (unless it can be implemented without speed impact). And I know the file format will change when I add more members to the class (This will most likely not happen but when it happens then I also want to change the file format anyway)

My main concern is if this code guarantees that it always writes and reads 32 bytes. I'm pretty new to C++ and my ancient C knowledge tells me that there is (or was) some kind of packed structs and aligned structs where the compiler could decide to align 8 bit values to 16 bits for some reason. I don't want some compiler (current or future ones) to store the 32 bit floats in 64 bit values because this obviously changes the binary data format. Can this happen with my code when compiled on specific platforms? If yes, what's the best way to write binary floats to a stream then? Shall I write each coordinate in each vector with a separate call to write()? Or are there other/better techniques to write and read the binary data?

If you see other issues with my code which are not related to my question please feel free to comment anyway. As a C++ newbie I'm eager to learn.


texts:
For a set of 2D or 3D points \$\{\mathbf P_0, \mathbf P_1,\cdots,\mathbf P_n\}\$, their parameters \$\mathbf T = \{t_0,t_1,\cdots,t_n \}\$ could be computed as follow:

$$\begin{align}
t_0&=0\\
t_i&=\frac{\sum_{j=1}^{i}||\mathbf P_j- \mathbf P_{j-1}||}{\sum_{j=1}^{n}||\mathbf P_j-\mathbf P_{j-1}||} \qquad i=1,2,\cdots,n
\end{align}$$

Here is my C implementation:

/********************************************************************
         v1 = {v1(0),v1(1),...,v1(c-1)}
         v2 = {v2(0),v2(1),...,v2(c-1)}
     compute the 2-norm of the difference of two vector v1 and v2
*********************************************************************/
double vector_norm(double *v1, double *v2, int c) {
    int i;
    double res = 0.0;
    for (i = 0; i < c; i++) {
        res += pow(v1[i] - v2[i], 2);
    }
    return sqrt(res);
}

/********************************************************
 In general, P is a matrix of dimensions {n + 1, c}
 here, it was saved as a vector
********************************************************/
void calc_paras(double *P, int n, int c, double *paras) {
    int i;
    double len = 0.0;
    double chord;
    //compute the length and total length
    paras[0] = 0.0;
    for (i = 0; i < n; i++) {
        chord = vector_norm(P + (i + 1) * c, P + i * c, c);
        len += chord;
        paras[i+1] = len;
    }
    //normalize the paras to [0,1]
    for (i = 0; i <= n; i++) {
        paras[i] /= len;
    }
}

Is a more efficient C implemetation of calc_paras() possible?


texts: Computing the improper integral of several functions

texts:
How can I optimize and make prettier the following code?

Main.cpp

#include "UtilitiesP.h"
#include "Simpson.h"

int main(void)
{
    double agm(1/functionsP::agm(1, 2));
    double integral( (2/constantsP::kPi) * Simpson(0, constantsP::kPi*0.5, constantsP::kEps, functionsP::eliptic));
    assert(fabs(agm-integral)<constantsP::kEps);

    double firstVal(constantsP::kPi*0.5);
    integral = Simpson(constantsP::kAlmostZero, 10000, constantsP::kEps, functionsP::Dirichlet);

    std::cout << firstVal << std::endl;
    std::cout << integral << std::endl;

    double secondVal(sqrt(constantsP::kPi)*0.5);
    integral = Simpson(constantsP::kAlmostZero, 12, constantsP::kEps, functionsP::Puasson);

    std::cout << secondVal << std::endl;
    std::cout << integral << std::endl;

    double thirdVal(constantsP::kPi/sin(constantsP::kNumberFromEuler*constantsP::kPi));
    integral = Simpson(constantsP::kAlmostZero, 13, constantsP::kEps, functionsP::Euler);

    std::cout << thirdVal << std::endl;
    std::cout << integral << std::endl;

    return 0;
}

Utilities.h

#include <stdexcept>
#include <iostream>

//#define NDEBUG
#include <cassert>

namespace constantsP
{
    const double kPi(3.1415926535897932);
    const double kEps(1.e-12);
    const double kAlmostZero(1.e-7);
    const double kBigNumber(30);
    const double kNumberFromEuler(0.4);
};

namespace functionsP
{
    double agm(const double&, const double&);
    double eliptic(const double&);
    double Dirichlet(const double&);
    double Puasson(const double&);
    double Euler(const double&);
};

Utilities.cpp

#include "UtilitiesP.h"

double functionsP::agm(const double& a, const double& b)
{
    if(a <= 0 || b <= 0)
    {throw std::invalid_argument("Arithmetic-geometric mean is defined only for 0 < a < b.");}

    double aPrev(a), bPrev(b), aCurrent(a), bCurrent(b);
    do
    {
        aPrev = aCurrent;
        bPrev = bCurrent;
        aCurrent = sqrt(aPrev*bPrev);
        bCurrent = (aPrev+bPrev)*0.5;
    }while((aPrev < aCurrent) && (bCurrent < bPrev) && (aPrev < bPrev));

    double res((aPrev <= aCurrent)?aPrev:bPrev);

    return res;
}

double functionsP::eliptic(const double& x)
{
    return 1/sqrt(pow(1*sin(x), 2) + pow(2*cos(x), 2));
}

double functionsP::Dirichlet(const double& x)
{
    return sin(2*x)/x;
}

double functionsP::Puasson(const double& x)
{
    return exp(-(x*x));
}

double functionsP::Euler(const double& x)
{
    return pow(x, constantsP::kNumberFromEuler-1)/(1+x);
}

Simpson.h

#include <cmath>

double Simpson (const double& a, const double& b, const double& eps, double(*const f)(const double&));

Simpson.cpp

#include "Simpson.h"

double Simpson (const double& a, const double& b, const double& eps, double(*const f)(const double&))
{
    double step((b-a)*0.5);
    double s1(step*(f(a)+f(b))), s2(0), s4(4*step*f(a+step));
    double previousSum(0), currentSum(s1+s4);
    int n(2);
    do
    {
        previousSum = currentSum;
        n += n;
        step *= 0.5;

        s1 *= 0.5;
        s2 = 0.5*s2+0.25*s4;

        s4 = 0;
        for(int i(1); i < n; i+=2)
        {s4 += f(a+i*step);}
        s4 = 4*step*s4;

        currentSum = s1+s2+s4;
    }
    while(eps<fabs(previousSum-currentSum));

    return currentSum/3;
}

After running the code you will see that it works well for the first three integrals. But it works very bad for the last one. It takes very much time to compute it.

What can I change in order to make it work faster?

What comments about the style do you have?


texts: Thread safe logging class in C# to use from DLL

texts:
I tried to sample up a logging class from this question and answer(I want to use this class from C# DLL).
Made slight modification mainly to file name, and also how data is written.
I am interested if this can be considered thread safe logging class?
I am particularly concerned by the comment under the answer. See below.
I didn't particularly understand the comment.

  You should also ditch the TextWriter.SyncTextWriter if you are going
  this way. Every method call on SyncTextWriter takes a lock on the
  instance. This is not necessary if you are wrapping the calls to the
  TextWriter in your own Logger classs methods. If you are passing a raw
  SyncTextWriter` around you can deadlock like this: lock(textWriter){
  textWriter.WriteLine("test"); // oops deadlock

Here is the class:

public static class Logger
{
    private static readonly object _syncObject = new object();

    static readonly TextWriter tw;

    static Logger()
    {
         // Note1:
         // My intent was that the log file name is same as the date on which the log
         // entry was added by the user - but apparently this approach as below is not
         // correct since it is in static constructor and the same date will be set for the file names even if log entries were added at different dates
         // Note2: The current answer doesn't address this, I would appreciate if someone can tell me where to move this code too to achieve what I want
         const string FMT = "yyyy-MM-dd";
         DateTime now1 = DateTime.Now;
         string strDate = now1.ToString(FMT);

        tw = TextWriter.Synchronized(File.AppendText(SPath() + "\\Log " + strDate + ".txt"));
    }

    public static string SPath()
    {
        return ConfigManager.GetAppSetting("logPath");
    }

    public static void Write(string logMessage)
    {
        try
        {
            Log(logMessage, tw);
        }
        catch (IOException e)
        {
            tw.Close();
        }
    }

    public static void Log(string logMessage, TextWriter w)    {
      // only one thread can own this lock, so other threads
      // entering this method will wait here until lock is
      // available.
      lock(_syncObject) {
       w.WriteLine("{0} {1} {2}", DateTime.Now.ToLongTimeString(),
          DateTime.Now.ToLongDateString(), logMessage);

       // Where to call flush??
       w.Flush();
     }
   }
}

PS. You can see classes like NLog have some requirements when they must be called from DLL(like config file must be in exe file which is calling DLL etc.). I'd like to avoid such things, as well as configurations which these classes require.


texts: Find the date for the nearest day of the week, in this case Fri & Sat

texts:
General objective: Find the date (day of the month) of the nearest specified day of the week and output.

More specifically: Focusing on events which take place every Fri & Sat, want the page to automatically update dates to next events. HOWEVER for clarity the page should never display Fridays and Saturdays which are NOT part of the same weekend. This would only happen on a SAT. So, if today's date is SAT, the displayed date for FRI should be yesterday (the immediately previous Friday), while the displayed date for SAT should be today's date.

It seems to work now.

Does this code follow common best practices?

Can you foresee cases where it would fail?

I am quite new to JavaScript and coding as you can probably tell.

(function() {

  var startingDate = new Date();

    function dateOfNearestDay(startingDate, nearestDay) {

    var nearestTime = new Date(startingDate.getTime());

    if (startingDate.getDay() == 6 && nearestDay == 5) {

      nearestTime.setDate((startingDate.getDate() + (7 + nearestDay - startingDate.getDay()) % 7) - 7);
    }
    else {

      nearestTime.setDate(startingDate.getDate() + (7 + nearestDay - startingDate.getDay()) % 7);

    }

    var nearestMonth = nearestTime.getMonth();
    var nearestDate = nearestTime.getDate();
    var nearestBoth = [nearestMonth, nearestDate];

    return nearestBoth;
  }

  monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  var nearestMonthFriday = monthNames[dateOfNearestDay(startingDate, 5)[0]];
  var nearestDateFriday = dateOfNearestDay(startingDate, 5)[1];
  var nearestMonthSaturday = monthNames[dateOfNearestDay(startingDate, 6)[0]];
  var nearestDateSaturday = dateOfNearestDay(startingDate, 6)[1];

  var fridaysDate = document.getElementById('fridaysDate');
  var saturdaysDate = document.getElementById('saturdaysDate');

  fridaysDate.textContent = nearestMonthFriday + " " + nearestDateFriday;
  saturdaysDate.textContent = nearestMonthSaturday + " " + nearestDateSaturday;

}());


texts:
I have 2 Flask apps (different projects) that work together . One implements some API which uses tokens for auth. The second one consumes the API and makes a web interface for it. Now I have a login function that sends the username and password to the API, and if correct, gets the auth token in return. Once I have the token, I save it to the session of the user and the user should now be considered as logged in/ autheticated.

Here is my login function -

def login(self):
        response = make_request(BASE_URL + 'login/', clean_data(self.data))
        if response.status_code == 200:
            session['auth_token'] = response.json().get('auth_token')
            return True
        return False

Also I am using Redis to store sessions if that matters. I have made the following login_required decorator -

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get('auth_token') is None:
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)

    return decorated_function

While it does work, I'm not sure if this is the best way to make that decorator. Any suggestions would be helpful.


texts:
I am currently trying out code for timing efficiency (how fast it runs, basically).

The general consensus is that code with ActiveCell,.Select,Selection and so forth are basicly rejected for being slow and buggy, whereas code that uses variables and not ActiveCell,.Select,Selection are considered quicker and less buggy

The two codes I have made do the same thing, which is to enter a number 40000+1 every consecutive cell (so Cell A1 is 40000 then A2 is 40001 and so forth) and then converts those numbers into dates. One does this with ActiveCell, Selection and Select, while the other does it with varibles,Long and Range. I also did both with and then without Application.ScreenUpdating = False to see how that worked as well.

The code ActiveCell etc. ran at 13494,26567,26489,14040,26598(without Application.ScreenUpdating = False) and 1154,1123,1123,1107,1170 (with Application.ScreenUpdating = False) "Milliseconds"

The code without ActiveCell ran at 905,905,905,671,687 (without Application.ScreenUpdating = False) and ran at 577,609,577,577,562 (with Application.ScreenUpdating = False) "Milliseconds"

The milliseconds is in "Milliseconds" as the Private Declare Function GetTickCount Lib "kernel32.dll" () As Long I have been lead to believe isnt very accurate, I use it because the accurate ones are addins for excel and I unable to download or install anything on this PC, but gvies a decent idea of the speed the code runs at

The code that the efficency tests is the For i = 1 To 1000 loop

Code with ActiveCells:

Private Declare Function GetTickCount Lib "kernel32.dll" () As Long

Sub UsingVaribles()

Dim NumberToday As Long
Dim StartTimer As Long
Dim rngCells As Range
Dim rng As Range

Application.ScreenUpdating = False

[A1].Select

NumberToday = 40000

StartTimer = GetTickCount

k = 1

    For q = 1 To 26

        For i = 1 To 1000
        NumberToday = NumberToday + 1
        Set rngCells = Cells(i, k)
        rngCells.Value = NumberToday
        Next i

    Range(rngCells, Cells(1, k)).NumberFormat = "m/d/yyyy" ' 1 bug out

    k = k + 1

    Next q

MsgBox (GetTickCount - StartTimer & " Milliseconds")

End Sub

Code without ActiveCells:

Sub UsingActivecell()

Application.ScreenUpdating = False

[A1].Select

NumberToday = 40000

Dim StartTimer As Long

StartTimer = GetTickCount

    For q = 1 To 26

        For i = 1 To 1000
        NumberToday = NumberToday + 1
        ActiveCell.Value = NumberToday
        ActiveCell.Offset(1, 0).Select
        Next i

ActiveCell.Offset(-1, 0).Select
Range(Selection, Selection.End(xlUp)).Select ' 3 issues with bug out, due to my incompitence
Selection.NumberFormat = "m/d/yyyy"

ActiveCell.Offset(0, 1).Select
ActiveCell.End(xlUp).Select

Next q

MsgBox (GetTickCount - StartTimer & " Milliseconds")

End Sub


texts:
I was just trying to make an alternate Ajax watermark from "insert date" (first mode) to "mm/dd/yyyy" (second mode). After some trial and error, I successfully implemented a solution using JavaScript.

How can I improve this script functionality?

JavaScript:

var original = "insert date";
var alternate = "mmddyyyy";
var countalerted = 0;
var txt = "";
var intird = 0;
if (intird == 0) {
    intrId = setInterval(function () { alterWaterMarkForDateTBX() }, 1000);
}
function SetIntervalTBX() {
    setInterval(function () { alterWaterMarkForDateTBX() }, 1000);
}

function alterWaterMarkForDateTBX() {
    var d = new Date();
    var t = d.toLocaleTimeString();

    if (countalerted < 4) {
        if (countalerted % 2 == 0) {
            document.forms["form1"].elements["TBXinsertDate"].value = original;
        }
        else {
            document.forms["form1"].elements["TBXinsertDate"].value = alternate;
        }
        countalerted++;
    }
    else {
        window.status = intrId;
        clearInterval(intrId);
//        document.forms["form1"].elements["TBXinsertDate"].value = original;
    }
}

var wasFocused = false;var wasBlur = false;
function Focus(objname, waterMarkText) {
    wasFocused = true;
    if (wasBlur == false) {
        obj = document.getElementById(objname);
        if (obj.value == waterMarkText) {
            obj.value = "";
            obj.className = "NormalTextBox";
            if (obj.value == original || obj.value == alternate || obj.value == "" || obj.value == null) {
                obj.style.color = "black";
            }
        }
    }
}

//i added "__/__/____" for the value of the ajax MaskEdit

function Blur(objname, waterMarkText) {
    wasBlur = true;
    var alternateWM1 = "insert date";
    var alternateWM2 = "mm/dd/yyyy";
    obj = document.getElementById(objname);
    if (obj.value == "" || obj.value == "__/__/____") {
        obj.value = waterMarkText;
        obj.className = "WaterMarkedTextBox";

    }
    else {
        obj.className = "NormalTextBox";
    }

    if (obj.value == original || obj.value == alternate || obj.value == "" || obj.value == null || obj.value == "__/__/____") {
        obj.style.color = "gray";
        if (wasFocused == true) {
            SetIntervalTBX();
        }
    }
}

ASPX / HTML

<form id="form1" runat="server">
    <asp:TextBox ID="TBXinsertDate" runat="server"
     ToolTip="date Box"  Width="79px"
     onfocus="Focus(this.id, this.value)"
     onblur="Blur(this.id, this.value)" >
    </asp:TextBox>
 </form>


texts: How to improve readability of a big lisp function

texts:
My main method (remove-random-edge) looks quite difficult to read. I'm new to list, so would appreciate any advice on how to improve the code.

(defun find-node (node graph)
  (find-if #'(lambda (i) (eql node (first i))) graph))

;; Input, graph, is in form ((from-1 to-1 to-2 to-3 ...)
;;                           (from-2 to-4 to-5 to-6 ...) ...)
;; where from-n and to-n are integers.
(defun remove-random-edge (graph)
  "Remove one random edge from a graph given as adjacency list."
  (let* ((node-list-1 (elt graph (random (length graph))))
         (node-1 (first node-list-1))
         (destinations (remove-duplicates (rest node-list-1)))
         (node-2 (elt destinations (random (length destinations))))
         (node-list-2 (find-node node-2 graph)))
    (flet ((replace-tail-for-head (node) (if (eql node node-2) node-1 node))
           (is-head-p (node) (eql node-1 node))
           (is-tail-p (node) (eql node-2 node))
           (starts-with-tail-p (nodes) (eql node-2 (first nodes))))
      (setf (rest node-list-1) (concatenate 'list
                                 (rest node-list-1)
                                 (remove-if #'is-head-p (rest node-list-2))))
      (loop for node in (remove-duplicates (rest node-list-2))
            with match
            with repcd
            do (setf match (find-node node graph))
            do (setf repcd (if (eql node node-1)
                             (remove-if #'is-tail-p (rest match))
                             (map 'list #'replace-tail-for-head (rest match))))
            do (setf (rest match) (sort repcd #'<)))
      (remove-if #'starts-with-tail-p graph))))

UPD: With review comments applied:

(defun remove-random-edge (graph)
  "Remove one random edge from a graph given as adjacency list."
  (let* ((head-list (elt graph (random (length graph))))
         (head (first head-list))
         (destinations (remove-duplicates (rest head-list)))
         (tail (elt destinations (random (length destinations))))
         (tail-list (assoc tail graph)))
    (flet ((replace-tail-for-head (node) (if (eql node tail) head node)))
      (setf (rest head-list) (concatenate 'list
                               (rest head-list)
                               (remove head (rest tail-list))))
      (loop for node in (remove-duplicates (rest tail-list))
            for match = (assoc node graph)
            do (setf (rest match) (if (eql node head)
                                    (remove tail (rest match))
                                    (mapcar #'replace-tail-for-head (rest match)))))
      (remove tail graph :key #'first))))

Before:

15.109 seconds of real time
50,245,719,578 processor cycles
767,039,256 bytes consed

After:

2.312 seconds of real time
7,665,669,728 processor cycles
778,172,816 bytes consed


texts: Object oriented, runtime expandable Sieve of Eratosthenes

texts:
In answering this question, it seemed to me that it would be nice to have a runtime expandable Sieve of Eratosthenes.  This is my implementation of that notion.

Design

I've created a class named Sieve which has two member functions:

unsigned Sieve::expand(unsigned upperlimit);

This expands the existing sieve up to the passed upper limit and attempts to minimize rework.  That is, if the current sieve has an upper limit of 10 and the expansion request is 15, the code only processes the difference, i.e. the half open range (10, 15].  If the new requested limit is smaller, the code simply returns without doing anything.

The other significant function is:

bool isPrime(unsigned n) const;

As one would expect, if n is not greater than the current upper limit, the returned bool is true if n is prime.  If n is greater than the current limit, this function throws a std::range_error.  The intent is that one could either catch an error or, better, always call expand before isPrime.  The reason for not combining those within the class code is that I wanted to create a complete but minimal interface.

The test code is simply a reinterpretation of the original code's interface.  Specifically, it expects one integer to be the number of test cases, T, and then for each test case, a lower and upper integer (m, and n).  For each test case, the code prints a list of prime numbers in the range [m, n] separated by spaces.  The test code assumes correct input and does not, for example, check to assure that m < n.

primes.cpp

#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <stdexcept>

class Sieve {
public:
    Sieve();
    unsigned expand(unsigned upperlimit);
    bool isPrime(unsigned n) const;
private:
    unsigned limit;
    std::vector<bool> composite;
};

Sieve::Sieve() :
    limit{0},
    composite{}
{}

bool Sieve::isPrime(unsigned n) const {
    if (n > limit)
        throw std::range_error("n must be less than limit");
    return n==2 || (n%2 && !composite[n/2]);
}

unsigned Sieve::expand(unsigned upperlimit) {
    if (upperlimit > limit) {
        composite.resize(upperlimit);
        composite[0] = true;  // 1 is not prime
        const unsigned sqrtLimit = std::ceil(std::sqrt(upperlimit));
        // std::cout << "old limit = " << limit << ", new limit = " << upperlimit << "\n";
        for (unsigned i = 3; i <= sqrtLimit; i+=2) {
            if (!composite[i/2]) {
                const unsigned start = i * std::max(i, (((limit+i)/i)|1));
                // std::cout << "Starting with i = " << i << ", from " << start << "\n";
                for (unsigned j = start; j <= upperlimit; j += i+i) {
                    composite[j/2] = true;
                    // std::cout << j << " is composite because it's a multiple of " << i << "\n";
                }
            }
        }
        limit = upperlimit;
    }
    return limit;
}

int main() {
    int T;
    int m, n;
    Sieve sieve;

    for (std::cin >> T; T; --T) {
        std::cin >> m >> n;
        sieve.expand(n);
        for (int i = m; i <= n; ++i) {
            if (sieve.isPrime(i)) {
                std::cout << i << ' ';
            }
        }
        std::cout << '\n';
    }
}

Results

When compiled on my 64-bit Linux machine with this command:

g++ -O2 $CXXFLAGS primes.cpp -o primes

I can then run and time the program with this:

time echo 4 1 13 40 50 80 90 10000000 10000100| ./primes

Here is the output:

2 3 5 7 11 13
41 43 47
83 89
10000019 10000079

real  0m0.044s
user  0m0.041s
sys   0m0.004s


texts: Converting a string into an array and returning the values spelled in reverse

texts:
I must create a function that accepts a string of names all separated by a comma.
Example: "Jack,Matthew,John,Sam"
And return the string of names in the same order but spelled in reverse.
Expected output: "kcaJ,wehttaM,nhoJ,maS"
I completed the function with an inner for loop but I would like to know if maybe running a single for loop and inside using a Linq function or something similar, would have been better?
public string Reverse(string s)
{
    var names = s.Split(",");
    string temp = "";

    for (int i = 0; i < names.Length; i++)
    {
        for (int j = names[i].Length - 1; j >= 0; j--)
        {
            temp += names[i].ElementAt(j);
        }
        temp += i == names.Length - 1 ? "" : ",";
    }

    return temp;
}

Anyway I found this problem very simple even though I tried taking my time on it, I found this solution almost immediately so I went with it. I am thinking maybe if I spent more time on it then I could have implemented this with some sort of Linq function to reverse the spelling of the names and removed the inner loop.
Really any suggestions for improving this small function is appreciated.


texts: Permutation-stream based n-queens solution

texts:
Following is a very crisp solution for solving n-queens problem in Racket programming language. The method is to get all permutations (so that no 2 queens are in same line) and to check these for any of them being on diagonals:

#lang racket

; FOLLOWING FN RETURNS TRUE IF QUEENS ARE ON DIAGONALS:
(define (check-diagonals bd)
  (for/or ((r1 (length bd)))
    (for/or ((r2 (range (add1 r1) (length bd))))
      (= (abs (- r1 r2))
         (abs(- (list-ref bd r1)
                (list-ref bd r2)))))))

; SET BOARD SIZE:
(define N 8)

; 3-LINE SEARCH LOOP:
(for ((brd (in-permutations (range N))))
  (when (not (check-diagonals brd))
    (displayln brd)))

The in-permutations function returns a stream sending one permutation at a time, so it does not find all permutations in advance.

Can this code be further improved to increase its speed for larger numbers, especially by parallelization or concurrency? Thanks for your help.

(PS: I have also posted this at https://stackoverflow.com/questions/46144576/parallel-running-of-racket-code)


texts: Cleaning address line data sent to couriers API

texts:
I've developed a client library to integrate with a couriers shipping API. The courier only accepts a limited set of characters for addresses, so I've created a helper class to strip out invalid characters and optionally replace them (with for example a ?).

public static class StringCleaner
{
    private static readonly char[] ValidCharacters =
    {
        ' ', '#', '&', '\'', '(', ')', '+', ',', '-', '.', '/',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        ':', '?', '@',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        '[', ']', '_', '`',
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        '{', '|', '}', '~',
    };

    public static string CleanString(string stringToClean, string replacement = "")
    {
        int length = stringToClean.Length;
        var newString = new StringBuilder();
        for (var i = 0; i < length; i++)
        {
            if (ValidCharacters.Contains(stringToClean[i]))
            {
                newString.Append(stringToClean[i]);
            }
            else
            {
                newString.Append(replacement);
            }
        }

        return newString.ToString();
    }
}


texts: Returning a collection inside of an IEnumerable method

texts:
The following scenario came out of a discussion I was having with a fellow developer on this project. He likes to execute an Ienumerable as soon as possible, hence why he’s doing it inside of the method. Whereas, I’m thinking that if you wait until the object is actually needed, using differed execution, you’re eliminating wasted objects in the memory.

Knowing that PricingInformation is a List, is my return statement consider best practice or not? Should I defer the execution to a later time? Or is it wise to ToArray() the Select during the return statement?

Which of these approaches do you guys think is more appropriate?

public IEnumerable<ProductPrice> GetPrices(IEnumerable<string> skus, string accountNumber)
{
    if (skus.Any())
    {
        TesscoModel.PricingQuery priceQuery = new TesscoModel.PricingQuery();
        foreach (string sku in skus)
            priceQuery.Skus.Add(new TesscoModel.SkuDetail() { Sku = sku, Quantity = 1 });
        priceQuery.Account = accountNumber;
        TesscoModel.PricingInformationBatch pricingInfoBatch = RestHelper.PostJsonAsync<TesscoModel.PricingInformationBatch>(Settings.PricingServiceEndpoint, priceQuery).Result;

        return pricingInfoBatch?.PricingInformation?.Select(pi => new ProductPrice { Sku = pi.Sku, Price = pi.OnSalePrice != default(decimal) ? pi.OnSalePrice : pi.UnitPrice, ListPrice = pi.ListPrice })?.ToArray() ?? Enumerable.Empty<ProductPrice>();
    }
    else
    {
        return Enumerable.Empty<ProductPrice>();
    }
}

This method then gets called by another method inside of a helper. Inside of which, I am using FirstOrDefault to find the first sku. FirstOrDefault is again an enumerator.

I think the differed execution is more appropriate here, because I shouldn't execute the pointer until I absolutely have to. I'm thinking that by using ToArray() too early, I'm keeping the object on memory for too long. Even though, it might not be needed.

//Get sku Pricing in bulk
IEnumerable<ProductPrice> productPrices = productService.GetPrices(skus, (!account.IsNull()) ? account.AccountNumber : string.Empty);

foreach (var line in lines)
{
    var productPrice = productPrices.FirstOrDefault(p => p.Sku.Equals(line.Sku));
    line.ListPrice = productPrice?.ListPrice ?? default(decimal);
    line.YourPrice = productPrice?.Price ?? default(decimal);
}


texts: Many-readers-one-writer with semaphores and multithreading

texts:
I've been looking for a solution to the may readers one writer in Java.
I was intrigued by this question posted here and I read the Wikipedia entry about it.

So far, I've reached a fine solution, or at least that's what I think. I've set up a new GitHub repo to put the code to be used in another project if people want. But I'm open to improvements and critics if you see fit.

The pseudocode of the main class is here:

abstract class AbsrtactReadersWriter<T> {

Semaphore readCountSempaphote = new Semaphore(1);
Semaphore resourceSemaphore = new Semaphore(1, true);
Semaphore serviceQueueSemaphore = new Semaphore(1,true);
int readCount = 0;

public final T read() {
    T data = null;
    try {
        // Entry to read
        serviceQueueSemaphore.acquire();
        readCountSempaphote.acquire();
        readCount++;
        if (readCount == 1){
            resourceSemaphore.acquire();
        }
        serviceQueueSemaphore.release();
        readCountSempaphote.release();
        // CRITICAL SECTION Do read
        data = executeReading();
        // Exit to read
        readCountSempaphote.acquire();
        readCount--;
        if (readCount == 0){
            resourceSemaphore.release();
        }
        readCountSempaphote.release();
    } catch (InterruptedException e) {
        System.out.println(e.getMessage());
    }
    return data;
  }

// Protected critical section that read the resource
abstract protected T executeReading();

public final void write(T data) {
    try {
        // Entry write
        serviceQueueSemaphore.acquire();
        resourceSemaphore.acquire();
        serviceQueueSemaphore.release();
        // CRITICAL SECTION  Do Write
        executeWriting(data);
        // Exit write
        resourceSemaphore.release();
    } catch (InterruptedException e) {
        System.out.println(e.getMessage());
    }
  }

// Protected critical section that writes to the resource
abstract protected void executeWriting(T data);

}

This pseudocode lacks some elements (privates, comments) form the class on the GitHub repo, but hits the point. In the repo, you can also see examples and tests.

The starvation problem on readers/writer is solved by Java itself, as the semaphores are created with the fair parameter, that forces the fairness of the blocking and a FIFO queue on the waiting threads. I use an AtomicInteger to store the readcount, even it's protected; the equality operation maybe not and doesn't impose a great penalty.

[EDIT1] As suggested by @greybeard I now use an integer and not an AtomicInteger. Code tested and changed into git


texts:
I have a script that alerts me via email when a partition grows past a defined threshold in one hour. My script is run from cron hourly. Everything seems fine for 99% of the time, but occasionally I get an email from my script stating that growth in the past hour is something like ".08%", well below my current threshold of 0.75%. Is something wrong with my logic?

#Drive to monitor
monDrive=/opt
#Enter a number .01-100. i.e 50 = 50%, and 0.5 = 1/2 of a percent.
percentThreshold=0.75
#Email address to send alerts to
emailAlert=alerts@domain.com

##Do not modify anything below this point
prevReading=/root/diskcheckreading.txt

checkDiskUse() {
        df "$monDrive" | awk 'END{printf "%0.2f",$2/$1*100; exit}'
}

checkDiskFree() {
        df "$monDrive" | awk 'END{printf "%0.2f",$3/1048576; exit}'
}

#Check if file exists with previous reading
[ -f $prevReading ] && prev=$(cat $prevReading) || { checkDiskUse > $prevReading; exit; }

#Validate file content
printf "%0.2f" "$prev" > /dev/null || exit

#Get current percentage used of monitored drive
current=$(checkDiskUse)

#Get current free capacity of monitored drive
diskFree=$(checkDiskFree)

#Calculate the difference
results=$(bc -l <<< $current-$prev )
#Check if the difference exceeds the threshold
if  [[ $results > $percentThreshold ]]
         then printf "\"$monDrive\" has grown $results%% in the past hour.     Remaining capacity on $monDrive is $diskFree GB.\n\n$(hostname):$(pwd)/$(basename $0)" | mail -s "Disk Alert - $(hostname):$monDrive" $emailAlert
fi

#log current reading for next check
echo $current > $prevReading


texts:
Introduction
This code was part of one of my projects where it was used to generate boolean input values for truth tables. I have since generalized it for combinations of variables with only 2 values, and added a dash of general Scala-isms. This has been unit-tested with ScalaTest, and has proper documentation.
I rewrote my original code which used bitmasking and shifts because I thought it was too "magical", i.e., difficult to understand at first glance. The bitmasking method also does not give a proper ordering of the values as I would have liked it, which this method does.
This also embodies the concept of a multi-line expression-bodied method.
Notes
My IDE (IntelliJ Idea) recommends not using superfluous parentheses, but I leave them in for clarity.
I would like reviews on any and all aspects of the code and documentation, including but not limited to performance (not really important over clarity to me here, otherwise I'd have used the bitmasking version instead), clarity and idiomatic nature of the code.
Running
Just copy into a file with extension .scala and run it in the Scala REPL as a script. Example usage:
allCombinations(4, true, false) // duplicates the use case I had in my project.

(Run the above in the REPL after the script as beem loaded (scala <file name>.scala, or put it at the bottom of the file <file name>.scala)

Code
/**
    * Generates all possible distinct combinations of `n` variables which have only 2 values,
    * `value` and `alternativeValue`.
    *
    * @param n                the number of variables to generate combinations for
    * @param value            one possible value for a variable
    * @param alternativeValue the other possible value for a variable
    * @return all possible distinct combinations of `n` booleans
    */
def allCombinations[T](n: Int, value: T, alternativeValue: T): Seq[Seq[T]] = {
    for (i <- 0 to n) yield {
      // Make the first i values true and the rest false,
      // and then take all their permutations.
      // This gives us all the required combinations.
      (Seq.tabulate(n)(x =>
                       if (x < i) value
                       else alternativeValue)
       ).permutations
    } // flatten 1 level into a 1-deep list
}.flatten


texts: Is there a way to make my Rock, Paper, Scissors game more concise?

texts:
I am learning JavaScript and I just wrote a Rock, Paper, Scissors game that will first prompt the two players for their choices and validate them. In the event of a tie, each player will choose their answer again and it will once again be validated. Everything works fine, but it feels like I have a lot of repetition going on here. Since I'm new to this, I can't figure out a way to make this more concise if possible.

var compare = function(choice1, choice2){
    while (choice1 != 'rock' && choice1 != 'paper' && choice1 != "scissors"){
        choice1 = prompt('Invalid entry. Player 1, please choose rock, paper, or scissors only');
    }
    while (choice2 != 'rock' && choice2 != 'paper' && choice2 != "scissors"){
        choice2 = prompt('Invalid entry. Player 2, please choose rock, paper, or scissors only');
    }
    while (choice1 == choice2){
        choice1 = prompt('Tiebreaker!. Player 1, please choose rock, paper, or scissors only');
     while (choice1 != 'rock' && choice1 != 'paper' && choice1 != "scissors"){
        choice1 = prompt('Invalid Entry. Player 1, please choose rock, paper, or scissors only');
        }
        choice2 = prompt('Tiebreaker!. Player 2, please choose rock, paper, or scissors only');
     while (choice2 != 'rock' && choice2 != 'paper' && choice2 != "scissors"){
        choice2 = prompt('Invalid Entry. Player 2, please choose rock, paper, or scissors only');
        }

    }
    if (choice1 == 'rock'){
        if (choice2 == 'scissors'){
            return 'rock wins';
        }
        else{
            return 'paper wins';
        }
    }
    if (choice1 == 'paper'){
        if (choice2 == 'rock'){
            return 'paper wins';
        }
        else{
            return 'scissors wins';
        }
    }
    if (choice1 == 'scissors' ){
        if (choice2 == 'rock'){
            return 'rock wins';
        }
        else{
            return 'scissors wins';
        }
    }
}


texts: Finding the relationship between two values

texts:
My code was made as an practice for CodeChef. Here's the brief from that page:

  Relational Operators are operators which check the relationship between two values.
  Given two numerical values A and B you need to help chef in finding the relationship between them that is:
  First one is greater than second or
  First one is less than second or
  First and second one are equal.

I couldn't submit the code because of an error so I'd like to see the criticism of the Code Review community.

package main;

import java.util.Scanner;

public class Method1 {
    public static float a, b, t;
    public static Scanner scanner;

    public static void main(String[] args) {
        scanner = new Scanner(System.in);
        System.out.println("Type your first Value please.");
        a = scanner.nextFloat();
        System.out.println("Type your second Value please.");
        b = scanner.nextFloat();
        if (a == b) {
            System.out.println('=');
        }
       if (a > b){
           System.out.println('>');
       }
       if (a < b){
           System.out.println("<");
       }
    }
}

I would like to note that I know its very basic and easy to make but its just a practice for me to see where I'm at in this kinda stuff.


texts: Java Implementation of linked list add(i, x) method

texts:
I'm currently trying to brush up on ADT implementations, specifically an implementation for a Linked List (I'm using Java 5 to do this).

Is this implementation I've written for add(i, x) correct and efficient?

public void add(int i, Object x) {

    // Possible Cases:
    //
    //     1. The list is non-empty, but the requested index is out of
    //        range (it must be from 0 to size(), inclusive)
    //
    //     2. The list itself is empty, which will only work if i = 0
    //
    // This implementation of add(i, x) relies on finding the node just before
    // the requested index i.

    // These will be used to traverse the list
    Node currentNode = head;
    int indexCounter = 0;

    // This will be used to mark the node before the requested index node
    int targetIndex = i - 1;

    // This is the new node to be inserted in the list
    Node newNode = new Node(x);

    if (currentNode != null) {

        while (indexCounter < targetIndex && currentNode.getNext() != null) {

            indexCounter++;
            currentNode = currentNode.getNext();
        }

        if (indexCounter == targetIndex) {

            newNode.setNext(currentNode.getNext());
            currentNode.setNext(newNode);

        } else if (i == 0) {

            newNode.setNext(head);
            head = newNode;
        }

    } else if (i == 0) {

        head = newNode;
    }
}