Monthly Archives: March 2016


HOWTO: Make Terminator Terminal Act Like Guake Terminal in Fedora 23 1

We tried to toggle the visibility of the terminator window using the default keybinding which is (Shift+Ctrl+Alt+A) and failed. Changing the configuration in the ‘Terminator Preferences’ under Keybindings to a new key-bind also did not do any good. We could not get the hide_window keybinding to work and so we could not toggle the window visibility with the keyboard.

We propose this alternative solution that requires two additional packages: xdotool and wmctrl.

In Fedora you can install them using sudo dnf install xdotool wmctrl and in Ubuntu using sudo apt-get install xdotool wmctrl

After the installation is complete, you need to paste the following code in a file and make it an executable.

e.g From a terminal issue nano ~/toggle_visibility.sh, then paste the code and hit CTRL+X to exit. When prompted if you want to save press ‘Y’ and enter.

#!/bin/bash

#The purpose of this script is to allow the user to toggle the visibility of (almost) any window.
#Please note it will work on the first match, so if there are multiple instances of an application it would be a random window of them the one to be affected.
#Usually it will control the window with the smallest PID.

#Checking that all dependencies are met, since we cannot proceed without them.
declare -a DEPENDENCIES=("xdotool" "wmctrl");
declare -a MANAGERS=("dnf" "apt-get");

for DEPENDENCY in ${DEPENDENCIES[@]}; do
    echo -n "Checking if $DEPENDENCY is available";
    if hash $DEPENDENCY 2>/dev/null; then
        echo "- OK, Found";
    else
        echo "- ERROR, Not Found in $PATH";
        for MANAGER in ${MANAGERS[@]}; do
            if hash $MANAGER 2>/dev/null; then
                echo -n "$DEPENDENCY is missing, would you like to try and install it via $MANAGER now? [Y/N] (default is Y): ";
                read ANSWER;
                if [[ "$ANSWER" == "Y" || "$ANSWER" == "y" || "$ANSWER" == "" ]]; then
                    sudo "$MANAGER" install "$DEPENDENCY";
                else
                    echo "Terminating";
                    exit -1;
                fi
            fi
        done
    fi
done

APPLICATION="$1";

#Checking if the application name provided by the user exists
if ! hash $APPLICATION 2>/dev/null; then
    echo -e "$APPLICATION does not seem to be a valid executable\nTerminating";
    exit -2;
fi

#Checking if the application is running. We are using pgrep as various application are python scripts and we will not be able to find them using pidof. pgrep will look through the currently running processes and list the process IDs of all the processes that are called $APPLICATION.
PID=$(pgrep --exact $APPLICATION | head -n 1);

#If the application is not running, we will try to launch it.
if [ -z $PID ]; then
  echo "$APPLICATION not running, launching it..";
    $APPLICATION;
else
    #Since the application has a live instance, we can proceed with the rest of the code.
    #We will get the PID of the application that is currently focused, if it is not the application we passed as parameter we will change the focus to that. In the other case, we will minimize the application.
  echo -n "$APPLICATION instance found - ";
    FOCUSED=$(xdotool getactivewindow getwindowpid);
    if [[ $PID == $FOCUSED ]]; then
    echo "It was focused so we are minimizing it";
        #We minimize the active window which we know in this case that it is the application we passed as parameter.
        xdotool getactivewindow windowminimize;
    else
    echo "We are setting the focus on it";
        #We set the focus to the application we passed as parameter. If it is minimized it will be raised as well.
        wmctrl -x -R $APPLICATION;
    fi
fi

exit 0

Afterwards, you need to make the script an executable so you should issue chmod +x ~/toggle_visibility.sh to do that.

Then, execute ~/toggle_visibility.sh in your terminal once. We need to do that in order to install any missing dependencies for the tool.

Finally, you need to create a custom shortcut that will call the script using the key combination you like at any point.

For Fedora,

  1. Issue the following in a terminal gnome-control-panel to start the gnome control panel.
  2. In the newly appeared window, click on the ‘keyboard’ icon that is in the category ‘Hardware’.
  3. After that, click on the tab ‘Shortcuts’
  4. and on the left list, click on custom shortcuts.
  5. You will see a button with the + sign, click that.
  6. In the dialog box that will appear enter the following:
    – In the name field enter anything you like. e.g ‘Toggle Terminator Visibility’
    – In the command field enter ‘/home/<USER>/toggle_visibility.sh terminator’ where user enter your own username.
    – Click apply.
  7. You will see a new row with two columns with the name you just set in the first column. Click on the second column, where it should say ‘Disabled’ and the press the key combination you want for toggling terminator e.g F12

