texts:
I'm not exactly sure if this is technically an "arena allocator" but it serves a similar purpose: providing a fast way to allocate a lot of objects that can all be freed at once.

#include <type_traits>
#include <utility>
#include <new>

template <std::size_t BlockSizeIn = 1024>
struct BlockProviderNewDelete
{
    static constexpr std::size_t BlockSize = BlockSizeIn;

    static void* allocateBlock()
    {
        return ::operator new(BlockSize);
    }
    static void freeBlock(void *block) noexcept
    {
        ::operator delete(block);
    }
};

template <class BlockProviderIn>
class ArenaAllocator
{
public:
    using BlockProvider = BlockProviderIn;

private:
    struct AllocBlock
    {
        AllocBlock *next;
        char mem[BlockProvider::BlockSize - sizeof(AllocBlock*)];
    };
    AllocBlock *base;
    AllocBlock *headBlock;
    std::size_t headIndex;

    void appendBlock()
    {
        AllocBlock *newBlock = static_cast<AllocBlock*>(BlockProvider::allocateBlock());
        newBlock->next = nullptr;
        headBlock->next = newBlock;
        headBlock = newBlock;
        headIndex = 0;
    }
    void nextBlock()
    {
        if(headBlock->next)
        {
            headBlock = headBlock->next;
            headIndex = 0;
        }
        else
            appendBlock();
    }

public:
    static constexpr std::size_t BlockSize = BlockProvider::BlockSize;
    static constexpr std::size_t MaxAllocationSize = sizeof(AllocBlock::mem);

    ArenaAllocator()
    {
        base = static_cast<AllocBlock*>(BlockProvider::allocateBlock());
        base->next = nullptr;
        headBlock = base;
        headIndex = 0;
    }
    ~ArenaAllocator()
    {
        AllocBlock *cur = base, *next;
        while(cur != nullptr)
        {
            next = cur->next;
            BlockProvider::freeBlock(cur);
            cur = next;
        }
    }

    void reset() noexcept
    {
        headBlock = base;
        headIndex = 0;
    }

    void* allocate(std::size_t s)
    {
        if(s == 0) s = 1;

        if(s > MaxAllocationSize)
            return nullptr;
        else if(s > MaxAllocationSize - headIndex)
            nextBlock();

        void *ptr = &headBlock->mem[headIndex];
        headIndex += s;
        if(headIndex >= MaxAllocationSize)
            nextBlock();

        return ptr;
    }

    template <typename T, typename... Args>
    T* construct(Args... args)
    {
        static_assert(std::is_trivially_destructible<T>::value, "Type must be trivially destructible!");
        static_assert(sizeof(T) <= MaxAllocationSize, "Type must not be larger than max allocation size!");

        T *result = static_cast<T*>(allocate(sizeof(T)));
        new (result) T(std::forward<Args>(args)...);
        return result;
    }
};

template <std::size_t BlockSize>
using ArenaAllocatorDefault = ArenaAllocator<BlockProviderNewDelete<BlockSize>>;

A caveat to this is that types allocated with the arena allocator must be trivially destructible (i.e. their memory must be reusable without destroying them first).

I'm already aware of one major issue: it doesn't consider alignment. However that's a fairly easy fix, so I'd like that to be ignored in the review. I'm mostly wondering whether this invokes any undefined behavior (other than due to ignoring memory alignment).

Here's an example of usage (this was to test if it leaked any blocks of memory or segfaulted. It didn't.):

// 2 MiB block size
ArenaAllocatorDefault<2097152> test;

for(size_t i = 0; i < 100000; ++i)
{
    for(size_t j = 0; j < 1000000; ++j)
    {
        test.construct<char[128]>();
    }
    test.reset();
}

Obviously you'd want to actually use the pointer returned by the construct() method for usual purposes but this was just for testing.


texts: Sed script that removes specific lines in `seq` output

texts:
I have a file to process with sed but I am not quite familiar with the commands with capital letters used for multi-line patterns. I use seq to test the script and I have converted it to the problem described below. The sed script and expected output are also attached. I believe the script can be written in a much better way but I am not sure how to do it.

Problem description:

  Filter the output of seq $m, where $m is a given integer. removing the \$n^{\rm th}\$ line if either \$n-2\$, \$n-1\$, \$n\$, or \$n+1\$ contains the digit \$7\$.

Sed script (together with the seq pipe, note this is GNU sed):

seq "$m"|sed ':c N;N;N;:a N;s/.*\n.*7.*\n.*\n.*\n//g;tc;P;s/^[^\n]*\n//g;ba;'

I believe setting two labels (a and c) is not necessary.

Edit: There seems to be a nicer alternative, based on the answer to Delete 5 Lines Before and 6 Liens After Pattern Match Using sed, as follows,

seq "$m"|sed 'N;/7/!{P;D};:b N;s/\n/&/3;Tb;d'

This avoids writing out a lot of N; and \n's explicitly. Still I believe it can be improved.

Sample output for m=100

1
2
3
4
5
10
11
12
13
14
15
20
21
22
23
24
25
30
31
32
33
34
35
40
41
42
43
44
45
50
51
52
53
54
55
60
61
62
63
64
65
82
83
84
85
90
91
92
93
94
95
100

Related: Extension of Game of Sevens Challenge at CodeGolf


texts: Rust code that reads two columns of data from .txt file

texts:
I'm writing a code to read data from text file in Rust. The target files have two columns and non-fixed length rows, for example,

example.txt

1  1
2  4
3  9
4  16

To achieve this, I wrote following code.

use std::fs::read_to_string;

pub fn open_file(filename: &str) -> (Vec<f32>, Vec<f32>){
    let data = read_to_string(filename);
    let xy = match data {
        Ok(content) => content,
        Err(error) => {panic!("Could not open or find file: {}", error);}
    };

    let xy_pairs: Vec<&str> = xy.trim().split("\n").collect();
    let mut x: Vec<f32> = Vec::new();
    let mut y: Vec<f32> = Vec::new();

    for pair in xy_pairs {
        let p: Vec<&str> = pair.trim().split(" ").collect();

        x.push(p[0].parse().unwrap());
        y.push(p[1].parse().unwrap());
    }

    (x, y)
}

I'm a beginner of Rust, so I don't know that I follow the best practice in Rust and this is the most efficient code.

I want some advice about this function.


texts: Remove Duplicates From Linked List In Place - Java

texts:
This is my implementation

class Ch02LinkedLists {
    void removeDuplicatesInPlace(Node head) {
        Node anchor = head;
        Node curr;

        while ((curr = anchor) != null) {
            while (curr.next != null)
                if (curr.next.val == anchor.val)
                    curr.next = curr.next.next;
                else
                    curr = curr.next;
            anchor = anchor.next;
        }
    }
}

class Node {
    char val;
    Node next;

    Node(char val) {
        this.val = val;
    }
}

And my test code

public class Ch02LinkedListsTest {

    Ch02LinkedLists linkedLists = new Ch02LinkedLists();

    @Test(timeout = 200) // Timeout to detect infinite loop
    public void removeDuplicatesInPlace() {
        Node a = new Node('a');
        Node a_dup = new Node('a');
        Node b = new Node('b');
        Node c = new Node('c');
        Node b_dup = new Node('b');
        Node b_dup_dup = new Node('b');
        Node c_dup = new Node('c');
        Node c_dup_dup = new Node('c');

        a.next = a_dup;
        a_dup.next = b;
        b.next = c;
        c.next = b_dup;
        b_dup.next = b_dup_dup;
        b_dup_dup.next = c_dup;
        c_dup.next = c_dup_dup;

        // a -> a -> b -> c -> b -> b -> c -> c
        linkedLists.removeDuplicatesInPlace(a);
        // a -> b -> c

        assertThat(a.val, equalTo('a'));
        assertThat(a.next.val, equalTo('b'));
        assertThat(a.next.next.val, equalTo('c'));
        assertThat(a.next.next.next, equalTo(null));
    }

}

As you see I have a single statement in my inner while hence no need for the curly braces..

while (curr.next != null)
    if (curr.next.val == anchor.val)
        curr.next = curr.next.next;
    else
        curr = curr.next;

Is there any way to achieve it for the outer loop, i.e. for:

while ((curr = anchor) != null) {
    // inner while here
    anchor = anchor.next;
}

so that I can remove the curly braces from the outer while as well?

Also, any other review is welcome.


texts:
I wrote this program in C to solve a given Sudoku puzzle (represented as 2D array) using backtracking algorithm. How can I make it more efficient, maybe faster and more C-onic?

This is my first post here, all suggestions are welcome! (be pedantic with me!)

#include <stdio.h>

#define GRID_SIZE 9

typedef int (*grid)[GRID_SIZE];
typedef struct { int x, y; } v2;

void dump(const grid board)
{
    int i, j;

    for (i = 0; i < GRID_SIZE; ++i)
    {
        for (j = 0; j < GRID_SIZE; ++j)
            printf("%d ", board[i][j]);
        puts("");
    }
}

int possible(const grid board, const v2 pos, const int v)
{
    int i, j, x0, y0;

    for (i = 0; i < GRID_SIZE; ++i)
        if (board[pos.y][i] == v)
            return 0;
    for (i = 0; i < GRID_SIZE; ++i)
        if (board[i][pos.x] == v)
            return 0;

    x0 = (pos.x / 3) * 3;
    y0 = (pos.y / 3) * 3;

    for (i = 0; i < 3; ++i)
        for (j = 0; j < 3; ++j)
            if (board[i + y0][j + x0] == v)
                return 0;

    return 1;
}

void solve(grid board)
{
    int y, x, v;

    for (y = 0; y < GRID_SIZE; ++y)
        for (x = 0; x < GRID_SIZE; ++x)
            if (board[y][x] == 0)
            {
                for (v = 1; v < 10; ++v)
                {
                    const v2 pos = {x, y};
                    if (possible(board, pos, v))
                    {
                        board[y][x] = v;
                        solve(board);
                        board[y][x] = 0;
                    }
                }
                return;
            }

    dump(board);
}

int main(void)
{
    /* 0 represents an empty cell */
    int board[GRID_SIZE][GRID_SIZE] =
    {
        {7, 0, 0, 0, 0, 1, 0, 0, 3},
        {0, 0, 3, 0, 0, 2, 6, 0, 0},
        {0, 2, 0, 7, 0, 8, 0, 0, 5},
        {0, 6, 0, 0, 1, 0, 3, 7, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 1, 5, 0, 7, 0, 0, 6, 0},
        {3, 0, 0, 2, 0, 4, 0, 5, 0},
        {0, 0, 8, 5, 0, 0, 7, 0, 0},
        {5, 0, 0, 1, 0, 0, 0, 0, 9},
    };

    solve(board);

    return 0;
}


texts: Avoid existSync function on Node.js - Express API controller

texts:
I have many json files that I want to serve through an API. The json files look something like this:

...
170102.json
170103.json
170104.json
170108.json
170109.json
170120.json
...

The name of each file is the date in the format 'yymmdd.json'. There are a lot of files missing, so if a user ask for a file that is not present, the data from the most recent previous file must be served. For example, with the above files, if someone ask for the data from date 2017-01-07, he should get the data from file 170104.json. But if the gap between files is greater than five, then no data should be provided. With the previous files if someone request for the data from date 2017-01-20, then a 404 error should be return.

I have this controller which does the job, but I'm concern that it is using the existSync function and therefore blocking the node process (the end point is localhost:3000/api/:year/:month/:day):

