Nuevas versiones de EasyJob, CurrículumFácil y CV-Express

Acabo de subir la última versión de EasyJob, CurrículumFácil y CV-Express. Contienen mejor soporte para envío de currículos por email, incluyendo servidores seguros con TLS y algunas opciones para evitar que el CV sea considerado spam.
 
Por lo visto, GMail y Hotmail son especialmente paranoicos en este sentido, y si se envía un email usando una cuenta de estos servicios y sin proporcionar el nombre de usuario y contraseña, el email es borrado automáticamente sin dar ningún error al usuario.  Las nuevas versiones resuelven este problema.
 
También incluyen arreglos para unos errores que se manifestaban en ciertas configuraciones de Windows Vista.

Manipular ficheros en Amazon S3 con Python y Boto

Automatizar la subida (o descarga) de ficheros a Amazon S3 con Python

Desde que empecé a usar Amazon S3 para alojar los instaladores de EasyJob Resume Builder, CurrículumFácil y CV-Express, me surgió un problema: tenía que actualizar los ficheros después de cada compilación, de forma manual.

Para evitar errores y despistes y siguiendo el principio de que "coñazo es todo aquello que no automatizas", me puse a buscar módulos Python para manipular ficheros en Amazon S3

Boto: una interfase integrada a los servicios presentes y futuros de Amazon Web Services (AWS) en Python

Para mi agradable sorpresa, me encontré con Boto, una serie de módulos python que te permiten acceder de forma programática a practicamente todos los servicos ofrecidos por Amazon Web Services. Algunos de ellos son:

  • Simple Storage Service (S3)
  • Simple Queue Service (SQS)
  • Elastic Compute Cloud (EC2)
    • Elastic Load Balancer (ELB)
    • CloudWatch
    • AutoScale
  • Mechanical Turk
  • SimpleDB (SDB)
  • CloudFront
  • Virtual Private Cloud (VPC)
Sólo he mirado lo referente a S3, y en general parece una API bastante clara y bastante estable (es a fecha de hoy un versión 1.8).

Algunos ejemplos de código con Boto y Python para acceder a "buckets" y ficheros en Amazon S3:

from boto.s3.connection import S3Connectionfrom boto.s3.key import KeyS3_ACCESS_ID = "xxxxxxxxxxxxxxxxxxxxx"S3_SECRET_ACCESS_KEY = "yyyyyyyyyyyyyyyyyyyyyyyyyy"def view_buckets():    """    Recupera una lista de los "buckets" en S3    """    #Nos conectamos a S3    c = S3Connection(aws_secret_access_key = S3_SECRET_ACCESS_KEY, aws_access_key_id=S3_ACCESS_ID)    # recuperamso los buckets    buckets= c.get_all_buckets()    c.close()    return bucketsdef get_keys_in_bucket(bucket_name):    """    Obtiene la lista de claves en un bucket    """    c = S3Connection(aws_secret_access_key = S3_SECRET_ACCESS_KEY, aws_access_key_id=S3_ACCESS_ID)    b = c.get_bucket(bucket_name)    keys = b.list()    return keysdef upload_file_to_bucket(bucket_name, file_name, s3_key):    """    Sube un fichero a un bucket    """    # Nos conectamos a s3    c = S3Connection(aws_secret_access_key = S3_SECRET_ACCESS_KEY, aws_access_key_id=S3_ACCESS_ID)    # Obtenemos el bucket    b = c.get_bucket(bucket_name)    # Subimos el fichero    k = Key(b)    k.key  = s3_key    k.set_contents_from_filename(file_name)

Instrucciones para almacenar y compartir ficheros con Amazon S3

Almacenar datos en Amazon Simple Storage Service (S3)
Outlook
 
 

Desde hace algún tiempo, el ancho de banda consumido por las descargas de EasyJob, CurrículumFácil y CV-Express está disparado y hubo que buscar alguna alternativa para almacenar las demos de los tres programas.

 

En un principio, pensé en contratar un servicio de hosting sin límites de ancho de banda, como los que ofrece JVDS . El precio era razonable (algo así como USD 60 / mes) y había visto muy buenos comentarios sobre ellos, creo que en Hacker News.

 

