texts: Calculates best angle on path and approximates cardinal direction

texts:
This program uses the C language. What's used are two points, and the usage of the inverse tan function finds the angle of the line between the two points. Afterward, it finds the cardinal direction on the plane. -y is south, +y is north. It seems to work quite well. However, I want to find what is unconventional of my program. I want to learn to write good code and this is a good step towards it.

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>

#define PI 3.14159265

int cardinal(double degrees)
{
    // 0 is North
    // 1 is North-east
    // 2 is East
    // 3 is South-east
    // 4 is South
    // 5 is South-west
    // 6 is West
    // 7 is North-west
    int cardinal;
    if (degrees >= -22.5 && degrees <= 22.5)
        cardinal = 0;
    if (degrees > 22.5 && degrees < 67.5)
        cardinal = 1;
    if (degrees >= 67.5 && degrees <= 112.5)
        cardinal = 2;
    if (degrees > 112.5 && degrees < 157.5)
        cardinal = 3;
    if (degrees >= -157.5 && degrees <= 157.5)
        cardinal = 4;
    if (degrees > -157.5 && degrees < -112.5)
        cardinal = 5;
    if (degrees >= -112.5 && degrees <= -67.5)
        cardinal = 6;
    if (degrees > -67.5 && degrees < -22.5)
        cardinal = 7;

    return cardinal;
}

char* direction(int cardinal)
{
    if (cardinal == 0)
        return "north";
    if (cardinal == 1)
        return "northeast";
    if (cardinal == 2)
        return "east";
    if (cardinal == 3)
        return "southeast";
    if (cardinal == 4)
        return "south";
    if (cardinal == 5)
        return "southwest";
    if (cardinal == 6)
        return "west";
    if (cardinal == 7)
        return "northwest";
}

int main()
{
    int xpl = 494, ypl = 105;
    int xcom = 152, ycom = -168;

    double degrees;
    double radians;

    int num;

    double CONS = 180.0 / PI;

    int xo = xcom - xpl;
    int yo = ycom - ypl;

    radians = atan2(yo, xo);
    degrees = radians * CONS;

    num = cardinal(degrees);

    printf("The angle to travel in is %f (degrees) %f (radians)\n", degrees, radians);
    printf("Numerical direction: %d", num);
    printf("\nDirection: %s", direction(num));

    return 0;
}


texts:
My name is Ethan and I am trying to build an API for scaping technical papers to use for developers. Right now it only works for ArXiV but I would greatly appreciate some mentoring or a code review of my repo. I am a new developer and want to get my code to professional quality.

Repo: https://github.com/evader110/ArXivPully

Source provided as well:

from falcon import API
from urllib import request
from bs4 import BeautifulSoup

class ArXivPully:
    # Removes rogue newline characters from the title and abstract
    def cleanText(self,text):
        return ' '.join(text.split('\n'))

    def pullFromArXiv(self,search_query, num_results=10):
        # Fix Input if it has spaces in it
        split_query = search_query.split(' ')
        if(len(split_query) > 1):
            search_query = '%20'.join(split_query)
        url = 'https://export.arxiv.org/api/query?search_query=all:'+search_query+'&start=0&max_results='+str(num_results)
        data = request.urlopen(url).read()
        output = []
        soup = BeautifulSoup(data, 'html.parser')
        titles = soup.find_all('title')

        # ArXiv populates the first title value as the search query
        titles.pop(0)

        bodies = soup.find_all('summary')
        links = soup.find_all('link', title='pdf')
        for i in range(len(titles)):
            title = self.cleanText(titles[i].text.strip())
            body = self.cleanText(bodies[i].text.strip())
            pdf_link = links[i]['href']
            output.append([pdf_link, title, body])
        return output

    def on_get(self, req, resp):
        """Handles GET requests"""
        output = []
        for item in req.params.items():
            output.append(self.pullFromArXiv(item[0],item[1]))
        resp.media = output

api = API()
api.add_route('/api/query', ArXivPully())

Some design explanations. I run this API through Google Cloud Platform using Falcon API because both options are free for me and were the simplest to implement. Some known issues are already posted in the repo but I want to better understand Software Development skills, best practices, etc. I greatly appreciate any tips big or small and I look forward to drastically changing this source code to make it more robust.


texts: Single function to read one, read all, or set

texts:
I have the below function, it is designed so I can call:

$object->temp('one', 1);    //add the key `one` to the temp array with value 1
$object->temp('two', 2);    //add the key `two` to the temp array with value 2
$object->temp('three', 3);  //add the key `three` to the temp array with value 3

$object->temp('three');       //returns 3
$object->temp('three', null); //removes the `three` key
$object->temp();              //returns array('one' => 1, 'two' => 2)

and it works well, my only gripe is that I don't like using the $value = 'read_temp in the definition, it feels like a hack to me.

So, is there anything wrong with that, and how can this function be optimized?

public function temp($key = null, $value = 'read_temp') {
    if($key === null)
        return $this->temp;

    if ($value === null){
        unset($this->temp[$key]);
    }

    elseif ($value == 'read_temp' && isset($this->temp[$key])) {
        $value = $this->temp[$key];
    } else {
        $this->temp[$key] = $value;
    }

    return $value;
}

I could split this into two setTemp getTemp (or three clearTemp to be pedantic) functions, but I would like to be able to have just one function call to do everything.


texts: Check whether string of braces, brackets, and parentheses is balanced

texts:
The Task

is taken from codewars:

  Write a function that takes a string of braces, and determines if the
  order of the braces is valid. It should return true if the string is
  valid, and false if it's invalid.

  All input strings will be nonempty, and will only consist of
  parentheses, brackets and curly braces: ()[]{}.

  What is considered Valid? A string of braces is considered valid if
  all braces are matched with the correct brace.

  Examples

  (){}[]   =>  True
  ([{}])   =>  True
  (}       =>  False
  [(])     =>  False
  [({})](] =>  False

My solution

const areBracesBalanced = brc => {
  const brace = Object.freeze({
    "(": [],
    "[": [],
    "{": [],
  });

  const removeBrace = b => brace[b].splice(-1, 1);
  const getLastBraceIndex = b => brace[b][brace[b].length - 1]
  const braceExists = b => !brace[b].length;
  const isBraceBeforeClosed = (before, current) => braceExists(before) || getLastBraceIndex(before) < getLastBraceIndex(current);

  const braceIsBalanced = (b, i) => {
    switch (b) {
      case "(":
      case "[":
      case "{":
        return brace[b].push(i);
      case ")":
        return isBraceBeforeClosed("[", "(") &&
               isBraceBeforeClosed("{", "(") &&
               removeBrace("(");
      case "]":
        return isBraceBeforeClosed("(", "[") &&
               isBraceBeforeClosed("{", "[") &&
               removeBrace("[");
      case "}":
        return isBraceBeforeClosed("(", "{") &&
               isBraceBeforeClosed("[", "{") &&
               removeBrace("{");
      default:
        // be a good code...
    }
  };

  return[...brc]
    .every(braceIsBalanced) && !Object.values(brace).flat().length;
}


texts:
Please comment about performance

https://leetcode.com/problems/leaf-similar-trees/

  Consider all the leaves of a binary tree.  From left to right order,
  the values of those leaves form a leaf value sequence.

  For example, in the given tree above, the leaf value sequence is (6,
  7, 4, 9, 8).

  Two binary trees are considered leaf-similar if their leaf value
  sequence is the same.

  Return true if and only if the two given trees with head nodes root1
  and root2 are leaf-similar.

  Note:

  Both of the given trees will have between 1 and 100 nodes.

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

namespace TreeQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/leaf-similar-trees/
    /// </summary>
    [TestClass]
    public class LeafSimilarTrees
    {
        [TestMethod]
        public void LeafSimilarTreesTest()
        {
            TreeNode root1 = new TreeNode(3);
            root1.left = new TreeNode(5);
            root1.left.left = new TreeNode(6);
            root1.left.right = new TreeNode(2);
            root1.left.right.left = new TreeNode(7);
            root1.left.right.right = new TreeNode(4);
            root1.right = new TreeNode(1);
            root1.right.left = new TreeNode(9);
            root1.right.right = new TreeNode(8);

            TreeNode root2 = new TreeNode(3);
            root2.left = new TreeNode(1);
            root2.left.left = new TreeNode(6);
            root2.left.right = new TreeNode(2);
            root2.left.right.left = new TreeNode(7);
            root2.left.right.right = new TreeNode(4);
            root2.right = new TreeNode(5);
            root2.right.left = new TreeNode(9);
            root2.right.right = new TreeNode(8);
            Assert.IsTrue(LeafSimilar(root1,root2));

        }

        public bool LeafSimilar(TreeNode root1, TreeNode root2)
        {
            List<int> tree1 = new List<int>();
            List<int> tree2 = new List<int>();
            DFS(root1, tree1);
            DFS(root2, tree2);
            if (tree1.Count != tree2.Count)
            {
                return false;
            }
            for (int i = 0; i < tree1.Count; i++)
            {
                if (tree1[i] != tree2[i])
                {
                    return false;
                }
            }
            return true;
        }

        public void DFS(TreeNode root, List<int> list)
        {
            if (root == null)
            {
                return;
            }
            if (root.left != null)
            {
                DFS(root.left, list);
            }
            if (root.right != null)
            {
                DFS(root.right, list);
            }
            if (root.left == null && root.right == null)
            {
                list.Add(root.val);
            }
        }
    }
}


texts:
I've been working on implementing a doubly linked list from scratch in Java, and if anyone has time, could you critique it?

class Node {
    Node prev;
    Node next;
    int data;

    public Node(int d) {
        data = d;
        prev = null;
        next = null;
    }
}

class LinkedList {
    Node head;

    public LinkedList() {
        head = null;
    }

    public void insert(int d) {
        if (head == null) {
            head = new Node(d);
            return;
        }

        if (head.data > d) {
            Node holder = head;
            Node newNode = new Node(d);
            head = newNode;
            head.next = holder;
            holder.prev = newNode;
            return;
        }

        Node tmpNode = head;

        while (tmpNode.next != null && tmpNode.next.data < d) {
            tmpNode = tmpNode.next;
        }

        Node prevTmp = tmpNode;
        Node insertedNode = new Node(d);

        if (tmpNode.next != null) {
            Node nextTmp = tmpNode.next;
            insertedNode.next = nextTmp;
            nextTmp.prev = insertedNode;
        }
        prevTmp.next = insertedNode;
        insertedNode.prev = prevTmp;
    }

    public void delete(int d) {
        if (head == null) {
            System.out.println("The list is empty.");
            return;
        }

        if (head.data == d) {
            head = head.next;
            if (head != null) {
                head.prev = null;
            }
            return;
        }

        Node tmpNode = head;

        while (tmpNode != null && tmpNode.data != d) {
            tmpNode = tmpNode.next;
        }

        if (tmpNode == null) {
            System.out.println("That node does not exist in the list");
            return;
        }

        if (tmpNode.data == d) {
            tmpNode.prev.next = tmpNode.next;
            if (tmpNode.next != null) {
                tmpNode.next.prev = tmpNode.prev;
            }
        }
    }

