Posts arquivos para janeiro, 2012

31jan2012

Creating debian packages with setup.py

por em Sem categoria
(0) comentários

ncode@karoly:~/Devel/sica$ sudo apt-get install devscripts

ncode@karoly:~/Devel/sica$ find *
src
src/plugin
src/plugin/sica.py
src/sica.conf

ncode@karoly:~/Devel/sica$ vim setup.py
#!/usr/bin/python
from distutils.core import setup
setup(name='sica',
      version='0.0.1',
      description='Collectd Plugin',
      author='Juliano Martinez',
      author_email='juliano@martinez.io',
      url='https://github.com/ncode/sica',
      data_files=[('/etc/collectd/plugins.d', ['src/sica.conf']),
                        ('/usr/share/collctd/modules', ['src/plugin/sica.py'])]

      )

ncode@karoly:~/Devel$ mv sica sica-0.0.1
ncode@karoly:~/Devel$ cd sica-0.0.1/

ncode@karoly:~/Devel/sica-0.0.1$ dh_make -n -s
Maintainer name : Juliano Martinez
Email-Address : juliano@martinez.io
Date : Tue, 31 Jan 2012 11:23:04 -0200
Package Name : sica
Version : 0.0.1
License : gpl3

Using dpatch : no
Type of Package : Single
Hit <enter> to confirm:
Currently there is no top level Makefile. This may require additional tuning.
Done. Please edit the files in the debian/ subdirectory now. You should also
check that the sica Makefiles install into $DESTDIR and not in / .

ncode@karoly:~/Devel/sica-0.0.1$ dch -i

sica (0.0.1-1) stable; urgency=low

      * Building to stable

-- Juliano Martinez <juliano@martinez.io>  Tue, 31 Jan 2012 11:27:45 -0200

sica (0.0.1) unstable; urgency=low

  * Initial Release.

 -- Juliano Martinez <juliano@martinez.io>  Tue, 31 Jan 2012 11:23:04 -0200

ncode@karoly:~/Devel/sica-0.0.1$ vim debian/control
Source: sica
Section: python
Priority: extra
Maintainer: Juliano Martinez <juliano@martinez.io>
Build-Depends: debhelper (>= 7.0.50~)
Standards-Version: 3.8.4
Homepage: https://github.com/ncode/sica

Package: sica
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: Collectd Plugin
 Collectd Plugin

ncode@karoly:~/Devel/sica-0.0.1$ dpkg-buildpackage -us -uc -rfakeroot

ncode@karoly:~/Devel/sica-0.0.1$ dpkg -c ../sica_0.0.1_amd64.deb
drwxr-xr-x root/root         0 2012-01-31 11:23 ./
drwxr-xr-x root/root         0 2012-01-31 11:23 ./etc/
drwxr-xr-x root/root         0 2012-01-31 11:23 ./etc/collectd/
drwxr-xr-x root/root         0 2012-01-31 11:23 ./etc/collectd/plugins.d/
-rw-r--r-- root/root       344 2012-01-31 00:29 ./etc/collectd/plugins.d/sica.conf
drwxr-xr-x root/root         0 2012-01-31 11:23 ./usr/
drwxr-xr-x root/root         0 2012-01-31 11:23 ./usr/share/
drwxr-xr-x root/root         0 2012-01-31 11:23 ./usr/share/pyshared/
-rw-r--r-- root/root       247 2012-01-31 11:23 ./usr/share/pyshared/sica-0.0.1.egg-info
drwxr-xr-x root/root         0 2012-01-31 11:23 ./usr/share/collctd/
drwxr-xr-x root/root         0 2012-01-31 11:23 ./usr/share/collctd/modules/
-rw-r--r-- root/root       949 2012-01-31 01:20 ./usr/share/collctd/modules/sica.py
drwxr-xr-x root/root         0 2012-01-31 11:23 ./usr/share/doc/
drwxr-xr-x root/root         0 2012-01-31 11:23 ./usr/share/doc/sica/
-rw-r--r-- root/root       190 2012-01-31 11:23 ./usr/share/doc/sica/README.Debian
-rw-r--r-- root/root      1815 2012-01-31 11:23 ./usr/share/doc/sica/copyright
-rw-r--r-- root/root       143 2012-01-31 11:23 ./usr/share/doc/sica/changelog.gz
drwxr-xr-x root/root         0 2012-01-31 11:23 ./usr/share/python-support/
-rw-r--r-- root/root        40 2012-01-31 11:23 ./usr/share/python-support/sica.public

 

Permalink | Leave a comment  »

30jan2012

Logging with Graylog2, GELF and logix

