## Sunday, February 12, 2017

### Minimizing risk trough Un-correlation

The number of possible major/minor currency is large and trading currencies that are correlated logically increases risk. My Google search for least correlated Forex pairs came up empty so I decided to run the analysis myself.

Using information from this list on Oanda I created a JS script that would loop through the table entires and return the least correlated pairs based on the 1 year value. To my surprise I had to permit high correlations of >0.80 for the major currencies, and >0.95 for the major and minor currencies together to get values returned.

#### Major Currencies

["AUD/USD", "EUR/AUD", "EUR/CHF", "EUR/GBP", "EUR/USD", "NZD/USD"]

#### Major + Minor Currencies

Feel free to comment or follow me @danielsokolows.

#### Console JS Snippet

document.querySelector('#Table_button').click(); // swithc to table mode which shows numbers
var aPairElementList = Array.prototype.slice.call(document.querySelector('#Table').querySelectorAll('.currency_pair'),0);
var aReturnedPairs = aPairElementList.map(function(oElement) {return oElement.innerText}); // whatever remains in this array is our uncorrelated pairs
var aPairsCompared = [];
// for each pair select it
for (var i = 0; i < aPairElementList.length; i++) {
aPairElementList[i].querySelector('button').click();
// NEED TO RESCAN THE aPairElementList as the nodes have been destroyed and re-created so our aPairElementList is outdated
aPairElementList = Array.prototype.slice.call(document.querySelector('#Table').querySelectorAll('.currency_pair'),0);

// no loop over the entire list and prune any correlated pairs from our aReturnedPairs
for (var j = 0; j < aPairElementList.length; j++) {
// go to the nth sibling and check for corelation, and remove from our returned list if correlated positively
// 7th  next sibling is 1 Year
if (aPairElementList[i].innerText != aPairElementList[j].innerText && aPairsCompared.indexOf(aPairElementList[i].innerText + aPairElementList[j].innerText) == -1) {
var nCorelationValue = Number(aPairElementList[j].nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerText);
//console.assert(nCorelationValue != NaN, 'Must never have failed to parse correlation');
if (nCorelationValue == NaN) {throw new Exception('Must never have failed to parse correlation')};
if (nCorelationValue >= 0.95) {
console.log('Removing because \'' + aPairElementList[i].innerText + '\' correlation with \'' + aPairElementList[j].innerText + '\' is ' + nCorelationValue);
aReturnedPairs.splice(aReturnedPairs.indexOf(aPairElementList[j].innerText), 1);
// store the reverse of the pair so we don't don't compare it
aPairsCompared.push(aPairElementList[j].innerText + aPairElementList[i].innerText);
}
}
}
}
console.log(aReturnedPairs)

## Startup init script for the Distributed WPA PSK strength auditor python script

Turning the `help_crack.py` utility into a system daemon can be achieved by utilizing the `screen` utility, below is my first attempt at it - feel free to comment with improvements or questions.

#!/bin/sh
### BEGIN INIT INFO
# Provides:
# Required-Start:    \$remote_fs \$syslog
# Required-Stop:     \$remote_fs \$syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

# Symbolic link this file into your `/etc/init.d`, then run `rcconf` and select the script to start, note the file name must be alphanumeric only
# example: `root@sh1:/etc/init.d# ln -s /usr/local/wpa-sec.stanev.org-help_crack.py/help_crack.py.init.sh help_crack`

dir="/usr/local/wpa-sec.stanev.org-help_crack.py"
cmd="screen -d -m -S help_crack.py ./help_crack.py"
user=""
#!/bin/sh
### BEGIN INIT INFO
# Provides:
# Required-Start:    \$remote_fs \$syslog
# Required-Stop:     \$remote_fs \$syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

# Symbolic link this file into your `/etc/init.d`, then run `rcconf` and select the script to start, note the file name must be alphanumeric only
# example: `root@sh1:/etc/init.d# ln -s /usr/local/wpa-sec.stanev.org-help_crack.py/help_crack.py.init.sh help_crack`

dir="/usr/local/wpa-sec.stanev.org-help_crack.py"
cmd="screen -d -m -S help_crack.py ./help_crack.py"
user=""

name=`basename \$0`
pid_file="/var/run/\$name.pid"
stdout_log="/var/log/\$name.log"
stderr_log="/var/log/\$name.err"

get_pid() {
cat "\$pid_file"
}

is_running() {
[ -f "\$pid_file" ] && ps `get_pid` > /dev/null 2>&1
}

case "\$1" in
start)
if is_running; then
else
echo "Starting \$name"
cd "\$dir"
if [ -z "\$user" ]; then
#sudo \$cmd >> "\$stdout_log" 2>> "\$stderr_log" & # start it in the background which we don't want so that we can get the right PID
sudo \$cmd >> "\$stdout_log" 2>> "\$stderr_log"
else
# sudo -u "\$user" \$cmd >> "\$stdout_log" 2>> "\$stderr_log" & # start it in the background which we don't want so that we can get the right PID
sudo -u "\$user" \$cmd >> "\$stdout_log" 2>> "\$stderr_log"
fi
#echo \$! > "\$pid_file"
# IMPRV: make the session name a variable or extract it from the `cmd`
screen -ls | grep -Po '(?<=\t)(\d+)(?=.help_crack.py)' > "\$pid_file"
if ! is_running; then
echo "Unable to start, see \$stdout_log and \$stderr_log"
exit 1
fi

echo "Started, you can reconnect by typing \`screen -r `get_pid`\`"

fi
;;
stop)
if is_running; then
echo -n "Stopping \$name.."
# killin Screen PID is not enough, so we gather all children and kill them too
pids_to_kill=""
current_pid=`get_pid`
#echo "current_pid=\$current_pid"
while [ -n "\$current_pid" ] # if not empty execute loop
do
pids_to_kill="\$current_pid \$pids_to_kill"
current_pid=`pgrep -P \$current_pid`
done
#echo \$pids_to_kill
kill \$pids_to_kill
for i in {1..10}
do
if ! is_running; then
break
fi

echo -n "."
sleep 1
done
echo

if is_running; then
echo "Not stopped; may still be shutting down or shutdown may have failed"
exit 1
else
echo "Stopped"
if [ -f "\$pid_file" ]; then
rm "\$pid_file"
fi
fi
else
echo "Not running"
fi
;;
restart)
\$0 stop
if is_running; then
echo "Unable to stop, will not attempt to start"
exit 1
fi
\$0 start
;;
status)
if is_running; then
echo "Running, you can reconnect by typing \`screen -r `get_pid`\`"
else
echo "Stopped"
exit 1
fi
;;
*)
echo "Usage: \$0 {start|stop|restart|status}"
exit 1
;;
esac

exit 0

## Thursday, December 8, 2016

### Lightning Out off Platform Example

Due to the limited documentation out there for the BETA Lightning Out functionality I am posting my code for others to benefit.