    public void print() {
        Node tmpNode = head;

        while (tmpNode != null) {
            System.out.print(tmpNode.data + " -> ");
            tmpNode = tmpNode.next;
        }

        System.out.print("null");
    }


texts: Using Mutex to prevent multiple WPF application launches

texts:
I've inherited an existing application which is a WPF implementation of toast notifications. This application is installed to multiple client PCs across the estate and, once installed, runs in the background. The notifier then works regardless of who is logged onto the machine. One of the improvements I have been asked to make is to prevent the application from being started more than once.

I am considering using a mutex to do this. I've implemented a solution that functionally works at startup using inspiration from MSDN and Stack Overflow but would like to identify any potential weaknesses or scenarios which could break the code. Ultimately, I don't want some crash to occur that might fail to dispose the mutex or leave the application unable to start, although I think I have catered as best possible.

public partial class MainWindow : Window
{
    // unique id for application mutex
    private static string mutexId = string.Format("Local\\{{{0}}}", "1109F104-B4B4-4ED1-920C-F4D8EFE9E833");

    private static string applicationName = "My App";

    private bool hasHandle;

    private Mutex mutex;

    /// <summary>
    /// Initializes a new instance of the MainWindow class.
    /// N.B. Inspiration for this implementation sourced from:
    /// https://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567
    /// </summary>
    public MainWindow()
    {
        this.mutex = new Mutex(false, mutexId);

        // Allow all users of the system to access the mutex with full control.
        var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
            MutexRights.FullControl, AccessControlType.Allow);
        var securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);
        mutex.SetAccessControl(securitySettings);

        try
        {
            try
            {
                hasHandle = this.mutex.WaitOne(1000, false);
                if (!hasHandle)
                {
                    MessageBox.Show("Application is already running.", applicationName);
                    Application.Current.Shutdown();
                }
            }
            catch (AbandonedMutexException)
            {
                // Log the fact the mutex was abandoned in another process, it will still get aquired
                hasHandle = true;
            }

            // Perform your work here.
            InitializeComponent();
            Closing += (s, e) => Shutdown();
        }
        catch (Exception e)
        {
            //If InitializeComponent throws an error, gracefully cleanup the application.
            Shutdown();
        }

    }

    private void Shutdown()
    {
        ViewModelLocator.Cleanup();

        // Release the mutex if a handle was aquired while the application was running.
        if (this.hasHandle)
        {
            this.mutex.ReleaseMutex();
        }

        this.mutex.Dispose();
    }
}

For brevity I've omitted using statements and namespace declarations, as well as the .xaml files and existing solution, as I want to focus on this new improvement, which is self-contained. I'm also conscious of trying to keep startup and shutdown as simple as possible, so would happily consider improvements to remove unneeded code.

Finally, I have seen this similar question and would be happy with an answer to use this example if this is the best way of meeting the requirement.


texts:
I was wondering if this was a decent way of handling this function. Please take a look.

// Use Less Mixins from Theme Options to adjust Stylesheets before Parsing Less to CSS
add_filter( 'less_vars', 'wellies_less_vars', 10, 2 );
function wellies_less_vars( $vars, $handle ) {

    //Necessary for UpTheme Framework
    global $up_options;

    //Grab Theme option and check if it's empty and default to color if it is.
    $linkcolor = empty($up_options->linkcolor) ? '#08c' : $up_options->linkcolor;
    $linkcolorhover = empty($up_options->linkcolorhover) ? '#03c' : $up_options->linkcolorhover;
    $networknavstart = empty($up_options->networknavstartcolor) ? '#333' :$up_options->networknavstartcolor;
    $networknavend = empty($up_options->networknavendcolor) ? '#222' :$up_options->networknavendcolor;
    $sitenavstart = empty($up_options->sitenavstartcolor) ? '#333' :$up_options->sitenavstartcolor;
    $sitenavend = empty($up_options->sitenavendcolor) ? '#222' :$up_options->sitenavendcolor;

    //Set Less Mixins to Variables above
    $vars = array(
        'linkColor' => $linkcolor,
        'linkColorHover' => $linkcolorhover,
        'networkNavBarStart' => $networknavstart,
        'networkNavBarEnd' => $networknavend,
        'siteNavBarStart' => $sitenavstart,
        'siteNavBarEnd' => $sitenavend,
    );
    return $vars;
}
//Enqueue Stylesheets if not on dashboard.
function wellies_css_loader() {
    if ( ! is_admin() )
        wp_enqueue_style('bootstrap', get_bloginfo('template_directory').'/library/css/lib/bootstrap.less',  array(), '', 'screen, projection');
    wp_enqueue_style('themes', get_bloginfo('template_directory').'/library/css/theme.less', array(), '', 'screen, projection');
}
add_action('wp', 'wellies_css_loader');

It is currently working but I don't want to have it slow down the site if I can optimize it somehow.


texts: Recursively patching the properties of an ORM model and related models

texts:
The following excerpt is part of a method for recursively patching the properties of an ORM model and related models using a dictionary:

try:
    anhaenge = d['anhaenge']
except KeyError:
    self.logger.debug('anhaenge unchanged')
else:
    try:
        anhang = anhaenge['anhang']
    except KeyError:
        self.logger.debug('anhaenge.anhang unchanged')
    except TypeError:  # anhaenge is probably None
        for record in self.anhang:
            yield (record, PatchMode.DELETE)
    else:
        for record in self.anhang:
            yield (record, PatchMode.DELETE)

        if anhang:
            for anhang_ in anhang:
                with suppress(EmptyDict):
                    for record in Anhang.from_dict(
                            anhang_, immobilie=self):
                        yield (record, PatchMode.CREATE)

I currently violate the don't repeat yourself (DRY) principle, since I do the very same operation within the block handling the TypeError and at the beginning of the inner else block.
How can I resolve this to have the code

for record in self.anhang:
    yield (record, PatchMode.DELETE)

only once?

Clarifying the input:

The inputd is a dictionary derived by json.loads() from a JSON string through a web API.
The method, the above excerpt is extracted from uses this dictionary to modify database records represented by the ORM model this methods belongs to.
Examples of d:

# Delete all subsequent anhang records
d = {'anhaenge': {
    'anhang': None}}

# Change all related anhang records to those represented by the dicts in
# the list, meaning:
# 1) Delete all old records
# 2) Create new ones from the dicts
d = {'anhaenge': {
    'anhang': [
        {'anhangtitel': 'Attachment1'},
        {'anhangtitel': 'Attachment2'}]}}

# All subsequent anhang records are left as they are.
# Subsequent foo records may be altered accordingly
d = {'anhaenge': {
    'foo': 'bar'}}


texts:
What the code does is convert an image to a bitmap without having to create 3 arrays to make the conversion. It basically uses 1/3rd of the memory that it would normally use.

I'm trying to refactor this method to make it shorter, less complex and more readable. So far, I've been unsuccessful in the 4 attempts I've made. Every time I try to extract something it says that there are ambiguous return statements.

private Bitmap decodeBitmapFromFile(File file, boolean preview) {
  byte[] byteArr = new byte[0];
  byte[] buffer = new byte[1024];
  int count = 0;
  int len;
  InputStream inputStream = null;

  try {
    inputStream = new FileInputStream(file);
    while ((len = inputStream.read(buffer)) > -1) {
      if (len != 0) {
        if (count + len > byteArr.length) {
          byte[] newBuf = new byte[(count + len) * 2];
          System.arraycopy(byteArr, 0, newBuf, 0, count);
          byteArr = newBuf;
        }

        System.arraycopy(buffer, 0, byteArr, count, len);
        count += len;
      }
    }

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(byteArr, 0, count, options);

    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inJustDecodeBounds = false;
    if (preview) {
      options.inSampleSize = getInSampleSize();
    }
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

    return BitmapFactory.decodeByteArray(byteArr, 0, count, options);
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    try {
      inputStream.close();
    } catch (Exception e) {
    }
  }

  return null;
}


texts: Check if a string contains a set of characters

texts:
I have written this piece of code to check if a string contains a set of characters, regardless of the order.

Eg: 'ruby is best' / 'bysbe' => true

Code:

def find_chars(s1,s2)
s1.chars.sort.join =~ Regexp.new(s2.chars.sort.join(".*")) ? true : false
end

I need to optimize it to reduce executing time. How? What is slowing the performance, the regex, the methods, the ternary, or all together?

EDIT:

The last one provided by @Flambino performs significantly better, and this one performs best

def find_chars(subject, characters)
  characters.chars.uniq.all?{|i| characters.count(i) <= subject.count(i)}
end

Now I only need to investigate why :)


texts:
I've written a basic server/client application to use in an automation application written in C#. The code is working pretty good, but I have a few thing I want to improve:

Server:

   public void socketListener()
{

    peerListener = new TcpListener(IPAddress.Any, ControlLayer.control_GlobalParam.TCP_PORT);
    peerListener.Start();
    int MessageLength = 0;
    //_infrastructure_TcpServerAndClient.PeerListener_start();
    Socket socket = null;
    while (true)
    {
        if (peerListener.Pending())
        {
            Thread.Sleep(500);
            continue;
        }
        else
        {
            byte[] StreamMessage = new byte[9632*2];
            try
            {
            socket = peerListener.AcceptSocket();

            Thread.Sleep(500);

                MessageLength = socket.Receive(StreamMessage, 0, StreamMessage.Length, SocketFlags.None);
            }
            catch (Exception ex)
            {
                //remote disconnected garcefully ?
                Console.WriteLine(ex);

            }
            if (MessageLength > 0 )
            {
                string message = System.Text.Encoding.Default.GetString(StreamMessage);

                if (Domain_GlobalParam.IsCollectTcpServerOutput)
                {
                    onDataRecieved(this, "Collecting log from Remote station", "TcpServer");
                }
                else
                {
                    onDataRecieved(this, message, "TcpServer");
                }
                new Thread(() => ParseMessage(message)).Start();

                //ParseMessage(message);
            }
        }
    }
}

Client:

        internal void CreateClient(object message)
    {
        try
        {

            _infrastructure_TcpServerAndClient.PeerClient_Connect();
            _infrastructure_TcpServerAndClient.SendMessageViaStreamWriter(message);
            _infrastructure_TcpServerAndClient.CloseConnection();

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
    internal void PeerClient_Connect()
{
    peerClient = new TcpClient();
    peerClient.Connect(ComSettings.IpAddress, ComSettings.Port);

}
internal void SendMessageViaStreamWriter(object message)
{
    string MessageOut = (string)message + "\n";
    netStream = peerClient.GetStream();
    StreamWriter sw = new StreamWriter(netStream);
    sw.Write(MessageOut);
    sw.Flush();
}
internal void CloseConnection()
{
    netStream.Close();
    peerClient.Close();
}

I've noticed that from time to time I miss out some messages (especially long ones). What do you think I can improve here?


texts:
I've been learning NodeJS recently, and have a small program to get the external IP address on my home network from fugal.net, compare it to the previous IP address, and if there is a change update the stored version, and send an email with the new IP.

I'm running node 0.11.12 on a Raspberry Pi, and storing on mongodb 2.1.1. I would appreciate any recommendations on how to improve it.

var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var nodemailer = require('nodemailer');

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'mygmail@gmail.com',
        pass: 'mypassword'
    }
});

