GVKun编程网logo

iOS-Snippets 常见代码块引用(ios常用代码块整理集合)

4

在这里,我们将给大家分享关于iOS-Snippets常见代码块引用的知识,让您更了解ios常用代码块整理集合的本质,同时也会涉及到如何更有效地20VeryUsefulJavaCodeSnippets、

在这里,我们将给大家分享关于iOS-Snippets 常见代码块引用的知识,让您更了解ios常用代码块整理集合的本质,同时也会涉及到如何更有效地20 Very Useful Java Code Snippets、20 very useful Java code snippets for Java Develop、50 Useful CSS Snippets Every Designer Should Have_html/css_WEB-ITnose、7个WordPress常用代码段(Code Snippets)的内容。

本文目录一览:

iOS-Snippets 常见代码块引用(ios常用代码块整理集合)

iOS-Snippets 常见代码块引用(ios常用代码块整理集合)


#pragma mark - LifeCycle
#pragma mark - Setter
#pragma mark - Getter
#pragma mark - Public
#pragma mark - Private
#pragma mark - Notification
#pragma mark - Delegate

///全局
UIKIT_EXTERN const CGFloat TEST

UIKIT_EXTERN NSString *const TEST


// 异步主线程执行,不强持有Self
#define MJRefreshDispatchAsyncOnMainQueue(x) \
__weak typeof(self) weakSelf = self; \
dispatch_async(dispatch_get_main_queue(), ^{ \
typeof(weakSelf) self = weakSelf; \
{x} \
});

 

20 Very Useful Java Code Snippets

20 Very Useful Java Code Snippets

Following are few very useful Java code snippets for Java developers. Few of them are written by me and few are taken from other code reference. Feel free to comment about the code and also add your code snippet.

1. Converting Strings to int and int to String

String a = String.valueOf(2);  //integer to numeric string
inti = Integer.parseInt(a);//numeric string to an int

2. Append text to file in Java

Updated: Thanks Simone for pointing to exception. I have changed the code.

BufferedWriter out =null;
try{
    out =newBufferedWriter(newFileWriter(”filename”,true));
    out.write(”aString”);
}catch(IOException e) {
    // error processing code
}finally{
    if(out !=null) {
        out.close();
    }
}

3. Get name of current method in Java

String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

4. Convert String to Date in Java

java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);

or

SimpleDateFormat format =newSimpleDateFormat("dd.MM.yyyy");
Date date = format.parse( myString );

5. Connecting to Oracle using Java JDBC

publicclassOracleJdbcTest
{
    String driver;
 
    Connection con;
     
    publicvoidinit(FileInputStream fs)throwsClassNotFoundException, SQLException, FileNotFoundException, IOException
    {
        Properties props =newProperties();
        props.load(fs);
        String url = props.getProperty("db.url");
        String userName = props.getProperty("db.user");
        String password = props.getProperty("db.password");
        Class.forName(driverClass);
 
        con=DriverManager.getConnection(url, userName, password);
    }
     
    publicvoidfetch()throwsSQLException, IOException
    {
        PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
        ResultSet rs = ps.executeQuery();
         
        while(rs.next())
        {
            // do the thing you do
        }
        rs.close();
        ps.close();
    }
 
    publicstaticvoidmain(String[] args)
    {
        OracleJdbcTest test =newOracleJdbcTest();
        test.init();
        test.fetch();
    }
}

6. Convert Java util.Date to sql.Date


This snippet shows how to convert a java util Date into a sql Date for use in databases.

java.util.Date utilDate =newjava.util.Date();
java.sql.Date sqlDate =newjava.sql.Date(utilDate.getTime());

7. Java Fast File Copy using NIO

publicstaticvoidfileCopy( File in, File out )
            throwsIOException
    {
        FileChannel inChannel =newFileInputStream( in ).getChannel();
        FileChannel outChannel =newFileOutputStream( out ).getChannel();
        try
        {
//          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows
 
            // magic number for Windows, 64Mb - 32Kb)
            intmaxCount = (64*1024*1024) - (32*1024);
            longsize = inChannel.size();
            longposition =0;
            while( position < size )
            {
               position += inChannel.transferTo( position, maxCount, outChannel );
            }
        }
        finally
        {
            if( inChannel !=null)
            {
               inChannel.close();
            }
            if( outChannel !=null)
            {
                outChannel.close();
            }
        }
    }

8. Create Thumbnail of an image in Java

privatevoidcreateThumbnail(String filename,intthumbWidth,intthumbHeight,intquality, String outFilename)
        throwsInterruptedException, FileNotFoundException, IOException
    {
        // load image from filename
        Image image = Toolkit.getDefaultToolkit().getImage(filename);
        MediaTracker mediaTracker =newMediaTracker(newContainer());
        mediaTracker.addImage(image,0);
        mediaTracker.waitForID(0);
        // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());
         
        // determine thumbnail size from WIDTH and HEIGHT
        doublethumbRatio = (double)thumbWidth / (double)thumbHeight;
        intimageWidth = image.getWidth(null);
        intimageHeight = image.getHeight(null);
        doubleimageRatio = (double)imageWidth / (double)imageHeight;
        if(thumbRatio < imageRatio) {
            thumbHeight = (int)(thumbWidth / imageRatio);
        }else{
            thumbWidth = (int)(thumbHeight * imageRatio);
        }
         
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        BufferedImage thumbImage =newBufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image,0,0, thumbWidth, thumbHeight,null);
         
        // save thumbnail image to outFilename
        BufferedOutputStream out =newBufferedOutputStream(newFileOutputStream(outFilename));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
        quality = Math.max(0, Math.min(quality,100));
        param.setQuality((float)quality /100.0f,false);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(thumbImage);
        out.close();
    }

9. Creating JSON data in Java

Read this article for more details.
Download JAR file json-rpc-1.0.jar (75 kb)

importorg.json.JSONObject;
...
...
JSONObject json =newJSONObject();
json.put("city","Mumbai");
json.put("country","India");
...
String output = json.toString();
...

10. PDF Generation in Java using iText JAR

Read this article for more details.

importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.OutputStream;
importjava.util.Date;
 
importcom.lowagie.text.Document;
importcom.lowagie.text.Paragraph;
importcom.lowagie.text.pdf.PdfWriter;
 
publicclassGeneratePDF {
 
    publicstaticvoidmain(String[] args) {
        try{
            OutputStream file =newFileOutputStream(newFile("C:\\Test.pdf"));
 
            Document document =newDocument();
            PdfWriter.getInstance(document, file);
            document.open();
            document.add(newParagraph("Hello Kiran"));
            document.add(newParagraph(newDate().toString()));
 
            document.close();
            file.close();
 
        }catch(Exception e) {
 
            e.printStackTrace();
        }
    }
}

11. HTTP Proxy setting in Java

Read this article for more details.

System.getProperties().put("http.proxyHost","someProxyURL");
System.getProperties().put("http.proxyPort","someProxyPort");
System.getProperties().put("http.proxyUser","someUserName");
System.getProperties().put("http.proxyPassword","somePassword");

12. Java Singleton example

Read this article for more details.
Update: Thanks Markus for the comment. I have updated the code and changed it to more robust implementation.

publicclassSimpleSingleton {
    privatestaticSimpleSingleton singleInstance = newSimpleSingleton();
 
    //Marking default constructor private
    //to avoid direct instantiation.
    privateSimpleSingleton() {
    }
 
    //Get instance for class SimpleSingleton
    publicstaticSimpleSingleton getInstance() {
 
        returnsingleInstance;
    }
}

One more implementation of Singleton class. Thanks to Ralph and Lukasz Zielinski for pointing this out.

publicenumSimpleSingleton {
    INSTANCE;
    publicvoiddoSomething() {
    }
}
 
//Call the method from Singleton:
SimpleSingleton.INSTANCE.doSomething();

13. Capture screen shots in Java

Read this article for more details.

importjava.awt.Dimension;
importjava.awt.Rectangle;
importjava.awt.Robot;
importjava.awt.Toolkit;
importjava.awt.image.BufferedImage;
importjavax.imageio.ImageIO;
importjava.io.File;
 
...
 
publicvoidcaptureScreen(String fileName)throwsException {
 
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle =newRectangle(screenSize);
   Robot robot =newRobot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image,"png",newFile(fileName));
 
}
...

14. Files-Directory listing in Java

File dir =newFile("directoryName");
  String[] children = dir.list();
  if(children ==null) {
      // Either dir does not exist or is not a directory
  }else{
      for(inti=0; i < children.length; i++) {
          // Get filename of file or directory
          String filename = children[i];
      }
  }
 
  // It is also possible to filter the list of returned files.
  // This example does not return any files that start with `.''.
  FilenameFilter filter =newFilenameFilter() {
      publicbooleanaccept(File dir, String name) {
          return!name.startsWith(".");
      }
  };
  children = dir.list(filter);
 
  // The list of files can also be retrieved as File objects
  File[] files = dir.listFiles();
 
  // This filter only returns directories
  FileFilter fileFilter =newFileFilter() {
      publicbooleanaccept(File file) {
          returnfile.isDirectory();
      }
  };
  files = dir.listFiles(fileFilter);

15. Creating ZIP and JAR Files in Java

importjava.util.zip.*;
importjava.io.*;
 
