The Chuck Norris Facts Bash Script
Pon un Chuck Norris en tu vida! O mejor aun, pon miles de Chuck Facts en tu consola!
Bored STenyaK Productions presents: chuckfacts.sh!

Coming this winter to a console in front of you…
#!/bin/bash
# check for parameters
if [ -z $1 ]
then
echo "Please specify the destination chuck norris facts file."
echo "E.g.: $0 ~/.chuckfacts.txt"
exit
fi
ffile=$1
old=0
if [ -s $ffile ]
then
old=$(wc -l $ffile |sed "s/\s.*//g")
fi
echo -n "Getting facts pack"
# download the 170 first chuck norris pages of 4q.cc site to disk
for i in $(seq 1 170)
do
echo -n " $i"
# only store facts
wget -qO - \
"http://4q.cc/index.php?pid=listfacts&person=chuck&page=$i" \
| grep "index.php?pid=fact&person=chuck" >> $ffile
done
echo ""
echo -n "Post-processing facts..."
# remove unnecessary html code
perl -pi -e "s/.*id=.{32,32}\">//g;s/<\/a>.*//g" $ffile
# replace most common html entities
perl -pi -e "s/"/\"/g" $ffile
perl -pi -e "s/&/&/g" $ffile
# remove empty lines
perl -ni -e "print unless /pid=/" $ffile
# remove redundant lines
cat $ffile |sort |uniq > /tmp/chuckfacts.tmp
mv /tmp/chuckfacts.tmp $ffile
new=$(wc -l $ffile |sed "s/\s.*//g")
echo " OK"
echo "Generated $(($new-$old)) new facts ($new in total) facts."
# show how to add a fortune-like command to bashrc
echo ""
echo "You can add this to your ~/.bashrc file:"
echo 'test -s '$ffile' && cowsay -f $(ls /usr/share/cowsay/cows
| shuf |head -1) "$(cat '$ffile' |shuf |head -1)"'
Mira que no me aburro a veces ni nada eh…
En defensa de los derechos de los ciudadanos en Internet
Ante la inclusión en el Anteproyecto de Ley de Economía Sostenible de modificaciones legislativas que afectan al libre ejercicio de las libertades de expresión, información y el derecho de acceso a la cultura a través de Internet, los periodistas, bloggers, usuarios, profesionales y creadores de internet manifestamos nuestra firme oposición al proyecto, y declaramos que…
1.- Los derechos de autor no pueden situarse por encima de los derechos fundamentales de los ciudadanos, como el derecho a la privacidad, a la seguridad, a la presunción de inocencia, a la tutela judicial efectiva y a la libertad de expresión.
2.- La suspensión de derechos fundamentales es y debe seguir siendo competencia exclusiva del poder judicial. Ni un cierre sin sentencia. Este anteproyecto, en contra de lo establecido en el artículo 20.5 de la Constitución, pone en manos de un órgano no judicial -un organismo dependiente del ministerio de Cultura-, la potestad de impedir a los ciudadanos españoles el acceso a cualquier página web.
3.- La nueva legislación creará inseguridad jurídica en todo el sector tecnológico español, perjudicando uno de los pocos campos de desarrollo y futuro de nuestra economía, entorpeciendo la creación de empresas, introduciendo trabas a la libre competencia y ralentizando su proyección internacional.
4.- La nueva legislación propuesta amenaza a los nuevos creadores y entorpece la creación cultural. Con Internet y los sucesivos avances tecnológicos se ha democratizado extraordinariamente la creación y emisión de contenidos de todo tipo, que ya no provienen prevalentemente de las industrias culturales tradicionales, sino de multitud de fuentes diferentes.
5.- Los autores, como todos los trabajadores, tienen derecho a vivir de su trabajo con nuevas ideas creativas, modelos de negocio y actividades asociadas a sus creaciones. Intentar sostener con cambios legislativos a una industria obsoleta que no sabe adaptarse a este nuevo entorno no es ni justo ni realista. Si su modelo de negocio se basaba en el control de las copias de las obras y en Internet no es posible sin vulnerar derechos fundamentales, deberían buscar otro modelo.
6.- Consideramos que las industrias culturales necesitan para sobrevivir alternativas modernas, eficaces, creíbles y asequibles y que se adecuen a los nuevos usos sociales, en lugar de limitaciones tan desproporcionadas como ineficaces para el fin que dicen perseguir.
7.- Internet debe funcionar de forma libre y sin interferencias políticas auspiciadas por sectores que pretenden perpetuar obsoletos modelos de negocio e imposibilitar que el saber humano siga siendo libre.
8.- Exigimos que el Gobierno garantice por ley la neutralidad de la Red en España, ante cualquier presión que pueda producirse, como marco para el desarrollo de una economía sostenible y realista de cara al futuro.
9.- Proponemos una verdadera reforma del derecho de propiedad intelectual orientada a su fin: devolver a la sociedad el conocimiento, promover el dominio público y limitar los abusos de las entidades gestoras.
10.- En democracia las leyes y sus modificaciones deben aprobarse tras el oportuno debate público y habiendo consultado previamente a todas las partes implicadas. No es de recibo que se realicen cambios legislativos que afectan a derechos fundamentales en una ley no orgánica y que versa sobre otra materia.
11.12.09Google’s “go” simple & stupid benchmark (2nd round: memspeed)
Continued from Round 1: I/O
Thanks to Juanval for the suggestion.
$ cat hello.cpp && g++ hello.cpp &&
> time for i in $(seq 10); do ./a.out; done
int main (int argc, char** argv)
{
const int size = 250;
int a[size],b[size],c[size];
for(int i=0;i<size;++i)
for(int j=0;j<size;++j)
for(int k=0;k<size;++k)
c[k]+=a[i]*b[j];
}
real 0m1.041s
user 0m0.944s
sys 0m0.020s
$ cat hello.py &&
> time for i in $(seq 10); do python hello.py; done
size = 250
a,b,c = [0]*size, [0]*size, [0]*size
for i in a:
for j in b:
for k in range(0,size):
c[k] += i*j
real 1m7.210s
user 1m4.924s
sys 0m0.084s
$ cat hello.go && 8g hello.go && 8l hello.8 &&
> time for i in $(seq 10); do ./8.out; done
package main
func main()
{
var a,b,c [250]int;
for i := range a
{
for j := range b
{
for k := range c
{
c[k] += a[i] * b[j];
}
}
}
}
real 0m3.000s
user 0m2.812s
sys 0m0.020s
11.11.09 Google’s “go” simple & stupid benchmark (1st round: I/O)
Systems programming language? They gotta be kiddin…
$ cat hello.cpp && g++ hello.cpp &&
> time for i in $(seq 100); do ./a.out >/dev/null; done
#include <stdio.h>
int main (int argc, char** argv)
{
for (int i=10000;i--;)
{
printf("hello, world\n");
}
}
real 0m0.427s
user 0m0.220s
sys 0m0.164s
$ cat hello.py &&
> time for i in $(seq 100); do python hello.py >/dev/null; done
for i in range(1,10001):
print "hello, world"
real 0m3.809s
user 0m2.800s
sys 0m0.724s
$ cat hello.go && 8g hello.go && 8l hello.8 &&
> time for i in $(seq 100); do ./8.out >/dev/null; done
package main
import "fmt"
func main()
{
for i:=10000;i>0;i--
{
fmt.Printf("hello, world\n")
}
}
real 0m7.528s
user 0m6.388s
sys 0m0.664s
Continued in Round 2: memspeed
09.11.09Puls, 256 bytes intro by Arriola
This post is twice the size of Puls
hoygan, no puedo resizear las afotos, cómo ago!
Hay momentos en la vida en que pringar puede ser divertido. Por supuesto, se trata de cuando alguien te ruegadeja migrar su apestoso Microsoft Windows Whatever (TM) a Linux.
En su primeras horas de contacto con una Ubuntu 9.04 recién instalada, mi querida aikurushii se me queja en formato hoygan (que en mala hora se me ocurrió enseñarle) de que en Windows podía redimensionar imágenes con solo hacer click derecho, y ahora en Linux no, y que Linux apesta.
Como acto reflejo, me calzo un ssh a su ordenador, y esgrimiendo vim a dos manos le esbozo un bash en 5 minutos:
#!/bin/bash
size=$(echo "$0" |sed "s/.*\.\(.*\)\.sh/\1/g")
for i in "$@"
do
newname="$(echo "$i" |sed "s/\.\(...\)$/.$size.\1/g")"
cp "$i" "$newname"
mogrify -resize $size "$newname"
done
text="Resized to $size px wide."
#some optional user interface candy, uncomment at will:
#zenity --info --text "$text"
#echo $text
El script en cuestión se guarda en, por ejemplo, /usr/local/bin/resizer.640.sh, o resizer.1024.sh, o la resolución a la que se quiera redimensionar las imágenes (también se puede symlinkear el script con varios nombres, por supuesto, y cada uno resizeará a un tamaño diferente).
Y por fin, desde el navegador de ficheros de turno, se le dice que abra las imágenes en cuestion con el susodicho script, et voilà, Linux doesn’t suck any more!
Bueno, y entonces es cuando se me ocurre googlear un poco
y encuentro esta cosa llamada NIS… si el caso es reinventar la rueda
Frikuriosidades estadisticas en bash
Tras descubrir el excelente sitio CommandLineFu, no he podido resistirme a probar uno de sus fus con los cuatro usuarios que utilizo mas a menudo.
El comando en cuestion muestra un Top 10 de comandos usados en bash:
history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head
Los resultados obtenidos son:
stenyak@home root@home stenyak@work root@work 3195 ls 1098 ls 1481 ls 182 pacman 2240 cd 639 cd 1310 svn 146 ls 1147 hg 356 vi 1045 cd 80 rm 1077 vi 303 emerge 1017 vi 74 vi 393 rm 233 eix 979 make 58 cd 381 su 144 rm 386 rm 36 for 357 find 93 grep 373 grep 23 ping 333 man 87 mount 269 ssh 19 umount 293 mplayer 82 man 266 svndiff.sh 19 grep 275 mv 81 smartctl 161 hg 15 su
Por supuesto, las estadisticas son todo mentiras. Cabe destacar el buen trabajo que hacen muchas distribuciones en conseguir que bash autodestruya sus historiales. No me he molestado en comprobarlo en las Gentoo y ArchLinux que utilizo, pero si usais Ubuntu, que sepais que os ocurre by default.
Pero weno, que he hecho esto porque me aburria, asi que la rigurosidad de la prueba nos la pela un poco, no? xD
He probao el script en la RedHat de mi server offsite, pero parece no funcionar; si alguno hoygais un fix, ruego compartais el conocimiento.
(tenia pensao meter una grafica de gnumeric o gnuplot por aki, que los posts siempre quedan mejor con dibujines para que la gente no tenga que leer, pero sorry, no me aburro tanto esta vez
. Weno, vamos a intentar hacer el blog un poco mas interactivo, a ver que tal sale…)
¿Cual es tu Top 10 como luser y como root?
Bash 4.0 on the loose!
Parece que hay una nueva version del omnipresente y monopólico shell default en casi cualquier distribución GNU/Linux:
El changelog de la nueva 4.0 no parece sugerir grandes cambios a primera vista, sino más bien pequeños tweaks por aki y por allá, pero son bienvenidos de todas formas. Al fin y al cabo, existen mil y una shells alternativas en caso de que no nos mole mucho la forma a veces warra de implementar funcionalidades en bash
Happy bashacking!
01.20.09Consistent Desktop UI proposal
I’ve always been a bit particular with my desktop preferences. After using WindowMaker, Gnome+Sawfish, Ion2, WMII, Kde+Kwin, Gnome+Metacity, Compiz Fusion+AWN and testing out some more, I’ve yet to see one that fully addresses my needs.
One of my main complaints is the waste of screen real estate. Both window managers and applications themselves are at fault for this. The influence of Windows UI style in panels and windows has prevented most designers from getting the most out of the users’ screens. Ion2 is the window manager i’m currently most happy with, but it’s still not perfect if applications don’t properly cooperate, which is only possible if they follow some sort of guidelines (such as those discussed and published by the FreeDesktop project).
This blog post shows a suggestion that could, IMHO, improve the desktop experience, although maybe at the cost of reduced usability for computer illiterates.
As an introduction, here’s a quickly gimped draft of the idea I had some months ago:
The increase in usable space is obvious (well, at least to power users). The famous and ancient “title bar” is gone. We already have the window title in the so-called task bar, so why repeat it again using a whole horizontal bar for it? And what’s with the habit of dedicating another whole bar for 5 tiny application menues? Furthermore, the old status bar can be set to automatically hide for additional real estate (with a behaviour similar to that of Google browser Chrome).
Most interactive widgets have been moved to the top of screen (but they might as well have been placed on the bottom or aside). Personally, I see no reason for spreading buttons all over the screen, other than following the current desktop environment trends. Having them all close together greatly reduces the need to move the mouse.
Keep in mind that the tabs depicted in that draft are not supposed to be fullscreen-only, but have a mixed TDI & MDI behaviour (similar to Opera but, instead, leaving the management of those document windows to… well, the window manager
).
But it doesn’t stop there. While we’re at it, why not merge the ideas behind desktops and apps? Here’s the natural evolution of the original idea:
There, the concept of virtual desktops is applied as a way to organize tabs (instead of using yet more windows for the same application instance).
The key is what I’ve just decided to name generic-bar. This bar contains an “app” icon (gnome icon, firefox icon, favicon…), abstracted pager, “tabs” and applets (menues, buttons, traditional applets…) in any desired number and order. For example, in the last draft there are two generic bars: the first one contains “applications”, while the second one contains what we currently know as “tabs”. In essence, both applications and tabs would be handled the same way by the proposed desktop environment. Furthermore, this hypothetical desktop environment could handle generic-bar nesting of any depth.
The good thing is that this desktop proposal does not remove any functionality currently found on most desktop environment UIs, but actually adds more while freeing up even more space for your valuable applications to use.
11.13.08Looking beyond Pandora’s box
Many of you may remember the awesome Pandora music service. If you’re north american, you can actually still enjoy it, while the rest of the world suffers a massive IP address ban.
Luckily, there are several alternatives to Pandora’s boombox, the most known of which is Last FM: Imeem, Youtube music playlists, Anywhere FM… But recently I got pointed in the direction of a very interesting one: Jamendo.
Jamendo hosts a heck of a lot of music without shitty restrictive licenses. Not only is most of the music very high quality, but it’s also free for download. That’s right, at no cost. You can burn whole albums onto discs, copy them to thumbdrives, share with friends, share with strangers (via P2P)… almost anything you want to do, you can, in virtue of their Creative Commons licenses.
You can also, of course, donate some money to the artists you like.
We can’t thank you enough, Lessig!