For Ubuntu, go to System Settings and follow the same procedure after step 2.

You are ready to go 🙂

Just try the key combination you just provided and terminator will appear in front of you. Pressing it once more it will hide it.


C: Split a buffer to a list of segments of a specific size in bits

Full project and source code to segment buffer to parts of specific size in bits (8 downloads)

The following code will split a buffer in C to a list of segments.
The size of the segments does not have to be a multiple of a byte.
User defines the size of the segments in bits when calling node_t *segment(const unsigned char buffer[], const unsigned int buffer_bytes_size, const unsigned int segment_bit_size, const unsigned int first_segment_bit_size);.

Each segment is an instance of element_t structure as follows:

struct element_t {
  unsigned char *segment;
  unsigned int unused_bits;
  unsigned int size;
};

Variable unused_bits defines the bits in the last byte that should not be used in future operations.

Full project and source code to segment buffer to parts of specific size in bits (8 downloads)

Following is the code that performs the segmentation:

#include "segmentation.h"

#include <math.h>
#include <limits.h>
#include <malloc.h>
#include <string.h>

//This method will create a string made of 0s and 1s representing the bits in an object.
//It will skip printing the last n bits as per the input
char *create_bit_representation_string(const void *object, const unsigned int size,
                                       const unsigned int skip_last_bits)
{
    unsigned int i = 0;
    const unsigned char *byte;
    unsigned int temp_size = size;
    const double mask_filter = pow(2, skip_last_bits);
    const unsigned int skip_last_bytes = skip_last_bits / CHAR_BIT;
    char *result = malloc(sizeof(char) * size * CHAR_BIT - skip_last_bits + 1);

    for (byte = object; temp_size--; ++byte)
    {
        unsigned char mask;
        for (mask = 1 << (CHAR_BIT - 1); mask; mask >>= 1)
        {
            //We do not want to print the last n bits of the last byte as they should always be 0
            if ((temp_size < skip_last_bytes) || (temp_size == 0 && mask < mask_filter))
            {
                break;
            }
            result[i++] = (char) (mask & *byte ? '1' : '0');
        }
    }

    result[i] = '\0';
    return result;
}

//Creating a mask where the first n bits are 1s and the rest are 0s to zero the unused bits of the segment
unsigned char create_left_mask(const unsigned int bits)
{

    unsigned char left_mask = 0;
    unsigned int i;
    for (i = 0; i < bits; i++)
    {
        left_mask |= (1 << (CHAR_BIT - 1 - i));
    }
    return left_mask;
}

//This function will shift to the left a char array for up to 7 bits.
//It will update the object and return the number of bits shifted
unsigned int
shift_left_char_array_n_bits(void *object, const unsigned int size, const unsigned int bits)
{
    if (bits == 0)
    {
        return 0;
    }

    if (bits < 1 || bits > CHAR_BIT - 1)
    {
        fprintf(stderr, "%s: Bad value %u for 'bits', it should be [1,7]"
                "\n\tIgnoring operation\n", __FUNCTION__, bits);
        return 0;
    }

    //Creating a mask where the first n bits are 1s and the rest are 0s.
    const unsigned char left_mask = create_left_mask(bits);

    unsigned char *byte;
    unsigned int temp_size = size;
    //We use temp_size as a counter (until it reaches 0) and we move the byte pointer at each loop
    for (byte = object; temp_size--; ++byte)
    {
        unsigned char carry = 0;
        if (temp_size)
        {
            //We get the bits we want to carry using the mask
            carry = byte[1] & left_mask;
            //Then shift them to the right, as this is where they will be in the new byte.
            carry >>= (CHAR_BIT - bits);
        }
        //Shifting the new byte to make space for the carry
        *byte <<= bits;
        //Applying carry
        *byte |= carry;
    }
    return bits;
}

const unsigned int calculate_unused_bits(const unsigned int segment_bit_size)
{
    return (CHAR_BIT - (segment_bit_size % CHAR_BIT)) % CHAR_BIT;
}

element_t *create_element(const unsigned char buffer[], const unsigned int byte_size,
                          const unsigned int unused_bits, const unsigned int bytes_skipped,
                          const unsigned char left_mask)
{
    element_t *element = (element_t *) malloc(sizeof(element_t));
    element->segment = malloc(byte_size);
    element->size = byte_size;
    element->unused_bits = unused_bits;
    memcpy(element->segment, &(buffer[bytes_skipped]), byte_size);
    //Zeroing the unused bits at the end of the segment
    element->segment[byte_size - 1] &= left_mask;
    return element;
}