publicclassZipIt {
    publicstaticvoidmain(String args[])throwsIOException {
        if(args.length <2) {
            System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
            System.exit(-1);
        }
        File zipFile =newFile(args[0]);
        if(zipFile.exists()) {
            System.err.println("Zip file already exists, please try another");
            System.exit(-2);
        }
        FileOutputStream fos =newFileOutputStream(zipFile);
        ZipOutputStream zos =newZipOutputStream(fos);
        intbytesRead;
        byte[] buffer =newbyte[1024];
        CRC32 crc =newCRC32();
        for(inti=1, n=args.length; i < n; i++) {
            String name = args[i];
            File file =newFile(name);
            if(!file.exists()) {
                System.err.println("Skipping: "+ name);
                continue;
            }
            BufferedInputStream bis =newBufferedInputStream(
                newFileInputStream(file));
            crc.reset();
            while((bytesRead = bis.read(buffer)) != -1) {
                crc.update(buffer,0, bytesRead);
            }
            bis.close();
            // Reset to beginning of input stream
            bis =newBufferedInputStream(
                newFileInputStream(file));
            ZipEntry entry =newZipEntry(name);
            entry.setMethod(ZipEntry.STORED);
            entry.setCompressedSize(file.length());
            entry.setSize(file.length());
            entry.setCrc(crc.getValue());
            zos.putNextEntry(entry);
            while((bytesRead = bis.read(buffer)) != -1) {
                zos.write(buffer,0, bytesRead);
            }
            bis.close();
        }
        zos.close();
    }
}

16. Parsing / Reading XML file in Java

Sample XML file.

<?xmlversion="1.0"?>
<students>
    <student>
        <name>John</name>
        <grade>B</grade>
        <age>12</age>
    </student>
    <student>
        <name>Mary</name>
        <grade>A</grade>
        <age>11</age>
    </student>
    <student>
        <name>Simon</name>
        <grade>A</grade>
        <age>18</age>
    </student>
</students>

Java code to parse above XML.

packagenet.viralpatel.java.xmlparser;
 
importjava.io.File;
importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.DocumentBuilderFactory;
 
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
importorg.w3c.dom.Node;
importorg.w3c.dom.NodeList;
 
publicclassXMLParser {
 
    publicvoidgetAllUserNames(String fileName) {
        try{
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            File file =newFile(fileName);
            if(file.exists()) {
                Document doc = db.parse(file);
                Element docEle = doc.getDocumentElement();
 
                // Print root element of the document
                System.out.println("Root element of the document: "
                        + docEle.getNodeName());
 
                NodeList studentList = docEle.getElementsByTagName("student");
 
                // Print total student elements in document
                System.out
                        .println("Total students: "+ studentList.getLength());
 
                if(studentList !=null&& studentList.getLength() >0) {
                    for(inti =0; i < studentList.getLength(); i++) {
 
                        Node node = studentList.item(i);
 
                        if(node.getNodeType() == Node.ELEMENT_NODE) {
 
                            System.out
                                    .println("=====================");
 
                            Element e = (Element) node;
                            NodeList nodeList = e.getElementsByTagName("name");
                            System.out.println("Name: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
 
                            nodeList = e.getElementsByTagName("grade");
                            System.out.println("Grade: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
 
                            nodeList = e.getElementsByTagName("age");
                            System.out.println("Age: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
                        }
                    }
                }else{
                    System.exit(1);
                }
            }
        }catch(Exception e) {
            System.out.println(e);
        }
    }
    publicstaticvoidmain(String[] args) {
 
        XMLParser parser =newXMLParser();
        parser.getAllUserNames("c:\\test.xml");
    }
}

17. Convert Array to Map in Java

importjava.util.Map;
importorg.apache.commons.lang.ArrayUtils;
 
publicclassMain {
 
  publicstaticvoidmain(String[] args) {
    String[][] countries = { {"United States","New York"}, {"United Kingdom","London"},
        {"Netherland","Amsterdam"}, {"Japan","Tokyo"}, {"France","Paris"} };
 
    Map countryCapitals = ArrayUtils.toMap(countries);
 
    System.out.println("Capital of Japan is "+ countryCapitals.get("Japan"));
    System.out.println("Capital of France is "+ countryCapitals.get("France"));
  }
}

18. Send Email using Java

importjavax.mail.*;
importjavax.mail.internet.*;
importjava.util.*;
 
publicvoidpostMail( String recipients[ ], String subject, String message , String from)throwsMessagingException
{
    booleandebug =false;
 
     //Set the host smtp address
     Properties props =newProperties();
     props.put("mail.smtp.host","smtp.example.com");
 
    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props,null);
    session.setDebug(debug);
 
    // create a message
    Message msg =newMimeMessage(session);
 
    // set the from and to address
    InternetAddress addressFrom =newInternetAddress(from);
    msg.setFrom(addressFrom);
 
    InternetAddress[] addressTo =newInternetAddress[recipients.length];
    for(inti =0; i < recipients.length; i++)
    {
        addressTo[i] =newInternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    
 
    // Optional : You can also set your custom headers in the Email if you Want
    msg.addHeader("MyHeaderName","myHeaderValue");
 
    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message,"text/plain");
    Transport.send(msg);
}

19. Send HTTP request & fetching data using Java

importjava.io.BufferedReader;
importjava.io.InputStreamReader;
importjava.net.URL;
 
publicclassMain {
    publicstaticvoidmain(String[] args)  {
        try{
            URL my_url =newURL("http://www.viralpatel.net/blogs/");
            BufferedReader br =newBufferedReader(newInputStreamReader(my_url.openStream()));
            String strTemp ="";
            while(null!= (strTemp = br.readLine())){
            System.out.println(strTemp);
        }
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

20. Resize an Array in Java

/**
* Reallocates an array with a new size, and copies the contents
* of the old array to the new array.
* @param oldArray  the old array, to be reallocated.
* @param newSize   the new array size.
* @return          A new array with the same contents.
*/
privatestaticObject resizeArray (Object oldArray,intnewSize) {
   intoldSize = java.lang.reflect.Array.getLength(oldArray);
   Class elementType = oldArray.getClass().getComponentType();
   Object newArray = java.lang.reflect.Array.newInstance(
         elementType,newSize);
   intpreserveLength = Math.min(oldSize,newSize);
   if(preserveLength >0)
      System.arraycopy (oldArray,0,newArray,0,preserveLength);
   returnnewArray;
}
 
// Test routine for resizeArray().
publicstaticvoidmain (String[] args) {
   int[] a = {1,2,3};
   a = (int[])resizeArray(a,5);
   a[3] =4;
   a[4] =5;
   for(inti=0; i<a.length; i++)
      System.out.println (a[i]);
}

20 very useful Java code snippets for Java Develop

20 very useful Java code snippets for Java Develop

1. Converting Strings to int and int to String
view plaincopy to clipboardprint?
 
String a = String.valueOf(2);   //integer to numeric string  
int i = Integer.parseInt(a); //numeric string to an int 


String a = String.valueOf(2);   //integer to numeric string
int i = Integer.parseInt(a); //numeric string to an int
2. Append text to file in Java
Updated: Thanks Simone for pointing to exception. I have changed the code.

view plaincopy to clipboardprint?
 
BufferedWriter out = null;  
try {  
    out = new BufferedWriter(new FileWriter(”filename”, true));  
    out.write(”aString”);  
} catch (IOException e) {  
    // error processing code  
} finally {  
    if (out != null) {  
        out.close();  
    }  



BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(”filename”, true));
out.write(”aString”);
} catch (IOException e) {
// error processing code
} finally {
if (out != null) {
out.close();
}
}
3. Get name of current method in Java
view plaincopy to clipboardprint?
 
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); 


String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
4. Convert String to Date in Java
view plaincopy to clipboardprint?
 
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String); 


java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
or

view plaincopy to clipboardprint?
 
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );  
Date date = format.parse( myString ); 


SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date date = format.parse( myString );
5. Connecting to Oracle using Java JDBC
view plaincopy to clipboardprint?
 
public class OracleJdbcTest  
{  
    String driver;  
 
    Connection con;  
 
    public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException  
    {  
        Properties props = new Properties();  
        props.load(fs);  
        String url = props.getProperty("db.url");  
        String userName = props.getProperty("db.user");  
        String password = props.getProperty("db.password");  
        Class.forName(driverClass);  
 
        con=DriverManager.getConnection(url, userName, password);  
    }  
 
    public void fetch() throws SQLException, IOException  
    {  
        PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");  
        ResultSet rs = ps.executeQuery();  
 
        while (rs.next())  
        {  
            // do the thing you do  
        }  
        rs.close();  
        ps.close();  
    }  
 
    public static void main(String[] args)  
    {  
        OracleJdbcTest test = new OracleJdbcTest();  
        test.init();  
        test.fetch();  
    }  



public class OracleJdbcTest
{
String driver;

Connection con;

public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
{
Properties props = new Properties();
props.load(fs);
String url = props.getProperty("db.url");
String userName = props.getProperty("db.user");
String password = props.getProperty("db.password");
Class.forName(driverClass);

con=DriverManager.getConnection(url, userName, password);
}

public void fetch() throws SQLException, IOException
{
PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
ResultSet rs = ps.executeQuery();

while (rs.next())
{
// do the thing you do
}
rs.close();
ps.close();
}

public static void main(String[] args)
{
OracleJdbcTest test = new OracleJdbcTest();
test.init();
test.fetch();
}
}
6. Convert Java util.Date to sql.Date

This snippet shows how to convert a java util Date into a sql Date for use in databases.

view plaincopy to clipboardprint?
 
java.util.Date utilDate = new java.util.Date();  
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); 


java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
7. Java Fast File Copy using NIO
view plaincopy to clipboardprint?
 
public static void fileCopy( File in, File out )  
            throws IOException  
    {  
        FileChannel inChannel = new FileInputStream( in ).getChannel();  
        FileChannel outChannel = new FileOutputStream( out ).getChannel();  
        try 
        {  
//          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows  
 
            // magic number for Windows, 64Mb - 32Kb)  
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);  
            long size = inChannel.size();  
            long position = 0;  
            while ( position < size )  
            {  
               position += inChannel.transferTo( position, maxCount, outChannel );  
            }  
        }  
        finally 
        {  
            if ( inChannel != null )  
            {  
               inChannel.close();  
            }  
            if ( outChannel != null )  
            {  
                outChannel.close();  
            }  
        }  
    } 


