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

TL;DR;
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

{alpha=0xFF}{red=0xAA){green=0xBB}{blue=0xCC}

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
{0b11111111}{0b10101010}{0b10111011}{0b11001100}

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.

/** ARGB_8888 Pixel abstraction */
public static class PixelARGB_8888 {
 public final byte a;
 public final byte r;
 public final byte g;
 public final byte b;
 public final int intVal;

 public PixelARGB_8888(final int argb32bitInt) {
  a = (byte)((argb32bitInt >> 24) & 0xff);
  r = (byte)((argb32bitInt >> 16) & 0xff);
  g = (byte)((argb32bitInt >> 8) & 0xff);
  b = (byte)(argb32bitInt & 0xff);
  intVal = argb32bitInt;
 }

 public PixelARGB_8888(byte a, byte r, byte g, byte b) {
  this.a = a;
  this.r = r;
  this.g = g;
  this.b = b;
  intVal = (a << 24) + (r << 16) + (g << 8) + b;
 }

 public static int multiplyByFloat(float factor, int arg32bitInt) {
  return multiplyByFloat(factor, arg32bitInt, false);
 }

 public static int multiplyByFloat(float factor, int argb32bitInt, boolean multiplyAlphaChannel) {
  PixelARGB_8888 original = new PixelARGB_8888(argb32bitInt);
  byte alpha = original.a;
  if (multiplyAlphaChannel) {
   alpha = (byte)(original.a * factor);
  }
  PixelARGB_8888 multiplied = new PixelARGB_8888(alpha, (byte)(factor * original.r), (byte)(factor * original.g), (byte)(factor * original.b));
  return multiplied.intVal;
 }
}

[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

android-how-to-make-background-with-2-borders-gubatron

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?)

 

android-how-to-make-background-with-colored-border-and-shadow-with-shape

[TUTORIAL] HOW TO PAUSE AN AWS ELASTIC BEANSTALK ENVIRONMENT USING THE DASHBOARD

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.

aws-elasticbean-no-pause-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.
thanks-bow

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 = (
        "mod_fastcgi",
        "mod_access",
        "mod_alias",
        "mod_accesslog",
        "mod_compress",
        "mod_rewrite",
        "mod_redirect",
        "mod_status",
        "mod_proxy",
        "mod_setenv",
        "mod_magnet"
)

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")
   fp:flush()
   fp:close()
end

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

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
    else
        return false
    end
end

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

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 
                serve_html(cached_page) 
            end
        else
            serve_html(cached_page)
        end
        --log('cache-hit: ' .. cached_page)
    end
else
    --log('cache-miss: ' .. cached_page)
end

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
DialogPreference.showDialog()
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:

builder.setCustomTitle(myCustomTitleView);

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:

final ViewGroup parent = (ViewGroup) myCustomTitleView.getParent();
parent.removeView(myCustomTitleView);
builder.setCustomTitle(myCustomTitleView);

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

#!/bin/bash

# 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?)

IntelliJ / Adroid Studio / CLion / GoLand / PyCharm / PHPStorm keymap shortcuts I can’t live without

Download settings.jar (Import with `File -> Import Settings`)

I got to IntelliJ after years of using Emacs and Eclipse. Here’s how my keymap looks now that I work with Jetbrains tools, these are the keyboard shortcuts I can’t live without as a programmer.

 

Legend (Mac keyboard)
⌘ Command
⇧ Shift

⌘1 Show Intent Actions (Things like assign to local variable)
⌘- Decrease font size
⌘= Increase font size
⌘0 Reset font size
⌘↓ Scroll to botom
⌘↑ Scroll to top
⌘f Find in text
⌘. Find next highlighted error
^⇧F Find in path (searches in all files, like a grep)
⌘⇧G Find Usages (Find all Occurrences of selected symbol [variable, method, class, identifier])
⌘I Show current function/method parameter info
F3 Jump to source (go inside function’s code)
⌘E Show list of recent files
⌘B Build
⌘L Jump to line number
⌘[ Back
⌘] Forward
⌘T Show implementations of an interface.
⌘⇧F Format (selected) code
⌘⇧O Organize/Optimize imports
⌘⌥R Rename current symbol
^K Kill line
⌘D Duplicate line
Ctrl+G on selected token – repeats selection and enables multiple cursors
Alt+Up | Alt+Down – Move the current line up or down

