31 dic 2010

Center DIV/Container/Layer IE : flumpCakes

This is a demo to show how to center a DIV in the center of the screen from Internet Explorer 4 and up. Including all modern browsers too.
The trick is to add text-align: center; to the body selector, then add the usual margin: 0 auto; to the container selector which you want centered. Apply text-align: left; on the container to counter the center align for body.
View this pages source code to see how it's done

28 dic 2010

Message Broker help: XML standalone

XML standalone

El elemento XML standalone define la existencia de una DTD definida externamente.
Es un elemento de valor y almacena los datos correspondientes al valor de la serie autónoma de la declaración. Es siempre hijo del elemento XmlDecl. Los valores válidos para el elemento autónomo son yes y no. An example is shown below:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE s1 PUBLIC "http://www.ibm.com/example.dtd" 
"example.dtd" >
<s1>.........</s1>
Un valor de no indica que este documento XML no es autónomo y depende de una DTD definida externamente. Un valor de yes indica que el documento XML es un documento independiente. Sin embargo, dado que el release actual de WebSphere Message Broker no resuelve las DTD definidas externamente, el valor de standalone (autónomo) no es relevante y se ignora.

15 dic 2010

Maven - Frequently Asked Technical Questions

  1. How do I prevent "[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!"
  2. How do I prevent including JARs in WEB-INF/lib? I need a "compile only" scope!
  3. How do I list available plugins?
  4. How do I determine what version of a plugin I am using?
  5. How can I use Ant tasks in a Maven build?
  6. How can I use Maven features in an Ant build?
  7. How do I set up Maven so it will compile with a target and source JVM of my choice?
  8. Is it possible to create my own directory structure?
  9. Where is the source code? I couldn't seem to find a link anywhere on the Maven2 site.
  10. Maven can't seem to download the dependencies. Is my installation correct?
  11. I have a jar that I want to put into my local repository. How can I copy it in?
  12. How do I unsubscribe from Maven mailing lists?
  13. How do I skip the tests?
  14. How can I run a single unit test?
  15. Handle special characters in site
  16. How do I include tools.jar in my dependencies?
  17. Maven compiles my test classes but doesn't run them?
  18. Where are Maven SNAPSHOT artifacts?
  19. Where are the Maven XSD schemas?
  20. Maven doesn't work, how do I get help?
  21. How to produce execution debug output or error messages?
  22. What is a Mojo?
  23. How to find dependencies on public Maven repositories?

An introduction to Maven 2 - JavaWorld

Maven is a popular open source build tool for enterprise Java projects, designed to take much of the hard work out of the build process. Maven uses a declarative approach, where the project structure and contents are described, rather then the task-based approach used in Ant or in traditional make files, for example. This helps enforce company-wide development standards and reduces the time needed to write and maintain build scripts.
The declarative, lifecycle-based approach used by Maven 1 is, for many, a radical departure from more traditional build techniques, and Maven 2 goes even further in this regard. In this article, I go through some of the basic principals behind Maven 2 and then step through a working example. Let's start by reviewing the fundamentals of Maven 2.

The project object model

The heart of a Maven 2 project is the project object model (or POM for short). It contains a detailed description of your project, including information about versioning and configuration management, dependencies, application and testing resources, team members and structure, and much more. The POM takes the form of an XML file (pom.xml), which is placed in your project home directory. A simple pom.xml file is shown here:
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/maven-v4_0_0.xsd">
  4.0.0
  com.javaworld.hotels
  HotelDatabase
  war
  1.0-SNAPSHOT
  Maven Quick Start Archetype
  http://maven.apache.org
  
     
        junit
        junit
        3.8.1
        test
     
  


The Maven 2 directory structure

Much of Maven's power comes from the standard practices it encourages. A developer who has previously worked on a Maven project will immediately feel familiar with the structure and organization of a new one. Time need not be wasted reinventing directory structures, conventions, and customized Ant build scripts for each project. Although you can override any particular directory location for your own specific ends, you really should respect the standard Maven 2 directory structure as much as possible, for several reasons:
  • It makes your POM file smaller and simpler
  • It makes the project easier to understand and makes life easier for the poor guy who must maintain the project when you leave
  • It makes it easier to integrate plug-ins
The standard Maven 2 directory structure is illustrated in Figure 1. In the project home directory goes the POM (pom.xml) and two subdirectories: src for all source code and target for generated artifacts.

