texts: Utmost function that takes a comparator function

texts:
I'm working through Paul Graham's "ANSI Common Lisp". In Chapter 6 (p105), he introduces the idea of utility functions. He points out these are core to bottom-up programming and reusability. He observes that for such utility functions in lisp and fp "it's easier to abstract out the general when you can pass the specific as a function argument".

The example below is given in the book (my own code for discussion will follow after this example).

 (defun most (fn lst)

 "What's the el of a list with highest score, according to provided
scoring fn?"

   (if (null lst)

      (values nil nil)
      (let* ((wins (car lst))           ; 'wins' is 'winning element'
             (max (funcall fn wins)))   ; 'max' is 'winning score'
        (dolist (obj (cdr lst))
          (let ((score (funcall fn obj)))
            (when (> score max)
              (setf wins obj
                    max score))))
        (values wins max))))

which runs as

> (most #'length '((a b) (a b c) (a)))
(A B C) ;
3

So, most above is effectively mapping the given list using the function argument then simply applying an arithmetic max to find the winner (though it does it in a slightly more efficient way than I just described).

I recalled a previous example where a comparator function was passed as an argument, allowing choice between > or <, for example. So, I added an second function argument to the above function as below (the only change is that the function arg has been added and then the single line where I've added a new comment).

(defun utmost (> fn lst)                ; note '>' is name of a variable!
  "Same as most above but with extra function argument allowing e.g. < or >"
  (if (null lst)
      (values nil nil)
      (let* ((wins (car lst))           ; 'wins' is 'winning element'
             (max (funcall fn wins)))   ; 'max' is 'winning score'
        (dolist (obj (cdr lst))
          (let ((score (funcall fn obj)))
            (when (funcall > score max) ; <- I replaced '>' with 'funcall >'
              (setf wins obj
                    max score))))
        (values wins max))))

which can be run as:

> (utmost #'< #'length '((a b) (a b c) (a)))
(A) ;
1

Above, we passed < as the new fn param, so 'utmost' has taken the form of returning the element of the given list of 'least' ('length') this time.

Questions

Given that this is my first attempt at 'designing' a function that takes more than one function parameter, I'm wondering if I'm on the right track at all.

Obviously the name 'utmost' is not very good ('extremal', 'outlier'? - don't like the latter).

I wonder if the more you abstract out and so the more general a function becomes, the harder it becomes to name it? :)

If I wanted to parameterise 'lowest' or 'highest' I feel there should be a better way to do it, because passing > or < doesn't seem as intuitive as being able to state you want the lowest or highest.

Are there any design errors or misconceptions worth pointing out in the above?

Are there some better examples of functions which use multiple function arguments worth making a part of ones toolkit?


texts: Simulation to find max population of R-pentominos in Game of Life

texts:
I'm brand new to Python and I feel my code is really like what coded in Java.

I try to practice python by small problem and that is to find the maximum population of R-pentomino. Wiki says:

  During this early research, Conway discovered that the R-pentomino
  failed to stabilize in a small number of generations. In fact, it
  takes 1103 generations to stabilize, by which time it has a population
  of 116 and has fired six escaping gliders (these were the first
  gliders ever discovered).

So I write this code:

from sets import Set

__author__ = 'Sayakiss'

dx = [0, 0, 1, -1, 1, -1, 1, -1]
dy = [1, -1, 0, 0, -1, 1, 1, -1]

def is_ng_alive(x, y, original_set):
    cnt = 0;
    for i in range(len(dx)):
        nx = x + dx[i]
        ny = y + dy[i]
        if (nx, ny) in original_set:
            cnt += 1
    if (x, y) in original_set:
        if cnt in [2, 3]:
            return True
    else:
        if cnt == 3:
            return True
    return False

def sim(original_set):
    new_set = Set()
    for (x, y) in original_set:
        for i in range(len(dx)):
            nx = x + dx[i]
            ny = y + dy[i]
            if is_ng_alive(nx, ny, original_set):
                new_set.add((nx, ny))
        if is_ng_alive(x, y, original_set):
            new_set.add((x, y))
    return new_set

def print_cell_set(cell_set, x_size=10, y_size=10):
    for x in range(-x_size, x_size):
        for y in range(-y_size, y_size):
            if (x, y) in cell_set:
                print '*',
            else:
                print '.',
        print ''

cell_set = Set([(0, 1), (0, 2), (1, 0), (1, 1), (2, 1)])
max_size = 0
max_gen = 0
for i in range(1500):
    cell_set = sim(cell_set)
    gen_size = len(cell_set)
    if gen_size > max_size:
        max_size = gen_size
        max_gen = i + 1
    print str(i + 1) + " generation population: " + str(gen_size)

print str(max_gen) + "-" + str(max_size)

Output of my code should be 821-319. It means the maximum population is 319 and occurs in 821-th generation. I'm quite sure it's correct because my friend's code gives the same answer.

Could anyone give me some suggestions about my code?


texts: Calculating prime factors in MIPS assembly

texts:
The goal of this was to be able to enter any number and print out the prime factors of that number. Are there any shorter ways of writing this code? I'm not very familiar with low-level syntax and was hoping somebody could give it a look.

.text
.align 2
.globl main

main:

# compute and display the first prime numbers up to n where n is given. Set n to be 19 but the program should work of any value of n.

li  $v0, 4
la  $a0, prompt
syscall       # call operating sys

li  $v0, 5    # read keyboard into $v0 (number n is the limit)
syscall       # call operating sys
move    $t0,$v0   # store n in $t0

li  $v0, 4    # display message to user
la  $a0, message
syscall

      # call operating sys

li  $v0, 4
la  $a0, space
syscall       # call operating sys

# Load variables into registers
lw  $t1, i  # $t1 = i
lw  $t2, k  # $t2 = k
lw  $t3, p  # $t3 = p
lw  $t5, c  # $t5 = c
lw  $t6, d  # $t6 = d

blt $t0,$t1 L2

li  $v0, 1          # print integer function call 1
move    $a0, $t1        # integer to print
syscall
        # call operating sys

li $v0, 4       # print new line
la $a0, space
syscall                 # call operating sys

    #Outer loop

L2: move $t3, $zero

    # Inner loop

L1: remu $t4, $t1, $t2
bne $t4, $zero, I

move $t3, $t5

I:  add $t2, $t2, $t5   # increment k

blt $t2, $t1 L1

bne $t3, $zero, P

li  $v0, 1          # print integer function call 1
move    $a0, $t1        # integer to print
syscall

li  $v0, 4      # print new line
la  $a0, space
syscall         # call operating sys

P:  add $t1, $t1, $t5   # increment i

move $t2, $t6

bgt  $t1, $t0, E
j L2

E:  li  $v0,    10  # system call code for exit = 10
    syscall     # call operating sys

end:    jr  $ra

.data

prompt:
.asciiz "Please enter the number you wish to find the prime numbers of :  "

message:
.asciiz "The Prime Numbers are : "

space:  .asciiz  "\n    "

#initialization of registers

i:
.word   2

p:
.word   0

k:
.word   2

c:
.word   1

d:
.word   2


texts: Multithreaded Matrix Multiplication in C++, improving efficiency?

texts:
Here is a very simple Matrix Multiplication console application using multiple threads (one per row), I'm just looking for feedback to keep improving :) thank you in advance
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <vector>
    #include <string>
    #include <thread>

using namespace std;

struct Matrix {
    unsigned int cols = 0;
    unsigned rows = 0;
    int **data;

    Matrix() {};
    Matrix(int r, int c) {
        cols = c;
        rows = r;
        data = new int* [rows];
        for (int i = 0; i < rows; ++i) {
            data[i] = new int[cols];
            for (int j = 0; j < cols; ++j)
                data[i][j] = 0;
        }
    }
};

Matrix ReadMatrix(string fileName) {
    fstream file(fileName, fstream::in);
    Matrix matrix;
    try {
        if (file.is_open()) {
            int rows, cols;
            file >> rows >> cols;
            matrix = Matrix(rows, cols);

            for (int r = 0; r < matrix.rows; ++r)
                for (int c = 0; c < matrix.cols; ++c)
                    file >> matrix.data[r][c];

            file.close();
            cout << "File: " << fileName << " read.\n";
        }
        else cout << "could not open file/matrix: " << fileName << "\n";
        return matrix;
    }
    catch (exception ex) {
        if (file.is_open())file.close();
        throw ex;
    }
}

void MultiplyRow(Matrix m1, Matrix m2, Matrix result, int row) {
    for (int c = 0; c < m2.cols; ++c)
        for (int i = 0; i < m1.cols; ++i)
            result.data[row][c] += (m1.data[row][i] * m2.data[i][c]);
    string str = ("Row: " + to_string(row) + " complete.\n");
    cout << str;
}

Matrix MultiplyMatrices(Matrix m1, Matrix m2) {
    try {
        Matrix matrix;
        if (m1.cols == m2.rows) {

            vector<thread> threads;
            matrix = Matrix(m1.rows, m2.cols);

            for (int i = 0; i < m1.rows; ++i)
                threads.emplace_back(MultiplyRow, m1, m2, matrix, i);

            for (int i = 0; i < threads.size(); ++i)
                threads[i].join();

            cout << "Matrices multiplied.\n";
        }
        else cout << "cannot multiply matrices\n";
        return matrix;
    }
    catch (exception ex) {
        throw ex;
    }
}

void WriteMatrixToFile(int **data, int rows, int cols, string fileName) {
    try {
        ofstream file(fileName);
        char SPACE = ' ';
        if (file.is_open()) {
            file << rows << SPACE << cols << "\n";
            for (int r = 0; r < rows; ++r) {
                for (int c = 0; c < cols; ++c) {
                    file << data[r][c] << SPACE;
                }
                file << "\n";
            }
        }
        cout << "Matrix written to: " << fileName << ".\n";
        file.close();
    }
    catch (exception ex) {
        throw ex;
    }
}

int main()
{
    //read matrices
    Matrix matrix1 = ReadMatrix("matrix1.txt");
    Matrix matrix2 = ReadMatrix("matrix2.txt");

    //multiply matrices
    Matrix result = MultiplyMatrices(matrix1, matrix2);

    //put result into results file
    WriteMatrixToFile(result.data, result.rows, result.cols, "result.txt");
}


texts: Optimizing multiplication of two polynomials in GF(2^32)

texts:
I have the following method for multiplying two polynomials in GF(232):

#include <iostream>
#include <cassert>
#include <ctime>
#include <random>
#include <wmmintrin.h>

typedef unsigned short uint16_t;
typedef unsigned int uint32_t;

unsigned get_high16(unsigned x)
{
    return (x >> 16) & 0xffff;
}

unsigned get_low16(unsigned x)
{
    return x & 0xffff;
}

uint32_t mul_reduce_32(uint32_t x, uint32_t y)
{
    const __m128i a = _mm_set_epi32(0, 0, 0, x);
    const __m128i b = _mm_set_epi32(0, 0, 0, y);
    const __m128i c =_mm_clmulepi64_si128(a, b, 0);

    uint16_t D = _mm_extract_epi16(c, 2);

    D ^= _mm_extract_epi32(c, 1) >> 31;
    D ^= _mm_extract_epi32(c, 1) >> 30;
    D ^= _mm_extract_epi32(c, 1) >> 29;
    D ^= _mm_extract_epi32(c, 1) >> 27;
    D ^= _mm_extract_epi32(c, 1) >> 25;

    const uint16_t X3 = _mm_extract_epi16(c, 3);
    const __m128i X3D = _mm_set_epi16(0, 0, 0, 0, 0, 0, X3, D);

    const uint32_t E = _mm_extract_epi32(X3D, 0) << 7;
    const uint32_t F = _mm_extract_epi32(X3D, 0) << 5;
    const uint32_t G = _mm_extract_epi32(X3D, 0) << 3;
    const uint32_t I = _mm_extract_epi32(X3D, 0) << 2;
    const uint32_t J = _mm_extract_epi32(X3D, 0) << 1;

    const uint16_t H1 = X3 ^ get_high16(E) ^ get_high16(F) ^ get_high16(G) ^ get_high16(I) ^ get_high16(J);
    const uint16_t H0 = D ^ get_low16(E) ^ get_low16(F) ^ get_low16(G) ^ get_low16(I) ^ get_low16(J);

    const uint16_t R1 = _mm_extract_epi16(c, 1) ^ H1;
    const uint16_t R0 = _mm_extract_epi16(c, 0) ^ H0;

    return _mm_extract_epi32(_mm_set_epi16(0, 0, 0, 0, 0, 0, R1, R0), 0);
}

The following is a small test program and benchmark for the function.

int main()
{
    assert(mul_reduce_32(1, 1) == 1);
    assert(mul_reduce_32(23523, 34651) == 744709325);
    assert(mul_reduce_32(34652346, 5534651) == 1329462203);

    // A little benchmark
    std::mt19937 rng(std::time(0));
    std::uniform_int_distribution<uint32_t> uint_dist10(0, std::numeric_limits<uint32_t>::max());

    const int N = 100000000;
    std::vector<uint32_t> vec1(N, 0);

    std::cout << "mul_reduce_32\n";
    clock_t startTime = clock();

    for(int i = 0; i < N; ++i)
    {
        vec1[i] = mul_reduce_32(rng(), rng());
    }

    std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC << " seconds.\n";
}

I'm interested in getting more out of mul_reduce_32 in terms of performance. Here are my main concerns:

I'm setting a and b using _mm_set_epi32. Is this even a good idea? I suppose I could have used _mm_load_si128 or _mm_loadu_si128, but the problem seems to be that it doesn't touch the 98 higher bits, and makes those high bits garbage.
Currently, I am using many temporary variables. I could try to help the compiler by removing many of them, but this way the code should be more readable and easier for someone to modify.
I'm using variables of different size -- is this a good idea? I might remember some old wisdom that says I should always just stick to the "most native" unsigned type. Concretely, should I replace say each uint16_t with uint32_t (or even a 64-bit type)?
Should I be mixing __m128i types with unsigned types to begin with? As I understand it, the __m128i types are guaranteed to be mapped to a dedicated register, whereas this is not the case for a uint32_t.

Can you suggest additional optimizations? I'm knowledgeable in C++, but a total newbie with SSE intrinsics.


texts: Asynchronous logging using custom log4j appender and ExecutorService

texts:
I have a requirement to send emails when certain errors are logged(using log4j 1.2.17). But the SMTP appender sends emails in a synchronized manner. I can not use the AsyncAppender either. So I have written my own custom appender and an email sender which utilizes the javax.mail library. The custom appender creates a fixed thread pool of 5 threads using the ExecutorService, and in the custom Appenders append() method I create an object of the email sender class that I have written and submit that to the thread pool.

The Code for the custom appender is as following(some of the non-important segments have been removed eg: some parameters when creating an instance of emailSender)

public class emailAppender extends AppenderSkeleton {

    private static ExecutorService threadPool = null;

    static {
        threadPool = Executors.newFixedThreadPool(5);
    }
    @Override
    protected void append(LoggingEvent event) {
        if(this.closed != true){
            emailSender emailNotification = new emailSender(
                   event.getMessage().toString(),getReceiver());
            threadPool.submit(emailNotification);
        }
    }

    public void close() {
        this.closed=true;
    }

    public boolean requiresLayout() {
        return false;
    }
}

The code for the email sender is as follows

public class emailSender implements Runnable  {

    public emailSender( password, String message, String receiver){
        this.message=message;
        this.receiver=receiver;
    }

    public void run() {
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", getSmtpPort());

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getSmtpUsername(),getSmtpPassword());
                    }
                });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(getSmtpUsername()));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(getReceiver()));
            message.setSubject(getSubject());
            message.setText(getMessage());
            Transport.send(message);
            System.out.println("Notification sent successfully to " + getReceiver() + " for Error : " + getMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

The size of the thread pool was determined considering the maximum number of errors that get logged at one time. And also the downside of the solution being asynchronous is that the logs might not actually get emailed which is acceptable for us.

Currently, this code works fine for me. I would want to know if this code is acceptable for production without considering the fact that the logs might not get emailed due to asynchronous behavior.


texts: Using SSH.NET to interact with a Bash shell

texts:
I'm trying to interact with a bash shell on a router to automate some CLI commands using SSH.NET. I'm not sure if the approach I'm taking is the best one and would like to get some recommendations on how to improve my methology. Although this code does indeed work correctly and does produced consistent results, the timeout involved makes the entire operation take a long time.

Here's the class I wrote to consume the ShellStream:

using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using Renci.SshNet;

public class InteractiveShellStream : IDisposable
{
    private const int TIMEOUT = 3000;
    private bool disposed = false;
    private readonly Stopwatch wait;
    private readonly ShellStream shell;

    public InteractiveShellStream(ShellStream shellStream)
    {
        wait = new Stopwatch();
        shell = shellStream;

        wait.Start();
        while (!shell.DataAvailable && wait.ElapsedMilliseconds < TIMEOUT)
            Thread.Sleep(200);
        wait.Stop();
    }

    public void Write(string command)
    {
        shell.Write(command);
    }

    public void WriteLine(string command)
    {
        shell.WriteLine(command);
    }

    public string Read()
    {
        return shell.Read();
    }

    public string ReadLine()
    {
        return shell.ReadLine();
    }

    public string ReadWithTimeout()
    {
        StringBuilder buffer = new StringBuilder();

        wait.Restart();
        while (!shell.DataAvailable && wait.ElapsedMilliseconds < TIMEOUT)
            Thread.Sleep(100);
        wait.Stop();

        while (shell.DataAvailable)
        {
            buffer.Append(shell.Read());
            wait.Restart();
            while (!shell.DataAvailable && wait.ElapsedMilliseconds < TIMEOUT)
                Thread.Sleep(200);
            wait.Stop();
        }

        return buffer.ToString();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            shell.Dispose();
        }

        disposed = true;
    }

    ~InteractiveShellStream()
    {
        Dispose(false);
    }
}

