[CODE] Arduino 4 BIT LED binary counter

Here’s my “Hello World” on Arduino.
A 4-bit binary counter for arduino.
If you add another LED on the 5th pin, then it can count from 0 to 31 (32 values)

Circuit wired by @KataySantos

[pastacode lang=”c” manual=”int%20counter%20%3D%20-1%3B%0Aint%20MAX_VALUE%20%3D%2016%3B%0A%0Avoid%20updateLED(int%20pin%2C%20int%20bit%2C%20int%20ctr)%20%7B%0A%20%20digitalWrite(pin%2C%20(ctr%20%26%20(1%3C%3Cbit))%20%3D%3D%20(1%3C%3Cbit)%20%3F%20HIGH%20%3A%20LOW)%3B%0A%7D%0Avoid%20setup()%20%7B%0A%20%20%2F%2F%20this%20runs%20once%0A%20%20pinMode(1%2C%20OUTPUT)%3B%0A%20%20pinMode(2%2C%20OUTPUT)%3B%0A%20%20pinMode(3%2C%20OUTPUT)%3B%0A%20%20pinMode(4%2C%20OUTPUT)%3B%0A%7D%0A%0Avoid%20loop()%20%7B%0A%20%20%2F%2F%20this%20runs%20repeatedly%0A%20%20counter%20%3D%20(counter%20%2B%201)%20%25%20MAX_VALUE%3B%0A%20%20updateLED(1%2C%200%2C%20counter)%3B%0A%20%20updateLED(2%2C%201%2C%20counter)%3B%0A%20%20updateLED(3%2C%202%2C%20counter)%3B%0A%20%20updateLED(4%2C%203%2C%20counter)%3B%0A%20%20delay(500)%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

[CODE/PHP] JpGraph: How to output your graph as a base64 encoded image

Some times you just want to output the image created by your $graph object without having to create a separate .php script that would need to receive a bunch of parameters.

Here’s a function you can pass your $graph object right before the $graph->Stroke(); call

[pastacode lang=”php” manual=”function%20graphInSrc(%24graph%2C%20%24width%2C%20%24height)%20%7B%0A%20%20%24img%20%3D%20%24graph-%3EStroke(_IMG_HANDLER)%3B%0A%20%20ob_start()%3B%0A%20%20imagepng(%24img)%3B%0A%20%20%24img_data%20%3D%20ob_get_contents()%3B%0A%20%20ob_end_clean()%3B%0A%0A%20%20echo%20’%3Cimg%20width%3D%22′.%24width.’%22%20height%3D%22′.%24height.’%22%20src%3D%22data%3Aimage%2Fpng%3Bbase64%2C’.base64_encode(%24img_data).’%22%2F%3E’%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

[GIT] How to replace the master branch with another branch.

git checkout master
git reset --hard fixed-master-branch
git push origin master -f

Sometimes someone may pollute the ‘master’ branch and you may have noticed this only after you’ve fetched, rebased and pushed your commits.
So your history may end up like this (I’ll use decimal numbers on the commit IDs for illustrative purposes only):

commit: 87
Author: me
A good commit

commit: 86
Author: other guy
Merge: that brought back a lot of crap because they probably used some GUI based git client and they did a git pull without your permission

commit: 85
Author: other guy
Another commit that shouldn't be here

commit: 84
Author: me
Another the last good commit

Now, your master is all effed up and you’re about to have an anxiety attack. What you want is to have this in your git log.

commit: 87
Author: me
A good commit

commit: 84
Author: me
Another the last good commit

To get back to this state is pretty easy:

  1. Check out the last good commit

git checkout 84

Now you will be detached from master, let’s name this temporary branch ‘fixed-master-branch’

git checkout -b fixed-master-branch

Now the last commit you should see should be commit 84.

Let’s now bring our commit, and skip the 2 sucky commits

git cherry-pick 87

Now your ‘fixed-master-branch’ branch looks exactly how you want the master to look like.

But now, you want to replace the old master with the new one.

Go back to the broked master

git checkout master

And fix it, and fuck all that merge –strategy ours BS advice you will find on StackOverflow as it will leave the git log history really weird.

git reset --hard fixed-master-branch

Now when you look at your history, master will be the same as ‘fixed-master’, and to fix your remote repo, you will have to make a push –force and let everyone know that you did that because you needed to clean your repository’s history

git push origin master -f

You’re done.

[CODE/JAVA] ARGB_8888 Pixel Abstraction

This is one of the ways you can decode Pixel colors out of the integers you get from Android Pixels.

ARGB_8888, stands for Alpha, Reg, Green, Blue. The 8’s stand for the number of bits per channel.

In Android, signed int‘s are used to represent pixel’s alpha/color information.
Since Android’s language of choice is java, these ints are 32-bit integers, each int takes 4 bytes.

4 bytes = 32 bits = 8bits + 8bits + 8bits + 8bits.

If you had an int like 0xFFAABBCC, each pair of letters on that hexadecimal would mean the following from left to right


If you’ve done web programming and played with rgb colors and you didn’t know about this, now it all should click on how your web browser represents colors, except in HTML you don’t deal with the alpha value in the front. On Android’s XML you do.

In bits (binary), the 0xFFAABBCC value would look like this:

alpha red green blue
0xFF 0xAA 0xBB 0xCC
255 170 187 204

If you wanted to look at the entire number in binary/bits, it’d be something like this (leaving spaces for visual help):

0b11111111 10101010 10111011 11001100 == 0xFFAABBCC == 4289379276

So if you wanted to get the red channel (0xAA = 170 = 0b10101010) , you’d have to move the whole thing towards the right 16 places, and then compare it with only the rightmost 8 bits.

So, we shift 16 places to the right, we’d get rid of the 2 bytes on the right side and end up only with the left half

0b11111111 10101010

Since we only care about those 8 bits on the right, we do an “&” (bitwise “and”) against 0xFF=255=0b111111111 (all 8 rightmost bits set to 1)

0b11111111 10101010 &
0b00000000 11111111
0b00000000 10101010

So with simple right bit shifting and “& 0xff” of the shifted value we can extract the values per channel.

This class also features a “multiplyByFloat()” function, which I was using to multiply to each channel as I was operating with convolution kernels while playing with image filters.

[pastacode lang=”java” manual=”%2F**%20ARGB_8888%20Pixel%20abstraction%20*%2F%0Apublic%20static%20class%20PixelARGB_8888%20%7B%0A%20public%20final%20byte%20a%3B%0A%20public%20final%20byte%20r%3B%0A%20public%20final%20byte%20g%3B%0A%20public%20final%20byte%20b%3B%0A%20public%20final%20int%20intVal%3B%0A%0A%20public%20PixelARGB_8888(final%20int%20argb32bitInt)%20%7B%0A%20%20a%20%3D%20(byte)((argb32bitInt%20%3E%3E%2024)%20%26%200xff)%3B%0A%20%20r%20%3D%20(byte)((argb32bitInt%20%3E%3E%2016)%20%26%200xff)%3B%0A%20%20g%20%3D%20(byte)((argb32bitInt%20%3E%3E%208)%20%26%200xff)%3B%0A%20%20b%20%3D%20(byte)(argb32bitInt%20%26%200xff)%3B%0A%20%20intVal%20%3D%20argb32bitInt%3B%0A%20%7D%0A%0A%20public%20PixelARGB_8888(byte%20a%2C%20byte%20r%2C%20byte%20g%2C%20byte%20b)%20%7B%0A%20%20this.a%20%3D%20a%3B%0A%20%20this.r%20%3D%20r%3B%0A%20%20this.g%20%3D%20g%3B%0A%20%20this.b%20%3D%20b%3B%0A%20%20intVal%20%3D%20(a%20%3C%3C%2024)%20%2B%20(r%20%3C%3C%2016)%20%2B%20(g%20%3C%3C%208)%20%2B%20b%3B%0A%20%7D%0A%0A%20public%20static%20int%20multiplyByFloat(float%20factor%2C%20int%20arg32bitInt)%20%7B%0A%20%20return%20multiplyByFloat(factor%2C%20arg32bitInt%2C%20false)%3B%0A%20%7D%0A%0A%20public%20static%20int%20multiplyByFloat(float%20factor%2C%20int%20argb32bitInt%2C%20boolean%20multiplyAlphaChannel)%20%7B%0A%20%20PixelARGB_8888%20original%20%3D%20new%20PixelARGB_8888(argb32bitInt)%3B%0A%20%20byte%20alpha%20%3D%20original.a%3B%0A%20%20if%20(multiplyAlphaChannel)%20%7B%0A%20%20%20alpha%20%3D%20(byte)(original.a%20*%20factor)%3B%0A%20%20%7D%0A%20%20PixelARGB_8888%20multiplied%20%3D%20new%20PixelARGB_8888(alpha%2C%20(byte)(factor%20*%20original.r)%2C%20(byte)(factor%20*%20original.g)%2C%20(byte)(factor%20*%20original.b))%3B%0A%20%20return%20multiplied.intVal%3B%0A%20%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

[ANDROID] How to create a background shape with a double border / rounded border with a drop shadow

Usually we use <shape> objects in our .xml drawables meant for the backgrounds of buttons or other View objects.

I came across a situation where such object should appear as if it had been previously selected, and the graphic design choice was to put a thick rounded stroke around the container, while at the same time showing a hint of a dropped shadow.

Android <shape>’s only allow us to define rectangles, curve their <corners>, fill them up with <solid> colors, and to give them a single <stroke> around (dashed or solid). Therefore we can’t think of using 2 strokes.

Luckily drawable resources to be used as View backgrounds can be created using not just shapes, or bitmaps, but <layer-list>’s.

For creating the selected button below


this is what I did (after over an hour of playing around until I was happy, for some reason UI code takes me the longest to get it right, am I the only one?)




So you have set up a test elastic beanstalk environment because you don’t want to put at risk your production elastic bean.
You don’t want to pay for the time you’re not using it, and there’s no freaking “Pause Environment” option.


all you can do is “Terminate Environment”? but then to crete the damn environment it takes forever to configure (if you’re using the dashboard), so we don’t want to do that.

If you try to terminate the associated EC2 instance, the Elastic Beanstalk environment will automatically provision a new machine for you, so that doesn’t work. What do you do?

Open the Elastic Bean environment you want to pause and go to “Configuration”
Screen Shot 2016-06-23 at 1.55.02 PM

On the Scaling card, click on the Gear icon to change its settings

Screen Shot 2016-06-23 at 1.55.11 PM

in the “Auto Scaling” options, set the “Minimum instance count” to 0, and the “Maximum instance count” to 0

Screen Shot 2016-06-23 at 1.55.56 PM

Hit “Apply”
Screen Shot 2016-06-23 at 1.56.03 PM

Wait for your environment to apply the new configuration

Screen Shot 2016-06-23 at 1.56.15 PM


Now your health status has switched to gray. It’s now paused and you won’t be paying for the test ec2 instance while you’re not working on it.

Screen Shot 2016-06-23 at 1.58.11 PM

If you are curious and you check the ec2 instances associated to the environment, it/them should be terminated now, but now the environment won’t try to provision new ones.

Savings in your pocket. Cheers.


[SYSADMIN] Serve your WordPress cached pages directly with lighttpd and not PHP

Optimizing Your WordPress Cache Loads in Lighttpd.

If you don’t configure your wordpress virtual host properly in lighttpd, your wordpress cache will still make use of PHP.

Wouldn’t it be nice if all those cached requests were served directy from the webserver as the static files that they are, bypassing the CPU/memory load PHP can have, and use those resources for otherthings?

Install and Enable mod_magnet

For this to occur with lighttpd, you will need mod_magnet, so assuming you’re on a Ubuntu/Debian based linux distro let’s make sure we have it installed.

sudo apt-get install lighttpd-mod-magnet

Then let’s make sure it’s enabled, you can do this manually on your lighttpd.conf by adding “mod_magnet” to the list of enabled modules…

server.modules = (

or you can do it the lighty way:

sudo lighty-enable-mod magnet

(this simply makes a symlink to the 10-magnet.conf file inside /etc/lighttpd/conf-enabled which lighty will check upon startup)

The cache logic script that will be executed by lighttpd

Now, on your wordpress directory, create a file called rewrite.lua and paste the following script in it:

function log(str)
   -- wanna tail -f a log to see what's happening    
   fp = io.open("/path/to/some/lua.log","a+")
   fp:write(str .. "\n")

function serve_html(cached_page)
    if (lighty.stat(cached_page)) then
        lighty.env["physical.path"] = cached_page
        return true
        return false

function serve_gzip(cached_page)
    if (lighty.stat(cached_page .. ".gz")) then
        lighty.header["Content-Encoding"] = "gzip"
        lighty.header["Content-Type"] = ""
        lighty.env["physical.path"] = cached_page .. ".gz"
        return true
        return false

if (lighty.env["uri.scheme"] == "http") then
    ext = ".html"
    ext = "-https.html"

cached_page = lighty.env["physical.doc-root"] .. "/wp-content/cache/supercache/" .. lighty.request["Host"] .. lighty.env["request.orig-uri"]
cached_page = string.gsub(cached_page, "//", "/")
cached_page = string.gsub(cached_page, lighty.request["Host"] .. "/index.php", lighty.request["Host"])

attr = lighty.stat(cached_page)

if (attr) then
    query_condition = not (lighty.env["uri.query"] and string.find(lighty.env["uri.query"], ".*s=.*"))
    user_cookie = lighty.request["Cookie"] or "no_cookie_here"
    cookie_condition = not (string.find(user_cookie, ".*comment_author.*") or (string.find(user_cookie, ".*wordpress.*") and not string.find(user_cookie,"wordpress_test_cookie")))

    if (query_condition and cookie_condition) then
        accept_encoding = lighty.request["Accept-Encoding"] or "no_acceptance"

        if (string.find(accept_encoding, "gzip")) then
            if not serve_gzip(cached_page) then 
        --log('cache-hit: ' .. cached_page)
    --log('cache-miss: ' .. cached_page)

Configuring your vhost in lighttpd for WordPress redirects and direct cache serves without php.

Then on your vhost configuration in lighttpd.conf add the following towards the end.
(Fix paths if you have to)

var.wp_blog = 1

magnet.attract-physical-path-to = ( server.document-root + "/rewrite.lua" )

url.rewrite-if-not-file = (
   "^/(wp-.+).*/?" => "$0",
   "^/(sitemap.xml)" => "$0",
   "^/(xmlrpc.php)" => "$0",
   "^/(.+)/?$" => "/index.php/$1"

Restart your lighttpd sudo service lighttpd restart

Now watch how your PHP processes breathe a lot better and you page loads are insanely faster.

You’re welcome 🙂

[ANDROID] How to set a custom title View on a DialogPreference extending class.

So you have a FooDialogPreference class which extends DialogPreference, and one of the things you’d like to do to it, is to change the Dialog’s title.

DialogPreference happens to be a bit of a bitch, you can’t just call getDialog() and start playing with its features before it is shown because the Dialog object is only created when DialogPreference.showDialog()is called.

However, there’s ONE entry point where you can make your magic happen.

If we look at the code of
from the geniuses at the Android project, some gentle soul added a call to
onPrepareDialogBuilder(mBuilder); which is a method you’re meant to override.

Override this method, and then with the builder object you’ve received you will be able to call:


However, there’s a couple of things you need to do:

  1. Instantiate your myCustomTitleView object on the implementation of your onBindDialogView, and keep the reference as a private property of your FooDialogPreference class.

  2. Make sure to detach it from it’s parent ViewGroup, otherwise you will get an IllegalStateException from android.view.ViewGroup.addViewInner() letting you know this view you’re trying to add, cannot have a parent.

This is what I had to do:

[pastacode lang=”java” manual=”final%20ViewGroup%20parent%20%3D%20(ViewGroup)%20myCustomTitleView.getParent()%3B%0Aparent.removeView(myCustomTitleView)%3B%0Abuilder.setCustomTitle(myCustomTitleView)%3B” message=”” highlight=”” provider=”manual”/]

That’s all folks!

Things to think about when tuning libtorrent for high performance

An user on the libtorrent mailing list had the following problem:

I’m doing some testing for a libtorrent application that will use a small number of peers (often just 1 seed and 1 downloaded) and high bandwidth delay product links (in the hundreds of Mb/s and 100ms+ round trip). I’m unable to get more than 20Mbps with a single peer on a 140ms RTT link (simulated delay with no packet loss). If I take the network simulator delay down to 0, I can get almost a full 1000Mbps on the same system. I’ve tried playing with everything that sounded relevant in session_settings, but nothing seems to make any improvement at all.

Is this the best that can be expected out of uTP on a high latency link? Or is there some combination of parameters that would improve the single peer throughput? Alternatively, is there a way to get libtorrent to make multiple connections between the same 2 peers?

If you’re facing a similar situation here are some things you could adjust according to Arvid Norberg lead engineer of the libtorrent project.

“Did you increase the socket buffer sizes on both ends?”

int recv_socket_buffer_size;
int send_socket_buffer_size;

“There’s also buffer sizes at the bittorrent level:”

int send_buffer_low_watermark;
int send_buffer_watermark;
int send_buffer_watermark_factor;

“And there are buffers at the disk layer:”

int max_queued_disk_bytes;
int max_queued_disk_bytes_low_watermark;

If the performance issue happens with uTP but not TCP though, it’s probably
just the first ones that matters.

Also, the uTP implementation needs a system call for each packet sent and
received (i.e. it does not use sendmmsg()/recvmmsg()) which also makes it
more expensive than TCP, but that would primarily cause additional CPU
usage, and only slow-downs once a CPU core is pegged.

command line speed test, see how fast is your server’s connection

Save the following script in a file called speed_test


# Requirements
# sudo apt-get install lftp iperf

lftp -e 'pget http://releases.ubuntu.com/14.04.3/ubuntu-14.04.3-desktop-amd64.iso; exit; '

make sure the file is executable: sudo chmod +x speed_test

Once you have installed lftp and iperf make sure you have the script somewhere in your $PATH.

The script basically downloads an ubuntu iso and does the math.

The output looks like this on a AWS m3.large instance:

$ speed_test
1054871586 bytes transferred in 14 seconds (70.37M/s)

Multiply by 8 to convert 70.37M/s to Megabits per second = 562.96 Mbit/s

AWS’s download speeds for m3.large instances is half a gigabit in January 2016. (or is that the upload speed of the Ubuntu ISO server?)