learning to program…properly

I get by in programming via experimentation and google. However, there are times where I wish I knew how to program more ‘proper’. I’ve been wanting to learn how to make iphone apps for some time now so thanks to davey I’ve been watching a few tutorial videos on objective-c. Many start with the basics which can be quite tedious, but I suffer through them to make sure I don’t miss any crucial information. Today I learned exactly what break & continue mean in the context of a for loop. I had an idea previously but never bothered to look up the formal definition. So lets for instance look at this for loop:

for (int i = 1; i < 5000; i++){
    if (i == 101)
    break;
    printf("The index value is %i\n",i);
}
This loop is super simple: it prints the value of i until i==101 when it completely drops out of the loop. On the other hand we have:
for (int i = 1; i < 5000; i++){
    if (i % 5. == 0)
    continue;
    printf("The index value is %i\n",i);
}

which says that if the remainder of i/5 is equal to 0, then consider this specific loop iteration finished and move on to the next one without executing any of the code below. The % sign here is known as the modulus operator.

In summary:

break;    //DROPS OUT OF THE FOR LOOP COMPLETELY
continue; //COMPLETES CURRENT ITERATION AND MOVES ON TO THE NEXT

bash math!

In doing some Kelvin-Helmholtz comparisons I have been trying to cook up a script that can stitch two movies together with ffmpeg. In order to determine how many frames I need I must do a simple subtraction in bash, but how?! Easy apparently…you just:

#!/bin/bash
BEG=10
END=400
NUM=$((END-BEG))
echo $NUM

and it will return the value 390. So how about that ffmpeg script?!

#!/bin/bash

FPS=12

BEG=10
END=50

DIR1=.
DIR2=.

PREFIX1=splash\_%04d.png
PREFIX2=splash\_%04d.png

MOV1=1.mov
MOV2=2.mov
FINAL=SIDEBYSIDE.mov

NUM=$((END-BEG))

if [ $END -gt 0 ]
  then
  PARAM="-vframes $NUM"
  else
  PARAM=""
fi

ffmpeg -start\_number $BEG -r $FPS -i $DIR1/$PREFIX1 $PARAM -vcodec qtrle $MOV1
ffmpeg -start\_number $BEG -r $FPS -i $DIR2/$PREFIX2 $PARAM -vcodec qtrle $MOV2

## SIDE BY SIDE ##
ffmpeg -i $MOV2 -vf "movie=$MOV1 [in1]; [in]pad=iw\*2:ih:iw:0[in0]; [in0][in1] overlay=0:0 [out]" -vcodec qtrle $FINAL
Here’s the end result:

bounding box for text in matplotlib

More often than not nowadays I find myself having to add text to my figures. The problem that often arise is how do I make it stand out? Creating a bounding box for the text is not necessarily straight forward and I’m tired of searching for it:
text(-7.5,7.5,DIRS[i],bbox={'edgecolor':'k', 'facecolor':color[i],
'alpha':0.5})

h5py to replace npz?!

Apparently .npz files have a limit of ~4GB, which can be a problem when dealing with large datasets ($$600^3$$), so how do I write binary files of this size?! Looks like I need to migrate to HDF5…lol; here’s an example for read/write similar to npz:

import h5py
a = np.random.rand(1000,1000)
f = h5py.File('/tmp/myfile.hdf5')
f['a'] = a # <-- Save
f.close()

now that will write the file, lets open it

import h5py
f = h5py.File('/tmp/myfile.hdf5')
b = f['a']
#b = b[()]
f.keys() #shows all values in the dataset
f.close()

but the odd thing is, you can’t directly access the data here by just ‘b’. Instead there is a ton of information attached like b.shape, b.dtype, etc etc, all found here. Instead, you simply have to use the command

b.value

and that will output the data of the file.


customizing matplotlib’s legend()

I am constantly needing to customize the legend() in python. Whether it be changing the marker size, the line width, or the fontsize I’m constantly looking things up. There’s an easy way to set this at the beginning of your script; as an example:
params = {'legend.fontsize' : 16,
'legend.linewidth' : 1.5,
'legend.markerscale' : 3}
rcParams.update(params)
You could easily add other options such as modifying the handlelen (line width), font, etc etc. All options can be found via matplotlib’s legend() api site.