Figure 1. The standard Maven 2 directory layout
The src directory has a number of subdirectories, each of which has a clearly defined purpose:
  • src/main/java: Your Java source code goes here (strangely enough!)
  • src/main/resources: Other resources your application needs
  • src/main/filters: Resource filters, in the form of properties files, which may be used to define variables only known at runtime
  • src/main/config: Configuration files
  • src/main/webapp: The Web application directory for a WAR project
  • src/test/java: Unit tests
  • src/test/resources: Resources to be used for unit tests, but will not be deployed
  • src/test/filters: Resources filters to be used for unit tests, but will not be deployed
  • src/site: Files used to generate the Maven project Website

Project lifecycles

Project lifecycles are central to Maven 2. Most developers are familiar with the notion of build phases such as compile, test, and deploy. Ant has targets with names like those. In Maven 1, corresponding plug-ins are called directly. To compile Java source code, for instance, the java plug-in is used:
 $maven java:compile


In Maven 2, this notion is standardized into a set of well-known and well-defined lifecycle phases (see Figure 2). Instead of invoking plug-ins, the Maven 2 developer invokes a lifecycle phase: $mvn compile.

Figure 2. Maven 2 lifecycle phases
Some of the more useful Maven 2 lifecycle phases are the following:
  • generate-sources: Generates any extra source code needed for the application, which is generally accomplished using the appropriate plug-ins
  • compile: Compiles the project source code
  • test-compile: Compiles the project unit tests
  • test: Runs the unit tests (typically using JUnit) in the src/test directory
  • package: Packages the compiled code in its distributable format (JAR, WAR, etc.)
  • integration-test: Processes and deploys the package if necessary into an environment where integration tests can be run
  • install: Installs the package into the local repository for use as a dependency in other projects on your local machine
  • deploy: Done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects
Many other lifecycle phases are available. See Resources for more details.
These phases illustrate the benefits of the recommended practices encouraged by Maven 2: once a developer is familiar with the main Maven 2 lifecycle phases, he should feel at ease with the lifecycle phases of any Maven project.
The lifecycle phase invokes the plug-ins it needs to do the job. Invoking a lifecycle phase automatically invokes any previous lifecycle phases as well. Since the lifecycle phases are limited in number, easy to understand, and well organized, becoming familiar with the lifecycle of a new Maven 2 project is easy.

Transitive dependencies

One of the highlights of Maven 2 is transitive dependency management. If you have ever used a tool like urpmi on a Linux box, you'll know what transitive dependencies are. With Maven 1, you have to declare each and every JAR that will be needed, directly or indirectly, by your application. For example, can you list the JARs needed by a Hibernate application? With Maven 2, you don't have to. You just tell Maven which libraries you need, and Maven will take care of the libraries that your libraries need (and so on).
Suppose you want to use Hibernate in your project. You would simply add a new dependency to the dependencies section in pom.xml, as follows:
  
     hibernate
     hibernate
     3.0.3
     compile
  


And that's it! You don't have to hunt around to know in which other JARs (and in which versions) you need to run Hibernate 3.0.3; Maven will do it for you!
The XML structure for dependencies in Maven 2 is similar to the one used in Maven 1. The main difference is the scope tag, which is explained in the following section.

Dependency scopes

In a real-world enterprise application, you may not need to include all the dependencies in the deployed application. Some JARs are needed only for unit testing, while others will be provided at runtime by the application server. Using a technique called dependency scoping, Maven 2 lets you use certain JARs only when you really need them and excludes them from the classpath when you don't.

26 oct 2010

How to submit a HTML form on enter keypress

Pues aquí va un sencillo código javascript que permite enviar un formulario html al pulsar enter.

document.onkeypress = processKey;

function processKey(e)
{
if (null == e)
e = window.event ;
if (e.keyCode == 13) {
/* funcion a implementar */
submitForm() ;
}
}

claro y simple.

P.D:
Me gusta mas el titulo en inglés ( How to... )
Escribir esto es castellano tiene su historia...

10 sept 2010

StringBuffer

Clase JAVA que representa una secuencia de caracteres modificables en cualquier momento por cualquier proceso (safe-thread).

Los métodos de StringBuffer son synchronized donde sea necesario pudiendo usarse de forma segura en un escenario multiproceso.
De forma que las operaciones realizadas sobre una instancia se comportan como si hubieran ocurrido en serie, pero manteniendo la consistencia de las llamadas de cada uno de los métodos.

Caracteristicas principales

Los métodos Append e insert, vienen sobrecargados para aceptar cualquier tipo de dato, que muy eficientemente lo transformará en una secuencia de caracteres.

Además la clase autogestiona su capacidad. Si se queda sin espacio reserva nuevo.

Una opción para un solo proceso (single-thread) de esta clase es StringBuilder

9 sept 2010

Reset mysql root password on Windows ( Metodo infalible)

Tras muchos quebraderos de cabeza tras olvidar la clave root del mysql en mi máquina local, por fin he descubierto como hacerlo sin problemas...

Muchos sitios web, hablan de instrucciones por linea de comandos, etc...
Todos estos métodos que he probado, siempre fallan, por alguna propiedad de nuestro servidor mysql... que causa un error e impide ejecutar las tareas que nos dictan..

Existe un método infalible.
Muchos habréis probado a desinstalar el mysql server, viendo con horror en la nueva instalación, como os pide el password antiguo una y otra vez...

Pues bien en Windows 7 existe una carpeta llamada ProgramData, que en otros windows estará en users/user/appdata o alguna ruta parecida...
borra la carpeta de mysql y reinstala tu mysql.. Problema resuelto.

Diréis vaya cosa...
Pues me da igual... este apunte es para mi!
ya que cada vez que olvido el password del root de mysql, pierdo 5 horas en volver a ponerme a funcionar.

ea!

27 ago 2010

Could not reliably determine the server's fully qualified domain name Error

Utilizando Apache Web Server sobre Windows7, y creo que Vista también, por los posts que he leído en la red, nos podemos encontrar con el siguiente error:

Could not reliably determine the server's fully qualified domain name, using 192.168.1.128 for ServerName

... o cualquier otra IP según vuestro rooter.

Tras leer varios posts acerca de como solucionar el problema en vano, os voy a contar un pequeño truco para corregirlo, sin entrar mucho en la raiz del problema, ya que mis conocimientos administrativos sobre Windows7 aún son muy escasos.

Problema

Ocurría cuando accedía a algún virtual host definido en el Server.
Tras comprobar que la configuración del Apache esta bien, y también la configuración del archivo hosts... conluimos que tiene que ser un problema de permisos sobre alguno de estos archivos.

Supongo que todo tiene que ver al editar estos archivos, los permisos quedan modificados de tal forma que chocan con las reglas de seguridad de estos sistemas operativos que son más restrictivos.

Solución

Copiar algún archivo de esas mismas carpetas y del mismo tipo que los archivos de configuración que no hayamos modificado.
Copiar el contenido de nuestros archivos de configuración y pegarlo en estas copias, con algún editor de texto básico que no haga más operaciones en el background de su acción guardar.

Sustituir las copias por los archivos... y todo debería estar funcionando.

22 ago 2010

5 Common SEO Mistakes with Web Page Titles

Page titles are one of the most powerful on-site search engine ranking factors that you have control over but website owners often neglect them.

Whether your intention is to improve your search engine visibility or make your website more meaningful and interoperable, you should avoid these five common pitfalls when coming up with page titles.

What Are Web Page Titles?

A web page title is the value you assign the "title" tag that’s typically found on top of an HTML/XHTML document inside the "head" tag.
Most web browsers will display the web page title at the top of the browser window and/or in the browser tab.
For example, the following title:
10 SEO Tips to Remember When Building Your Site
Shows up like this in Google Chrome, Mozilla Firefox, and Microsoft Internet Explorer:

And then, this is how Google displays the title value (after a search query of "seo tips remember"):
value" width="550" height="164">
Now that we are all synced up on what exactly web page titles are, let’s discuss popular mistakes that I see with web page titles.

1. Not Having a Title

There is a tremendous number of websites that don’t have a title tag or that use a default title like "Untitled Document". Just try a search in Google for "untitled document" and you won’t believe the millions of results that matches your search.
Not Having a Title
Because search engines use your title tag to display in their search results, not having one — or having one that isn’t meaningful — makes it hard to find and index your pages.
Page titles give a web page some context. It tells a web robot like Google’s search spider what the web page is about.

2. Page Titles That Are Too Short or Too Long

Even though this is not a massive issue, short page titles will limit the potential of a page to rank for several keywords. Google, for example, can display up to 70 characters in their search engine results page (SERP) — why not take advantage of that?
But don’t overdo it. Keep in mind that the more keywords there are in the title, the more diluted they become. Having too many keywords in the page title, although visible by Google, can lead to the common issue of keyword cannibalization (which we will talk about next).
Terms that appear first in the title are the ones that will be given more importance. For example, if a web page talks about how to repair a broken hard drive on a Dell XPS laptop and the main keywords are "repair", "Dell", and "XPS", a title like:
DIY: How to Repair a Broken Hard Drive on a Dell XPS Laptop
Can be revised to:
Repair a Dell XPS Laptop's Broken Hard Drive
Notice how the key terms are closer to the beginning in the second example, and that it is shorter than the first example. Not only is it better for search engine ranking, but it’s also easier to read and comprehend.
Devise great titles that give your web pages meanings, and remember that web users want information quickly — don’t make them have to think about what your page titles are by writing informative page titles that are neither too short and lacking information or too long and hard to read.

3. Keyword Cannibalization

This is a situation when pages titles are stuffed with too many keywords. Keyword-stuffing is an unscrupulous tactic that a few SEO consultants use to improve their clients’ search engine rankings. Though I am an SEO consultant myself, I don’t recommend blatantly loading your pages with keywords because not only does it affect your search engine ranking’s effectiveness, but is also the reason that we sometimes see non-relevant web pages ranking highly for a specific keyword.
Because your web pages are (or should be) distinct and should have unique content, the same should be the case with page titles. Repeating the same keywords in various pages regardless of whether or not they are relevant to that particular page is not going to help, mainly for two reasons:
  1. Irrelevant web pages may be picked up by the search engines, but will have high bounce rates as it doesn’t convert effectively due to the fact that the page isn’t what the searcher is looking for
  2. It violates Google’s mantra of "Don’t be evil"

4. Using the Company/Site Name in All Web Pages

As previously said, Google displays up to 70 characters of a given page title in their SERPs. It does see longer ones, though, and despite what many SEO professionals preach, it isn’t a huge problem to have page titles that are greater than 70 characters in a page title.
Nevertheless, you need to think of what should and shouldn’t appear in the title. Many website owners tend to include their business name in the title, some of which can be very lengthy. What is even worse is that they want their name to appear first in every single web page.
Including your company name (unless it’s a search term that will likely be used), is unnecessary, and is consistent with some of the mistakes I’ve discussed earlier.
For example, study this title:
ACME Exporting/Importing Company, LLC: Export Surfboards to Hawaii
With the page title including the company’s name, it is using 37 more characters (with spaces)!
Search engine ranking might be better if it was simply:
Export Surfboards to Hawaii
It would make sense displaying your company name in the homepage, contact page, and about page but avoid them in content pages.

5. Duplicate Web Page Titles

Another common mistake is having duplicate page titles. This makes it difficult to determine which page is which when they are all displayed in search engine results pages.
As previously said, all of your web pages should be unique — so by logic, all of your web page titles should also be unparalleled.

Related Content

6 ago 2010

Efectos con Mootools

Dentro de la librería Mootools, nos encontramos los siguientes recursos para construir efectos para nuestras webs:

Clase Fx

La clase Fx es la clase base para el core de Mootools para realizar varias clases derivadas, que implementan diversos tipos de efectos útiles para enriquecer la experiencia de usuario.

Es importante, no obstante, conocer un poco esta clase, o al menos tenerla en cuenta cuando consultemos la documentación de Mootools, porque tiene muchas cosas que son comunes a todas las clases derivadas para hacer efectos.

Clases que heredan de Fx

Fx.CSS

Esta clase tiene funcionalidades para interpretar estilos y clases CSS.
Todos los métodos y propiedades de esta clase son privados.
Sirve para que las otras clases de Fx la utilicen.

Fx.Tween

Una clase que sirve para hacer una transición de cualquier propiedad CSS, de un valor a otro. Con ella podremos hacer efectos con cualquier duración, de modo que su presentación sea suave. Por ejemplo si hacemos un efecto para alterar la propiedad "top" de un elemento de la página, desde el valor 0 al 100, lo que ocurrirá es que el elemento se moverá por la página 100 píxeles hacia abajo, desde el pixel 0 al 100. Si habíamos configurado el estilo con una duración de, por ejemplo, 1 segundo, el movimiento del elemento, desde que está en la posición inicial a que llega a la final, tardará 1 segundo, con lo que el usuario lo verá suavizado.

Fx.Morph

Esta clase es parecida a Fx.Teen, con la diferencia que permite alterar varias propiedades CSS al mismo tiempo.

Fx.Transitions

Para hacer efectos más detallistas, que ajustan el proceso de transición con una función matemática. Por ejemplo esto sirve para hacer un desplazamiento de un elemento, pero donde la velocidad del movimiento no es linear, sino que es por ejemplo exponencial, siendo más rápido al inicio o al final del movimiento. Existen diferentes funciones matemáticas preestablecidas para genera efectos simpáticos, como movimientos con un rebote cuando llegan al final o que se pasan y luego vuelven, como si fuera un elástico.

