Pages

Dec 19, 2011

Javascript check element visibility

The following function checks if a given element is within browser's viewport:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

Sample Usage

On this example I'll be loading iframes only when they are on the browsers viewport. For this to work I initially printed all iframe's without the SRC attribute. Instead, I used the REL attribute as a placeholder for the iframe destination:

    var my_interval = setInterval(checkIframesVisibility, 1000);

    function checkIframesVisibility()
    {
        $("iframe").each(function(i) {
            if (isScrolledIntoView($(this)))
            {
                if ($(this).attr('src') == "")
                {
                    $(this).attr('src', $(this).attr('rel'));
                    $(this).iframeAutoHeight({debug: false, diagnostics: false});
                }
            }
        });
    }

    function isScrolledIntoView(elem)
    {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
    }

PS: The iframeAutoHeight is a plugin that auto resizes the iframe to the content's height.

Hope you find this is useful!

Nov 10, 2011

Global Apache 404 Page

This will setup a single 404 page for all domains on your web server.

1st: create a fancy 404 page like this one:
2nd: put it somewhere on your server:
/etc/apache2/error-documents/404.html

3rd: edit your apache configuration (/etc/apache2/apache2.conf on ubuntu machines):
Alias /404 /etc/apache2/error-documents/404.html
ErrorDocument 404 /404

Nov 8, 2011

Linux jail/lock/chroot users to homedir


Jailing, Chrooting, Locking users/applications...



Yes, they do give it a lot of names... but if all you want to do is to create a user on your system and give him ssh/ftp access without exposing your whole system - therefore jailing him - just follow this steps. I promise it will take no more than 5 mins!


This as been tested by myself on Ubuntu 10.04


STEP 1
download & extract jailkit, then:
./configure
make
make install

STEP 2
set up the jail path:
sudo mkdir /jail
sudo chown root:root /jail

STEP 3
define the environment
sudo jk_init -v /jail basicshell
sudo jk_init -v /jail editors
sudo jk_init -v /jail extendedshell
sudo jk_init -v /jail netutils
sudo jk_init -v /jail ssh
sudo jk_init -v /jail sftp
sudo jk_init -v /jail jk_lsh

STEP 4
add a user
sudo adduser dummy
sudo jk_jailuser -m -j /jail dummy
sudo mkdir -p /jail/home/dummy
chown dummy:dummy /jail/home/dummy

VERIFY
/jail/etc/group should look like:
dummy:x:500:

/jail/etc/passwd should look like:
dummy:x:1001:500::/home/dummy:/bin/bash

Now login via ssh/sftp with the dummy user. You should see a small portion of a filesystem if you change directory do / but you won't be able to see the REAL system files.

Thanks to http://ubuntuforums.org/showthread.php?t=248724 !

Oct 6, 2011

Linux convert FLAC to MP3 under terminal

Using the terminal, navigate to your .flac folder.

Run the following command:

for file in *.flac; do flac -cd "$file" | lame -h - "${file%.flac}.mp3"; done

Note: You'll need both flac and lame installed (obviously).

If you need a more advanced script try this solution over linuxtutorialblog.com.

Oct 4, 2011

Allow symbolic links on Mac OS's native Apache

Edit:
/etc/apache2/users/<YOURUSER>.conf

Put:
<Directory "/Users/<YOURUSER>/Sites/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

Terminal colors on Mac OS

edit:
~/.bash_profile
put:
export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced

Jun 29, 2011

MySQL export to file

Export a query result to a file directly from MySQL.

First open mysql with "-s -t" arguments - this will force mysql to output without boxing characters:
mysql -s -t -u <user> <database_name>

Now:
SELECT * FROM table INTO OUTFILE '/path/to/file.txt'

It's all good, peace!

Typical MySQL encoding problem

Don't you just HATE encodings?

Ever wanted to insert something in MySQL and were 100% sure the text/database/table/fields were in UTF-8 and by some reason the text got all scrambled up?

This usually works for me:

mysql_query("SET NAMES 'utf8'");

Hope it helps!

Jun 17, 2011

jQuery preload images

Cool jquery image preload method:

(function($) {
 var imgList = [];
 $.extend({
  preload: function(imgArr, option) {
   var setting = $.extend({
    init: function(loaded, total) {},
    loaded: function(img, loaded, total) {},
    loaded_all: function(loaded, total) {}
   }, option);
   var total = imgArr.length;
   var loaded = 0;
   
   setting.init(0, total);
   for(var i in imgArr) {
    imgList.push($("")
     .attr("src", imgArr[i])
     .load(function() {
      loaded++;
      setting.loaded(this, loaded, total);
      if(loaded == total) {
       setting.loaded_all(loaded, total);
      }
     })
    );
   }
   
  }
 });
})(jQuery);
 
 
$(function() {
 
 $.preload([
  "http://farm3.static.flickr.com/2661/3792282714_90584b41d5_b.jpg",
  "http://farm2.static.flickr.com/1266/1402810863_d41f360b2e_o.jpg"
 ], {
  init: function(loaded, total) {
   $("#indicator").html("Loaded: "+loaded+"/"+total);
  },
  loaded: function(img, loaded, total) {
   $("#indicator").html("Loaded: "+loaded+"/"+total);
   $("#full-screen").append(img);
  },
  loaded_all: function(loaded, total) {
   $("#indicator").html("Loaded: "+loaded+"/"+total+". Done!");
  }
 });
 
});

From: http://ditio.net/2010/02/14/jquery-preload-images-tutorial-and-example/
Live example: http://ditio.net/demo/preloader/

jQuery "sleep" function plugin - doTimeout

jQuery doTimeout: Like setTimeout, but better!

It's really not a "sleep" function but it acts just like we want when we go "oh! I could really use a sleep function right now!"

$.doTimeout(3000,function(){
    alert('yeeey!');
});

Homepage: http://benalman.com/projects/jquery-dotimeout-plugin/
GitHub: http://github.com/cowboy/jquery-dotimeout

Jun 16, 2011

PHP5 Dynamically calling Classes and Methods

Easy peasy:

$class_name = 'NiceClass';
$method_name = 'niceMethod';
$arguments = array('a' => true, 'b' => 5);

if (class_exists($class_name)) {
  $class = new $class_name();
  if (method_exists($class, $method_name)) {  
    $class->$method_name($arguments);
  }
  
}

May 30, 2011

Linux change timezone

$ cd /etc/
$ ln -sf /usr/share/zoneinfo/Europe/Lisbon localtime

Apr 7, 2011

Array Distritos Portugal

Por vezes dá jeito:

$array = array(
            'aveiro' => 'Aveiro',
            'beja' => 'Beja',
            'braga' => 'Braga',
            'braganca' => 'Bragança',
            'castelo-branco' => 'Castelo Branco',
            'coimbra' => 'Coimbra',
            'evora' => 'Évora',
            'faro' => 'Faro',
            'guarda' => 'Guarda',
            'leiria' => 'Leiria',
            'lisboa' => 'Lisboa',
            'portalegre' => 'Portalegre',
            'porto' => 'Porto',
            'santarem' => 'Santarém',
            'setubal' => 'Setúbal',
            'viana-do-castelo' => 'Viana do Castelo',
            'vila-real' => 'Vila Real',
            'viseu' => 'Viseu',

            'outro-ilhas' => 'Outro (ilhas)',
        );

Mar 16, 2011

Linux Nautilus Quick Resize Images

sudo aptitude install nautilus-image-converter
and then:

Feb 3, 2011

Mac OS and XAMPP: conflicts with native PHP

My developments on my macbook have been on hold for quite some time now... Last time I used PHP on it, it was running Leopard and everything was running smooth. Today (with Snow Leopard), while performing a simple PHP task (using php-cli), it shouted the following error:

PDO Connection Error: SQLSTATE[HY000] [2002] No such file or directory

After more investigation then I'd like.. I found the problem.

The php-cli I was using was pointing to the OS's native php (which I've never used).

All I needed to do was:
$ mv /usr/bin/php /usr/bin/php-native
$ cd /usr/bin
$ ln -s /Applications/XAMPP/xamppfiles/php php

This way I kept a copy of OS's native PHP, and created a symlink to XAMPP's PHP.

Feb 1, 2011

php url-safe base64 encoding

Basically:
  • '+' is replaced by '-'
  • '/' is replaced by '_'(underscore)
  • '=' is replaced by '!'

function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

function urlsafe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

Jan 17, 2011

Cycle all class's wth JQuery

Teclas de Atalho: Percorrer classes com JQuery: "Para percorrer as classes de um elemento com JQuery, use o seguinte código: var elemento = $('div'); var classes = elemento.attr('class').sp..."