random header images for homepage

PHP isn’t so bad once you get the hang of it! The use of the glob() function allowed me to query all images in a given folder, and stick them in an array. So now I can dynamically update my header images without having to mess with the PHP code itself. The important segment is found in header.php, or header-xxxx.php depending on what you’re calling:
<?php
$imgarray = glob("./wp-content/headers/homepage/\*.\*",1);
$cnt = count($imgarray);
$rn = rand(0,$cnt-1);
$img = $imgarray[$rn];
?>
FYI glob() requires an absolute path…so you can’t simply use the content_path() function as I was before. However, now I can drop all the images I want into wp-content/headers/homepage and they will automatically be added to the list of possible images. I just have to remember to crop them properly to 1040x250 or they’ll show up as their original size.

PHP is annoying

I wanted to randomize the header image for the gaming subcategory…talk about a pain in the neck! PHP seems to be pretty robust, but the syntax is quite different than either Python or C which I am used to. I had to change a few things, first up - category.php; I went from
get_header();
to
<?php
if ( is_category( 'Gaming' ) ) :
  get_header( 'gaming' );
elseif ( is_404() ) :
  get_header( '404' );
else :
  get_header();
endif;
?>
Apparently there are different methods of doing this with curly brackets, but this was the cleanest example I could find and it resembles python. It basically says to use header-gaming.php if the category matches “Gaming”. Next up was that file, which I just made a copy of header.php. I added this relavant code:
<?php
$url = content_url();
$img0 = $url . "/uploads/2013/06/cropped-ORIGINAL.jpg";
$img1 = $url . "/uploads/2013/06/cropped-KUNARK.jpg";
$img2 = $url . "/uploads/2013/06/cropped-VELIOUS.jpg";
$img3 = $url .
"/uploads/2013/06/cropped-arma3_e32013_screenshot_06-100041641-orig1.png";
$imgarray = array($img0,$img1,$img2,$img3);

$cnt = count($imgarray);
$rn = rand(1,$cnt-1);
$img = $imgarray[$rn];
//echo "selecting image " . $rn . " out of " . $cnt;
?>
This was a pain. The first line assigns the variable $url to the wordpress content directory as this is where the header images are currently stored. The next 4 lines combine that directory with the remaining image path. Next I add all of these images to an array called imgarray. I can then count how large that array is, generate a random number, then assign $img using the random number as an index for the $imgarray. Next is the HTML part that actually places the image:
<img src="<?php echo $img; ?>"...
which is pretty straight forward.

Next up: scanning a directory for a list of images and automatically adding them to an array as to make this process automatic. This will allow me to randomize each page with pretty pictures. Start with these stack overflow suggestions.


Progress bar….

I got tired of waiting for code to finish and having no idea how far along it was.  Stack exchange provided an elegant solution of which I modified:

 import time,sys

def update_progress(step,datalen):
 progress = float(step)/float(datalen)
 barLength = 10 # Modify this to change the length of the progress bar
 status = ""
 if progress < 0:
 progress = 0
 status = "Halt...rn"
 if step >= datalen-1:
 progress = 1
 status = "Done...rn"

block = int(round(barLength*progress))
 text = "rPercent: [%s] %2.2f%% %s" % ("#"*block +
"-"*(barLength-block),
 progress*100, status)
 sys.stdout.write(text)
 sys.stdout.flush()

datalen=150
 for i in range(datalen):
 time.sleep(0.1) #just to slow it down!
 update_progress(i,datalen)

UPDATE (10/31/13)

here’s a cython version:
 cdef void update_progress(int step, int datalen):
 cdef float progress = float(step)/float(datalen)
 cdef int barLength = 10 # Modify this to change the length of the
 progress bar
 status = ""
 if progress < 0:
 progress = 0
 status = "Halt...rn"
 if step >= datalen-1:
 progress = 1
 status = "Done...rn"

cdef int block = int(np.round(barLength*progress))
 text = "rPercent: [%s] %2.2f%% %s" % ("#"*block +
"-"*(barLength-block),
 progress*100, status)
 sys.stdout.write(text)
 sys.stdout.flush()