@Andy_McPalace http://t.co/BkcDzHSK

Finding file under cursor on VIM

Working in a big project, I had the problem that the scripts included lots of files and used a lot of templates that were called programatically, because of that, I was looking for files a lot.

Searching the vim wiki I found a script that is used to find files inside a directory and choose the file you need. I’ve modified it a bit and finally it looks like this:

"Function for finding files
" Find file in current directory and edit it.
function! Find(name)
  let l:list=system("find . -name '".a:name."*[htm|html|php]' | grep -v .svn | perl -ne 'print \"$.\\t$_\"'")
  let l:num=strlen(substitute(l:list, "[^\n]", "", "g"))
  if l:num < 1
    echo "'".a:name."' not found"
    return
  endif
  if l:num != 1
    echo l:list
    let l:input=input("Which ? (CR=nothing)\n")
    if strlen(l:input)==0
      return
    endif
    if strlen(substitute(l:input, "[0-9]", "", "g"))>0
      echo "Not a number"
      return
    endif
    if l:input<1 || l:input>l:num
      echo "Out of range"
      return
    endif
    let l:line=matchstr("\n".l:list, "\n".l:input."\t[^\n]*")
  else
    let l:line=l:list
  endif
  let l:line=substitute(l:line, "^[^\t]*\t./", "", "")
  execute ":e ".l:line
endfunction
command! -nargs=1 Find :call Find("<args>")

The function is used doing something like

:Find <name>

The real thing here is to map a keybiding to search the file where the cursor is standing.. Like this:

:nmap <leader>f "zyiw:exe "Find ".@z.""<CR>

This way, with the keystroke “\f” you start the function searching for the word under cursor. Be aware that the keybinding changes if you modified your leader variable.

Recursive search inside files in vim

I just knew about the :vimgrep command inside vim, it is used to search a pattern in a filetree, us it like:

vimgrep /$.ajax/ **/*.html

then, you can check all the files that resulted of that command with:

:copen

BTW: vim is *awesome*!

Encrypt files in unix

As my memory sucks I have an encrypted file that stores passwords. Of course I need a secure way to do that.. what I do is this:

To encrypt:

openssl des3 -salt -in passwords -out passwords.crypt

To decrypt:

openssl des3 -d -salt -in passwords.crypt -out passwords

UPDATE:
I just realized that VIM has a built in way to encrypt and decrypt files that works great.. You must use the -x option

vim -x [filename]

Css tip of the day

*{ outline: none; }

It get rids of the stupid border around inputs

I love VIM

If you read the previous post, you will understand why this is awesome

:%s/^\(\d\d\)\(.*\)/<li><a href="images\/membranofonos\/\1.jpg">\2<\/a><\/li>

Renaming files in batch

Yesterday I stumbled upon a problem renaming files. I had a really big bunch of files named as [numbers]{abigpileofcharacters}.jpeg/gif. I needed to work with filenames more standarized, something like [numbers].jpeg/gif.

First problem was finding a way to rename those files. I thought of a piped mv command with some sed or something like that, but it got complicated.. so I asked on my favorite IRC channel and a friend told me about a script that comes inside a Debian package when you install XFCE, that script is named prename, it is a modification of an old script named rename. It’s written in perl and its Awesome!

It’s awesome because of this:

perl renamer.pl 's/(\d+).*\.([\w]+)/$1.$2/' *.*

If you dont understand that, go read about Regular expressions. The script renames the files according to the regular expressions using $1 and $2. That’s just awesome.

As the Debian package is not usable in OsX I’ve uploaded to GitHub and BitBucket.

Resizing images in CakePHP

Developing an app with CakePHP, I needed to resize an image in order to show them in the frontend. It’s a common task in nowadays webs so it shouldn’t be complicated. Doing a short google search i found this solution that it’s fine, but it didn’t work on the version of CakePHP I’m using, so, i’ve modified a bit and now I can use it. It’s a helper that you can use directly on the template, so it’s really handy.

The helper is in charge of resizing the images and save them in the cache directory /webroot/image_cache, you must be sure this directory exists.

/app/views/helpers/resizer.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php  
class ResizerHelper extends AppHelper { 
    var $helpers = array('Html'); 
    var $cacheDir = 'image_cache'; // relative to IMAGES_URL path 
 
    /** 
     * Automatically resizes an image and returns formatted IMG tag 
     * 
     * @param string $path Path to the image file, relative to the webroot/img/ directory. 
     * @param integer $width Image of returned image 
     * @param integer $height Height of returned image 
     * @param boolean $aspect Maintain aspect ratio (default: true) 
     * @param array    $htmlAttributes Array of HTML attributes. 
     * @param boolean $return Wheter this method should return a value or output it. This overrides AUTO_OUTPUT.
     * @return mixed    Either string or echos the value, depends on AUTO_OUTPUT and $return. 
     * @access public 
     */ 
    function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {
        $types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type
        $fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS;
        $url = $fullpath.$path; 
        if (!($size = getimagesize($url)))  
            return; // image doesn't exist 
        if ($aspect) { // adjust to aspect. 
            if (($size[1]/$height) > ($size[0]/$width))  // $size[0]:width, [1]:height, [2]:type
                $width = ceil(($size[0]/$size[1]) * $height); 
            else  
                $height = ceil($width / ($size[0]/$size[1])); 
        } 
        $relfile = $this->webroot.$this->cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file 
        $cachefile = $fullpath.$this->cacheDir.DS.$width.'x'.$height.'_'.basename($path);  // location on server 
        if (file_exists($cachefile)) { 
            $csize = getimagesize($cachefile); 
            $cached = ($csize[0] == $width && $csize[1] == $height); // image is cached 
            if (@filemtime($cachefile) < @filemtime($url)) // check if up to date 
                $cached = false; 
        } else { 
            $cached = false; 
        } 
        if (!$cached) { 
            $resize = ($size[0] > $width || $size[1] > $height) || ($size[0] < $width || $size[1] < $height);
        } else { 
            $resize = false; 
        } 
        if ($resize) { 
            $image = call_user_func('imagecreatefrom'.$types[$size[2]], $url); 
            if (function_exists("imagecreatetruecolor") && ($temp = imagecreatetruecolor ($width, $height))) {
                imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
              } else { 
                $temp = imagecreate ($width, $height); 
                imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
            } 
            call_user_func("image".$types[$size[2]], $temp, $cachefile); 
            imagedestroy ($image); 
            imagedestroy ($temp); 
        }          
        return $this->output(sprintf($this->Html->tags['image'], $relfile, null), $return); 
    } 
}
?>

