Thursday, December 4, 2014

Quicktip : Remove invalid utf8 charactes in a file

Whenever I need to check if a file contains invalid utf8 chars:

isutf8 file.txt

(in ubuntu, you need to install the `moreutils` package)

Then, to rremove invalid chars, use iconv:

iconv -f utf-8 -t utf-8 -c nonutf-8.txt > utf8.txt

-c stands for remove `invalid chars`
-f 'from' utf8
-t 'to' utf8 

Wednesday, October 15, 2014

Quick Tip: nginx.conf file for upstart in Ubuntu 14.04

It tookme several tries to find the right configuration file for nginx to work with upstart (for example Ubunty 14.04 uses upstart)

The configuration file is based in the oficial nginx file, but modified to allow restarts (*)


# nginx
 
description "nginx http daemon"
author "George Shammas "
 
start on (filesystem and net-device-up IFACE=lo)
stop on runlevel [!2345]
 
env DAEMON=/usr/sbin/nginx
env PID=/var/run/nginx.pid
 
expect fork
respawn
respawn limit 10 5
 
pre-start script
        $DAEMON -t
        if [ $? -ne 0 ]
                then exit $?
        fi
end script
 
# Ensure nginx is shutdown gracefully
# Upstart will be tracking the wrong PID so the following is needed to stop nginx
post-stop exec start-stop-daemon --stop --pidfile $PID --name nginx --exec $DAEMON --signal QUIT

exec $DAEMON -c /etc/nginx/conf/nginx.conf
--- (*) Without the post-stop script, nginx didnt kill the forked processed and spit a 502 Bad Gateway . #you can see taht children are not killed after a `service nginx stop` sudo netstat -tulpn #to kill stalled children sudo fuser -k 80/tcp

Wednesday, May 21, 2014

Quick tip: CSS for Hanging indentation


Sometimes you need to achieve a fancy effect on the first line of a paragraph, so that just the first line is indented to the left and the other lines be displayed a little bit to the right. Even, I discovered that it has a name 'Hanging Indent':

This is the first line of a very very very very very
    very very very very very very very very very very
    long paragraph. And there is more than one sentence.

    In fact we could reach almost a dozen.


Just apply a combination of a negative text-indent and padding-left (or margin-left). Ex:

p {
  text-align: left;
  text-indent: -25px;
  padding-left: 25px;
}


There is a 'first-letter' property in css that gives you more customization @see this

Monday, May 19, 2014

Quick tip: optimize images from command line

I use this trick for quickly optimize images. Note, I use ubuntu:

just install these tools

sudo apt-get install optipng jpegoptim

and now you can do (beware: input is overwritten)

optipng file.png 
jpegoptim file.jpg

both tools work in the same way

jpegoptim [ options ] filenames
optipng [options] files



to convert between formats, you can use imageMagick

sudo apt-get install imagemagick

and now

convert input.png output.jpg
convert input.jpg output.png 

Profit!

Sunday, March 23, 2014

Handy enhancement for ruby String: Defaults to default text

In my code , I repeat a lot this pattern: if the string is blank / empty, return a default text, otherwise return the original text.

final_text = text.blank? ? "default text" : text content_tag :h1, text.blank? ? "default text" : text, :class => 'mega'


I discovered this little gem in Stackoverflow (I lost the original source), you only need to reopen the String class, in an intializer, or decorator.

class String

  def defaults_to(what)
    self.strip!
    self.blank? ? what : self
  end


end

and, now you can use it in a readable form

text.defaults_to("default text")


Saturday, March 1, 2014

Concerns in Rails (or how to reuse code)

I have been doing some experiments with rails Concerns . While they have been widely publicited for Rails 4, you can use them in Rails 3 as well.

They are like the ruby standard include / extend pattern, but taking care of dependencies. In any case it would be easy to go back to the 'raw' include / exclude game.

This is an example of how to use them.

 require 'active_support/concern'