Debugger shortcuts
F5 Step Into
F6 Step Over
F7 Step Out
F9 Resume Program

^K Cut up to Line End. (Deletes everything to the right of where the text cursor or caret is)

How to create a list that holds different object types using `void*` in C.

I remember being in school back around 1998 and not knowing enough about C to do this. After coding in other languages, then going back to C++ and understanding at a lower level how references and pointers work, this was pretty easy to figure out.

In this exercise I store elements of different types in a forward linked list.
In order to know what to dereference as I iterate through the list’s elements, I’ve put a “.type” field, which has an int value representing the type of the object stored.

The “.value” is simply a void*, which lets me store a pointer of any kind, and it works pretty well.

Here’s the code for your enjoyment, I hope this is useful to C apprentices.

The example shows how you can store native types like int, or more complex char* or even a struct person* (which is the more useful probably to your purposes)

It’s a good exercise to see the uses of the “address of” operator “&”, which is used to initialize pointers (the ‘&’ can also be used differently to create references, which I call in my mind as ‘aliases’, but this is not shown in this example)

I also play with a not so popular syntax to access a pointer’s sub-fields:

(*myPointer).structField == myPointer-&gt;structField

to teach you that the -&gt; is a short hand for dereferencing a pointer and accessing one of its fields.

//                                                                                                                                                                                          
// An exercise to play with a struct that stores anything using a void* field.                                                                                                              
//                                                                                                                                                                                          

#include <stdio.h>

#define TRUE 1

int TYPE_INT = 0;
int TYPE_STRING = 1;
int TYPE_BOOLEAN = 2;
int TYPE_PERSON = 3;

struct node {
  struct node* next;
  int type;
  void* value;
};

struct person {
  char* name;
  int age;
};

int main(int args, char **argv) {

  struct person aPerson;
  aPerson.name = "Angel";
  aPerson.age = 35;

  // Define a linked list of objects.                                                                                                                                                       
  // We use that .type field to know what we're dealing                                                                                                                                     
  // with on every iteration. On .value we store our values.                                                                                                                                
  struct node nodes[] = {
    { .next = &nodes[1], .type = TYPE_INT    , .value=1                   },
    { .next = &nodes[2], .type = TYPE_STRING , .value="anyfing, anyfing!" },
    { .next = &nodes[3], .type = TYPE_PERSON , .value=&aPerson            },
    { .next = NULL     , .type = TYPE_BOOLEAN, .value=TRUE                }
  };

  // We iterate through the list                                                                                                                                                            
  for ( struct node *currentNode = &nodes[0]; currentNode;  currentNode = currentNode->next) {
    int currentType = (*currentNode).type;
    if (currentType == TYPE_INT) {
      printf("%s: %dn", "- INTEGER", (*currentNode).value); // just playing with syntax, same as currentNode->value                                                                        
    } else if (currentType == TYPE_STRING) {
      printf("%s: %sn", "- STRING", currentNode->value);
    } else if (currentType == TYPE_BOOLEAN) {
      printf("%s: %dn", "- BOOLEAN (true:1, false:0)", currentNode->value);
    } else if (currentType == TYPE_PERSON) {
        // since we're using void*, we end up with a pointer to struct person, which we *dereference                                                                                        
        // into a struct in the stack.                                                                                                                                                      
        struct person currentPerson = *(struct person*) currentNode->value;
        printf("%s: %s (%d)n","- TYPE_PERSON", currentPerson.name, currentPerson.age);
      }
  }

    return 0;
}

The output is this:

- INTEGER: 1
- STRING: anyfing, anyfing!
- TYPE_PERSON: Angel (35)
- BOOLEAN (true:1, false:0): 1