you are here: codestackercodes [RSS]

hartija css print framework

http://code.google.com/p/hartija/

body { 
width:100% !important;
margin:0 !important;
padding:0 !important;
line-height: 1.4;
word-spacing:1.1pt;
letter-spacing:0.2pt; font-family: Garamond,"Times New Roman", serif; color: #000; background: none; font-size: 12pt; }

h1,h2,h3,h4,h5,h6 { font-family: Helvetica, Arial, sans-serif; }
h1{font-size:19pt;}
h2{font-size:17pt;}
h3{font-size:15pt;}
h4,h5,h6{font-size:12pt;}

code { font: 10pt Courier, monospace; } 
blockquote { margin: 1.3em; padding: 1em;  font-size: 10pt; }
hr { background-color: #ccc; }

img { float: left; margin: 1em 1.5em 1.5em 0; }
a img { border: none; }

a:link, a:visited { background: transparent; font-weight: 700; text-decoration: underline;color:#333; }
a:link[href^="http://"]:after, a[href^="http://"]:visited:after { content: " (" attr(href) ") "; font-size: 90%; }
a[href^="http://"] {color:#000; }

table { margin: 1px; text-align:left; }
th { border-bottom: 1px solid #333;  font-weight: bold; }
td { border-bottom: 1px solid #333; }
th,td { padding: 4px 10px 4px 0; }
tfoot { font-style: italic; }
caption { background: #fff; margin-bottom:2em; text-align:left; }
thead {display: table-header-group;}
tr {page-break-inside: avoid;} 

finding duplicates entries

having example in rails. from: http://blog.grayproductions.net/articles/five_activerecord_tips

duplicates = User.find( :all,
  :select     => "email, COUNT(email) AS duplicate_count",
  :conditions => "email IS NOT NULL AND email != ''",
  :group      => "email HAVING duplicate_count > 1"
)

count domain users using sql

from: http://www.mendable.com/sql-trick-where-are-your-users-from/

SELECT COUNT(*) AS Total, SUBSTRING_INDEX(email, '@', -1) AS Domain FROM users 
GROUP BY SUBSTRING_INDEX(email, '@', -1) ORDER BY COUNT(*) DESC LIMIT 10;

jquery fade and slide toggle plugin

from: http://www.position-absolute.com/articles/jquery-fade-and-slide-toggle-plugin/

jQuery.fn.fadeSliderToggle = function(settings) {
 	 settings = jQuery.extend({
		speed:500,
		easing : "swing"
	}, settings)
	
	caller = this
 	if($(caller).css("display") == "none"){
 		$(caller).animate({
 			opacity: 1,
 			height: 'toggle'
 		}, settings.speed, settings.easing);
	}else{
		$(caller).animate({
 			opacity: 0,
 			height: 'toggle'
 		}, settings.speed, settings.easing);
	}
};

// use: $('#my_div').fadeSliderToggle();

succ method

from: http://www.ruby-doc.org/core/classes/String.html#M000795

>> "abb".succ
=> "abc"
>> "1".succ
=> "2"
>> "1999zzz".succ
=> "2000aaa"
>> 

hirb example

to install:
gem install cldwalker-hirb --source http://gems.github.com

>> require 'hirb'
=> []
>> Hirb.enable
=> nil
>> Exam.find(:all, :limit => 5)
+----+----------+----------+----------+----------+---------+----------+------+
| id | title    | exam     | creat... | updat... | user_id | categ... | hits |
+----+----------+----------+----------+----------+---------+----------+------+
| 1  | Simul... | Simul... | 2009-... | 2009-... | 1       | 1        | 152  |
| 2  | Simul... | Simul... | 2009-... | 2009-... | 1       | 1        | 143  |
| 3  | Espec... | Espec... | 2009-... | 2009-... | 1       | 1        | 1089 |
| 4  | Espec... | Espec... | 2009-... | 2009-... | 1       | 1        | 80   |
| 5  | Espec... | Espec... | 2009-... | 2009-... | 1       | 1        | 40   |
+----+----------+----------+----------+----------+---------+----------+------+
5 rows in set
>>

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>

trabalho de criptografia do michel

public class trabalho {
	
	public static int gerencia_chave(String chave) { // retorna o ASCII do menor caracter da chave

		
		char[] curinga = chave.toCharArray();
		
		int min = 256;
		
		for (int k=0; k<curinga.length; k++) {
			if ((int) curinga[k] < min) { 
				min = curinga[k];
			}
		}
		
		return min;
		
	}
	
	public static String inverte(String string) { // inverte a string de trás pra frente

	    int i, len = string.length();
	    StringBuffer dest = new StringBuffer(len);

	    for (i = (len - 1); i >= 0; i--){
	    	dest.append(string.charAt(i));
	    }
	    	
	    return dest.toString();
	  }
	
	public static void criptografa (String string, String chave) {

		char[] lista = string.toCharArray();
		String holder = "";
		
		for (int i = 0; i<lista.length; i++){
			
			int novochar = (int) lista[i] + gerencia_chave(chave) - 65; 

			holder += (char) novochar;
		}
		System.out.println(string + " = " + inverte(holder));
	}
	
	public static void descriptografa (String string, String chave) {

		char[] lista = string.toCharArray();
		String holder = "";
		
		for (int i = 0; i<lista.length; i++){
			
			int novochar = (int) lista[i] - gerencia_chave(chave) + 65; 

			holder += (char) novochar;
		}
		System.out.println(string + " = " + inverte(holder));
		
	}
	
	public static void main(String args[]) {
		
		criptografa("Computador", "Dinei");
		
		descriptografa("urgdwxsprF", "Dinei");
		
		criptografa("Computação", "Dinei");
		
		descriptografa("ræêdwxsprF", "Dinei");
		
		criptografa("Programador", "Dinei");
		
		descriptografa("urgdpdujruS", "Dinei");
		
		criptografa("Programação", "Dinei");
		
		descriptografa("ræêdpdujruS", "Dinei");
		
		criptografa("ABCDEFGHIJKLMNOPQRSTUVWXYZ ÁÉÍÓÚÂÊÃÕ 0123456789 abcdefghijklmnopqrstuvwxyz áéíóúâêãõ", "Dinei"); // teste básico: não retorna nenhum caracter não imprimível

	}
}

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
Displaying Code 141 - 160 of 301 in total