module Concerns

  module DummyConstants

  end

  module Dummy
    extend ActiveSupport::Concern

    #it seems that things declared here are shared between all inclusions (saving memeory)
    SEXY_REGEXP = /SEXY_REGEXP/i
    MEM_HOGGING = Array.new(1024 * 1024)
    MEMBERSHIP_STATUSES = %w(accepted invited requested rejected_by_group rejected_group)

    included do
      #The included block will be triggered at inclusion time
      before_create :stuff_on_creation

      attr_accessor :accesor_for_the_instance
      class << self
        attr_accessor :accesor_for_the_class
      end

    end

    module ClassMethods
      #Methods in ClassMethods will get added class methods
      def dummy?
        puts "\nCLASS dummy? called\n"
        true
      end

    end

    #these methods are added as instance methods

    def dummy?
      puts "\nINSTANCE dummy? called\n"
      true
    end

    def stuff_on_creation
      puts "\ncreation called\n"
    end

  end


end


Just create a file under model/concerns/dummy.rb and include it

User.send :include, Concerns::Dummy

or

class User
 include Concerns::Dummy end

Note that I repeat the namespace Concerns, but in other examples found in internet people dont. Rails 4 has included models/concerns and controllers/concerns in the autoload paths and in Rails 4 it would work without the namespace. In Rails 3, you need to add the namespace OR using some trick.

I find easier to understand if I include the 'Concern', tough.

Profit!




Saturday, February 8, 2014

Descubriendo los podcasts

Un podcast es basicamente un blog, pero de audio. Y lo realmente importante es que hay miles de podcasts disponibles, con alta calidad y tratando temáticas muy variadas. Sólo tienes que bajarte los audios (mp3) y escucharlos cuando quieras.

--

Todo se inicia con un tweet de @david_bonilla 
"Yo salgo a correr para tener una excusa para escuchar el ". Así descubro que "El amuleto de yendor" es un podcast sobre tecnología, dode 2 chavales hablan sobre cosas que me interesan.


El prime paso, fue descargarme el último programa desde ivoox : me lo escuche de una sentada pues no tiene desperdicio. ivoox está bien para descargarse programas antiguos, pero se queda corto a la hora de descubrir podcasts similares o buscar ciertas temáticas. Además yo quería que me avisaran cuando se grababan episodios nuevos (esto se llama subscripciones, y se maneja mediante rss).

--

Tras un mes de aprendizaje, así es como gestiono mis podcasts:

gPodder.net es el servicio que me permite guardar mis subscripciones . Es gratuito. Necesitas crear  una cuenta y comenzar a añadir los podcasts que te interesen.

Lo siguiente es utilizar un programa que te descarge nuevos audios (episodios) según van apareciendo. Así te ahorras mucha gestion manual.
- para ordenadores tenemos clientes oficiales de gPodder en todas las plataformas http://gpodder.org/downloads así tengo mis WIndows y Linux sincronizados.
- para android yo utilizo ListeUp (no se cual es la diferencia entre la free o la pro de 1€, pero como es un programa que utilizo mucho, acabé pagando) . Con esto cubro mi MotoG y Nexus7 . Esta aplicacion tiene 2 cosas muy buenas: recuerda el audio que estábas escuchando la última vez que apagaste y que puedes manejar los controles desde la pantalla de bloqueo. También sincroniza con gPodder.
- para el iPad utilizo la aplicacion de podcasts oficial . No me gusta mucho porque no tiene integracion con gpodder, y tengo que añadir mis subscripciones a mano. De todas formas los podcasts los suelo escuchar en el movil o en ordenador, asi que no he investigado más.
- Creo que VLC tambien puede manejar subscripciones de podcasts, pero no está integrado con gpodder.
- si no te interesa la integracion con gpodder, en android tienes PodcastAddict, que es una pasada
- si viajas mucho en coche, puedes pasar los episodios a tu reproductor de mp3 y escucharlo en el coche.

Si utilizas gpodder en varios dispositivos, recuerda gestionar que todos están subscritos a las mismas fuentes y sincronizados, desde https://gpodder.net/devices/ Asi te evitas mucho trabajo.

--

Qué escucho?

Basicamente tecnología: iCharlas, PassionGeek, Infoxicados y el amuleto de Yendor.

Aqui estan mis subscripciones: en rss , opml o directamente la página de gpodder

Suelo descubrir nuevos podcasts, navegando por las subscripciones de otros usuarios que estan suscritos a mis mismos podcasts: algunas veces te llevas una sorpresa!

Dejo un enlace con uno de los episodios que mas me gustaron: Javifrechi (de infoxicados) en iCharlas, parte1 y parte2