And here's how I use it:

SshClient client = new SshClient(hostname, port, username, password);
client.Connect();

InteractiveShellStream shell = new InteractiveShellStream(client.CreateShellStream("xterm-mono", 80, 24, 800, 600, 2000));

Console.Write(shell.ReadWithTimeout());

shell.WriteLine("configure");
Console.Write(shell.ReadWithTimeout());

shell.WriteLine("delete firewall group address-group Monitored");
Console.Write(shell.ReadWithTimeout());

shell.WriteLine("commit");
Console.Write(shell.ReadWithTimeout());

shell.WriteLine("exit");
Console.Write(shell.ReadWithTimeout());

shell.Dispose();

client.Disconnect();
client.Dispose();


texts:
Not so long ago I learned how to implement the minimax algorithm with alpha beta pruning, and even created a perfect Tic Tac Toe player. How can I improve this?

public Best chooseMove(boolean side,int[]board,int alpha,int beta,int depth,int maxDepth){
    Best myBest = new Best();
    Best reply;
    int num;

    if(Board.checkGameOver(board)||depth==maxDepth){
        Best fakeBest = new Best();
        fakeBest.setScore(returnPositionScore(board));
        return fakeBest;
    }

    if(side){
        myBest.setScore(alpha);
        num = numberOfEngine;
    }
    else{
        myBest.setScore(beta);
        num = numberOfOpponent;
    }
    ArrayList<Integer> availableMoves = new ArrayList<Integer>(searchAvailableMoves(board));

    for(Integer move:availableMoves){
        board[move.intValue()] = num;
        reply = chooseMove(!side,board,alpha,beta,depth+1,maxDepth);
        board[move.intValue()] = 0;
        if(side&&reply.getScore()>myBest.getScore()){
            myBest.setMove(move.intValue());
            myBest.setScore(reply.getScore());
            alpha = reply.getScore();

        }
        else if(!side&&reply.getScore()<myBest.getScore()){
            myBest.setMove(move.intValue());
            myBest.setScore(reply.getScore());
            beta = reply.getScore();

        }
        if(alpha>=beta){
            return myBest;
        }
    }

    return myBest;
}


texts:
I'm trying to do some util class to operate on enums - convert Enums to its special strings representation via interface method.
String stored in enum constructors.

public enum StatusEnum implements HumanReadableEnum {
    NOT_VERIFIED("Not verified message"),
    INVALID("Invalid message"),
    APPROVED("Approved message");

    private String text;
    public String getHumanReadable(){   // single method of HumanReadableEnum
        return text;
    }

For example instead of HumanReadableEnum[] v = StatusEnum.values()
 I want to get List of inner text messages and do it in generic style.

So now I made a toHumanReadableCollection method:

public class EnumUtils {
    public static <CustomEnum extends Enum & HumanReadableEnum, E extends Class<CustomEnum>>
    List<String> toHumanReadableCollection(E enumClass){
        Enum[] values = enumClass.getEnumConstants();
        List<String> humanReadableCollection = new ArrayList<>(values.length);

        for (Enum value : values) {
            String stringRepresentation = ((CustomEnum)value).getHumanReadable();
            humanReadableCollection.add(stringRepresentation);
        }
        return humanReadableCollection;
    }
}

As a result I can do something like:

List<String> messagesOfEnum1 = EnumUtils.toHumanReadableCollection(MyEnum1.class);
List<String> messagesOfEnum2 = EnumUtils.toHumanReadableCollection(MyEnum2.class);

And have code of toHumanReadableCollection in single place. But I have some doubts about performance.
So could somebody help me to understand the cost of my code? :) Did I touched the reflection?)


texts:
Can the following be rewritten in a more programmatic way, possibly getting rid of the embedded for loops?

function createCards() {
    var cards = [];
    var i, j, k, l;

    for(i = 0; i < 3; i += 1)
        for(j = 0; j < 3; j += 1)
            for(k = 0; k < 3; k += 1)
                for(l = 0; l < 3; l += 1)
                    cards.push([i, j, k, l]);

    return cards;
}

Since this is code is targetting Node, I'm happy to use EcmaScript 6 features.


texts: database connection, fetching rows and handling error in csharp

texts:
Fetching database records and displaying as JSON. Asking for revision to ensure if everything's ok, i.e. connections are properly handled and closed in case of error.

public class Department
{
    public Department(int id, String name)
    {
        this.Id = id;
        this.Name = name;
    }

    public int Id { get; set; }

    public String Name { get; set; }
}

public List<Department> FindAllDepartment()
{
    List<Department> rows = new List<Department>();
    using (SqlConnection sqlConnection = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;pooling=true"))
    {
        SqlCommand command = new SqlCommand("SELECT * FROM Employees.dbo.Department", sqlConnection);
        try
        {
            sqlConnection.Open();
            using (SqlDataReader sqlDataReader = command.ExecuteReader())
            {
                while (sqlDataReader.Read())
                    rows.Add(new Department(sqlDataReader.GetInt32(0), sqlDataReader.GetString(1)));
            }
            return rows;
        }
        finally
        {
            sqlConnection.Close();
        }
    }
}


texts: File Writing optimizations - FileOutputStream vs Writers

texts:
I'm using a simple logger on a server, which uses a method that looks like this:

@Override
public synchronized void write(String logtag, String reason, int severity) {

    long logtime = System.currentTimeMillis();
    String message = "";

    switch (severity) {
        case DEBUG:
            if (!debug) return;
            message = "[" + logtime + "] {DEBUG} " + logtag + "% " + reason + "\n$";
            break;
        case INFO:
            message = "[" + logtime + "] {INFO} " + logtag + "% " + reason + "\n$";
            break;
        case ERROR:
            message = "[" + logtime + "] {ERROR} " + logtag + "% " + reason + "\n$";
            break;
        case FATAL:
            message = "[" + logtime + "] {FATAL} " + logtag + "% " + reason + "\n$";
           break;
        case EXCEPTION:
            message = "[" + logtime + "] {EXCEPTION} " + logtag + "% " + reason + "\n$";
            break;
        default:
            message = "Anthrazit error! Invalid severity: " + severity;
    }

    try {
        out.write(message.getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
        errorOnInit(e);
    }

    if (exitOnFatal && severity == FATAL) {
        System.err.println("Anthrazit exit on fatal: " + message + ". Please check the logs.");
        close();
        System.exit(1);
    }

}

After doing some research I found some classes designed to to this, like PrintWriter and others. Is there any performance difference between my approach and the PrintWriters?


texts: Determine whether a checkbox is checked or unchecked

texts:
I have a jQuery "checkbox checked/unchecked" function that works well. This is a checkbox for turning a particular URL parameter on or off.  But I believe this code could be written a lot tighter. Does anyone have any suggestions?

$('#mapControl').live('click', function(){
var thisUrl = $(location).attr('href');
if($(this).is(':checked')) {
    var lastFour = thisUrl.substr(thisUrl.length - 4);
    var param;
    if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'}
    thisUrl=thisUrl+param;
} else {
    $('#urlParam').val(thisUrl);
    if (thisUrl.indexOf('?mapControl=true') >= 0){
        thisUrl=thisUrl.replace('?mapControl=true','');
    } else if (thisUrl.indexOf('&mapControl=true') >= 0){
        thisUrl=thisUrl.replace('&mapControl=true','');
    }
}
$('#urlParam').val(thisUrl);
});

I was given some suggestions (because i erroneously posted on StackOverflow) and was asked to post my question here. So with the feedback I got - I ended up with this code.

    function getParam() {
    var n;
    var myUrl = window.location.href;
    var lastFour = myUrl.substr(myUrl.length - 4);
    if (lastFour == 'com/') {n='?'} else {n='&'}
    return n;
}

$('#mapControl').on('click', function(){
    var thisUrl = window.location.href;
    var urlParamObj = $('#urlParam');
    if(this.checked === true) {
        var lastFour = thisUrl.substr(thisUrl.length - 4);
        var param = getParam();
        thisUrl=thisUrl+param+'mapControl=true';
    } else {
        urlParamObj.val(thisUrl);
        thisUrl=thisUrl.replace('?mapControl=true','').replace('&mapControl=true','');
    }
    urlParamObj.val(thisUrl);
});

I think this is the tightest it could be and I can use the getParam function for other checkboxes.


texts:
Can you review my code?

class Router {

    /**
     * Store the current URI [0] => Controller/ [1] => Method/ [2]=> parameter
     * @var array
     */
    private $URI = array();

    /**
     * Store an instance of configuration object
     * @var object
     */
    private $config = NULL;

    /**
     *  Store an instance of Application object
     * @var object
     */
    private $app = NULL;

    /**
     * Initialize the router
     */
    public function __construct() {
        $this->startup();
    }

    /**
     *
     * @param object $route
     * @return string
     */
    public function get($route) {
        return $this->config->getRoute($route);
    }

    /**
     * First step, to catch the url and manipulate it.
     */
    private function startup() {

        if ($url = $this->getURL()) {

            $this->app = Application::getAppInstance();
            $this->config = Application::getInstance('Configuration');

            if ($this->validateURL()) {
                $class = (isset($url[1])) ? $url[1] : $this->get('defaultController');
                unset($url[1]);
                $method = (isset($url[2])) ? $url[2] : $this->get('defaultMethod');
                unset($url[2]);
                $params = (count($url > 0)) ? $url : "";
                unset($url);

                if (class_exists($class)) {
                    $controller = $this->app->getInstance($class);
                } else {
                    exit("Class not found");
                }
                if (method_exists($controller, $method)) {
                    if ($params !== "") {
                        call_user_func_array(array($class, $method), $params);
                    } else {
                        $controller->{$method}();
                    }
                } else {
                    exit("Method not found");
                }
            } else {
                exit("URI chars not allowed");
            }
        } else {
            if ($this->get('defaultController') !== "") {
                $this->app->getInstance($this->get('defaultController'));
                call_user_func(array($this->get('defaultController'), $this->get('defaultMethod')));
            } else {
                echo "Default does not added.";
            }
        }
    }

    /**
     * Get the current url and convert into an array
     * @return array
     */
    private function getURL() {
        $currentURL = $_SERVER['QUERY_STRING'];
        if ($currentURL !== "") {
            $currentURL = rtrim($currentURL, '/');
            $currentURL = explode('/', $currentURL);
            unset($currentURL[0]);
            $this->URI = $currentURL;
            return $currentURL;
        }
        return false;
    }

    /**
     * Validate the URI characters
     * @return boolean
     */
    private function validateURL() {
        foreach ($this->URI as $uri) {
            if (!preg_match("/^[" . $this->config->get('allow_uri_chars') . "]+$/i", $uri)) {
                return false;
            }
        }
        return true;
    }

}


texts: Review of HTML and CSS for a newsfeed of posts

texts:
Originally my wireframe was

But I ended up going with this in testing. The image is the result of my new code.

Keep in mind that the actual content is just filler content and will be dynamic. I just wanted to get the styling in place.

I created each article with the following code

HTML

[test] Title of the Discussion

Here we are talking about something. and this is the short brief about it.

     Posted on

       4/4/1984

     by

       Firstname Surname

     View &rarr;

CSS

.discusBox {
  border: #333 solid 1px;
  height: 120px;
  width: 720px;
  position: relative;
  background-color: #fff;
}

.discusTitle {
  line-height: 40px;
  padding-left: 6px;
  position: absolute;
  top: 0;
  left: 120px;
  width: 600px;
  vertical-align: middle;
}

.discusTitle h3 {
  font-size: 18px;
  font-weight: bold;
}

.discusBrief {
  height: 60px;
  width: 600px;
  position: absolute;
  top: 40px;
  left: 120px;
  overflow: hidden;
}
.discusBrief p { padding-left: 6px; }

.discusMeta {
  height: 20px;
  width: 600px;
  position: absolute;
  top: 100px;
  left: 120px;
  font-size: 11px;
  line-height: 20px;
  vertical-align: middle;
}

.discusMetaPostedOn, .discusBy {
  display: inline;
  float: left;
}

.discusMetaPostedOn {
  padding-left: 6px;
  margin-right: 24px;
}
.discusMetaPostedOn p { margin-bottom: 0;}

.discusBy { }

.discusLink {
  float: right;
  background-color: #2fb7e0;
  width: 120px;
  text-align: center;
}

.discusLink a{
  color: #fff;
  text-decoration: none;
  display: block;
}


texts: Interface and implementation of this replacement for Rebol/Red REJOIN

texts:
This is a draft implementation of a function called COMBINE.  It's not intended to be a complex formatting dialect, just a replacement for REJOIN that has a better name and more useful behavior.  Its purpose is laid out pretty thoroughly in this blog entry:

http://blog.hostilefork.com/combine-alternative-rebol-red-rejoin/

But to make a long story short, it is supposed to let you flatten expressions into a string.  If an expression returns a block, then that block will be recursively evaluated using the same rules as if it had been handed to COMBINE directly:

combine: function [
    {Combine evaluated expressions and substitute block variables to produce a string}
    block [block!] "Specification to process"
    /with "Add delimiter between values (will be combined if a block)"
        delimiter [block! any-string! char!]
    /into "Insert output into an existing string instead of making a new one"
        out [any-string!]
    /local
        value
] [
    ;-- No good heuristic for string size yet
    unless into [
        out: make string! 10
    ]

    if block? delimiter [
        delimiter: combine delimiter
    ]

    needs-delimiter: false
    pre-delimit: does [
        either needs-delimiter [
            out: append out delimiter
        ] [
            needs-delimiter: true? with
        ]
    ]

    ;-- Do evaluation of the block until a non-none evaluation result
    ;-- is found... or the end of the input is reached.
    while [not tail? block] [
        set/any 'value do/next block 'block

        ;-- Blocks are substituted in evaluation, like the recursive nature
        ;-- of parse rules.

        case [
            unset? :value [
                ;-- Ignore unset? (precedent: any, all, compose)
            ]

            none? :value [
                ;-- Skip all nones
            ]

            any [
                function? :value
                closure? :value
            ] [
                throw make error! "Evaluation in COMBINE gave function/closure"
            ]

            block? value [
                pre-delimit
                out: combine/into value out
            ]

            any-block? value [
                ;-- all other block types as *results* of evaluations throw
                ;-- errors for the moment.  (It's legal to use PAREN! in the
                ;-- COMBINE, but a function invocation that returns a PAREN!
                ;-- will not recursively iterate the way BLOCK! does)
                throw make error! "Evaluation in COMBINE gave non-block! block"
            ]

            any-word? value [
                ;-- currently we throw errors on words if that's what an
                ;-- evaluation produces.  Theoretically these could be
                ;-- given behaviors in the dialect, but the potential for
                ;-- bugs probably outweighs the value (of converting implicitly
                ;-- to a string or trying to run an evaluation of a non-block)
                throw make error! "Evaluation in COMBINE gave symbolic word"
            ]

            true [
                pre-delimit
                out: append out (form :value)
            ]
        ]
    ]
    either into [out] [head out]
]

Pretty much anything here is up for review; both the interface and the implementation.  A few things to wonder about:

What would be a good heuristic for the output size?
Right now combine [if (1 > 2) {something}] returns an empty string.  Initially I thought that if it only received NONE, then it should return NONE.  But the existence of the /INTO refinement makes that not possible to distinguish, as it's supposed to return the insertion position.  Is this distinction more important than offering /INTO to the caller (rejoin didn't...).
How should other string types be returned?  Currently the only way to get a non-string is to use /into, in order to avoid the sensitivity of the type of the first element that REJOIN has.  But should there be an /AS refinement for passing the target type?


texts: Packet Scout (show traffic on specified port)

texts:
I've just made a github repository for a simple packet scout in C#. It is my first time using C# (other than Neoaxis 3D engine logic) since I am more familiar with C#. Below is the main bulk of the code that I'd like to improve. You can see all of the code here. If you have any suggestions please share them.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace Packet_Scout
{
    public partial class Form1 : Form {
        private const string endl = "\n";
        private UdpClient socket;
        private bool listening = false;
        private static string buff = "";

        public Form1() {
            InitializeComponent();
        }

        private void downloadbuffer() {
            rblog.Text += buff;
            buff = "";
        }

        private void btnstart_Click(object sender, EventArgs e) {
            if (!listening) {
                rblog.Text = "";
                socket = new UdpClient((int)ndoor.Value);
                tmbuf.Start();
                bgw.RunWorkerAsync();
                btnstart.Text = "Stop";
                listening = true;
            } else {
                tmbuf.Stop();
                downloadbuffer();
                bgw.CancelAsync();
                socket.Close();
                rblog.Text += "Stopped!";
                listening = false;
                btnstart.Text = "Start";
            }
        }

        private void bgw_DoWork(object sender, DoWorkEventArgs e) {
            buff = "Listening on port " + ndoor.Value + endl;

            while (socket != null) {
                if (socket.Available > 0) {
                    IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
                    Byte[] recvbytes= socket.Receive(ref ipep);

                    buff += "Client (" + ipep.Address + ":" + ipep.Port + "): ";
                    foreach (Byte b in recvbytes) buff += b.ToString() + " ";
                    buff += endl;
                }
            }
        }

        private void tmbuf_Tick(object sender, EventArgs e) {
            downloadbuffer();
        }
    }
}


texts: Python generator to produce lattice points on an n-simplex.

texts:
Looking for a code review, and hopefully to learn something if someone has a nicer solution.  Here's what I wrote:

from __future__ import division, print_function
from future_builtins import *
import numpy as np

def _walk(num_dims, samples_per_dim, max_):
    if num_dims == 0:
        yield np.array([(max_ - 1) / (samples_per_dim - 1)])
    else:
        for i in range(max_):
            for rest in _walk(num_dims - 1, samples_per_dim, max_ - i):
                yield np.concatenate((np.array([i]) / (samples_per_dim - 1),
                                      rest))

def walk(num_dims, samples_per_dim):
    """
    A generator that returns lattice points on an n-simplex.
    """
    return _walk(num_dims, samples_per_dim, samples_per_dim)

So, list(walk(2, 3)) yields:

[array([ 0.,  0.,  1.]),
 array([ 0. ,  0.5,  0.5]),
 array([ 0.,  1.,  0.]),
 array([ 0.5,  0. ,  0.5]),
 array([ 0.5,  0.5,  0. ]),
 array([ 1.,  0.,  0.])]


texts: Finding min and max values of an iterable on the fly

texts:
This is a follow up for my question about optimizing solution for DNA Health HackerRank problem.

Short re-cap:

  You are given 2 arrays (genes and health), one of
  which have a 'gene' name, and the other - 'gene' weight (aka
  health). You then given a bunch of strings, each containing values m and n, which denote the start and end of the slice to be applied
  to the genes and health arrays, and the 'gene'-string, for which
  we need to determine healthiness. Then we need to return health-values
  for the most and the least healthy strings.

At the advice from AJNeufeld, I optimized my code into the following. Unfotunately, it still fails to execute on large testcases, such as this one.

So, the question now is: what else can I do to make the solution less expensive?

if __name__ == '__main__':
    n = int(input())

    genes = input().rstrip().split()
    genes_regex = [re.compile(f"(?={gene})") for gene in genes]
    health = list(map(int, input().rstrip().split()))

    s = int(input())
    min_weight = math.inf
    max_weight = -math.inf

    for s_itr in range(s):
        m,n,gn = input().split()
        weight = 0
        for i in range(int(m),int(n)+1):
            if genes[i] in gn:
                matches = len(re.findall(genes_regex[i], gn))
                weight += health[i]*matches

        if weight < min_weight:
            min_weight = weight
        if weight > max_weight:
            max_weight = weight

    print(min_weight, max_weight)


texts:
I have written a short C/C++ code finding root by bisection. (This is a simple iterative numerical method allowing to find the root of an equation i.e. x such that f(x) = 0). Bisection Method

The header simply consists of guards and of the following lines:

#include <functional>
double bisection(double x1,
                 double x2,
                 double e,
                 std::function<double(double)>& f);

In order to get plain C code, the std::function<double(double)> in the signature of the function has to be turned into a double(*f)(double);

I have two questions.

The first is if this code can be improved (minor improvements).
The second is if recursion is a good choice.

namespace {
    double bisection(double x1,
                     double x2,
                     double e,
                     std::function<double(double)>& f,
                     double fx1,
                     double fx2){
        double mid = x1*0.5 + x2*0.5;
        if (x2 - x1 < e)
            return mid;
        double fmid = f(mid);
        if ((fmid>0.0) == (fx1 > 0.0))
            return bisection(mid, x2, e, f, fmid, fx2);
        return bisection(x1, mid, e, f, fx1, fmid);
    }
}

double bisection(double x1,
                 double x2,
                 double e,
                 std::function<double(double)>& f){
    double fx1 = f(x1);
    double fx2 = f(x2);
    return bisection(x1, x2, e, f, fx1, fx2);
}

An example of main using my code is:

#include "bisection.hpp"
int main(){
    bisection(0.0, 1.0, 1.0E-6, [](double x){return x*x-0.5;})

    return 0;
}

please notice that x1 and x2 are expected to be ordered: x1 < x2. Moreover the user should be aware of the fact that there will be a log_2((x_2-x_1)/tolerance) calls stack.


texts: Refining/simplifying jquery for hiding and showing fieldsets

texts:
I'm starting to figure out this jquery stuff, but as you can see there's a long ways to go. How would I approach refining and simplifying this snippet. Its purpose is to show a fieldset[data-content] with inputs inside when you click a "show" link, and to hide said fieldset and remove all "required" attributes when you click the "Hide" link.

I'm using data-* for all functionality and .class for styling. Hence not using classes/ID's for these items.

JQuery

$(function() {
  $('[data-content]').hide(); // hide content initially
  $('[data-show]').click(function() {
    $('[data-content]').fadeIn('slow'); //fade in/show content
    $(this).addClass('active'); //add .active to "show" link
    $('[data-hide]').removeClass('active'); // remove .active from "hide" link
    $("[data-content] :input").prop('required',true); // add required if :visible
  return false;
  });
  $('[data-hide]').click(function() {
    $('[data-content]').fadeOut('fast'); //fade out/hide content
    $(this).addClass('active'); //add active class to "hide" link
    $('[data-show]').removeClass('active'); //remove active class from "show" link
    $("[data-content] :input").prop('required',null); // remove "required" if :hidden
  return false;
  });
});

HTML example

Show
Hide

<fieldset data-content>
  <input type="text" placeholder="Yada">
</fieldset>
<fieldset>
  <input type="text" placeholder="yada2" required>
</fieldset>


texts:
https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799

  Given a non-empty array of integers, return the k most frequent
  elements.

  Example 1:

  Input: nums = [1,1,1,2,2,3], k = 2
  Output: [1,2]

  Example 2:

  Input: nums = [1], k = 1 Output: [1] Note:

  You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  Your algorithm's time complexity must be better than O(n log n), where
  n is the array's size.

using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

//good example for bucket sort
namespace SortingQuestions
{
    /// <summary>
    /// https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
    /// </summary>
    [TestClass]
    public class TopKFrequentTest
    {
        [TestMethod]
        public void SimpleUseCaseTest()
        {
            int[] nums = { 1, 1, 1, 2, 2, 3 };
            int k = 2;
            int[] expected = { 1, 2 };
            CollectionAssert.AreEqual(expected, TopKFrequentClass.TopKFrequent(nums, k).ToArray());
        }
    }

    public class TopKFrequentClass
    {
        public static IList<int> TopKFrequent(int[] nums, int k)
        {
            Dictionary<int, int> number2Count = new Dictionary<int, int>();

            //we count how many times each number appears
            foreach (var num in nums)
            {
                number2Count.TryGetValue(num, out var temp);
                number2Count[num] = temp + 1;
            }

            List<int>[] bucket = new List<int>[nums.Length + 1];

            //we allocate an array in the size of the original list of numbers
            //we iterate all of the numbers and for add each number to the index in the array
            // the index represents how many times that number appeared
            //
            //    0 times -> none
            //    1 times -> number 3
            //    2 times -> number 2
            //    3 times -> number 1
            //    4 times -> none
            //    5 times -> none
            foreach (var key in number2Count.Keys)
            {
                int frequency = number2Count[key];
                if (bucket[frequency] == null)
                {
                    bucket[frequency] = new List<int>();
                }
                bucket[frequency].Add(key);
            }

            List<int> result = new List<int>();
            // we iterate the list bucket in reverse until the number of items in the result
            // list equals k, because we iterate in reserve we get the biggest numbers
            for (int pos = bucket.Length - 1; pos >= 0 && result.Count < k; pos--)
            {
                if (bucket[pos] != null)
                {
                    result.AddRange(bucket[pos]);
                }
            }

            return result;
        }
    }
}

I really like this question and it took me some time to understand how to implement the bucket sorting.

I know I can also use MaxHeap.
Since C# doesn't have a MaxHeap, do you think using a SortedList can help here somehow with the performance? (remember the question limitations)

I am mainly looking for performance optimizations.


texts: Transaction handling for multiple SQL statements

texts:
In this code I update two tables called Payment and SalaryTrans. First I insert records (Salary payments) to Payment table and then I update SalaryTrans table. When a record is inserted to Payment table, ID is auto generated (auto increment column) and then that ID should be updated in SalaryTrans table (for all matching records).

The following code compiles and runs giving the desired output, but I just want to know whether the transactions are handled properly.  Also, are there any other flows in this code?

Could you please review and give your feedback?

public int InsertPaymentDetails(List<PaymentInfo> list, int totalRecords, decimal totalAmount )
{
    const string selectSatement = @"INSERT INTO Payment (payment_type, reference, payment_date, total_records, total_amount)
VALUES(@type, @reference, @date, @totalRecords, @totalAmount ) ";

    const string updateStatement = @"UPDATE SalaryTrans SET payment_id = (SELECT TOP 1 id FROM Payment ORDER BY Payment.id DESC)
WHERE SalaryTrans.employee_id = @employeeID AND SalaryTrans.reference = @reference ";

    //An item is refered in the list just to get the PaymentType, PaymentDate etc. as these information are common for all items in the list
    var first = 0;
    var payInfo = list[first];

    //To get the affected rows following variables are declared
    int result= 0;
    int affectedRecords = 0;

    using (SqlConnection sqlConnection = new SqlConnection(db.ConnectionString))
    {
        sqlConnection.Open();
        using (SqlTransaction sqlTrans = sqlConnection.BeginTransaction ())
        using (SqlCommand sqlCommand = new SqlCommand(selectSatement, sqlConnection,sqlTrans))
        {
            sqlCommand.Parameters.Add("@type", SqlDbType.VarChar).Value = payInfo.PaymentType;
            sqlCommand.Parameters.Add("@date", SqlDbType.Date).Value = payInfo.PaymentDate;
            sqlCommand.Parameters.Add("@reference", SqlDbType.VarChar).Value = payInfo.Reference;
            sqlCommand.Parameters.Add("@totalRecords", SqlDbType.Int).Value = totalRecords;
            sqlCommand.Parameters.Add("@totalAmount", SqlDbType.Decimal).Value = totalAmount;

            sqlCommand.ExecuteNonQuery();

            SqlParameter paramEmployeeID = new SqlParameter("@employeeID", SqlDbType.Int);
            sqlCommand.Parameters.Add(paramEmployeeID);

            foreach (PaymentInfo p in list)
            {
                paramEmployeeID.Value = p.EmployeeID;
                sqlCommand.CommandText = updateStatement; //Command text changed to update second table
                result = sqlCommand.ExecuteNonQuery();
                //If at least one recored was inserted then the recordsAffected should be +1
                if (result == +1)
                    affectedRecords = 1;
            }
            sqlTrans.Commit();
            return affectedRecords;
        }
    }
}


texts: Msbuild batch - if any build fails than skip the last one

texts:
I have this batch that builds some projects using msbuild.

What I want to do is to skip building my-last.proj if any of the above builds fail: my-proj1.proj to my-proj5.proj using environment variables.

I'm sure that there is another cleaner way to do this, but so far I just can't figure it out.

msbuild /target:Win32 my-proj1.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED32=1
)
msbuild /target:X64 my-proj1.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED64=1
)

msbuild /target:ManagedWin32 my-proj1.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED32=1
)
msbuild /target:ManagedX64 my-proj1.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED64=1
)

msbuild /target:Win32 my-proj2.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED32=1
)
msbuild /target:X64 my-proj2.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED64=1
)

msbuild /target:Win32 my-proj3.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED32=1
)
msbuild /target:Win32 my-proj4.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED32=1
)
msbuild /target:Win32 my-proj5.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED32=1
)

IF NOT "%FAILED32%" == "1" (
msbuild /target:setup32 my-last.proj
)

msbuild /target:X64 my-proj3.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED64=1
)
msbuild /target:X64 my-proj4.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED64=1
)
msbuild /target:X64 my-proj5.proj
IF NOT ERRORLEVEL 0 (
    set /p BUILDFAILED64=1
)

IF NOT "%FAILED64%" == "1" (
msbuild /target:setup64 my-last.proj
)

Does anyone have any ideas?


texts:
This is a basic name generator I just wrote and want some feedback.
It basically chooses between a vowel or a consonant and appends it to a string. Note that it never puts two vowels or two consonants directly together, as it checks for that.

import random

vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x', 'y', 'z']

def generate_name(length):
    if length <= 0:
        return False

    full_syl = ''
    for i in range(length):
        decision = random.choice(('consonant', 'vowel'))

        if full_syl[-1:].lower() in vowels:
            decision = 'consonant'
        if full_syl[-1:].lower() in consonants:
            decision = 'vowel'

        if decision == 'consonant':
            syl_choice = random.choice(consonants)
        else:
            syl_choice = random.choice(vowels)

        if full_syl == '':
            full_syl += syl_choice.upper()
        else:
            full_syl += syl_choice

    return full_syl

for i in range(100):
    length = random.randint(3, 10)
    print(generate_name(length))


texts: How can this layered PHP architecture be improved?

texts:
This is my first "large scale" system I've designed for myself. Since I'm more of a front end developer than backend developer, I'm not sure if my architecture is sound.

I've created a Factory class which I use to create all my classes and connect to the DB. I think I've tried to use used Singelton(?) pattern, but I'm not really sure.

It probably would be easier if you knew more about the system, but in short it's an online directory mixed with user interaction and social media.

It would be great if I could get some feedback on this.

My factory class

include_once('abc.class.php');

class Factory {
  // One function for each class I include
  // This is the only place I include class files
  function new_abc_obj($id = NULL) { return new Abc(Conn::get_conn(), $id); }
}

My DB connection class

class Conn {
  private static $conn = NULL;

  /* Establish PDO DB connection */
  private static function init() {
      $conf = self::config();
      try {
        self::$conn = new PDO($conf['dsn'], $conf['user'], $conf['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
      }
      catch (PDOException $e) {
        // We remove the username if we get [1045] Access denied
        if (preg_match("/\b1045\b/i", $e->getMessage()))
          echo "SQLSTATE[28000] [1045] Access denied for user 'name removed' @ 'localhost' (using password: YES)";
        else
          echo $e->getMessage();
      }
  }

  /* Get DB connection */
  public static function get_conn() {
    if (!self::$conn) { self::init(); }
    return self::$conn;
  }

  /* Get username, password and db data from config.php */
  private static function config() {
    $conf = array();

    $conf['user']    = DB_USER;
    $conf['pass']    = DB_PASSWORD;
    $conf['dsn']     = 'mysql:dbname='.DB_NAME.';host='.DB_HOST;

    return $conf;
  }
}

My class interface

interface iAbc {
  public function one();
  public function two();
}

My Business Logic Layer (BLL)

class Abc extends AbcDAO implements iAbc {
  private $data = array();
  protected $db;

  function __construct(&$db, $id) {
    $this->db = &$db;

    if($id) {
      $this->setData($id);
    }
  }

  // __set, __get, __isset is here

  public function one(){};
  public function two(){
    $result = parent::get_some_data();
    return $result;
  };
}

My Data Access Layer (DLL)

class AbcDAO {
  protected function get_some_data($name){
    $sql ="SELECT 123;";
    $stmt = $this->db->prepare($sql);
    $stmt->bindParam(':name', $name, PDO::PARAM_STR);
    $stmt->execute();
    $result = $stmt->fetchAll();
    return $result;
  }
}

And this is how I create the object:

$my_abc = Factory::new_abc_obj();
$test = $my_abc->two();


texts:
Here is how to transform a Zorglub (it is an API that I can not modify):

Zorglub transformedZorglub = zorglub.transform()

I am given a java.util.List<Zorglub> and I must transform them all, then afterwards I will perform more operations on the transformed Zorglubs. After transformation I never use the originals anymore. This question is only about the transformation part. I wrote this:

List<Zorglub> transformedZorglubs = new ArrayList<Zorglub>(zorglubs.size())
zorglubs.each {
    transformedZorglubs.add(
        it.transform()
    )
}
zorglubs = transformedZorglubs

Is there something smarter or more elegant to do?

In particular, something that would avoid creating a new list and using twice as much memory, while avoiding bugs that often arise when modifying a list while iterating over it?


texts: Memoization of Fibonacci using generic Int => Int helper

texts:
I'm trying to understand memoization using Scala. I took the Fibonacci sequence as an example because of the high cost of recursively computing numbers in the sequence without memoization.

class memoize private (val f: Int => Int) {
  import scala.collection.mutable
  val cache = new mutable.HashMap[Int, Int]()
  def memoized_f(x : Int) : Int =
    cache.getOrElseUpdate(x, f(x))
}
object memoize {
  def apply(f: Int => Int) : Int => Int = new memoize(f).memoized_f
}

val fib : Int=>Int = memoize((n:Int) => {
  if (n <= 1) n else fib(n-1) + fib(n-2)
})

With memoization the function fib is called 10 times compared to 276 without it. I discovered that val fib is required: def fib results in the memo object being created on each call to fib!

I realize that this could eventually be generalized by parameterising memoize with a type T (or key K and value V) to replace Int. But I wanted to start somewhere simple to understand how the technique works. Given that I'm looking at memoizing only Int => Int functions, could what I've done be improved in terms of function or style?

I've also discovered a couple of related items on the web: Is there a generic way to memoize in Scala? and Memo in ScalaZ (see also this tutorial), but I'm not entirely sure how what I've done relates to them.


texts: Concatenating results in a comma separated list

texts:
I am trying to list all of the employees linked to a certain 'Interaction' I want the employees listed on one line with comma's separating them, I have the following query which works but is very slow.

SELECT CONVERT(VARCHAR(254), COALESCE(STUFF((
SELECT ', ' + LTRIM(RTRIM(REPLACE(emp1.Full_Name,CHAR(9),'')))
FROM Employee emp1 WITH (nolock)
JOIN Rn_Int_Employee rie WITH (nolock) on emp1.Employee_Id = rie.Employee_Id
WHERE rnint.Rn_Interactions_Id = rie.Rn_Interactions_Id
GROUP BY emp1.Full_Name
ORDER BY emp1.Full_Name
FOR XML PATH (''),TYPE ).value('text()[1]', 'nvarchar(max)'), 1, 2, '')
,STUFF((
SELECT ', ' + LTRIM(RTRIM(REPLACE(emp1.Full_Name,CHAR(9),'')))
FROM Employee emp1 WITH (nolock)
WHERE rnint.Rn_Create_User=emp1.Rn_Employee_User_Id
GROUP BY emp1.Full_Name
ORDER BY emp1.Full_Name
FOR XML PATH (''),TYPE ).value('text()[1]', 'nvarchar(max)'), 1, 2, '')))
Employees
FROM Rn_Interactions rnint

Does anyone have any recommendations for a more efficient way of doing this?


texts:
I have a series if statements where I am trying to find the highest resolution file in an set of files. Is there a way that I can refactor this code to be shorter and or cleaner?

begin
  icon = icons.find { |name, _| name.downcase.include? 'xxxhdpi' }
  if icon.nil?
    icon = icons.find { |name, _| name.downcase.include? 'xxhdpi' }
  end
  if icon.nil?
    icon = icons.find { |name, _| name.downcase.include? 'xhdpi' }
  end
  if icon
    File.open(tmp_icon.path.to_s, 'wb') do |f|
      icon { |_, data| f.write data }
      s3_icon = bucket.objects[icon_path].write(Pathname.new(tmp_icon.path),
                                              content_type: 'image/png')
      icon_url = s3_icon.public_url(secure: true)
    end
  end
ensure
  tmp_icon.close
  tmp_icon.unlink
end


texts: Count word frequencies, and print them most-frequent first

texts:
I'm writing a comparison of a simple word-counting program in various languages. The task is to count the frequencies of unique, space-separated words in the input, and output the results most frequent first. Case should be normalized to lowercase (ASCII is okay).
But it's been a long time since I've written C++ (before the C++11 days). Is this idiomatic modern C++? Any improvements I could make to make this more idiomatic or simpler (I'm not looking for efficiency improvements here). I want to stick to the standard library.
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

int main() {
    string word;
    unordered_map<string, int> counts;
    while (cin >> word) {
        transform(word.begin(), word.end(), word.begin(),
            [](unsigned char c){ return tolower(c); });
        counts[word]++;
    }

    vector<pair<string, int>> ordered(counts.begin(), counts.end());
    sort(ordered.begin(), ordered.end(), [](auto &a, auto &b) {
        return a.second > b.second;
    });

    for (auto count : ordered) {
        cout << count.first << " " << count.second << "\n";
    }
    return 0;
}


texts: Scalability of running commands from user input

texts:
Here is some code I have that has been extracted and shrunk down from a project of mine.

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

#define streq(x, y) (strcmp((x), (y)) == 0)
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

typedef struct
{
    const char *cmd;
    void* (*fn)(void);
} __attribute__((__packed__)) Command;

void* getTime(void)
{
    return ((void*)((uintptr_t)time(NULL)));
}

void* getDay(void)
{
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    return ((void*)((uintptr_t)(tm.tm_wday)));
}

static Command commands[] =
{
    {"time", getTime},
    {"day", getDay},
};

int main(int argc, char *argv[])
{
    for (int i = 0; i < ARRAY_SIZE(commands); ++i)
    {
        Command *p = commands+i;
        if (streq(argv[1], p->cmd)) printf("%d\n", (int)p->fn());
    }
}

When run with some given input, it runs the method associated with that input. Since this is a scaled down version of my project, it can only run two commands.

$ ./test-command day
4

Right now, my implementation should run with \$ O \left( n\right)\$ time complexity.  This would be unacceptable with the hundreds of thousands of commands my project could scale to. I am looking for reviews on scalability and optimization, and how well my Command structure and function pointer template would scale as well.


texts: Compute spherical distance matrix from list of geographical coordinates

texts:
I've got a list of geographic coordinates ([lat, long]) and want to compute the corresponding matrix of distances. Distance shall be spherical distance in km.

def distance_on_unit_sphere(coord1, coord2):
    lat1 = coord1[0]
    long1 = coord1[1]
    lat2 = coord2[0]
    long2 = coord2[1]
    # Convert latitude and longitude to spherical coordinates in radians.
    degrees_to_radians = math.pi/180.0
    phi1 = (90.0 - lat1)*degrees_to_radians
    phi2 = (90.0 - lat2)*degrees_to_radians
    theta1 = long1*degrees_to_radians
    theta2 = long2*degrees_to_radians
    # Compute spherical distance from spherical coordinates.
    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
           math.cos(phi1)*math.cos(phi2))
    arc = math.acos( cos )
    # Multiply with radius of the earth in km (GRS 80-Ellipsoid)
    distance = arc * 6371.007176
    return distance

import math
from collections import OrderedDict

    coordinates_dict = {u'YALE UNIVERSITY': [41.3111, -72.9267],
                        u'YONSEI UNIVERSITY': [37.5664, 126.939],
                        u'YORK UNIVERSITY': [43.7731, -79.5036],
                        u'YUAN ZE UNIVERSITY': [24.9697, 121.267],
                        u'ZHEJIANG UNIVERSITY': [30.2636, 120.121],
                        u'ZHONGNAN UNIVERSITY OF ECONOMICS AND LAW': [30.4752, 114.394]}

    distance_dict = {}

    for university in coordinates_dict.keys():
        distance_dict[university] = OrderedDict()
        coord1 = coordinates_dict[university]
        for other_university in coordinates_dict.keys():
            coord2 = coordinates_dict[other_university]
            distance = distance_on_unit_sphere(coord1, coord2)
            distance_dict[university][other_university] = distance

While distance_on_unit_sphere() is certainly already optimal (I got it from johndcook.com), I think the process to compute the matrix could be sped up. Right now I use a nested loop, I believe that's quite inefficient, right?


texts: Java class for simple statistics calculations

texts:
I've written a class for a project of mine whose responsibility is to perform basic statistic calculations like mean, median and mode. The aim is for it to be a helper class, so it should not be instantiable. I later want to extend it to include weighted mean and range/interquartile range as well as variance.

Here is the code:

import java.util.Arrays;
import java.util.HashMap;

public class BasicStatistics {

    //Prevent instantiation...
    //throws UnsupportedOperationException to defend against reflection
    private BasicStatistics() throws UnsupportedOperationException{
        throw new UnsupportedOperationException();
    }

    public static class Mode {

        private static int mode;
        private static HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();

        private Mode() throws UnsupportedOperationException{
             throw new UnsupportedOperationException();
        }

        public static int calculateMode(int ints[]){
            int max = 0;
            int temp = 0;

            for (int i = 0; i < ints.length; i++){
                if (hm.get(ints[i]) != null){
                    int count = hm.get(ints[i]);
                    count += 1;
                    hm.put(ints[i], count);
                    if (count > max){
                        max = count;
                        temp = ints[i];
                    }
                } else {
                     hm.put(ints[i], 1);
                }
            }

            if (temp == 0){
                mode = ints[0];
            } else {
                mode = temp;
            }

            return mode;
        }

    }

    public static class Mean {

        private static float mean;

        private Mean() throws UnsupportedOperationException{
            throw new UnsupportedOperationException();
        }

        public static float calculateMean(int ints[]){

            for (int element  : ints){
                mean += element;
            }

            return mean / ints.length;
        }

    }

    public static class Median {

        private static float median;

        private Median() throws UnsupportedOperationException{
            throw new UnsupportedOperationException();
        }

        public static float calculateMedian(int ints[]){

            Arrays.sort(ints);

            if (ints.length % 2 == 0){
                median = (float) (ints[ints.length / 2] + ints[(ints.length / 2) - 1]);
                median /= 2;
            } else {
                median = (float) ints[ints.length / 2];
            }

            return median;
        }
    }
}


texts:
I wrote this code in C++ to convert an array to a binary tree.

For instance, int nums[] = {7,5,9,1,7,3} to a binary tree (root-7, root's left child-5, root's right child-9...).

( here, I made a function named 'create_tree()' which only take one argument )

Is there any shorter way to do this?

#include <iostream>
#include <cstdlib>
#include <cstdio>

template<class E>
struct TNode{
    E value;
    TNode<E>* leftChild;
    TNode<E>* rightChild;

    TNode<E>(){
        this->value = NULL;
        this->leftChild = NULL;
        this->rightChild = NULL;
    }

    TNode<E>(E value){
        this->value = value;
        this->leftChild = NULL;
        this->rightChild = NULL;
    }
};

template<class E>
class BTree{
private:
    TNode<E>* root;

    /**
        build and return the pointer to a binary tree for given array 'arr' and array         size 'len'
    */
    TNode<E>* build(E* arr, int len){

        TNode<E> *subRoot = new TNode<E>(arr[0]);
        if (len == 1){
            return subRoot;  // terminating function - at the leaf
        }
        E* elementsToLeft = new E[len];  // array to store the left subtree children
        E* elementsToRight = new E[len];  // array to store the right sub tree     children

        int counterLeft = 0;
        int counterRight = 0;

        for (int i = 1; i < len; i = (i * 2) + 1){
            for (int j = i; j < i + ((i + 1) / 2); j++){
                elementsToLeft[counterLeft] = arr[j]; // appending the array which     has children of left sub tree
                counterLeft++;
                if ((j + (i + 1) / 2)<len){  // check whether there are childs to     store in the right sub tree....
                    elementsToRight[counterRight] = arr[j + (i + 1) / 2]; //   appending the array which has children of left sub tree
                    counterRight++;
                }

            }
        }
        subRoot->leftChild = build(elementsToLeft, counterLeft);  // recursive call>     array- left sub tree's children and size
        subRoot->rightChild = build(elementsToRight, counterRight); // recursive     call> array- right sub tree's children and size
        return subRoot;
    }

public:

    /**
    add the value specified by newvalueas the left child of the tree node specified     by parent,if the node does not have a left childalready.
    returns 1 if addition is successful and returns -1 in failure.
    */
    template <class E>
    int intaddLeftChild(TNode<E>* parent, E newvalue){
        if (parent->leftChild != NULL){ return -1; }
        TNode<E> *temp = new TNode<E>(newvalue);
        parent->leftChild = temp;
        return 1;
    }

    /**add the value specified by newvalueas the right child of the tree node     specified by parent, if the node does not have a right childalready.
    returns 1 if addition is successful and returns -1 in failure.
    */
    template <class E>
    int intaddRightChild(TNode<E>* parent, E newvalue){
        if (parent->rightChild != NULL){ return -1; }
        TNode<E> *temp = new TNode<E>(newvalue);
        parent->rightChild = temp;
        return 1;
    }

    /**
    function to create and return the pointer to a Binary tree from an array
    input an array. eg:- int i[] = {3,5,7} ; create_tree(i);
    */
    template<class E, int N>
    TNode<E>* create_tree(E(&elements)[N]){
        int length = N;
        return build(elements, N);
    }
};

int main(){
    //to demonstrate
    int nums[] = { 7,5,9,1,7,3};
    BTree<int> mal;

    TNode<int>* BinaryTree = mal.create_tree(nums); // store the made binary tree     from nums and point it by the pointer, BinaryTree.

}


texts: Regular expression to get a string between two strings where the last string can also be 'end of string'

texts:
I intend to extract a URL search parameter value using a regular expression in plain javascript. The parameter can be in any order in the search query.
So is there a better approach than ?

const query1 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue';

const query2 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue&someMoreParam=dummy_value2';

let requiredParam = query1.match(/requiredParam=(.*?)$/) || [];
console.log('Using regex "/requiredParam=(.*?)$/"');
console.log(`For Query1: result = ${requiredParam[1]}`);

requiredParam = query2.match(/requiredParam=(.*?)&/) || [];
console.log('Using regex "/requiredParam=(.*?)&/"');
console.log(`For Query2: result = ${requiredParam[1]}`);

console.log('Combining both regex "/requiredParam=(.*?)(&|$)/"');
requiredParam = query1.match(/requiredParam=(.*?)(&|$)/) || [];
console.log(`For Query1: result = ${requiredParam[1]}`);
requiredParam = query2.match(/requiredParam=(.*?)(&|$)/) || [];
console.log(`For Query2: result = ${requiredParam[1]}`);

Edit:
My constraints:

Browser compatibility including IE 9
Using only vanilla javascript


texts: Helper method to check if 3 numbers match some of the valid results

texts:
I have this helper method to check if 3 numbers match some of the valid results (XXX+bool, XXX, -XX, X-X, XX-, --X).

const categoryNumber = (numbers, myBool, resultNumbers) => {
  const matches = numbers.map((val, index) => val === resultNumbers[index]);
  if (matches[0] && matches[1] && matches[2] && myBool) return 1;
  if (matches[0] && matches[1] && matches[2]) return 2;
  if (matches[0] && matches[1]) return 3;
  if (matches[1] && matches[2]) return 4;
  if (matches[0] && matches[2]) return 5;
  if (matches[2]) return 6;
  return 0;
};

Type vars?:

numbers:       numeric array size 3
myBool:        boolean
resultNumbers: numeric array size 3


texts: How to get a centered mean (excluding max and min value) of a list in Python?

texts:
I'm learning Python & practising from this site and here is the particular problem at hand:

Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more.
centered_average([1, 2, 3, 4, 100]) → 3
centered_average([1, 1, 5, 5, 10, 8, 7]) → 5
centered_average([-10, -4, -2, -4, -2, 0]) → -3

My solution is as follows:
def centered_average(nums):
  items = len(nums)
  total = 0
  high = max(nums)
  low = min(nums)
  for num in nums:
    total += num
  aveg = (total -high-low) / (items-2)
  return aveg

The above code works fine. I want to ask more experienced programmers if this could be done in a better manner - or is this solution fine?


texts: Getting an array of certain objects within an object

texts:
I'm trying to get an array of all "form" objects within a large "masterFormObject" object. Is this the cleanest way to do so, or is there a better way I can check if the form objects themselves are not undefined directly and check both the applicant and account portion of this form object without having two separate blocks of undefined checks / forEach loops?

vm.getAllForms = function (type) {

  var allForms = [];
  var accountForms = [];
  var applicantForms = [];

  if (undefined != vm.masterFormObject) {
    if (undefined != vm.masterFormObject.payload) {
      if (undefined != vm.masterFormObject.payload.accounts) {
        vm.masterFormObject.payload.accounts.forEach(function (account) {
          if (undefined != account.Forms) {

            account.Forms.forEach(function (Form) {

              allForms.push(Form);
              accountForms.push(Form);

            });
          }
        });
      }

      if (undefined != vm.masterFormObject.payload.accounts) {
        vm.masterFormObject.payload.applicants.forEach(function (applicant) {
          if (undefined != applicant.Forms) {
            applicant.Forms.forEach(function (Form) {
              allForms.push(Form);
              applicantForms.push(Form);
            });
          }
        });
      }
    }
  }


texts: Business logic inside MVC Cart Controller method

texts:
I have a controller method, invoked when a user adds the product he is viewing to the cart.

The way I understand how MVC works, this can be considered a fat controller already, but I'm still not completely sure.

And if that's the case, then how can I possibly refactor this code?

public function processAddingAndUpdatingOfCartItems()
{
    // Get values from request
    $productId  = $_POST['productId'];
    $quantity   = $_POST['quantity'];

    // Instantiate DB Connection object
    $connection = new Connection();

    // Get product details of currently viewed product to be added to cart
    $productTable   = new ProductTable($connection);
    $productDetails = $productTable->getProductDetailsByProductId($productId);

    // Get price of currently viewed product: desired quantity * unit price
    $productModel = new Product();
    $productPrice = $productModel->computeProductPrice($productId, $quantity);

    // Store properties in an array
    $cartItemProperties = array(
        'productId'     => $productId
        ,'quantity'     => $quantity
        ,'unitPrice'    => $productDetails->price
        ,'price'        => $productPrice
    );

    // Create Cart Item Model
    $cartItem   = new CartItemModel();
    $cartItem->setCartItemProperties($cartItemProperties);

    // Check if a cart already exists for the current session
    $cartValidator                  = new CartValidator();
    $doesCartExistForCurrentUser    = $cartValidator->doesCartExistForCurrentUser();

    // Instantiate CartTable and CartItemTable for database queries
    $cartTable      = new CartTable($connection);
    $cartItemTable  = new CartItemTable();

    // If a cart already exists for the current session
    if($doesCartExistForCurrentUser) {
        // Get cart id in the current session
        $session        = new SessionModel();
        $cartId         = $session->getSessionKey('cartId');

        // Insert item into cart
        $cartItemTable->insertItemIntoCart($cartItem);

        // Refresh total amount of cart
        $this->refreshCartTotalAmount($cartTable, $cartId);
    } else {
        // If no cart exists yet for the current session

        // Set default user id to 0
        $sessionUserId = 0;
        $session        = new SessionModel();

        // Check if user is logged in
        $customerValidator = new CustomerValidator();
        if($customerValidator->isUserLoggedIn())
        {
            $sessionUserId  = $session->getSessionKey('userId');
        }

        // Create new cart model containing necessary properties
        $cart = new CartModel();
        $cartProperties = array(
            'customerId' => $sessionUserId
            // other properties
        );

        // Insert into carts table
        $last_cart_id = $cartTable->insertCart($cart);

        // Set cartId property of Cart Item Model
        $cartItem->cartId = $last_cart_id;

        // Insert item into cart
        $cartItemTable->insertItemIntoCart($cartItem);

        // Refresh total amount of cart
        $this->refreshCartTotalAmount($cartTable, $last_cart_id);

        // Set session cart id

        $session->setSessionKey('cartId', $last_cart_id);
    }
}


texts: Set a font for a UITextView if the font is nil or not equal to desired font

texts:
Main question
I am setting a font for a UITextView that is a subview in a custom view. I only set it if the user didn't specify the font size in the Interface Builder.
I have the following working code
if self.view.font == nil || self.view.font!.fontName != mongolFontName {

        view.font = UIFont(name: mongolFontName, size: defaultFontSize)

}

but the if line seems more verbose than it needs to be. Is there a more concise way of getting the same result?
Extra background info
This is a continuation in the same vane of a previous question. After making changes based on advice from the answers there (though still more to do), the code I have now is
import UIKit

@IBDesignable class UIMongolTextView: UIView {

    // ********* Unique to TextView *********
    private let view = UITextView()
    let mongolFontName = "ChimeeWhiteMirrored"
    let defaultFontSize: CGFloat = 17

    @IBInspectable var text: String {
        get {
            return view.text
        }
        set {
            view.text = newValue
        }
    }

    @IBInspectable var fontSize: CGFloat {
        get {
            if let font = view.font {
                return font.pointSize
            } else {
                return 0.0
            }
        }
        set {
            view.font = UIFont(name: mongolFontName, size: newValue)
        }
    }

    func setup() {

        view.backgroundColor = UIColor.clearColor()

        // set font if user didn't specify size in IB
        if self.view.font == nil || self.view.font!.fontName != mongolFontName {

            view.font = UIFont(name: mongolFontName, size: defaultFontSize)
        }

    }

    // *******************************************
    // ****** General code for Mongol views ******
    // *******************************************

    private var oldWidth: CGFloat = 0
    private var oldHeight: CGFloat = 0

    // This method gets called if you create the view in the Interface Builder
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    // This method gets called if you create the view in code
    override init(frame: CGRect){
        super.init(frame: frame)
        self.setup()
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.setup()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // layoutSubviews gets called multiple times, only need it once
        if self.frame.height == oldHeight && self.frame.width == oldWidth {
            return
        } else {
            oldWidth = self.frame.width
            oldHeight = self.frame.height
        }

        // Remove the old rotation view
        if self.subviews.count > 0 {
            self.subviews[0].removeFromSuperview()
        }

        // setup rotationView container
        let rotationView = UIView()
        rotationView.frame = CGRect(origin: CGPointZero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
        self.addSubview(rotationView)

        // transform rotationView (so that it covers the same frame as self)
        rotationView.transform = translateRotateFlip()

        // add view
        view.frame = rotationView.bounds
        rotationView.addSubview(view)

    }

    func translateRotateFlip() -> CGAffineTransform {

        var transform = CGAffineTransformIdentity

        // translate to new center
        transform = CGAffineTransformTranslate(transform, (self.bounds.width / 2)-(self.bounds.height / 2), (self.bounds.height / 2)-(self.bounds.width / 2))
        // rotate counterclockwise around center
        transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
        // flip vertically
        transform = CGAffineTransformScale(transform, -1, 1)

        return transform
    }

}


texts: Breaking down a dollar amount into bill and coin denominations

texts:
I've started coding C++ again after a 6 month break to prepare for a class I'm taking this quarter. I found this idea and thought it would be fun to try and code.

I originally started with input as a string, and wanted to split it into two ints at ., but this way seemed easier.  Then came the rounding errors. This is why I multiply by such a large number, and 100 was still giving me incorrect values.  I'm really just looking for any feedback on ways I could improve my code, stylistically or otherwise.

cout << "Welcome to Dollar Break Down!" << endl; //print welcome message
cout << "Please enter a dollar amount: ";        // prompt for input of a dollar amount

double amt;                                                         // var to store the amount
cin >> amt;                                                         // read in and store amount
cout << endl;                                                       // spacing

int dollars = amt;                                                  // dollars = (int)amt ex: int(45.97) = 45

// compute dollars
dollars / 100 == 1 ?                                                // check if bill amount is single or plural
    cout << dollars / 100 << " hundred" << endl :                   // print singe
    cout << dollars / 100 << " hundreds" << endl;                   // print plural
dollars = dollars % 100;                                            // compute remainder after removing bill amount
dollars / 50 == 1 ?
    cout << dollars / 50 << " fifty" << endl :                      // repeat for each bill type
    cout << dollars / 50 << " fifties" << endl;
dollars = dollars % 50;
dollars / 20 == 1 ?
    cout << dollars / 20 << " twenty" << endl :
    cout << dollars / 20 << " twenties" << endl;
dollars = dollars % 20;
dollars / 10 == 1 ?
    cout << dollars / 10 << " ten" << endl :
    cout << dollars / 10 << " tens" << endl;
dollars = dollars % 10;
dollars / 5 == 1 ?
    cout << dollars / 5 << " five" << endl :
    cout << dollars / 5 << " fives" << endl;
dollars = dollars % 5;
dollars / 1 == 1 ?
    cout << dollars / 1 << " one" << endl:
    cout << dollars / 1 << " ones" << endl;

cout << endl;                                                   // spacing between dollars and cents

dollars = amt;                                                  // reset dollars to amt for cents calculation
amt *= 10000;                                                   // multiply to remove rounding errors
dollars *= 10000;                                               // same thing
int cents = (amt - dollars) / 100;                              // compute cents without rounding errors

// compute cents
cents / 25 == 1 ?
    cout << cents / 25 << " quarter" << endl :
    cout << cents / 25 << " quarters" << endl;
cents = cents % 25;
cents / 10 == 1 ?
    cout << cents / 10 << " dime" << endl :
    cout << cents / 10 << " dimes" << endl;
cents = cents % 10;
cents / 25 == 1 ?
    cout << cents / 5 << " nickel" << endl :
    cout << cents / 5 << " nickels" << endl;
cents = cents % 5;
cents / 25 == 1 ?
    cout << cents / 1 << " penny" << endl :
    cout << cents / 1 << " pennies" << endl;


texts: Writing to and reading from socket in an IMAP client

texts:
I implemented the following method to send IMAP commands to server and return the response to caller. Here, I'm not trying to parse the commands. Would like some advice on how I can improve the method (e.g. avoiding unnecessary copying) because I feel like I keep moving data between buffers and strings too much.

The other concern I have is about the size of the response. Right now, I'm returning a string. But this string can be potentially large (example fetch an email with a large email body or 100 email headers that contains subject, date and sender). In such a case, should I allocate response in the free-store and return a pointer to it or something like that? Thank you.

std::string cmail::ImapClient::execute(const std::string &command)
{
    std::stringstream ss;
    ss << ++commandCounter << " " << command;
    std::string cmd = ss.str();
    spdlog::trace("C: " + cmd);
    boost::system::error_code error;
    boost::asio::write(socket, boost::asio::buffer(cmd.append("\r\n")), error);
    if(error)
    {
        spdlog::error("Failed to dispatch command " + cmd + " because " + error.message());
        return "";
    }

    boost::asio::streambuf buffer;
    boost::asio::read_until(socket, buffer, '\n', error);
    if(error)
    {
        spdlog::error("Failed to receive response for command " + cmd + " because " + error.message());
        return "";
    }

    ss.str(std::string());
    ss.clear();
    std::istream is(&buffer);
    std::string line;
    while(std::getline(is, line))
    {
       ss << line << std::endl;
    }

    std::string response = ss.str();

    if(spdlog::default_logger()->level() == spdlog::level::trace)
    {
        std::string s = response;
        s.pop_back();
        spdlog::trace("S: " + s);
    }

    return response;
}

Thank you for your effort and time, helping me.


texts:
The purpose of this code is to change each column to a row, and assign keys to each value for the new array according to the old array. I would like to know if there're other ways to optimize it.

<?php

$arr = [
    'name' => ['a', 'b', 'c'],
    'age'  => [ 2 ,  1 ,  3 ]
];

$result = [];
$keys   = array_keys($arr);
foreach($arr[$keys[0]] as $index => $temp) {
    $data = [];
    foreach($keys as $i => $key) {
        $data[$key] = $arr[$key][$index];
    }
    $result[] = $data;
}

print_r($result);

Which gives:

$result = [
    ['name' => 'a', 'age' => 2],
    ['name' => 'b', 'age' => 1],
    ['name' => 'c', 'age' => 3],
];


texts: Am I using my data source array correctly?

texts:
When I want to make some quick tests for my UITableViewControllers, I usually create an NSArray that holds some dummy data. I would like to know if I'm doing anything wrong here:

First in MasterViewController.h:

#import <UIKit/UIKit.h>

@class DetailViewController;

@interface MasterViewController : UITableViewController

@property (nonatomic, retain) NSArray *dataSourceArray;

@end

and then in MasterViewController.m:

#import "MasterViewController.h"

@implementation MasterViewController

@synthesize dataSourceArray = _dataSourceArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Master", @"Master");
        _dataSourceArray = [[NSArray alloc] initWithObjects:@"obj 1", @"obj 2", @"obj 3", nil];
    }
    return self;
}

- (void)dealloc
{
    [_dataSourceArray release];
    [super dealloc];
}

So, the real question, as long as I'm not assigning _dataSourceArray to something else, I'm safe in terms of memory management here, right?


texts: Insertion sort revised with output to console

texts:
I took the question Performing insertion sort in C# and tidied it up a bit, then I thought about the use of the arrays and was wondering if it worked, and it does.

So now I have 3 static methods in a simple Program class to run from the console, just to check 15 numbers quickly.  It's not very efficient.

What can be done to make it more efficient? I am assuming taking out the PrintIntegerArray from inside the PerformInsertionSort method for larger arrays would help with that.

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = new int[15] {9,4,13,42,56,21,1,19,42,42,40,109,3,8,99};

        Console.WriteLine("Final OutPut");
        PrintIntegerArray(PerformInsertionSort(numbers));
        Console.ReadLine();
    }

    static int[] PerformInsertionSort(int[] inputArray)
    {
        for (int i = 0; i < inputArray.Length - 1; i++)
        {
            for (int j = i + 1; j > 0; j--)
            {
                if (inputArray[j - 1] > inputArray[j])
                {
                    int temp = inputArray[j - 1];
                    inputArray[j - 1] = inputArray[j];
                    inputArray[j] = temp;
                }
                PrintIntegerArray(inputArray);
            }
        }
        return inputArray;
    }

    public static void PrintIntegerArray(int[] array)
    {
        foreach (int i in array)
        {
            Console.Write(i.ToString() + ", ");
        }
        Console.WriteLine("End of Array");
        Console.ReadLine();
    }
}


texts: How can I optimize this Monte Carlo simulation running at 10,000,000 iterations?

texts:
I am writing this Monte Carlo simulation and I am facing this issue when running the code at 10,000,000 iterations. here is the code:

import random as rnd
from time import time

#get user input on number of iterations
numOfIterations = raw_input('Enter the number of iterations: ')
numOfIterations = int(numOfIterations)

start = time()

#initialize bag (44 green, 20 blue, 15 yellow,  11 red, 2 white, 1 black
#a counter
#and question counter
bag = 44*'g'+ 20*'b' + 15*'y' + 11*'r' + 2*'w' + 'k'
counter = {'g':0, 'b':0,'y':0 ,'r':0,'w':0,'k':0}
question = {'one':0,'two':0,'three':0,'four':0,'five':0}

for i in range(0,numOfIterations):
  for j in xrange(0,5):
    draw = rnd.sample(bag,5)
    for x in draw: counter[x]+=1
  if counter['w'] >0 and counter['k'] >0: question['one']+=1
  if counter['b'] > counter['r']: question['two']+=1
  if counter['b'] > counter['y']: question['three']+=1
  if counter['y'] > counter['r']: question['four']+=1
  if counter['g'] < (counter['b']+counter['y']+counter['r']+counter['w']+counter['k']): question['five']+=1
  for k in counter: counter[k] = 0

p1 = float(question['one'])/float(numOfIterations)
p2 = float(question['two'])/float(numOfIterations)
p3 = float(question['three'])/float(numOfIterations)
p4 = float(question['four'])/float(numOfIterations)
p5 = float(question['five'])/float(numOfIterations)

print 'Q1 \t Q2 \t Q3 \t Q4 \t Q5'
print str(p1)+'\t'+str(p2)+'\t'+str(p3)+'\t'+str(p4)+'\t'+str(p5)

end = time()

print 'it took ' +str(end-start)+ ' seconds'

any suggestions/criticism would be appreciated.


texts: Using argparse with parameters defined in config file

texts:
I understand that and why using eval is generally considered bad practice in most cases (see e.g. here). Related questions on config files and argparse don't use types. (1, 2)

