Pages

Tuesday, April 24, 2012

13 Most Used Speedy Tools To Write CSS and HTML Code

from: http://technotab.com/13-most-used-speedy-tools-to-write-css-and-html-code/
HTML which stands for Hypertext mark-up language is supposed to be the main language for web pages. Hence the purpose of a web browser is to read the HTML documents and then compose them into either audible or visible websites.
CSS (Cascading style sheets) which is used to describe the looks and the formatting of the document more popularly known as presentation semantics. It is therefore used to design a webpage. In order to minimize the time needed to design a website or optimize a web page we need to increase the speed of the coding of HTML and CSS.
Some of these tools can work on both sides that are the client and the server. HTML is very useful because it helps in adding images and also objects to be embedded. Coming to CSS another use it has is that it can be used to view the web page differently depending on various factors like the size of the screen or also the device or gadget on which it is being viewed.
Here we have listed best tools which can be used to speed up your HTML and CSS coding time. Please share your thoughts in our comment section below.

1)  CleverCSS


CleverCSS is a small markup language for CSS inspired by Python that can be used to build a style sheet in a clean and structured way. In many ways it’s cleaner and more powerful than CSS2 is.
The most obvious difference to CSS is the syntax: it is indentation based and not flat. While this is obviously against the Python Zen, it’s nonetheless a good idea for structural styles.

2)  Sass


Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
Sass has two syntaxes. The new main syntax (as of Sass 3) is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.
The second, older syntax is known as the indented syntax (or just “Sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Although no longer the primary syntax, the indented syntax will continue to be supported. Files in the indented syntax use the extension .sass.

3)  Sajax


Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTP Request or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh. The toolkit does 99% of the work for you so you have no excuse to not use it.

4)  Komodo Edit for Perl, Python, Tcl, PHP, Ruby, Javascript


Komodo Edit is a fast, smart, free and open-source code editor. Switching your trusty code editor is hard, but give Komodo Edit (or its big brother Komodo IDE) a try: it’ll be worth your while.
Windows, Mac, Linux? Yes. PHP, Python, Ruby, JavaScript, Perl, Tcl, XML, HTML 5, CSS 3? Yes, with (customizable) syntax coloring, folding, background syntax checking, and excellent auto-complete and calltips (we call it “code intelligence”). What else? Fast open (no more slow poking around for files); remote file editing; Vi keybindings (good ones); and a toolboxwith shell command integration, macros and code snippets… all wrapped around a tricked-out editor and an extension mechanism the same as Firefox’s.

5)  CSSTidy


CSSTidy is an open source CSS parser and optimiser. It is available as executable file (available for Windows, Linux and OSX) which can be controlled per command line and as PHP script (both with almost the same functionality).
In opposite to most other CSS parsers, no regular expressions are used and thus CSSTidy has full CSS2 support and a higher reliability.

6)  Less


The dynamic style sheet language. LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. LESS runs on both the client-side (IE 6+, Webkit, Firefox) and server-side, with Node.js and Rhino.

7)  Vim


Vim is a highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor distributed with most UNIX systems. Vim is distributed free as charityware.

8)  HSS


HSS is tool that extends the CSS syntax with powerful features such as variables and nested blocks. HSS is a CSS compiler which supports valid CSS syntax, so for every error that occurs during the parsing of the HSS file, it will display and error indicating at which file and which line the error occurred.

9)  Zen Coding — a new way of writing HTML and CSS code


Zen Coding is an editor plugin for high-speed HTML, XML, XSL (or any other structured code format) coding and editing. The core of this plugin is a powerful abbreviation engine which allows you to expand expressions—similar to CSS selectors—into HTML code.

 10)  XCSS


First CSS framework that allows you to work object oriented and keeps your workflow as dry as possible. xCSS bases on CSS and empowers a straightforward and object-oriented workflow when developing complex style cascades. Using xCSS means a dramatic cut down to your development time by: having a intuitive overview of the overall CSS structure, using variables, re-using existing style cascades and many other handy features. But, most frameworks are bulky and inflexible, aren’t they? Not xCSS! It’s lightweight and seamlessly integrates into any existing workflow. Aside from that the CSS overhead is getting reduced while your (X)HTML attributes remain semantic.

11)  Haml


Haml is a markup language that’s used to cleanly and simply describe the HTML of any web document without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ASP, and ERB, the templating language used in most Ruby on Rails applications. However, Haml avoids the need for explicitly coding HTML into the template, because it itself is a description of the HTML, with some code to generate dynamic content.

12)  About Markup Generator


Markup Generator is a simple tool created for xhtml/css coders that are tired of writing boring frame code at the very beginning of slicing work. It’s main purpose is to speed up your work by generating xhtml markup and a css frame out of very intuitive, shortened syntax so you can jump directly to the elements styling.

13)  BluePrint


Blueprint is a CSS framework, which aims to cut down on your development time. It gives you a solid foundation to build your project on top of, with an easy-to-use grid, sensible typography, useful plugins, and even a style sheet for printing.

iText: Create a PDF in Java

from: http://www.rgagnon.com/javadetails/java-0618.html

iText

http://www.lowagie.com/iText/ iText is a very simple to use package to create and manipulate PDF file.
For the simple need, only 1 jar is required (ex. itext-2.1.3.jar, download at http://www.lowagie.com/iText/download.html)
In this example, you pass on the command line a filename (plain text file - args[0]) to convert to a PDF file (args[1]).
import java.io.*;

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class TextFileToPDF {

  /*
     ex. java TextFileToPDF  c:\temp\text.txt  c:\temp\text.pdf
  */
  public static void main (String [] args){
    BufferedReader input = null;
    Document output = null;
    System.out.println("Convert text file to pdf");
    System.out.println("input  : " + args[0]);
    System.out.println("output : " + args[1]);
    try {
      // text file to convert to pdf as args[0]
      input = 
        new BufferedReader (new FileReader(args[0]));
      // letter 8.5x11
      //    see com.lowagie.text.PageSize for a complete list of page-size constants.
      output = new Document(PageSize.LETTER, 40, 40, 40, 40);
      // pdf file as args[1]
      PdfWriter.getInstance(output, new FileOutputStream (args[1]));

      output.open();
      output.addAuthor("RealHowTo");
      output.addSubject(args[0]);
      output.addTitle(args[0]);

      String line = "";
      while(null != (line = input.readLine())) {
        System.out.println(line);
        Paragraph p = new Paragraph(line);
        p.setAlignment(Element.ALIGN_JUSTIFIED);
        output.add(p);
      }
      System.out.println("Done.");
      output.close();
      input.close();
      System.exit(0);
    }
    catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
}

Add a watermark to an existing document.
import java.io.FileOutputStream;
import java.util.HashMap;

import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class AddWatermarkPageNumbers {
    public static void main(String[] args) {
        System.out.println("Add watermarks and pagenumbers");
        try {
            PdfReader reader = new PdfReader("ChapterSection.pdf");
            int n = reader.getNumberOfPages();
            // create a stamper that will copy the document to a new file
            PdfStamper stamp = new PdfStamper(reader, 
               new FileOutputStream("watermark_pagenumbers.pdf"));
            // adding some metadata
            HashMap moreInfo = new HashMap();
            moreInfo.put("Author", "Bruno Lowagie");
            stamp.setMoreInfo(moreInfo);
            // adding content to each page
            int i = 0;
            PdfContentByte under;
            PdfContentByte over;
            Image img = Image.getInstance("watermark.jpg");
            BaseFont bf = 
               BaseFont.createFont
                 (BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            img.setAbsolutePosition(200, 400);
            while (i < n) {
                i++;
                // watermark under the existing page
                under = stamp.getUnderContent(i);
                under.addImage(img);
                // text over the existing page
                over = stamp.getOverContent(i);
                over.beginText();
                over.setFontAndSize(bf, 18);
                over.setTextMatrix(30, 30);
                over.showText("page " + i);
                over.setFontAndSize(bf, 32);
                over.showTextAligned
                   (Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
                over.endText();
            }
            // adding an extra page
            stamp.insertPage(1, PageSize.A4);
            over = stamp.getOverContent(1);
            over.beginText();
            over.setFontAndSize(bf, 18);
            over.showTextAligned(Element.ALIGN_LEFT, 
                    "DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
            over.endText();
            // adding a page from another document
            PdfReader reader2 = new PdfReader("SimpleAnnotations1.pdf");
            under = stamp.getUnderContent(1);
            under.addTemplate
                (stamp.getImportedPage(reader2, 3), 1, 0, 0, 1, 0, 0);
            // closing PdfStamper will generate the new PDF file
            stamp.close();
        }
        catch (Exception de) {
            de.printStackTrace();
        }
    }
}

A good introduction to iText : http://www.informit.com/articles/printerfriendly.aspx?p=420686

Tuesday, April 17, 2012

Decorator Pattern

from: http://www.oodesign.com/decorator-pattern.html



Motivation

Extending an object�s functionality can be done statically (at compile time) by using inheritance however it might be necessary to extend an object�s functionality dynamically (at runtime) as an object is used.
Consider the typical example of a graphical window. To extend the functionality of the graphical window for example by adding a frame to the window, would require extending the window class to create a FramedWindow class. To create a framed window it is necessary to create an object of the FramedWindow class. However it would be impossible to start with a plain window and to extend its functionality at runtime to become a framed window.

Intent

  • The intent of this pattern is to add additional responsibilities dynamically to an object.

Implementation

The figure below shows a UML class diagram for the Decorator Pattern:
Decorator Pattern Implementation - UML Class Diagram The participants classes in the decorator pattern are:
  • Component - Interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponent - Defines an object to which additional responsibilities can be added.
  • Decorator - Maintains a reference to a Component object and defines an interface that conforms to Component's interface.
  • Concrete Decorators - Concrete Decorators extend the functionality of the component by adding state or adding behavior.

Description

The decorator pattern applies when there is a need to dynamically add as well as remove responsibilities to a class, and when subclassing would be impossible due to the large number of subclasses that could result.

Applicability & Examples



Example - Extending capabilities of a Graphical Window at runtime

Decorator Pattern Example - UML Class Diagram
In Graphical User Interface toolkits windows behaviors can be added dynamically by using the decorator design pattern.

Specific problems and implementation


Graphical User Interface Frameworks

GUI toolkits use decoration pattern to add functionalities dynamically as explained before.

Related Patterns

  • Adapter Pattern - A decorator is different from an adapter in that a decorator changes object's responsibilities, while an adapter changes an object interface.
  • Composite Pattern - A decorator can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities.

Consequences

  • Decoration is more convenient for adding functionalities to objects instead of entire classes at runtime. With decoration it is also possible to remove the added functionalities dynamically.
  • Decoration adds functionality to objects at runtime which would make debugging system functionality harder.

Known Uses:

  • GUI toolkits as has been previously explained.

Singleton Pattern

from: http://www.oodesign.com/singleton-pattern.html

Motivation

Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent

  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.

Implementation

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.
Singleton Implementation - UML Class Diagram
The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.
class Singleton
{
 private static Singleton instance;
 private Singleton()
 {
  ...
 }

 public static synchronized Singleton getInstance()
 {
  if (instance == null)
   instance = new Singleton();

  return instance;
 }
 ...
 public void doSomething()
 {
  ... 
 }
}
You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.
The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner:
Singleton.getInstance().doSomething();

Applicability & Examples

According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:

Example 1 - Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 - Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Example 3 - Accesing resources in shared mode

It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

Example 4 - Factories implemented as Singletons

Let's assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

Specific problems and implementation


Thread-safe implementation for multi-threading use.

A robust singleton implementation should work in any conditions. This is why we need to ensure it works when multiple threads uses it. As seen in the previous examples singletons can be used specifically in multi-threaded application to make sure the reads/writes are synchronized.

Lazy instantiation using double locking mechanism.

The standard implementation shown in the above code is a thread safe implementation, but it's not the best thread-safe implementation beacuse synchronization is very expensive when we are talking about the performance. We can see that the synchronized method getInstance does not need to be checked for syncronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any syncronized block. This optimization consist in checking in an unsynchronized block if the object is null and if not to check again and create it in an syncronized block. This is called double locking mechanism.
In this case case the singleton instance is created when the getInstance() method is called for the first time. This is called lazy instantiation and it ensures that the singleton instance is created only when it is needed.
//Lazy instantiation using double locking mechanism.
class Singleton
{
 private static Singleton instance;

 private Singleton()
 {
 System.out.println("Singleton(): Initializing Instance");
 }

 public static Singleton getInstance()
 {
  if (instance == null)
  {
   synchronized(Singleton.class)
   {
    if (instance == null)
    {
     System.out.println("getInstance(): First time getInstance was invoked!");
     instance = new Singleton();
    }
   }            
  }

  return instance;
 }

 public void doSomething()
 {
  System.out.println("doSomething(): Singleton does something!");
 }
}
A detialed discussion(double locking mechanism) can be found on http://www-128.ibm.com/developerworks/java/library/j-dcl.html?loc=j

Early instantiation using implementation with static field

In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the instance member is declared static. This is why in we don't need to synchronize any portion of the code in this case. The class is loaded once this guarantee the uniquity of the object.
Singleton - A simple example (java)
//Early instantiation using implementation with static field.
class Singleton
{
 private static Singleton instance = new Singleton();

 private Singleton()
 {
  System.out.println("Singleton(): Initializing Instance");
 }

 public static Singleton getInstance()
 {    
  return instance;
 }

 public void doSomething()
 {
  System.out.println("doSomething(): Singleton does something!");
 }
}

Protected constructor

It is possible to use a protected constructor to in order to permit the subclassing of the singeton. This techique has 2 drawbacks that makes singleton inheritance impractical:
  • First of all, if the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
  • Second of all, in order to use the derived class all the getInstance calls should be changed in the existing code from Singleton.getInstance() to NewSingleton.getInstance().

Multiple singleton instances if classes loaded by different classloaders access a singleton.

If a class(same name, same package) is loaded by 2 diferent classloaders they represents 2 different clasess in memory.

Serialization

If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be implemented. See Serializable () and readResolve Method () in javadocs.
 public class Singleton implements Serializable {
  ...

  // This method is called immediately after an object of this class is deserialized.
  // This method returns the singleton instance.
  protected Object readResolve() {
   return getInstance();
  }
 }

Abstract Factory and Factory Methods implemented as singletons.

There are certain situations when the a factory should be unique. Having 2 factories might have undesired effects when objects are created. To ensure that a factory is unique it should be implemented as a singleton. By doing so we also avoid to instantiate the class before using it.

Hot Spot:

  • Multithreading - A special care should be taken when singleton has to be used in a multithreading application.
  • Serialization - When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
  • Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
  • Global Access Point represented by the class name - The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.