public static void fileCopy( File in, File out )
            throws IOException
    {
        FileChannel inChannel = new FileInputStream( in ).getChannel();
        FileChannel outChannel = new FileOutputStream( out ).getChannel();
        try
        {
//          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows

            // magic number for Windows, 64Mb - 32Kb)
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while ( position < size )
            {
               position += inChannel.transferTo( position, maxCount, outChannel );
            }
        }
        finally
        {
            if ( inChannel != null )
            {
               inChannel.close();
            }
            if ( outChannel != null )
            {
                outChannel.close();
            }
        }
    }
8. Create Thumbnail of an image in Java
view plaincopy to clipboardprint?
 
private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)  
        throws InterruptedException, FileNotFoundException, IOException  
    {  
        // load image from filename  
        Image image = Toolkit.getDefaultToolkit().getImage(filename);  
        MediaTracker mediaTracker = new MediaTracker(new Container());  
        mediaTracker.addImage(image, 0);  
        mediaTracker.waitForID(0);  
        // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());  
 
        // determine thumbnail size from WIDTH and HEIGHT  
        double thumbRatio = (double)thumbWidth / (double)thumbHeight;  
        int imageWidth = image.getWidth(null);  
        int imageHeight = image.getHeight(null);  
        double imageRatio = (double)imageWidth / (double)imageHeight;  
        if (thumbRatio < imageRatio) {  
            thumbHeight = (int)(thumbWidth / imageRatio);  
        } else {  
            thumbWidth = (int)(thumbHeight * imageRatio);  
        }  
 
        // draw original image to thumbnail image object and  
        // scale it to the new size on-the-fly  
        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);  
        Graphics2D graphics2D = thumbImage.createGraphics();  
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
        graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);  
 
        // save thumbnail image to outFilename  
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));  
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);  
        quality = Math.max(0, Math.min(quality, 100));  
        param.setQuality((float)quality / 100.0f, false);  
        encoder.setJPEGEncodeParam(param);  
        encoder.encode(thumbImage);  
        out.close();  
    } 


private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
throws InterruptedException, FileNotFoundException, IOException
{
// load image from filename
Image image = Toolkit.getDefaultToolkit().getImage(filename);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
// use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());

// determine thumbnail size from WIDTH and HEIGHT
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageHeight;
if (thumbRatio < imageRatio) {
thumbHeight = (int)(thumbWidth / imageRatio);
} else {
thumbWidth = (int)(thumbHeight * imageRatio);
}

// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

// save thumbnail image to outFilename
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
}
9. Creating JSON data in Java
Read this article for more details.
Download JAR file json-rpc-1.0.jar (75 kb)

view plaincopy to clipboardprint?
 
import org.json.JSONObject;  
...  
...  
JSONObject json = new JSONObject();  
json.put("city", "Mumbai");  
json.put("country", "India");  
...  
String output = json.toString();  
... 


import org.json.JSONObject;
...
...
JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");
...
String output = json.toString();
...
10. PDF Generation in Java using iText JAR
Read this article for more details.

view plaincopy to clipboardprint?
 
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.OutputStream;  
import java.util.Date;  
 
import com.lowagie.text.Document;  
import com.lowagie.text.Paragraph;  
import com.lowagie.text.pdf.PdfWriter;  
 
public class GeneratePDF {  
 
    public static void main(String[] args) {  
        try {  
            OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));  
 
            Document document = new Document();  
            PdfWriter.getInstance(document, file);  
            document.open();  
            document.add(new Paragraph("Hello Kiran"));  
            document.add(new Paragraph(new Date().toString()));  
 
            document.close();  
            file.close();  
 
        } catch (Exception e) {  
 
            e.printStackTrace();  
        }  
    }  



import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF {

    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));

            Document document = new Document();
            PdfWriter.getInstance(document, file);
            document.open();
            document.add(new Paragraph("Hello Kiran"));
            document.add(new Paragraph(new Date().toString()));

            document.close();
            file.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}
11. HTTP Proxy setting in Java
Read this article for more details.

view plaincopy to clipboardprint?
 
System.getProperties().put("http.proxyHost", "someProxyURL");  
System.getProperties().put("http.proxyPort", "someProxyPort");  
System.getProperties().put("http.proxyUser", "someUserName");  
System.getProperties().put("http.proxyPassword", "somePassword"); 


System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");
12. Java Singleton example
Read this article for more details.
Update: Thanks Markus for the comment. I have updated the code and changed it to more robust implementation.

view plaincopy to clipboardprint?
 
public class SimpleSingleton {  
    private static SimpleSingleton singleInstance =  new SimpleSingleton();  
 
    //Marking default constructor private  
    //to avoid direct instantiation.  
    private SimpleSingleton() {  
    }  
 
    //Get instance for class SimpleSingleton  
    public static SimpleSingleton getInstance() {  
 
        return singleInstance;  
    }  



public class SimpleSingleton {
private static SimpleSingleton singleInstance =  new SimpleSingleton();

//Marking default constructor private
//to avoid direct instantiation.
private SimpleSingleton() {
}

//Get instance for class SimpleSingleton
public static SimpleSingleton getInstance() {

return singleInstance;
}
}
One more implementation of Singleton class. Thanks to Ralph and Lukasz Zielinski for pointing this out.

view plaincopy to clipboardprint?
 
public enum SimpleSingleton {  
    INSTANCE;  
    public void doSomething() {  
    }  
}  
 
//Call the method from Singleton:  
SimpleSingleton.INSTANCE.doSomething(); 


public enum SimpleSingleton {
INSTANCE;
public void doSomething() {
}
}

//Call the method from Singleton:
SimpleSingleton.INSTANCE.doSomething();
13. Capture screen shots in Java
Read this article for more details.

view plaincopy to clipboardprint?
 
import java.awt.Dimension;  
import java.awt.Rectangle;  
import java.awt.Robot;  
import java.awt.Toolkit;  
import java.awt.image.BufferedImage;  
import javax.imageio.ImageIO;  
import java.io.File;  
 
...  
 
public void captureScreen(String fileName) throws Exception {  
 
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();  
   Rectangle screenRectangle = new Rectangle(screenSize);  
   Robot robot = new Robot();  
   BufferedImage image = robot.createScreenCapture(screenRectangle);  
   ImageIO.write(image, "png", new File(fileName));  
 
}  
... 


import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

...

public void captureScreen(String fileName) throws Exception {

   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   Robot robot = new Robot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image, "png", new File(fileName));

}
...
14. Files-Directory listing in Java
view plaincopy to clipboardprint?
File dir = new File("directoryName");  
  String[] children = dir.list();  
  if (children == null) {  
      // Either dir does not exist or is not a directory  
  } else {  
      for (int i=0; i < children.length; i++) {  
          // Get filename of file or directory  
          String filename = children[i];  
      }  
  }  
 
  // It is also possible to filter the list of returned files.  
  // This example does not return any files that start with `.''.  
  FilenameFilter filter = new FilenameFilter() {  
      public boolean accept(File dir, String name) {  
          return !name.startsWith(".");  
      }  
  };  
  children = dir.list(filter);  
 
  // The list of files can also be retrieved as File objects  
  File[] files = dir.listFiles();  
 
  // This filter only returns directories  
  FileFilter fileFilter = new FileFilter() {  
      public boolean accept(File file) {  
          return file.isDirectory();  
      }  
  };  
  files = dir.listFiles(fileFilter); 


  File dir = new File("directoryName");
    String[] children = dir.list();
    if (children == null) {
        // Either dir does not exist or is not a directory
    } else {
        for (int i=0; i < children.length; i++) {
            // Get filename of file or directory
            String filename = children[i];
        }
    }

    // It is also possible to filter the list of returned files.
    // This example does not return any files that start with `.''.
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return !name.startsWith(".");
        }
    };
    children = dir.list(filter);

    // The list of files can also be retrieved as File objects
    File[] files = dir.listFiles();

    // This filter only returns directories
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    files = dir.listFiles(fileFilter);
15. Creating ZIP and JAR Files in Java
view plaincopy to clipboardprint?
 
import java.util.zip.*;  
import java.io.*;  
 
public class ZipIt {  
    public static void main(String args[]) throws IOException {  
        if (args.length < 2) {  
            System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");  
            System.exit(-1);  
        }  
        File zipFile = new File(args[0]);  
        if (zipFile.exists()) {  
            System.err.println("Zip file already exists, please try another");  
            System.exit(-2);  
        }  
        FileOutputStream fos = new FileOutputStream(zipFile);  
        ZipOutputStream zos = new ZipOutputStream(fos);  
        int bytesRead;  
        byte[] buffer = new byte[1024];  
        CRC32 crc = new CRC32();  
        for (int i=1, n=args.length; i < n; i++) {  
            String name = args[i];  
            File file = new File(name);  
            if (!file.exists()) {  
                System.err.println("Skipping: " + name);  
                continue;  
            }  
            BufferedInputStream bis = new BufferedInputStream(  
                new FileInputStream(file));  
            crc.reset();  
            while ((bytesRead = bis.read(buffer)) != -1) {  
                crc.update(buffer, 0, bytesRead);  
            }  
            bis.close();  
            // Reset to beginning of input stream  
            bis = new BufferedInputStream(  
                new FileInputStream(file));  
            ZipEntry entry = new ZipEntry(name);  
            entry.setMethod(ZipEntry.STORED);  
            entry.setCompressedSize(file.length());  
            entry.setSize(file.length());  
            entry.setCrc(crc.getValue());  
            zos.putNextEntry(entry);  
            while ((bytesRead = bis.read(buffer)) != -1) {  
                zos.write(buffer, 0, bytesRead);  
            }  
            bis.close();  
        }  
        zos.close();  
    }  



import java.util.zip.*;
import java.io.*;

public class ZipIt {
    public static void main(String args[]) throws IOException {
        if (args.length < 2) {
            System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
            System.exit(-1);
        }
        File zipFile = new File(args[0]);
        if (zipFile.exists()) {
            System.err.println("Zip file already exists, please try another");
            System.exit(-2);
        }
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        int bytesRead;
        byte[] buffer = new byte[1024];
        CRC32 crc = new CRC32();
        for (int i=1, n=args.length; i < n; i++) {
            String name = args[i];
            File file = new File(name);
            if (!file.exists()) {
                System.err.println("Skipping: " + name);
                continue;
            }
            BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(file));
            crc.reset();
            while ((bytesRead = bis.read(buffer)) != -1) {
                crc.update(buffer, 0, bytesRead);
            }
            bis.close();
            // Reset to beginning of input stream
            bis = new BufferedInputStream(
                new FileInputStream(file));
            ZipEntry entry = new ZipEntry(name);
            entry.setMethod(ZipEntry.STORED);
            entry.setCompressedSize(file.length());
            entry.setSize(file.length());
            entry.setCrc(crc.getValue());
            zos.putNextEntry(entry);
            while ((bytesRead = bis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesRead);
            }
            bis.close();
        }
        zos.close();
    }
}
16. Parsing / Reading XML file in Java
Sample XML file.

