Espacio de tecnologia, software libre y sus derivados. Una horda de monos entrenados escriben de vez en cuando por aqui algunas noticias, opiniones e incluso alguna que otra cosa fuera del tema. Maqueros, favor de abstenerse que no somos lo suficientemente guapos.

Piano daemon

mod_python sobre NetBSD 5.X

Mod_python es un modulo Apache que embebe el Interprete de Python dentro del el servidor. Con mod_python tu podras escribir aplicaciones webs basada en aplicaciones Python que correran mucho mas rapido que las aplicaciones tradicionales de CGI ademas de tener acceso a las caracteristicas avanzadas de retener conecciones a bases de datos y acceso a funciones internas de Apache.

Instalando el Port en NetBSD 5.X
# cd /usr/pkgsrc/www/ap2-python && make && make install

Luego hay que editar el httpd.conf, agregando la siguiente línea para cargar el módulo.

LoadModule python_module /usr/pkg/lib/httpd/mod_python.so

Mod_python handlers

Apache procesa las requests en fases. Un Handler es una funcion que procesas una particular parte del request. Los Handlers son proporcionados por Apache y por sus modulos como , mod_python.

El Handler Publisher permite accesar a funciones y variables dentro de un modulo via URLs. Evitandoce asi el codigo spagetthi.

Para probar el funcionamiento del módulo debemos hacer lo siguiente. En primer lugar, vamos a necesitar definir un handler de python para los requests en un .htaccess. Allí escribimos algo como lo siguiente:

AddHandler mod_python .py
PythonHandler mod_python.publisher
PythonOption session DbmSession
PythonOption session_dbm /home/user/domains/test.com/session.dbm
PythonOption ApplicationPath /
PythonDebug On ## Turn this off when done with debugging

DirectoryIndex index.py

Por supuesto, habrá que ajustar los datos a lo que sea necesario.
Luego, creamos el índice de nuestro sitio, en este caso en /home/user/domains/test.com/public_html/index.py con el siguiente código:

## index.py
from mod_python import apache

def index(req):
     req.content_type = 'text/plain'
     req.write('Hello from mod_pythonn')
     return apache.OK

Luego accedemos a http://test.com/ y si vemos “Hello from mod_python”, es que hemos instalado correctamente mod_python.

Instalando Subversion & Apache 2.2 & TRAC sobre NetBSD 5


# cd /usr/pkgsrc/www/ap2-subversion && make && make install

# cp /usr/pkg/share/examples/rc.d/apache /etc/rc.d

# echo "apache=YES" >>   /etc/rc.conf

# cd /usr/ports/www/trac && make && make install

Tutorial Hello world para principiantes de desarrollo iphone

Introduccion:

Les mostrare la manera mas simple de crear un programa Hello World sobre IphoneI am going to show you the simplest way to create hello world iPhone tutorial. Para probar el codigo sobre un dispositivo (iPhone) necesitaras comprar una licencia de desarrollador la cual tiene un costo de 99$ para ti y de 299$ para una empresa.


Iniciando el Desarrollo con Iphone:

Lo primero que necesitaras es conocer c-objetive … te recomiendo bajarte algunos libros de rapidlibrary.
O tambien podrias leer “getting started with iPhone”, este tutorial cubre las cosas que tu requieres saber antes de iniciar el desarrollo para iPhone( Tambien puedes mirar el video tutorial de “Getting Started with iPhone” ).

La Idea de este tutorial
Ya existen muchos tutorial sobre Hellos Wolrd in Iphone pero se me antojo escribir uno muy muy basico sobre el iPhone sdk el cual cubre xcode, y interface builder.

Simples pasos creae aplicacion hello world iPhone

Paso 1:Abre el Xcode y da click sobre File > New Project. Select “View-Based Application” y da click sobre “Choose..” button. El nombre de este proyecto sera “Hello World” y da click sobre el boton “Save”. Ahora ya tienes una plantillapara tu proyecto iphone hello world.

Step 2:Ahora pulsa el botton Build and Go para corre esta aplicacion plantilla. Esto iniciara el simulador iPhone y podras ver una pantalla gris en este. Da click sobre el boton Home button and este te mostrara HelloWorld icon sobre el dash board del iPhone simulator.

P1
Salida de nuestra primera aplicacion iphone

Paso 3:Ahora abre tu Xcode project y selecciona el archivo HelloWorldViewController.h y escribe el siguiente codigo:

IBOutlet UITextField *txtUserName;
IBOutlet UILabel *lblUserTypedName;
Also write this method before end of this class
- (IBAction) submitYourName;?

Paso 4:Entonces tu archivo HelloWorldViewController.h lucira como esto:

#import 

@interface HelloWorldViewController : UIViewController {
IBOutlet UITextField *txtUserName;
IBOutlet UILabel *lblUserTypedName;
}

- (IBAction) submitYourName;
@end

Paso 5:Ahora abriremos el archivo HelloWorldViewController.m y escribiremos este metodo antes de @end?

- (IBAction) submitYourName;
{lblUserTypedName.text = txtUserName.text;}

Paso 6:Ahora iniciermos con algo de diseño sobre el (constructor de interfaces) interface builder. Ejecuta un doble click sobre el archivo MainWindow.xib el cual es la principal ventana o punto de entrada hacia tu aplicacion.

p02
Estructura de tu aplicacion iphone

picture-8.png
Interface builder apariencia

Paso 7:Clickea sobre Herramientas y selecctiona Library (cmd + shift + L) y arrastra el campo de texto a tu vista. Como el campo de texto esta ya seleccionado, clickea sobre Tools>Inspector (cmd + 1) y en el campo de Texto teclea “Tu nombre”.

picture-9.png
Agrega etiqueta a tu primer aplicacion iPhone

picture-10.png
Cambiando texto en tu UILabel

Paso 8:Ahora arrastra el componente TextField de tu Library hacia tu vista (cmd+shift+L) y tambien arrastra otra Label dentro de la vista.
screen-shot-2010-06-28-at-31351-pm.png
Agregando un componente Text field a tu primera aplicacion iPhone

picture-12.png
Agregando otra Label a tu primera aplicacion iPhone

Paso 9:Lo ultimo por hacer es arrastrar un boton hacia la vista y entonces abrir el Inspector de nuevo mediante el menu superior selecting tools>Inspector. En Title teclee “Submit”.
picture-19.png

Paso 10:Ahora mapea la variable controller clase funcion y metodos con el interface builder. Seleccione File’s Owner en Interface builder y seleccione inspector de coneccion desde Tools cmd + 2

picture-13.png
Mapea tu controller con el Interface Builder

Paso 11:Ahora tu puedes ver 2 nuevas variables son agregadas in el connection inspector txtUserName y lblUserTypedName. Clickea sobre txtUserName radio button y arrastra este a el text field en la vista (como tu puedes ver en la imagen)
picture-14.png
Mapea tu text field con Interface builder

Paso 12:Haz lo mismo con el lblUserTypedName, selecciona su radio y arrastra es hacia abajo de la label.
picture-15.png
Mapea tu label field con Interface builder

Paso 13:Ahora el ultimo paso es, click sobre submitYourName radio y arrastra este a el botton y selecciona touch down de la lista.
picture-21.png
Mapea tu button con Interface builder

picture-23.png
Establecer tipo de accion al boton

Paso 14:Ahora cierra la interface y abre xcode. And press “build and go”.

Salida final

picture-25.png

We are the world Japones


We are the world - Imitacion en television Japonesa

Lista en twitter para los maestros de unix-masters

http://twitter.com/pianodaemon/unix-masters

Lista en twitter para los maestros de jquery — Jquery Master’s list on twitter

http://twitter.com/pianodaemon/jquery-masters

Helio + Chicle (Do not repeat it yourself!)

TwwetDeck fabuloso cliente para tweeter

http://www.tweetdeck.com/desktop/

@pianodaemon

Este es mi usuario de tweeter ahi los veo

Como validar la estructura de un Comprobante fiscal Digital usando el esquema cfv2.xsd

De las pocas cosas que me gustan de java… esta su parser SAX…..que tambien valida esquemas….


import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.Document;

public class ValidateXmlWithSchema{

	public boolean validate(String file_path){

		boolean valor_retono = true;

		final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
	    final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
		final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
		final String MY_SCHEMA = new OsVars().getSchemaDir() + "cfdv2.xsd";
		final String MY_XML= file_path;

		// Creando la factoria e indicando que hay validacion
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		documentBuilderFactory.setNamespaceAware(true);
		documentBuilderFactory.setValidating(true);

		try {

			//Configurando el Schema de validacion
			documentBuilderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
			documentBuilderFactory.setAttribute(JAXP_SCHEMA_SOURCE, new File(MY_SCHEMA));
			// Parseando el documento
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			documentBuilder.setErrorHandler(new ParserErrorHandler());

			@SuppressWarnings("unused")
			Document parse = documentBuilder.parse(new File(MY_XML));

		} catch (SAXException saxEx){
			valor_retono =  false;
			System.out.println(saxEx.toString());
		} catch (Exception ex) {
			valor_retono =  false;
			System.out.println(ex.toString());
		}

		return valor_retono;
	}

	private class ParserErrorHandler extends DefaultHandler {

		@Override
		public void warning(SAXParseException e) throws SAXException {
			System.out.println("Warning: ");
			printInfo(e);
		}

		@Override
		public void error(SAXParseException e) throws SAXException {
			System.out.println("Error: ");
			printInfo(e);
		}

		@Override
		public void fatalError(SAXParseException e) throws SAXException {
			System.out.println("Error Fatal: ");
			printInfo(e);
		}
		private void printInfo(SAXParseException e) {
			System.out.println("   Publico ID: "+e.getPublicId());
			System.out.println("   Sistema ID: "+e.getSystemId());
			System.out.println("   Linea numero: "+e.getLineNumber());
			System.out.println("   Columna number: "+e.getColumnNumber());
			System.out.println("   Mensaje: "+e.getMessage());
		}
	}

}

De JSON a java

Para vivir tengo que escribir kilometros y kilometros de codigo en este mugre lenguaje (oseace java)….
Para que ustedes no pasen por lo mismo… ahi les dejo algo hecho para pasar de JSON a java


import java.util.List;
import java.util.ArrayList;

import java.util.Map;
import java.util.Iterator;

import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.util.HashMap;

public class Json2Java {

	/**
	* getList provides a List representation of the JSON Object
	* @param jsonResponse The JSON array string
	* @return List of JSONObject.
	**/
	public List getList(String jsonResponse) throws Exception {
	  List listResponse = new ArrayList();
	  if (jsonResponse.startsWith(”[”)) {
	    JSONArray jsonArray = JSONArray.fromObject(jsonResponse);
	    toJavaList(jsonArray, listResponse);
	  } else {
	    throw new Exception(”MalFormed JSON Array Response.”);
	  }

	  return listResponse;
	}

	/**
	* getMap provides a Map representation of the JSON Object
	* @param jsonResponse The JSON object string
	* @return Map of JSONObject.
	**/
	public Map getMap(String jsonResponse ) throws Exception {
	  Map mapResponse = new HashMap();
	  if (jsonResponse.startsWith(”{”)) {
	    JSONObject jsonObj = JSONObject.fromObject(jsonResponse);
	    toJavaMap(jsonObj, mapResponse);
	  } else {
	    throw new Exception(”MalFormed JSON Array Response.”);
	  }
	  return mapResponse;
	}

	/**
	* toJavaMap converts the JSONObject into a Java Map
	* @param o
	* JSONObject to be converted to Java Map
	* @param b
	* Java Map to hold converted JSONObject response.
	**/
	@SuppressWarnings(”unchecked”)
	private static void toJavaMap(JSONObject o, Map b) {
	  Iterator ji = o.keys();
	  while (ji.hasNext()) {
	    String key = (String) ji.next();
	    Object val = o.get(key);
	    if (val.getClass() == JSONObject.class) {
	      Map sub = new HashMap();
	      toJavaMap((JSONObject) val, sub);
	      b.put(key, sub);
	    } else if (val.getClass() == JSONArray.class) {
	      List l = new ArrayList();
	      JSONArray arr = (JSONArray) val;
	      for (int a = 0; a < arr.size(); a++) {
	        Map sub = new HashMap();
	        Object element = arr.get(a);
	        if (element instanceof JSONObject) {
	          toJavaMap((JSONObject) element, sub);
	          l.add(sub);
	        } else {
	          l.add(element);
	        }
	      }
	      b.put(key, l);
	    } else {
	      b.put(key, val);
	    }
	  }
	}

	/**
	* toJavaList converts JSON’s array response into Java’s List
	* @param ar
	* JSONArray to be converted to Java List
	* @param ll
	* Java List to hold the converted JSONArray response
	**/
	private static void toJavaList(JSONArray ar, List ll) {
	  int i = 0;
	  while (i < ar.size()) {
	    Object val = ar.get(i);
	    if (val.getClass() == JSONObject.class) {
	      Map sub = new HashMap();
	      toJavaMap((JSONObject) val, sub);
	      ll.add(sub);
	    } else if (val.getClass() == JSONArray.class) {
	      List l = new ArrayList();
	      JSONArray arr = (JSONArray) val;
	      for (int a = 0; a < arr.size(); a++) {
	        Map sub = new HashMap();
	        Object element = arr.get(a);
	        if (element instanceof JSONObject) {
	          toJavaMap((JSONObject) element, sub);
	          ll.add(sub);
	        } else {
	          ll.add(element);
	        }
	      }
	      l.add(l);
	    } else {
	      ll.add(val);
	    }
	    i++;
	  }
	}

}