por em Sem categoria
(0) comentários

"Graylog2 is an open source log management solution that stores your logs in ElasticSearch. It consists of a server written in Java that accepts your syslog messages via TCP, UDP or AMQP and stores it in the database. The second part is a web interface that allows you to manage the log messages from your web browser. Take a look at the screenshots or the latest release info page to get a feeling of what you can do with Graylog2..."

http://graylog2.org/about

"Syslog is okay for logging system messages of your servers. Use it for that. GELF instead is great for logging from within applications. It is a good practice to send GELF messages directly from your existing logging classes so it is very easy to integrate into existing applications. You could use GELF to send every exception as a log message to your Graylog2 server. You don't have to care about timeouts, connection problems or anything that might break your application from within your logging class because GELF is sent via UDP. The disadvantage of this fire and forget principle is of course that no one guarantees that your GELF message will ever arrive. I'd say that important messages will just occur again. TCP support for those who like it is coming though..."

https://github.com/Graylog2/graylog2-docs/wiki/GELF

So... I wrote a tool to send syslog events to graylog2 via AMQP :D

https://github.com/ncode/logix
https://github.com/locaweb/logix

 

Permalink | Leave a comment  »

29jan2012

Kernel Log: Coming in 3.3 (Part 1) – Networking

por em Sem categoria
(0) comentários

"Version 3.3 of the Linux kernel offers another way to team multiple Ethernet devices. Support for ‘Open vSwitch’, a virtual network switch that was specifically developed for virtualised environments, has also been added. Byte Queue Limits are designed to reduce the latencies that cause the much-discussed ‘buffer bloat’..."

http://www.h-online.com/open/features/Kernel-Log-Coming-in-3-3-Part-1-Networking-1421959.html

Permalink | Leave a comment  »

26jan2012

Princípio de carousel de imagens com jQuery – Criando um plugin simples

(0) comentários

Nos últimos meses, tenho usado bastante o efeito de carousel.
Como todo programador, me incomodo de ter que ‘me repetir’. Ou ter que repensar uma lógica que já resolvi uma vez.

Nem sempre ‘temos tempo’ de parar, analisar e otimizar oque estamos fazendo.
Porém, devemos fazer isso.

Fiz vários tipos de carouseis, porém por serem diferentes um dos outros, e alguns possuirem algumas peculiaridades, configurações extras, estilizações fora dos padrões, acabei fazendo os meus próprios códigos, e não usando nenhum plugin pronto.

Nesse post, vou deixar o start de um plugin de jQuery, que rapidamente fiz aqui.
Muitas melhorias precisam ser feitas, como:
-> possibilitar scroll vertical
-> não limitar a marcação a ser usada
-> permitir uso do easing..

e por ai vai.. nisso, eu acabaria recriando o cycle(ou chegando perto do efeito Hz dele). Não é essa a intenção.
Até agora é para ser simples mesmo, e muito mais simples de usar também.

Como todos os meus efeitos, esse não foge do meu padrão: resolvi as partes mais complicadas no css.
O js é simples. O instanciamento ainda mais.

É isso, sem mais, segue o código, e logo abaixo a demonstração.
A grande ‘sacada’, é deixar o plugin se virar com a animação, (setas prev e next), e termos uma chamada simples e limpa assim:

/* fim plugin carousel */
jQuery(document).ready(function(){
	jQuery('#slide').carousel();
	jQuery('#slide2').carousel();
});

Demonstração

=) Vejam como fiz:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
/* carousel */
jQuery.fn.carousel = function( settings ){
	var $this = jQuery( this );
	var defaults = {
		prev: '.nav-left',
		next: '.nav-right',
		pos: 0,
		speed: 1000
	}
	settings = jQuery.extend(defaults, settings); 

	var lis = $this.find('li');
	var width_li = lis.eq(0).width()+ parseInt( lis.eq(0).css('marginLeft') )+parseInt( lis.eq(0).css('marginRight') );
	var ul = $this.find('ul');

	var prev = $this.find( settings.prev );
	var next = $this.find( settings.next );

	ul.css({width: (width_li*lis.length)+'px'});

	/* .nav-left */
	prev.click(function(){
		if( settings.pos>0 ){
			settings.pos--;
			_move( ul, settings.pos, width_li, settings.speed );
		}
	});
	/* .nav-right */
	next.click(function(){
		if( lis.length-1>settings.pos ){
			settings.pos++;
			_move( ul, settings.pos, width_li, settings.speed );
		}
	});

	/* funcoes privadas */
	_move = function( ul, pos, width_li, speed ){
		var new_left =  -1*pos*width_li;
		ul.animate({left:new_left+'px'},settings.speed);
	}

	return $this;
};
/* fim plugin carousel */
jQuery(document).ready(function(){
	jQuery('#slide').carousel();
	jQuery('#slide2').carousel();
});
</script>
<style type="text/css">
* { margin: 0; padding: 0; }
#slide { width: 460px; height: 300px; }
	#slide li { width: 460px; height: 300px; }