Método fade()

Podríamos hacer un fundido de opaco a transparente con la sentencia:
$("mielemento").fade("out");

Para hacer un fundido de transparente a opaco, se puede invocar el método fade() de esta manera:
$("mielemento").fade("in");

Método highlight()

$("mielemento").highlight("#ccc");
El método genera un efecto de cambio gradual del color de fondo del elemento, desde su color actual hasta el color que le enviamos por parámetro, volviendo de nuevo a su color original. Si el elemento anteriormente no tenía color asignado, o si era transparente, se toma el blanco como color por defecto del elemento.

$("mielemento").highlight("#f07990","#ccc");
Doble transición de color.

Método tween()

Tiene 3 parámetros:
- nombre de atributo CSS.
- valor inicial, ( con unidades ).
- valor final, ( con unidades ).

El efecto que resultará es una transición entre el valor inicial y el final.

$("micapa").tween("width", "0px", "300px");
Transforma el elemento cuyo id="micapa" en ancho de 0 a 300 px.


$("micapa").tween("width", "300px");
En este caso solo recibe el valor final.

Clase Fx.Tween

Sirve para hacer efectos avanzados.
Para hacer efectos con esta clase tenemos que instanciar un objeto Fx.Tween. Al constructor tenemos que enviarle el identificador del elemento HTML sobre el que queramos hacer los efectos, así como otros datos opcionales que veremos más tarde.

miEfecto = new Fx.Tween("micapa");

Con esto tenemos un objeto en la variable "miEfecto" con el que podemos invocar diversas acciones para realizar transiciones mendiante la alteración de propiedades CSS del elemento "micapa".
Lo más básico que podremos desear hacer con esta clase es poner en marcha un efecto y para ello disponemos del método start(), que podemos usar por ejemplo de esta manera:

miEfecto.start("background-color", "#ff8800");

Datos opcionales

Forma de setear ciertos parámetros avanzados de los efectos Mootools, como definir la duración o la propiedad CSS que se debe alterar cuando se ponga en marcha el efecto.
Todos estos parámetros opcionales se envían en un objeto "options" al constructor.

efectoColorTexto = new Fx.Tween("capatxt", {
property: 'color',
duration: 'long',
fps: 100
});


property: 'color'
Sirve para especificar que la propiedad CSS sobre la que queremos hacer el efecto es "color", para cambiar el color del texto.

duration: 'long'
Sirve para indicar que la duración del efecto debe ser larga ("long" equivale a 1 segundo de duración). Podríamos haber especificado una duración con un número en milisegundos (ms) u otros valores en texto como "normal" que equivale a 500 ms o "short" que equivale a 250 ms.

fps: 100
Con fps indicamos los "frames por segundo", es decir, la cantidad de veces que se actualiza la propiedad CSS en cada segundo que ocupe la transición.

Una vez creado el objeto de la clase Fx.Tween, habría que invocar al método start() para iniciar el efecto, de manera similar a como vimos en el ejemplo anterior. Sin embargo, como en este caso ya hemos indicado la propiedad CSS que se debe alterar en las "options", dentro del la propiedad "property", ya no es necesario indicar esa propiedad en el método start().

efectoColorTexto.start("#ff8800");


Nota: como podremos ver en la documentación de Mootools, el método start() de la clase Fx.Tween recibe como mínimo un parámetro y como máximo tres. El único parámetro que es obligado es el valor de finalización del efecto. Los otros dos parámetros opcionales son el nombre del atributo CSS a alterar y el valor del atributo de inicio para el efecto.

myFx.start([property,] [from,] to);

Eventos de efectos en Mootools

Para codificar comportamientos a realizar en respuesta a eventos tenemos dos posibilidades:

1. Codificar el evento dentro de los "options" enviados al contructor de la clase.

Eventos en la clase Fx y las que heredan de ésta
Los eventos que soportan las clases de efectos en Mootools, es decir, las clases que dependen en la jerarquía de herencia de Fx, son los siguientes:

* Evento start: que se produce cuando el efecto comienza a ejecutarse
* Evento cancel: que se lanza cuando se para manualmente un efecto
* Evento complete: ocurre en el momento que el efecto termina su ejecución
* Evento chainComplete: en caso de encadenar varios eventos con chain, algo que no hemos visto todavía en el manual, se lanza cuando la pila de efectos ha sido completada.

