you are here: codestackercodes [RSS]

Tamanho mínimo da DIV

#container {
  min-height: 500px; /* isso o FF e outros conseguem exergar e aumentam quando necessário o tamanho da div */
}
html>body #container {height:auto;height:500px;} /* mas o IE não lê o min-height. E aumenta a div com o height. */

Hello Buddy

HelloBuddy.appController = SC.Object.create(
{
  greeting: "Hello Buddy!"
});

show hidden files in finder

to reverse, replaces YES by NO

defaults write com.apple.Finder AppleShowAllFiles YES
killall Finder

highlight active item in dock

for mac users. type in terminal

defaults write com.apple.dock mouse-over-hilte-stack -boolean YES

killall Dock

test

class Teste
  def teste
    "teste"
    Constant
  end
end

resize window bookmarklet

create a link with this:

javascript: resizeTo(800,600);

javascript: resizeTo(1024,768);

resize image

<?
////////////////////////////////////////////////////////////////////////////////////
// generate a croped-image from a picture
// source: http://mediumexposure.com/techblog/smart-image-resizing-while-preserving-transparency-php-and-gd-library
// resizes a image, without crop
// usage: resizeImage("test/6.jpg", "540", "720", true, "test/output.jpg")
////////////////////////////////////////////////////////////////////////////////////

function resizeImage( $file, $width = 0, $height = 0, $proportional = false, $output = 'file') {
	$info = getimagesize($file);
	$image = '';
	$final_width = 0;
	$final_height = 0;
	list($width_old, $height_old) = $info;
	if ($proportional) {
		if ($width == 0) $factor = $height/$height_old;
		elseif ($height == 0) $factor = $width/$width_old;
		else $factor = min ( $width / $width_old, $height / $height_old);  
		$final_width = round ($width_old * $factor);
		$final_height = round ($height_old * $factor);
	}
	else {
		$final_width = ( $width <= 0 ) ? $width_old : $width;
		$final_height = ( $height <= 0 ) ? $height_old : $height;
	}
	switch ( $info[2] ) {
		case IMAGETYPE_GIF:
			$image = imagecreatefromgif($file);
		break;
		case IMAGETYPE_JPEG:
			$image = imagecreatefromjpeg($file);
		break;
		case IMAGETYPE_PNG:
			$image = imagecreatefrompng($file);
		break;
		default:
			return false;
	}
        
	$image_resized = imagecreatetruecolor( $final_width, $final_height );
			
	if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
		$trnprt_indx = imagecolortransparent($image);

		if ($trnprt_indx >= 0) {
			$trnprt_color    = imagecolorsforindex($image, $trnprt_indx);
			$trnprt_indx    = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
			imagefill($image_resized, 0, 0, $trnprt_indx);
			imagecolortransparent($image_resized, $trnprt_indx);
		} 
		elseif ($info[2] == IMAGETYPE_PNG) {
			imagealphablending($image_resized, false);
			$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
			imagefill($image_resized, 0, 0, $color);
			imagesavealpha($image_resized, true);
		}
	}
	imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);    
        
	switch ( strtolower($output) ) {
		case 'browser':
			$mime = image_type_to_mime_type($info[2]);
			header("Content-type: $mime");
			$output = NULL;
		break;
		case 'file':
			$output = $file;
		break;
		case 'return':
			return $image_resized;
		break;
		default:
		break;
	}
	switch ( $info[2] ) {
		case IMAGETYPE_GIF:
			imagegif($image_resized, $output);
		break;
		case IMAGETYPE_JPEG:
			imagejpeg($image_resized, $output);
		break;
		case IMAGETYPE_PNG:
			imagepng($image_resized, $output);
		break;
		default:
			return false;
	}
	return true;
}
?>

resize image with crop

////////////////////////////////////////////////////////////////////////////////////
// generate a croped-image from a picture
// source: http://www.seaton-online.com/forum/index.php?showtopic=545
// usage: cropImage("300", "225", "test/5.jpg", "jpg", "test/output.jpg");
////////////////////////////////////////////////////////////////////////////////////

function cropImage($nw, $nh, $source, $stype, $dest) {
         $size = getimagesize($source);
         $w = $size[0];
         $h = $size[1];

          switch($stype) {
              case 'gif':
              $simg = imagecreatefromgif($source);
              break;
              case 'jpg':
              $simg = imagecreatefromjpeg($source);
              break;
              case 'png':
              $simg = imagecreatefrompng($source);
              break;
          }

          $dimg = imagecreatetruecolor($nw, $nh);
          $wm = $w/$nw;
          $hm = $h/$nh;
          $h_height = $nh/2;
          $w_height = $nw/2;

          if($w> $h) {
              $adjusted_width = $w / $hm;
              $half_width = $adjusted_width / 2;
              $int_width = $half_width - $w_height;
              imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
          } elseif(($w <$h) || ($w == $h)) {
              $adjusted_height = $h / $wm;
              $half_height = $adjusted_height / 2;
              $int_height = $half_height - $h_height;
              imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
          } else {
              imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
          }

          imagejpeg($dimg,$dest,80);
}

hello kitty em php

<?php

echo "hello kitty";

?>

