you are here: codestackercodes [RSS]leozera [RSS]

listing files in a directory with rails

@files = Dir.glob("public/files/*")

for file in @files
    puts file
end

cross-browser transparency using css

.class {  
    filter:alpha(opacity=50);  
    -moz-opacity:0.5;  
    -khtml-opacity: 0.5;  
    opacity: 0.5;  
}

email regex

validates_format_of :email, 
:with => /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/, 
:message => "is invalid" 

list all jquery function with firebug

$(document).ready(function() { jQuery.fn.each( function(i) { console.log(i); }); });

jquery twitter

http://ralphwhitbeck.com/content/binary/twitter-json-jquery.html

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script>
	$(document).ready( function() {
	
		var url = "http://twitter.com/status/user_timeline/RedWolves.json?count=3&callback=?";
		$.getJSON(url,
        function(data){
			$.each(data, function(i, item) {
				$("img#profile").attr("src", item.user["profile_image_url"]); 
				$("#tweets ul").append("<li>" + item.text.linkify() + " <span class='created_at'>" + relative_time(item.created_at) + " via " + item.source + "</span></li>");
			});
        });
	});
	
	String.prototype.linkify = function() {
		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
    return m.link(m);
  });
 }; 
  function relative_time(time_value) {
	  var values = time_value.split(" ");
	  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	  var parsed_date = Date.parse(time_value);
	  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  delta = delta + (relative_to.getTimezoneOffset() * 60);
	  
	  var r = '';
	  if (delta < 60) {
	    r = 'a minute ago';
	  } else if(delta < 120) {
	    r = 'couple of minutes ago';
	  } else if(delta < (45*60)) {
	    r = (parseInt(delta / 60)).toString() + ' minutes ago';
	  } else if(delta < (90*60)) {
	    r = 'an hour ago';
	  } else if(delta < (24*60*60)) {
	    r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	  } else if(delta < (48*60*60)) {
	    r = '1 day ago';
	  } else {
	    r = (parseInt(delta / 86400)).toString() + ' days ago';
	  }
	  
	  return r;
}
function twitter_callback ()
{
	return true;
}

</script>	
</head>
<body>
	<div id="tweets">
		<img id="profile">
		<ul></ul>
	</div>
</body>
</html>

short css

body {
	background: #[hex-color] url([image URL]) [repeat] [attachment] [position];
}

p {
	font: [style] [variant] [weight] [size]/[line-height] [family], [family];
}

cool link effect with css

a {
	background-color:#fff;
	border-width:1px;
	border-style:solid;
	border-bottom-color:#aaa;
	border-right-color:#aaa;
	border-top-color:#ddd;
	border-left-color:#ddd;
	border-radius:3px;
	-moz-border-radius:3px;
	-webkit-border-radius:3px;
	-webkit-box-shadow:2px 2px 2px #bbb;
	
	padding: 10px;
}
a:hover {
	border-top-color:#aaa;
	border-left-color:#aaa;
	border-right-color:#ddd;
	border-bottom-color:#ddd;
	-webkit-box-shadow:0 0 0;
}

short url in wordpress with tinyurl

paste the function in function.php file and call in you template with:

<?php echo 'ID)).'">short url'; ?>

<?php

function getShortUrl($url) {
  $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
  return $tinyurl;
}

?>

cool newsticker using jquery

from http://benjaminsterling.com/blog-news-ticker/