var efecto = new Fx.Tween("capaefectos",{
property: 'width',
duration: 1000,
unit: "px",
onStart: function(){
$("mensaje").set("html", "Comenzando el efecto...");
}
});



2. Codificar el evento por medio del método addEvent() sobre el objeto ya instanciado.

Ahora veremos otro modo posible de asignar eventos, que se hace con el propio evento instanciado y el método addEvent.

efecto.addEvent("complete", function(){
$("mensaje").set("html", "Terminó el efecto.");
});


Con este código conseguimos que al efecto, instanciado en la variable "efecto", se le añada un evento "complete", que se ejecutará cuando el proceso del efecto termine.

El código del evento es bien simple, ya que sólo actualiza el HTML de la capa "mensaje".

Ahora, cuando iniciemos el efecto y éste se complete, se actualizará el texto de la capa mensaje. Sólo nos quedaría llamar al método start() del evento, que invocaremos cuando el usuario haga clic sobre un par de enlaces creados en la página.

$("enlaceencoger").addEvent("click", function(e){
e.stop();
efecto.start(100);
});
$("enlaceestirar").addEvent("click", function(e){
e.stop();
efecto.start(750);
});


Tenemos pues dos enlaces con identificadores "enlaceencoger" y "enlaceestirar", que llaman al método start() del efecto creado anteriormente, enviando el valor numérico que queremos asignar a la propiedad CSS dada de alta en las "options", que era width. Además, como en las "options" ya habíamos asignado las unidades CSS "px", con pasar un valor numérico a start(), será suficiente, porque el efecto ya sabe que son píxeles lo que estamos midiendo.

Podemos ver el código :


window.addEvent("domready", function(){
var efecto = new Fx.Tween("capaefectos",{
property: 'width',
duration: 1000,
unit: "px",
onStart: function(){
$("mensaje").set("html", "Comenzando el efecto...");
}
});
efecto.addEvent("complete", function(){
$("mensaje").set("html", "Terminó el efecto.");
});

$("enlaceencoger").addEvent("click", function(e){
e.stop();
efecto.start(100);
});
$("enlaceestirar").addEvent("click", function(e){
e.stop();
efecto.start(750);
});
});

Y el body tendría algo así
<div id="capaefectos" style="width: 500px; background-color: #ffcc66; padding: 10px; overflow: hidden;">
Esta capa es sobre la que voy a crear los efectos con la clase Fx.Tween, a los que asignaremos diferentes eventos para probar.
</div>
<a href="#" id="enlaceestirar">Estirar capa con efecto</a>
<a href="#" id="enlaceencoger">contraer capa con efecto</a>
<div id="mensaje"></div>

8 jul 2010

HTML iframe tag

Definition and Usage


The <iframe> tag defines an inline frame that contains another document.




Browser Support


Internet Explorer Firefox Opera Google Chrome Safari


The <iframe> tag is supported in all major browsers.




Differences Between HTML and XHTML


NONE




Tips and Notes


Tip: To deal with browsers that do not understand iframes, place the text you want between the opening <iframe> tag and the closing </iframe> tag.




Optional Attributes


DTD indicates in which HTML 4.01/XHTML 1.0 DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD
align left
right
top
middle
bottom
Deprecated. Use styles instead.
Specifies the alignment of an iframe according to surrounding elements
TF
frameborder 1
0
Specifies whether or not to display a border around an iframe TF
height pixels
%
Specifies the height of an iframe TF
longdesc URL Specifies a page that contains a long description of the content of an iframe TF
marginheight pixels Specifies the top and bottom margins of an iframe TF
marginwidth pixels Specifies the left and right margins of an iframe TF
name name Specifies the name of an iframe TF
scrolling yes
no
auto
Specifies whether or not to display scrollbars in an iframe TF
src URL Specifies the URL of the document to show in an iframe TF
width pixels
%
Specifies the width of an iframe TF


Standard Attributes

The <iframe$gt; tag supports the following standard attributes:

Attribute Value Description DTD
class classname Specifies a classname for an element TF
id id Specifies a unique id for an element TF
style style_definition Specifies an inline style for an element TF
title text Specifies extra information about an element TF

More information about Standard Attributes.


Event Attributes

According to the W3C, the <iframe> tag does not support any event attributes.

However, the onload event is supported in all browsers.

More information about Event Attributes.

5 jul 2010

CSS display property

Definition and Usage

The display property specifies the type of box an element should generate.

Default value: inline
Inherited: no
Version: CSS1
JavaScript syntax: object.style.display="inline"


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The display property is supported in all major browsers.

Note: No versions of Internet Explorer (including IE8) support the property values "inline-table", "run-in", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", or "table-row-group".



Property Values


)
Value Description
none The element will generate no box at all
block The element will generate a block box (a line break before and after the element)
inline The element will generate an inline box (no line break before or after the element). This is default
inline-block The element will generate a block box, laid out as an inline box
inline-table The element will generate an inline box (like <table>, with no line break before or after)
list-item The element will generate a block box, and an inline box for the list marker
run-in The element will generate a block or inline box, depending on context
table The element will behave like a table (like <table>, with a line break before and after)
table-caption The element will behave like a table caption (like <caption>)
table-cell The element will behave like a table cell
table-column The element will behave like a table column
table-column-group The element will behave like a table column group (like
table-footer-group The element will behave like a table footer row group
table-header-group The element will behave like a table header row group
table-row The element will behave like a table row
table-row-group The element will behave like a table row group
inherit Specifies that the value of the display property should be inherited from the parent element

30 jun 2010

HTML5: area / map

areaimage-map hyperlink # T

The area element represents either a hyperlink with some text and a corresponding area on an image map, or a dead area on an image map.

Permitted content #

empty (void element)

Permitted attributes #

common attributes & alt & href & target & rel & media & hreflang & type & shape="rect" & coords or shape="circle" & coords or shape="poly" & coords or shape="default"

Descriptions for attributes specific to this element #

alt = normal character data
The fallback content for the image map.
href = URI
A URL that provides the destination of the hyperlink for this area.
target = browsing-context name or keyword
A name or keyword giving a browsing context for UAs to use when following the hyperlink for this area.
rel = tokens NEW
A list of tokens that specify the relationship between the document containing the area and the destination indicated by the area.
media = media-query list NEW
The media for which the destination of the hyperlink was designed.
hreflang = language tag NEW
The language of the destination of the hyperlink.
type = MIME type
The MIME type of the destination of the hyperlink.
shape = "rect" & coords = rectangle
Specifies that the shape of the area of this hyperlink on the image map is a rectangle.
shape = "circle" & coords = circle
Specifies that the shape of the area of this hyperlink on the image map is a circle.
shape = "poly" & coords = polygon
Specifies that the shape of the area of this hyperlink on the image map is a polygon.
shape = "default"
Specifies that the shape of the area of this hyperlink on the image map is a rectangle that exactly covers the entire image.

Additional constraints and admonitions #

  • The area element must have an ancestor map element.
  • The nohref attribute on the area element is obsolete. Omitting the href attribute is sufficient.

Tag omission #

The area element is a void element. An area element must have a start tag but must not have an end tag.

Permitted parent elements #

any element that can contain phrasing elements

DOM interface #

interface HTMLAreaElement : HTMLElement {
attribute DOMString alt;
attribute DOMString coords;
attribute DOMString shape;
stringifier attribute DOMString href;
attribute DOMString target;
attribute DOMString rel;
readonly attribute DOMTokenList relList;
attribute DOMString media;
attribute DOMString hreflang;
attribute DOMString type;

// URL decomposition IDL attributes
attribute DOMString protocol;
attribute DOMString host;
attribute DOMString hostname;
attribute DOMString port;
attribute DOMString pathname;
attribute DOMString search;
attribute DOMString hash;
};

Typical default display properties #

area {
display: none; }

Definition and Usage

The <map> tag is used to define a client-side image-map. An image-map is an image with clickable areas.

The name attribute is required in the map element. This attribute is associated with the <img>'s usemap attribute and creates a relationship between the image and the map.

The map element contains a number of area elements, that defines the clickable areas in the image map.

 Tips and Notes
Note: The area element is always nested inside the map element. The area element defines the regions in the image map.

Attributes

Attribute Value Description
name unique name Defines a unique name for the map tag, so it can be referred to.

Standard Attributes

The <map> tag also supports the Standard Attributes in HTML 5.

Event Attributes

The <map> tag also supports the Event Attributes in HTML 5.


26 jun 2010

Virtual hosts on Apache 2.2

Creando servidores virtuales en Apache 2.2


Apache 2.2 adopta una estructura modular para sus ficheros de configuración.
Así la definición de servidores virtuales la realizamos en un archivo externo extra/httpd-vhosts.conf.
Incluimos este archivo dentro del archivo de configuración principal httpd.conf.
También impone unas restricciones más severas en acceso que versiones anteriores, por lo que debemos configurar propiedades extra para conseguir acceso a los servidores virutales y no obtener el siguiente mensaje:

Forbidden

  • You don't have permission to access /index.php on this server.
Debido a estos permisos más estrictos, recomiendo crear un directorio raiz donde colgar nuestros servidores virtuales.


Suponemos que nuestro directorio de servidores virtuales es D:\vhosts.

Nota: Las restricciones de seguridad de Windows Vista y Windows 7 previenen el guardar datos en los archivos que mencionamos en estas instrucciones, incluso aunque estes logado como administrador.


  • Crear un directorio dentro de D:\htdocs para cada servidor virtual.
  • Abre C:\WINDOWS\system32\drivers\etc\hosts con tu editor de textos, y añade una línea como éstas por cada servidor virutal.


    127.0.0.1 localhost
    127.0.0.1 vhExample

  • Abre conf\httpd.conf en tu editor de texto y busca la sección #Virtual hosts ,y descomenta la línea
    #Include conf/extra/httpd-vhosts.conf
  • Abre conf\extra\httpd-vhosts.conf en tu editor de texto. La imagen muestra su típica estructura:

    Contents of   httpd-vhosts.conf
  • Al comienzo del archivo insertamos las siguientes líneas:
    <directory>
    Order Deny,Allow
    Allow from all
    </directory>


    Esto define los permisos correctos para el directorio que contiene los sites que queremos tratar como servidores virtuales.
    La ruta del archivo debe usar forward slashes e incluirse entre comillas si tiene espacios en blanco.
    Mientras que los servidores virutales estén en subdirectorios de este directorio raiz, tienen los permisos adecuados.
    Si hay varios directorios raiz, podemos crear diferentes directivas <directory> para ellos.
  • De los comandos que arriba se usan para definir un servidor virutal solo DocumentRoot y ServerName son obligatorias.
    Cuando usamos virutal hosting, Apache desactiva la raiz del servidor principal, así que nuestro primer servidor virutal debe replicar la raiz original del servidor.
    Luego añadimos tantos modulos virutalHost como servidores queramos definir, con su localización como DocumentRoot, y su nombre.
    Volvemos a usar forward slashes e incluir entre comillas si necesario.

    <VirtualHost *:80>
    DocumentRoot D:/htdocs/
    ServerName localhost
    </VirtualHost>

    <VirtualHost *:80>
    DocumentRoot D:/htdocs/vhExample
    ServerName vhExample
    </VirtualHost>

  • Guardamos los cambios en httpd-vhosts.conf, y reiniciamos Apache.
    Todos los sites configurados siguen siendo accesibles como http://localhost/sitename/.
    Además podemos acceder a cada servidor virtual de forma directa como http://vhExample/.
  • Si continuas teniendo problemas para acceder a los servidores virtuales, asegúrate de haber añadido la directiva DirectoryIndex en httpd.conf.

23 abr 2010

PHP: preg_match - Manual


Description

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags [, int $offset ]]] )