Please note that after extensive research I have come to the conclusion that off platform functionality is broken, but executing the code from within a naked VF page should work. The issue is that the bootstrapping process does not adjust the URLs for the dynamically loaded scripts and styles sheets - the JS assumes it is still run from within a SF org domain. A case with SF has been filled but if I am incorrect on my conclusion please comment.

Even if one patches the script/style URLs loading at runtime further errors manifest from withing aura_prod.js

## Salesforce's 'Lighting Out' Example

Prior to using the below code ensure you have wrapped your lighting component into an App, setup a connected App, and CORS whitelisted your domain - afterwards copy and paste the below into your HTML file to be served from a server.

...
<div id='lightning'></div>
<script src="https://<REMOVED>.lightning.force.com/lightning/lightning.out.js"></script>
<script>
sAccessToken = location.hash.match(/access_token=([^&]*)/) ? location.hash.match(/access_token=([^d]*)/)[1] : null;
sInstanceURL = location.hash.match(/instance_url=([^&]*)/) ? decodeURIComponent(location.hash.match(/instance_url=([^&]*)/)[1]) : null;
if (sAccessToken ==  null) {
}
//debugger;
\$Lightning.use(
,function() {
\$Lightning.createComponent(
,{
<MORE ATTRIBUTES HERE>
}
,"lightning"
,function(cmp) {
//do some stuff
debugger
}
);
}
,sInstanceURL
,sAccessToken
);
</script>
......

## Unable to delete folder due to 'path too long' error

Windows dinosaur 256(?) path limitation weirdness prevented me from deleting a backup recovery folder, the solution to that is to use a utility called Unlocker - it also allows deletion/moving of locked files. If you found this useful feel free to follow me on twitter @danielsokolows or comment, also do donate the author of the program.

## Protocol error occurred. Error was returned from the destination server.

The Softether server by default to run on port 443, if you server also hosts normal https then 443 is already taken and so Softether can't bind to it.

When you run `vpncmd` it attempts to connect, find an active port, but of course fails with 'Protocol error occurred. Error was returned from the destination server.' because it's not actually connecting to the vpn server.

By default Softether also listens on 992, 1194, and 5555 so the sollution is to modify specify `localhost:5555` when executing the `vpncmnd`. If this has helped you feel free to comment or follow me on twitter @danielsokolows.

## Save error: A problem was encountered while invoking the subscription method

If in the Salesforce 'Developer Console' you get the error mentioned in the subject or if you in Eclipse Force.com IDE you get:

Save error: A problem was encountered while invoking the subscription method: No TOKENS named markup://c:defaultTokens foundproblem Save error: COMPONENT's markup cannot be empty. If you are trying to delete the Lightning definition bundle, directly delete the bundle instead. Save error: QualifiedName is required for descriptors

Then ensure that you don't have an empty `controller=""` attribute, this took a me a little while to notice so for the prosperity of others and my own memory forming benefit I am posting this. If this has helped you feel free to follow or thanks comment.

## Fix for: `Command '/usr/bin/python src/build/linux/sysroot_scripts/install-sysroot.py --running-as-hook' returned non-zero exit status 1 in /root/chromium-src`.

As part of some R&D for a JS framework I have been thinking of for a while I needed to do some Chromium hacking, problem is I hit a wall just simply attempting to check out the source code. This was on a fresh Debian VM machine following the official checkout docs.

