Reto
Programacion
Modificar el programa de saidjose:
Superficie de un triangulo rectangulo
de tal manera que quede lo mas profesional posible: validación de datos, validación de entrada, que acepte argumentos a través de la linea de comandos:
# Calcula la superficie de un objeto de altura 10 y de base 3 al estilo BSD:
% calcular -a 10 -b 3
O al estilo GNU:
% calcular --altura=10 --base=3
O usando ambos estilos:
% calcular -a 10 --base=3
*SIN* usar ningún widget (GTK+, Motif, Qt, GNUStep, etc, etc).
Es decir, que no sea para el entorno gráfico sino para la consola.
Tip: En entornos BSD y GNU/Linux pueden usar la funcion getopt(3) incluído en la librería #include <unistd.h> para checar los argumentos de la función main(3).
Permalink: http://mononeurona.org/users/entry/asarch/1523
The Multiple Instances Bug
Hacks
Introducción
Yo lo llamo “The Multiple Instances Bug” a manera de broma, el cual consiste en lo siguiente:
- Usando el pdksh (“Public Domain Korn Shel”) abre tres ventanas del XTerm y teclea “echo Hello from #1” en la primer ventana, “echo Hello from #2” en la segunda y “echo Hello from #3” en la tercer ventana.
- Ahora ciérralos de forma aleatoria.
- Abre una cuarta ventana y trata de llamar todos esos comandos desde el historial y verás que solamente el historial de la última ventana se guardó ya que esta sobreescribió a las otras dos.
Esto no pasa con la versión oficial del Korn Shell, el ksh93 ni tampoco con la versión de MirBSD, el mksh.
COMPLEX_HISTORY e EASY_HISTORY
Esto no es broma para la gente de pdksh ya que en el siguiente archivo:
aparece este bug como una de las prioridades a corregir:
* history
There are two versions of the history code, COMPLEX_HISTORY and
EASY_HISTORY, which need to be merged. COMPLEX does at&t style history
where the history file is written after each command and checked when
ever looking through the history (in case another shell has added
something). EASY simply reads the history file at startup and writes
it before exiting.
* re-write the COMPLEX_HISTORY code so mmap() not needed (currently
can't be used on machines without mmap()).
* Add multiline knowledge to COMPLEX_HISTORY (see EASY_HISTORY
stuff).
* change COMPLEX_HISTORY code so concurrent history files are
controlled by an option (set -o history-concurrent?). Delete
the EASY_HISTORY code.
* bring history code up to POSIX standards (see POSIX description
of fc, etc.).
que explicado en el idioma de Cervantes:
Que es lo que esta ocacionando este “bug”.
La solución propuesta a este problema es modificar el código de COMPLEX_HISTORY de tal manera que prescinda (que no necesite) de la función mmap() ya que ésta no se encuentra disponible en todas las arquitecturas.
O, escribir un mmap() propio que emule esta función en donde no esté disponible.
Asi que si tienes un tiempecito, la comunidad del software libre te estará muy agradecido.
La página oficial del pdksh es la siguiente:
Por cierto, si estás pensando “implementar” código (robar) de otros proyectos, checa muy bien las cláusulas de la licencia por favor.
Permalink: http://mononeurona.org/users/entry/asarch/1514
Korn Shell Settings (actualizado para ksh93)
Hacks
La versión corregida y aumentada, lista para ser usada con el pkgsrc de NetBSD e incluso con GNU/Linux ya que es la misma versión del Korn Shell: el ksh93.
Esto va en ~/.profile:
case $SHELL in
*bash*) # GNU Bourne Shell
. $HOME/.bashrc
;;
*ksh*) # Korn Shell Settings
export ENV=$HOME/.kshrc
;;
esac
# Display the fortune cookie
fortune -a
y esto en ~/.kshrc:
# Enviroment vars
export EDITOR=vi
export FCEDIT=$EDITOR
export HISTEDIT=$EDITOR
export VISUAL=$EDITOR
# Each Korn Shell variant has its own history file
export HISTFILE=$HOME/.$(basename $SHELL)_history
# Locale settings
if [ $USER != "root" ]; then
export LANG=en_US.ISO8859-1
export LC_ALL=${LANG}
fi
# Set the editor command line style
set -o vi
# Notify about background processes
set -o notify
# Set the ls tyle
if [ $USER != "root" ]; then
alias ls='ls -FA'
fi
# Set the prompt
case $KSH_VERSION in
*MIRBSD*) # MirBSD Korn Shell
PS1='[${USER:=$(id -un)}'"@${HOSTNAME:=$(hostname -s)}:!]"
;;
*) # All the rest variants
PS1='
$(whoami)@$(hostname)
$(date)
$(pwd)
[$(tty):!]'
;;
esac
PS1=$PS1'$(if (( $(id -u) )); then print \$; else print \#; fi) '
Permalink: http://mononeurona.org/users/entry/asarch/1508
Reto
Hacks
¿Cómo le haces para cambiar la extensión de un grupo de archivos?
Obviamente no con el siguiente:
% mv *.sh *.txt
ni tampoco con el siguiente:
% find . -maxdepth 1 -type f -name '*.sh' -exec mv {} {}.txt \;
ya que quedarían muy feos al tener ahora la extensión '*.sh.txt'.
Permalink: http://mononeurona.org/users/entry/asarch/1507
Creación del disco de instalación de OpenBSD
Hacks
Estos son los pasos que se necesitan. Para una explicación detallada consulta:
A lo que te truje Chencha:
- Primero creamos el espacio de trabajo y nos situamos dentro:
% cd ./openbsd-installation-disc
- Descargamos el release completo:
- Le hacemos el hack para el proceso de instalación:
- Creamos la imágen de disco:
Y listo.
Permalink: http://mononeurona.org/users/entry/asarch/1506
C Shell Settings
Hacks
He aquí mis preferencias del C Shell:
# Enviroment Shell Vars
set filec
set histfile=$HOME/.csh_hist
set history=2048
set notify
set savehist=204
# Locale settings
setenv LANG en_US.ISO8859-1
setenv LC_ALL ${LANG}
qué contraste con las del Korn Shell, ya que este no cuenta con el editor de líneas de comandos e historial interactivo (poder acceder a el mediante las teclas de dirección), pero si un poderoso mecanismo de sustitución del historial.
O sea, un shell para verdaderos hackers (cof cof
cof cof).
Permalink: http://mononeurona.org/users/entry/asarch/1494
Korn Shell Settings
Hacks
He aquí el archivo de configuración del Korn Shell:
# Enviroment vars
export EDITOR=vi
export FCEDIT=$EDITOR
export HISTEDIT=$EDITOR
export HISTFILE=$HOME/.ksh_hist
export HISTSIZE=2048
export VISUAL=$EDITOR
# Locale settings
if [ $USER != "root" ]; then
export LANG=en_US.ISO8859-1
export LC_ALL=$LANG
fi
# Set the editor command line style
set -o vi
# Notify about background processes
set -o notify
# Set the ls style
if [ $USER != "root" ]; then
alias ls='ls -AF'
fi
# Let's set the prompt
case $KSH_VERSION in
*PD\ KSH*) # pdksh
PS1='
$(whoami)@$(hostname)
$(date)
$(pwd)
[$(tty):!]'
;;
*) # All the rest variants
PS1='[${USER:=$(id -un)}'"@${HOSTNAME:=$(hostname -s)}:!]"
;;
esac
PS1=$PS1'$(if (( $(id -u) )); then print \$; else print \#; fi) '
La configuración para que en cada login se apliquen los cambios:
# Korn Shell Settings
export ENV=$HOME/.kshrc
fortune -a
Y listo.
Permalink: http://mononeurona.org/users/entry/asarch/1492
Hardcore “Got Milk?”
Mujeres
Permalink: http://mononeurona.org/users/entry/asarch/1446
LyX
Instalacion
LyX 1.4.5.1 del directorio /usr/pkgsrc/editors/lyx-qt:
Permalink: http://mononeurona.org/users/entry/asarch/1445
Kernel “combinado” de NetBSD (reloaded)
Hacks
Introducción
La laptop que tengo tiene una tarjeta de red inalámbrica Intel PRO/Wireless 3945ABG así como tambien un procesador Intel Duo, que a según dicen tiene doble núcleo y que tambien es bueno para la virtualización “por hardware” del Xen.
El detalle es que con los kernels que trae por default el disco de instalación del NetBSD no puedo ambas cosas:
- GENERIC.MP <- Solamente puedo usar los dos procesadores sin conexión inalámbrica.
- GENERIC_LAPTOP <- Aquí si tengo conexión pero nada más puedo usar un sólo CPU.
El siguiente es un script para reducir los pasos de la compilación del kernel “combinado”.
En lugar de hacer:
- Tomamos una copia del kernel de SMP para el nuevo kernel:
- Le agregamos las bondades del kernel para laptops:
- Comentamos la siguiente directiva
#include "arch/i386/conf/std.i386"
- Obtenemos las líneas de los errores:
...
wanda:25: already have options `INCLUDE_CONFIG_FILE=1'
wanda:29: duplicate maxusers parameter
wanda:33: already have options `I486_CPU=1'
wanda:34: already have options `I586_CPU=1'
wanda:35: already have options `I686_CPU=1'
wanda:37: already have makeoptions `CPUFLAGS=-march=i486 -mtune=pentiumpro'
wanda:42: already have options `VM86=1'
wanda:43: already have options `USER_LDT=1'
wanda:46: already have options `ENHANCED_SPEEDSTEP=1'
...
- Aislamos el número de línea solamente:
...
25
29
33
34
35
37
42
43
46
...
- Y comentamos todas esas líneas una por una a mano.
- Mezclamos ambos kernels:
- Corregimos los errores:
- Creamos el directorio de compilación:
- Nos situamos dentro y compilamos:
Y listo. Ahora Solamente:
- Renombramos el otro kernel:
- Y situamos nuestro nuevo kernel recien horneadito:
- Y reiniciamos para probarlo.
Código fuente
Este es el pedazo de “maravilla”:
#-------------------------------------------------------------------------------
#
# preparar_kernel.sh: Script para comentar las lineas
# cuando se combinan dos kernels.
#
# Copyright (c) 2008, asarch.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of copyright holders nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
#-------------------------------------------------------------------------------
#-----------------------------------------------------------
# Validacion de los argumentos del script
#-----------------------------------------------------------
#
if (( $# == 0 )); then
echo Forma de uso: $0 nombre_del_nuevo_kernel
exit 1
fi
#-----------------------------------------------------------
# Validacion del usuario
#-----------------------------------------------------------
#
if [[ $USER != "root" ]]; then
echo Necesitas ser el root.
exit 1
fi
#-----------------------------------------------------------
# Inicializacion de variables
#-----------------------------------------------------------
#
BASE_DIR="/tmp"
KERN_FILE=$1
ERR_LOG=$BASE_DIR"/"$KERN_FILE".log"
ERR_LINES=$BASE_DIR"/"$KERN_FILE"-err-lines.log"
#-----------------------------------------------------------
#
# Comentamos la siguiente linea
#
# include "arch/i386/conf/std.i386"
#
#-----------------------------------------------------------
#
ex - $KERN_FILE << EOS
/std.i386
s/include/#include/
p
w
EOS
#-----------------------------------------------------------
# Obtenemos los errores
#-----------------------------------------------------------
#
config $KERN_FILE > $ERR_LOG 2>&1
#-----------------------------------------------------------
# Verificamos que se haya podido crear el registro de errores
#-----------------------------------------------------------
#
if [[ ! -e $ERR_LOG ]]; then
echo No se pudo crear el registro de los errores: $ERR_LOG
exit 1
fi
#-----------------------------------------------------------
# Obtenemos las lineas de los errores
#-----------------------------------------------------------
#
SED_CMD="s/${KERN_FILE}://"
cat $ERR_LOG | sed $SED_CMD | sed 's/: .*//' > $ERR_LINES
#-----------------------------------------------------------
# Verificamos que se haya podido crear el registro de las lineas
#-----------------------------------------------------------
#
if [[ ! -e $ERR_LINES ]]; then
echo No se pudo crear el registro de las lineas: $ERR_LINES
exit 1
fi
#-----------------------------------------------------------
# Contamos el total de lineas a procesar
#-----------------------------------------------------------
#
TOTAL=$( wc -l < $ERR_LINES )
#-----------------------------------------------------------
# Verificamos que se hayan encontrado las lineas
#-----------------------------------------------------------
#
if (( $TOTAL == 0 )); then
echo No hay lineas por corregir
exit 1
fi
#-----------------------------------------------------------
# Un hack para que funcione
#-----------------------------------------------------------
#
let "TOTAL--"
I=1
#-----------------------------------------------------------
# Proceso principal
#-----------------------------------------------------------
#
while (( $I <= $TOTAL )); do
LINE=$( head -n $I < $ERR_LINES | tail -n 1 )
echo Editando la linea $LINE
ex - $KERN_FILE << EOS
$LINE
i
#
.
j
p
w
EOS
echo
let "I++"
done
Si encuentras un error por favor repórtalo. Muchas gracias.
Permalink: http://mononeurona.org/users/entry/asarch/1444

