<html>
	<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
        <script type="text/javascript">
			var height = 0;
			var to = null;
			var theAnimation;
			var newsScroller;
			$(document)
			.ready(function(){
				newsScroller = $('#newsScroller');
				
				var curSet = newsScroller
				.prev()
					.addClass('ns')
				.end()
				.wrap('<div>')
				.parent()
					.addClass('ns')
				.end()
				.wrap('<div>')
				.children()
				.slice(0,4)
				.each(function(){
					height += $(this).outerHeight(true);
				});
				
				theAnimation = function(){
					if( !newsScroller.is(':animated') ){
						newsScroller.animate({top:-height},1000,function(){
							height = 0;
							curSet = newsScroller
							.append(curSet)
							.css('top',0)
							.children()
							.slice(0,4)
							.each(function(){
								height += $(this).outerHeight(true);
							});
						});
					}
				};
				
				to = setInterval(theAnimation,4000);
				
				newsScroller.bind('mouseenter',function(){
					clearInterval(to);
				})
				.bind('mouseleave',function(){
					theAnimation();
					to = setInterval(theAnimation,4000);
				});
			});
		</script>
        <style media="screen, projector">
			h3#newsScrollerTitle{
				margin:0;
				padding:0;
				font:bold 14px/1.2 Georgia, "Times New Roman", Times, serif;
			}
			dl#newsScroller{
				font:normal 11px/1.4 Arial, Helvetica, sans-serif;
				padding:0;
				margin:0;
			}
			dl#newsScroller dt{
				font-weight:bold;
			}
			dl#newsScroller dd{
				padding:0 0 0 11px;
				margin:0;
			}
			dl#newsScroller dd p{
				padding:0;
				margin:0 0 11px 0;
			}
			dl#newsScroller dd + dd{
				padding:0 0 0 22px;
			}
			
			h3#newsScrollerTitle.ns{
				padding:5px 11px;
				border:1px solid #B18C58;
				border-bottom:none;
				background:#beb677;
				width:278px;
			}
			div.ns{
				padding:11px;
				border:1px solid #B18C58;
				border-top:none;
				background:#E8E4B4;
				width:278px;
				height:300px;
				position:relative;
				overflow:hidden;
			}
			div.ns div{
				height:300px;
				overflow:hidden;
			}
			div.ns dl{
				position:relative;
				top:0;
			}
			div.ns dl dt,
			div.ns dl dd{
				position:relative;
			}
		</style>
    </head>
    
    <body>
    	<h3 id="newsScrollerTitle">Our News</h3>
    	<dl id="newsScroller">
        	<dt>Web Tech November Meetup Presentation</dt>
            <dd>
                <p>Last night I had the opportunity to speak at the Web Tech 
                November Meetup in Baltimore about jQuery.  I focused mainly 
                on traversing since I believe once you fully grasp some of 
                the built in jQuery traversing methods you can do just about 
                anything using jQuery and do it easily.</p>
                <p>Preparations<br/>
                I spent about three weeks getting [...]</p>
			</dd>
            <dd>Tuesday, November 25th, 2008</dd>
            <dd>Posted in Presentations, Web Development, jQuery | Edit | No Comments »</dd>
            
        	<dt>Slide in tab window using jQuery</dt>
            <dd>
                <p>Say you want to wanted to put little tabs - you know, the 
                ones like what you get from a lawyer or a realestate again to
                point out important things - off the side of your page so that
                your users can click, bring that tab into view to see what 
                important information you want [...]</p>
            </dd>
            <dd>Thursday, November 20th, 2008</dd>
            <dd>Posted in Tips, Tutorials, Web Development, jQuery | Edit | 5 Comments »</dd>
            
        	<dt>Better jQuery Code #2</dt>
            <dd>
                <p>In a follow up to my Better jQuery Code #1 post I will be
                writing about some other small items that I have found to make
                my code better and more readable.</p>
                <p>Chaining<br/>
                Chaining is one of the most beautiful and time save pieces of 
                code structure that jQuery brought to the game, the problem is
                is [...]   </p>         
            </dd>
            <dd>Sunday, November 16th, 2008</dd>
            <dd>Posted in Tips, Web Development, jQuery | Edit | 2 Comments »</dd>
            
        	<dt>Better jQuery Code #1</dt>
            <dd>
                <p>I've been wanting to write some jQuery tips for a while now 
                and just never know what to really say until I saw Marc 
                Grabanski's 5 Tips for Better jQuery Code.  Although I have 
                tips, I don't think I have any that are Earth shattering or ones
                that I can rank higher then the other, [...]</p>            
            </dd>
            <dd>Saturday, November 15th, 2008</dd>
            <dd>Posted in Tips, Web Development, jQuery | Edit | 8 Comments »</dd>
            
        	<dt>Release of jQuery UI v1.5</dt>
            <dd>
                <p>Well ladies and gents, it is finally here! Mark June 9th, 2008
                as the day the web got better, jQuery's long awaited release of 
                it's UI library update is here. Flushed with many bug fixes, a bunch
                of really good examples, many new features and a theme builder.</p>
                When jQuery UI first came out [...]            
            </dd>
            <dd>Monday, June 9th, 2008</dd>
            <dd>Posted in jQuery | Edit | 2 Comments »</dd>
        </dl>
    </body>
</html>

parse relative date

var d = Date.parse("Fri, 4 Dec 2008 15:13:00 +0000");
var dateFunc = new Date();
var timeSince = dateFunc.getTime() - d;
var inSeconds = timeSince / 1000;
var inMinutes = timeSince / 1000 / 60;
var inHours = timeSince / 1000 / 60 / 60;
var inDays = timeSince / 1000 / 60 / 60 / 24;
var inYears = timeSince / 1000 / 60 / 60 / 24 / 365;

if(Math.round(inSeconds) == 1){
	document.write("1 second ago");
}
else if(inMinutes < 1.01){
	document.write(Math.round(inSeconds) + " seconds ago");
}

else if(Math.round(inMinutes) == 1){
	document.write("1 minute ago");
}
else if(inHours < 1.01){
	document.write(Math.round(inMinutes) + " minutes ago");
}

else if(Math.round(inHours) == 1){
	document.write("1 hour ago");
}
else if(inDays < 1.01){
	document.write(Math.round(inHours) + " hours ago");
}

else if(Math.round(inDays) == 1){
	document.write("1 day ago");
}
else if(inYears < 1.01){
	document.write(Math.round(inDays) + " days ago");
}

else if(Math.round(inYears) == 1){
	document.write("1 year ago");
}
else {
document.write(Math.round(inYears) + " years ago");
}

Google::Translate, A Simple API In Ruby

install:
sudo gem install google_translate

require 'rubygems'
require 'google_translate'

tr = Google::Translate.new

# from English to Spanish

tr.translate :from => "en", :to => "es", :text => "Hello, World!"
 => Hola, Mundo!

truncate text at a word boundry

# in application_helper


def snippet(text, wordcount, omission)
 text.split[0..(wordcount-1)].join(" ") + (text.split.size > wordcount ? " " + omission : "")
end


# example


snippet(@post.body, 50, "#{link_to "More...", @post}")

created_today?

  class Book < ActiveRecord::Base
    def created_today?
      self.created_on.to_date == Date.today
    end
  end

jquery mouseover/mouseout effect in link

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ui.jquery.com/latest/ui/effects.core.js"></script>
<script type="text/javascript">
$(document).ready( function() {		
	$(".link").mouseover(function() {
		$(this).animate({ color: "#022d3f" }, 1000);
	}).mouseout(function() {
		$(this).animate({ color: "#ccc" }, 1000);
	}) 
</script>

ExternalInterface sample

import flash.external.ExternalInterface;
 
function alert() {
	ExternalInterface.call("alert", "Only a test");
}

mybt.onRelease = function(){
	alert();
}

cross-browser rounded corners using css

ie sux (again)

border-radius: 9px; /* CSS 3 */
-o-border-radius: 9px; /* Opera */
-icab-border-radius: 9px; /* iCab */
-khtml-border-radius: 9px; /* Konqueror */
-moz-border-radius: 9px; /* Firefox */
-webkit-border-radius: 9px; /* Safari */

fixing the ridiculous auto-padding in ie (win) submit buttons

ie sux!

input { overflow: visible; }

simple jquery equal columns plug-In

/** 
 * @projectDescription	Simple Equal Columns
 * @author 	Matt Hobbs
 * @version 	0.01 
 */
jQuery.fn.equalCols = function(){
	//Array Sorter

	var sortNumber = function(a,b){return b - a;};
	var heights = [];
	//Push each height into an array

	$(this).each(function(){
		heights.push($(this).height());
	});
	heights.sort(sortNumber);
	var maxHeight = heights[0];
	return this.each(function(){
		//Set each column to the max height

		$(this).css({'height': maxHeight});
	});
};
//Usage

jQuery(function($){
	//Select the columns that need to be equal e.g

	$('div.column').equalCols();
	$('#col1,#col2,#col3').equalCols();
});

formatting a drive as fat32 in mac os

diskutil partitionDisk /Volumes/leozera 1 MBRFormat "MS-DOS FAT32" "leozera" 100%

batch convertion: ffmpeg avi -> mpg

#!/bin/sh
for f in *.flv;
do
echo "Processing $f"
ffmpeg -i "$f" -target ntsc-dvd "${f%.flv}.mpg"
done
Displaying Code 141 - 160 of 270 in total