Tuesday, June 24, 2014

Highlight code on blogger


So if you've run into this post, you must be wondering how to apply code highlighting on popular blogging platform blogger.com and you're at the right place. Before we go to instructions here are some examples of highlighted code just for motivation. If you like it, you can proceed and integrate this handy feature.  
some random c code ...

// little c code
int main(int argc, char argv**) {
 int i;
 for(i = 0; i <= 99; i++)
   fprintf(stdout, "%d\n", i);

 return 0;
}

Or some php code:


require_once 'Zend/Uri/Http.php';

namespace Location\Web;

interface Factory
{
    static function _factory();
}

abstract class URI extends BaseURI implements Factory
{
    abstract function test();

    /**
     * Returns a URI
     *
     * @return URI
     */
    static public function _factory($stats = array(), $uri = 'http')
    {
        echo __METHOD__;
        $uri = explode(':', $uri, 0b10);
        $schemeSpecific = isset($uri[1]) ? $uri[1] : '';
        $desc = 'Multi
line description';

        // Security check
        if (!ctype_alnum($scheme)) {
            throw new Zend_Uri_Exception('Illegal scheme');
        }

        return [
            'uri'   => $uri,
            'value' => null,
        ];
    }
}
some html code ...

<!DOCTYPE html>
<title>Title</title>

<style>body {width: 500px;}</style>

<script type="application/javascript">
  function $init() {return true;}
</script>

<body>
  <div checked="" class="title" id="title">
Title</div>
<!-- here goes the rest of the page -->
</body>


css code ...

@media screen and (-webkit-min-device-pixel-ratio: 0) {
  body:first-of-type pre::after {
    content: 'highlight: ' attr(class);
  }
  body {
    background: linear-gradient(45deg, blue, red);
  }
}

If you like what you see, and want to implement this feature, follow few simple steps (by the way it's very easy):

On the left menu on your blogger account go to templates click "edit html" just before closing of:
</header> tag add 3 lines (2 comment lines are there just to remind you what you've added and where, in case you what to remove code highlighting later...)


<!-- highlight.js -->
<link href='http://yandex.st/highlightjs/8.0/styles/default.min.css' rel='stylesheet'/>
 <script src='http://yandex.st/highlightjs/8.0/highlight.min.js'/>
<script>hljs.initHighlightingOnLoad();</script>
<!-- / highlight.js -->


click "save template" and you're done.

Ok what now? How do I use code highlighting?

It turn out it's quite easy, when you want to highlight some code, first you write it in WYSIWYG editor like you normally would and then switch to HTML mode of editing post, and put around your code html tags like this:

<pre><code> your code ... </pre></code>


And your code will be heightlighted. If you want to specify what language you use in your code, that can be done like this:


<pre><code class='hljs python'> your code here ... </pre></code>


where instead of python you add language of your choosing. Here are some possible languages of highlight.js lib:

python
c
cpp
java
objectivec
cs (C#)
sql
lisp
xml
css
scala
go
javascript
json
bash
...

There are others as well. For full list of code markup highlighting check out: highlightjs test page
Also visit http://highlightjs.org/ for more info and details about some advanced features of this library.

happy coding!   

Sunday, June 22, 2014

Ubuntu 13.10 cursor blinking and printscreen multiple screens

After upgrading to Ubuntu 13.10 you may have a problem with cursor blinking all the time this upgrade also affects printscreen it renders as if you have two monitors. So what's the problem with cursor blinking and printscreen multiple monitors?

Well it's due to multiple monitor settings, to fix this you have to go to settings -> displays and turn of unknown display. Here is how to do that:

1. select unknown display (click on it)

Here is the image of unknown display selected:


After you've selected unknown display, turn it off by switching ON/OF scroll option. When you do that here is how your settings window should look:


That's it now your print screen should work fine, there should not be any multiple windows and cursor blinking will stop. That's it, you're done.

If you have problem with Ubuntu 13.10 vertical scrolling check out this post: Ubuntu 13.10 vertical scrolling fix

Enable edge vertical scrolling in ubuntu 13.10 and 14.04

First thing you notice after upgrade to Ubuntu 13.10 is that edge vertical scrolling doesn't work, to be precise there is still option to make it work, just by default this isn't the case anymore. So what should I do to return my edge vertical scrolling option?

Well it turns out that it's really simple to make it work again, what you have to do is to uncheck two finger scroll under settings -> Mouse and Touchpad

Here is the image before unchecking two finger scrolling option, to enable edge vertical scrolling uncheck two finger scroll option.


By the way two finger scroll option means that you scroll by fixing one finger on touch pad  and using other to scroll, anywhere on the tuchpad surface. This actually can work very well so before switching back, give it a chance! 

Saturday, June 21, 2014

Recover lost files from usb stick


Sometimes when we make a mistake and accidentally delete files from usb drive or do a partition format of usb, most people believe that it's for good and that we should let go, but in some cases files can be successfully recover and the day could be saved!

Generally there are two cases we could try recovery and hope for the best are:

1. When files were removed
2. We've done flash disk (flash usb stick) format [quick format only]
3. USB Flash stick format was performed [quick format] and some other files were written afterwards.
If you are happy user of Ubuntu OS (or unix in general), and  your case is one of the 3. files most likely could be recovered. In case 1 and 2 files can most certainly be recovered and in case 3 we depend on luck (we hope that files that were copied afterwards were not written on sectors containing files we are hoping to recover.

To do this under linux there is one wonderful little program called foremost which does the job.
Here is a download link: http://foremost.sourceforge.net/

Under Ubuntu you can install this via aptitude, to install type following in command shell:

$ sudo apt-get install foremost

Now that you have this program ready and installed, you can start recovery of your lost files.
For more info on command options of this wonderful software check out man pages

$ man foremost 

Ok now in order to recover lost files all you need to do is plugin you usb flash stick, find right device mapping and start recovery. To find usb device mapping (if you've already mounted usb flash stick onto file system) type

$ sudo mount 

Output should show mapping of all devices to corresponding paths on files system. For me when I insert flash usb, mapping of devices is /dev/sdc

Now to recover all lost files using foremost you enter following command:

$ sudo foremost -i /dev/sdc -o /media/recovery/ 

If you want to recover specific files (naturally faster) add -t flag with specified file type:
For instance if you want to recover all of office files like *.ppt *.doc other Word or Access files
you can use following command

$ sudo foremost -i /dev/sdc -o /media/recovery/ -t ole

Upon execution program will start to recover desired files and progress will be shown in terminal
like so:

Processing: /dev/sdc
|*****************************************************************************|

Now that file recovery is done you look into the magic hat and see what it brings you, if you're in luck (for case 3.) files should be recovered under /media/recovery/ path. Keep in mind that foremost runs under root privileges so you'll have to change the ownership of recovery folder in order to copy recovered files. Under recovery folder you'll see audit.txt file which contains results of foremost recovery. Output looks something like this:

Foremost version 1.5.7 by Jesse Kornblum, Kris Kendall, and Nick Mikus
Audit File

Foremost started at Sat Jun 21 22:37:38 2014
Invocation: foremost -i /dev/sdc -o /media/ddr/recover/ -t ole 
Output directory: /media/ddr/recover
Configuration file: /etc/foremost.conf
------------------------------------------------------------------
File: /dev/sdc
Start: Sat Jun 21 22:37:38 2014
Length: 7 GB (8004304896 bytes)

Num Name (bs=512)       Size File Offset Comment 

0: 00396638.ole       8 KB  203079117  
1: 00397608.ole       8 KB  203575709  
2: 00556587.ole     378 KB  284972979  
3: 10493472.xls      41 KB 5372657664  
4: 14399168.doc     396 KB 7372374016  
5: 14399968.doc      83 KB 7372783616  
6: 14400160.doc      45 KB 7372881920  
7: 14400672.doc     134 KB 7373144064  
8: 14400960.doc      18 KB 7373291520  
9: 14401056.doc      23 KB 7373340672  
10: 15154976.doc      78 KB 7759347712  
11: 15155200.doc      79 KB 7759462400  
12: 15155424.doc      80 KB 7759577088  
13: 15155648.doc      82 KB 7759691776  
14: 15155872.doc      85 KB 7759806464  
15: 15156096.doc      87 KB 7759921152  
16: 15156320.doc      87 KB 7760035840  
17: 15156608.doc      89 KB 7760183296  
18: 15156832.doc      90 KB 7760297984  
19: 15157056.doc      90 KB 7760412672  
20: 15157280.doc      90 KB 7760527360  
21: 15157504.doc      90 KB 7760642048  
22: 15157728.doc      91 KB 7760756736  
23: 15157952.doc      91 KB 7760871424  
24: 15158176.doc      92 KB 7760986112  
25: 15158400.doc      93 KB 7761100800  
26: 15158624.doc      93 KB 7761215488  
27: 15543062.ole       8 KB 7958048205  
28: 15544040.ole       8 KB 7958548893  
Finish: Sat Jun 21 22:43:38 2014

29 FILES EXTRACTED

ole:= 29
------------------------------------------------------------------

So I've been able to extract 29 ole files which is great considering I was in case 3 scenario of this tutorial.

Also keep in mind that best way to copy recovered files is via command shell using cp command and view them later as standard user. (Because when trying to access file directory in my case /recovery/doc gui based file system navigator shows as if doc is not a directory and it is, you can see it via terminal. To workaround this you copy files via terminal to some other location like:

we are at /recovery/doc/ path.

$ sudo mkdir -p /home/username/recovered_files/
$ sudo cp *.* /home/username/recovered_files/

And that's it now all of your recovered files are in /home/username/recovered_files directory (substitute username with your own username)

Hope this helps I've done some amazing job at recovery using this simple method, it's efficient and it works well.

Good luck at file recovery and check out post on how to make a bootable usb stick under linux




Make bootable usb under linux

Intro 

if you want to create bootable usb stick (pen drive) keep reading, first we will present a general overview of procedure and then step by step instructions with possible errors you could bump into along the road. Users who have done format of their usb flash sticks should proceed to part 2 of this tutorial (creating bootable usb stick using unetbootin

The general procedure 

requirements:
1. usb flash stick with sufficient memory space.
2. iso image of windows or linux depending what OS you want install on host machine.

general procedure:
1. Format your usb stick with FAT32 , FAT file system. (see formating usb stick under linux bellow for instructions how to do that)
2. using unetbootin program make your usb flash stick bootable.
3. boot from usb stick (see boot from usb)
4. install windows or linux OS (this is quite straight forward process once you boot from usb)

possible errors:
1. ISO file is corrupted and you need to download another ISO file image.
2. unetbootin finished creating bootable flash stick, but flash stick won't boot
        2a. If there is a boot manager screen of unetbootin but it won't boot, it's probably problem with ISO file so you need to find another working ISO image and redo the procedure. 
        2b. If there is no boot manager screen poping then usb is not bootable, try another usb port.



Format usb stick under linux 

There are a few ways to make this work, here are some of them starting from the easiest method. 

Format usb stick under linux Ubuntu

This method works for ubuntu distro of linux (they made it very simple *user friendly, hence it's so popular)
1. plug in you usb flash stick 
2.  find your disks application and open it. Here is how it looks like: 
click on disks icon

3. When you open disks app find your usb flash disk under "disk drives" like on image bellow:
4. Important: In order to format you usb flash drive it shouldn't be mounted onto file-system, by default it is, so you need to click stop sign and this will unmount usb flash drive from file system. You will know it's unmounted by checking In use status, see the image (it should say In use: NO) 

5. Click that settings icon like pointed on image under step 3. and select "FORMAT..." option. This will bring new window and with format options, see next image
6. Under erase leave it quick (don't overwrite existing data) 
Slow means that system will do full format in sense that every single bit of memory will be overwritten with zero. under Type select "compatible with all system devices (FAT)" and fill in last field Name whatever you want, it's name of your flash stick with you mount it. Next you click format and prompt window will ask you whether you are sure you want to format and you hit "FORMAT" 
(tip bellow explains that if you use quick format of data previously saved can be extracted with some recovery tools unless overwritten, so if you want to give your flash to another user consider full format. For our use this will not be necessary.)

Here is an image of prompt dialog: 
Click format button
If you've selected quick format process should finish in a second. And that should be it, you're done with format of your usb stick. This is the the easiest way and it's for users using Ubuntu linux distro.
If you're not using Ubuntu, bellow is another way via command shell. But before that, if you don't unmount your usb from file system, the error will be presented like on image bellow: 
If this happens you've forgot to unmount your usb, go back to step 4. 

Format usb stick under linux (In general all distros)

Before we could format usb stick, we need to find device path mapping of our usb flash stick. To do this type open your command shell (press CTRL+ALT+T) and type in: sudo fdisk -l like on image bellow:


Remeber to do this as super user (root) otherwise you won't be able to see disk partitions. Hence sudo.
The output should be something like on image (depending on your partition tables and devices) 

/dev/sdc1 is the device mapping of usb under my linux distro.
So this output will give you information of device mapping and mine is /dev/sdc1, mapping of your device will be something else perhaps /dev/sd[xa][xb] where [xa] is letter [a-z] number of hd devices on system, and [xb] is a number of partition.

We will need this information, so we can format our flash stick latter on. Now we need to unmount flash usb stick from file system, but before we do that, we should figure out what is the device -> file system mapping of usb. You can find this information by typing sudo mount command via command shell.

$ sudo mount 

Here is the image of output from my system, on yours it will be different but essentially what we need.
if device is mounted onto file system, you will see something like this. 


Once you've found this information (notice you see here mapping of device as well /dev/sdc[x] but if device is not mounted by default we wouldn't know what the mapping is before checking fdisk -l output)

On the image we see that mount path is /media/ddr/bootablefla (essentially it's shorten name of usb stick if name is too long). When you figure out what's the mounted device path, we can unmount device from file system. 

1. Unmount device from file system like so: 

$ sudo umount /media/ddr/bootablefla 

Where after umount you type your own mounted device path. After this step we can format usb stick. 

2. format usb stick. 

To format usb stick, you will need device mapping path and we've found for me it's /dev/sdc1 using fdisk -l command. 

To format usb stick, type command (in command shell) 

$ sudo mkfs.vfat /dev/sdc1

Here is the image of output: 


Note: if you haven't done umount from file system (of usb) error will on output and then you should go back to step 1. 

Just to give you some more options, here are some of other file system types, we've done format using FAT file-system.

mkfs.cramfs   mkfs.ext3     mkfs.ext4dev  mkfs.msdos
mkfs.bfs      mkfs.ext2     mkfs.ext4     mkfs.minix    mkfs.vfat

msdos is FAT32 file system.
ext2,ext3,ext4 linux file systems.
vfat is FAT file system. 
So now you're done with usb flash stick format, now you can make your bootable flash disk. Keep reading.

Other ways to format usb are by using gparted but that won't be covered in this tutorial. 


Creating bootable usb stick using unetbootin

in order to create bootable usb, you'll need one little program called unetbootin. You can download program from here http://unetbootin.sourceforge.net/

When you've downloaded your linux version of unetbootin, you should make it executable by assigning +x permissions to the binary file. (extension is .bin) 

To do this find the path where you've downloaded your unetbootin and execute following command:

$ chmod +x filename (where filename shoud be unetbootin filename ... for me it's unetbootin-linux-608.bin

Now you can start unetbootin using command: 

$ ./unetbootin-linux-608.bin &



You'll be asked for root access (root password and you type in yours) now application will run and it will look like something like this:

Now you should select diskimage iso path, click "..." and select your ISO image you've downloaded earlier. When you select your ISO image path, make sure type is USB DRIVE and Drive is set to your device path (it should auto detect all required fields) then you click "OK". 

After that you'll have to wait for some time until unetbootin copies all the image data to USB stick. Process looks like this: 



You hit exit, and that's it, you have bootable flash stick! 

So when the process finishes, you've done it! That's all there is to it. Now you have a bootable usb flash stick (pen drive) or what ever you call it. To boot from you usb keep reading this tutorial, it will be explained as well (but shortly).

Boot from USB

1. stick in your usb flash stick into usb port. 
2. restart your computer
3. when computer restarts start pressing "ESC" keyboard button (depending on laptop or pc there will be diferent keys most likely ESC, F2, F6, DELETE   

On some laptops pressing ESC gives you possibility to choose booting device for one instance and that's great just select your usb device and hit "ENTER" 

Otherwise you'll have to make a usb flash stick device a priority in BIOS under boot settings. When you do that, remeber to save settings in BIOS. Also don't mess around with other settings. Next time you restart if there is bootable flash stick plugged in, computer will recognize it and start boot process.

That's pretty much it. Hope you find this article / tutorial helpful. Good luck! 
  
  

Tuesday, April 15, 2014

PI approximation using Monte Carlo method - html5 canvas illustration

Just for fun I've coded simple Monte Carlo PI approximation illustrated with html5 canvas.

Here is full working example on jsfiddle: http://jsfiddle.net/yLmtp/

How it works?

Assuming we have a unit square

unit square
 If we draw circle inside the square with radius
1/2 we know that the area of that particular circle is AreaC  = radius^2 * PI = (1/2)^2 * PI = 1/4 * PI. Also area of unit circle is AreaS = 1^2 = 1

Finally if we calculate ratio of two areas we have AreaC/AreaS = (1/4 * PI) / 1 = 1/4 * PI

Ok, so ratio between areas is 1/4* PI but if we multiply above result by 4 we have exactly PI.

This is how we are going to approximate number PI, by calculating ratio between circle and square and multiplying that result by 4. 





What is the method?

We are going to generate new random (pseudorandom) point Ai(x,y) in each iteration within limits of our square and then we are going to observe will that point fall within the circle also or not. In case it does fall within the area of the circle we increase CA counter by 1 (CA++) otherwise we don't increase CA counter. Also in each iteration we increase SA counter by 1 (SA++) 

The more iterations (randomly generated points we have) more the ratio should converge to 1/4 * PI and since we just want to approximate number PI in each iteration we multiply result by 4.   


This method is very slow, how fast result converges to PI depends on how "random" are pseudorandom numbers generated by software and number of iterations.

The code is not optimized at all, it could be quicker, but that wasn't the intention. 

Here is full working example on jsfiddle: http://jsfiddle.net/yLmtp/

Friday, August 2, 2013

Creative use of google maps API


Google maps API provides an amazing api with great features web developers can build on to.
Here I'll present an idea I've used to build site tara smestaj mainly using google map api.

Tara smestaj is site oriented towards accommodation advertising but in a rather creative way. First of all my region is well know by tourism, it has some wonderful places to visit and enjoy in. I'm from Bajina Basta a city under mountain Tara separated from Bosnia by a river Drina, our most treasured river. (if you ever come here, try fly fishing). So the point here is that this is a place with a lot of natural wonders (see the picture bellow)

A view from one of many sites-seeing places on mountain Tara,
you can see Drina River in background.
Given we have all of this natural wonders it would be naive just to advertise accommodation in no reference to other places you can see. So the main idea is to build site which will promote tourism of Bajina Basta, but provide information for tourist not only of accommodation but also of places and sites they could visit along the way. The whole google map is integrated in site background and visitors while crawling the site can see all other attractive location relative to a position on a map.

In this way if a tourist (first timers) stumble upon a site they can explore more of a places they could see, for instance if someone chooses one accommodation over other, that could be because they know a sport fields is near the place they are staying or other could look for something else based on their on interest.

I'll share with you another interesting thing that happened just another day, my city (or town to be more precise since it has a population around 15k people) is famous by a house built on a rock of River Drina.

A house built upon a rock on river Drina. Amazing idea.
And since there is a marker of this house on tara smestaj site, a journalist from national tv called me and said that he had seen a site and is interested in doing an interview with an owner of the house. I was amazed how he stumbled upon my site since it is active somewhat over a month, but it seams that the information provided on site (about accommodation) is easy to navigate and trustworthy. (Actually he mentioned something of that kind). Of course I've gave the information of the owner (after contacting the owner) to the journalist and hopefully they'll mange to work out the interview. Anyways it's amazing yet unexpected thing that happened but all due to idea that didn't focus only to accommodation advertising...

Feel free to explore Tara smestaj and in some other post I'll add some programming details of how it all works.