view plaincopy to clipboardprint?
 
<?xml version="1.0"?> 
<students> 
    <student> 
        <name>John</name> 
        <grade>B</grade> 
        <age>12</age> 
    </student> 
    <student> 
        <name>Mary</name> 
        <grade>A</grade> 
        <age>11</age> 
    </student> 
    <student> 
        <name>Simon</name> 
        <grade>A</grade> 
        <age>18</age> 
    </student> 
</students> 


<?xml version="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>
Java code to parse above XML.

view plaincopy to clipboardprint?
 
package net.viralpatel.java.xmlparser;  
 
import java.io.File;  
import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
 
import org.w3c.dom.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
 
public class XMLParser {  
 
    public void getAllUserNames(String fileName) {  
        try {  
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
            DocumentBuilder db = dbf.newDocumentBuilder();  
            File file = new File(fileName);  
            if (file.exists()) {  
                Document doc = db.parse(file);  
                Element docEle = doc.getDocumentElement();  
 
                // Print root element of the document  
                System.out.println("Root element of the document: " 
                        + docEle.getNodeName());  
 
                NodeList studentList = docEle.getElementsByTagName("student");  
 
                // Print total student elements in document  
                System.out  
                        .println("Total students: " + studentList.getLength());  
 
                if (studentList != null && studentList.getLength() > 0) {  
                    for (int i = 0; i < studentList.getLength(); i++) {  
 
                        Node node = studentList.item(i);  
 
                        if (node.getNodeType() == Node.ELEMENT_NODE) {  
 
                            System.out  
                                    .println("=====================");  
 
                            Element e = (Element) node;  
                            NodeList nodeList = e.getElementsByTagName("name");  
                            System.out.println("Name: " 
                                    + nodeList.item(0).getChildNodes().item(0)  
                                            .getNodeValue());  
 
                            nodeList = e.getElementsByTagName("grade");  
                            System.out.println("Grade: " 
                                    + nodeList.item(0).getChildNodes().item(0)  
                                            .getNodeValue());  
 
                            nodeList = e.getElementsByTagName("age");  
                            System.out.println("Age: " 
                                    + nodeList.item(0).getChildNodes().item(0)  
                                            .getNodeValue());  
                        }  
                    }  
                } else {  
                    System.exit(1);  
                }  
            }  
        } catch (Exception e) {  
            System.out.println(e);  
        }  
    }  
    public static void main(String[] args) {  
 
        XMLParser parser = new XMLParser();  
        parser.getAllUserNames("c:\\test.xml");  
    }  



package net.viralpatel.java.xmlparser;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLParser {

public void getAllUserNames(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();

// Print root element of the document
System.out.println("Root element of the document: "
+ docEle.getNodeName());

NodeList studentList = docEle.getElementsByTagName("student");

// Print total student elements in document
System.out
.println("Total students: " + studentList.getLength());

if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {

Node node = studentList.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {

System.out
.println("=====================");

Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("name");
System.out.println("Name: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());

nodeList = e.getElementsByTagName("grade");
System.out.println("Grade: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());

nodeList = e.getElementsByTagName("age");
System.out.println("Age: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
}
}
} else {
System.exit(1);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {

XMLParser parser = new XMLParser();
parser.getAllUserNames("c:\\test.xml");
}
}
17. Convert Array to Map in Java
view plaincopy to clipboardprint?
 
import java.util.Map;  
import org.apache.commons.lang.ArrayUtils;  
 
public class Main {  
 
  public static void main(String[] args) {  
    String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },  
        { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };  
 
    Map countryCapitals = ArrayUtils.toMap(countries);  
 
    System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));  
    System.out.println("Capital of France is " + countryCapitals.get("France"));  
  }  



import java.util.Map;
import org.apache.commons.lang.ArrayUtils;

public class Main {

  public static void main(String[] args) {
    String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },
        { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };

    Map countryCapitals = ArrayUtils.toMap(countries);

    System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
    System.out.println("Capital of France is " + countryCapitals.get("France"));
  }
}
18. Send Email using Java
view plaincopy to clipboardprint?
 
import javax.mail.*;  
import javax.mail.internet.*;  
import java.util.*;  
 
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException  
{  
    boolean debug = false;  
 
     //Set the host smtp address  
     Properties props = new Properties();  
     props.put("mail.smtp.host", "smtp.example.com");  
 
    // create some properties and get the default Session  
    Session session = Session.getDefaultInstance(props, null);  
    session.setDebug(debug);  
 
    // create a message  
    Message msg = new MimeMessage(session);  
 
    // set the from and to address  
    InternetAddress addressFrom = new InternetAddress(from);  
    msg.setFrom(addressFrom);  
 
    InternetAddress[] addressTo = new InternetAddress[recipients.length];  
    for (int i = 0; i < recipients.length; i++)  
    {  
        addressTo[i] = new InternetAddress(recipients[i]);  
    }  
    msg.setRecipients(Message.RecipientType.TO, addressTo);  
 
    // Optional : You can also set your custom headers in the Email if you Want  
    msg.addHeader("MyHeaderName", "myHeaderValue");  
 
    // Setting the Subject and Content Type  
    msg.setSubject(subject);  
    msg.setContent(message, "text/plain");  
    Transport.send(msg);  



import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
    boolean debug = false;

     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", "smtp.example.com");

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Optional : You can also set your custom headers in the Email if you Want
    msg.addHeader("MyHeaderName", "myHeaderValue");

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
}
19. Send HTTP request & fetching data using Java
view plaincopy to clipboardprint?
 
import java.io.BufferedReader;  
import java.io.InputStreamReader;  
import java.net.URL;  
 
public class Main {  
    public static void main(String[] args)  {  
        try {  
            URL my_url = new URL("http://www.viralpatel.net/blogs/");  
            BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));  
            String strTemp = "";  
            while(null != (strTemp = br.readLine())){  
            System.out.println(strTemp);  
        }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    }  



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class Main {
public static void main(String[] args)  {
try {
URL my_url = new URL("http://www.viralpatel.net/blogs/");
BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
String strTemp = "";
while(null != (strTemp = br.readLine())){
System.out.println(strTemp);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
20. Resize an Array in Java
view plaincopy to clipboardprint?
 
/** 
* Reallocates an array with a new size, and copies the contents 
* of the old array to the new array. 
* @param oldArray  the old array, to be reallocated. 
* @param newSize   the new array size. 
* @return          A new array with the same contents. 
*/ 
private static Object resizeArray (Object oldArray, int newSize) {  
   int oldSize = java.lang.reflect.Array.getLength(oldArray);  
   Class elementType = oldArray.getClass().getComponentType();  
   Object newArray = java.lang.reflect.Array.newInstance(  
         elementType,newSize);  
   int preserveLength = Math.min(oldSize,newSize);  
   if (preserveLength > 0)  
      System.arraycopy (oldArray,0,newArray,0,preserveLength);  
   return newArray;  
}  
 
// Test routine for resizeArray().  
public static void main (String[] args) {  
   int[] a = {1,2,3};  
   a = (int[])resizeArray(a,5);  
   a[3] = 4;  
   a[4] = 5;  
   for (int i=0; i<a.length; i++)  
      System.out.println (a[i]);  

50 Useful CSS Snippets Every Designer Should Have_html/css_WEB-ITnose

50 Useful CSS Snippets Every Designer Should Have_html/css_WEB-ITnose

 1. css resets    html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {      margin: 0;      padding: 0;      border: 0;      font-size: 100%;      font: inherit;      vertical-align: baseline;      outline: none;      -webkit-box-sizing: border-box;      -moz-box-sizing: border-box;      box-sizing: border-box;    }    html { height: 101%; }    body { font-size: 62.5%; line-height: 1; font-family: arial, tahoma, sans-serif; }    article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; }    ol, ul { list-style: none; }    blockquote, q { quotes: none; }    blockquote:before, blockquote:after, q:before, q:after { content: ''''; content: none; }    strong { font-weight: bold; }     table { border-collapse: collapse; border-spacing: 0; }    img { border: 0; max-width: 100%; }    p { font-size: 1.2em; line-height: 1.0em; color: #333; }2. classic css clearfix    .clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; }    .clearfix { display: inline-block; }    html[xmlns] .clearfix { display: block; }    * html .clearfix { height: 1%; }3. 2011 updated clearfix    .clearfix:before, .container:after { content: ""; display: table; }    .clearfix:after { clear: both; }    /* ie 6/7 */    .clearfix { zoom: 1; }4. cross-browser transparency    .transparent {        filter: alpha(opacity=50); /* internet explorer */        -khtml-opacity: 0.5;      /* khtml, old safari */        -moz-opacity: 0.5;       /* mozilla, netscape */        opacity: 0.5;           /* fx, safari, opera */    }5. css blockquote template    blockquote {        background: #f9f9f9;        border-left: 10px solid #ccc;        margin: 1.5em 10px;        padding: .5em 10px;        quotes: "\201c""\201d""\2018""\2019";    }    blockquote:before {        color: #ccc;        content: open-quote;        font-size: 4em;        line-height: .1em;        margin-right: .25em;        vertical-align: -.4em;    }    blockquote p {        display: inline;    }6. individual rounded corners    #container {        -webkit-border-radius: 4px 3px 6px 10px;        -moz-border-radius: 4px 3px 6px 10px;        -o-border-radius: 4px 3px 6px 10px;        border-radius: 4px 3px 6px 10px;    }    /* alternative syntax broken into each line */    #container {        -webkit-border-top-left-radius: 4px;        -webkit-border-top-right-radius: 3px;        -webkit-border-bottom-right-radius: 6px;        -webkit-border-bottom-left-radius: 10px;        -moz-border-radius-topleft: 4px;        -moz-border-radius-topright: 3px;        -moz-border-radius-bottomright: 6px;        -moz-border-radius-bottomleft: 10px;    }7. general media queries/* smartphones (portrait and landscape) ----------- */@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {  /* styles */}/* smartphones (landscape) ----------- */@media only screen and (min-width : 321px) {  /* styles */}/* smartphones (portrait) ----------- */@media only screen and (max-width : 320px) {  /* styles */}/* ipads (portrait and landscape) ----------- */@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {  /* styles */}/* ipads (landscape) ----------- */@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {  /* styles */}/* ipads (portrait) ----------- */@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {  /* styles */}/* desktops and laptops ----------- */@media only screen and (min-width : 1224px) {  /* styles */}/* large screens ----------- */@media only screen and (min-width : 1824px) {  /* styles */}/* iphone 4 ----------- */@media only screen and (-webkit-min-device-pixel-ratio:1.5), only screen and (min-device-pixel-ratio:1.5) {  /* styles */}8. modern font stacks/* times new roman-based serif */font-family: cambria, "hoefler text", utopia, "liberation serif", "nimbus roman no9 l regular", times, "times new roman", serif;/* a modern georgia-based serif */font-family: constantia, "lucida bright", lucidabright, "lucida serif", lucida, "dejavu serif," "bitstream vera serif", "liberation serif", georgia, serif;/*a more traditional garamond-based serif */font-family: "palatino linotype", palatino, palladio, "urw palladio l", "book antiqua", baskerville, "bookman old style", "bitstream charter", "nimbus roman no9 l", garamond, "apple garamond", "itc garamond narrow", "new century schoolbook", "century schoolbook", "century schoolbook l", georgia, serif;/*the helvetica/arial-based sans serif */font-family: frutiger, "frutiger linotype", univers, calibri, "gill sans", "gill sans mt", "myriad pro", myriad, "dejavu sans condensed", "liberation sans", "nimbus sans l", tahoma, geneva, "helvetica neue", helvetica, arial, sans-serif;/*the verdana-based sans serif */font-family: corbel, "lucida grande", "lucida sans unicode", "lucida sans", "dejavu sans", "bitstream vera sans", "liberation sans", verdana, "verdana ref", sans-serif;/*the trebuchet-based sans serif */font-family: "segoe ui", candara, "bitstream vera sans", "dejavu sans", "bitstream vera sans", "trebuchet ms", verdana, "verdana ref", sans-serif;/*the heavier "impact" sans serif */font-family: impact, haettenschweiler, "franklin gothic bold", charcoal, "helvetica inserat", "bitstream vera sans bold", "arial black", sans-serif;/*the monospace */font-family: consolas, "andale mono wt", "andale mono", "lucida console", "lucida sans typewriter", "dejavu sans mono", "bitstream vera sans mono", "liberation mono", "nimbus mono l", monaco, "courier new", courier, monospace;9. custom text selection::selection { background: #e2eae2; }::-moz-selection { background: #e2eae2; }::-webkit-selection { background: #e2eae2; }10. hiding h1 text for logoh1 {    text-indent: -9999px;    margin: 0 auto;    width: 320px;    height: 85px;    background: transparent url("images/logo.png") no-repeat scroll;}11. polaroid image borderimg.polaroid {    background:#000; /*change this to a background image or remove*/    border:solid #fff;    border-width:6px 6px 20px 6px;    box-shadow:1px 1px 5px #333; /* standard blur at 5px. increase for more depth */    -webkit-box-shadow:1px 1px 5px #333;    -moz-box-shadow:1px 1px 5px #333;    height:200px; /*set to height of your image or desired div*/    width:200px; /*set to width of your image or desired div*/}12. anchor link pseudo classesa:link { color: blue; }a:visited { color: purple; }a:hover { color: red; }a:active { color: yellow; }13. fancy css3 pull-quotes.has-pullquote:before {    /* reset metrics. */    padding: 0;    border: none;    /* content */    content: attr(data-pullquote);    /* pull out to the right, modular scale based margins. */    float: right;    width: 320px;    margin: 12px -140px 24px 36px;    /* baseline correction */    position: relative;    top: 5px;    /* typography (30px line-height equals 25% incremental leading) */    font-size: 23px;    line-height: 30px;}.pullquote-adelle:before {    font-family: "adelle-1", "adelle-2";    font-weight: 100;    top: 10px !important;}.pullquote-helvetica:before {    font-family: "helvetica neue", arial, sans-serif;    font-weight: bold;    top: 7px !important;}.pullquote-facit:before {    font-family: "facitweb-1", "facitweb-2", helvetica, arial, sans-serif;    font-weight: bold;    top: 7px !important;}14. fullscreen backgrounds with css3html {     background: url(''images/bg.jpg'') no-repeat center center fixed;     -webkit-background-size: cover;    -moz-background-size: cover;    -o-background-size: cover;    background-size: cover;}15. vertically centered content.container {    min-height: 6.5em;    display: table-cell;    vertical-align: middle;}16. force vertical scrollbarshtml { height: 101% }17. css3 gradients template#colorbox {    background: #629721;    background-image: -webkit-gradient(linear, left top, left bottom, from(#83b842), to(#629721));    background-image: -webkit-linear-gradient(top, #83b842, #629721);    background-image: -moz-linear-gradient(top, #83b842, #629721);    background-image: -ms-linear-gradient(top, #83b842, #629721);    background-image: -o-linear-gradient(top, #83b842, #629721);    background-image: linear-gradient(top, #83b842, #629721);}18. @font-face template@font-face {    font-family: ''mywebfont'';    src: url(''webfont.eot''); /* ie9 compat modes */    src: url(''webfont.eot?#iefix'') format(''embedded-opentype''), /* ie6-ie8 */    url(''webfont.woff'') format(''woff''), /* modern browsers */    url(''webfont.ttf'')  format(''truetype''), /* safari, android, ios */    url(''webfont.svg#svgfontname'') format(''svg''); /* legacy ios */}body {    font-family: ''mywebfont'', arial, sans-serif;}19. stitched css3 elementsp {    position:relative;    z-index:1;    padding: 10px;    margin: 10px;    font-size: 21px;    line-height: 1.3em;    color: #fff;    background: #ff0030;    -webkit-box-shadow: 0 0 0 4px #ff0030, 2px 1px 4px 4px rgba(10,10,0,.5);    -moz-box-shadow: 0 0 0 4px #ff0030, 2px 1px 4px 4px rgba(10,10,0,.5);    box-shadow: 0 0 0 4px #ff0030, 2px 1px 6px 4px rgba(10,10,0,.5);    -webkit-border-radius: 3px;    -moz-border-radius: 3px;    border-radius: 3px;}p:before {    content: "";    position: absolute;    z-index: -1;    top: 3px;    bottom: 3px;    left :3px;    right: 3px;    border: 2px dashed #fff;}p a {    color: #fff;    text-decoration:none;}p a:hover, p a:focus, p a:active {    text-decoration:underline;}20. css3 zebra stripestbody tr:nth-child(odd) {    background-color: #ccc;}21. fancy ampersand.amp {    font-family: baskerville, ''goudy old style'', palatino, ''book antiqua'', serif;    font-style: italic;    font-weight: normal;}22. drop-cap paragraphsp:first-letter{    display: block;    margin: 5px 0 0 5px;    float: left;    color: #ff3366;    font-size: 5.4em;    font-family: georgia, times new roman, serif;}23. inner css3 box shadow#mydiv {     -moz-box-shadow: inset 2px 0 4px #000;    -webkit-box-shadow: inset 2px 0 4px #000;    box-shadow: inset 2px 0 4px #000;}24. outer css3 box shadow#mydiv {     -webkit-box-shadow: 0 2px 2px -2px rgba(0, 0, 0, 0.52);    -moz-box-shadow: 0 2px 2px -2px rgba(0, 0, 0, 0.52);    box-shadow: 0 2px 2px -2px rgba(0, 0, 0, 0.52);}25. triangular list bulletsul {    margin: 0.75em 0;    padding: 0 1em;    list-style: none;}li:before {     content: "";    border-color: transparent #111;    border-style: solid;    border-width: 0.35em 0 0.35em 0.45em;    display: block;    height: 0;    width: 0;    left: -1em;    top: 0.9em;    position: relative;}26. centered layout fixed width#page-wrap {    width: 800px;    margin: 0 auto;}27. css3 column text#columns-3 {    text-align: justify;    -moz-column-count: 3;    -moz-column-gap: 12px;    -moz-column-rule: 1px solid #c4c8cc;    -webkit-column-count: 3;    -webkit-column-gap: 12px;    -webkit-column-rule: 1px solid #c4c8cc;}28. css fixed footer#footer {    position: fixed;    left: 0px;    bottom: 0px;    height: 30px;    width: 100%;    background: #444;}/* ie 6 */* html #footer {    position: absolute;    top: expression((0-(footer.offsetheight)+(document.documentelement.clientheight ? document.documentelement.clientheight : document.body.clientheight)+(ignoreme = document.documentelement.scrolltop ? document.documentelement.scrolltop : document.body.scrolltop))+''px'');}29. transparent png fix for ie6.bg {    width:200px;    height:100px;    background: url(/folder/yourimage.png) no-repeat;    _background:none;    _filter:progid:dximagetransform.microsoft.alphaimageloader(src=''/folder/yourimage.png'',sizingmethod=''crop'');}/* 1px gif method */img, .png {    position: relative;    behavior: expression((this.runtimestyle.behavior="none")&&(this.pngset?this.pngset=true:(this.nodename == "img" && this.src.tolowercase().indexof(''.png'')>-1?(this.runtimestyle.backgroundimage = "none",       this.runtimestyle.filter = "progid:dximagetransform.microsoft.alphaimageloader(src=''" + this.src + "'', sizingmethod=''image'')",       this.src = "images/transparent.gif"):(this.origbg = this.origbg? this.origbg :this.currentstyle.backgroundimage.tostring().replace(''url("'','''').replace(''")'',''''),       this.runtimestyle.filter = "progid:dximagetransform.microsoft.alphaimageloader(src=''" + this.origbg + "'', sizingmethod=''crop'')",       this.runtimestyle.backgroundimage = "none")),this.pngset=true));}30. cross-browser minimum height#container {    min-height: 550px;    height: auto !important;    height: 550px;}31. css3 glowing inputsinput[type=text], textarea {    -webkit-transition: all 0.30s ease-in-out;    -moz-transition: all 0.30s ease-in-out;    -ms-transition: all 0.30s ease-in-out;    -o-transition: all 0.30s ease-in-out;    outline: none;    padding: 3px 0px 3px 3px;    margin: 5px 1px 3px 0px;    border: 1px solid #ddd;}input[type=text]:focus, textarea:focus {    box-shadow: 0 0 5px rgba(81, 203, 238, 1);    padding: 3px 0px 3px 3px;    margin: 5px 1px 3px 0px;    border: 1px solid rgba(81, 203, 238, 1);}32. style links based on filetype/* external links */a[href^="http://"] {    padding-right: 13px;    background: url(''external.gif'') no-repeat center right;}/* emails */a[href^="mailto:"] {    padding-right: 20px;    background: url(''email.png'') no-repeat center right;}/* pdfs */a[href$=".pdf"] {    padding-right: 18px;    background: url(''acrobat.png'') no-repeat center right;}33. force code wrapspre {    white-space: pre-wrap;       /* css-3 */    white-space: -moz-pre-wrap;  /* mozilla, since 1999 */    white-space: -pre-wrap;      /* opera 4-6 */    white-space: -o-pre-wrap;    /* opera 7 */    word-wrap: break-word;       /* internet explorer 5.5+ */}34. force hand cursor over clickable itemsa[href], input[type=''submit''], input[type=''image''], label[for], select, button, .pointer {    cursor: pointer;}35. webpage top box shadowbody:before {    content: "";    position: fixed;    top: -10px;    left: 0;    width: 100%;    height: 10px;    -webkit-box-shadow: 0px 0px 10px rgba(0,0,0,.8);    -moz-box-shadow: 0px 0px 10px rgba(0,0,0,.8);    box-shadow: 0px 0px 10px rgba(0,0,0,.8);    z-index: 100;}36. css3 speech bubble.chat-bubble {    background-color: #ededed;    border: 2px solid #666;    font-size: 35px;    line-height: 1.3em;    margin: 10px auto;    padding: 10px;    position: relative;    text-align: center;    width: 300px;    -moz-border-radius: 20px;    -webkit-border-radius: 20px;    -moz-box-shadow: 0 0 5px #888;    -webkit-box-shadow: 0 0 5px #888;    font-family: ''bangers'', arial, serif; }.chat-bubble-arrow-border {    border-color: #666 transparent transparent transparent;    border-style: solid;    border-width: 20px;    height: 0;    width: 0;    position: absolute;    bottom: -42px;    left: 30px;}.chat-bubble-arrow {    border-color: #ededed transparent transparent transparent;    border-style: solid;    border-width: 20px;    height: 0;    width: 0;    position: absolute;    bottom: -39px;    left: 30px;}37. default h1-h5 headersh1,h2,h3,h4,h5{    color: #005a9c;}h1{    font-size: 2.6em;    line-height: 2.45em;}h2{    font-size: 2.1em;    line-height: 1.9em;}h3{    font-size: 1.8em;    line-height: 1.65em;}h4{    font-size: 1.65em;    line-height: 1.4em;}h5{    font-size: 1.4em;    line-height: 1.25em;}38. pure css background noisebody {    background-image: url(data:image/png;base64,ivborw0kggoaaaansuheugaaadiaaaaycamaaaap4xidaaaauvbmvewfhywdg4n3d3dtbw17e3t1dxwbgyghh4d5exlzc3oli4ubm5uvlzwpj4+njy19fx2jiyl/f39ra2urkzgzmzlpawmxl5dvb29xcxgtk5nnz2c8tv1maaaag3rstlnaqebaqebaqebaqebaqebaqebaqebaqebaqeaveowtaaafvkleqvr4xpwwb67c2bufb3g557t/hro9/wumzhlgr4bg8z4qqgqjlhi4a8szfvrapvmtf9o7dmyrfz60yibhjrcgh1fyhilamdvx0cztopne77me0zty/nwwzchdtiqrmqdeuv3powq5ta2en0fy0inkqdd73lt9c9lezwunqgfhs9vqce3tvclfcqrstfoiykvjqbmpbq2l6izavpnapcou0dsw0sutqz/gtrguxfbyybnikykowqwgqwwma7qiyaxi+ilpdqo+hyhnut5zpfnshjynidtnpjyaynbkf6cwoygamy92u2hxhf/c1m8up/ztydiuj26udadqqsxqerwsomzt/xwrwaz5gusbikwg1h3fabj2osuouhgc6tk4emtjo0ttc6ibd3km0ve0tjwmdsfjzo+eeisaetr9p3wyrgjxqyc1krckdhmpxent5jetoulscpyzhxn5frpuphvbeqakxfaeb6en+cyn6xd7rygpxpnndmmzgm5dcs3ysnfdhuo2lgfzuukswyuyirjadybf3mfqekmjm+i2efha94ig3l7ukrr+gdwd73ydlib+6hgref1qtlmgmbm3/lex5gi1ux1rwpgxpluz2+i+ijzz8wqe4nilvqdkudfhzi5qdwy+kw5wgg2pgpeevecca7b85bo3f9dzxb3cdqvbzwcmzbymiqhzuyqthrvg2y4x+kolnyqla8aowwpuboyrxzxrfkuill6sfiwcbjxozjuacbj1cjh7giadbc9kqby3w/rgjda1iqqcoju2ww+76pzc9qg7m00dffe9hnnseupfl53r8f7yhswjwukp2q+k7rdsxyob11n0xtovnw4irmmfnv4h0uqws5exsmp9axbdtc9jwgneat5vtiusm1e7bsflst3bfa1tv8di3r8n3af7mnwzs49hmaue2wp+ttrq+aswpfg2awvsuoqbipwhgtuvuaae+a1z/7gc9hesnr+7wqcwg8c5yag3al1fm8t9aztp/bbjgwl1pnre7ruox7pemruervappes+yqeosmuolokqw49pgomjleh7ichnlg19yjs6xxomedym5xh2yxpv2tc0ro2jjfxc50apuxgob7lmsxftbeuv07tyyxpeluceh1gnd4ikh2lag5tdvhlcafzvpskfnccfx8pohjzd76bjweyfnfciwcyfubrc12ip/ppiha1/msz/rxjfdrjc5xiffjjpy2xl5zxdgufqyytr1zsp1y9p+tktdyysnflcxi0iyo4tpbdlrcpeqjk/pif5bklq77vseaa+z8qmjtfziwiitbnzr794uskbuat0ntesvjzqlafvqjopn9odg70ipbfbhkk+/q/awr0tjzyhruloa4mp+w/hfgadzubfw177g7j/ogbis8tahlyynl4x4rinf793oz+bu0saxtuhrvbft/dna3ctnpogbs4hrijtok8i+algt1lthi4sxfvonknrgqfaq2/gfnwmxgwffgymjpikykmw3ttg3zq9jq+f8xn+a5eeukhwvjwj2sgj1sop+wwhqfvijqwajhwtd8mnlsbewnnwta5z5kpzw5+lbvt99wqtdx29lmuh4oig/d86rukeaubjvh5xy6um/sfj7ei6uuvk4ail3myd4msstofgswsh/qjwaq5as7zcmgbzkzjju1urq74ci1gwbcsghtuv1h2mhsno3wp/3fev5a+4wz//6qy8jxjzsmxxy5+4w9cdnjy09t072ikg0enos0areygxqynxcyhwjttunacmelod4xpkoqityicwfq0jsipfpdqdnt+4/wuqcxy47qilbgaaaabjru5erkjggg==);    background-color: #0094d0;}39. continued list orderingol.chapters {    list-style: none;    margin-left: 0;}ol.chapters > li:before {    content: counter(chapter) ". ";    counter-increment: chapter;    font-weight: bold;    float: left;    width: 40px;}ol.chapters li {    clear: left;}ol.start {    counter-reset: chapter;}ol.continue {    counter-reset: chapter 11;}40. css tooltip hoversa {     border-bottom:1px solid #bbb;    color:#666;    display:inline-block;    position:relative;    text-decoration:none;}a:hover,a:focus {    color:#36c;}a:active {    top:1px; }/* tooltip styling */a[data-tooltip]:after {    border-top: 8px solid #222;    border-top: 8px solid hsla(0,0%,0%,.85);    border-left: 8px solid transparent;    border-right: 8px solid transparent;    content: "";    display: none;    height: 0;    width: 0;    left: 25%;    position: absolute;}a[data-tooltip]:before {    background: #222;    background: hsla(0,0%,0%,.85);    color: #f6f6f6;    content: attr(data-tooltip);    display: none;    font-family: sans-serif;    font-size: 14px;    height: 32px;    left: 0;    line-height: 32px;    padding: 0 15px;    position: absolute;    text-shadow: 0 1px 1px hsla(0,0%,0%,1);    white-space: nowrap;    -webkit-border-radius: 5px;    -moz-border-radius: 5px;    -o-border-radius: 5px;    border-radius: 5px;}a[data-tooltip]:hover:after {    display: block;    top: -9px;}a[data-tooltip]:hover:before {    display: block;    top: -41px;}a[data-tooltip]:active:after {    top: -10px;}a[data-tooltip]:active:before {    top: -42px;}41. dark grey rounded buttons.graybtn {    -moz-box-shadow:inset 0px 1px 0px 0px #ffffff;    -webkit-box-shadow:inset 0px 1px 0px 0px #ffffff;    box-shadow:inset 0px 1px 0px 0px #ffffff;    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #d1d1d1) );    background:-moz-linear-gradient( center top, #ffffff 5%, #d1d1d1 100% );    filter:progid:dximagetransform.microsoft.gradient(startcolorstr=''#ffffff'', endcolorstr=''#d1d1d1'');    background-color:#ffffff;    -moz-border-radius:6px;    -webkit-border-radius:6px;    border-radius:6px;    border:1px solid #dcdcdc;    display:inline-block;    color:#777777;    font-family:arial;    font-size:15px;    font-weight:bold;    padding:6px 24px;    text-decoration:none;    text-shadow:1px 1px 0px #ffffff;}.graybtn:hover {    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #d1d1d1), color-stop(1, #ffffff) );    background:-moz-linear-gradient( center top, #d1d1d1 5%, #ffffff 100% );    filter:progid:dximagetransform.microsoft.gradient(startcolorstr=''#d1d1d1'', endcolorstr=''#ffffff'');    background-color:#d1d1d1;}.graybtn:active {    position:relative;    top:1px;}42. display urls in a printed webpage@media print   {    a:after {      content: " [" attr(href) "] ";    }  }43. disable mobile webkit highlightsbody {    -webkit-touch-callout: none;    -webkit-user-select: none;    -khtml-user-select: none;    -moz-user-select: none;    -ms-user-select: none;    user-select: none;}44. css3 polka-dot patternbody {    background: radial-gradient(circle, white 10%, transparent 10%),    radial-gradient(circle, white 10%, black 10%) 50px 50px;    background-size: 100px 100px;}45. css3 checkered patternbody {    background-color: white;    background-image: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%, black),     linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%, black);    background-size: 100px 100px;    background-position: 0 0, 50px 50px;}46. github fork ribbon.ribbon {    background-color: #a00;    overflow: hidden;    /* top left corner */    position: absolute;    left: -3em;    top: 2.5em;    /* 45 deg ccw rotation */    -moz-transform: rotate(-45deg);    -webkit-transform: rotate(-45deg);    /* shadow */    -moz-box-shadow: 0 0 1em #888;    -webkit-box-shadow: 0 0 1em #888;}.ribbon a {    border: 1px solid #faa;    color: #fff;    display: block;    font: bold 81.25% ''helvetiva neue'', helvetica, arial, sans-serif;    margin: 0.05em 0 0.075em 0;    padding: 0.5em 3.5em;    text-align: center;    text-decoration: none;    /* shadow */    text-shadow: 0 0 0.5em #444;}47. condensed css font propertiesp {  font: italic small-caps bold 1.2em/1.0em arial, tahoma, helvetica;}48. paper page curl effectul.box {    position: relative;    z-index: 1; /* prevent shadows falling behind containers with backgrounds */    overflow: hidden;    list-style: none;    margin: 0;    padding: 0; }ul.box li {    position: relative;    float: left;    width: 250px;    height: 150px;    padding: 0;    border: 1px solid #efefef;    margin: 0 30px 30px 0;    background: #fff;    -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27), 0 0 40px rgba(0, 0, 0, 0.06) inset;    -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27), 0 0 40px rgba(0, 0, 0, 0.06) inset;     box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27), 0 0 40px rgba(0, 0, 0, 0.06) inset; }ul.box li:before,ul.box li:after {    content: '''';    z-index: -1;    position: absolute;    left: 10px;    bottom: 10px;    width: 70%;    max-width: 300px; /* avoid rotation causing ugly appearance at large container widths */    max-height: 100px;    height: 55%;    -webkit-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);    -moz-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);    -webkit-transform: skew(-15deg) rotate(-6deg);    -moz-transform: skew(-15deg) rotate(-6deg);    -ms-transform: skew(-15deg) rotate(-6deg);    -o-transform: skew(-15deg) rotate(-6deg);    transform: skew(-15deg) rotate(-6deg); }ul.box li:after {    left: auto;    right: 10px;    -webkit-transform: skew(15deg) rotate(6deg);    -moz-transform: skew(15deg) rotate(6deg);    -ms-transform: skew(15deg) rotate(6deg);    -o-transform: skew(15deg) rotate(6deg);    transform: skew(15deg) rotate(6deg); }49. glowing anchor linksa {    color: #00e;}a:visited {    color: #551a8b;}a:hover {    color: #06e;}a:focus {    outline: thin dotted;}a:hover, a:active {    outline: 0;}a, a:visited, a:active {    text-decoration: none;    color: #fff;    -webkit-transition: all .3s ease-in-out;}a:hover, .glow {    color: #ff0;    text-shadow: 0 0 10px #ff0;}50. featured css3 display banner.featurebanner {    position: relative;    margin: 20px}.featurebanner:before {    content: "featured";    position: absolute;    top: 5px;    left: -8px;    padding-right: 10px;    color: #232323;    font-weight: bold;    height: 0px;    border: 15px solid #ffa200;    border-right-color: transparent;    line-height: 0px;    box-shadow: -0px 5px 5px -5px #000;    z-index: 1;}.featurebanner:after {    content: "";    position: absolute;    top: 35px;    left: -8px;    border: 4px solid #89540c;    border-left-color: transparent;    border-bottom-color: transparent;}
登录后复制

转载自:http://www.9958.pw/post/css_50_useful

7个WordPress常用代码段(Code Snippets)

7个WordPress常用代码段(Code Snippets)

运用代码段(Code Snippets)插件管理代码,可以不用额外安装更多插件,来解决WordPress建站过程中的一些常见功能需求,譬如安装Google analytics跟踪代码。下文中记录了我在搭建外贸网站和个人博客中常用到的代码段。

原文首发于:https://loyseo.com/code-snipp...

如何在WordPress文章/页面上禁止加载WooCommerce .Js(Javascript)和.Css文件?

woocommerce会在每个页面都默认加载几个css和js,这对网站速度是有影响的,将下面这段代码,在code snippets插件中添加一个新snippet,能够实现在除了购物车、结算、账户、产品以外的页面中,移除woocommerce的css和js。

/** Disable All WooCommerce  Styles and Scripts Except Shop Pages*/
add\_action( ''wp\_enqueue\_scripts'', ''dequeue\_woocommerce\_styles\_scripts'', 99 );
function dequeue\_woocommerce\_styles_scripts() {
if ( function\_exists( ''is\_woocommerce'' ) ) {
if ( ! is\_woocommerce() && ! is\_cart() && ! is_checkout() ) {
# Styles
wp\_dequeue\_style( ''woocommerce-general'' );
wp\_dequeue\_style( ''woocommerce-layout'' );
wp\_dequeue\_style( ''woocommerce-smallscreen'' );
wp\_dequeue\_style( ''woocommerce\_frontend\_styles'' );
wp\_dequeue\_style( ''woocommerce\_fancybox\_styles'' );
wp\_dequeue\_style( ''woocommerce\_chosen\_styles'' );
wp\_dequeue\_style( ''woocommerce\_prettyPhoto\_css'' );
# Scripts
wp\_dequeue\_script( ''wc\_price\_slider'' );
wp\_dequeue\_script( ''wc-single-product'' );
wp\_dequeue\_script( ''wc-add-to-cart'' );
wp\_dequeue\_script( ''wc-cart-fragments'' );
wp\_dequeue\_script( ''wc-checkout'' );
wp\_dequeue\_script( ''wc-add-to-cart-variation'' );
wp\_dequeue\_script( ''wc-single-product'' );
wp\_dequeue\_script( ''wc-cart'' );
wp\_dequeue\_script( ''wc-chosen'' );
wp\_dequeue\_script( ''woocommerce'' );
wp\_dequeue\_script( ''prettyPhoto'' );
wp\_dequeue\_script( ''prettyPhoto-init'' );
wp\_dequeue\_script( ''jquery-blockui'' );
wp\_dequeue\_script( ''jquery-placeholder'' );
wp\_dequeue\_script( ''fancybox'' );
wp\_dequeue\_script( ''jqueryui'' );
}
}
}

如何禁用WordPress的XML-RPC

WordPress站点很少需要启用XML-RPC,但是启用它可能会导致大量的安全问题。如果你使用WordPress应用程序,你才需要启用它。此代码片段将禁用XML-RPC以提高站点安全性。

add\_filter(''xmlrpc\_enabled'', ''\_\_return\_false'');

如何用代码段安装Google Analytics跟踪代码

请将从Google analytics中获取的跟踪代码放入到如下代码段中

add\_action( ''wp\_head'', function () { ?>
    
这里粘贴Google Analytics的跟踪代码
<?php });

相关教程:如何给WordPress网站安装Google Analytics跟踪代码

如何移除/隐藏WordPress评论中的Url字段

下面这段代码可以移除/隐藏部分WordPress主题中评论URL字段,如果你使用后发现不能移除,那说明主题不兼容,你可以在谷歌搜索:Remove Website field from the Comment Form in XXX theme,将XXX改为你的主题名称。

function remove\_comment\_fields($fields) {
unset($fields\[''url''\]);
return $fields;
}
add\_filter(''comment\_form\_default\_fields'',''remove\_comment\_fields'');

譬如,在astra主题免费版中,隐藏评论的url字段使用下面的代码

function wpd\_remove\_comment\_website\_field( $fields ) {
    unset( $fields\[''url''\] );
    
    return $fields;
}
add\_filter( ''comment\_form\_default\_fields'', ''wpd\_remove\_comment\_website\_field'', 99 );

在astra 主题付费版中,移除评论的url字段使用下面的代码

function wpd\_remove\_comment\_website\_field( $fields ) {
    unset( $fields\[''url''\] );
    
    return $fields;
}
add\_filter( ''astra\_comment\_form\_default\_fields\_markup'', ''wpd\_remove\_comment\_website\_field'', 99 );

如何用代码段实现复制文章功能

下面这段代码可以给WordPress文章/自定义文章添加复制功能,在文章列表中会出现duplicate按钮,但不会给页面添加复制功能。使用它你可以省了一个复制文章功能插件。

/*
 * Function for post duplication. Dups appear as drafts. User is redirected to the edit screen
 */
function rd\_duplicate\_post\_as\_draft(){
  global $wpdb;
  if (! ( isset( $\_GET\[''post''\]) || isset( $\_POST\[''post''\])  || ( isset($\_REQUEST\[''action''\]) && ''rd\_duplicate\_post\_as\_draft'' == $\_REQUEST\[''action''\] ) ) ) {
    wp_die(''No post to duplicate has been supplied!'');
  }
 
  /*
   * Nonce verification
   */
  if ( !isset( $\_GET\[''duplicate\_nonce''\] ) || !wp\_verify\_nonce( $\_GET\[''duplicate\_nonce''\], basename( \_\_FILE\_\_ ) ) )
    return;
 
  /*
   * get the original post id
   */
  $post\_id = (isset($\_GET\[''post''\]) ? absint( $\_GET\[''post''\] ) : absint( $\_POST\[''post''\] ) );
  /*
   * and all the original post data then
   */
  $post = get\_post( $post\_id );
 
  /*
   * if you don''t want current user to be the new post author,
   * then change next couple of lines to this: $new\_post\_author = $post->post_author;
   */
  $current\_user = wp\_get\_current\_user();
  $new\_post\_author = $current_user->ID;
 
  /*
   * if post data exists, create the post duplicate
   */
  if (isset( $post ) && $post != null) {
 
    /*
     * new post data array
     */
    $args = array(
      ''comment\_status'' => $post->comment\_status,
      ''ping\_status''    => $post->ping\_status,
      ''post\_author''    => $new\_post_author,
      ''post\_content''   => $post->post\_content,
      ''post\_excerpt''   => $post->post\_excerpt,
      ''post\_name''      => $post->post\_name,
      ''post\_parent''    => $post->post\_parent,
      ''post\_password''  => $post->post\_password,
      ''post_status''    => ''draft'',
      ''post\_title''     => $post->post\_title,
      ''post\_type''      => $post->post\_type,
      ''to\_ping''        => $post->to\_ping,
      ''menu\_order''     => $post->menu\_order
    );
 
    /*
     * insert the post by wp\_insert\_post() function
     */
    $new\_post\_id = wp\_insert\_post( $args );
 
    /*
     * get all current post terms ad set them to the new post draft
     */
    $taxonomies = get\_object\_taxonomies($post->post\_type); // returns array of taxonomy names for post type, ex array("category", "post\_tag");
    foreach ($taxonomies as $taxonomy) {
      $post\_terms = wp\_get\_object\_terms($post_id, $taxonomy, array(''fields'' => ''slugs''));
      wp\_set\_object\_terms($new\_post\_id, $post\_terms, $taxonomy, false);
    }
 
    /*
     * duplicate all post meta just in two SQL queries
     */
    $post\_meta\_infos = $wpdb->get\_results("SELECT meta\_key, meta\_value FROM $wpdb->postmeta WHERE post\_id=$post_id");
    if (count($post\_meta\_infos)!=0) {
      $sql\_query = "INSERT INTO $wpdb->postmeta (post\_id, meta\_key, meta\_value) ";
      foreach ($post\_meta\_infos as $meta_info) {
        $meta\_key = $meta\_info->meta_key;
        if( $meta\_key == ''\_wp\_old\_slug'' ) continue;
        $meta\_value = addslashes($meta\_info->meta_value);
        $sql\_query\_sel\[\]= "SELECT $new\_post\_id, ''$meta\_key'', ''$meta\_value''";
      }
      $sql\_query.= implode(" UNION ALL ", $sql\_query_sel);
      $wpdb->query($sql_query);
    }
 
 
    /*
     * finally, redirect to the edit post screen for the new draft
     */
    wp\_redirect( admin\_url( ''post.php?action=edit&post='' . $new\_post\_id ) );
    exit;
  } else {
    wp\_die(''Post creation failed, could not find original post: '' . $post\_id);
  }
}
add\_action( ''admin\_action\_rd\_duplicate\_post\_as\_draft'', ''rd\_duplicate\_post\_as_draft'' );
 
/*
 * Add the duplicate link to action list for post\_row\_actions
 */
function rd\_duplicate\_post_link( $actions, $post ) {
  if (current\_user\_can(''edit_posts'')) {
    $actions\[''duplicate''\] = ''<a href="'' . wp\_nonce\_url(''admin.php?action=rd\_duplicate\_post\_as\_draft&post='' . $post->ID, basename(\_\_FILE\_\_), ''duplicate_nonce'' ) . ''" title="Duplicate this item" rel="permalink">Duplicate</a>'';
  }
  return $actions;
}
 
add\_filter( ''post\_row\_actions'', ''rd\_duplicate\_post\_link'', 10, 2 );

如何用代码段禁止WordPress自动生成图片

由于每张图片在上传到WordPress时,会被WordPress或部分插件自动生成很多不同尺寸的图片,针对用不上的图片尺寸,可以用短代码直接组织系统生成图片,不仅能节省空间,也能避免消耗压缩额度,下面介绍如何用代码段(code snippets)禁止WordPress自动生成图片。

需要知道的是,这些自动生成的图片并不能在Wordpress的媒体库看到,需要在服务器的文件夹中查看。

下图是Siteground后台查看图片文件的方法,请在进入网站的Sitetools后按下图所示顺序操作查看,我们能看到系统为同一张图生成了很多不同尺寸的图片。

在网站页面设计完、内容上传前,我们先禁止所有自动生成的图片;若马上可以上传内容了,我们可以根据设计情况,酌情放开部分图片尺寸,譬如在制作产品列表页时,我们用到了300*300px的图片,那么就在下面的代码中,将对应行的代码前加//注释掉或直接删除该行。

// disable generated image sizes
function shapeSpace_disable_image_sizes($sizes) {
    
    unset($sizes[''thumbnail'']);    // disable thumbnail size
    unset($sizes[''medium'']);       // disable medium size
    unset($sizes[''large'']);        // disable large size
    unset($sizes[''medium_large'']); // disable medium-large size
    unset($sizes[''1536x1536'']);    // disable 2x medium-large size
    unset($sizes[''2048x2048'']);    // disable 2x large size
   unset($sizes[''shop_catalog'']);
   unset($sizes[''shop_single'']);
   unset($sizes[''shop_thumbnail'']);
   unset($sizes[''woocommerce_thumbnail'']);
   unset($sizes[''woocommerce_single'']);
   unset($sizes[''woocommerce_gallery_thumbnail'']);
    
    return $sizes;
    
}
add_action(''intermediate_image_sizes_advanced'', ''shapeSpace_disable_image_sizes'');

// disable scaled image size
add_filter(''big_image_size_threshold'', ''__return_false'');

// disable other image sizes
function shapeSpace_disable_other_image_sizes() {
    
    remove_image_size(''post-thumbnail''); // disable images added via set_post_thumbnail_size() 
    remove_image_size(''another-size'');   // disable any other added image sizes
    
}
add_action(''init'', ''shapeSpace_disable_other_image_sizes'');

如何用代码段去掉Woocommerce产品首页、列表页的面包屑

/**
 * Remove the breadcrumbs 
 */
add\_action( ''init'', ''woo\_remove\_wc\_breadcrumbs'' );
function woo\_remove\_wc_breadcrumbs() {
    remove\_action( ''woocommerce\_before\_main\_content'', ''woocommerce_breadcrumb'', 20, 0 );
}
本文原文由LOYSEO 发布,LOYSEO专注于WordPress、Elementor、外贸建站教程。

推荐阅读

外贸建站系列教程
2020年B2B外贸建站的终极教程
2020年外贸建站需要注意什么?(4300字经验谈)

今天关于iOS-Snippets 常见代码块引用ios常用代码块整理集合的讲解已经结束,谢谢您的阅读,如果想了解更多关于20 Very Useful Java Code Snippets、20 very useful Java code snippets for Java Develop、50 Useful CSS Snippets Every Designer Should Have_html/css_WEB-ITnose、7个WordPress常用代码段(Code Snippets)的相关知识,请在本站搜索。

本文标签: