27
Jun 15

#nodejs module for parsing key/value strings

Since my regexp test on parsing a string was a success, I created a #nodejs module for parsing strings. And the funny part, I scrapped the regexp 🙂 It now supports multiple keys and multiple values.

So you can do something like this:

var res = ps.parse('"foo bar" bar,"foo bar"=1 bar,"foo bar"=bar,"foo bar"');
res = [
   ['foo bar', undefined],
   ['bar', '1'],
   ['foo bar', '1'],
   ['bar', ['bar', 'foo bar']],
   ['foo bar', ['bar', 'foo bar']]
]

You can find the code at GitHub or as a npm module

24
Jun 15

#javascript and parsing param string

Got a little challenge parsing strings like:

Little brown="and yellow" fox=1 jumps over=lazy dog

I wanted to split it into an array with key/value pairs, so the result would be:

var res =
[ [ 'Little', undefined ],
  [ 'brown', 'and yellow' ],
  [ 'fox', '1' ],
  [ 'jumps', undefined ],
  [ 'over', 'lazy' ],
  [ 'dog', undefined ] ]

And here the regexp guy in me popped out and wanted to go for a short version. I ended up with

var text = 'Little brown="and yellow" fox=1 jumps over=lazy dog';

var res = text.match(/([^=\s]+="[^"]+")|\S+/g).map(function (p) {
    return p.match(/^([^=\s]*)(?:="?([^"]*)"?)?$/).splice(1, 2);
})

console.log(res);

The first one (/([^=\s]+="[^"]+")|\S+/g) splits the string into an array of param|param=value|param="value with space". The second one (/^([^=\s])(?:="?([^"])"?)?$/) split that array into separate arrays which contains key,value and remove the possible double quote on the value. Since match return all the splits, I splice out the values from the new array, 1 and 2.

And there you go.

You can find the last version at GitHub

PS: This rely on that array.map() exists, which it does in #nodejs

18
Jun 15

@nodejs and object sort speed

I was coding a scheduler and needed a sorted array of the schedules, so I started to investigate the speed of different sorting variants I could use.

I created a little program (https://gist.github.com/flogvit/c9df93ab37ca4dbd2d7f) to test 4 different variants.

For the test I created an array with 100000 objects { v: num }, where num is 100000 to 1. v is the value I want to sort on. Then I did the sort 10 times for each variant, and then again running this 5 times.

The first variant was standard compare (compare):

function compare(a, b) {
  if (a.v < b.v)
    return -1;
  if (a.v > b.v)
    return 1;
  return 0;
}

sortarray.sort(compare);

The second was a value only version doing the minus variant (compareValue):

function compareValue(a, b) {
  return a.v - b.v;
}

sortarray.sort(compareValue);

Third variant is using async (async):

   async.sortBy(sortarray, function (entry, callback) {
      callback(null, entry.v);
    }, function (err, results) {
      sortarray = results;
    });

And last variant is using underscore (underscore):

sortarray = _.sortBy(sortarray, 'v');

The result where smaller is better:

compare 36.00
compareValue 36.58
underscore 50.84
async 228.48

And the full output from each run:

$ node --expose-gc sort.js
Running compare for average 30.8 ms
Running compareValue for average 38 ms
Running async for average 227 ms
Running underscore for average 51.8 ms
Running compare for average 38.8 ms
Running compareValue for average 36.6 ms
Running async for average 230.7 ms
Running underscore for average 49.5 ms
Running compare for average 37.2 ms
Running compareValue for average 35.2 ms
Running async for average 234.7 ms
Running underscore for average 52.6 ms
Running compare for average 37.4 ms
Running compareValue for average 37.1 ms
Running async for average 224.4 ms
Running underscore for average 49.4 ms
Running compare for average 35.8 ms
Running compareValue for average 36 ms
Running async for average 225.6 ms
Running underscore for average 50.9 ms
22
May 15

Solution to Vietnamese pesky snake in #perl

I got a link to the Vietnamese Pesky Snake math problem from my wife. (http://m.db.no/2015/05/21/nyheter/utenriks/matematikk/oppgave/39292707/) And as a programmer, I couldn't really sit there and solve it with my bare hands. Ok, I admit it's fun to solve math problems, but this was very much looking like a problem with more than one solution, and I needed to know for sure 🙂

So I created a little program in perl to solve this. It's located at gist: https://gist.github.com/flogvit/ba6e984236f9b4e08c10

And for those wondering, yes, it had several solutions, actually 128 of them.

17
May 15

#gravatar, easy way of update your avatar

If you are, like me, having a user at many different sites, I suggest checking out www.gravatar.com. Create your avatar once, and use it everywhere. If you want to change it everywhere, change it one place. I've been using it for a long time, and I love it.

15
May 15

Reformat your source code with #IntelliJ

Writing correctly formatted code isn't easy to do all the time. So what do you do when you have eg written your json files like:

{ "test": "testing"
, "bla": "blabla"
, "yo": "yo to you"}

and want it to be:

{
  "test": "testing",
  "bla": "blabla",
  "yo": "yo to you"
}

You go into your file and press alt-win-l (alt-cmd-l on mac). Voila. It's formatted correctly.

But then you understand that you have a lot of files that needs to be reformatted. Well, select all you files in the project window (shift/alt) and when in the project window press alt-win-l. You probably get a popup asking for optimizing, rearranging etc. Just leave them and press OK. Voila. All files correctly formatted.

Now you can go and get your well earned coffee break.

13
May 15

IntelliJ and TODO

When you code, it's often you come up with an idea or shortcoming of your function. It's easy to code on and think you can remember it later. You don't, trust me.

So what do you do when you're in an editor like IntelliJ? Well, you add a TODO: entry.


// TODO: This should probably be shortened
// TODO: Perhaps add yield on each result to support generators?
// TODO: Add callback?
var fibonacci = function(pos) {
    if (pos===0) return 0;
    if (pos===1) return 1;
    var result = 1;
    var last = 0;
    for(var i=2;i<=pos;i++) {
        var newLast = result;
        result = result+last;
        last = newLast;
    }
    return result;
}

console.log(fibonacci(10));

We came up with three ideas when writing that function. Then you switch to another file, do you stuff. Before you know it, it's gone two weeks since you added the TODO blocks. So what do you do in IntelliJ? You press win-6 (Windows) or cmd-6 (Mac) and get your TODO-list up and running. Choose Project (or File or Scope), and find all your TODOs. And if you wonder how to remove the list again, just press the same win-6, cmd-6

7
May 15

Node.js and random port

Sometimes you need to open a random port on your node server. You can of course try a random one to see if it fails, but a npm module makes this easy:

npm install portfinder
var pf = require('portfinder');
var http = require('http');

// If you want to change the first port to check
pf.basePort = 9000; // default is 8000

pf.getPort(function(err, port) {
  if (err) return; // handle error
  http.createServer().listen(port);
  console.log("I'm now listening on port "+port);
});

More information about the module is found at npmjs.com

12
Nov 14

Helping the world for free in the winter with #Folding@Home

When it gets colder, we use a lot of money to heat the house. Imagine if this money could be used to solve the Alzheimer's disease, without it costing you anything more?

Impossible, you might say! Nope. It's as simple as going to http://folding.stanford.edu, press "Start Folding" and voila you will help the world to find a solution to the diseases as Alzheimer, Huntington, Parkinson etc.

What's going on?

  1. You will use the computer to solve the diseases
  2. Your computer gets hotter of working, that heats your house
  3. You turn down the heat in your house, because your machine is warming instead
  4. Power costs are exactly equal, because the heat is heat, no matter what make it
  5. The world wins. Maybe even you one day, because we found the solution to a disease you got

So, help the world for free during the winter months! It does not cost you many minutes to go to http://folding.stanford.edu. But remember, when summer comes and you start cooling the house, turn off folding also

Right now in my computer to help solve: "This project explores the folding and dynamics of E.coli RNase H."

If you want to be part of my team, use teamnr: 227348. But feel free to be teamless. The important part is that you contribute.

Btw, there are more projects like this you can use to generate your heat. Another good one is http://boinc.berkeley.edu/

Tags:
10
Nov 14

Google Drive and many disks

So, you are the new happy owner of Google Apps Unlimited, and can store tons of files in your Google Drive. Then you have several computers you want to sync between. To make this easy, let's say you have 2 computers, where both have 2x1 TB disk. But you do different stuff on the different computers, and you want to make the most of your Google Drive, so you still have the files if you computer(s) crashing. So how do you do this?

Well, your first problem is that Google Drive reside on only one disk, usually under c:\Users\<username>\Google Drive. How do you make use of your brand new shiny 1TB disk which you have mounted on D:, and use the space on C: as well?

The answer to this is first to sort your stuff by different directories. So let's say you have some videos you've made. What you do is to make a directory D:\Videos. There you put all your shiny videos. You can even use up all your 1 TB space for those videos. Then you start up a command prompt as administrator [win-X Command Prompt (Admin)], and you type:


mklink /D "C:\Users\<youruser>\Google Drive\Videos" "D:\Videos"

And voila, you have a symlink in your google drive to the D:\Videos, which is now available as Google Drive\Videos. Give it a minute before you see Google Drive start to sync it.

But you don't want to have the videos on your other computer? Easy, just turn off the directory in your Google Drive->Preferences->Sync options.