var config = {
    hostname: 'fugal.net',
    path: '/ip.cgi',
    agent: false
};

http.request(config, function(res) {

    if(res.statusCode != 200) {
        throw new Error('non-OK status: ' + res.statusCode);
    }
    res.setEncoding('utf-8');
    var ipAddress = '';
    res.on('data', function(chunk) {    ipAddress += chunk; });
    res.on('end', function() {
        MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

            var collection = db.collection('test');
            collection.findOne({}, function(err, item) {

                var changeNeeded = false;
                if(item.ipAddress != ipAddress) {

                    changeNeeded = true;
                    db.collection('test').update({_id: item._id}, {$set: {ipAddress: ipAddress}}, {w:1}, function(err) {
                        if(err) throw err;
                        db.close();
                    });
                    sendMail(ipAddress);

                }
                if(!changeNeeded)
                    db.close();

            });

        });

    });

}).on('error', function(err) {
    throw err;
}).end();

function sendMail(ipAddress) {

    var mailOptions = {
        from: 'mygmail@gmail.com', // sender address
        to: 'mygmail@gmail.com',   // list of receivers
        subject: 'IP Address Changed',  // Subject line
        text: 'New IP Address: ' + ipAddress       // html body
    };

    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
        }else{
            console.log('Message sent: ' + info.response);
        }
    });

}

The big stumbling block for me was where to put the call to "db.close()" because of JavaScript's asynchronous nature.

The code to get the IP address was taken from here. The nodemail code is straight from the usage example on http://www.nodemailer.com.


texts:
I've started my first application using backbone and have something basic up and running, backbone seems to give a lot of freedom to application design and I don't know what I'm doing right and wrong in that regard. I'm just after some tips and criticism.

The first view is for the details which should be visible when the page loads:

var DetailsView = Backbone.View.extend({

    el: $(".details"),

    initialize: function(options) {
        // nothing here yet
    },

    render: function() {
        // nothing here yet
    },

    events: {
        "click .btn": "setDetails"
    },

    setDetails: function(e) {
        this.$el.hide();
        // will do validation here...
        this.options.dataEditorView.$el.show();
        this.options.finalView.render();

    }

});

Once a user has completed the details form for that view, the data edit view is displayed:

var DataEditorView = Backbone.View.extend({
    el: $(".data-editor"),

    initialize: function(options) {

    },

    events: {
        "keypress .point-x": "addSeriesPoint",
        "keypress .point-y": "addSeriesPoint"
    },

    addSeriesPoint: function(e) {
        if (e.keyCode != 13) return;
        //if (!this.input.val()) return;

        console.log('adding point');

        var point = [];
        point[0] = $("#input-point-x").val();
        point[1] = $("#input-point-y").val();

        Series.create({
            x: $("#input-point-x").val(),
            y: $("#input-point-y").val()
        });

        var points = this.options.seriesCollection.toJSON();
        this.options.summaryView.addPoint(points);

        $(".point-x").val("");
        $(".point-x").focus();

    }

});

And the summary view which is visible while the date editor view is visible:

var SummaryView = Backbone.View.extend({
    initialize: function() {

        console.log('initialising...');

        this.canvas = d3.select(this.el)
                        .append("svg")
                        .attr("width", 600)
                        .attr("height", 500);

    },

    className: "summary",

    render: function() {
        $("body").append(this.el);
    },

    addPoint: function(points) {
        console.log(points);
        this.canvas.selectAll("circle")
                    .data(points)
                    .enter()
                    .append("circle")
                    .attr("r", 42)
                    .attr("cx", function(d) { return d.x })
                    .attr("cy", function(d) { return d.y })
                    .transition().selectAll('circle')
                    .ease('bounce').duration(900)
                    .attr('r', function (d) {
                        console.log(d);
                        return 99; //ugh
                    });
    }

});


texts: Running 2 sets of tasks at the same time

texts:
Currently, my team and I have 2 types of databases that are updated periodically, SQL Server and Access. Also, we run specialized reports based on those databases.

Basically, we have 4 tasks that need to be completed:

Update SQL Server
Publish SQL Server Reports
Update Access Databases
Publish Access Db reports

Access takes forever to run, so I am trying to make my code run the task of Updating Access and Publishing Access reports at the same time that I am updating SQL Server and publishing those reports.

Can someone verify if I am on the right path, or maybe share a link that better explains async?

static void Main(string[] args)
{
    var cs1 = new _1_UpdateSQL();
    var cs2 = new _2_PublishSQLRpts();

    Task t = TriggerAccess();

    cs1.UpdateSqlCodeOnly();
    cs2.PublishSqlRptsCodeOnly();
    t.Wait();
}

static async Task TriggerAccess()
{
    var cs3 = new _3_UpdateAccessDb();
    var cs4 = new _4_PublishAccessRpts();

    await Task.Run(() => cs3.UpdateAccessDbCodeOnly());
    await Task.Run(() => cs4.PublishAccessRptsCodeOnly());

}


texts: Inheritance: declare a method that returns the current instance class

texts:
I have a Vector and 2-dimensional Vector, defined as follows:

    // A general vector
    class Vector {
        values: number[];

        constructor (...values: number[]) {
            this.values = values;
        }

        opposite(): Vector {
            return new Vector(...this.values.map((value, index) => -value));
        }
    }

    // Two-dimensional vector
    class Vector2 extends Vector {
        constructor(x: number, y: number) {
            super(x, y);
        }

        get x() {
            return this.values[0];
        }

        get y() {
            return this.values[1];
        }
    }

And I have the following code:

    let v = new Vector2(1, 2);
    let w = v.opposite();

    // this is wrong, since w is not a 2-dimensional vector
    console.log(w.x);

How could I solve this inheritance problem elegantly? For me, there are two alternatives:

Override the "opposite" method. I think that this is not a good idea, since currently there is only one method, but there could be a lot of them.

// Two-dimensional vector
class Vector2 extends Vector {
    // ... more methods ... blah blah blah ...
    // overrides the super class method
    opposite(): Vector2 {
        let [x, y] = super.opposite().values;
        return new Vector2(x, y);
    }
}

Create a named constructor. I think this is a good solution, but a bit tedious:

// Two-dimensional vector
class Vector2 extends Vector {
    constructor(x: number, y: number) {
        super(x, y);
    }

    // declare a "named constructor"
    static createFromVector(v: Vector): Vector2 {
        let [x, y] = v.values;
        return new Vector2(x, y);
    }

    // ... more methods ... blah blah blah ...
}

let v = new Vector2(1, 2);
// It's good, but a bit tedious writing constantly "createFromVector"
let w = Vector2.createFromVector(v.opposite());

How do you address this problem?


texts:
I'd like this code to be improved.

import java.util.Scanner;

public class ArrayElementFind {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String[] arr= { "A","B","C","D"};

        Scanner in=new Scanner(System.in);

        System.out.println("Enter the char to search");
        String a=in.nextLine();

        //int len=arr.length;

        boolean check=loopcheck(arr,a);

        if(check){
            System.out.println("Element is present");
        }
        else{
            System.out.println("Element is not present");
        }

    }

    private static boolean loopcheck(String[] arr, String a) {
        // TODO Auto-generated method stub

        for(String s:arr){
            if(s.equals(a)){
                return true;
            }
        }

        return false;
    }
}


texts:
WeakPtr can point to any object provided it inherits from WeakBase. So, for example, you could use it to observe an object managed by a unique_ptr (that's my use case). It is not possible to make this thread safe.

Curious what could be improved.

#ifndef WeakPtr_h
#define WeakPtr_h

#include <memory>
#include <iostream>
#include <cassert>

class WeakBase;

struct Remnant {
  bool alive = true;
};

// An intrusive zeroing weak pointer.
// Not thread safe.
template<class T>
class WeakPtr {

  std::shared_ptr<Remnant> _r;
  T* _p;

 public:
  WeakPtr(T* ptr = nullptr) : _r(ptr ? ptr->GetRemnant() : nullptr ), _p(ptr) { }

  WeakPtr(const WeakPtr& other) : _r(other._r), _p(other._p) { }

  ~WeakPtr() { }

  WeakPtr& operator=(const WeakPtr& other) {
    if(this != &other) {
      _r = other._r;
      _p = other._p;
    }
    return *this;
  }

  T* operator->() const {
    assert(_r);
    assert(_r->alive);
    return _p;
  }

  operator bool() const {
    if(_r) {
      return _r->alive;
    }
    return false;
  }

  T* Get() const {
    if(_r && _r->alive)
      return _p;
    return nullptr;
  }

  std::shared_ptr<Remnant> GetRemnant() const {
    return _r;
  }

  T& operator*() const {
    assert(_r);
    assert(_r->alive);
    return *Get();
  }

  template<class T2>
  bool operator==(const WeakPtr<T2>& other) const {
    return _r == other.GetRemnant();
  }

  template<class T2>
  bool operator!=(const WeakPtr<T2>& other) const {
    return _r != other.GetRemnant();
  }

  template<class T2>
  bool operator<(const WeakPtr<T2>& other) const {
    // Compare remnants to ensure the order
    // is stable even after objects are deleted.
    return _r < other.GetRemnant();
  }

  void Print(std::ostream& out) const {
    out << _p;
  }

}; // class WeakPtr

class WeakBase {

  std::shared_ptr<Remnant> _r;

public:

  WeakBase() { }

  const std::shared_ptr<Remnant>& GetRemnant() {

    if(! _r)
      _r = std::make_shared<Remnant>();
    return _r;
  }

  virtual ~WeakBase() {
    if(_r)
      _r->alive = false;
  }

};

template<class T>
std::ostream& operator<<(std::ostream& out, const WeakPtr<T>& p) {
  p.Print(out);
  return out;
}

#endif // WeakPtr_hpp

Commentary

It would be possible to eliminate Remnant and reduce the size of WeakPtr by using the null_deleter technique here: http://www.boost.org/doc/libs/1_59_0/libs/smart_ptr/sp_techniques.html#weak_without_shared. However that results in needless atomic modification of the shared_ptr use count (via weak_ptr::lock) every time the pointer is used.

Basic Usage Example

struct TestWeakPtr : public WeakBase {

  virtual ~TestWeakPtr() { }

};

static void basicTest() {
  auto p = new TestWeakPtr;

  WeakPtr<TestWeakPtr> wp(p);

  assert(wp);

  delete p;

  assert(! wp);
}


texts: User defined string literals and namespace use

texts:
I have a need to process URIs in one of my applications, sometimes from const char[] literals.

My API:

namespace net {
    class uri { ... }; // contains decomposed URI (path, parameters, etc)

    uri parse_uri(const std::string& uri_str); // parse string and return uri instance
}

// within global namespace (this is what the question is about):
uri operator "" _uri(const char*str, const unsigned long size)
{
    return net::parse_uri(std::string{str, str + size});
}

Client code:

auto x = "/static/path/here/image.jpg"_uri;

I tried defining the string conversion operator within the net namespace, but (disimilar to other operators) it seems I have to explicitly specify access to it in client code (with using namespace net; for example).

My question:

Does this clash with the "compiler searches for operators in the namespace of the object it applies to" rule (like it would for an operator+(uri&, uri&) for example)? (As a rule of thumb, I assume the problem is with my code, not the compiler).

What is the best practice or policy to use here? Import the namespace / operator in client code, or pollute the global namespace (like I did)?

I am using CLang 5.1 on OS X.


texts:
I have made a beginner program using C that uses file handling and formats the given file. Formatting includes removing trailing blank spaces, replacing one or more blanks by a single blank and also wrapping lines.
It would be extremely helpful if you could point out the mistakes I have made and also if  I add any other features to file formatting.

MAIN.C

#include <stdio.h>
#include <stdlib.h>
#include "whiteSpacing.c"
#include "lineFolding.c"

FILE *p;
FILE *q;
char c;

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Error! Check number of arguements.\n");
        exit(-1);
    }

    p = fopen(argv[1], "r");                //original file containing input
    q = fopen("temporary.txt", "w");

    if(p == NULL || q == NULL)          //error checking, also asks user if file is to be created.
    {
        printf("ERROR! Unable to open file\n");
        printf("Do you want to create '%s' file ? (y/n)\n", argv[1]);
        c = getchar();

        if(c == 'y' || c == 'Y')
        {
            p = fopen(argv[1], "w+");
            printf("Type here to write to the file\n");

            while((c = getchar()) != EOF)
            {
                putc(c, p);
            }
            fclose(p);

            p = fopen(argv[1], "r");
        }

        else
            exit(1);
    }

    while((c = getc(p)) != EOF)   // for line wrapping
    {
        folding();
    }

    fclose(p);
    fclose(q);

    p = fopen("temporary.txt", "r");  // original file will be overwritten
    q = fopen(argv[1], "w");

    if(p == NULL || q == NULL)
    {
        printf("ERROR! Unable to open file\n");
        exit(1);
    }

    while((c = getc(p)) != EOF)         //removes trailing spaces/tabs, also replaces two or more white space by a single space.
    {
        whiteSpacing();
    }

    remove("temporary.txt");

    printf("Text in \"%s\" was formatted and overwritten.\n", argv[1]);
    fclose(p);
    fclose(q);

    return 0;
}