root@lh1:~/chromium-src# fetch --no-history chromium
Running: gclient root
Running: gclient config --spec 'solutions = [
{
"managed": False,
"name": "src",
"deps_file": ".DEPS.git",
"custom_deps": {},
},
]
'
Running: gclient sync --no-history
Error: Command '/usr/bin/python src/build/linux/sysroot_scripts/install-sysroot.py --running-as-hook' returned non-zero exit status 1 in /root/chromium-src
Traceback (most recent call last):
File "/root/depot_tools/fetch.py", line 353, in
sys.exit(main())
File "/root/depot_tools/fetch.py", line 348, in main
return run(options, spec, root)
File "/root/depot_tools/fetch.py", line 342, in run
return checkout.init()
File "/root/depot_tools/fetch.py", line 142, in init
self.run_gclient(*sync_cmd)
File "/root/depot_tools/fetch.py", line 76, in run_gclient
return self.run(cmd_prefix + cmd, **kwargs)
File "/root/depot_tools/fetch.py", line 66, in run
return subprocess.check_output(cmd, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '('gclient', 'sync', '--no-history')' returned non-zero exit status 2

The solution is to:

• `export PATH=\$PATH:/root/depot_tools`, this one is important or you will get an error when script is processing 'Downloading /root/chromium-src/src/third_party/binutils/Linux_x64/binutils.tar.bz2'.
• gclient sync --nohooks --no-history chromium which will fetch the code without running hooks code; more info here.
• Then running `aptitude install sudo` if not already installed
• `./src/build/install-build-deps.sh --unsupported --no-syms --no-arm --no-chromeos-fonts --no-nacl`
• But that will error out with various 'E: Unable to locate package ...' on a Debian system, copy the echoed command and remove the packages from the list manually or use Bash's for loop like so:
• for i in apache2-bin bison cdbs curl devscripts dpkg-dev elfutils fakeroot flex fonts-indic fonts-thai-tlwg g++ git-core git-svn gperf language-pack-da language-pack-fr language-pack-he language-pack-zh-hant lib32gcc1 lib32stdc++6 libapache2-mod-php5 libasound2 libasound2-dev libatk1.0-0 libav-tools libbluetooth-dev libbrlapi0.6 libbrlapi-dev libbz2-1.0 libbz2-dev libc6 libc6-i386 libcairo2 libcairo2-dev libcap2 libcap-dev libcups2 libcups2-dev libcurl4-gnutls-dev libdrm-dev libelf-dev libexpat1 libffi6 libffi-dev libfontconfig1 libfreetype6 libgbm-dev libgconf2-dev libgl1-mesa-dev libgles2-mesa-dev libglib2.0-0 libglib2.0-dev libglu1-mesa-dev libgnome-keyring0 libgnome-keyring-dev libgtk2.0-0 libgtk2.0-dev libjpeg-dev libkrb5-dev libnspr4 libnspr4-dev libnss3 libnss3-dev libpam0g libpam0g-dev libpango1.0-0 libpci3 libpci-dev libpcre3 libpixman-1-0 libpng12-0 libpulse0 libpulse-dev libsctp-dev libspeechd2 libspeechd-dev libsqlite3-0 libsqlite3-dev libssl-dev libstdc++6 libudev1 libudev-dev libwww-perl libx11-6 libxau6 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxdmcp6 libxext6 libxfixes3 libxi6 libxinerama1 libxkbcommon-dev libxrandr2 libxrender1 libxslt1-dev libxss-dev libxt-dev libxtst6 libxtst-dev mesa-common-dev msttcorefonts openbox patch perl php5-cgi pkg-config python python-cherrypy3 python-crypto python-dev python-numpy python-opencv python-openssl python-psutil python-yaml realpath rpm ruby subversion ttf-dejavu-core ttf-kochi-gothic ttf-kochi-mincho wdiff xcompmgr zip zlib1g; do sudo apt-get install -y \$i; done

• Then finally run `gclient runhooks`.

## "Save error: Package Visibility: Type is not visible: "

If all other checks fail and you are actually able to reference `` than in my experience this error is caused due to the fact that the class you are working on has been updated on the server.

Solution is to disable tooling api support in project properties. If this has helped you please comment or follow me .

## Control your Phone with Windows keyboard and mouse

While at work, I have been on a search to control my phone through the computers keyboard and mouse. Today I have found Across software which is a possible solution, but unfortunatly Lumia 640 LTE lacks the proper bluetooth keyboard profile.

## Why 'Systems Hungarian' makes sense.

As a developer, if you prefix the variable type you are clearly in the minority - I for one am a propoment of Systems Hungarian and belong to that group myself.

The merrits become apparent when reading other people's code, or when you look at your own code months/years after. Properly naming variables is hard, the type is not always obvious and left to individual interpenetration. Prefixing completely removes any uncertainty, it immediately reveals the type of the variable, and the developer reading the code does not have to go through the mental friction of inferring from the name or from how it is being used in the context or traversing back to where the variable was defined.

For weakly typed languages like JS/Python it has the huge additional benefit of making debugging that much easier, when one treats the prefix as the intent of what should be the value stored it reveals possible issues immediately when steping through code.

When the end goal is the benefit to 'other' developers reading your code Systems Hungarian makes perfect sense. Yes, it does mean some time getting used to it, but it's no different then any other coding pattern you habituate yourself to.

We end up gravitating towards the familiar and find other patterns ugly which in my opinion is the root cause of the negativity against type prefixing.

## JavaScript and Apex variable prefixing

Variables are prefixed using letters from primitive types, the base 'Object', or `f` for functions. An exception are arrays that are prefixed with `a` even though the base type is an Object - this keeps the rule list small and as follows:

// Note: you can use `Object.prototype.toString.call(variable)` to get the primitive type of it.

var nYear; // for Numbers
var bGender; // for Booleans
var sName; // strings
var oTable; // objects
var aScores; // arrays
var fAge = function () {}; //gets age of the person

I am was happy to find at one other person thinks the same: what-do-you-mean-by-the-initial-letter-on-javascript-variables-functions.

Apex variable prefixing

Blob blBlobieFoo;
Boolean bBooleano;
Datetime dtStartDateAndTime;
Decimal dAgeOfUniverise;
Double dbBiggerNumber;
Integer iUserAge;
Long lTurlleAge;
Object oContentList;
Object oContentMap;
String sFirstName;
Time tAlarm;

What are you thoughts on this?

## Code coverage highlighting lines missing from class editor

It appears that in latest Winter 2016 upgrade a bug was introduced where code coverage line highlights are missing from the Salesforce Developer Console

You can get them back by selecting the 'Test > Always Run Asynchronously' checkbox and re-running your test.

## Saturday, January 2, 2016

### LightScribe Template Labeler installation "Operating System Inadequate" Issue

Unfortunately 'LightScribe Template Labeler' installation will not work on Windows 8 and Windows 10 machines as the install simply will error out with 'Operating System Inadequate'. Trying to install using compatibility mode did not help.

### Installing LightScribe Template Labeler Workaround

However if you simply copy the installed folder from an older machine like Windows 7 into your `C:\\Program Files (x86)\LightScribe Template Labeler`, create a shortcut, then the software will still happily work, see: http://answers.microsoft.com/en-us/windows/forum/windows8_1-performance/lightscribe-templatesimple-labeler-the-system-is/c2ebee28-bfb5-4aef-beb3-a43329561da8?db=5&auth=1

So you can install Windows 7 machine in a virtual machine, install 'LightScribe Template Labeler', and then copy the resulting folder to your Windows 8 or Windows 10 machine. For my own convenience to avoid this process in the future I am keeping a zipped version of the folder that you can download it here: LightScribe Template Labeler for Windows 10 (please comment if the link is dead).

Feel free to comment or follow me .

## Running Fallout 4 at 50FPS on a low end graphic card

My self built development rig (currently pumping out OrchestraCMS/Salesforce sites) does not have a discrete 3d video card, but instead it has a low end Radeon HD 6530D built-in as part of the AMD A6-3650 CPU. Clearly it is a system not designed to handle latest games, but once in a while I like to indulge and so this time I tried playing Fallout 4...

Even at all the lowest resolution and settings I was only able to squeeze about 16 frames per second (FPS) --- I rather watch paint dry.

Overclocking the rig front side bus (FSB) 35% from 100MHz to 135MHz, that is CPU from 2600MHz to 3150MHz and DDR3 memory from 1333MHz to 1799MhZ (the F1A75-V PRO motherboard is fantastic for overclockability, just ensure to run the latest BIOS which allowed me to push it this far) things improved by 8 frames to 24FPS. Better but that's when there isn't anything existing happening on the screen so still unplayable.

### Changing resolution in `Fallout4Prefs.ini`

I almost gave up but then decided to take a look inside the `Fallout4Prefs.ini` file and noticed the screen resolution mode settings `iSize H` and `iSize W`. And so I changed them to the lowest resolution my card supported (see 'Display Settings > Display adapter properties > List All Modes'): 640px by 480px and behold the glorious FPS now!

So even though the frame-rate is very fine indeed the resolution sucks, maybe I'll just pretend this is the Pip-Boy experience mode - maybe I should get an old CRT monitor too :). Feel free to comment or .

## Fast Salesforce `staticresrouces` Development Locally

The problem with front end development in the cloud is that it is painfully slow! Unfortunately this is the reality of the cloud nature of SF and it will remain so - at least until there will be ability to spin up local SF development servers.

It takes about 30 seconds or more to save on a busy org. That is mainly because of the typical save cycle, 'change', 'zip', 'save to server', and then 'refresh in browser':

• doing this many times a day adds up to a substantial time lost
• loss of focus/concentration - while you wait
• ‘clobbering of static resources’ when working in a team
• pure maddening in tight timelines

### Current Solutions

##### Make changes in browser, ex. Chrome
• Great for CSS
• Limited for JS (can’t re-run `onload` event)
• Cumbersome for HTML
• Can’t use your favorite (Eclipse IDE) editor
##### Develop files locally
• Ok for initial design mockups
• Impractical once code starts living in SF
• ##### Javascript / CSS injection
• Browser security issues as file must live on server
• Ok for CSS, problematic for JS
• Order issues, `onload` event, etc.
• Can’t do HTML

• ### The Solution: Have Charles or Fiddler serve it!

The idea is to use an intermediate proxy to highjack our requests and inject files from a local file system. There are two mainstream popular programs to accomplish this. An old and tried Fiddler for Windows machines and Charles Mac

Once you setup Charles or Fiddler you can map any server response to local files. In the case of CSS/JS this allows you to edit these locally and immediately be able to preview your changes in the browser. Since the common design pattern is to use folder for static resoruces you can just map the entire `resource-bundles` folder instead of individual files:

• In Charels the 'Path' matching pattern should be of format `/resource//*` mapped to local path to the bundle in `resource-bundles` folder (a Maven's Mate convention that Eclipsers should follow).
• For Fiddler the 'AutoResponder' rule should be `REGEX:.+?//.visual.force.com/resource/.+?//(.+)\$` mapped to `\resource-bundles\\\$2`.

If you found this useful please feel free to comment or follow me .

## Exim configuration error in line 438 of /var/lib/exim4/config.autogenerated.tmp: error in ACL: unknown ACL condition/modifier in "spam = debian-spamd:true"

root@sh1:/etc/exim4# dpkg-reconfigure exim4-config
2015-10-25 14:09:40 Exim configuration error in line 438 of /var/lib/exim4/config.autogenerated.tmp:
error in ACL: unknown ACL condition/modifier in "spam = debian-spamd:true"
Invalid new configfile /var/lib/exim4/config.autogenerated.tmp, not installing
/var/lib/exim4/config.autogenerated.tmp to /var/lib/exim4/config.autogenerated

The one stumped be for a bit but the solution - at least on a Debian based system - is to ensure you have installed 'exim4-daemon-heavy` instead of the light packages, aptitude install exim4-daemon-heavy.

If this has helped comment of follow me .

## Simple Linux Performance Script

When deploying new virtual machines with different provides I like to do basic performance tests using built in utilities like `dd` and `bc`. I had a little script linux-benchmark.sh which I have now cleaned up and making it public. When run it will do basic test for HD, Internet and CPU and save it as a timestamped text file.

### Sample output:

root@sh1:~# ./linux-benchmark.sh
Please be patient, this might take a minute or so.

Hostname:             sh1
IP(s):                45.55.218.113
CPU model:            Intel(R) Xeon(R) CPU E5-2630L v2 @ 2.40GHz
Number of cores:      1
CPU frequency:        2399.998 MHz
System uptime:        60 days, 2:17,
Total amount of ram:  500 MB
Total amount of swap: 2929 MB
Calc PI to 5000:      0m31.818s
I/O (conv=fdatasync): 528MB/s

### The `linux-benchmark.sh` script

#!/bin/bash
# Author: Daniel Sokolowski
# source: https://bitbucket.org/snippets/danielsokolowski/G5oeA
# inspired by http://www.commandlinefu.com/commands/view/229/quick-integer-cpu-benchmark, http://serverfault.com/questions/372020/what-are-the-best-possible-ways-to-benchmark-ram-no-ecc-under-linux-arm

echo "Please be patient, this might take a minute or so."
hostname=\$(cat /etc/hostname)
cname=\$(cat /proc/cpuinfo|grep name|head -1|awk '{ \$1=\$2=\$3=""; print }' | xargs)  # xargs left/left trims the string
cores=\$(cat /proc/cpuinfo|grep MHz|wc -l | xargs)
freq=\$(cat /proc/cpuinfo|grep MHz|head -1|awk '{ print \$4 }')
cpuspeed=\$( (time echo "scale=5000; a(1)*4" | bc -l > /dev/null) 2>&1 | head --lines=2 | tail --lines=1 | awk -F ' ' '{print \$2}')
tram=\$(free -m | awk 'NR==2'|awk '{ print \$2 }')
swap=\$(free -m | awk 'NR==4'| awk '{ print \$2 }')
up=\$(uptime|awk '{ \$1=\$2=\$(NF-6)=\$(NF-5)=\$(NF-4)=\$(NF-3)=\$(NF-2)=\$(NF-1)=\$NF=""; print }' | xargs) # xargs left/left trims the string

cache=\$((wget -O /dev/null http://cachefly.cachefly.net/100mb.test) 2>&1 | tail -2 | head -1 | awk '{print \$3 \$4 }' | sed 's/^(\(.*\))\$/\1/' )
io=\$( (dd if=/dev/zero of=test_\$\$ bs=1M count=256 conv=fdatasync &&rm -f test_\$\$) 2>&1 | tail -1| awk '{ print \$(NF-1) \$NF }')
io2=\$( (dd if=/dev/zero of=test_\$\$ bs=1M count=256 oflag=dsync &&rm -f test_\$\$) 2>&1 | tail -1| awk '{ print \$(NF-1) \$NF }')

# memory test
tempDir=`mktemp -d -t linux-benchmark-XXX`
mount -t tmpfs \$tempDir \$tempDir
#io3=\$( (dd if=/dev/zero of=\$tempDir/test_\$\$ bs=1M count=256 conv=fdatasync &&rm -f test_\$\$) 2>&1 | tail -1| awk '{ print \$(NF-1) \$NF }')
io3=\$( (dd if=/dev/zero of=\$tempDir/test_\$\$ bs=1M conv=fdatasync &&rm -f test_\$\$) 2>&1 | tail -1| awk '{ print \$(NF-1) \$NF }')
umount -f \$tempDir
mount -t tmpfs \$tempDir \$tempDir
#io4=\$( (dd if=/dev/zero of=\$tempDir/test_\$\$ bs=1M count=256 oflag=dsync &&rm -f test_\$\$) 2>&1 | tail -1| awk '{ print \$(NF-1) \$NF }')
io4=\$( (dd if=/dev/zero of=\$tempDir/test_\$\$ bs=1M oflag=dsync &&rm -f test_\$\$) 2>&1 | tail -1| awk '{ print \$(NF-1) \$NF }')
umount -f \$tempDir

outputfilename=\$(basename \$0-run-`date "+%Y.%m.%d-%H.%M.%S".txt`)
echo "Hostname:             \$hostname" >> \$outputfilename
echo "IP(s):                \$ips"  >> \$outputfilename
echo "CPU model:            \$cname" >> \$outputfilename
echo "Number of cores:      \$cores" >> \$outputfilename
echo "CPU frequency:        \$freq MHz" >> \$outputfilename
echo "System uptime:        \$up" >> \$outputfilename
echo "Total amount of ram:  \$tram MB" >> \$outputfilename
echo "Total amount of swap: \$swap MB" >> \$outputfilename
echo "Calc PI to 5000:      \$cpuspeed"  >> \$outputfilename
echo "HDD I/O (conv=fdatasync): \$io" >> \$outputfilename
echo "HDD I/O (oflad=dsync):    \$io2" >> \$outputfilename
echo "Memory I/O (conv=fdatasync): \$io3" >> \$outputfilename
echo "Memory I/O (oflad=dsync):    \$io4" >> \$outputfilename

echo ""
cat \$outputfilename
echo ""

If you found this useful comment or follow me .

## Work around to key tones not working in Linphone when connected through Freeswtich

If you find that after dialing into any IVR your key presses are not registering, and you are connecting to a Freeswitch voip gateway it is likely due to this Bug: Telephone-event codec clock-rate mismatch (leads to DTMF issue); go 'Options > Settings > Codec' and move the 8000Hz codes up.

A temporary work around is to change your codec priorities in Linphone to use one of the lower quality 8000Hz ones first.

Comment or follow me if this has helped you.

## Creating a 'NS' record

It's NOT possible - try setting u BIND instead or contacting the author to add support for it; I am creating this entry so that it would save hours of searching for others.
The basic setup that should work is to point your domain dns servers to to 'ns1.yourdomain.com` where ns1 resolves to your servers IP, however because dnsmasq can not answer with a NS record and the process fails - that is my understanding based on my readings

## Windows Insider won't updated

So my 10162 insider windows edition is now expired, keeps restarting, telling me it will stop working and yet Windows Update says there is no updates.

Search on the Internet found many with similar issues but none of the solutions worked, however the below did the trick for me

• Mount the file by right clicking
• Enter one of the following Product Keys - Windows 10 build 10240 keys:
• Windows 10 Home build 10240 - TX9XD-98N7V-6WMQ6-BX7FG-H8Q99
• Windows 10 Pro build 10240 - VK7JG-NPHTM-C97JM-9MPGT-3V66T
• Windows 10 Enterprise build 10240 - NPPR9-FWDCX-D2C8J-H872K-2YT43
• When the installation finishes ensure you are still part of the insider builds

If this has helped you drop me a comment or follow me on twitter @danielsokolows.

## Sorting the results of 'View/Add Dependencies'

When you have to shift through over 100+ entries it would help if SF's interface allowed for sorting. The missing functionality can be achieved by running the below JS, which can be invoked using a handy bookmarklet. Create one as follows:
• Name it `SF Make `<table class='list' ...>` Sortable`
• In the url paste the blelow JS snippet
javascript:/* `sortTable` from https://gist.github.com/danielsokolowski/994d47baa95ef81fd8fc */ function TableSort(a){this.tbl=a;this.lastSortedTh=null;if(this.tbl&&"TABLE"==this.tbl.nodeName){a=this.tbl.tHead.rows[0].cells;for(var b=0;a[b];b++)a[b].className.match(/asc|dsc/)&&(this.lastSortedTh=a[b]);this.makeSortable()}}TableSort.prototype.makeSortable=function(){for(var a=this.tbl.tHead.rows[0].cells,b=0;a[b];b++){a[b].cIdx=b;var c=document.createElement("a");c.href="#";c.innerHTML=a[b].innerHTML;c.onclick=function(a){return function(){a.sortCol(this);return!1}}(this);a[b].innerHTML="";a[b].appendChild(c)}};TableSort.prototype.sortCol=function(a){var b=this.tbl.rows,c=[],f=[],g=0,d=0;a=a.parentNode;for(var l=a.cIdx,e=1;b[e];e++){var h=b[e].cells[l],h=h.textContent?h.textContent:h.innerText,k=h.replace(/(\\$|\,|\s)/g,"");parseFloat(k)==k?f[d++]={value:Number(k),row:b[e]}:c[g++]={value:h,row:b[e]}}b=[];a.className.match("asc")?(e=bubbleSort(c,-1),c=bubbleSort(f,-1),a.className=a.className.replace(/asc/,"dsc")):(e=bubbleSort(f,1),c=bubbleSort(c,1),a.className.match("dsc")?a.className=a.className.replace(/dsc/,"asc"):a.className+="asc");this.lastSortedTh&&a!=this.lastSortedTh&&(this.lastSortedTh.className=this.lastSortedTh.className.replace(/dsc|asc/g,""));this.lastSortedTh=a;b=e.concat(c);c=this.tbl.tBodies[0];for(e=0;b[e];e++)c.appendChild(b[e].row)};function bubbleSort(a,b){var c,f;1===b?(c=0,f=a.length):-1===b&&(c=a.length-1,f=-1);for(var g=!0;g;)for(var g=!1,d=c;d!=f;d+=b)a[d+b]&&a[d].value>a[d+b].value&&(g=a[d],a[d]=a[d+b],a[d+b]=g,g=!0);return a};new TableSort(document.querySelector('table.list'));

## Is your compass configuration correct?.

Unbelievable, compass chokes on directories with spaces (I think, and at least on a Windows machine).

I have resolved it by creating a junction from the repository into a folder without spaces - see this awesome utility: http://schinagl.priv.at/nt/hardlinkshellext/linkshellextension.html

And food for thought: consider if SASS is needed, do you want to debug your SASS or CSS?

## Error: inlining failed in call to always_inline '_mm_loadu_ps'

The error happens when trying to compile the 'lame' needed by the 'mod_shout' module. From Google it appears to only happen on 32bit architecture.

The solution is to search for `xmmintrin.h` and remove the line from file `./lib/lame-3.98.4/configure`. The final code block should look as follows:

...
errno.h \
fcntl.h \
sys/soundcard.h \
sys/time.h \
unistd.h \
linux/soundcard.h
do :
...

## Tuesday, May 26, 2015

This is on Windows 10 Preview, updated drivers, updated flash, clean Chrome install, re-installed Chrome, deleted user profile - all of these failed to resolve the crash when trying to start a Google Hangouts.

Solution is to un-install Google Stable and install Google Canary. Feel free to comment or follow me on twitter @danielsokolows if this post has helped you.

## Description Path Location Type Resource Save error: An unexpected error occurred. Please include this ErrorId if you contact support: 693681547-51638 (-1906541512) ... line 0 Force.com save problem ...

The blackbox that SF is does not lend it self to debugging so this one took me a while to track so if this post has helped you do comment or follow me on twitter :). The cause was using `this` keyword in my bind SOQL variables and removing it fixed the problem.

Looks like a bug if you ask me to me. If you find others send them to me or comment and I will update the post.

oOrderedContentIds = [SELECT Id FROM cms__Content__c
WHERE Id in :oPrunedContentRenderingsMap.keySet()
ORDER BY cms__Original_Published_Start_Date__c DESC
LIMIT :iQueryLimit // *NOTE:* using `this.` keyword will crap out with unexpected error when saving
OFFSET :iQueryOffset];

Be great

## Free built in Hyper-V in Windows is a fantastic free product

In an effort to self host my Linode server my research has led me to decided to Virtual Machine to run a Debian distribution. Those interested might want to know that I have fully explored other options mainly OpenWRT or running Debian on a beefy MIPS processor; former failed due to lack of proper packages, latter failed due to the difficultly hacking Debian onto MIPS and the lack of tailored router interface.

The two main products a quick Google search returns are VirtualBox and VMWare Player, both are free but I was leaning towards VMWare because - it is my understanding - it's native format can be uploaded to an online host as is. However to my big surprise Microsoft provides it's own Virtualization software built into Windows 8.1.

It's fantastic to use, full of professional features such as VM auto start for and seems to have better virtualisation as I was able to adjust the console's frame buffer resolution without a problem but could not do so in VMWare virtualization.

To install in Start screen type 'Turn Windows features on or off' and locate the Hyper V grouping. While you there notice there are other goodies like a solid free web server 'ISS'

## The gotcha behind 0% credit card balance transfers

At the beginning of this year I have financed solar panels on a low interest line of credit with Scotiabank. In May I became aware of the 0.00% balance transfer option my MBNA credit card was offering and shortly afterwards I had the line of credit transferred to my credit card.

I have done the home work, worked out the total costs (fees) to transfer over, called in to learn how things worked, confirmed there would be no interest charged, even confirmed that it will be ok for me to transfer any remaining balance back onto my line of credit before the promotion ended.

Furthermore I recall explicitly asking what is the catch or hidden costs or anything else I should know about and was told there are none and no.

When the first statement came it did show 0.00% promotional offer on the transfer and no interest, I felt smart, savvy, and proud to have saved a few hundred dollars in overall interest costs.

### But there is a gotcha that got me!

Yesterday I took a close look and to my shock discovered I have been paying interest charges on every statement since my initial check.

As seen in the picture the huge gotcha is that any new purchases after the balance transfer are charged the full 19.99% after the month grace period because any payments you make are going against you balance transfer! Serious trickery I tell you!

I will be calling MBNA in hopes they will see that I was misinformed and reverse the interest charges, and to others considering saving a little on interest be wary of my experience and DO NOT make new purchases on the card. If you found this useful feel free to comment or follow me on twitter .

## Clearing stale errors in salesforce Eclipse

When the default salesforce eclipse builders are enabled there is an intermittent issue (perhaps triggered by too many 'saves'?) where a complication error can not be cleared. Restarting Eclipse and right clicking and deleting the errors has no effect - the same error comes back after saving. However manually saving to the server by using the 'Right Click > Force.com > Save to Server' option does work.

The only way I was able to clear this was to 'Right Click > Force.com > Refresh from Server' the file - this bug has been reported on Salesforce's Github.

## Git Patch 'File does not exist' Solution

Today I needed to apply GIT formatted patches in Eclipse which led me to an hour or so long search on how to do it. Officially the help docs even state it's no possible however there is a Bug 358257 which is set to FIXED for this issue; but I was still getting the 'File does not exist' error.

As shown in the above screen shot the solution is obvious, one must ignore leading patch segments until the files name path matches . This obvious solution escaped me and so I am posting this just in case you the reader have found yourself in the same situation as well.

## The file name(s) would be too long for the destination folder.

Windows under the hood supports pathnames up to 32000 characters however due to some reasons - which I can only think are legacy support related - programs like 'Explorer' will choke on anything longer then about 260 characters during copy operations. This is very frustrating and can be major pain if you are re-installing your system and are keeping your program settings for example the Eclipse Workspace folder.

In my quest for a solution I have found Terra Nova copy but my experience found it buggy - eventually I have discovered FastCopy utility by a Japanese programmer - it has nice right click integration and works well with Windows 8.1 even though has not been updated in a while.

Drop a comment or follow me on twitter @danielsokolows if you found this post useful, and also considering donating to the author.

## How to create a RSS feed search for a specific genre

As seen in the screenshot there is no direct way to specify a 'genre' search however after a bit of expirmenting I have found that there is a unsupported `genre:` parameter. Specifing it one can create a custom advance torrent search that will filter on movie genre - this is becaus you are then able to get the RSS feed of the search by appending `?rss=1` example:

## Wednesday, September 10, 2014

### How to run all tests in Salesforce

Because the location of this button is not obvious and because it took a number of searches to locate I am bloging this; the button is located on the 'Setup > Devleop > Apex Classes' page instead of where it should be: 'Apex Test Execution'.

Feel free to comment or follow me on

## System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>.

The above error is triggered in the database layer and caused by a trigger or workflow outside of your main code of block that is bubbling this exception. This is rather difficult to track down especially if you are unfamiliar with the code, I am sharing my procedure in the hopes this saves you time - if you find this helpful drop me a line or follow me on twitter @danielsokolows.

This error is caused by unique field constraint on the object, so the first step is to examine the object and locate the API names of all unique fieds. You can do this through SF direclty 'Setup < Customize < <object being inserted> < Fields' or by downloading the `src/objects` metadata information and searching for <unique>; I preffer the latter and actually download ALL matadata information for projects I take over.

Next step is to take the field api names and go over triggers and workflows to find where it is referenced and how, this can be time consuming if there are a lot of entries so I preffer to just search within `src/workflows` and `src/triggers` metadata.

In the final step you need to examine the code and figure out which unique field is being populated and how and in effect understand how the duplicate value found error is being triggered. In my situation it turned out to be rather straighforward:

Be great

## Eclipse IDE Salesforce Save error: Illegal assignment from Id to SOBJECT:Property__c

This is a straight forward error message once you understand the cause. I posting this as search results I found deal with the reverse of this situation `Illegal assignment from SObject:<Object> to Id.

The solution is to reference using the `__r` which returns the actual SObject instead of `__c` which returns an `Id`

...
globalDevelopment = tch.createAndInsertOpp(new Map {'RecordType' => 'project'}); // dev project
mainProp = globalDevelopment.property__r; // must use `__r` to return actuall SObject
...

If this post has helped do comment here or follow me on twitter @danielsokolows.

## How to expand all nodes in Outline view

There is a minimize all button but no expand all, searching the net was not helpful right away but I did find the solution after about half hour - hence to save you time I have posted this.

Pressing Numeric Keypad '*' character expands all the nodes of the currently focused tree view, note pressing 'Shift + 8' will not work. If you found this useful feel free to comment or follow me @danielsokolows

## Getting free online cloud space

Microsoft's OneDrive (formally SkyDrive) gives you 7GB free, however by setting up a Camera Roll (SkyDrive on your phone) you get an extra 3GB and you can further get 5GB for anyone you invite.

The cool thing is that both the person inviting and invitee end up with an extra 0.5GB, so please use the below link and we both benefit

https://onedrive.live.com?invref=18c99e1843b58545&invsrc=90

On a side note I must say I am mightily impressed with the social consolidation: LinkedIn, Facebook, Skype, Twitter, etc but that's a post for another day, thanks and hope this helps, @danielsokolows.

## Mercurial Eclipse fresh install not working

Someone dropped the ball on this one, yes the solution is obvious once it's obvious - but until then you will be pulling your hair out. After all you did just install the Mercurial Eclipse plugin from Eclipse Marketplace so it should just work? Well it didn't for me and neither did trying the latest snapshot builds - when restarting Eclipse I kept getting:

The cause of this error is that there is no actual built in mercruial support in the plugin so one must have `hg` installed natively. The solution is to go to Mercurial download page, run the setup, and then restart your eclipse.

If this has helped you feel free to follow me on Google+ or on twitter @danielsokolow or just say hello.

## System wide horizontal scrolling with Ctrl+ or Shift+ mouse wheel

There is an outstanding Bug 201984 to provide a horizontal scrolling mechanism within Eclipse for mouses without a tilt scroll wheel. Untill it's acutally implemented (please register and vote up the bug) the below work with X-Mouse Button Control works just great, and is also system wide.

• In the main window go to 'Layer 2' and change 'Wheel Up' and 'Wheel Down' to 'Scroll Windows Right' and 'Scroll Window Left'
• Go into the 'Settings > Modifier Keys Tab' and select 'Shift' for the 'Activate Layer 2' setting.

Now in whatever active window, including Eclipse pressing shift and then scrolling up and down will scroll horizontally.

Update: I have been using this approach for a few days now and noticed that not all windows are horizontal scroll enabled - this appears to be a limitation of Eclipse IDE rather than this approach. Please take a moment and upvote this Eclipse Bug #201984

## ANT build fails with NullPointerException on the <input> tag.

This error drove me crazy and took me longer than I would like to admit to figure out - the solution was to run the ANT script "in the same JRE as the workspace". There is an eclipse open Bug 281837 from 2009 but without any follow up so perhaps do add your comment/vote there to create some traction.

To change the JRE setting right click on the ant script and choose "Run As > Ant Build... > JRE tab".

If this has helped feel free to follow me on twitter @danielsokolows.

## Or where is the damn VPN over ICMP / DNS setting in SoftEther

Because the infrequent times I need to install a SoftEther server I seem to waste half an hour trying to locate this setting.

BUT, it's already enabled by default.

Well enjoy this tip and if this has helped do thank me by following me on twitter @danielsokolows.

## Sunday, December 8, 2013

### March 14, 2014 Update - I have sold am selling my 'Developer 3' for life instance

See performance stats below and email me at 'cloudatcost-dev3-for-sale [at] danols.com' if interested.

Below is latest performance snapshot - it's usable but not for what I need. Make me an offer in the comment section, the first reasonable amount will be accepted and we'll use a paypal for the transaction.

oot@debian7:~# . test-linode.sh
\$ openssl speed sha1
...
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
sha1             34431.17k    90492.32k   200161.54k   303043.38k   328540.16k

\$ dd if=/dev/zero of=test bs=64k count=5k oflag=dsync && rm test
5120+0 records in
5120+0 records out
335544320 bytes (336 MB) copied, 84.5891 s, 4.0 MB/s

...
Length: 536870912 (512M) [application/zip]
Saving to: `/dev/null'

...
536,870,912 1.18M/s   in 4m 25s

## Super cheap hosting but too good to be true

I've bought their for life Development 3 package about a month or so ago and aside from the rough administration panel at that time I was very impressed at the perfromance and support. The CloudAtCost instance was beating my good old and tried Linode VPS server and tickets were being answsered within hours - please use the previous or this Linode link if you decide to sign up as I get a small kickback .

Fast forward to today and I feel I might have fallen victim to the "Too good to be true" experience. My tickets go unanswered, there was a two week unable to re-image due to maintance message, and performance has hit rock bottom as seen per the stats below

CloudAtCost Dev 3 Package
dd if=/dev/zero of=test bs=64k count=5k oflag=dsync ---> 3.6 MB/s
SHA1 OpenSSL 8192 Test: 322022.06k

Linode 1GB Package
dd if=/dev/zero of=test bs=64k count=5k oflag=dsync ---> 26.7 MB/s
SHA1 OpenSSL 8192 Test: 275749.84k

But let's be fair here and assume that CloudAtCost is simply swamped with the explosion of people jumping at their for life cloud packages, and so with that in mind I reserve the final verdict if I wasted my money to say 6-12 months from now. However the early lesson here is clearly that you get what you pay for.

### Testing script used

Below is very rought testing script I use when comparing new services to Linode.

#!/bin/sh

#echo 'time arc a -mx temp.arc linux'
#rm temp.arc
#time arc a -mx temp.arc linux

echo 'time openssl speed sha1'
time openssl speed sha1

echo 'time tar cf - linux | bzip2 -9 - > temp.tar.bz2'
rm temp.tar.bz2
time tar cf - linux | bzip2 -9 - > temp.tar.bz2

echo 'time dd if=/dev/zero of=test bs=64k count=5k oflag=dsync && rm test'
time dd if=/dev/zero of=test bs=64k count=5k oflag=dsync && rm test

#wget ftp://ftp.kernel.org/pub/linux/kernel/v2.4/linux-2.4.0.tar.bz2
#time tar -xvf linux-2.4.0.tar.bz2

### Feb 01 2014 Update

New 2.0 control panel with better usability but network connection performance has further deteriorated.

CloudAtCost Dev 3 Package
dd if=/dev/zero of=test bs=64k count=5k oflag=dsync ---> 10.7 MB/s
SHA1 OpenSSL 8192 Test: 379376.98k

## Setting up persistent Starbound on Debian

Starbound is a Terraria survival/build like game set in space. Based on watching few videos and playing it for a bit I concluded that except for the over abundant life and loot on every planet this game appeals to me very much. And so along with my minecraft.danols.com server I have decided to run a starbound.danols.com 24/7 dedicated one for Starbound; below is how I did it.

## Get a dedicated Debian linux server

If you don't have yet a linux server I recommend going with Linode Xen VPS hosting - the basic first package will suffice. I have been with them for over 5 years now and can not say enough good things about them.

Yes, there are chepaer alternatives out there but heed the warning that you get what you pay for. With the basic package I am able to run a Freeswtich VOIP server, Minecraft, email, and few websites. Their setup instructions are solid so use that to provision a Debian 7 instance.

Please use the above link or this 7d884fa5262b62b8735502da003fee34061db49b referral code as I will get a small kick back if you do sign up.

If you don't have a domain provider yet I recommend 1&1 Internet. I have used GoDaddy and 1and1 side-by-side over the last few years and I lean towards 1and1 since their prices are good and you also get private registration for free.

Once you get a domain, edit 1and1 or GoDaddy DNS (Domain Resolution Servers) entries and point them at Linode's servers.

After you get the DNS setup with your domain registrat, log into your Linode account and adjust the DNS entires there to point to your server, this is only needed if you are running the server under a subdomain like myself. Below is a screen shot of my starbound.danols.com settings.

To confirm everything is setup correctly ping your domain and if there is a response you are done with this step. This means that now when players want to join your server they just type your domain address instead of your IP.

root@sh1:/usr/local# ping starbound.danols.com
PING starbound.danols.com (69.164.217.6) 56(84) bytes of data.
64 bytes from sh1.danols.com (69.164.217.6): icmp_seq=1 ttl=64 time=0.051 ms
64 bytes from sh1.danols.com (69.164.217.6): icmp_seq=2 ttl=64 time=0.065 ms
64 bytes from sh1.danols.com (69.164.217.6): icmp_seq=3 ttl=64 time=0.064 ms
--- starbound.danols.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 0.051/0.060/0.065/0.006 ms

## Copy the Linux server binaries from your Steam's Starbound folder

Your windows Steam based installation of Starbound includes Linux execetubales to run a dedicated Starbound server. Using a SFTP WinSCP client copy <install directory>\Steam\SteamApps\common\Starbound\linux64\*.* files to /usr/local/starbound-server/linux64/ and <install directory>\Steam\SteamApps\common\Starbound\assets\*.* files to /usr/local/starbound-server/assets.

The final folder structures looks like this:

/usr/local/starbound-server/
/assets/  (files from asssets in steam folder)
/linux64/     (files from linux64 steam folder)

If you are curious why are we placing our Starbound server under '/usr/local/' folder structure feel free to read Debian FilesystemHierarchyStandard wiki.

## Create a starbound-server user and the system startup script

To SSH remote into your server I use Kitty which is a putty clone with extra handy futures such as the ability to store passwords.

To create a limited starbound user which the server will run under execute adduser command as follows:

Adding new user `starbound-server' (1005) with group `daemon' ...
Not creating home directory `/usr/local/starbound-server/'.
Changing the user information for starbound-server
Enter the new value, or press ENTER for the default
Full Name []: Starbound Server
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n]

Now to create the game server startup init system script execute nano /usr/local/starbound-server/starbound-server-init.d-script.sh and paste the following script contents into it.

#!/bin/sh
### BEGIN INIT INFO
# Provides:      starbound
# Required-Start:    \$local_fs \$remote_fs \$network \$syslog \$named
# Required-Stop:    \$local_fs \$remote_fs \$network \$syslog \$named
# Default-Start:    2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the starbound server
# Description:      starts starbound using start-stop-daemon
### END INIT INFO

### NOTE: after linking it into init.d run `update-rc.d starbound-server.sh defaults`

### Settings
PID=/var/run/starbound-server.pid
DAEMON=/usr/local/starbound-server/linux64/starbound_server   # Server BIN
DAEMON_FOLDER=/usr/local/starbound-server/linux64/            # Folder where starbound_server file lives
DAEMON_OPTS=""
NAME=Starbound                                            # Name of process
DESC="Starbound server"                                   # Desc of process
USER=starbound-server                                     # User used to run the process (do not use root)

# Check if user exists
if ! id -u \$USER > /dev/null 2>&1; then
echo "The user does not exist; execute below commands to crate and try again:"
echo "  ..."
echo "  root@sh1:~# chown starbound-server:daemon /usr/local/starbound-server/ -R"
exit 1
fi

### Check if server file exists and is executable
if [ ! -e \$DAEMON ]; then echo "File \$DAEMON does not exist"; exit 1; fi
if [ ! -x \$DAEMON ]; then echo "Server file is not executable; run 'chmod +x \$DAEMON' to fix."; exit 1; fi

set -e

. /lib/lsb/init-functions

start() {
# start the server
# echo "start-stop-daemon --start --make-pidfile --pidfile \$PID --chuid \$USER --chdir \$DAEMON_FOLDER --exec \$DAEMON -- \$DAEMON_OPTS"
start-stop-daemon --start --make-pidfile --pidfile \$PID --chuid \$USER  --chdir \$DAEMON_FOLDER  --exec \$DAEMON -- \$DAEMON_OPTS > /dev/null &

}

stop() {
# gracefully stop the server
start-stop-daemon --stop --signal INT --pidfile \$PID --chuid \$USER --oknodo --exec \$DAEMON
}

case "\$1" in
start)
log_daemon_msg "Starting \$DESC" "\$NAME"
start
log_end_msg \$?
;;

stop)
log_daemon_msg "Stopping \$DESC" "\$NAME"
stop
log_end_msg \$?
;;
restart)
log_daemon_msg "Restarting \$DESC" "\$NAME"
stop
sleep 1
start
log_end_msg \$?
;;

status)
status_of_proc -p \$PID "\$DAEMON" starbound
;;

*)
echo "Usage: \$NAME {start|stop|backup|restart|status}" >&2
exit 1
;;
esac

exit 0

### error while loading shared libraries: libvorbisfile.so.3: cannot open shared object file: No such file or directory

You might get the above error message so let's run aptitude install libvorbisfile3 which resolved the missing library issue for me.

## Final steps and test run

Ensure that all files are owned by the startbound-server user - do this by executing chown starbound-server:daemon /usr/local/starbound-server/ -R. Add the startup script to the boot process by linking it from '/etc/init.d' folder and adding it to the startup sequence as follows:

root@sh1:/usr/local/starbound-server/assets# ln -s /usr/local/starbound-server/starbound-server-init.d-script.sh /etc/init.d/starbound-server.sh
root@sh1:/usr/local/starbound-server/assets# update-rc.d starbound-server.sh defaults

Test the entire setup by starting the game server /etc/init.d/starbound-server.sh start, and logging into your new shiny server. Feel free to follow me on Twitter @danielsokolow and comment if you have any questions.

And lastly do log into my persistent server at starbound.danols.com to check it out.

## Troubleshooting

Best way to troubleshoot is to start the server manually and look for any errors in the console, to start the server manually do as follows:

root@sh1:/etc/init.d# cd /usr/local/starbound-server/linux64/
root@sh1:/usr/local/starbound-server/bin# ./starbound_server
Info: Creating Star::Root with 1 assets sources and config file: './starbound.config'
...

Warn: Slow asset 0.081 : /objects/generic/capsulemed/capsulemed.png:default
Warn: Perf: UniverseServer::createWorld millis: 6830
Warn: Perf: UniverseServer::doTriggeredStorage millis: 363
Warn: Perf: UniverseServer::run.innerloop millis: 473
Info: Shutting down world alpha:-61930447:-6722809:-4350314:8:6

## Tips

The log is very noisy, but you can mitiage some of that by using a good log coloriser like 'ccze'; to install and use execute the following:

root@sh1:~# aptitude install ccze
...
root@sh1:~# tail -f -n 50 /usr/local/starbound-server/linux64/starbound_server.log | ccze -A
...

### Auto re-start the server if it dies

I've noticed the server seems to stops running after a while which - I attribute this to the beta code quality - as a work arround I created the following cron entry which just executes /etc/init.d/starbound-server start; the start-stop-deamon takes care of not spawning a new server if it is already running for us.

I like to be explicit so I anmed the below as /usr/local/starbound-server/starbound-server-cron.d-entry and linked it as /etc/cron.d/starbound-server-start-if-needed. Note that files in cron.d must not have periods in them.

# On Debian system symlink this file into your `/etc/cron.d` folder like so
#
# > ln -s /usr/local/starbound-server/starbound-server-cron.d-entry /etc/cron.d/starbound-server-start-if-needed
#