So, in order to use it in the template you must add it to the controller

1
var $helpers    = array('Html', 'Form', 'Session', 'Resizer');

Finally, in the template

1
<?php echo $this->Resizer->resize($image['url'], 150, 150, true) ?>

Markup.io :: Web app for doing annotation over webpages

I’ve just discovered reading Online [spanish] a web app to do annotations over web pages as if they were there all the time

To use it, you just need to go to the official site and copy the bookmark button

It works as a charm and it’s really usefull when working with a client if you want to point things out or he wants to make you see anything odd. You can circle things, do arrows, write text or just draw :P

Flash block in Safari

Ok, It’s been a while since I’m noticing my mac’s battery is not lasting the time I want. Doing some checks using Activity Monitor, o found out that flash spends almost 20% of the microprocesor, and that’s just when I’m on newspapers sites with all those crappy ads. So, doing some google search, I found ClickToFlash a small plugin for safari that works as flashblock for firefox.

Things I liked the most:

  • Posibility to view youtube videos in quicktime instead of the standard flash player
  • Whitelists for sites that you want to execute flash without asking
  • It’s just a standard .pkg file
  • It’s Open Source!

Uploading images using CakePHP

First of all, I need to say that I’m not even close to being a good CakePHP developer. Not even a PHP developer. I Don’t even like it very much, but well, somethings we have to do things we don’t like. Having that said, this is a little snippet I use on my CakePHP controllers to upload images, save them, and add the URL into the database table. In the view, I use a file input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function __upload($file_array){
    $file = new File($file_array['tmp_name']);
    $file_base = pathinfo($file_array['name']);;
    $ext = strtolower($file_base['extension']);
    if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'png') {
        $this->Session->setFlash('You may only upload image files.');
        $this->render();
    } else {
        $data = $file->read();
        $file->close();
        $full_path = '/upload_images/'.$file_array['name'];
        $file = new File(WWW_ROOT.$full_path, true);
        $file->write($data);
        $file->close();
         return $full_path;
    }
    return 'Ouch!';
}

If you copy and paste this example, the images are uploaded to wwwroot/upload_images/

This snippet it’s not just for uploading images, it can be used with any file type

Continue Reading »