//This method will split a buffer to segments of specific size in bits and it will return them as a list
//(each element contains the segment data, its size in bytes and the number of bits that are not used from the last byte)
//If the input buffer is less than the segment size, it will return one segment with all the data.
//The user can set the bit size of the first segment to be different than the rest using first_segment_bit_size > 0
node_t *segment(const unsigned char buffer[], const unsigned int buffer_bytes_size,
                const unsigned int segment_bit_size, const unsigned int first_segment_bit_size)
{
    if (buffer_bytes_size == 0)
    {
        fprintf(stderr, "%s: Bad value %u for 'buffer_bytes_size', it should be greater than 0"
                "\n\tIgnoring operation\n", __FUNCTION__, buffer_bytes_size);
        return NULL;
    }
    if (segment_bit_size == 0)
    {
        fprintf(stderr, "%s: Bad value %u for 'segment_bit_size', it should be greater than 0"
                "\n\tIgnoring operation\n", __FUNCTION__, segment_bit_size);
        return NULL;
    }

    node_t *head = NULL;

    const double char_bit = CHAR_BIT;
    const unsigned int first_segment_byte_size = (unsigned int) ceil(
            first_segment_bit_size / char_bit);
    if (first_segment_byte_size > buffer_bytes_size)
    {
        append(&head, create_element(buffer, buffer_bytes_size, 0, 0, UCHAR_MAX));
        return head;
    }

    unsigned char *temp_buffer = malloc(buffer_bytes_size);
    memcpy(temp_buffer, buffer, buffer_bytes_size);

    unsigned int bits_shifted = 0;
    unsigned int bytes_skipped = 0;

    if (first_segment_bit_size > 0)
    {
        const unsigned int first_segment_unused_bits = calculate_unused_bits(
                first_segment_bit_size);
        const unsigned int first_segment_byte_size_without_incomplete_byte =
                first_segment_bit_size / CHAR_BIT;

        const unsigned int first_segment_bits = CHAR_BIT - first_segment_unused_bits;
        const unsigned char left_mask = create_left_mask(first_segment_bits);

        append(&head, create_element(temp_buffer, first_segment_byte_size,
                                     first_segment_unused_bits, bytes_skipped, left_mask));

        bytes_skipped += first_segment_byte_size_without_incomplete_byte;

        if (bytes_skipped == buffer_bytes_size)
        {
            free(temp_buffer);
            return head;
        }
        if (first_segment_bits > 0 && first_segment_bits < CHAR_BIT)
        {
            bits_shifted += shift_left_char_array_n_bits(&(temp_buffer[bytes_skipped]),
                                                         buffer_bytes_size - bytes_skipped -
                                                         (bits_shifted / CHAR_BIT),
                                                         first_segment_bits);
        }
    }

    const unsigned int segment_byte_size = (unsigned int) ceil(segment_bit_size / char_bit);
    const unsigned int buffer_bits_size =
            (buffer_bytes_size - bytes_skipped) * CHAR_BIT - bits_shifted;
    const unsigned int segments_count = buffer_bits_size / segment_bit_size;

    if (segments_count == 0)
    {
        append(&head, create_element(temp_buffer, buffer_bytes_size - bytes_skipped, bits_shifted, bytes_skipped, UCHAR_MAX));
        free(temp_buffer);
        return head;
    }

    //Creating a mask where first n bits are 1s and the rest are 0s to zero the unused bits of the segment
    const unsigned int segment_unused_bits = calculate_unused_bits(segment_bit_size);
    const unsigned int last_segment_bits = CHAR_BIT - segment_unused_bits;
    const unsigned char left_mask = create_left_mask(last_segment_bits);
    const unsigned int segment_byte_size_without_incomplete_byte = segment_bit_size / CHAR_BIT;
    const unsigned int extra_bits = buffer_bits_size % segment_bit_size;

    unsigned int i;
    for (i = 0; i < segments_count; i++)
    {
        append(&head,
               create_element(temp_buffer, segment_byte_size, segment_unused_bits, bytes_skipped,
                              left_mask));
        bytes_skipped += segment_byte_size_without_incomplete_byte;

        if ((segments_count > 1 || extra_bits > 0) &&
            (last_segment_bits > 0 && last_segment_bits < CHAR_BIT))
        {
            bits_shifted += shift_left_char_array_n_bits(&(temp_buffer[bytes_skipped]),
                                                         buffer_bytes_size - bytes_skipped -
                                                         (bits_shifted / CHAR_BIT),
                                                         last_segment_bits);
        }
    }

    if (extra_bits)
    {
        const unsigned int last_segment_bytes_size =
                buffer_bytes_size - bytes_skipped - (bits_shifted / CHAR_BIT);
        const unsigned int unused_bytes_for_last_segment =
                segment_byte_size - last_segment_bytes_size;
        const unsigned int last_segment_unused_bits =
                segment_bit_size - (buffer_bits_size % segment_bit_size) + segment_unused_bits -
                (unused_bytes_for_last_segment * CHAR_BIT);
        append(&head, create_element(temp_buffer, last_segment_bytes_size,
                                     last_segment_unused_bits, bytes_skipped, UCHAR_MAX));
    }

    free(temp_buffer);
    return head;
}