Searches subject for a match to the regular expression given in pattern.


Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

matches

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

flags

flags can be the following flag:

PREG_OFFSET_CAPTURE
If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.
offset

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).

Note: Using offset is not equivalent to passing substr($subject, $offset) to preg_match() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). Compare:

= "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>

The above example will output:

Array
(
)

while this example

= "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

will produce

Array
(
[0] => Array
(
[0] => def
[1] => 0
)

)

Return Values

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.



Examples

Example #1 Find the string of text "php"

// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
echo
"A match was found.";
} else {
echo
"A match was not found.";
}
?>

Example #2 Find the word "web"

/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo
"A match was found.";
} else {
echo
"A match was not found.";
}

if (
preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo
"A match was found.";
} else {
echo
"A match was not found.";
}
?>

Example #3 Getting the domain name out of a URL

// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i',
"http://www.php.net/index.html", $matches);
$host = $matches[1];

// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo
"domain name is: {$matches[0]}\n";
?>

The above example will output:

domain name is: php.net

Example #4 Using named subpattern

= 'foobar: 2008';

preg_match('/(?P\w+): (?P\d+)/', $str, $matches);

/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however
* the above form is recommended for backwards compatibility */
// preg_match('/(?\w+): (?\d+)/', $str, $matches);

print_r($matches);

?>

The above example will output:

Array
(
[0] => foobar: 2008
[name] => foobar
[1] => foobar
[digit] => 2008
[2] => 2008
)

Tip

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.