I needed to parse a number of command line arguments and decided to store the arguments, defaults and help strings in a .json file. I read the .json and add every argument to an argparse.ArgumentParser. To specify a type I need to pass a callable like float and not the string "float".

To get from the string to the callable I thought of

using eval
using a dict to map from string to callable
using a if/else or switch

and decided to use to use eval to avoid hard coding all types.

I have no security concerns because the argument file is supplied by the user and the program that uses this code is targeted at scientists that will realistically want to change the file to add parameters or change defaults. (Also, it is a university project which will never be run except for grading. I handed in a version using eval.)

Is there a smart solution avoiding hardcoding all types and avoiding eval, or did I find a place where eval is a sensible choice? I was only allowed to use the standard library.

Minimal args.json:

{
    "dt": {
        "type": "float",
        "help": "Time step size",
        "default": 0.4},
    "T": {
        "type": "int",
        "help": "Time steps between outputs",
        "default": 50},
    "f": {
        "type": "str",
        "help": "Landscape file name",
        "default": "small.dat"}
}

Runnable code, put args.json above in same directory to run:

import json
import argparse
import pprint

def setup_parser(arguments, title):

    parser = argparse.ArgumentParser(description=title,
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    for key, val in arguments.items():
        parser.add_argument('-%s' % key,
                            type=eval(val["type"]),
                            help=val["help"],
                            default=val["default"])

    return parser

def read_params(parser):

    parameters = vars(parser.parse_args())
    return parameters

def get_parameters(title=None):

    with open("args.json") as data_file:
        data = json.load(data_file)
    parser = setup_parser(data, title)
    parameters = read_params(parser)

    return parameters

if __name__ == "__main__":
    params = get_parameters()
    pprint.pprint(params)


texts: PHP Autoloader - For classes, traits and interfaces

texts:
Please review my Autoloader, which is the first file included in index.php

Note that there is no resource with the same name for trait, interface and class. Each resource has it's own name. And even if some class is named "Ha" and some trait is named "Ha", one of them has specific namespace for this.

<?php
### Autoload class ###
class Autoload
{
    # The path for classes, traits or interfaces #
    private static $path  = 'private/Model/';

    # The resource files by default will be NULL #
    private static $resource_files = null;

    # Search for resource_files in recursive mode #
    private static function recursive_glob($pattern)
    {
        $resource_files = glob($pattern);
        foreach(glob(dirname($pattern).'/*', GLOB_ONLYDIR | GLOB_NOSORT) as $directory)
        {
            $resource_files = array_merge(
                $resource_files,
                self::recursive_glob($directory.'/'.basename($pattern))
            );
        }
        return $resource_files;
    }

    # Order array to start with files that has the name like the $resource or closely... #
    private static function order_resource_files($resource)
    {
        $resource_name = explode('\\', $resource);
        $resource_name = end($resource_name);

        foreach(self::$resource_files as $file_key => $file)
        {
            if(stripos($file, $resource_name) !== false)
            {
                self::$resource_files[-1] = $file;
                unset(self::$resource_files[$file_key]);

                ksort(self::$resource_files);
                self::$resource_files = array_values(self::$resource_files);
            }
        }
    }

    # Find resource #
    public static function find($resource)
    {
        # Set $resource_files if is NULL #
        if(!self::$resource_files)
        {
            self::$resource_files = self::recursive_glob(self::$path.'*.php');
        }

        # Order $resource_files by given resource #
        self::order_resource_files($resource);

        # Now that we have the $resource_files array, we can start searching #
        foreach(self::$resource_files as $file_key => $file)
        {
            # First, remove the file from array #
            unset(self::$resource_files[$file_key]);

            # Include file #
            require_once $file;

            # If resource exists now, then we can stop and search for other resources later #
            if(class_exists($resource) || trait_exists($resource) || interface_exists($resource))
            {
                break;
            }
        }
    }
}

### Check PHP version and call Autoload::find ###
if(version_compare(PHP_VERSION, '5.1.2', '>='))
{
    if(version_compare(PHP_VERSION, '5.3.0', '>='))
    {
        spl_autoload_register('Autoload::find', true, true);
    }
    else
    {
        spl_autoload_register('Autoload::find');
    }
}
else
{
    function __autoload($resource)
    {
        Autoload::find($resource);
    }
}