linefolding.c

#define MAXLEN 65       //length for wrapping
#define MAXLINE 1000    // maximum length for one line

extern FILE *p;
extern FILE *q;
extern char c;

int getLine(char *);
void trim(char *);

void folding(void)
{
    char line[MAXLINE];
    int len;

    while((len = getLine(line)) > 1) // proceed only if length of line is greater than 1
    {
        if(len > MAXLEN)    // fold the length only if length of line is greater than the MAXLEN.
        {
            trim(line);
        }
        fprintf(q, "%s", line);
    }

}

int getLine(char line[])
{
    int nc = 0;
    while(((c != EOF)) && c != '\n')  // store each character of a line in an array.
    {
        line[nc] = c;
        nc++;
        c = getc(p);
    }
    if(c == '\n')
        line[nc] = '\n';

    line[nc + 1] = '\0';

    return nc;
}

void trim(char line[])
{
    int i = 0;
    int lastBlank = 0;
    int j = 1;

    for(i = 0; line[i] != '\0'; i++)
    {
        if(line[i] == ' ' || line[i] == '\t' || line[i] == '\n' || line[i] == ',' || line[i] == '.')   // kees track of the last white Spacing or non alphabetical character .
        {
            lastBlank = i;
        }

        if(i == MAXLEN * j)    //prints a new line at every MAXLEN interval
        {
            line[lastBlank] = '\n';
            j++;
        }
    }

    line[i] = '\n';
    line[i + 1] = '\0';
}

whiteSpacing.c

#include <stdio.h>

extern FILE *p;
extern FILE *q;
extern char c;

void whiteSpacing()
{
    while(c == ' ')   //replaces two or more spaces by a single space
    {
        c = getc(p);
        if (c != ' ' && c != EOF)
            putc(' ', q);

    }
    putc(c, q);
}


texts:
I'm looking for the best solution.

Here is a response from server and i need to get Organizations list:

Content-Type:application/json;charset=UTF-8
 {
   "code": 0,
   "message": "success",
   "organizations": [
     {
       "organization_id": "10234695",
       "name": "Zillum",
       "contact_name": "John Smith",
       "email": "johnsmith@zillum.com",
       "is_default_org": false,
       "language_code": "en",
       "fiscal_year_start_month": 0,
       "account_created_date": "2016-02-18",
       "time_zone": "PST",
       "is_org_active": true,
       "currency_id": "460000000000097",
       "currency_code": "USD",
       "currency_symbol": "$",
       "currency_format": "###,##0.00",
       "price_precision": 2
     },
     {...},
     {...}
   ]

Here is my convert method:

var contentJson = await SendRequest(request);
            var contentJo = (JObject)JsonConvert.DeserializeObject(contentJson);
            var organizationsJArray = contentJo["organizations"]
                .Value<JArray>();

            var organizations = organizationsJArray.ToObject<List<Organization>>();

Code works, but I'm looking for a better Convert Method. Can I do without converting to JArray?


texts:
I have recently started trying Java 8 and I am trying to solve problems as much possible using Java 8 lingo.

I wrote the code for the Sparse Arrays problem on HackerRank and needed to know a few pointers regarding my code:

Is it the right way to code in Java 8?
How much more efficient is it than legacy Java programs?
Are there any improvements or misconceptions regarding the association of this code to Java 8?

public class SparseArrays {

    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        List<String> corpus = new ArrayList<String>();
        IntStream.range(0, N).forEach(n -> corpus.add(sc.next()));

        int Q = sc.nextInt();
        List<String> queries = new ArrayList<String>();
        IntStream.range(0, Q).forEach(n -> queries.add(sc.next()));

        queries.stream().forEach(query -> System.out.println(corpus.stream().filter(p -> p.equals(query)).count()));
    }
}


texts:
As some part of my application needs connection to database I wanted to create tests that use mocks to avoid running special instance of database just for testing. That gave me a glimpse of how can I use mocks and I played with them a bit.
I wanted to test express router:
UserRouter.post("/users", async ({ body }: Request, res: Response) => {
    try {
        const userRepository = getCustomRepository(UserRepository);
        const user = userRepository.create({ ...body } as User);
        await userRepository.save(user);
        res.send(user.toJSON());
    } catch (error) {
        res.status(400).send();
    }
});

To do so I created mocks:
jest.mock("typeorm", () => ({
    __esModule: true,
    getCustomRepository: jest.fn(),
    PrimaryGeneratedColumn: jest.fn(),
    Column: jest.fn(),
    CreateDateColumn: jest.fn(),
    UpdateDateColumn: jest.fn(),
    Entity: jest.fn(),
    EntityRepository: jest.fn(),
    Repository: jest.fn(),
}));

const getCustomRepositoryMock = mocked(getCustomRepository);
const MockedRepository = {
    create: jest.fn(),
    save: jest.fn(),
};
const MockedEntity = {
    toJSON: jest.fn(),
};

beforeEach(() => {
    jest.resetAllMocks();
    getCustomRepositoryMock.mockReturnValueOnce(MockedRepository);
});

Then instead of passing and requiring actual data to be return I relayed of testing whether mocks were used, what data were passed to their calls etc. Here is an example:
it("should call save on UserRepository with value returned by call create on UserRepository", async () => {
    MockedRepository.create.mockReturnValue(MockedEntity);
    await request(app).post(path).send();
    expect(MockedRepository.save).toBeCalledWith(MockedEntity);
});

Commit with all my tests is here.


texts:
I wrote a script which logs memory usage of a process (pid in file), and reacts in case a limit is reached. I run the script nightly. In my case, the process concerned propably has a memory leak and locks up the whole system after a couple of days. Hence, the script should reboot the system if excess memory is used. Logged memory usage values are formated to have 1 decimal place.

The code works, but I'd like to know if and how I could optimize it, and if there are no mistakes.

#!/bin/sh

# process_monitor.sh
#
# monitor specific process
# customized for memory usage monitor (can easily be changed)
# customized to perform system reboot if limit is exceeded (can easily be changed)
# by geohei <xxxx@xxxx.xx>
# created : 14.10.2016
# revised : n/a
#
# use cron to trigger (e.g. nightly at 04:15 '15 4 * * * ~/process_monitor.sh'
# /bin/bc is used (possibly not installed by default)
#
# $pidfile must include path
# $logpath is used to save 'process_monitor.log' file (omit trailing '/')
# $pidlimit can be floating point (e.g. 14.1)

pidfile='/tmp/process.pid'
logpath='~'
pidlimit=20.0

pidvalue=$(ps -p $(eval "cat $echo $pidfile") -o %mem --no-headers)

if [ "$(echo "${pidvalue} > ${pidlimit}" | bc)" -eq 1 ]; then
    # log $pidvalue, $pidlimit and reboot system
    echo "$(date '+%Y-%m-%d %H:%M:%S')   pidvalue: $pidvalue, pidlimit: $(echo $pidlimit | awk '{printf "%.1f\n", int($1)}') - reboot" >> $logpath/process_monitor.log
    shutdown -r -t 10
    exit 1
else
    # log $pidvalue, $pidlimit
    echo "$(date '+%Y-%m-%d %H:%M:%S')   pidvalue: $pidvalue, pidlimit: $pidlimit" >> $logpath/process_monitor.log
fi

exit 0

That's how the log looks like:

...
2016-10-14 04:15:04   pidvalue: 19.2, pidlimit: 20.0
2016-10-15 04:15:03   pidvalue: 20.4, pidlimit: 20.0 - reboot
...

Any remarks, comments or suggestions?


texts: How to efficently generate n different subsets of length k from List?

texts:
I would like to generate n subsets from objects from a List. Each subset should have k elements. Each subset should be unique.

The output should be a List of Lists.

My (very very slow way) is to create ALL possible subsets:

public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(IEnumerable<T> source)
{
    if (!source.Any())
        return Enumerable.Repeat(Enumerable.Empty<T>(), 1);

    var element = source.Take(1);

    var haveNots = SubSetsOf(source.Skip(1));
    var haves = haveNots.Select(set => element.Concat(set));

    return haves.Concat(haveNots);
}

Afterwards I select the subsets with length k with the help of linq .where(x => x.Count() == k) and randomly select n of them.

This is very slow, because if the input list has 50 elements, there are 1125899906842624 different possible subsets. This is a big overhead.

How can I solve this problem more efficiently?


texts: Combining text in an array in JavaScript

texts:
My JS looks like this:

preLoadImages("/media/img/elements/frontpage/1.jpg","/media/img/elements/frontpage/2.jpg","/media/img/elements/frontpage/3.jpg","/media/img/elements/frontpage/4.jpg","/media/img/elements/frontpage/5.jpg","/media/img/elements/frontpage/6.jpg","/media/img/elements/frontpage/7.jpg","/media/img/elements/frontpage/8.jpg","/media/img/elements/frontpage/9.jpg","/media/img/elements/frontpage/10.jpg");

What would be a better way to do this?

var directory = "/media/img/elements/frontpage/"

preLoadImages(directory+"1.jpg",directory+"2.jpg",directory+"3.jpg",directory+"4.jpg",directory+"5.jpg",directory+"6.jpg",directory+"7.jpg",directory+"8.jpg",directory+"9.jpg",directory+"10.jpg");

Doesn't seem much better. There must be a zip/map/join type thing I can use here?


texts:
I have improved this post to the code below.

As always, any critique is much appreciated!

<?php

class QueueNode {

    function __construct($item) {
        $this->item = $item;
        $this->next = null;
    }

    function __destruct() {
        $this->item = null;
    }

    function getItem() {
        return $this->item;
    }
}

class QueueIterator implements Iterator {

    function __construct($queue) {
        $this->queue = $queue;
        $this->current_node = $queue->head;
    }

    public function current() {
        return $this->current_node->item;
    }

    public function key(): \scalar {
        return null;
    }

    public function next(): void {
        $this->current_node = $this->current_node->next;
    }

    public function rewind(): void {
        $this->current_node = $this->queue->head;
    }

    public function valid(): bool {
        return isset($this->current_node);
    }
}

class Queue implements IteratorAggregate {

    function __construct() {
        $this->head = null;
        $this->tail = null;
        $this->size = 0;
    }

    function __destruct() {
        $this->head = null;
        $this->tail = null;
    }

    function push($item) {
        if ($this->size === 0) {
            $this->head = $this->tail = new QueueNode($item);
        } else {
            $new_node = new QueueNode($item);
            $this->tail->next = $new_node;
            $this->tail = $new_node;
        }

        $this->size++;
    }

    function pop() {
        if ($this->size === 0) {
            throw new Exception("Popping from an empty queue.");
        }

        $ret = $this->head->getItem();
        $this->head = $this->head->next;

        if (--$this->size == 0) {
            $this->head = $this->tail = null;
        }

        return $ret;
    }

    function getFirst() {
        if  ($this->size() === 0) {
            throw new Exception("getFirst() on empty Queue.");
        }

        return $this->head->getItem();
    }

    function getLast() {
        if ($this->size() === 0) {
            throw new Exception("getLast() on empty Queue.");
        }

        return $this->tail->getItem();
    }

    function size() {
        return $this->size;
    }

    function isEmpty() {
        return size() === 0;
    }

    public function getIterator(): \Traversable {
        return new QueueIterator($this);
    }
}

$queue = new Queue();

for ($i = 1; $i <= 10; $i++) {
    $queue->push($i);
}

echo "Iteration: ";

foreach ($queue as $item) {
    echo $item . " ";
}

echo "
Popping: ";

for ($i = 1; $i <= 10; $i++) {
    echo $queue->getFirst() . ", " . $queue->pop() . " ";
}

echo "
Bye!";
?>

Output

Iteration: 1 2 3 4 5 6 7 8 9 10
Popping: 1, 1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 8, 8 9, 9 10, 10
Bye!


texts:
I'm just starting to learn JavaScript. I implemented the Diamond kata, and I would appreciate if anybody could give me some feedback. I'm particularly concerned about learning the most 'idiomatic' way to do things in JavaScript, style conventions, etc.

The diamond kata consists of the following problem statement:

Given a letter, print a diamond starting with ‘A’ with the supplied letter
at the widest point.

For example: print-diamond ‘C’ prints

  A
 B B
C   C
 B B
  A

The production code (test code in the Gist):

// Diamond Kata with a TDD approach. First attempt
'use strict';

module.exports.Diamond = Diamond;

function Letter(char, spaces) {
  this._char = char;
  this._spaces = spaces;
}
Letter.prototype.print = function print() {
  return this._char + (
    (this._spaces > 0)
      ? (Array(this._spaces + 1).join(' ') + this._char + '\n')
      : '\n'
  );
}

// Singleton list with all letters
var LETTERS = new function () {
  // Init all upper-case letters
  for (let char=65; char <= 90; char++) {
    let character = String.fromCharCode(char);
    this[character] = new Letter(character, (char - 65) + (char - 65 - 1));
  }
}();
LETTERS.__proto__.iterateLetters = function (character, callback) {
  var chars = Object.keys(this);
  var last = chars.indexOf(character);
  var pos = 0;
  var direction = 1;
  // Forwards
  while (pos >= 0) {
    callback(this[chars[pos]], pos, last);
    if (pos === last) {
      // Reached final character, return to 'A'
      direction = -1;
    }
    pos += 1 * direction;
  }
}

function Diamond (letter) {
  if (typeof(letter) !== 'string' && !(letter instanceof String)) {
    throw new Error('Letter must be an string');
  }
  this._letter = letter;
};
Diamond.prototype.process = function process() {
  var prefix = function (max, current) {
    return Array(1 + max - current).join(' ');
  }
  var result = '';
  LETTERS.iterateLetters(this._letter, function (letter, current, last) {
    result += prefix(last, current);
    result += letter.print();
  });
  return result;
}

This code is meant to execute at a "Node --harmony" environment, although except from the module exportation, this is just plain JavaScript.

A working demo is available here.

This is written using a TDD approach. The test code, as well as this same snippet, can be found in the Gist.


texts: Managing configs to use scripts on different computers

texts:
I have some python scripts to run on different computers. To avoid struggles with different paths and filenames I made specific config-files (DConfig, AConfig and MConfig) and another script that decides which config to use. It works, but I guess, there are better ways to do this. Any ideas?
import os
import socket

hostname_K = 'DESKTOP-K'
hostname_A = 'A'
hostname_M = ''                    # hostname not known for sure

print("start config")
print("cwd: ", os.getcwd())
print("os: ", os.name)
# print(os.getlogin())                # Doesn't work on non-posix

hostname = socket.gethostname()
if hostname == hostname_K:
    import DConfig as Conf
elif hostname == hostname_A:
    import AConfig as Conf
else:
    print("Hostname: {}, guess we are on M".format(hostname))
    import MConfig as Conf

dirData = Conf.dirData
dirScript = Conf.dirScript
pathDB = Conf.pathDB

print("config done.")

How it is used by other scripts:
import config
XMLFILE = config.dirData + 'Tags.xml'
DATABASE = config.pathDB

Here is an example script for one of the config-files.
dirData = '/home/username/path/to/data/'
dirScript = '/home/username/path/to/scripts/'
pathDB = '/home/username/path/to/database.db'

The other scripts are similar.


texts: Trie data structure in C++ with add and search

texts:
I am learning C++11 and wanted to practice data structures so here is my trie implementation with add and search functions. What are some things to improve?

trie.h

#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>

namespace {
    class Node
    {
    public:
        Node();
        ~Node();
        Node(char c);
        char get_value() const;
        bool get_leaf() const;
        void set_leaf();

        Node* get_child(const char key);
        std::vector<Node *> children;

    private:
        char value;
    };
}

class NodePointerComp
{
public:
    explicit NodePointerComp(const char key);
    char const key_;
    bool operator()(Node const *n) const;

};

class Trie
{
public:
    Trie();
    ~Trie();
    void add_word(std::string const &word);
    bool search(std::string const &word);
    std::vector<std::string> find_suffix(std::string const &s, int max);

private:
    Node *root;
    Node* find_string(std::string const &word);
};

trie.cpp

#include "trie.h"

Node::Node() {}
Node::Node(char c) : value(c) {}

char Node::get_value() const { return value < 0 ? -value : value; }

bool Node::get_leaf() const { return value < 0 ? true : false; }

// a string with char -128 or a nullchar will break this
void Node::set_leaf()
{
    if (value > 0)
        value = -value;
}

NodePointerComp::NodePointerComp(const char key) : key_(key) {}

bool NodePointerComp::operator()(Node const *n) const { return n->get_value() == key_; }

Node* Node::get_child(const char key)
{
    auto x = std::find_if(children.begin(), children.end(), NodePointerComp(key));
    if (x == children.end())
        return nullptr;

    return *x;
}

Node::~Node()
{
    for (auto c : children)
        delete c;
}

Trie::Trie()
{
    root = new Node();
}

void Trie::add_word(std::string const &word)
{
    Node *curr = root;

    uint32_t i = 0;
    for (i; i < word.length(); i++)
    {
        if (curr->get_child(word[i]) == nullptr)
            break;

        curr = curr->get_child(word[i]);
    }

    for (i; i < word.length(); i++)
    {
        curr->children.push_back(new Node(word[i]));
        curr = curr->children.back();
    }

    curr->set_leaf();

}

std::vector<std::string> Trie::find_suffix(std::string const & s, int max)
{
    Node *curr = find_string(s);
    if (!curr || max == 0)
        return {};

    std::vector<std::string> output;
    std::stack<std::pair<Node*, std::string>> st;

    for (auto c : curr->children)
        st.push({ c, ""});

    while (!st.empty())
    {
        auto p = st.top();
        st.pop();

        p.second += p.first->get_value();
        if (p.first->get_leaf())
        {
            output.push_back(p.second);
            if (output.size() == max)
                break;
        }

        for (auto c : p.first->children)
            st.push({ c, p.second });

    }

    return output;
}

Node* Trie::find_string(std::string const & word)
{
    Node *curr = root;
    std::string str;

    for (auto c : word)
        if ((curr = curr->get_child(c)) == nullptr)
            return nullptr;

    return curr;
}

bool Trie::search(std::string const &word)
{
    auto *p = find_string(word);
    if (p) return p->get_leaf();
    return false;
}

Trie::~Trie()
{
    delete root;
}


texts:
I'm creating a pandas.DataFrame out of lags from an existing pandas.DataFrame, using DataFrame.shift and pandas.concat. There are a two aspects I don't like about this code:

Using np.ones_like to create constants
Building up a list of lag tables and using pandas.concat to combine them

"""
>>> df = pd.DataFrame({'GDP': [100, 110, 120, 130, 140, 150],
...                    'INV': [0, 10, 20, 30, 40, 50]})

>>> lagged_dataframe(df, lags=3)
   GDP  INV  GDP_Int  INV_Int  GDP_Lag01  INV_Lag01  GDP_Lag02  INV_Lag02  \\
0  100    0        1        1        NaN        NaN        NaN        NaN
1  110   10        1        1      100.0        0.0        NaN        NaN
2  120   20        1        1      110.0       10.0      100.0        0.0
3  130   30        1        1      120.0       20.0      110.0       10.0
4  140   40        1        1      130.0       30.0      120.0       20.0
5  150   50        1        1      140.0       40.0      130.0       30.0
<BLANKLINE>
   GDP_Lag03  INV_Lag03
0        NaN        NaN
1        NaN        NaN
2        NaN        NaN
3      100.0        0.0
4      110.0       10.0
5      120.0       20.0

"""

import numpy as np
import pandas as pd

def constants(df):
    new_columns = ["{}_Int".format(variable) for variable in df.columns]
    return pd.DataFrame(np.ones_like(df.loc[:,:]), index=df.index, columns=new_columns)

def lag(df, n):
    new_columns = ["{}_Lag{:02d}".format(variable, n) for variable in df.columns]
    new_df = df.shift(n)
    new_df.columns = new_columns
    return new_df

def lagged_dataframe(df, lags=1):
    data_frames = [df]
    data_frames.append(constants(df))
    data_frames.extend([lag(df, i) for i in range(1, lags + 1)])
    return pd.concat(data_frames, axis=1)

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True, optionflags=doctest.NORMALIZE_WHITESPACE)


texts: Precognitive waiting - waiting for something to finish, before it starts

texts:
I have implemented a class that has a method to wait until "something else" has happened. When this has happened, the current thread stops waiting and returns from the method. This is my current code:

public class InMemoryAviReadyNotifier implements AviReadyNotifier, MessageListener<UrlAviMessage>
{
    private Map<SourceAndFileName, CountDownLatch> m_map = Maps.newConcurrentMap();
    private Map<SourceAndFileName, URL> m_resultMap = Maps.newConcurrentMap();

    @Override
    public void messageReceived( MessageSource messageSource, UrlAviMessage message )
    {
        SourceAndFileName key = new SourceAndFileName( (DetectorMessageSource)messageSource, message.getFileName() );
        CountDownLatch countDownLatch = m_map.get( key );
        if( countDownLatch != null )
        {
            m_resultMap.put( key, message.getLocation() );
            countDownLatch.countDown();
        }
        m_map.remove( key );
    }

    @Override
    public Class<? extends DeviceToServerMessage> responseClass()
    {
        return UrlAviMessage.class;
    }

    @Override
    public InputStream waitForAvi( DetectorMessageSource messageSource, String aviFileName ) throws InterruptedException
    {
        CountDownLatch countDownLatch = new CountDownLatch( 1 );
        SourceAndFileName key = new SourceAndFileName( messageSource, aviFileName );
        m_map.put( key, countDownLatch );
        countDownLatch.await();
        URL url = m_resultMap.get( key );
        // TODO download the avi to a temp local folder so we can add connect and read timeouts on the connection
        return url.openStream();
    }

    private static class SourceAndFileName
    {
        private final DetectorMessageSource m_source;
        private final String m_fileName;

        public SourceAndFileName( DetectorMessageSource source, String fileName )
        {
            m_source = source;
            m_fileName = fileName;
        }

        @Override
        public boolean equals( Object o )
        {
            boolean result = false;

            if (this == o)
            {
                result = true;
            }
            else if (o instanceof SourceAndFileName)
            {
                SourceAndFileName other = (SourceAndFileName)o;

                result = Objects.equals( m_source, other.m_source)
                        && Objects.equals( m_fileName, other.m_fileName );
            }

            return result;
        }

        @Override
        public int hashCode()
        {
            return Objects.hash( m_source, m_fileName );
        }

        @Override
        public String toString()
        {
            return toStringHelper( this )
                    .add( "source", m_source )
                    .add( "fileName", m_fileName )
                    .toString();
        }
    }
}

The waitForAvi method gets called from one thread. It will wait until messageReceived gets called with the good arguments and then it will countdown the CountDownLatch. I need to get the message.getLocation() return value (an URL) in the waitForAvi method. I using 2 Maps like I do here the best option or are there alternatives I could consider?

I am aware that in the current implementation I can potentially wait forever if the messageReceived never happens, but adding timeouts to this code has not been done yet.


texts:
I have the below code. I have list of status which contain may contain 4 values. R,UR,DO,NDO

based on this list. i need to convert to Y,N values

If list contains R the Readstatus="Y"

If list contains UR the Readstatus="N"

If both the ReadStatus="Y,N"

If list contains DO the DoneStatus="Y"

If list contains NDO the DoneStatus="N"
If both the DoneStatus="Y,N"

the below code works but its too ugly. is there any thing i can change

                Dim Readstatus As String = ""
                Dim DoneStatus As String = ""
                If Not String.IsNullOrEmpty(Status) Then
                    Dim listStatus = Status.Split(",").ToList()
                    If listStatus.Contains("R") Then
                        Readstatus = "Y"
                    End If
                    If listStatus.Contains("UR") Then
                        If String.IsNullOrEmpty(Readstatus) Then
                            Readstatus = "N"
                        Else
                            Readstatus = Readstatus & ",N"
                        End If

                    End If
                    If listStatus.Contains("DO") Then
                        DoneStatus = "Y"
                    End If
                    If listStatus.Contains("NDO") Then
                        If String.IsNullOrEmpty(DoneStatus) Then
                            DoneStatus = "N"
                        Else
                            DoneStatus = DoneStatus & ",N"
                        End If
                    End


texts:
Ok so my name is qqqiiiiiiiifdff and I made this code that simulates a perceptual color picker algorithm that selects the nearest color by iterating over the color array and selecting the minimum error, processing the calculations in a perceptual manner.
This is an example:
#include <stdint.h>
#include <math.h>

inline double square(double x){return x*x;}

inline double sRGBtolinear(double input){
    if(input < 0) return -sRGBtolinear(-input);
    else if(input > 0.0404482362771082) return pow((input+0.055)/1.055, 2.4);
    else return input/12.92;
}

inline double lineartosRGB(double input){
    if(input < 0) return -lineartosRGB(-input);
    else if(input > 0.00313066844250063) return pow(input, 0.4166666666666667)*1.055-0.055;
    else return input*12.92;
}

inline double lineartosRGBderivative(double input){
    if(input < 0) return lineartosRGBderivative(-input);
    else if(input > 0.00313066844250063) return pow(input, -0.5833333333333334)*0.4166666666666667*1.055;
    else return 12.92;
}

uint64_t selectnearest(uint32_t* palette, uint64_t palettelength, uint32_t color){
    uint64_t index = 0;
    double maxerror = 1.0/0.0;
    for(uint64_t i=0; i<palettelength; i++){
        double color1[3];
        double color2[3];
        color1[0] = sRGBtolinear((color/65536%256)/255.0);
        color1[1] = sRGBtolinear((color/256%256)/255.0);
        color1[2] = sRGBtolinear((color%256)/255.0);
        color2[0] = sRGBtolinear((palette[i]/65536%256)/255.0);
        color2[1] = sRGBtolinear((palette[i]/256%256)/255.0);
        color2[2] = sRGBtolinear((palette[i]%256)/255.0);
        double initdistance = sqrt((square(212671.0*(color1[0]-color2[0]))+square(715160.0*(color1[1]-color2[1]))+square(72169.0*(color1[2]-color2[2])))/561891144402.0);
        double brightness1 = ((212671.0*color1[0])+(715160.0*color1[1])+(72169.0*color1[2]))/1000000.0;
        double brightness2 = ((212671.0*color2[0])+(715160.0*color2[1])+(72169.0*color2[2]))/1000000.0;
        double sRGBbrightness1 = lineartosRGB(brightness1);
        double sRGBbrightness2 = lineartosRGB(brightness2);
        double brightnessdifference = brightness2 - brightness1;
        double sRGBbrightnessdifference = sRGBbrightness2 - sRGBbrightness1;
        if(brightness1 == brightness2){
            brightnessdifference = 1;
            sRGBbrightnessdifference = lineartosRGBderivative(brightness1);
        }
        double result = initdistance*(sRGBbrightnessdifference/brightnessdifference);
        if(result < maxerror){
            index = i;
            maxerror = result;
        }
    }
    return index;
}

int main(){
    const uint64_t amountofcolors = 216;
    uint32_t palette[amountofcolors];
    for(uint64_t i=0; i<216; i++){
        palette[i] = i%6*0x000033 + i/6%6*0x003300 + i/36%6*0x330000;
    } // sample palette
    volatile uint32_t color;
    for(uint64_t i=0; i<65536; i++){
        color = (rand()%4096)+(rand()%4096*4096);
        color = palette[selectnearest(palette, amountofcolors, color)];
    }
}

To a person who does not know any code, this does not appear inefficient until it is run. What happened here? The process returned zero, and the execution time is 31.141 seconds. Now, it might seem like this is quite fast for 65536 colors to quantize to the palette, however you could imagine how a dynamic script to play a 256×256 movie in a reduced palette will play in 0.03 fps. Could this be a processing error and I have to try again? No, because the next time it is not much better at 31.085 seconds, and again at 31.110 seconds. Now, you could argue that a different color picker algorithm would be faster, however that is not the point because they don't pick colors the same way, the point is to make this specific algorithm faster, but still pick the colors about the same way. What should be done in order to improve the efficiency of this method?


texts: Simple command line tool to query database. Need code optimized

texts:
public class ConsoleQuery {
    public static void main(String[] args) throws SQLException {
        if (args.length == 0) {
            System.out.println("You must specify name");
            return;
        }
        String name = args[0];
        Map < String, Object > device = getDeviceByName(name);
        if (device != null) {
            System.out.printf("Found device by name %s: %s",
                name, device);
        } else {
            System.out.printf("There is no device by name %s", name);
        }
    }

    private static Map < String, Object > getDeviceByName(String name) throws SQLException {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "test", "test");
        PreparedStatement statement = connection.prepareStatement("SELECT id, mac, name FROM device");
        ResultSet rs = statement.executeQuery();
        List < Map < String, Object >> deviceList = new LinkedList < Map < String, Object >> ();
        try {
            ResultSetMetaData rsmd = rs.getMetaData();
            Integer columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                Map < String, Object > row = new LinkedHashMap < String, Object > ();
                for (int i = 1; i <= columnCount; i++) {
                    row.put(rsmd.getColumnName(i), rs.getObject(i));
                }
                deviceList.add(row);
            }
        } finally {
            rs.close();
        }
        for (Map < String, Object > device: deviceList) {
            if (name.equals(String.valueOf(device.get("name")))) {
                return device;
            }
        }
        return null;
    }
}


texts: Proper way of handling exceptions while reading user input from file

texts:
I am parsing a text file (UTF-8) and checking for several conditions that need to be satisfied for the code to be happy. If not, then there is no point to continue and the program should die.

At the moment I am catching exceptions and if caught, throw RuntimeException to signal the user that something went wrong.

What would be a proper way of doing this or is it OK the way it is?

/**
 * Reads the maze from plain text and converts it to char[][]
 * Marks the start (B) and end (F) coordinates if found, if not throws exception
 * Expects each line to have the same length as the the first line, throws exception if not
 *
 * @return maze as char[][]
 */