import fs from 'fs';
import path from 'path';

const getData = (req, res) => {
  const {
    year,
    month,
    day,
  } = req.params;
  const date = new Date(`${year}/${month}/${day}`);
  let fileDate = date.toISOString().substring(2, 10).replace(/-/g, '');
  let jsonFile = path.join(__dirname, 'data', `${fileDate}.json`);

  for (let i = 1; i <= 5; i += 1) {
    if (fs.existsSync(jsonFile)) {
      break;
    } else {
      date.setDate(date.getDate() - 1);
      fileDate = date.toISOString().substring(2, 10).replace(/-/g, '');
      jsonFile = path.join(__dirname, 'data', `${fileDate}.json`);
    }
  }

  fs.readFile(jsonFile, 'UTF-8', (err, data) => {
    if (err) {
      res.status(404).send('Not found');
    } else {
      res.json(JSON.parse(data));
    }
  });
};

export default getData;

// this is routes.js

import getData from '../controllers/apiController';

const routes = (app) => {
  app.route('/api/:year/:month/:day')
    .get(getData);
};

export default routes;

How can I improve this to be non blocking, or improve it's quality or performance overall? I'm learning nodejs and express and trying to grasp all of its best features, but having a hard time getting my head around the async functions, so any advice to improve this in that direction is very welcome.


texts:
I'm in the process of learning SQLite in C# and I've come up with some generic methods for finding and updating data. I would appreciate any pointers with the design of my methods and/or my SQL syntax.

FYI: I'm using System.Data and Mono.Data.SqliteClientfor C# Mono 2.0 (Unity3D).

Here is an example of the database used for this post. Let's also assume that I check for null prior to obtaining/updating data.

Info - Table name

    | display_name | coins | total_score |
    |    Michael   |  100  |    1356     |
    |     John     |   50  |     904     |

Below is my FindData method, which is used to lookup data in a specified table.

    public object FindData (string tableName, string selectHeader, string whereHeader, object whereValue)
    {
        using (var dbConnection = new SqliteConnection ("URI=file:" + Application.dataPath + connection))
        {
            dbConnection.Open ();

            using (var dbCommand = dbConnection.CreateCommand ())
            {
                dbCommand.CommandText = string.Format ("SELECT {0} " +
                                                       "FROM {1} " +
                                                       "WHERE {2} = @whereValue", selectHeader, tableName, whereHeader);

                SqliteParameter whereParam = new SqliteParameter ("@whereValue", whereValue);
                dbCommand.Parameters.Add (whereParam);

                using (var dbReader = dbCommand.ExecuteReader ())
                {
                    while (dbReader.Read ())
                    {
                        if (dbReader.GetValue (0) != null)
                            return dbReader.GetValue (0);
                    }
                }
            }
        }
        return null;
    }

I attempted to have SQL Injection prevention parameters for tableName, selectHeader and whereHeader, however, it kept throwing an error saying the syntax was wrong. I'm assuming this can't be done then.

That method can be used like so:

int coins = (int)FindData ("Info", "coins", "display_name", "Michael");

This attempts to obtain the value under column coins, from the table Info where the display_name column is equal to Michael

Next I have the UpdateData method. This is used to update/save the data in the specified table.

public void UpdateData (string tableName, string whereHeader, object whereValue, string setHeader, object setValue)
{
    using (var dbConnection = new SqliteConnection ("URI=file:" + Application.dataPath + connection))
    {
        dbConnection.Open ();

        using (var dbCommand = dbConnection.CreateCommand ())
        {

            dbCommand.CommandText = string.Format ("UPDATE {0} " +
                                                   "SET {1} = @setValue " +
                                                   "WHERE {2} = @whereValue",
                tableName, setHeader, whereHeader);

            SqliteParameter setParam = new SqliteParameter ("@setValue", setValue);
            SqliteParameter whereParam = new SqliteParameter ("@whereValue", whereValue);

            dbCommand.Parameters.Add (setParam);
            dbCommand.Parameters.Add (whereParam);

            Debug.Log (dbCommand.CommandText);

            dbCommand.ExecuteNonQuery ();
        }
    }
}

This method can be used like so:

UpdateData ("Info", "display_name", character.displayName, "coins", character.coins);

This method attempts to update the Info table, based on the column displayName, which equals character.displayName, which then updates the coins column based on the character.coins variable

Can anyone provide any criticism/advice on these generic methods for saving and loading data from a Sqlite database.


texts: Project Euler 21: Sum of amicable numbers optimisation

texts:
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
  If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

  For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

  Evaluate the sum of all the amicable numbers under 10000.

I have the following code which I know works, but is very slow for large numbers.

import time
start = time.time()

n = int(input("Enter a number"))

def factor(c):
    factors = []
    for d in range(1, int(c / 2) + 1):
        if c % d == 0:
            factors.append(d)
    return sum(factors)

def sum_ammicable(x):
    ammicable = set()
    for a in range(1, x):
        for b in range(1, x):
            if a != b:
                if factor(a) == b and factor(b) == a:
                    ammicable.update([a,b])
    return sum(ammicable)

print(sum_ammicable(n))

end = time.time()
print(end -start)

How can I optimise this code


texts: Correct usage of alignas in std::ostringstream wrapper

texts:
Please take a look at this code:

class error_stream: boost::noncopyable
{
public:
    template<typename T>
    std::ostream& operator<<(T&& arg)
    {
        return strm() << std::forward<T>(arg);
    }
    std::string str() { return strm().str(); }
    bool empty() const { return !holder_.valid(); }
private:
    std::ostringstream& strm() { return holder_; }
    struct alignas(std::ostringstream) holder
    {
        holder(): ptr_{} {}
        ~holder()
        {
            if(valid())
                ptr_->~basic_ostringstream();
        }
        operator std::ostringstream&()
        {
            if(!valid())
                ptr_ = new (memory_) std::ostringstream{};
            return *ptr_;
        }
        bool valid() const { return ptr_; }
    private:
        char memory_[sizeof(std::ostringstream)];
        std::ostringstream* ptr_;
    } holder_;
};

Here I want to avoid creating std::ostringstream if there was no output made into it:

error_stream strm;
//strm << "...";
if(!strm.empty())
{
    //...get strm.str();
}

I use placement new/delete when a client outputs something into the stream. Do I need to use alingas for block of memory that will hold instance of std::ostringstream?

UPDATE: To give more context - this is part of THROW wrapper:

...
#define THROW_EX_WITH_LOCATION(EXCEPTION, LOCATION)                \
    for(error_stream strm;;                                        \
        strm.empty()?                                              \
            throw_exception<EXCEPTION>(LOCATION):                  \
            throw_exception<EXCEPTION>(LOCATION, strm.str()))      \
        strm
...

I don't want to create any stream if ther is no error message but solution should work with minumum overhead over version with just std::ostringstream.

Consider the following cases:

THROW();

and

THROW() << "some error";

I agree this looks like nitpicking.


texts:
I have following code for a library management system.

Is the following code a proper implementation of the Repository Pattern?
How can I adapt this code to use generics?
Should I let MyOracleReservationRepository and MyOracleBookRepository be  DataContracts if I am consuming this code as a WCF service (business Layer will be called by service layer)?

Business Layer

namespace LibraryBL
{
    public class ReservationManager
    {
        //LibraryDAL.ReservationDAL resDAL = new LibraryDAL.ReservationDAL();
        //LibraryDAL.BookDAL bookDAL = new LibraryDAL.BookDAL();

        LibraryRepository.IReservationRepository reservationRepository;
        LibraryRepository.IBookRepository bookRepository;

        public ReservationManager(LibraryRepository.IReservationRepository resRepositroy, LibraryRepository.IBookRepository bookRepositroy)
        {
            reservationRepository = resRepositroy;
            bookRepository = bookRepositroy;
        }

        public List<LibraryDTO.Reservation> GetAllReservations()
        {

            List<LibraryDTO.Reservation> allReservations = reservationRepository.GetAllReservations();

            //Book object inside allReservations has two values as NULL (author and BookTitile).
            //These values need to be set using foreach loop
            foreach (LibraryDTO.Reservation reservation in allReservations)
            {
                int bookID =reservation.ReservedBook.BookID;
                LibraryDTO.Book book = bookRepository.GetBookByID(bookID);
                reservation.ReservedBook = book;
            }
            return allReservations;
        }

    }

}

Repository

namespace LibraryRepository
{
    public interface IReservationRepository
    {
        List<LibraryDTO.Reservation> GetAllReservations();
    }

    public interface IBookRepository
    {
        LibraryDTO.Book GetBookByID(int bookID);
    }

    public class MyOracleReservationRepository : IReservationRepository
    {
        public List<LibraryDTO.Reservation> GetAllReservations()
        {
            int databaseValueResID1 = 1;
            DateTime databaseValueResDate1 = System.Convert.ToDateTime("1/1/2001");
            int databaseValueResBookID1 = 101;

            List<LibraryDTO.Reservation> reservations = new List<LibraryDTO.Reservation>();

            LibraryDTO.Reservation res = new LibraryDTO.Reservation();
            res.ReservationID = databaseValueResID1;
            res.ReservedDate = databaseValueResDate1;
            res.ReservedBook = new LibraryDTO.Book();
            res.ReservedBook.BookID = databaseValueResBookID1;
            res.ReservedBook.Author = null; //Set as null as we don't have values in Reservation DAL
            res.ReservedBook.BookTitle = null; //Set as null as we don't have values in Reservation DAL

            reservations.Add(res);
            return reservations;
        }
    }

    public class MyOracleBookRepository : IBookRepository
    {
        public LibraryDTO.Book GetBookByID(int bookID)
        {
            LibraryDTO.Book book = null;
            if (bookID == 101)
            {
                book = new LibraryDTO.Book();
                book.BookID = 101;
                book.Author = "First Author";
                book.BookTitle = "Book 1";
            }
            return book;
        }
    }
}


texts:
I have updated the code and the program now works as it should. If you could critique my code that would be great. I am new to C so I guess I will have made some rookie error :)

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

// Function to check if alphabet characters.
int alphaCheck(char * argv[]) {
  int length = strlen(argv[1]), n;
  for (n = 0; n < length; n++) {
    if (!isalpha(argv[1][n])) {
      printf("Characters 'A-Z' for Keyword.\n");
      return 2;
    }
  }
}

int main(int argc, char * keyWord[]) {
  int cipher[64], i, j, k;
  char message[128];
  int keyCount = 0;
  int p = strlen(keyWord[1]);

  // Validation - using alphaCheck Function
  if (argc != 2 || alphaCheck(keyWord) == 2) {
    return 0;
  }

  // For loop to convert to upper and set value ie A = 0 B = 1
  for (i = 0, j = strlen(keyWord[1]); i < j; i++) {
    cipher[i] = (toupper(keyWord[1][i]) - 65);
  }

  // Prompt the user for the message to encrypt
  printf("Enter your secret message: ");
  fgets(message, 128, stdin);

  for (i = 0, k = strlen(message); i < k; i++) {
    if (isupper(message[i])) {
      char c = (message[i] - 65 + cipher[keyCount])  % 26 + 65;
      printf("%c", c);
      keyCount++;
    }
    else if (islower(message[i])) {
      char d = (message[i] - 97 + cipher[keyCount]) % 26 + 97;
      printf("%c", d);
      keyCount++;
    }
    else {
      printf("%c\n", message[i]);
    }
    if (keyCount >= p) {
      keyCount = 0;
    }
  }
}