#slide2 { width: 140px; height: 105px; padding: 10px 25px; background: #000; }
	#slide2 li { width: 140px; height: 105px; }
hr { margin: 50px; }

/* css do plugin */
.carousel { position: relative; }
.overflow { overflow: hidden; height: 100%; position: relative; }
.carousel ul { position: absolute; top: 0; left: 0; }
.carousel li { float: left; }
.nav { position: absolute; top: 50%; z-index: 3;
	background: url('images/nav.png') no-repeat;
	width: 36px; height: 36px; margin-top: -18px;
	cursor: pointer;
}
.nav-left { left: 10px; }
.nav-right { right: 10px; background-position: right top; }
	.nav-left:hover { background-position: left -36px; }
	.nav-right:hover { background-position: right -36px; }
/* css do plugin */
</style>
</head>
<body>

	<div id="slide" class="carousel">
		<div class="nav nav-left"></div>
		<div class="overflow">
			<ul>
				<li><img src="images/1.jpg" alt="" /></li>
				<li><img src="images/2.jpg" alt="" /></li>
				<li><img src="images/3.jpg" alt="" /></li>
				<li><img src="images/4.jpg" alt="" /></li>
				<li><img src="images/5.jpg" alt="" /></li>
			</ul>
		</div>
		<div class="nav nav-right"></div>
	</div><!-- /slide -->

	<hr />

	<div id="slide2" class="carousel">
		<div class="nav nav-left"></div>
		<div class="overflow">
			<ul>
				<li><img src="images/mini1.jpg" alt="" /></li>
				<li><img src="images/mini2.jpg" alt="" /></li>
				<li><img src="images/mini3.jpg" alt="" /></li>
				<li><img src="images/mini4.jpg" alt="" /></li>
			</ul>
		</div>
		<div class="nav nav-right"></div>
	</div><!-- /slide -->
</body>
</html>
25jan2012

Alterar dimensões de embed do youtube com javascript

(0) comentários

Repositório, para deixar arquivado aqui.
Veja que ao clicar em cada botão, o tamanho do vídeo se altera.

<html>
<head>
<style type="text/css">
* { margin: 0; padding: 0; }
html, body { height: 100%; }
</style>
<script type="text/javascript">
function sizeIframe( w, h )
{
	document.getElementById('yt').width = w;
	document.getElementById('yt').height = h;
}
window.onload = function(){
	sizeIframe( document.body.offsetWidth, document.body.offsetHeight-30 );
}
</script>
</head>
<body>
	<iframe width="420" height="315" src="http://www.youtube.com/embed/tvaPMNq4Ey0" frameborder="0" allowfullscreen id="yt"></iframe>

	<input type="button" name="mudar" value="600x480" onclick="sizeIframe( 600, 480 )" />
	<input type="button" name="mudar" value="600x480" onclick="sizeIframe( 420, 315 )" />
	<input type="button" name="mudar" value="300x240" onclick="sizeIframe( 300, 240 )" />
</body>
</html>

É isso. Me diga se vc usar.

25jan2012

Exibir restante de conteúdo, que já estava sendo mostrado pela “metade”- jQuery exibe-esconde

(0) comentários

Boas,

A idéia aqui, foi chegar próximo do efeito de “Exibir mais” do youtube:
Escondido:

A mostra:

Ok ?
Uma parte do conteúdo fica a mostra, e clicando no botão aparece o restante.

O primeiro passo é resolver o efeito no css. Todos os efeitos são apenas css. O javascript manipulando css. jQuery só entra para facilitar essa manipulação, porém é importante ressaltar, que toda a lógica e o efeito em si, ficou no css.

Depois de conseguir resolver tanto o estado aberto, qnto o fechado, usando apenas css e html, sem nenhuma linha de js, fazer o comportamento fica super simples.

<html>
<head>
<style type="text/css">
* { margin: 0; padding: 0; }
p { margin-bottom: 10px; }
.content { margin: 0 auto; width: 500px; }
#panel { position: relative; width: 500px; margin: 0 auto; }
#content { }
.hidden { height: 100px; overflow: hidden; }
#toggle { width: 488px; height: 20px; padding: 5px;
	background: #fff; border: 1px solid #ccc; cursor: pointer;
	text-align: center;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery('#toggle').click(function(){
		jQuery('#panel').toggleClass('hidden');
	});
});
</script>
</head>
<body>
	<div id="panel" class="hidden content">
		<div id="content">
			<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sed gravida dolor. Fusce aliquam, urna sit amet
            luctus adipiscing, massa sem venenatis dui, quis accumsan mi orci eu orci. Mauris nec massa non mi iaculis tincidunt
            eget a lectus. Curabitur suscipit, magna vel laoreet volutpat, sem mauris placerat risus, nec pretium mauris orci non dui.</p>

			<p>Cras in massa dapibus leo tincidunt molestie nec ut sem. Aenean sit amet ipsum risus. Class aptent taciti sociosqu
            ad litora torquent per conubia nostra, per inceptos himenaeos. Cras vitae erat at magna volutpat consequat ut a justo.
            Mauris dapibus dolor at orci placerat congue. Praesent facilisis sodales molestie. Quisque eget lacus eget justo aliquet
             sagittis. Duis sed elit id dui semper feugiat. Vivamus risus magna, facilisis at hendrerit sit amet, accumsan nec felis.</p>

			<p>Nunc massa tellus, fringilla ut tincidunt consequat, ultricies eget nunc. </p>
         </div><!-- /content -->
	</div><!-- /panel -->
	<div id="toggle" class="content">toggle</div>
</body>
</html>

Demonstração

24jan2012

Debianization with git-buildpackage

por em Sem categoria
(0) comentários

"After building some useful piece of software, one has to decide how to best deploy it. In UNIX, the standard way to do that is by publishing the source code in .tar.gz format and requiring users to compile it.

In Debian there is an alternative: using a .deb package. With a .deb package, a single dpkg -i <package>.deb installs the software.

This article explains how to create and support a .deb package for a simple software maintained in git, by tracking the packaging scheme in a specific branch on the same repository."

http://lpenz.github.com/articles/debgit/index.html

Permalink | Leave a comment  »

24jan2012

Sobre o livro “Design Emocional”

(0) comentários

Bom, eu já tinha lido O Design do Dia a Dia, e quase sem querer acabei tendo em mãos pedindo uma indicação sobre oque ler, o “próximo” livro do Donald A. Norman.

Muito bom esse livro também. Podemos lê-lo como um complemento do outro.

Uma decisão tem que dar a sensacão de que é boa.
O pensamento vai sendo construido ao longo do livro.
Emoções norteiam as nossas escolhas. Primeiro inconscientemente, e muito depois de forma lógica, decidimos oque queremos, e oque vamos fazer.

Olhar o Design das coisas sob essa perspectiva, te faz refletir, como que algo além de ser bonito, usável, tb pode ser agradável.
Ou então como temos coisas que nos agradam, nos fazem sentir bem, mas não as usamos.

Realmente um mundo se abre, qndo vc nota que por mais que algo seja prático, não usamos se for feio, se não nos fizer sentir bem. E se algo for realmente bonito, e nos transmitir boas sensações, usaremos, apesar dos defeitos.

Norman nos apresenta nesse livro, 3 tipos de Design: Viceral, Comportamental e Reflexivo.
Vale muito a pena. Eu indico.

23jan2012

Exemplo de uso jQuery.Deferred – simples

(0) comentários

Talvez esteja faltando algo “simples”, situações “cotidianas”, ou sei lá oque.

Estou vendo muitas pessoas no fórum com a mesma dúvida: “usar o objeto Deferred do jQuery”, “pegar o retorno de uma requisição ajax”, e coisas relacionadas.

Eu sempre indico o ótimo tutorial do Maujor:
http://www.maujor.com/blog/2011/02/01/o-objeto-deferred-da-jquery-1-5, porém talvez por ser tão completo, e ter tantas informações, alguns iniciantes podem não estar “entendendo”.

Vou deixar alguns exemplos práticos(todos com o mesmo resultado), de algumas formas de usar o Deferred:

<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
	<script type="text/javascript">
	jQuery(document).ready(function(){
		/* retorna undefined */
		jQuery('#ajax_form_undefined').submit(function(){
			var form = jQuery( this );
			var ret = envia_form_nao_funciona( form );
			alert( ret );
			return false;
		});

		/* enviando ajax_form com done */
		jQuery('#ajax_form').submit(function(){

			var ret = envia_form( jQuery( this ) );
			ret.done(function( dados ){
				alert( dados );
			});

			return false;
		});

		/* enviando ajax_form2 com then */
		jQuery('#ajax_form2').submit(function(){

			var ret = envia_form( jQuery( this ) );
			ret.then(function( dados ){
				alert( dados );
			});

			return false;
		});

		/* enviando ajax_form3 com success */
		jQuery('#ajax_form3').submit(function(){

			var ret = envia_form( jQuery( this ) );
			ret.success(function( dados ){
				alert( dados );
			});

			return false;
		});
	});
	function envia_form_nao_funciona( form )
	{
		jQuery.ajax({
			type: form.attr('method'),
			url: form.attr('action'),
			data: form.serialize(),
			success: function( dados ){
				return dados
			}
		});
	}
	function envia_form( form )
	{
		return jQuery.ajax({
			type: form.attr('method'),
			url: form.attr('action'),
			data: form.serialize()
		});
	}
	</script>
</head>
<body>
	<h2>Exemplo do que "não funciona"(retorna undefined)</h2>
	<form method="post" action="processa.php" id="ajax_form_undefined">
		<label><input type="hidden" name="id" value="" /></label>
		<label>Nome: <input type="text" name="nome" value="nome1" /></label>
		<label>Email: <input type="text" name="email" value="email1" /></label>

		<label><input type="submit" name="enviar" value="Enviar" /></label>
	</form>

	<h2>Recebendo com done</h2>
	<form method="post" action="processa.php" id="ajax_form">
		<label><input type="hidden" name="id" value="" /></label>
		<label>Nome: <input type="text" name="nome" value="nome2" /></label>
		<label>Email: <input type="text" name="email" value="email2" /></label>

		<label><input type="submit" name="enviar" value="Enviar" /></label>
	</form>

	<h2>Recebendo com then</h2>
	<form method="post" action="processa.php" id="ajax_form2">
		<label><input type="hidden" name="id" value="" /></label>
		<label>Nome: <input type="text" name="nome" value="nome3" /></label>
		<label>Email: <input type="text" name="email" value="email3" /></label>

		<label><input type="submit" name="enviar" value="Enviar" /></label>
	</form>

	<h2>Recebendo com success</h2>
	<form method="post" action="processa.php" id="ajax_form3">
		<label><input type="hidden" name="id" value="" /></label>
		<label>Nome: <input type="text" name="nome" value="nome4" /></label>
		<label>Email: <input type="text" name="email" value="email4" /></label>

		<label><input type="submit" name="enviar" value="Enviar" /></label>
	</form>
</body>
</html>

Demonstração online

Convém lembrar que “precisamos” do deferred por causa do assincronismo das requisições, ou seja, o objeto ajax, envia para o servidor, o servidor processa, e o objeto ajax trás o retorno, sem refresh, porém também, sem que o restante do script aguarde esse retorno.

É essa diferença entre “sincrono” e “assincrono”. Note que enviando em modo sincrono async: false,, eu consigo “pegar o retorno” do ajax.

	jQuery(document).ready(function(){
		/* retorna undefined */
		jQuery('#ajax_form_sincrono').submit(function(){
			var form = jQuery( this );
			var ret = envia_form_sincrono( form );
			alert( ret );
			return false;
		});

	});
	function envia_form_sincrono( form )
	{
		var ret = '';
		jQuery.ajax({
			type: form.attr('method'),
			url: form.attr('action'),
			data: form.serialize(),
			async: false,
			success: function( dados ){
				ret = dados;
			}
		});
		return ret;
	}

E ai ? qual dos dois usar ? sincrono ? ou assincrono com o deffered ?
Não sei, isso depende da sua aplicação, e é assunto para um próximo post talvez.

Usou ? comente.. este é o “meu pagamento” pelo que escrevo: o teu comentário.

20jan2012

Restriction driven simplicity

(0) comentários

I just returned from vacation and was reviewing some photos in my cel phone when I found some old photos from a previous trip to SF. In the airport there was an exhibition about TV sets and some old remote controls got my attention. Here’s a picture of them:

Old TV remote control

Old TV remote control

Checkout the number of buttons in the remote control. The maximum is 4. There are some remotes with only one button. When I was a kid I remember the first TV bought in my house with a remote control that had only 2 buttons, one for volume and other for changing channel. That simple! That was around 1975. At the time, the technology for making a remote control was too expansive, so it could not be too complicated and have too many buttons, otherwise it would be too expansive to be sold in the market. That was the restriction that drove the simplicity of those 1st generation remote control. Now we don’t have that restriction and we get remotes that can accomplish much more tasks but are way more complex. Take a look at the picture below (and I even picked a not-so-complex one!):

Digital TV Remote Control

Digital TV Remote Control

So maybe next time we want to design something more simple, we can think of imposing some restrictions to the design process! :-)

Switch to our mobile site