Friday, December 18, 2015

Windows DOS Batch: Rename all the folders numerically

The following snippet renames all folders in current directory to numbers starting from 0.

set i=0
for %f in (*) do (set /A "i=i+1")

References

Thursday, December 17, 2015

Python: Call Function From String

Somehow there is a need to make calls from string, i.e. I have the name of the functions in string, now I need to call that function from that string.

import inspect

class API:
    def f1(self):
        print "f1 is called from",self.__class__.__name__
        
def f1():
    print "f1 is called from",inspect.stack()[0][3]
        
api = API()
a = "f1"

globals()[a]()
getattr(api,a)()

The results should be

f1 is called from f1
f1 is called from API

Tuesday, December 1, 2015

Windows cmd: Create Incrementing Folders With For Loop

Bring up Windows console with Win+R and cmd, type

for /l %i in (1,1,100);do mkdir %i

Syntax

      FOR /L %%parameter IN (start,step,end) DO command 

Notice that, double percentage symbol is used for batch file, and on the command line

%%parameter : A replaceable parameter:
                 in a batch file use %%i (on the command line %i)

References

Tuesday, November 3, 2015

HTML5 Image Capture on Mobile and Server-side Handling

Since on mobile browsers, the video tag is not fully supported, one need to use the following to take a shot.

<button onclick="$('#inputv').trigger('click');">Take a shot</button>
<input type="file" id="inputv" name="inputv" accept="image/*" capture="camera" style="display:none">
<div id="f_img"></div>

And on js side, you need to utilize FileReader object to read the image shot from it. The image is stored in base64 string format, which can be added to src attribute to show the image on the page.

window.addEventListener("DOMContentLoaded", function(){
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        $("#inputv").change(function(e){
                var f = e.target.files[0];
                //  alert(f.size);
                var reader = new FileReader();
                reader.onload = function(e) {
                    //write your code to process the image
                    $("#f_img").html('<img src="' + e.target.result + '">');
                };
                reader.readAsDataURL(f);
        });
    // Great success! All the File APIs are supported.
    } else {
        $("#notice").append('The File APIs are not fully supported in this browser.');
    }

The image in base64 can be uploaded to the server part using input tag with the type as text. A possible server-side handling witten in python can be the following:

from flask import request

image = request.form['image']

def save_b64(image):
    img_str = str(image) #unicode to str obj
    head="data:image/jpeg;base64,"
    if str(img_str).startswith(head):
        l = len(head)
        img_str = img_str[l:]
    
    import time
    timestr = time.strftime("%Y%m%d%H%M%S")
    path = "image/capture-" + timestr + ".jpg"
    try:
        img = open(path, "wb")
        img.write(img_str.decode('base64'))
        img.close()
        return path
    except Exception as e:
        return False

Monday, April 20, 2015

OpenCV: Passing Parameters to Trackbar Callback Function

OpenCV Trackbars are created through the system call like below, with a callback function which is called when there is any change on the bar.

createTrackbar("Dummy Trackbar Name", "Dummy Window Name", &pos, max_pos, onTrackbarChange, &u);

Here pos is the pass-by-ref variable that records the current position of trackbar, max_pos denotes its maximum possible value of this variable that the bar can handle. onTrackbarChange is the callback function u is the user data that is passed to the callback function.

onTrackbarChange is prototyped as

void onTrackbarChange(int, void*);

Since there is only limited parameters, the data has to be packaged into an object or a structure like this,

typedef struct {
 Mat* grad;
 Mat* dst;
 Mat* detected_edges;
 int* pos;
 int* ratio;
 int* kernel_size;
 char* window_name;
} userdata;

Of cource, the members within userdata structure could be whatever type you might need. Here I grab a snippet of what my demo is using. Thus you can implement the callback function on demand.

void onTrackbarChange(int pos, void* ud) {
 userdata u = *static_cast(ud);

 // Reduce noise with a kernel 3x3
 blur(*u.grad, *u.detected_edges, Size(3, 3));

 // Canny detector
 Canny(*u.detected_edges, *u.detected_edges, *u.pos, *u.pos*(*u.ratio), *u.kernel_size);

 // Using Canny's output as a mask, we display our result
 *u.dst = Scalar::all(0);

 (*u.grad).copyTo(*u.dst, *u.detected_edges);
 imshow(u.window_name, *u.dst);
        waitKey(0);
}

Friday, April 11, 2014

CentOS: Compiling and Installing PHP Imagick extension

Requirements

This extension requires ImageMagick version 6.2.4+ and PHP 5.1.3+. Package information is here, Imagick package on PECL

The normal procedure goes like this

    wget http://pear.php.net/go-pear.phar
    php go-pear.phar
    pecl install imagick

While it throws the following error,

    No releases available for package "pecl.php.net/imagick"
    install failed

So I decided to compile directly from source (in order to generate imagick.so)

    yum install php-pear php-devel
    yum install ImageMagick ImageMagick-devel
    yum install pcre-devel
    wget http://pecl.php.net/get/imagick-3.2.0RC1.tgz
    tar -xvf imagick-3.2.0RC1.tgz
    cd imagick-3.2.0RC1/
    phpize
    ./configure
    make
    make test
    make install

Remember to turn on the extension in the php configuration file.

    vim /etc/php.ini
        extension = imagick.so

References

Sunday, April 6, 2014

PHP: Get Token From Dropbox

Just use Dropbox for serving the files/pictures of your personal site or startup site, for free use, there is up to 16 GB maximum capacity, far enough to carry out your idea.

First off, we will sign up for Dropbox, start a application that uses Core API. This will give you the key and secret. Prepare it in a file named config.json.

{
  "key": "your-dropbox-api-key",
  "secret": "your-dropbox-api-secret"
}

Download you PHP sdks from here: https://www.dropbox.com/developers/core/sdks/php. Unzip and put in your project directory.

Prepare you getdbxtoken.php as following, this will load dropbox php library along with you config in the previous json file.

<?php
require_once "dropbox-php-sdk-1.1.3/lib/Dropbox/autoload.php";
use \Dropbox as dbx;

        $appInfo = dbx\AppInfo::loadFromJsonFile("config.json");
        $webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
        $authorizeUrl = $webAuth->start();
        echo "1. Go to: " . $authorizeUrl . "\n";
        echo "2. Click \"Allow\" (you might have to log in first).\n";
        echo "3. Copy the authorization code.\n";
        $authCode = \trim(\readline("Enter the authorization code here: "));

        list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
        print "Access Token: " . $accessToken . "\n";

        $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
        $accountInfo = $dbxClient->getAccountInfo();
        print_r($accountInfo);

?>

Run the script from command line:

chmod a+x getdbxtoken.php
php -q getdbxtoken.php

You will need to input auth code in order to get the token, which is obtained by following the link and give the allow permission (go to the brower and [login in] and grant that). While you get that auth code, copy it to your command line, press enter. It will throw you the access token. In consequence, we tried to open a new client and fetch the account info, which is returned as an array, printed to your screen later.

1. Go to: https://www.dropbox.com/1/oauth2/authorize?locale=&client_id=SOME_CLIEND_ID&response_type=code
2. Click "Allow" (you might have to log in first).
3. Copy the authorization code.
Enter the authorization code here: 

To note once obtained the token, you might want to save it to a secure place since you don't need to log in (auth) again. Next time you can just build client by the token, and connect directly to dropbox.