texts: My Calendar generation code is slow. How do I improve it?

texts:
I have a model I have created to generate iCal and the necessary JSON for the jQuery calendar plugin Full Calendar to work. When I display the page, the JSON generation takes about 7 seconds. The query itself has been running in only a few microseconds. So I know my code is the problem.

I was trying to get the format like what Full Calendar expects thus why I wrote the code how I did. My guess is that the below is the problem. Any thoughts on where I can improve this?

#region Event
public class Event
{
    public string Title { set; get; }
    public string Description { set; get; }
    public string URL { set; get; }
    public string UID { set; get; }
    public DateTime DateTimeStamp { set; get; }
    public DateTime CreatedDateTime { set; get; }
    public DateTime Start { set; get; }
    public DateTime End { set; get; }
    public bool AllDay { set; get; }
}
#endregion

public class Calendar
{
    #region Model
    public string CalendarName { set; get; }
    public string Product { set; get; }
    public string TimeZone { set; get; }
    public List<Event> Events { private set; get; }
    #endregion

    /// <summary>
    /// Creates a calendar json string.
    /// </summary>
    /// <returns></returns>
    public string ToFullCalendarJsonString()
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("[");

        int count = Events.Count;
        int i = 0;

        foreach (Event eventItem in Events)
        {
            sb.Append("{");
            sb.AppendFormat("\"title\":\"{0}\",", eventItem.Title);
            sb.AppendFormat("\"allDay\":\"{0}\",", eventItem.AllDay);

            if (eventItem.AllDay)
            {
                sb.AppendFormat("\"start\":\"{0}T00:00:00\",", eventItem.Start.ToString("yyyy-MM-dd"));
                sb.AppendFormat("\"end\":\"{0}T00:00:00\",", eventItem.End.ToString("yyyy-MM-dd"));
            }
            else
            {
                sb.AppendFormat("\"start\":\"{0}T{1}\",", eventItem.Start.ToString("yyyy-MM-dd"), eventItem.Start.ToString("HH:mm:ss"));
                sb.AppendFormat("\"end\":\"{0}T{1}\",", eventItem.End.ToString("yyyy-MM-dd"), eventItem.End.ToString("HH:mm:ss"));
            }
            sb.AppendFormat("\"url\":\"{0}\"", eventItem.URL);
            sb.Append("}");

            i++;

            if (i < count)
            {
                sb.Append(",");
            }
        }

        sb.Append("]");

        return sb.ToString();
    }


texts: Java implementation of the Factory Method pattern

texts:
I am working on a very simple game and thought it would be a good opportunity to learn and use the Factory Method pattern for creating game objects. I studied the pattern but I'm a bit confused about the Java implementation so thought I would share what I have come up with and get some opinions.

Please keep in mind that I am basing this design on the example from "Design Patterns... by the GOF" so we will use the following pieces: Product, ConcreteProduct, Creator, and ConcreteCreator.

Product (Interface for Game Objects)

public interface GameObject {
   public abstract void doSomeStuff();
}

ConcreteProducts (Implements Product Interface, 1 for each Game Object)

public class PlayerImpl implements GameObject {
    @Override
    public void doSomeStuff() {
        System.out.println("I am a player object!");
    }
}

public class EnemyImpl implements GameObject {
    @Override
    public void doSomeStuff() {
        System.out.println("I am an Enemy, you better run!");
    }
}

Creator (Interface that defines how to create objects)

This is the one I'm most confused about, seems un-necessary unless instead of an Interface it was some Abstract class, but even then seems kind of pointless to use a Creator in this design pattern?

 public interface GameObjectFactory {
    public abstract GameObject createGameObject(GameObjectFactoryImpl.Type type);
}

ConcreteCreator (Implements Creator, creates objects)

The ConcreteCreator will have a nested enumeration to help the client decide which player types are available. We will throw an exception if for some reason there is a game object type in the enumeration that is not handled in the factory method.

public class GameObjectFactoryImpl implements GameObjectFactory{

    // A helper enum that clients will use to create game objects
    public enum Type {
        PLAYER, ENEMY;
    }

    public GameObject createGameObject(GameObjectFactoryImpl.Type type) {

        switch (type) {
        case PLAYER:
            return new PlayerImpl();
        case ENEMY:
            return new EnemyImpl();
        default:
            throw new RuntimeException("Unsupported object type!");
        }

    }
}

Client

public class Game {

    private static GameObjectFactory gameObjectFactory = new GameObjectFactoryImpl();

    public static void main(String args[]){

        GameObject player = gameObjectFactory.createGameObject(GameObjectFactoryImpl.Type.PLAYER);
        GameObject enemy = gameObjectFactory.createGameObject(GameObjectFactoryImpl.Type.ENEMY);

        player.doSomeStuff();
        enemy.doSomeStuff();
    }

}


texts: Finding (and counting) duplicate JS/Java files

texts:
I have the following script which takes minutes to give output.

printf "\nDuplicate JS Filenames...\n"
(
  find . -name '*.js' -type f -exec basename {} \; | sort | uniq -c | grep -v "^[ \t]*1 ";
  echo "$(find . -type f -name '*.js' | wc -l) JS files in search directory";
  echo "$(find . -name '*.js' -type f -exec basename {} \; | sort | uniq -c | grep -v "^[ \t]*1 " | wc -l) duplicates found";
)

printf "\nDuplicate Java Filenames...\n"
(
  find . -name '*.java' -type f -exec basename {} \; | sort | uniq -c | grep -v "^[ \t]*1 ";
  echo "$(find . -type f -name '*.java' | wc -l) Java files in search directory";
  echo "$(find . -name '*.java' -type f -exec basename {} \; | sort | uniq -c | grep -v "^[ \t]*1 " | wc -l) duplicates found";
)

I know that I make the same request, or similar ones, a couple of times.

How could I optimize this, and maybe already the base command - I'm surprised that find takes so long, or is it due to sort, uniq, and grep?


texts:
Problem 3 - Largest prime factor

Exercise

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

My solution

package pl.hubot.projecteuler.problem3;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.print(Collections.max(primeFactors()));
    }

    private static List<Long> primeFactors() {
        long n = 600851475143L;
        List<Long> factors = new ArrayList<>();
        for (long i = 2; i <= n; i++) {
            while (n % i == 0) {
                factors.add(i);
                n /= i;
            }
        }
        return factors;
    }
}

I would like ask review for my code and possible improvements. I am interested how is performance of my code.


texts: Extraction of numbers from currency string

texts:
I have the following code; whereas currency and views are in reality many JSON objects from an SAP export, that I can not rely upon to be in the same format. That is why I'm regexing over these inputs. My code looks clumsy to me. Can it be improved?

var currency = "20.002,03 €"; // sometimes this String is "-" or " "
var views    = "38";          // sometimes this String is "-" or " "

var reDigit = /[\d\,\.]+/g;
var map = {',':'.', '.':''};

if (typeof currency != 'undefined' && typeof views != 'undefined') {

    currency = currency.match(reDigit);
    views = views.match(reDigit);

    if (currency != null && views != null ) {

        currency = currency[0];
        views = views[0];

        currency = currency.replace(/[,.]/g, function(k) {
            return map[k];
        });
        return currency / views;
    } else {
        return undefined;
    };
} else {
    return undefined;
}

In the currency variable, dots need to get eliminated and commas turned into floating points. I need to cater for cases when currency and views variables do not have a number in their string or do have a dash or a blank in them.

Would you say this script can be optimsed to be more efficient?


texts: Nesting of paragraph with headings and cite with dynamic content in a VueJS app

texts:
Background

I added a few items to a codepen that displayed a list of beers. One of them was the citation of the brewer who gave tips. Previously the tips were just generated into a
 but now I have wrapped it inside a blockquote

Code

    Tips from the brewer:
    "{{ beer.tips }}"

      &ndash; {{ beer.contributor }}
      <a style="color: white" :href="`https://www.twitter.com/${beer.twitter}`" target="_blank">{{beer.twitter}}

Demo

My working demo is available on CodePen


texts: Constructing entities from API with foreign keys

texts:
I'm loading three kinds of entities from an API (in csv format unfortunately). While the first two are fine, the third has foreign keys to both of them. What I'm currently doing is constructing the first two lists and then while constructing the third list I assign the entities for every item. This is how it looks:

var platforms = await Task.Run(() => parsed.Data.Select(p => CreatePlatform(p,stations,lines)).ToList());

private static Platform CreatePlatform(Dictionary<string, string> data, List<Station> stations, List<Line> lines)
    {
        if (data.Keys.Except(PlatformFields).Any())
            return null; // TODO log; invalid data format
        Platform platform = null;
        try
        {
            platform = new Platform
            {
                SteigId = Convert.ToInt32(data["STEIG_ID"]),
                Richtung = data["RICHTUNG"],
                Reihenfolge = Convert.ToInt32(data["REIHENFOLGE"]),
                RblNummer = string.IsNullOrEmpty(data["RBL_NUMMER"]) ? null : (int?) Convert.ToInt32(data["RBL_NUMMER"]),
                Bereich = string.IsNullOrEmpty(data["BEREICH"])? null : (int?) Convert.ToInt32(data["BEREICH"]),
                Steig = data["STEIG"],
                SteigWgs84Lat = Convert.ToDouble(data["STEIG_WGS84_LAT"]),
                SteigWgs84Lon = Convert.ToDouble(data["STEIG_WGS84_LON"]),
                Stand = data["STAND"],

                Station = stations.Single(s => s.HaltestellenId == Convert.ToInt32(data["FK_HALTESTELLEN_ID"])),
                Line = lines.Single(l => l.LinienId == Convert.ToInt32(data["FK_LINIEN_ID"]))

            };
        }
        catch (FormatException ex)
        {
            return null; // TODO log;
        }
        return platform;
    }