private char[][] readMazeFromFile() {
    List<String> stringList;
    try {
        stringList = Files.readAllLines(Paths.get("h40.in"), Charset.forName("UTF-8"));
    } catch (MalformedInputException e){
        throw new RuntimeException(String.format("Did not understand file,
        check the charset, expecting UTF-8\n%s", e.getMessage()));
    } catch (IOException e) {
        throw new RuntimeException(String.format("Did not understand file,
        sorry\n%s", e.getMessage()));
    } catch (Exception e){
        throw new RuntimeException(String.format
        ("Generic error while reading the input file, sorry\n%s", e));
    }

    char[][] charMaze = new char[stringList.size()][];
    for (int i = 0; i < stringList.size(); i++) {
        if (stringList.get(i).contains("B")) {
            startX = i;
            startY = stringList.get(i).indexOf("B");
        }
        if (stringList.get(i).contains("F")) {
            endX = i;
            endY = stringList.get(i).indexOf("F");
        }
        try {
            charMaze[i] = stringList.get(i).toCharArray();
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new RuntimeException(String.format("Did not understand the maze,
            expecting square.\n%s", e.getMessage()));
        }

    }
    if (startX == -1 || startY == -1)
        throw new RuntimeException("Could not find starting point (B), aborting.");
    if (endX == -1 || endY == -1)
        throw new RuntimeException("Could not find ending point (F), aborting.");
    return charMaze;
}


texts:
The problem can be found online here.

In short, we're given the following function definition, that will recursively generate all the possible solutions for the "eight-queen-problem".

(define (queens board-size)
  (define (queen-cols k)
    (if (= k 0)
        (list empty-board)
        (filter
         (lambda (positions) (safe? k positions))
         (flatmap
          (lambda (rest-of-queens)
            (map (lambda (new-row)
                   (adjoin-position new-row k rest-of-queens))
                 (enumerate-interval 1 board-size)))
          (queen-cols (- k 1))))))
  (queen-cols board-size))

The problem consists of:

implementing the representation of board positions and define empty-board.
writing the function definitions for adjoin-position and safe?

The two following functions have already been defined in previous exercises:

(define (enumerate-interval low high)
  (if (> low high)
      '()
      (cons low
        (enumerate-interval (+ low 1) high))))

(define (flatmap proc seq)
  (fold-rigth append '() (map proc seq)))

Here's my commented working solution. You'll find I express my ideas in Python a lot, because it's practically like writing pseudo-code and, sadly, it still governs pretty much the way I think of code. I'm looking for any kind of feedback, from how to improve execution time, to how to make it more readable or any Scheme good practice you may mention. I don't know anybody in real-life who codes in Scheme, so I seek feedback from the next best place :)

;; A set of position is a list of pairs.
;; The pairs are cons where the car is the value of the row and the cdr is the column.
;; Since we're recursively iterating through the board horizontally, the cdr can be seen as the index.

(define empty-board '())

(define (adjoin-position row col board)
  (append board (list (cons row col))))

;; in python there's the bracket syntax to return an element from a list:
;; f[3] returns the 4th element of f. I could not find such a thing in Scheme, so I wrote this function.
(define (getposval pos idx)
  (caar (filter (lambda (pair) (= (cdr pair) idx))
        pos)))

;; any/all (say it quickly it sounds like Annie Hall) are inspired by their Python equivalent.
;; Is there something similar in Scheme?
(define (any? seq)
  (fold-right (lambda (x y) (or x y)) #f seq))

(define (all? seq)
  (fold-right (lambda (x y) (and x y)) #t seq))

;; A position set is not safe if there exist i such as:
;;    - pos[col] == pos[i] # they're on the same row
;;    or
;;    - abs(pos[col] - pos[i]) == col - i # they're on a diagonal
(define (safe? col positions)
    (all? (map (lambda (x)
            (or (= col (cdr x))
                    ;; I should not write (getposval positions) so often
                    ;; maybe replace it with a let?
            (not (or (= (getposval positions col)
                    (getposval positions (cdr x)))
                 (= (abs (- (getposval positions col)
                        (getposval positions (cdr x))))
                    (- col (cdr x)))))))
           positions)))


texts:
Sometimes I need a reference counting smart pointer that should not be nullptr. For example, I want to share a very heavy object without copying. And it's more convenient to place it on the heap. So I could use a shared_ptr. Also, I don't need to assign nullptr to this pointer or reassign it. So I don't want to check for nullptr in code that uses it. I think it would be useful to have a pointer that cannot be nullptr and cannot be reassigned.

I wrote a small prototype that has this features.

 #include <iostream>
 #include <string>
 #include <memory>
 #include <exception>
 #include <thread>

 using namespace std;

 // Box cannot hold nullptr
 template<class T>
 class Box
 {
 public:
     template <class... Args>
     static Box<T> create(Args&&... args)
     {
         return Box<T>(make_shared<T>(std::forward<Args>(args)...));
     }

     T * operator-> () const
     {
         return ptr.operator -> ();
     }
 private:
     Box(const shared_ptr<T> & ptr)
         : ptr(ptr)
     {}

     shared_ptr<T> ptr;
 };

 struct Test
 {
     Test(int i, double d, const string & s)
         : i(i), d(d), s(s)
     {
         cout << "Test ctor" << endl;
     }

     ~Test()
     {
         cout << "Test dtor" << endl;
     }

     Test(const Test & test) = delete;
     Test(Test && test) = delete;
     Test & operator = (const Test & test) = delete;
     Test & operator = (Test && test) = delete;

     int i;
     double d;
     string s;
 };

 void print(const Box<Test> & test)
 {
     // there is no need to check for nullptr
     cout << test->i << " " << test->d << " " << test->s << endl;
 }

 void twice(Box<Test> test)
 {
     // there is no need to check for nullptr
     test->i *= 2;
     test->d *= 2;
     test->s += test->s;
 }

 /*
 stdout:
 Test ctor
 42 3.14 hello
 84 6.28 hellohello
 Test dtor
 */
 int main()
 {
     Box<Test> test = Box<Test>::create(42, 3.14, "hello");
     print(test);

     thread t(twice, test);
     t.join();

     print(test);
 }

Is this code correct? And is this a good approach?

Update:
It looks like I found a ready solution https://github.com/dropbox/nn

Related discussions:

1) https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/5TPClBA1fs8

2) http://boost.2283326.n4.nabble.com/Why-no-non-null-smart-pointers-td2642959.html

3) https://lists.boost.org/Archives/boost/2013/10/206732.php


texts:
I'm trying to implement business logic layer based on concepts of commands and command handlers.

A command is a thing that contains input parameters for executing some action, and it knows what kind of output that action should produce. A command handler contains logic for actually executing an action: it accepts a command as a param, handles it in some way, and (if successful) produces an output object.

public interface ICommand<TResultData>
{ }

public interface ICommandHandler<TCommand, TResultData>
    where TCommand : ICommand<TResultData>
{
    CommandResult<TResultData> Handle(TCommand command);
}

public static class CommandProcessor
{
    public static CommandResult<TResultData> Process<TCommand, TResultData>(TCommand command)
        where TCommand : ICommand<TResultData>
    {
        var handler = ServiceLocator.GetInstance<ICommandHandler<TCommand, TResultData>>();
        return handler.Handle(command);
    }
}
public class CommandResult<TResultData>
{
    public bool Success { get; set; }

    public string Error { get; set; }

    public TResultData Data { get; set; }
}

Example usage:

// CreateUserCommand & handler implementations *very* simplified
public class CreateUserCommand : ICommand<User>
{
    public string Email { get; set; }
}

public class CreateUserCommandHandler : ICommandHandler<CreateUserCommand, User>
{
    private readonly IRepository repository;
    public CreateUserCommandHandler (IRepository repository)
    {
        this.repository = repository;
    }
    public CommandResult<User> Handle(CreateUserCommand command)
    {
        if(this.repository.Users.Any(u=>u.Email == command.Email)
          return new CommandResult<User> { Success = false, Error = "Email already taken"};
        var user = new User {Email = command.Email};
        this.repository.Users.Add(user);
        return new CommandResult<User> { Success = true, Data = user};
    }
}

// command usage in application code
var command = new CreateUserCommand { Email = "some.email.com" };
CommandResult<User> result = CommandProcessor.Process(command);
if(result.Success)
{
    // at this point we know that result.Data is of type User, which is nice
    // so we can use this strictly-typed result data in any way
    User createdUser = result.Data;
    Console.Writeline("Created user with Id = " + createdUser.Id);
}
else
{
    Console.Writeline("Error creating user: " + result.Error);
}

Everything works pretty nice, as you can see in the usage example, but one thing that bothers me is the empty interface ICommand. Is it a bad thing here? Can the code be refactored in some way to make it better?


texts:
Just as a learning exercise, I set out making a stopwatch without looking up how to do it etc.

I know it will have been done many times before.  I'm just looking for some feedback on what I should do to make the code more efficient / cleaner / in keeping with standards etc.

This is the result

// declare vars
var secondsDiv = $("#seconds");
var minsDiv = $("#mins");
var hoursDiv = $("#hours");
var interval = null;
var timer = false;

// return the value of a given div
function getCurrentValue(value) {
  return value.html();
}

// reset the value of a chosen div to 00
function resetValue(value){
  value.html("00");
}

// check if values are more than 59 to progress the timer
function check59() {
  var currentSec = getCurrentValue(secondsDiv);
  var currentMins = getCurrentValue(minsDiv);
  var currentHours = getCurrentValue(hoursDiv);
  // check the seconds to become a minute
  if (currentSec > 59) {
    currentMins++;
    if (currentMins < 10) {
      minsDiv.html("0" + currentMins);
    } else {
      minsDiv.html(currentMins);
    }
    resetValue(secondsDiv);
  }
  // check the minutes to become an hour
  if (currentMins > 59) {
    currentHours++;
    if (currentHours < 10) {
      hoursDiv.html("0" + currentHours);
    } else {
      hoursDiv.html(currentHours);
    }
    resetValue(minsDiv);
  }
}

// add seconds
function addSecond() {
  var currentSec = getCurrentValue(secondsDiv);
  currentSec++;
  if (currentSec < 10) {
    secondsDiv.html("0" + currentSec);
  } else {
    secondsDiv.html(currentSec);
  }
  check59();
}

// run the initial addSecond function every second
$("#startTimer").click(function(){
  if (timer===false) {
    timer = true;
    interval = setInterval(addSecond, 1000);
  }
});

// stop the addSecond function every second
$("#pauseTimer").click(function(){
  clearInterval(interval);
  timer = false;
});

// reset all values
$("#clearTimer").click(function(){
  resetValue(secondsDiv);
  resetValue(minsDiv);
  resetValue(hoursDiv);
});


texts: Suspend and resume a thread using signals

texts:
The other day I ran into this question on stackoverflow.
Just for curiosity I wanted to implement suspending and resuming the thread, so I used signals and used pause() in the signal handler.

Is it OK to use this way? This question has many answers how to suspend/resume a thread, but I want to know what is wrong with my approach.

As far as I know signal handlers should be treated as interrupts i.e. minimum code and immediate return from it.

According to this, pause() is async-signal safe system call.

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>

// Since I have only 2 threads so using two variables,
// array of bools will be more useful for `n` number of threads.
static int is_th1_ready = 0;
static int is_th2_ready = 0;

static void cb_sig(int signal)
{
        switch(signal) {
        case SIGUSR1:
                pause();
                break;
        case SIGUSR2:
                break;
        }
}

static void *thread_job(void *t_id)
{
        int i = 0;
        struct sigaction act;

        pthread_detach(pthread_self());
        sigemptyset(&act.sa_mask);
        act.sa_flags = 0;
        act.sa_handler = cb_sig;

        if (sigaction(SIGUSR1, &act, NULL) == -1)
                printf("unable to handle siguser1\n");
        if (sigaction(SIGUSR2, &act, NULL) == -1)
                printf("unable to handle siguser2\n");

        if (t_id == (void *)1)
            is_th1_ready = 1;
        if (t_id == (void *)2)
            is_th2_ready = 1;

        while (1) {
                printf("thread id: %p, counter: %d\n", t_id, i++);
                sleep(1);
        }

        return NULL;
}

int main()
{
        int terminate = 0;
        int user_input;
        pthread_t thread1, thread2;

        pthread_create(&thread1, NULL, thread_job, (void *)1);
        // Spawned thread2 just to make sure it isn't suspended/paused
        // when thread1 received SIGUSR1/SIGUSR2 signal
        pthread_create(&thread2, NULL, thread_job, (void *)2);

        while (!is_th1_ready && !is_th2_ready);

        while (!terminate) {
                // to test, I am sensing signals depending on input from STDIN
                printf("0: pause thread1, 1: resume thread1, -1: exit\n");
                scanf("%d", &user_input);

                switch(user_input) {
                case -1:
                        printf("terminating\n");
                        terminate = 1;
                        break;
                case 0:
                        printf("raising SIGUSR1 to thread1\n");
                        pthread_kill(thread1, SIGUSR1);
                        break;
                case 1:
                        printf("raising SIGUSR2 to thread1\n");
                        pthread_kill(thread1, SIGUSR2);
                        break;
                }
        }

        pthread_kill(thread1, SIGKILL);
        pthread_kill(thread2, SIGKILL);

        return 0;
}


texts: Attempting to efficiently compute the largest prime factor

texts:
I'm working on the third Euler problem and I've written a simple little function that returns the list of prime factors of a given number.

The number for which I have to get all the factors is over 6 billion, so building this huge freakin list of numbers in memory struck me as wonky.

I decided I'd build a factor function that generates output by the chunk and spits it out so that I can write it to a text file chunk by chunk.  A buffered_factor function:

Ok, I've decided that doing the 'buffered' thing isn't needful.  The computation is just going to take a while, and making my factor function a generator will keep my program light in memory.

I'm looking for best practices and practical advice about (what I think is describable as) buffering the output of a function.

Here's the prime sieve:

def is_prime(n):
    if n == 1:
        return False
    if n == 2:
        return True

    for i in range(2, int(math.ciel(math.sqrt(n))):
        if n % i:
            return False
        return True

And the factoratorizer:

def factor(num):
    """Get factors of given number.

    :param num: get us them there factors o this number here
    :type num: integer
    :param chunk_size: number of operations to work through before crapping out a list
    :rtype: list of factors
    :raises: ValueError on num < 1
    """
    if num < 1:
        raise ValueError('Given %s. Numbers >= 1, please' % num)

    for i in (n + 1 for n in xrange(num)):
        if num % i == 0:
            if is_prime(i):
                yield i

I'm trying to use it thusly:

import os
from factor import factor
TARGET = 600851475143
OUTFILE = 'factors.txt'

with open(OUTFILE, 'w') as f:
   for output in buffered_factor(TARGET):
       f.write(str(output))
       f.flush()

Nothing's being written to file, so obviously I'm doing something wrong.


texts: Binary search that gets ALL matching results

texts:
I am implementing a binary search to retrieve all matches of a specified value. Instead of a regular binary search that would just return the first match, I want to get that first match AND all matches above and below it in the set of objects.

For example, I have an array of objects that are sorted by the name property of each object in alphabetical order, and the first letter of that name property is what I use for comparison of the value provided.

The object would look like this (using fake values):

[
    { name: 'Apple',      id: 1, ...},
    { name: 'Apple',      id: 2, ...},
    { name: 'Basketball', id: 3, ...},
    { name: 'Basketball', id: 4, ...},
    { name: 'Cooking',    id: 5, ...},
    { name: 'Cooking',    id: 6, ...},
    { name: 'Dinosaurs',  id: 7, ...},
    ...
]

The list goes on all the way to Z, and each set of letters has probably 100+ results so there is a big set of objects here.

My code achieves what I want, but I feel as though I wrote way more code than I needed, but I've already refactored a few times and can't seem to shrink it much more.

A simple for loop could have achieved this for me and shrunk the code down to like 10 lines, but it would be essentially looping through a set of 2000+ items even when it only needs the first 100..

Here's the code (the main function is _binarySearchAll at the bottom):

getBrands(letter) {
    let brands = this.brands,
        _firstLetter = brand => {
            if ('hasOwnProperty' in brand && brand.hasOwnProperty('name')) {
                return brand.name.slice(0, 1).toLowerCase();
            }

            return false;
        },
        _traverse = (up, arr, i) => {
            let store = [],
                direction = up ? 1 : -1;

            while (_firstLetter(arr[i]) === letter) {
                store.push(arr[i]);

                i = i + direction;

                if (typeof arr[i] === 'undefined') {
                    break;
                }
            }

            return store;
        },
        _each = (arr, callback) => {
            let i = 0,
                len = arr.length - 1;

            while (++i < len) {
                callback(arr[i]);
            }
        },
        _compare = (brand, letter) => {
            let brandLetter = _firstLetter(brand);

            if (brandLetter === letter) {
                return 0;
            } else if (brandLetter < letter) {
                return 1;
            } else if (brandLetter > letter) {
                return -1;
            }
        },
        _all = (arr, i) => {
            let store = [],
                down = false,
                up = true;

            _each(_traverse(down, arr, i - 1), match => {
                store.push(match);
            });

            _each(_traverse(up, arr, i + 1), match => {
                store.push(match);
            });

            store.push(arr[i]);

            return store;
        },
        _binarySearchAll = (arr, val, compare) => {
            let start = 0,
                stop = arr.length - 1,
                mid = (start + stop) >> 1;

            while (start < stop) {
                let result = compare(arr[mid], val);

                if (result === 0) {
                    return _all(arr, mid);
                } else if (result > 0) {
                    start = mid + 1;
                } else if (result < 0) {
                    stop = mid - 1;
                }

                mid = (start + stop) >> 1;
            }
        };

    return _binarySearchAll(brands, letter, _compare);
}

Any help would be appreciated. If you want to test out the function, copy and paste it into Chrome Dev tools (or any other JS playground that supports ES6) and just past a similar array of objects as provided in my example. Try to have like 20 of each letter, then call getBrands('a') or some other letter, and you'll get an array of objects all starting with the first letter 'a'.


texts:
I have written a voting class in Laravel. It uses the voting sites API to check if the user has voted today. A user is only allowed to vote once every day.

All votes reset at midnight (i.e. 12:00 AM Chicago time) and I create a cookie to not bother wasting a curl response till then, so the cookie expires when a new vote is allowed.

The API returns response codes: 2 means the user hasn't voted for them in the past 24 hours, and 3 means they have voted for them in the past 24 hours. Just think of 2 as 0 and 3 as 1 in a false/true situation.

The reason I am asking this question is I don't think I am handling cookies the best way I can. Could anyone advise a better way to create them? I wasn't sure how to do it without a response, as Laravel says you have to send it with a response.

If the user needs to vote, they are sent to the voting page. For now I've just put a temp link as http://need2vote.com until I finish the class.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Auth;
use Redirect;
use Illuminate\Support\Facades\Route;
use Cookie;
use Illuminate\Http\Request;
use Config;

class VotingController extends Controller
{
    protected $pageUsername;
    protected $requestTimeout;
    protected $usingCloudflare;
    protected $apiUrl;

    public function __construct()
    {
        $this->pageUsername = Config::get('voting.username');
        $this->requestTimeout = Config::get('voting.timeout');
        $this->usingCloudflare = true;
        $this->apiUrl = Config::get('voting.api_url');
    }

    public function checkVote(Request $request)
    {
        if (Config::get('voting.enabled') == false) {
            return;
        }

        if ($this->isVoteCookieSet()) {
            return;
        }

        $urlRequest = $this->apiUrl . 'user=' . $this->pageUsername . '&ip=' . $request->ip();

        $result = $this->makeCurlRequest($urlRequest, $this->requestTimeout);

        if ($result == 3) {
            $this->redirectToVote();
        }
        else {
            $this->setVoteCookie();
        }
    }

    private function makeCurlRequest($url, $timeout)
    {
        if (function_exists('curl_version'))
        {
            $curl = curl_init();

            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);

            $requestData = curl_exec($curl);

            curl_close($curl);
        }
        else
        {
            $requestData = stream_context_create(array('http' => array('timeout' => $timeout)));
            return file_get_contents($url, 0, $requestData);
        }

        return $requestData;
    }

    public function redirectToVote() {
        header('Location: http://needtovote.com');
        exit();
    }

    private function setVoteCookie() {
        $rankingsResetTime = $this->getVoteResetTime();
        setcookie('vote_timestamp', $rankingsResetTime, $rankingsResetTime);
    }

    private function isVoteCookieSet() {
        if (isset($_COOKIE['voting_timestamp'])) {
            if ($_COOKIE['voting_timestamp'] == $this->getVoteResetTime()) {
                return true;
            }
            else{
                setcookie('voting_timestamp', '');
                return false;
            }
        }

        return false;
    }

    private function getVoteResetTime() {
        $serverDefaultTime = date_default_timezone_get();
        date_default_timezone_set('America/Chicago');

        $rankingsResetTime = mktime(0, 0, 0, date('n'), date('j') + 1);
        date_default_timezone_set($serverDefaultTime);

        return $rankingsResetTime;
    }
}


texts: Status dispatching of my redux-thunk async action (post request)

texts:
I'm trying to dispatch to my reducers the current status of my request.
So far I'm wondering how refined the status publishing of my thunk action.

I feel like my code is very verbose and I wonder if I can reduce the line quantity of it.

I inform my store that the request have reached some step by dispatching a corresponding status.

Here my code :

// set the status available for my code with function arguments planned
export const postFileStatus = [
    { type: 'POST_FILE',status: request},
    { type: 'POST_FILE', status: success, response: res },
    { type: 'POST_FILE', status: error, error: err }

]

// dispatch the thunk to the redux middleware
const thunkFile = () => dispatch => {

// inform the request have started by retrieve the "request" status on my file
{ dispatch(postFileStatus.find(step => step.status === "request"));
 Axios.post("http://localhost:7500/api/files", {
      "word": state.word,
      "data": state.base64Data,
      "id" : state.wordId
    },
    { "Content-Type":"multipart/form-data"}
  )

  // inform the request have succeed by retrieve the "success" status on my file
  .then(res =>  {dispatch(postFileStatus.find(step => step.status === "success"))
  console.log(res) })
  .catch(err => {

    // inform the request have failed by retrieve the "error" status on my file
    dispatch(postFileStatus.find(step => step.status === "error"))
    console.log(" error :", error.response)
});

}
}