new flash helper with prototype effects

create an application helper to manage your rails messages
concept by nando vieira [simplesideias.com.br]

  # paste application_helper.rb

  def flash_message 
    messages = ""
    [:notice, :info, :warning, :error].each {|type|
      if flash[type]
        messages += "<p class=\"#{type}\" id=\"alert\">#{flash[type]}</p>"
      end
    }    
    messages
  end

  ####################################


  # your layout 

  <%= flash_message %>
	
  <% content_tag :script, :type => "text/javascript" do %>
    $('alert').style.display = 'none';
    new Effect.Appear('alert', {duration: 3});
    setTimeout("new Effect.Fade('alert');", 10000);
  <% end %>

Phone.rb

Class form my CRM

class Phone
  attr_reader :country_code, :area_code, :number
  
  def initialize(country_code, area_code, number)
    @country_code, @area_code, @number = country_code, area_code, number
  end
  
  def ==(value)
    @country_code == value.country_code &&
    @area_code == value.area_code &&
    @number == value.number
  end
  
  def to_s
    @number ? "+#{@country_code} #{@area_code} #{@number}" : "n/a"
  end
end

undescored para CameCase em PHP

Transforma uma string usando underscores para CamelCase

$name = 'we_love_code';
preg_replace('/_([a-z])/e', 'strtoupper(\\1)', "_{$name}");

mysql one line all database backup

mysqldump --al-databases -u -p > backup.sql

activing php_auth on dreamhost

by default, dreamhost runs php as cgi.
the follow line switchs from cgi to apache module execution, supporting php_auth.

// create a .htaccess with this: 
AddHandler application/x-httpd-php .php

remove all movieclips

a simple sample

// 3 solutions

for (var i in holder) {
    if(typeof(holder[i])=="movieclip" && holder[i]._name.substr(0,4)=="foo_") {
           holder[i].removeMovieClip();
    }
}

for (var i=0;i<noOfclips;i++) {
    var clip=_root["mc"+i];
    clip.removeMovieClip();
}

for (var n in this) { 
    removeMovieClip(this[n]); 
}

Traduz textos usando o google

Traduz palavras/frases/textos usando a API do Google, usei aqui http://github.com/rafaelss/shoes-translator

require 'rest_client'
require 'json'
require 'cgi'

word = CGI.escape("hello world")
response = RestClient.get "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=#{word}&langpair=en%7Cpt"
json = JSON.parse(response)
status = json['responseStatus']
if status == 200
    puts json['responseData']['translatedText']
else
    puts "(#{responseStatus}) erro ao traduzir #{word}"
end

"hello world"

a hello world program in javascript

alert("hello world")

resets autoincrement (mysql)

ALTER TABLE tablename AUTO_INCREMENT = 1

Chronic-like in Portuguese

require "rubygems"
require "activesupport"
require "unicode"

class String
  def as_time
    str = self.dup
    str.downcase!
    str.squish!
    str = Unicode.normalize_KD(self).gsub(/[^\x00-\x7F]/n,'')
    
    now = Time.now

    if str == 'hoje'
      Date.today.to_time
    elsif str == 'agora'
      Time.now
    elsif str == 'amanha'
      Date.tomorrow.to_time
    elsif str == 'ontem'
      Date.yesterday.to_time
    elsif str == 'anteontem'
      2.days.ago
    elsif str == 'depois de amanha'
      2.days.from_now
    elsif str =~ /^proxim[oa] (semana|dia|mes|ano)$/
      case $1
        when 'semana' then now.next_week
        when 'dia' then Date.tomorrow.to_time
        when 'mes' then now.next_month
        when 'ano' then now.next_year
      end
    elsif str =~ /^(mes|semana|ano) que vem/
      case $1
        when 'mes' then now.next_month
        when 'semana' then now.next_week
        when 'ano' then now.next_year
      end
    elsif str =~ /^(mes|semana|ano) passad[ao]/
      case $1
        when 'mes' then now.last_month
        when 'semana' then now.beginning_of_week
        when 'ano' then now.last_year
      end
    elsif str =~ /^de (tarde|manha|noite)/
      case $1
        when 'noite' then now.beginning_of_day + 20.hours
        when 'tarde' then now.beginning_of_day + 15.hours
        when 'manha' then now.beginning_of_day + 9.hours
      end
    elsif str =~ /^daqui h?a pouco/
      1.hour.from_now
    elsif str =~ /^daqui(?: h?a)? ([0-9]+) (dias?|mes(?:es)?|semanas?|anos?|horas?|minutos?)/
      num = $1.to_i
      interval = $2.gsub(/e?s$/, '')

      names = {
        'dia' => :day,
        'mes' => :month,
        'semana' => :week,
        'ano' => :year,
        'hora' => :hour,
        'minuto' => :minute
      }
      
      num.send(names[interval]).from_now
    end
  end
end

validation sample

validates_format_of :company_url, :with => /((http|https):\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?)/ # valida URL

validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :on => :create, :message=>"has an invalid format" 
validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => 'email must be valid'
validates_format_of :login, :with => /\w+@\w+\.\w{2}/

Displaying Code 281 - 300 of 300 in total