No obstante, al poco tiempo me enteré de la existencia de S3, un servicio de almacenamiento de datos distribuido("in the cloud" que se dice ahora) de Amazon. Basicamente es un"content delivery network", pero sin cerebro: no selecciona el servidor más próximo al cliente.

 

Los preciso parecían baratos,las tasas de transferencia muy buenas y solo se paga por lo que se usa, así que me decidí por Amazon S3.

 

Amazon S3 en pocas palabras

 

Amazon Simple Storage Service, mas conocido como Amazon S3 es un servicio de almacenamiento de datos online. Es barato, fácil de incorporar a tu servidor y  relativamente facil de administrar.  Es la misma infraestructura que utiliza Amazon para almacenar sus propios datos, así que es de esperar que los tuyos se vean tratados con el mismo mimo que probablemente dispensen a los suyos propios.

 

¿Quien necesita Amazon S3?

 

Cualquier webmaster que tenga algunos de estos problemas se vería beneficiado por Amazon S3:

 

Cualquiera que se esté quedando sin ancho de banda o pueda quedarse sin él. Si tienes tu servidor en un "hosting" compartido, y apareces en Digg o Menéame, puedes consumir todo tu ancho de banda en un periquete. Es muy posible que tu empresa de "hosting" te cierre el grifo y te dejen tirado.
  • Escasa escalabilidad: Al separar la descarga de ficheros estáticos del proceso normal de tu servidor, la respuesta de éste debería de mejorar y escalar mejor. Esto es particularmente importante cuando se está usando alguna tecnología que consume mucha memoria en el espacio de Apache, como pueda ser Django o Rails.
  • Necesidad de hacer backups online: Jungle Disk es un servicio de backup que utiliza Amazon S3 como infraestructura. No recuerdo  la cantidad de veces que me ha salvado el pellejo en los últimos meses...

     

     

     
    ¿Cómo darse de alta en Amazon S3?
     
    Lo primero es tener una cuenta en Amazon. La que usas para comprar libros sirve, no hace falta una nueva. Si  no tienes una (¿en qué planeta vives?) crea una.
     
    0outlook
     
    Los sigueintes pasos para empezar a usar Amazon S3 son:
     
     
    Crear una cuenta en AWS (Amazon Web Services)
     
    Ve a aws.amazon.com y crea una cuenta en Amazon Web Services.
     
    1outlook
     
     
    Busca Amazon Simple Storage Service (S3)
     
    Después de crear tu cuenta, te saldrá una página indicando que tu cuenta ha sido creada y que te han enviado cierta información por email.  También saldrá una lista con todos los servicios de AWS que puedes utilizar. Busca Amazon Simple Storage Service (S3).
     
    2outlook
     
    Date de Alta en Amazon Simple Storage (S3)
     
    Una vez más tienes que darte de alta (y van 3 con ésta), pero con un agravante: aquí tienes que dar los datos de tu tarjeta de crédito. Tranquilo, que aun no tienes que aflojar nada, solo pagarás cuando hagas uso del servicio. ;-)
     

    Busca el enlace que dice Sign up For This Web Service

     

    3outlook
     
     
    Access Key Id y Secrete Access Key
     
    Una vez que te hayas dado de alta, Amazon te dará lo que llama tus AWS Access identifiers. Son una especie de usuario y clave llamados, respectivamente Access Key Id y Secret Access Key. Guarda eso en algur lugar seguro.
     
    4outlook
     
    Pues con esto ya estás listo para empezar a usar Amazon S3, así que vamos a subir algunos ficheros.
     
     
    Como subir ficheros a Amazon S3
     
    Cunado empiezas, tu cuenta en Amazon S3 está vacía. En ella puedes crear "buckets" (cubos en cristiano). Un "bucket" es el Amazonés para carpeta. Puedess crear varios "buckets" y dentro de ellos es donde guardas tus ficheros.
     
    Hay una pega: los nombres de los "buckets" deben de ser únicos en todo el sisema S3 y no sólo en tu cuenta. Además sólopueden contener letras, números, puntos y guiones (-). Tienen que empezar con una letra o número, y su longitud tiene que estar entre 3 y 255 caracteres. Por si fuera poco, tampoco pueden tener pinta de direcciones IP, como 192.168.2.1
     
    En realidad, hayotra pega, el acceso a los ficheros es un poco engorroso, y tienes que usar un herramienta de algún tercero (Amazon sólo te da un API).
     
    Algunas de las mejores herramientas para subir y administrar ficheros y buckets en Amazon S3 son:
     
    S3Fox
     
    Es una extensión de Firefox que funciona como una administrador de ficheros y buckets. Es gratis y bastante bueno. Desgraciadamente, en estos momentos (Enero de 2010) no hay una versión para Firefox 3.6
     
    S3FM
     
    Esta es una herramienta online escrita en flash. Tal vez sea la ideal para empezar.
     
    CloudBerry S3 Explorer
     
    Los que hemos vendido nuestras almas inmortales al demonio de Redmond tambien tenemos esta otra opción que es gratis. Creoq ue también existe una version para Solaris, pero no estoy seguro.
     
    ¿Cómo bajar los ficheros que están en Amazon S3?
     
    Esto es algo que suele despistar al primera vez. Amazon S3 te tiene que generar una url para cada fichero. Para obtener esa url, , por ejemplo usando S3Fox, basta con hacer click con el botón derecho en el fichero y seleccionar "CopyURL to Clipboard".
     
    Las urls tendrán una pinta similar a ésta:
    http://nombre_del_bucket.s3.amazonaws.com/carpeta/nombre_del_fichero
     
    Recursos sobre Amazon S3
     
    Foro de Amazon S3: Mucha información útil, pero en Inglés.
  • Recomendaciones de administradores de archivos: http://superuser.com/questions/28510/best-amazon-s3-file-manager-utility
  • Boto: Módulo python que permite manipular casi todos los servicios de Amazon Web Services, incluido Amazon S3.

  • A high performance alternative to Dictionary and Collection: Treaps in Visual Basic (VB6)

    VB6 Collection Performance

     

    The Collection is the single data structure provided by VB5 and VB6, and was designed with the “one size fits all” philosophy. It allows you to access the elements in it by a key and also sequentially, and as most multi-use tools, doesn’t perform very well in either scenario.

     

    Much worse than the performance issues, are the serious limitations in Collection: as soon as you add a key, there’s no way to change it, and even worse, there’s no way to know which keys have been entered.

     

    Dictionary

     

     

     The Dictionary object came with the MS Scripting runtime dll and provides a much better implementation than the Collection. Even though much better than the humble Collection, Dictionary’s iteration methods are still a bit primitive and wasteful (from a performance point of view) when it contains many items.

     

    While delivering applications that used Dictionary (EasyJob Resume Builder http://www.easyjob.net), I encountered several serious issues that forced me to ditch it:

     

    ·         The MS Scripting Runtime dll (sccrun.dll) wasn’t correctly registering in some systems, making the app crash.

    ·         On some systems, the creation of a Dictionary object was being blocked by over enthusiastic security software that tried to prevent any script from running.

     

    Enter the Treap

     

    (hardcore nerd-talk ahead: you may skip this section if you want)

     

    I have no idea how the Dictionary or Collection are implemented, but they are probably based on a Balanced Binary Tree or a Hash Table.

     

    The Treap is also a Binary Balanced Tree, but with a twist that makes it very simple (if compared to other BBT’s, such as AVL Trees or Red-Black Trees) and very efficient in terms of both speed and memory.

     

    AVL and Red-Black trees are cool, because they guarantee O(log n) insert, lookup and deletion time, but are complicated to implement, as their rebalancing routines are complex.  However, if we are willing to accept a probabilistic assurance of good performance, Treaps provide a much simpler solution.

    The stroke of genius behind the Treap is to use randomness to keep a binary tree balanced. Binary search trees are great as long as they remain balanced. But if the elements are inserted in order, then the tree will turn into a linked list with very poor O(log n) performance. On the other hand if the elements are inserted in random order, then the tree will remain balanced.

     

    So here’s the magic cookie: no matter how you add the elements to the Treap, it will have the same structure it would have if the elements had been inserted in random order into a binary search tree.

     

    The Treap achieves this by using a random priority field in every node. The Treap behaves as a binary search tree with respect to the keys in the nodes, and also as a Heap with respect to the priorities. Hence the name: Treap = Tree + Heap.

     

    The algorithm to insert a new node is similar to that of red-black trees:

    1.      Find the unique leaf where the node can be inserted while preserving the Binary Search Tree property.

    2.      Perform a series of tree rotations to satisfy the Heap ordering property.

     

    Treap for Visual Basic 6

     

    The main class is CTreap.

     

    Values can be anything you can put into a Variant (strings, longs, singles, objects, other Treaps, whatever).

    Keys can be almost anything, except Arrays: dates, strings, numbers, objects, etc….

    If you try to add an Array as a key, you will get a Wrong Key Type error.

     

    Methods

     

    add(ByVal aKey As Variant, ByRef aValue As Variant) As Boolean

     

    Adds a value to the Treap. Unlike a Collection, the key is mandatory. Returns true if the key wasn’t already present and returns false if the key was already present (it won’t add the value in this case).

     

    clear()

     

    Zaps the whole Treap, leaving it empty.

     

    getValue(ByVal aKey As Variant, ByRef aValue As Variant) As Boolean

     

    Retrieve a value by its key.

    Since VB's assignment syntax is different for objects and non-objects, you can't just return the value, as the user won't know, a priori, which syntax (set x = y or x = y) to use. So we take a ByRef parameter and assign it to the value. This way the utter ugliness remains relatively hidden.

     

    Whoever designed this should be sent to Abu Graib.

     

    Returns true if the value was found, and false if it was not found.

    setValue(ByVal aKey As Variant, ByVal aNewValue As Variant) As Boolean

     

    Sets the new value for an existing node. Returns True if the node exists, and False if it doesn't.

     

    changeKey(ByVal oldKey As Variant, ByVal newKey As Variant) As Boolean

     

    Change the key of an existing node. If the node exists, return true, otherwise, return false.

     

    exists(ByVal aKey As Variant) As Boolean

     

    Detects the presence of a key.

     

    isEmpty() As Boolean

     

    Returns True if the Treap is empty.

     

    remove(ByVal aKey As Variant)

     

    Remove an element.

     

    Keys(Optional ascendingOrder As Boolean = True) As IIterator

     

    This is quite different from Collection and Dictionary. It returns an instance of CKeyIterator ( a class that implements the IIterator interface).

     

    The only methods of CKeyIterator that you have to worry about are hasMore() (returns True until you reach the last key in the Treap) and getItem(item As Variant).

     

    Example:

     

    ‘Iterate through the keys forwards and backwards

    ‘at the same time

     

    Dim vKey As Variant

    Dim rForwards As IIterator

    Dim rBackwards As IIterator

     

     

    Set rForwards = m_rtreap.keys(True)

    Set rBackwards = m_rtreap.keys(False)

     

    Do While rForwards.hasMore

        Call rForwards.getItem(vKey)

        Debug.Print CStr(vKey)

        Call rBackwards.getItem(vKey)

        Debug.Print CStr(vKey)

    Loop

     

    Values(Optional ascendingOrder As Boolean = True) As IIterator

     

    Similar to Keys(). Returns an instance of CValueIterator. Allows you to iterate the values in a Treap.

    Properties

     

    Count

     

    Read only. Returns the number of elements in the Treap.

     

    Events

     

    If you declare it with withevents, you can observe the changes in the treap with these events:

     

    Public Event onAdd(ByVal Sender As CTreap,

             ByVal newKey As Variant,

             ByVal newValue As Variant)

     

    Public Event onKeyChange(ByVal Sender As CTreap,

    ByVal oldKey As Variant,

    ByVal newKey As Variant)

     

    Public Event onValueChange(ByVal Sender As CTreap,

    ByVal Key As Variant,

    ByVal newValue As Variant)

     

    Public Event onRemove(ByVal Sender As CTreap,

      ByVal oldKey As Variant)

     

    Public Event onEmpty(ByVal Sender As CTreap)

     

     

     

    Contact

     

    If you find any bugs ore have any suggestions, please drop me a line.