Sample code that uses the function:

#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>

#include "libs/segmentation/segmentation.h"


// This application will create a char array of size BUFFER_BYTE_SIZE that contains random values
// and later it will split it in segments of size SEGMENT_BIT_SIZE.
// The first segment will be of size FIRST_SEGMENT_BIT_SIZE.

#define BUFFER_BYTE_SIZE 420
#define SEGMENT_BIT_SIZE 222
#define FIRST_SEGMENT_BIT_SIZE 11
#define POSSIBLE_VALUES 256

int main()
{
    srand(time(NULL));
    const unsigned int buffer_byte_size = BUFFER_BYTE_SIZE;
    fprintf(stdout, "Buffer Size: %uB\n", buffer_byte_size);
    const unsigned int segment_bit_size = SEGMENT_BIT_SIZE;
    fprintf(stdout, "Segment Size: %ub\n", segment_bit_size);
    const unsigned int first_segment_bit_size = FIRST_SEGMENT_BIT_SIZE;
    fprintf(stdout, "First Segment Size: %ub\n", first_segment_bit_size);
    unsigned char buffer[buffer_byte_size];
    unsigned int i;
    for (i = 0; i < buffer_byte_size; i++)
    {
        buffer[i] = (unsigned char) (rand() % POSSIBLE_VALUES);
    }
    char *buffer_bits = create_bit_representation_string(buffer, buffer_byte_size, 0);
    const size_t buffer_length = strlen(buffer_bits);
    fprintf(stdout, "\tBuffer: '%s'\n", buffer_bits);
    node_t *head = segment(buffer, buffer_byte_size, segment_bit_size, first_segment_bit_size);

    element_t *element = pop(&head);
    unsigned int bytes_skipped = 0;
    unsigned int segment_count = 0;
    unsigned int total_segment_bit_size = 0;
    while (element != NULL)
    {

        char *segment_bits = create_bit_representation_string(element->segment,
                                                              element->size,
                                                              element->unused_bits);
        const size_t segment_length = strlen(segment_bits);
        fprintf(stdout,
               "\t\tSegment %04u: Size in bytes %02u - Unused bits %04u - '%.*s'\n",
               ++segment_count,
               element->size, element->unused_bits,
               element->size * CHAR_BIT - element->unused_bits, segment_bits);
        if (segment_length == 0)
        {
            fprintf(stderr,
                    "Data validation failed."
                            "\n\tBuffer size in bytes %d"
                            "\n\tSegment size in bits %d"
                            "\n\tFirst Segment size in bits %d"
                            "\n\tFound empty segment\n",
                    buffer_byte_size, segment_bit_size, first_segment_bit_size);
            clear(&head);
            free(segment_bits);
            free(element->segment);
            free(element);
            free(buffer_bits);
            return EXIT_FAILURE;
        }
        for (i = 0; i < segment_length && bytes_skipped + i < buffer_length; i++)
        {
            if (segment_bits[i] != buffer_bits[bytes_skipped + i])
            {
                fprintf(stderr,
                        "Data validation failed."
                                "\n\tBuffer size in bytes %d"
                                "\n\tSegment size in bits %d"
                                "\n\tFirst Segment size in bits %d"
                                "\n\tPosition %u of the buffer"
                                "\n\tPosition %u of the segment\n",
                        buffer_byte_size, segment_bit_size, first_segment_bit_size, bytes_skipped + i, i);
                clear(&head);
                free(segment_bits);
                free(element->segment);
                free(element);
                free(buffer_bits);
                return EXIT_FAILURE;
            }
        }
        free(segment_bits);
        bytes_skipped += segment_length;

        const unsigned int current_segment_bit_size = ((element->size - 1) * CHAR_BIT) + CHAR_BIT - element->unused_bits;
        if (segment_length != current_segment_bit_size)
        {
            fprintf(stderr,
                    "Data validation failed."
                            "\n\tBuffer size in bytes %d"
                            "\n\tSegment size in bits %d"
                            "\n\tFirst Segment size in bits %d"
                            "\n\tCurrent Segment bit size (%u) not equal to its string representation (%lu)\n",
                    buffer_byte_size, segment_bit_size, first_segment_bit_size, current_segment_bit_size, segment_length);
            clear(&head);
            free(segment_bits);
            free(element->segment);
            free(element);
            free(buffer_bits);
            return EXIT_FAILURE;
        }
        total_segment_bit_size += current_segment_bit_size;

        free(element->segment);
        free(element);
        element = pop(&head);
    }

    free(buffer_bits);

    if (buffer_length != total_segment_bit_size) {
        fprintf(stderr,
                "Data validation failed."
                        "\n\tBuffer size in bytes %d"
                        "\n\tSegment size in bits %d"
                        "\n\tFirst Segment size in bits %d"
                        "\n\tTotal Segment bit size (%u) not equal to full string representation (%lu)\n",
                buffer_byte_size, segment_bit_size, first_segment_bit_size, total_segment_bit_size, buffer_length);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Full project and source code to segment buffer to parts of specific size in bits (8 downloads)


[JavaScript] Get values from URL parameter

The following code will get the query parameters of a URL and assign them to an object called QueryMap.

// This function is anonymous, is executed immediately and the return value is assigned to QueryMap.
var QueryMap = function () {
	var query_map = {};
	//The search property sets or returns the querystring part of a URL, including the question mark (?).
	//So we remove the question mark by removing the first characted of the string.
	var query = window.location.search.substring(1);
	var variables = query.split('&');
	for (var i = 0; i < variables.length; i++) {
		var position = variables[i].indexOf('=');
		var key = variables[i].substring(0, position);
		var value = variables[i].substring(position + 1);
		// If it is the first entry with this name
		if (typeof query_map[key] === "undefined") {
			query_map[key] = decodeURIComponent(value);
			// If it is the second entry with this name we change the value to an array of values
		}
		// If it is the second entry with this name we change the value to an array of values
		else if (typeof query_map[key] === "string") {
			var array = [query_map[key], decodeURIComponent(value)];
			query_map[key] = array;
		}
		// If it is the third or later entry with this name we just add to the array
		else {
			query_map[key].push(decodeURIComponent(value));
		}
	}
	return query_map;
}();

This code will handle cases where the equals sing (=) is part of the value of a variable.

Examples:

If the URL is http://example.com?a=1
Then QueryMap.a will contain value “1”.

If the URL is http://example.com?a=1&b=2
Then QueryMap.a will contain value “1” and QueryMap.b will contain value “2”.

If the URL is http://example.com?a=1=0001&b=2
Then QueryMap.a will contain value “1=0001” and QueryMap.b will contain value “2”.

If the URL is http://example.com?a=1=0001&b=2&b=0010
Then QueryMap.a will contain value “1=0001” and QueryMap.b will contain an array with the values “2” and “0010”.


[Video] Android OpenCV – Face Detection and Recognition Demo

Android OpenCV – Face Detection and Recognition Demo using Android NDK/JNI to load OpenCV library.

Google Play: https://play.google.com/store/apps/details?id=net.bytefreaks.opencvfacerecognition

Get it on Google Play

Our application is based on the ‘Face Detection’ sample of OpenCV. The sample that is available for download from http://sourceforge.net/projects/opencvlibrary/files/opencv-android/, you will notice that there are many versions there, we used version 2.4.11. Refer to this (http://docs.opencv.org/2.4/doc/tutorials/introduction/android_binary_package/O4A_SDK.html) introduction for more information.


Tail logs with color for Monolog

#1. Copy/paste the below lines in your .bashrc

tailf-with-colors () {
    if [ -z "$1" ] ; then
        echo "Please specify a file for monitoring"
        return
    fi

    tail -f $1 | awk '
                {matched=0}
                /INFO:/    {matched=1; print "\033[0;37m" $0 "\033[0m"}   # WHITE
                /NOTICE:/  {matched=1; print "\033[0;36m" $0 "\033[0m"}   # CYAN
                /WARNING:/ {matched=1; print "\033[0;34m" $0 "\033[0m"}   # BLUE
                /ERROR:/   {matched=1; print "\033[0;31m" $0 "\033[0m"}   # RED
                /ALERT:/   {matched=1; print "\033[0;35m" $0 "\033[0m"}   # PURPLE
                matched==0            {print "\033[0;33m" $0 "\033[0m"}   # YELLOW
        '
}

#2. Run source ~/.bashrc -- to reload 

#3. Run tailf-with-colors <filename>