Stations and Lines are sets that have been constructed in the exact same way (only without fk's). Hirarchy-wise I want the Stations to include a list of plattforms and each platform has the corresponding line. I also get this using the current method as entity framework handles the dependencies.

My problem is that this method of runnig two selects for every Platform item takes multiple seconds and i'm using this data for input suggestions which i'd like to be available as soon as possible

Is there a more efficient way of assigning the correct dependencies?

If there's some important information missing please tell me


texts:
Last Friday I was hit with a sorting interview question that I never really had to deal with.

  Develop a your own sorting algorithm.

  It cannot use any other Classes for help.
  It needs to be able to sort an array of millions of integers in size.
  It needs to be as fast as possible.

For instance:

int[] old = {5434, 3454, 2, 0, 356, 896, 7324, 888, 99, 78365, 111};
int highestNumber = 78365;

Would be

int[] new = {0, 2, 99, 111, 356, 888, 896, 3454, 5434, 7324, 78365};

I spent the night trying to come up with my own method to do this. And this is what I came up with.

public class Main {
    public static void main(String[] args) {
        int[] twentyMillion = new int [20000000];
        for (int i = 0; i < a.length; i++) {
            twentyMillion [i] = new Random().nextInt(20000000);
        }
        sortByAccendPro(twentyMillion , 20000000);
    }

    /**
     * Jasz sort algorithim.
     *
     * @param {int[]} twentyMillion - array of twenty million random ints.
     * @param {int} highestNumber - Highest number to sort to.
     */
    public void sortByAccendPro(int[] twentyMillion, int highestNumber ) {
        int[] rangePosition = new int[twentyMillion.length];
        int[] newArray = new int[twentyMillion.length];
        int[] range = new int[highestNumber];
        long time = System.nanoTime();
        for (int i = 0; i < twentyMillion.length; i++) {
            rangePosition[i] = twentyMillion[i];
            range[twentyMillion[i]]++;
        }
        for (int i = range.length - 1, past = twentyMillion.length; i >= 0; i--) {
            range[i] = past - range[i];
            past = range[i];
        }
        for (int i = 0; i < twentyMillion.length; i++) {
            newArray[range[rangePosition[i]]] = twentyMillion[i];
            range[rangePosition[i]]++;
        }
        System.out.println("time = " + (System.nanoTime() - time));
    }
}

Steps:

The first loop has the range of numbers. For instance, if the rangeArray goes from 0 to 3,000,000, it increments every case of each number it finds in that array. So every time it finds 2,750,000 it increments that position in the rangeArray.
The second loop works backwards from the max position in the rangeArray. So if the size is 3,000,000 and it has 100,000 cases of 3,000,000 it says that 3,000,000 will start at 2,900,000 and go to the max.
The 3rd loop loops back through the main array grabbing the same index in the range array and plugging the number in the correct position in the newArray.

It handles duplicates and with a little tinkering you can make it sort many other things. It uses more memory than I wanted in order to do sorting but wow its lightening fast. I never thought of looking into how these sorting algorithms work until I did this but can find nothing to compare it to.

What algorithm does this resemble and what can I do to make it better?


texts: Getting a substring of a string in JavaScript

texts:
I can have one of the following strings:

var username = "i:0#.f|myprovider|domain\\myuser"
var username2 = "myprovider|domain\\myuser"
var username3 = "myuser"

I always want only the myuser part of the string!

I tried the following in JS

var n = username.lastIndexOf('|');
var domainandusername = username.substring(n + 1);
var m = domainandusername.lastIndexOf('"\\"');
var username = domainandusername.substring(m + 1);

I have tried it within a simple page with JS and it seems to work. But is this a good way to solve this? I mean is it a good practice even to do this for string username2 and username3 where I know that they, for example, do not have a | and \\?


texts: Monte Carlo simulation of amoeba population

texts:
I wrote a simple Python simulation to answer the "Amoeba" population question posed here:

  A population of amoebas starts with 1. After 1 period that amoeba can divide into 1, 2, 3, or 0 (it can die) with equal probability. What is the probability that the entire population dies out eventually?

The script seems to work fine, but then I started playing with it to investigate curious effects.

If the number of trial generations is too large (num_generations_per_trial), I have problems with performance - the population size gets huge, and the simulation either runs slow or I encounter OverflowError on my brute force FOR loops.

I would appreciate feedback on efficiency options, and also on general code improvements.  I know the runs are independent and could be run in parallel. But that is still sort of brute force. I am curious more about making a single thread approach faster.

from __future__ import division
import random
import math
import time

def run_trial(max_split, num_generations):
    population = 1
    for generation in xrange(num_generations):
        for amoeba in xrange(population):
            amoeba_split = random.randint(0, max_split)
            population -= 1  # remove current amoeba (she will split or die)
            population += amoeba_split

        if population == 0:
            break
    return population

def main():
    extinct_counter = 0
    trials = 10000

    max_split_per_amoeba = 3
    num_generations_per_trial = 20 # populations can get *massive* as generations increase (memory / overflow errors at 100)

    print '***starting simulation***'
    print 'num trials: %i' % (trials)
    print 'max_split_per_amoeba: %i' % (max_split_per_amoeba)
    print 'num_generations_per_trial: %i' % (num_generations_per_trial)

    for trial in xrange(trials):
        outcome_population = run_trial(max_split_per_amoeba, num_generations_per_trial)
        if outcome_population == 0:
            extinct_counter += 1

        if divmod(trial+1, max(1,int(trials/20)))[1] == 0:
            print 'progress: %i trials complete | %i extinction counter | %.4f extinction probability' %  (trial+1, extinct_counter, extinct_counter/(trial+1))

    print 'extinct outcomes: %i' % (extinct_counter)
    print 'total trials: %i' % (trials)

    extinction_probability = extinct_counter / trials
    print 'extinction probability: %.4f' % (extinction_probability)

    expected_answer = math.sqrt(2)- 1
    print 'expected probability: %.4f' % (expected_answer)
    print 'delta from answer: %.4f' % (extinction_probability - expected_answer)

if __name__ == '__main__':
    start = time.clock()
    main()
    print 'runtime: %.3f s' % (time.clock() - start)
    print 'done'


texts:
Below is my code for the problem 1.4 in CTCI. I would like a review of my code and if my approach to the problem is correct.

Problem Statement:
Palindrome Permutation: Given a string, write a function to check if it is a permutation of
a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A
permutation is a rearrangement of letters. The palindrome does not need to be limited to just
dictionary words.

EXAMPLE

Input: Tact Coa

Output: True (permutations:"taco cat'; "atco cta'; etc.)

My Solution (Python):

def checkPalindromeAndPermutation(inputstr):
    lengthOfInputString = len(inputstr)
    counterforodd = 0
    actualCharactersInInput = 0
    inputstr = inputstr.lower()
    hashTable = dict()

    for i in inputstr:
        if i != " ":
            hashTable[i] = hashTable.get(i, 0) + 1
            actualCharactersInInput = actualCharactersInInput + 1
    print(hashTable)

    for item in hashTable:
        # if input has even length, but each character's frequency is not even, then it's not a plaindrome
        if actualCharactersInInput % 2 == 0 and hashTable[item] % 2 != 0:
            return False
        # if input has odd length, but more than one character's frequency is greater than 1 , then it's not a plaindrome
        if actualCharactersInInput % 2 == 1 and hashTable[item] % 2 == 1:
            counterforodd = counterforodd + 1
            if counterforodd > 1:
                return False
    return True

print("Answer : " , checkPalindromeAndPermutation("abc bac"))


texts: How to (and should I) avoid repetition while assigning values from different sources?

texts:
In a Mako template partial I accept an argument (step) that can be an instance of Step class, a dict or None. Can I in some way avoid repetition or do the check in other more 'pythonic' way? Or how could I gracefully avoid checking types at all?

<%include file="_step.mako" args="step=step" />

and then in _step.mako:

<%page args="step"/>
<%! from package.models.recipe import Step %>
<%
if isinstance(step, Step):
    number = step.number
    time_value = step.time_value
    text = step.text
elif type(step) is dict:
    number = step['number']
    time_value = step['time_value']
    text = step['text']
else:
    number = 1
    time_value = ''
    text = ''
%>


texts: Fastest way to get a value from csv file using java 7

texts:
My code picks a value from a too large csv file (~300MB.) at a given index i and j (assuming the csv as 2D array because it contains just data without headers), it works but it is slow.
Is there other method to pick a value from csv file faster?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

public class Main
{

    public static String r1(String input,int i, int j,int bufferSize){

        String[][] result = {};
        String row ="";

        try {
            BufferedReader r1 = new BufferedReader(new InputStreamReader(new FileInputStream(new File(input)), "UTF-8"), bufferSize);

            List<String[]> lines = new ArrayList<String[]>();

            while((row=r1.readLine())!=null){
                lines.add(row.split(","));
            }

            String[][] csv = new String[lines.size()][0];
            lines.toArray(csv);
            result = csv;
            r1.close();
        }

        catch(IOException e){
            e.printStackTrace();
        }
        return result[i][j];
    }

    public static void main(String[] args){
        int bufferSize = 10 * 1024;   //10 KB.
        String filename = "matrix.csv";
        int i = 744, j = 7000;
        String pickedValue = r1(filename,i,j,bufferSize);
        System.out.println(pickedValue);
    }

}


texts:
I have got two tables articles and tags in the database. My goal was to retrieve all fields from articles table and one category field from tags table with Eloquent. I couldn't do this so instead I came up with the following method in my controller.

public function showCategory($category){
    $data = DB::select('select articles.*,
                                tags.category
                                from articles
                                join tags on articles.id = tags.article_id
                                where lang = ? AND tags.category = ?', ['ru', $category]);

    return $data;
}

In my Article and Tag models a have those relationships, respectively:

Article.php

  public function tags(){
    return $this->hasMany('\App\Tag');
}

Tag.php

public function articles(){
    return $this->hasMany('App\Article');
}

This implementation works for me, but I am still curious how can I achieve the same result with Eloquent and eager load tag's category.


texts:
The question is that in a given integer n you have to sum its digits. For example, the sum for 111 would be 3.

Though I managed to solve the problem, I have a good feeling that this algorithm can still be improved.

public static int digit(int n){
    String numbers = n+"";
    int sum = 0;
    for(int x = 0; x < numbers.length(); x++){
        sum += Integer.parseInt(numbers.charAt(x)+"");
    }

    return sum;
}


texts: Removing elements on a List while iterating through it

texts:
I needed a way to remove elements on a List while iterating through it.

Supposedly something like this (illegal code):

List<Integer> nums = new ArrayList();
nums.add(1);
nums.add(2);
nums.add(3);
...
nums.add(10);

System.out.println("BEFORE REMOVE: " + nums);

for (Integer integer : nums) {
    if (integer < 3) {
        //not allowed
        nums.remove(integer);
    }
}

But we all know that the above code is not allowed.

So what I'm doing right now is that I create another List, where I'm putting every element that meets a given condition, then iterate through that List to get the elements that I need to remove on the first List.

List<Integer> toRemove = new ArrayList();
for (Integer integer : nums) {
    if (integer < 3) {
        toRemove.add(integer);
    }
}

for (Integer integer : toRemove) {
    nums.remove(integer);
}

System.out.println("AFTER REMOVE: " + nums);

I know it's not really long, but is there a better way to do this?

Is there some API that I can use?


texts:
My goal is to take any size number, and convert it to a string of smaller characters that represent the concatenation of the binary expansion of the number. To illustrate what I am talking about, here is an example using the number 4820:

4820's binary:   0001001011010100   #   16 bits of binary, enough to store the number 4820
Separated:     00010010  11010100   #   Simply split the binary into two char size pieces
Characters:      '\x12'       'Ô'   #   Converted the binary snippets into their respective characters
Together:                 '\x12Ô'   # The concatenation of the characters, this is what I need

I wrote a algorithm in Python to do the job for me, but I'm not sure if there is a easier way to do it, or if my algorithm is as efficient as it can be.

def to_chars(number, length):                             #takes number and expected binary length
    string = bin(number)[2:]                              #built-in binary conversion
    expanded = ('0' * (length - len(string))) + string    #expand the binary
    chars = ''
    for pos in range(int(length / 8)):                    #iterates over chunks of 8 bits
        section = expanded[8 * pos : 8 * (pos + 1)]       #gets the binary snippet
        chars += chr(int(section, 2))                     #converts the binary into a character
    return chars                                          #return the concatenated string

There has to be a lower level, possibly built in way to do the same thing, but faster. In a way, this is just the conversion from one data type to another, but I can't figure out a faster way.

Here are a few benchmarks:

%timeit to_chars(4820, 16)
100000 loops, best of 3: 3.04 µs per loop

%timeit to_chars(4820, 32)
100000 loops, best of 3: 4.6 µs per loop

%timeit to_chars(690655640, 32)
100000 loops, best of 3: 4.59 µs per loop


texts: Simple dice roll using std::string as dice notation

texts:
This will be a function that returns a random number from Dice Notation (more on Wikipedia).  I will later use this function to determine whether some skill check is passed or not.

Is there any need for optimization?
If so, how?
Any other thoughts about this code?

#include <string>

using namespace std;

int toInt(string text) {
    return atoi(text.c_str());
}

int main(int argc, char* argv[]) {

    srand(time(NULL));

    string diceString = "1d6+4";
    unsigned int dice1number = 0;

    string info = "dice ["+diceString+"] = %i\n";
    printf("==[START]================\n");

    printf(info.c_str(),dice1number);

    // parse dice
    unsigned int i=0;
    unsigned int part = 1;

    string dicePart1 = "";
    string dicePart2 = "";
    string dicePart3 = "";

    for(i=0;i<diceString.length();i++) {

        if (diceString[i]=='d') {
            part = 2;
            continue;
        }

        if (diceString[i]=='+') {
            part = 3;
            continue;
        }

        if (diceString[i]=='-') {
            dicePart3 += "-";
            part = 3;
            continue;
        }

        if (part==1 && diceString[i]>='0' && diceString[i]<='9') {
            dicePart1 += diceString[i];
        }

        if (part==2 && diceString[i]>='0' && diceString[i]<='9') {
            dicePart2 += diceString[i];
        }

        if (part==3 && diceString[i]>='0' && diceString[i]<='9') {
            dicePart3 += diceString[i];
        }

    }

    printf("dicePart1 = [%s]\n",dicePart1.c_str());
    printf("dicePart2 = [%s]\n",dicePart2.c_str());
    printf("dicePart3 = [%s]\n",dicePart3.c_str());

    int roll = 0;
    int add = toInt(dicePart3);
    roll = toInt(dicePart1) * (rand() % toInt(dicePart2)) + add;
    printf("roll = [%i]\n",roll);

    printf("==[END]==================\n");

    return 0;
}


texts: Different methods of API that use similar Services

texts:
I have three methods in API running similar code snippets. For this reuse the code inserted a switch-case according to the API method.  It's good practice that? I mean, this isn't a high coupling and low cohesion? There is another better way?

API

@ApiOperation(value = "Gerar permalinks de todos os arquivos com validação", response = Permalink.class)
    @RequestMapping(value = "{validacaoId}/permalink/all", method = RequestMethod.POST)
    public Permalink gerarPermalinkComValidacao(@PathVariable("validacaoId") String validacaoId) {
        return permalinkService.createPermalink(validacaoId, "Permalink com validação");
    }

    @ApiOperation(value = "Gerar permalinks de todos os arquivos NOKS com validação", response = Permalink.class)
    @RequestMapping(value = "{validacaoId}/permalink/noks", method = RequestMethod.POST)
    public Permalink gerarPermalinkNoks(@PathVariable("validacaoId") String validacaoId) {
        return permalinkService.createPermalink(validacaoId, "Permalink NOKS com validação");
    }

    @ApiOperation(value = "Gerar permalinks de todos os arquivos sem validação", response = Permalink.class)
    @RequestMapping(value = "{validacaoId}/permalink", method = RequestMethod.POST)
    public Permalink gerarPermalinkSemValidacao(@PathVariable("validacaoId") String validacaoId) {
        return permalinkService.createPermalink(validacaoId, "Permalink sem validação");
    }

Service

public Permalink createPermalink(String validacaoId, String tipo) {
        Validacao validacao = validacaoDAO.findById(validacaoId);
        Permalink permalink = new Permalink().setId(Util.getMd5Time(validacaoId));
        if (validacao == null) {
            throw new NotFoundException("Erro ao gerar permalink: ID da validação inválido.");
        }
        permalinkDAO.createPermalinkDirectory(validacao.getId());
        BasicDBList pecas;
        switch (tipo) {
            case "Permalink com validação":
                pecas = getAllFilesWithValidation(validacao.getId(), permalink.getId());
                break;
            case "Permalink NOKS com validação":
                pecas = noksWithValidation(validacao.getId());
                break;
            case "Permalink sem validação":
                pecas = getAllFiles(validacao.getId(), permalink.getId());
                break;
            default:
                throw new IllegalArgumentException("Tipo de permalink inválido.");
        }
        if (!pecas.isEmpty()) {
            permalink.setEmail(validacao.getEmail())
                    .setLogo(permalinkDAO.getLogo(validacao.getInstancia()).getString("logo", ""))
                    .setDataCriacao(DateTime.nowISODate())
                    .setTipo(tipo)
                    .setValidacaoId(validacao.getId())
                    .setInstancia(validacao.getInstancia())
                    .setPecas(pecas);
            permalinkDAO.create(permalink);
            return permalink;
        }
        throw new InternalServerErrorException("Erro ao obter peças para permalink.");
    }


texts:
awhile ago I asked about a thread pool implementation I had made. I took the advice down and modified it a lot over time to fit my needs. It has been serving me extremely well in all of my projects but I was wondering if there was anything else I could improve on?

Here is the class:

class ThreadPool{
public:
    /*  Constructor */
    ThreadPool(uint8_t numThreads) {
        assert(numThreads > 0);
        createThreads(numThreads);
    }

    //Destructor
    ~ThreadPool(){
        shutdown = true;
        notifier.notify_all();
        for(int i = 0; i < threads.size(); ++i){
            threads[i].join();
        }
    }

    //add any arg # function to queue
    template <typename Func, typename... Args >
    auto push(Func&& f, Args&&... args){

    //get return type of the function
    typedef decltype(f(args...)) retType;

    std::packaged_task<retType()> task(std::bind(f, args...));

    std::future<retType> future = task.get_future();

    {
        // lock jobQueue mutex, add job to the job queue
        std::unique_lock<std::mutex> lock(JobMutex);

        jobQueue.emplace(std::packaged_task<void()>(std::move(task)));
    }
    notifier.notify_one();

    return future;
    }

private:

    std::vector<std::thread> threads;
    std::queue<std::packaged_task<void()>> jobQueue;
    std::condition_variable notifier;
    std::mutex JobMutex;
    std::atomic<bool> shutdown = false;

    void createThreads(uint8_t numThreads) {
        auto threadFunc = [this]() {
            while (true) {
                std::packaged_task<void()> job;

                {
                    std::unique_lock<std::mutex> lock(JobMutex);
                    notifier.wait(lock, [this] {return !jobQueue.empty(); });

                    if(shutdown){
                        break;
                    }

                    //strange bug where it will continue even if the job queue is empty
                    if (jobQueue.size() < 1)
                        continue;

                    job = std::move(jobQueue.front());

                    jobQueue.pop();
                }
                job();
            }

        };
        threads.reserve(numThreads);
        for (int i = 0; i != numThreads; ++i) {
            threads.emplace_back(std::thread(threadFunc));
        }
    }

    ThreadPool(const ThreadPool& other) = delete;
    void operator=(const ThreadPool& other) = delete;

}; /* end ThreadPool Class */


texts:
Following task:

Customer-data, given in a JSON-file, have to be completed with additional address-data. Given in a second JSON-file.

Then these data-stock has to be saved into a MongoDB-database.

Schema of the customer-JSON:

[
    {
      "id": "1",
      "first_name": "Ario",
      "last_name": "Noteyoung",
      "email": "anoteyoung0@nhs.uk",
      "gender": "Male",
      "ip_address": "99.5.160.227",
      "ssn": "509-86-9654",
      "credit_card": "5602256742685208",
      "bitcoin": "179BsXQkUuC6NKYNsQkdmKQKbMBPmJtEHB",
      "street_address": "0227 Kropf Court"
    },
    {
      "id": "2",
      "first_name": "Minni",
      "last_name": "Endon",
      "email": "mendon1@netvibes.com",
      "gender": "Female",
      "ip_address": "213.62.229.103",
      "ssn": "765-11-9543",
      "credit_card": "67613037902735554",
      "bitcoin": "135wbMcR98R6hqqWgEJXHZHcanQKGRPwE1",
      "street_address": "90 Sutteridge Way"
    },
...
]

Schema of the addresses-JSON:

[
  {
    "country": "United States",
    "city": "New Orleans",
    "state": "Louisiana",
    "phone": "504-981-8641"
  },
  {
    "country": "United States",
    "city": "New York City",
    "state": "New York",
    "phone": "212-312-1945"
  },
...
]

Desired result:

[
  {
    "_id" : ObjectId("5b3f16f5743a6704739bf436"),
    "id" : "1",
    "first_name" : "Ario",
    "last_name" : "Noteyoung",
    "email" : "anoteyoung0@nhs.uk",
    "gender" : "Male",
    "ip_address" : "99.5.160.227",
    "ssn" : "509-86-9654",
    "credit_card" : "5602256742685208",
    "bitcoin" : "179BsXQkUuC6NKYNsQkdmKQKbMBPmJtEHB",
    "street_address" : "0227 Kropf Court",
    "country" : "United States",
    "city" : "New Orleans",
    "state" : "Louisiana",
    "phone" : "504-981-8641"
  },
  ...
]

My solution:

const mongodb = require("mongodb");

const filePathCustomer = "./customers.json";
const filePathAddresses = "./addresses.json";

const MongoClient = mongodb.MongoClient;

completeCustomers = (filePathCustomers, filePathAddresses) => {
  const customers = require(filePathCustomers);
  const addresses = require(filePathAddresses);

  return (updatedCustomers = customers.map((customer, index) => {
    const updatedCustomer = Object.assign(customer, addresses[index]);

    return updatedCustomer;
  }));
};

MongoClient.connect(
  "mongodb://localhost:27017/bitcoinExchange",
  (error, client) => {
    if (error) {
      throw new Error("Connecting to MongoDb has failed.");
    }

    const db = client.db();

    let execCompleteCustomer = new Promise(resolve => {
      resolve(completeCustomers(filePathCustomer, filePathAddresses));
    });

    execCompleteCustomer
      .then(customer => {
        db.collection("customers").insertMany(customer, (error, result) => {
          if (error) {
            db.close();
            throw new Error("Writing to database has failed");
          }
          console.log(
            "Count of customer documents inserted:",
            result.insertedCount
          );

          return true;
        });
      })
      .then(result => {
        if (result) db.close();
      })
      .catch(() => {
        db.close();
        throw new Error("The merging of the customer-data has failed.");
      });
  }
);

What would you have done different and why?

Is my error-handling done in a good way and fashion? How could it be improved?

What bothers me a bit are this multiple occurences of db.close().

Is there a way in Node to avoid these redundancy?

Something like finally in Java.


texts:
I recently put together an Express/Node API that consumes and transforms an additional third party API.

And while everything is working great, I feel there may be ways to improve the architecture and implementation.

This is my current implementation:

    nodes_modules/
    routes/
    ...api.js
    ...search.js
   index.js
   .babelrc
   .config.js
   .package.json

api.js

import express from "express";
let router = express.Router();

router.use('/search', require('./search'));

module.exports = router;

search.js

import express from "express";
import axios from "axios";
import transformer from "transformer";
const router = express.Router();

router.get('/:type', (req, res) => {

    const type = req.params.type;

    axios.get('http://example.com/api/' + type)
        .then((response) => {

            let transformed = {};

            switch(type) {
                case "people":
                    transformed = transformer.search(response.data, "results[*].{ name: name }");
                    break;
                case "aircrafts":
                    transformed = transformer.search(response.data, "results[*].{ name : aircraftName }");
                    break;
                default:
                    res.status(400).send({ error : "Bad request" });
                    break;
            }

            res.send({original: response.data, transformed: transformed });
        })
        .catch( () => {
            res.status(400).send({ error : "Bad request" });
        });
});

module.exports = router;

index.js

import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';

const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({  extended: true }));
app.use(bodyParser.json());

app.use('/api', require('./routes/api'));

app.use('*', (req,res) => {
   res.status(404).send('Page Not Found');
});

app.listen(3030, function() {
   console.log('running on port 3030');
});

I appreciate any suggestions for improvement, pointing out of any flaws or useful changes that can be made to the current implementation. Thank you


texts: Substitute Excel-Workbook reference for another

texts:
I have an Excel-Workbook, where we have an sheet where we consolidate data. Basically we link to other Excel-Workbooks. I wrote the following Macro, in order to update the path and filename. We cannot just update the whole link, since other parts need to reference the old path (and filename).

Sub neueDatei()

Dim Pfad As String, DateiName As String, DateiName_alt As String, h As String, formel As String
Dim tblRow As Long, test As Long
Dim wb As Workbook
Dim IVsh As Worksheet

Application.ScreenUpdating = False

Set wb = ActiveWorkbook

Set IVsh = wb.Sheets("Input Vektor")

With IVsh
    Pfad = .Range("C3").Value 'set the path
    DateiName = .Range("C4").Value 'set the filename
    tblRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'find last row
End With

If Mid(Pfad, Len(Pfad) - 1, 1) <> "\" Then
    Pfad = Pfad & "\" 'append \ if necessary
End If

If Mid(Pfad, 1, 1) <> "'" Then
    Pfad = "'" & Pfad 'excel needs a quote at the start of the path.
End If

DateiName_alt = DateiName

'add brackets to the filename
If Mid(DateiName, 1, 1) <> "[" Then
    DateiName = "[" & DateiName
    DateiName = DateiName & "]"
End If

'substitute the filenames
For i = 19 To tblRow
    If IVsh.Cells(i, 7).Value <> "" Then
        Exit For
    End If
    h = IVsh.Cells(i, 2).Formula
    If InStr(1, h, "[") > 0 Then
        IVsh.Cells(i, 2).Formula = "=" & Pfad & DateiName & Mid(h, InStr(1, h, "]") + 1)
    Else
        IVsh.Cells(i, 2).Formula = "=" & Pfad & DateiName_alt & Mid(h, InStr(1, h, "xlsx") + 4)
    End If
Next i

Application.ScreenUpdating = True

End Sub

The problem is, that the code runs relatively slow (a few minutes for only 2-3 thousand lines). Any suggestions, how I can speed this up?


texts: Composing functionality of sealed class with interfaces

texts:
public sealed class Client
{
    private Simulation _simulation;
    public Client(ITickProvider tickProvider, ICommandReceiver commandReceiver)
    {
        _simulation = new Simulation();
       tickProvider.Tick += HandleTick;
       commandReceiver.CommandReceived += HandleCommandReceived;
    }
    private void HandleTick ()
    {
        //Distribute tick to _simulation
    }
    private void HandleCommandReceived(Command command)
    {
        //Inject command to _simulation
    }
}

Client operates a multithreaded Simulation, distributing ticks and external input to the Simulation.
ITickProvider provides a Tick event that runs every e.g. fixed interval, button click, etc..
ICommandReceiver receives external input (Commands); i.e. User input, server input, serialized input, etc..
Because the interfaces' implementations are usually exclusive, I decided to make Client sealed and inject the functionality with the constructor. This also helps with controlling thread-sensitive access to Simulation.
What is the pattern of composing a sealed class with modular interfaces? Is this a well-known pattern and if so, have I implemented it correctly?


texts:
I've been working though Project Euler problems using JavaScript, and along the way I've found it useful to create "classes" for different types of numbers (like an integer that can be arbitrarily large). I recently decided to create a sort of class for Fractions to avoid floating point error.

I wrote the code using a more functional/procedural approach; however, I'm concerned that since JavaScript can't use types to distinguish functions that the function names will overlap with other code I write. I'm also looking for shorter names or better syntax to simplify how messy the math can get as shown in my tests. Here's a JSFiddle if you'd like to see the code in action.

General Global Functions

// Calculates the greatest common factor of two positive integers
function gcf(p, q) {
  if (p > q) return gcf(q, p);
  else if (p === 0) return q;
  else return gcf(q % p, p);
}

// Reduces two numbers by their greatest common factor
function gcd(p, q) {
  var f = gcf(p, q);

  return [
    p / f,
    q / f
  ];
}

Fraction Constructor

function createFraction(n, d) {
  if (d < 0) {
    n *= -1;
    d *= -1;
  }

  var f0 = reduce({
    n: n,
    d: d
  });
  return f0;
}

Fraction Utility Functions

function reduce(f0) {
  var f = gcf(Math.abs(f0.n), f0.d);
  f0.n /= f;
  f0.d /= f;
  return f0;
}

function invert(f0) {
  return createFraction(
    f0.d,
    f0.n
  );
}

function negate(f0) {
  return createFraction(
    f0.n * -1,
    f0.d
  );
}

Fraction Basic Math Functions

function multiply(f1, f2) {
  return createFraction(
    f1.n * f2.n,
    f1.d * f2.d
  );
}

function divide(f1, f2) {
  return multiply(f1, invert(f2));
}

function add(f1, f2) {
  var r = gcd(f1.d, f2.d);

  return createFraction(
    f1.n * r[1] + f2.n * r[0],
    f1.d * r[1]
  );
}

function subtract(f1, f2) {
  return add(f1, negate(f2));
}

Testing Code

function equals(f1, f2) {
  return f1.n === f2.n &&
    f1.d === f2.d;
}

function toString(f0) {
  return f0.n + "/" + f0.d;
}

function testEquals(line, f1, f2) {
  if (!equals(f1, f2)) console.log(line + " failed: " + toString(f1) + " !== " + toString(f2));
  else console.log(line + " good: " + toString(f1));
}

var line = 0;
testEquals(line++, add(createFraction(10, 40), createFraction(3, 30)), createFraction(7, 20));
testEquals(line++, subtract(createFraction(8, 3), createFraction(11, 30)), createFraction(69, 30));

testEquals(line++, multiply(createFraction(8, 3), createFraction(11, 30)), createFraction(88, 90));
testEquals(line++, divide(createFraction(8, 3), createFraction(11, 30)), createFraction(240, 33));

testEquals(line++, add(createFraction(-5, 8), createFraction(-1, -2)), createFraction(-1, 8));
testEquals(line++, subtract(createFraction(10, 40), createFraction(-3, 30)), createFraction(7, 20));

testEquals(line++, multiply(createFraction(-8, 3), createFraction(-11, 30)), createFraction(88, 90));
testEquals(line++, divide(createFraction(8, -3), createFraction(11, -30)), createFraction(240, 33));


texts: Increase performance in an R function using a vectorized approach

texts:
Goal

Write an R function to generate probabilities modeled by the following equation (IRT; 2 Parameter Logistic Model):

Data

set.seed(1)
a = runif(10, 1.5, 3)
b = rnorm(10, 0, 1)
theta = rnorm(10000000)
# the output of the implementation should result in
# a matrix with 100 mil. rows and 10 columns

Implementation

Strategy A

# the implementation of the equation
computeProbability = function(theta, b, a) {
    x = exp(1) ^ (a * (theta - b))
    return(x / (1 + x))
}

strategy.A = function(theta, b, a) {
    n.rows = length(theta)
    n.cols = length(b)

    prob_mtx = matrix(nrow = n.rows, ncol = n.cols)

    for(i in 1:n.rows)
    {
        prob_mtx[i, ] = computeProbability(theta[i], b, a)
    }
    return(prob_mtx)
}

Strategy B

strategy.B = function(theta, b, a) {
   return(t(sapply(theta, computeProbability, b = b, a = a)))
}

Strategy C

strategy.C = function(theta, b, a) {
    return(1 / (1 + exp(-sweep(outer(theta, b, "-"), 2, a, "*"))))
}

Timings

    # Strategy A        |       # Strategy B        |       # Strategy C
                        |                           |
 user  system elapsed   |    user  system elapsed   |   user  system elapsed
64.76    0.27   65.08   |   82.01    0.91   82.93   |   7.81    0.64    8.46

Question: Strategy C is by far the most efficient way, but how can I make it even faster?


texts: How would you convert this code to best take advantage of CSS transform for panning/zooming?

texts:
I am using react-flow-chart for a job project, but it doesn't implement zoom, and I would like to take the reigns and try applying it myself. I took a linear algebra class in college, but I am not very good at transformations. I could make my job a lot easier if I directly use CSS transforms and have it do the heavy lifting for me.

Code

I have put the in a CodeSandbox repo and have organized it as best as I could for clarity, so I recommend viewing the complete code from there, and fork it for significant changes.

https://codesandbox.io/s/agitated-wood-ksfbs?fontsize=14

App.js

export const App = () => {
  const [squares, setSquares] = useState([[0, 0], [20, 20], [50, 20]]);
  const [canvasPosition, setCanvasPosition] = useState([0, 0]);

  const onPositionChanged = R.curry((index, pos) => {
    if (index === "canvas") return setCanvasPosition(pos);
    setSquares(R.update(index, pos));
  });

  return (
    <Canvas
      position={canvasPosition}
      onPositionChanged={onPositionChanged}
      squares={squares}
    />
  );
};

Canvas.js

This is the part where I calculate each square's position and render it

const calculateSquarePosition = R.pipe(
    mult(scale),
    add(canvas),
    add(drag)
  );

  const onSquarePositionChanged = index =>
    R.pipe(
      add(neg(drag)),
      add(neg(canvas)),
      mult(1 / scale),
      onPositionChanged(index)
    );

  const renderSquare = (pos, index) => (
    <Square
      key={index}
      scale={scale}
      position={calculateSquarePosition(pos)}
      onPositionChanged={onSquarePositionChanged(index)}
    />
  );

The part where I handle zooming by mouse wheel:

  const onWheel = event => {
    const wheelDelta = event.deltaY;
    const newScale = R.pipe(
      R.add(wheelDelta * 0.001),
      clamp(0.2, 8)
    )(scale);

    const screenPos = getClientPos(event);
    const canvasToMouse = add(canvas, neg(screenPos));
    const normalizedCanvasToMouse = normalize(canvasToMouse);

    const distance = length(canvasToMouse);
    const newDistance = (distance / scale) * newScale;
    const newCanvasToMouse = mult(newDistance, normalizedCanvasToMouse);
    const newCanvas = add(screenPos, newCanvasToMouse);
    onPositionChanged("canvas", newCanvas);
    setScale(newScale);
  };

Explanation

My app consists of a Canvas, which has a specified width and height. I made a useDrag hook that allows it to listen for drag events and gives the drag displacement which can be used to translate the canvas position, which mostly moves all the Squares together (as the Canvas can be considered the parent element). Squares are also draggable.

Things get more complicated when the scale is involved as I have to translate view coords to scaled view coords etc. correctly.

I want to know what changes I should make to make the transformations, state management, and just the math work for me in the most natural way. I feel like there should a better way, but I am not sure how.

The ultimate goal is to transfer what I know into the react-flow-chart and implement the zoom myself, and hopefully give a pull request (my first ever.)

Please let me know of anything that could be improved in this code. I welcome any criticism/feedback.


texts: How to reorganize event listeners in javascript

texts:
I often find myself writing code as follows...

var startX, startY, dragging = false, element = document.getElementById("whatever");

var start = function(e){
  dragging = true;
  startX = e.pageX;
  startY = e.pageY;
  element.style.opacity = 0.5;
}

var move = function(e){
  if (!dragging) return;
  var deltaX = startX - e.pageX;
  var deltaY = startY - e.pageY;
  //apply to element
}

var end = function(e){
  dragging = false;
  element.style.opacity = 1;
}

element.addEventListener("mousedown", start, false);
document.addEventListener("mousemove", move, false);
document.addEventListener("mouseup", end, false);

Now, my problem is really basic, it feels to me that the functions should be auxiliary and belong to the bottom part of my program, but I don't know how to attach the functions to the event listeners without declaring them first. How do I restructure my code so that it is more evident what I'm going to do with these functions?


texts: Finding the sum of all the multiples of 3 or 5 below any given number

texts:
I wrote the following simple function in JavaScript that finds the sum of all the multiples of 3 or 5 below a value, given from a text-box.

I have used \$\dfrac{n}{2(a_1 + a_n)}\$ (sum of arithmetic sequence).

I was wondering if there is a way to shorten or otherwise improve this code.

function sum_of_all_mul_3_5(){
    var value=parseInt(document.getElementById("input").value);
    var result=(((Math.floor((value-1)/3))*(3+((Math.floor((value-1)/3))*3)))/2)+(((Math.floor((value-1)/5))*(5+((Math.floor((value-1)/5))*5)))/2)-(((Math.floor((value-1)/15))*(15+((Math.floor((value-1)/15))*15)))/2);
    document.getElementById("output").value=result ;
    }


texts:
I'm fairly new to Java and I'd like to know if there's any way to improve or refactor the prompt on validating integer values for best practices.
import java.util.Scanner;

public class Triangle {
 public static void main(String[] args) {
  int a, b, c;
  Scanner in = new Scanner(System.in);

  // Prompt for a
  System.out.print("a: ");
  if (!in.hasNextInt() || (a = in.nextInt()) <= 0) {
   System.out.println("Input must be a positive integer!");
   return;
  }

  // Prompt for b
  System.out.print("b: ");
  if (!in.hasNextInt() || (b = in.nextInt()) <= 0) {
   System.out.println("Input must be a positive integer!");
   return;
  }

  // Prompt for c
  System.out.print("c: ");
  if (!in.hasNextInt() || (c = in.nextInt()) <= 0) {
   System.out.println("Input must be a positive integer!");
   return;
  }

  if (a + b > c && a + c > b && b + c > a) {
   System.out.println("It's a traingle.");
  } else {
   System.out.println("Invalid lengths for a traingle.");
  }
 }
}


texts: Replacing certain characters in a QString

texts:
This question is kinda similar to mine. However, I am using C++ with Qt instead of C#.

How would I efficiently and easily remove all accents and special characters like !"§$%&/()=? etc. from a QString?

So "áche" should turn into "ache" or "über dir" to "ueber dir" (in german ü,ä,ö can be changed into the normalized character with an e appended) or at least "uber dir".

Note: Some people use a $ instead of s in some words so I want to make sure if a file is called "Ke$ha" that it will come out as "Kesha" or at least "KeSha".

The way I do it so far, incomplete, is like this:

void Utils::replaceInvalidChars(QString &str)
{
    if( str.size() == 0 )
        return;

    while( str.at(0) == '.' ) {
        str.remove(0,1);
    }

    str.replace( "/", "-" );
    str.replace( "|", "" );
    str.replace( ":", "-" );
    str.replace("\"", "" );
    str.replace( "?", "" );
    str.replace( "$", "s" );
    str.replace( "*", "" );
    str.replace( ",", "" );
    str.replace( "¿", "" );
    str.replace( "¡", "" );
    str.replace( "!", "" );
    str.replace( "'", "" );

    str.replace( "ë", "e" );
    str.replace( "ê", "e" );
    str.replace( "é", "e" );
    str.replace( "è", "e" );

    str.replace( "ç", "c" );

    str.replace( "ó", "o" );
    str.replace( "ö", "oe" );

    //U's...
    str.replace( "ü", "ue" );
    str.replace( "Ü", "U" );
    str.replace( "ù", "u" );
    str.replace( "Ù", "U" );
    str.replace( "û", "u" );
    str.replace( "Û", "u" );

    //ns
    str.replace( "ñ", "n" );

    //as
    str.replace( "ä", "ae" );
    str.replace( "Ä", "ae" );
    str.replace( "á", "a" );
    str.replace( "Á", "A" );
    str.replace( "à", "a" );
    str.replace( "À", "A" );

    str.replace( "ï", "i" );
}

So at first I remove all dots from the beginning. No matter how many there are. Then I replace certain characters with no character at all and some with a character like 's' or a depending on what it is.

My way is very long, tedious and chaotic. I am about to organize it a little with comments like "N's", "U's" etc. but still, if I make a mistake somewhere it will take way too long until I (eventually) find it.


texts:
I'm trying to create a function for a dynamic dropdown. I have done it this way and it works, but I want to make my code cleaner.

 function renderRowCounter() {

    var rowCount = [25, 50, 100];
    var first = rowCount[0];
    var items = '';

    $.each(rowCount, function(i,v) {
        items += "
" + v + "
";
    });

    return  "
" +
            "<button type=\"button\" data-toggle=\"dropdown\" class=\"btn btn-default dropdown-toggle\">" + first + " </button>" +
            "
" + items +
            "
" +
            "
 ";
}


texts: Creating CAPTCHA in ColdFusion then showing image in Vue.js

texts:
I am trying to create a CAPTCHA image on ColdFusion. ColdFusion will be producing REST services and hence will have to push the image via JSON. I want the image to be self contained. I don't want to expose any of the servers paths, so I am going to encode the image and push that via JSON. Last but not least, Vue.js will be used to show the image on the page.

Note: I have omitted the AJAX part for clarity.

<cfscript>
  // This is ColdFusion
  tempFile = "ram:///myImage.txt";

  myImage = ImageCreateCaptcha(100, 300, "Blackcat", "high");

  ImageWriteBase64(myImage, tempFile, "png",true, true);

  myfile = FileRead(tempFile);
  FileDelete(tempFile);
</cfscript>

<div id="image">
   <img :src="captcha">
</div>

<script>
  // this is JavaScript

  data = { 'captcha' : <cfoutput>'#myfile#'</cfoutput> };

  new Vue({
      el: '#image',
      data : data
      });
</script>

Can this process be improved?


texts:
I'm teaching myself Python and when a friend posted this sentence

  Only the fool would take trouble to verify that his sentence was
  composed of ten a's, three b's, four c's, four d's, forty-six e's,
  sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine l's,
  four m's, twenty-five n's, twenty-four o's, five p's, sixteen r's,
  forty-one s's, thirty-seven t's, ten u's, eight v's, eight w's, four
  x's, eleven y's, twenty-seven commas, twenty-three apostrophes, seven
  hyphens and, last but not least, a single !

I thought, as a fool, I would try to verify it by plotting a histogram. This is my code:

import matplotlib.pyplot as plt
import numpy as np

sentence = "Only the fool would take trouble to verify that his sentence was composed of ten a's, three b's, four c's, four d's, forty-six e's, sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine l's, four m's, twenty-five n's, twenty-four o's, five p's, sixteen r's, forty-one s's, thirty-seven t's, ten u's, eight v's, eight w's, four x's, eleven y's, twenty-seven commas, twenty-three apostrophes, seven hyphens and, last but not least, a single !".lower()

# Convert the string to an array of integers
numbers = np.array([ord(c) for c in sentence])
u = np.unique(numbers)
# Make the integers range from 0 to n so there are no gaps in the histogram
# [0][0] was a hack to make sure `np.where` returned an int instead of an array.
ind = [np.where(u==n)[0][0] for n in numbers]
bins = range(0,len(u)+1)
hist, bins = np.histogram(ind, bins)

plt.bar(bins[:-1], hist, align='center')
plt.xticks(np.unique(ind), [str(unichr(n)) for n in set(numbers)])
plt.grid()
plt.show()

Which generates

Please let me know how to improve my code. Also, please let me know what I did wrong with plt.xticks that resulted in the gaps at the beginning and the end (or is that just a case of incorrect axis limits?).


texts: Implementing a Trie in Python - follow-up

texts:
This is a follow-up of Wikipedia Trie pseudocode in Python

Code quality improvements

find has been fixed and a regression test ("bana" vs "banana") has been added so that it will never again be broken that way.
Used ordinary instance methods when sensible (previous code suffered from staticmethods overuse).
Significant simplification from the use of Python defaultdict
Operator overloading to provide easy membership test and printing (__repr__, __contains__)
Removed the value argument as I saw no use for it.
Minor doc-style language adjustments.
The printing is not used in testing anymore, as it should not be, because it is arbitrary (as Python's dicts are)

Functionality improvements

The printing is now as it should be, not reversed.
There is no more a weird inspect method, you can simply print the trie.

Example output

A trie from the words ('banning', 'banned', 'banana', 'bad', 'cooking', 'cought', 'count') is printed as:

c
 o
  o
   k
    i
     n
      g
       #
  u
   g
    h
     t
      #
   n
    t
     #
b
 a
  n
   a
    n
     a
      #
   n
    i
     n
      g
       #
    e
     d
      #
  d
   #

# signals the end of a word.

The code

import collections
import doctest

class Trie:
    """
    Implements a Trie (also known as 'digital tree',  'radix tree' or 'prefix tree').

    Where common starting letters of many words are stored just once.
    """
    def __init__(self):
        self.child = collections.defaultdict(Trie)

    def insert(self, string):
        """
        Add a given string to the trie, modifying it **in place**.

        >>> t = Trie()
        >>> t.insert('hello')
        >>> t.insert('hi')
        >>> list(sorted(t.child.keys()))
        ['h']
        >>> first_node = t.child['h']
        >>> list(sorted(first_node.child.keys()))
        ['e', 'i']

        As you can see, the same `h` was written only once,
        and it is connected with both `i` and `e`.
        """
        node = self
        for char in string:
            node = node.child[char]
        node = node.child[None]

    def __contains__(self, word):
        """
        >>> t = Trie()
        >>> t.insert('example')
        >>> 'example' in t
        True
        >>> 'exemplum' in t
        False
        >>> t.insert('bana')
        >>> 'banana' in t
        False
        >>> t.insert('banning')
        >>> t.insert('banned')
        """
        trie = self

        for char in word:
            if char in trie.child:
                trie = trie.child[char]
            else:
                return False

        return True

    def __str__(self, depth = 0):
        """
        Shows a nicely formatted and indented Trie.

        Cannot be tested as equivalent representations
        are arbitrarly chosen from (`dict`s are not ordered).
        """
        s = []
        for i in self.child:
            s.append( '{}{} {}'.format(
                ' ' * depth, i or '#', '\n' + self.child[i].__str__(depth + 1)))
        return ''.join(s)

if __name__ == '__main__':
    doctest.testmod()
    trie = Trie()
    for word in ('banning', 'banned', 'banana', 'bad', 'cooking', 'cought', 'count'):
        trie.insert(word)
    print(trie)


texts:
I'm very new to Go (this is my first real program), and I was hoping to see if there was anything I was missing about the language or any ways to make it more idiomatic.

calculator.go

package calculator

import (
    "../stack"
    "unicode"
    "strconv"
)

func Calculate(input string) int {
    stack := new(stack.Stack)

    for i := 0; i < len(input); i++{
        c := rune(input[i])

        if unicode.IsDigit(c) {
            stack.Push(parseNumber(input, &i))
        }
        switch c {
            case '+':
                b := stack.Pop()
                a := stack.Pop()
                stack.Push(a + b)
            case '-':
                b := stack.Pop()
                a := stack.Pop()
                stack.Push(a - b)
            case '*':
                b := stack.Pop()
                a := stack.Pop()
                stack.Push(a * b)
            case '/':
                b := stack.Pop()
                a := stack.Pop()
                stack.Push(a / b)
        }

    }

    if(stack.Size() > 1) {
        panic("Input did not fully simplify")
    }

    return stack.Pop()
}

func parseNumber(input string, i *int) int {
    initialIndex := *i

    for unicode.IsDigit(rune(input[*i])) {
        *i++
    }
    num, _ := strconv.Atoi(input[initialIndex : *i])
    return num
}

calculator_test.go

package calculator

import (
 "testing"
)

func TestCalculate(t *testing.T) {
    tests := map[string]int{
     "3 4 +":7,
     "3 4 -":-1,
     "3 4 *":12,
     "3 4 /":0,
     "1 1 + 2 -":0,
     "5 10 * 2 /":25,
    }
    for input, expected := range tests {
        result := Calculate(input)
        if(result != expected) {
            t.Log("Calculate failed. Expected ",expected, ", got ", result)
            t.Fail()
        }
    }
}

stack.go

package stack

type Stack struct {
    i int
    // fixed size
    data [100]int
}

func (s *Stack) Push(i int) {
    if(s.i + 1 >= len(s.data)){
        panic("Out of memory!")
    }

    s.data[s.i] = i
    s.i++
}
func (s *Stack) Pop() int {
    if(s.i - 1 < 0){
        panic("Can't pop when there is no data!")
    }

    s.i--
    return s.data[s.i]
}

func (s *Stack) Size() int {
    return s.i
}

stack_test.go
Not very proud of this. Is there any way I can reduce the duplicated code? Are there any built in assert methods?

package stack

import (
 "testing"
)

func TestStack(t *testing.T) {
    s := new(Stack)

    if(s.Size() != 0) {
        t.Fail()
    }

    s.Push(1)

    if(s.Size() != 1) {
        t.Fail()
    }

    s.Push(2)

    if(s.Size() != 2) {
        t.Fail()
    }

    s.Push(3)

    if(s.Size() != 3) {
        t.Fail()
    }

    if(s.Pop() != 3) {
        t.Log("Didn't pop in order!")
        t.Fail()
    }

    if(s.Size() != 2) {
        t.Fail()
    }
    if(s.Pop() != 2) {
        t.Log("Didn't pop in order!")
        t.Fail()
    }
    if(s.Size() != 1) {
        t.Fail()
    }

    if(s.Pop() != 1) {
        t.Log("Didn't pop in order!")
        t.Fail()
    }
    if(s.Size() != 0) {
        t.Fail()
    }
}


texts:
I want to wait for a line to be read, but only for so long before timing out.  This is what I came up with.  Is there a better way to do it?

Dim reader As New System.IO.StreamReader(pipe)

Dim nextCommand = Await New Func(Of Task(Of String))(
    Function()
        Dim t = reader.ReadLineAsync()
        If (Not t.Wait(2000)) Then Throw New MyTimeoutExeption()
        Return t
    End Function).Invoke()


texts: Avoid redundancy of HTML entities in .NET framework

texts:
I have to store various HTML named character references for the following purposes:

Escaping special characters myStringBuilder.Replace("À", WebHelper.Agrave)
Insert spaces in legacy reports ReportButtons.Controls.Add(New LiteralControl(WebHelper.Space))

This is the way I used to store until now:

public static class WebHelper
{
    #region [ Fields ]

    public const string Agrave = "&Agrave;";

    public const string Space = "&nbsp;";

    #endregion
}

Is this Single-Generic-Helper-Class the best way to solve this problem? Should all my programs reference it?


texts:
I have just finished building a Chess game in Java as an exercise. Whilst I am quite happy with the rest of the code, my castling move check code is lengthy and ugly and I want to see if there is a way to improve it.

There is a board class, which has a list of all pieces which are all unique classes extended from a single chessman class. This code is contained within the king class.

getOwner returns an enum which has a value of 0 or 1 depending on the player
checkPosition returns a boolean if there is a unit at the position or not
doMove is the normal form of moving pieces
getUnit retrieves a unit at a specified position
getPossibleMoves is every legal move a unit can make in the form of a point list

@Override
public boolean move(Point target){
    int owner = super.getOwner().getValue() * 2;
    List<Point> castlingMove = new ArrayList<>(Arrays.asList(new Point(3,1),new Point(7,1), new Point(3,8), new Point(7,8)));
    List<Point> rooks = new ArrayList<>(Arrays.asList(new Point(1,1), new Point(8,1), new Point(1,8), new Point(8,8)));
    Board b = super.getBoard();
    if (castlingMove.contains(target) && !this.moved) {
        boolean success = false;
        if (target.equals(castlingMove.get(owner + 1)) && b.checkPosition(rooks.get(owner + 1))){ // Castling Short
            success = checkRook(b, rooks, castlingMove, owner, 1);
        } else if(target.equals(castlingMove.get(owner)) && b.checkPosition(rooks.get(owner))){ // Castling Long
            success = checkRook(b, rooks, castlingMove, owner, 0);
        }
        if (success) this.moved = true;
        return success;
    } else {
        boolean success = this.doMove(target);
        if (success) this.moved = true;
        return success;
    }
}

private boolean checkRook(Board b, List<Point> rooks, List<Point> castlingMove, int owner, int moveType) {
    Chessman u = b.getUnit(rooks.get(owner + moveType));
    if (u instanceof Rook){
        Rook r = (Rook) u;
        if (!r.getMovedStatus()) {
            boolean noCheck = true;
            boolean freeSpace = true;
            for (Chessman unit : b.getAllUnits()){
                if (unit.getOwner() == super.getOwner()) continue;
                Point[] t = {(Point) super.getPosition().clone(), (Point) r.getPosition().clone()};
                int[] s = {5, 9};
                Point m = t[moveType];
                while (t[moveType].getX() < s[moveType]) {
                    if (unit.getPossibleMoves().contains(m)) noCheck = false;
                    m.translate(1, 0);
                    if (b.checkPosition(m) && m.x < s[moveType]) freeSpace = false;
                }
            }

            if (noCheck && freeSpace) {
                int[] p = {4,6};
                super.setPosition(castlingMove.get(owner + moveType));
                r.setPosition(new Point(p[moveType],super.getPosition().y));
                return true;
            }
        }
    }
    return false;
}

If anyone needs more code, just say so. I didn't include the whole project because it is a large amount of code.


texts:
I created this function and I'm unsure if it is sufficient for "real world use", because all code snippets on the net I found for recursive copy functions used functions like

$hDir = opendir($sSrc)

which I don't think are necessary. That's why I like to have my func checked by some PHP professionals:

It recursively copies directories.

Params:

$sSrc  Path of directory, of which the content is to be copied
$sDst  Path of directory, into which the content of $sSrc is to be
copied. Non existing directories are (recursively) created.
$blnKeepPerm  Optional argument specifying if destination objects
must have the same permission as their source objects

Returns:  True only if ALL elements are copied, otherwise false.

function rcopy ($sSrc, $sDst, $blnKeepPerm = 0) {
  if (! is_dir($sSrc)) return false;
  $sSrc = (substr($sSrc,-1)=='/' ? substr($sSrc,0,-1) : $sSrc);
  $sDst = (substr($sDst,-1)=='/' ? substr($sDst,0,-1) : $sDst);
  $blnRetval = true;
  if (! is_dir($sDst)) {
    if ($blnKeepPerm) {
      if (! @mkdir($sDst, fileperms($sSrc), true)) return false;
    } else {
      if (! @mkdir($sDst), (0777-umask()), true) return false;
    }
  }
  foreach (scandir($sSrc) as $sObj) {
    if ($sObj != '.' && $sObj != '..') {
      if (is_dir("$sSrc/$sObj")) {
        // the function returns true only if copying ALL of the
        // files/dirs succeeded. To prevent overwriting of $blnRetVal
        // by a later rcopy-call, the return values here are ANDed:
        $blnRetval = $blnRetval & rcopy ("$sSrc/$sObj", "$sDst/$sObj", $blnKeepPerm);
      } else {
        if (@copy ("$sSrc/$sObj", "$sDst/$sObj")) {
          if ($blnKeepPerm) {
            @chmod ("$sDst/$sObj", fileperms("$sSrc/$sObj"));
          }
        } else  $blnRetval = false;
      }
    }
  }
  return $blnRetval;
}

What do you think? What could/should be made better?


texts: Suggestions for improving error handling

texts:
I am interested in finding out what is the correct way of implementing error handling for this situation in C#.

The system tries to do an operation. If the operation succeeded (returns a non-error code), the system logs in a log database that the operation was succesfull. If the operation returns a error code or something caused an exception before the operation, the system will log an error. However, if the an error is caught when logging, the system shouldn't log an error in the database.

I am using C#. The following code is what I have used until now, but I don't know if it is the best practice in this situation.

int response = -1;  //some error code
try
{
    //some code to prepare the operation - may cause exceptions
    response = DoOperation();
    //some code to clean after the operation - may cause exceptions
}
catch
{
    //error handling
}

try
{
    if (response > 0) //non-error code
        //log event in database
    else
        //log event error in database
}
catch
{
    //logging error handling
}

Do you have any suggestions for improving my code?

Note: The catch blocks include in the original code handling specific errors, I just used a general catch blocks for code simplicity in my question.


texts: Generate a random integer of length N with unique digits

texts:
The task is simple: given N, generate a random integer with no repeating digits.

'''
Generate a random number of length, N and all digits
are unique
'''
from __future__ import print_function
import random
from collections import OrderedDict

# keep generating till all are unique
# This is a brute force approach where I store the digits generated
# so far in a OrderedDict and if the next random number is already
# there, i ignore it.
def randN(n):
    digits = OrderedDict()
    while len(digits) < n:
        d = random.randint(0, 9)
        if d == 0 and not digits.keys():
            continue
        else:
            if not digits.get(str(d), None):
                digits[str(d)] = 1
    return int(''.join(digits.keys()))

def _assert(randi, n):
    assert len(str(randi)) == n
    assert len(set(str(randi))) == n

for _ in range(100000):
    _assert(randN(10), 10)
    _assert(randN(1), 1)
    _assert(randN(5), 5)

I have a feeling there is a better approach to solve this, which is why I am posting it here.


texts: Iterate through multiple elements based on their id in jQuery

texts:
Haven't worked too much with jQuery and I had to get the values from different elements (they have the ids 0, 1 and 2) in order to compute the sum of them and update a field with that value.
The code works well but I was wondering if it is possible to write less code and use something like a for loop in this case.
Here is the code:
function total() {
  var subtotal0 = parseFloat(
    $('#0').find('.cart-subtotal').text().replace('€', '')
  );

  var subtotal1 = parseFloat(
    $('#1').find('.cart-subtotal').text().replace('€', '')
  );

  var subtotal2 = parseFloat(
    $('#2').find('.cart-subtotal').text().replace('€', '')
  );

  var total = subtotal0 + subtotal1 + subtotal2;

  $('.cart-total-price').text(total + '€');
}

Is it possible to make it better?