DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
  • submit to reddit
JQuery::
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
		jQuery.fn.alternateColorCellBoard=function(p1,p2,parr,col1,col2,ht,wd){
			return this.append(
				    function(){
				        var content='<table border="1" id="acbGridTable">';
				        var idv=0;
				        var colr=0;
				        for (var i=0; i<p1; i++  ){			        	 
				        	content=content+'<tr id="acbRId_'+i+'">';
				        	for (var j=0; j<p2; j++  ){
				        		if(i%2<1){
				        			if(j%2<1)
				        				colr=col1;
				        			else 
				        				colr=col2;				        			
				        		}else{ 
				        			if(j%2<1)
				        				colr=col2;			        				
				        			else 
				        				colr=col1;				        			
				        		}
				        		content=content+'<td height="'+ht+'"px" width="'+wd+'"px" bgcolor="'+colr+'" class="acbCId_'+idv+'" id="acbCId_'+idv+'">'+parr[idv]+'</td>';
				            	idv++;
				        	}			        	
				        	content=content+'</tr>';
				        }
				        content= content+'</table>';
				        return content;
				    });
		}
</script>




The HTML ::

<body>
<div>
	<div id="chequeredBoard"></div>
</div>
</body>

<script>
var myArr = [];
for (var i=0; i<100; i++  ){
	myArr[i]=i+1;
}

$(document).ready(function() {	   
		$('#chequeredBoard').alternateColorCellBoard(10,10,myArr,"red","skyblue",50,50);			
	});
</script>
//Load a diagram
Diagram diagram = new Diagram("C:\\Drawing1.vdx");

//Get first page
if (diagram.getPages().getCount() == 0)
{
    JOptionPane.showConfirmDialog(null, "The diagram does not contain pages.");
    return;
}
Page page0 = diagram.getPages().getPage(0);
//Get the rectangle master
Master masterRectangle = null;
for (Master master : (Iterable<Master>) diagram.getMasters())
    if (master.getName() == "Rectangle")
    {
        masterRectangle = master;
        break;
    }
if (masterRectangle == null)
{
    JOptionPane.showConfirmDialog(null, "The diagram does not contain rectangle's master.");
    return;
}
//Get the next shape ID
long nextID;
for (Page page : (Iterable<Page>)diagram.getPages())
{
    for (Shape shape : (Iterable<Shape>) page.getShapes())
    {
        long temp = GetMaxShapeID(shape);
        if (temp > nextID)
            nextID = temp;
    }
    nextID++;
}
//Set shape properties and add it in the shapes' collection
Shape rectangle = new Shape();
rectangle.setMaster(masterRectangle);
rectangle.setMasterShape(masterRectangle.getShapes().getShape(0));
rectangle.setID(nextID);
rectangle.getXForm().getPinX().setValue(5);
rectangle.getXForm().getPinY().setValue(5);
rectangle.setType(TypeValue.SHAPE);
rectangle.getText().getValue().add(new Txt("Aspose Diagram"));
rectangle.setTextStyle(diagram.getStyleSheets().getStyleSheet(3));
rectangle.getLine().getLineColor().setValue(page0.getShapes().getShape(1).getFill().getFillForegnd().getValue());
rectangle.getLine().getLineWeight().setValue(0.03041666666666667);
rectangle.getLine().getRounding().setValue(0.1);
rectangle.getFill().getFillBkgnd().setValue(page0.getShapes().getShape(0).getFill().getFillBkgnd().getValue());
rectangle.getFill().getFillForegnd().setValue("#ebf8df");
page0.getShapes().add(rectangle);
diagram.save("C:\\output.vdx", SaveFileFormat.VDX);
JOptionPane.showConfirmDialog(null, "Shape has been added.");

private long GetMaxShapeID(Shape shape)
{
    long max = shape.getID();
    for (Shape child : (Iterable<Shape>)shape.getShapes())
    {
        long temp = GetMaxShapeID(child);
        if (temp > max)
            max = temp;
    }
    return max;
}

Context XML (userDAO-queries.xml) part :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans		 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    
<util:map id="VALIDATE_USER_CREDENTIAL" key-type="java.lang.String" value-type="java.lang.String" >
    	<entry key="QUERY" >
    		 <value>SELECT	user_id,	 user_name,  user_password 
			FROM	ty_users 
			WHERE	user_name = ? AND user_password = ?
   		</value>
    	</entry> 
    </util:map>
</beans>




Java Code Part:

UserDAOImpl.java
public class UserDAOImpl implements UserDAO{
	
	private static final Logger logger = LoggerFactory.getLogger(UserDAOImpl.class);// logger
	
	DBQueries dbQuery = new DBQueriesImpl("userDAO-queries.xml");//
	DBConnection dbConn = ConnectionFactory.getInstance().getConnectionMySQL();
	
	@Override
	public List<User> authenitcUserDetails(String userName, String userPassword) {
		Map<String, String> queryMap = null;
		String query ;
		List<Map<String, Object>> mappedUserList = null;
		List<User> listUser = null;
		try{	
			listUser = new ArrayList<User>();
			queryMap = dbQuery.getQueryBeanFromFactory("VALIDATE_USER_CREDENTIAL"); //passing the query-name or Map Id.
			query =  dbQuery.getQuery(queryMap);//passing the query-map to get the query.

//rest of the code is common fetching code.						
			mappedUserList = dbConn.dbQueryRead(query, new Object[]{userName,userPassword});			
			if(mappedUserList.size()>0){
				listUser =  new QueryResultSetMapperImpl<User>().mapRersultSetToObject(mappedUserList, User.class);
			}
		}catch(Exception  ex){
			logger.error("fetchAllUser Error:: ", ex);
		}		
		return listUser;
	}
}








DBQueriesImpl.java
public class DBQueriesImpl implements DBQueries {
	
	private static final Logger logger = LoggerFactory.getLogger(DBQueriesImpl.class);
		
	private ApplicationContext queriesCtx ;
	
       /**
	 * @Desc: Loading the queryContext xml
	 * @param queryContext
	 */
	public DBQueriesImpl(String queryContext) {
		queriesCtx = new ClassPathXmlApplicationContext(queryContext);
	}
	
        /**
	 * @Desc: Reading from the loaded application context and getting the query-map, .  
	 */
	@Override
	public Map<String, String> getQueryBeanFromFactory(String beanId){
		Map<String, String> queryMap = null;
		if (queriesCtx != null && beanId != null) {
			queryMap = (Map<String, String>)queriesCtx.getBean(beanId);
		}
		return queryMap;
	}
	
       /**
	 * @Desc: Getting the exact query from the query-map, .  
	 */	
	@Override
	public String getQuery(Map<String, String> queryMap) {
		String query=null;
		try{
			if(queryMap.containsKey(QueryConstants.QUERY_NODE)){
				query = (String) queryMap.get(QueryConstants.QUERY_NODE);
				queryMap.remove(QueryConstants.QUERY_NODE);
			}else{
				throw new NoSuchFieldError();
			}
		}catch(Exception excp){
			excp.printStackTrace();
		}
		return query;
	}	
}
<html>
  <head>
    <title>Hello React</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="http://fb.me/react-0.11.1.js"></script>
    <script src="http://fb.me/JSXTransformer-0.11.1.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="page-header">
        <h1>ReactJS Hello World - Code Example</h1>
      </div>
      <div id="sayhello"></div>  
    </div>
    <script type="text/jsx">
      /** @jsx React.DOM */
      //
      // This is the parent component comprising of two inner components
      // One of the component is UserName which is used to allow user to enter their name
      // Other component is HelloText which displays the text such as Hello, World
      //
      var SayHello = React.createClass({
        // This is used to set the state, "data" which is 
        // accessed later in HelloText component to display the updated state
        // 
        getInitialState: function() {
          return {data: 'World'}
        },
        // It is recommended to capture events happening with any children
        // at the parent level and set the new state that updates the children appropriately
        handleNameSubmit: function(name) {
          this.setState({data: name});
        },
        // Render method which is comprised of two components such as UserName and HelloText
        //
        render: function() {
         return(
           <div>
            <UserName onNameSubmit={this.handleNameSubmit}/>
            <HelloText data={this.state.data}/>
           </div>
           );
        }
      });
      // UserName component which has following two methods:
      // handleChange: Used to capture onChange event 
      // render: Code to render the component
      //
      var UserName = React.createClass({
        handleChange: function() {
          var username = this.refs.username.getDOMNode().value.trim();
          this.props.onNameSubmit({username: username });
          this.refs.username.getDOMNode().value = '';
          return false;
        },
        render: function() {
         return(
          <form role="form" onChange={this.handleChange}>
             <div className="input-group input-group-lg">
                <input type="text" className="form-control col-md-8"  placeholder="Type Your Name" ref="username"/>
             </div>
          </form>
          );
        }
      });
      // HelloText component to display Hello World or Hello Name text
      // render: Consists of code display the HelloText component
      //
      var HelloText = React.createClass({
          render: function() {
            return (
            <div>
              <h3>Hello, {this.props.data}</h3>
            </div>
            );
          }
      });
      
      React.renderComponent(
        <SayHello />,
        document.getElementById( "sayhello" )
        );
    </script>
  </body>
</html>
//open document
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("/mnt/sdcard/input.pdf");
//create text stamp
com.aspose.pdf.TextStamp textStamp = new com.aspose.pdf.TextStamp("Sample Stamp");
//set properties of the stamp
textStamp.setTopMargin(10);
textStamp.setHorizontalAlignment(com.aspose.pdf.HorizontalAlignment.Center);
textStamp.setVerticalAlignment(com.aspose.pdf.VerticalAlignment.Top);

//set text properties
textStamp.getTextState().setFont(new com.aspose.pdf.FontRepository().findFont("Arial"));
textStamp.getTextState().setFontSize(14.0F);
textStamp.getTextState().setFontStyle(com.aspose.pdf.FontStyles.Bold);
textStamp.getTextState().setFontStyle(com.aspose.pdf.FontStyles.Italic);
textStamp.getTextState().setForegroundColor(java.awt.Color.GREEN);

// iterate through all pages of PDF file
for (int Page_counter =1; Page_counter<=pdfDocument.getPages().size();Page_counter++)
{
    //add stamp to all pages of PDF file
    pdfDocument.getPages().get_Item(Page_counter).addStamp(textStamp);
}
//save output document
pdfDocument.save("/mnt/sdcard/TextStamp_output.pdf");

MainActivity.java :

package www.andygeeks.blogspot.com;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import org.json.JSONArray;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    
boolean timeoutexcep=false,httpexcep=false,genexcep=false;
    
private static final String TAG_NAME = "J_Name";
private static final String TAG_ID = "J_Id";
private static final String TAG_PLACE = "J_Place";
private static final String TAG_MOBILE = "J_Phone";
    
public static String dist="Krishnagiri",type="P",no="50";
String Name,Id,Place,Phone;
    
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new pay().execute();
}

class pay extends AsyncTask<Void, Void, Void> {

private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {
this.dialog.setMessage("Loading data");
this.dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {

final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://www.xxxxxx.com/xxxx/xxx.asmx";
final String SOAP_ACTION = "http://tempuri.org/xxxxx";
final String METHOD_NAME = "xxxxx";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

request.addProperty("sDistrict", dist);
request.addProperty("sTaxType", type);
request.addProperty("sTaxNo", no);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

String responseJSON=response.toString();
JSONArray jarray =new JSONArray(responseJSON);

Name=jarray.getJSONObject(0).getString(TAG_NAME);
Id=jarray.getJSONObject(0).getString(TAG_ID);
Place=jarray.getJSONObject(0).getString(TAG_PLACE);
Phone=jarray.getJSONObject(0).getString(TAG_MOBILE);

System.out.println(request);
System.out.println(responseJSON);

}
catch(SocketTimeoutException e){
timeoutexcep=true;
e.printStackTrace();
}
catch(UnknownHostException e){
httpexcep=true;
e.printStackTrace();
}
catch (Exception e) {
genexcep=true;
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if(timeoutexcep){
Toast.makeText(MainActivity.this, "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
}
else if(httpexcep){
Toast.makeText(MainActivity.this, "Please check your Internet connection",Toast.LENGTH_LONG).show();
}
else if(genexcep){
Toast.makeText(MainActivity.this, "Please try later",Toast.LENGTH_LONG).show();
}

else{
tableview();
}
timeoutexcep=false;httpexcep=false;genexcep=false;
}
}

public void tableview(){
try{
TextView name = (TextView)findViewById(R.id.textView5);
name.setText(Name);

TextView door = (TextView)findViewById(R.id.textView6);
door.setText(Id);

TextView ward = (TextView)findViewById(R.id.textView7);
ward.setText(Place);

TextView mobile = (TextView)findViewById(R.id.textView8);
mobile.setText(Phone);
}
catch(Exception e){
}
}
    
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
package com.bos.jmx;

public class Shutdown implements ShutdownMBean {
	private static volatile boolean flagRunOne = false;

	@Override
	public void shutdown() throws Exception {
		if (!flagRunOne) {
			System.out.println("Server shutting down...");
			//Sample shutdown code here
			Main.shutdown();
			System.out.println("Server shutdown.");
			flagRunOne = true;
		}
	}
}
<!DOCTYPE html>
<html ng-app="ngSpApp">
<head>
  <title>Single Page App Template</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
		<table style="width:100%;margin:10px">
			<tr>
				<td style="width: 15%;vertical-align: top;">
					<div class="list-group" style="margin-top:20px" >
						<a href="#/" class="list-group-item active">Home</a> 
						<a href="#/link1" class="list-group-item">Link 1</a> 
					</div>
				</td>
				<td style="vertical-align: top;padding-left:10px;">
					<div ng-view></div>
				</td>
			</tr>
		</table>
	</div>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular-route.js"></script>
  <script>
    // 
    // Defining Module
    //
    var spApp = angular.module( "ngSpApp", ['ngRoute'] );
    //
    // Defining Routes
    //
    spApp.config(function($routeProvider) {
    	$routeProvider.when('/link1', {
    		controller : 'Link1Ctrl',
    		templateUrl : 'views/link1.html'
    	}).otherwise({
    		controller : 'HomeCtrl',
    		templateUrl: 'views/home.html'
        });
    });
    //
    // Controller for Home Page
    //
    spApp.controller( "HomeCtrl", [ '$scope', function($scope) {
      $scope.text = 'Hello, this is homepage';
    }]);
    //
    // Controller for Link1 Page
    //
    spApp.controller( "Link1Ctrl", [ '$scope', function($scope) {
      $scope.text = 'Hello, this is link1 page';
    }]);
  </script>
</body>
</html>
//[C# Code Sample]

Dictionary<string, Symbology> collection = new Dictionary<string, Symbology>();
collection.Add("ONE123", Symbology.Code39Standard);
collection.Add("Process Collection", Symbology.DataMatrix);
collection.Add("Dictionary Collection", Symbology.QR);
collection.Add("X06712AT", Symbology.Code128);
collection.Add("979026000043", Symbology.EAN13);
collection.Add("Aztec BarCode", Symbology.Aztec);

List<Bitmap> images = new List<Bitmap>();

foreach (KeyValuePair<string, Symbology> pair in collection)
using (BarCodeBuilder builder = new BarCodeBuilder())
{
    builder.CodeText = pair.Key;
    builder.SymbologyType = pair.Value;
    images.Add(builder.GenerateBarCodeImage());
}

int maxWidth = int.MinValue;
int sumHeight = 0;
foreach (Bitmap bmp in images)
{
    sumHeight += bmp.Height;
    if (maxWidth < bmp.Width)
        maxWidth = bmp.Width;
}

const int offset = 10;
Bitmap resultBitmap = new Bitmap(maxWidth + offset * 2, sumHeight + offset * images.Count);
using (Graphics g = Graphics.FromImage(resultBitmap))
{
    g.Clear(Color.White);

    int yPosition = offset;
    for (int i = 0; i < images.Count; ++i)
    {
        Bitmap currentBitmap = images[i];
        g.DrawImage(currentBitmap, offset, yPosition);
        yPosition += currentBitmap.Height + offset;
    }
}

resultBitmap.Save("barcode.png", ImageFormat.Png);

//[VB.NET Code Sample]

Dim collection As New Dictionary(Of String, Symbology)()
collection.Add("ONE123", Symbology.Code39Standard)
collection.Add("Process Collection", Symbology.DataMatrix)
collection.Add("Dictionary Collection", Symbology.QR)
collection.Add("X06712AT", Symbology.Code128)
collection.Add("979026000043", Symbology.EAN13)
collection.Add("Aztec BarCode", Symbology.Aztec)

Dim images As New List(Of Bitmap)()

For Each pair As KeyValuePair(Of String, Symbology) In collection
    Using builder As New BarCodeBuilder()
	builder.CodeText = pair.Key
	builder.SymbologyType = pair.Value
	images.Add(builder.GenerateBarCodeImage())
    End Using
Next

Dim maxWidth As Integer = Integer.MinValue
Dim sumHeight As Integer = 0
For Each bmp As Bitmap In images
    sumHeight += bmp.Height
    If maxWidth < bmp.Width Then
	maxWidth = bmp.Width
    End If
Next

Const  offset As Integer = 10
Dim resultBitmap As New Bitmap(maxWidth + offset * 2, sumHeight + offset * images.Count)
Using g As Graphics = Graphics.FromImage(resultBitmap)
    g.Clear(Color.White)

    Dim yPosition As Integer = offset
    For i As Integer = 0 To images.Count - 1
  	Dim currentBitmap As Bitmap = images(i)
	g.DrawImage(currentBitmap, offset, yPosition)
	yPosition += currentBitmap.Height + offset
    Next
End Using

resultBitmap.Save("barcode.png", ImageFormat.Png)

-- Relative time with interval
DATE_SUB(NOW(), INTERVAL 25 HOUR)
 
-- Select all users that were updated in the last 24 hours.
SELECT * FROM users
WHERE users.updated > DATE_SUB(NOW(), INTERVAL 24 HOUR);
 
-- Select all users that were updated in the last 7 days.
SELECT * FROM users
WHERE users.updated > DATE_SUB(NOW(), INTERVAL 7 DAY);
//The sample code below shows how to use the steps above to run OCR on part of an image. 

//[C#]

const string resourceFileName = @"Aspose.OCR.Resources.zip";

try
{
    //Create an instance of OcrEngine and assign 
    //image, language and image settings
    OcrEngine ocrEngine = new OcrEngine();
    ocrEngine.Image = ImageStream.FromFile("Sample.bmp");

    ocrEngine.Languages.AddLanguage(Language.Load("english"));
    ocrEngine.Config.UseDefaultDictionaries = true;

    //Define the block in which to recognize text
    int startX = 0, startY = 0, width = 120, height = 100;

    //Clear recognition blocks
    ocrEngine.Config.ClearRecognitionBlocks();

    //Add 3 rectangle blocks to user defined recognition blocks
    ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(startX, startY, width, height));

    //Set the resource file name and extract OCR text
    using (ocrEngine.Resource = new FileStream(resourceFileName, FileMode.Open))
    {
        try
        {
            if (ocrEngine.Process())
            {
                //Retrieve user defined blocks that determines the paye layout
                var blocks = ocrEngine.Config.RecognitionBlocks;
                //Loop over the list of blocks
                foreach (var block in blocks)
                {
                    //Display if block is set to be recognized
                    Console.WriteLine(block.ToRecognize);
                    //Check if block has recognition data
                    if (block.RecognitionData == null)
                    {
                        Console.WriteLine("Null{0}", Environment.NewLine);
                        continue;
                    }
                    //Display dimension & size of rectangle that defines the recognition block
                    Console.WriteLine("Block: {0}", block.Rectangle);
                    //Display the recognition results
                    Console.WriteLine("Text: {0}{1}", block.RecognitionData.Text, Environment.NewLine);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
    }
    ocrEngine = null;
}
catch (Exception ex)
{
    Console.WriteLine("Exception: " + ex.Message);
} 
 

//[VB.NET]
 
Const resourceFileName As String = "Aspose.OCR.Resources.zip"

Try
	'Create an instance of OcrEngine and assign 
	'image, language and image settings
	Dim ocrEngine As New OcrEngine()
	ocrEngine.Image = ImageStream.FromFile("Sample.bmp")

	ocrEngine.Languages.AddLanguage(Language.Load("english"))
	ocrEngine.Config.UseDefaultDictionaries = True

	'Define the block in which to recognize text
	Dim startX As Integer = 0, startY As Integer = 0, width As Integer = 120, height As Integer = 100

	'Clear recognition blocks
	ocrEngine.Config.ClearRecognitionBlocks()

	'Add 3 rectangle blocks to user defined recognition blocks
	ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(startX, startY, width, height))

	'Set the resource file name and extract OCR text
	ocrEngine.Resource = New FileStream(resourceFileName, FileMode.Open)
	Using ocrEngine.Resource
		Try
			If ocrEngine.Process() Then
				'Retrieve user defined blocks that determines the paye layout
				Dim blocks = ocrEngine.Config.RecognitionBlocks
				'Loop over the list of blocks
				For Each block In blocks
					'Display if block is set to be recognized
					Console.WriteLine(block.ToRecognize)
					'Check if block has recognition data
					If block.RecognitionData Is Nothing Then
						Console.WriteLine("Null{0}", Environment.NewLine)
						Continue For
					End If
					'Display dimension & size of rectangle that defines the recognition block
					Console.WriteLine("Block: {0}", block.Rectangle)
					'Display the recognition results
					Console.WriteLine("Text: {0}{1}", block.RecognitionData.Text, Environment.NewLine)
				Next block
			End If
		Catch ex As Exception
			Console.WriteLine("Exception: " & ex.Message)
		End Try
	End Using
	ocrEngine = Nothing
Catch ex As Exception
	Console.WriteLine("Exception: " & ex.Message)
End Try

static void ExtractInlineAttachments()
  {
        MapiMessage message = MapiMessage.fromFile("Test.msg");
    MapiAttachmentCollection attachments = message.getAttachments();
    for (Object untypedAttachment : attachments)
    {
          MapiAttachment attachment = (MapiAttachment) untypedAttachment;
          if(IsAttachmentInline(attachment))
          {
                try
                {
                      SaveAttachment(attachment, UUID.randomUUID().toString());
                }
                catch (IOException | FileNotFoundException e)
                {
                      // TODO Auto-generated catch block
                          e.printStackTrace();
                    }
              }
        }
  }
  static boolean IsAttachmentInline(MapiAttachment attachment)
  {
        MapiObjectProperty objectData = attachment.getObjectData();
        if (objectData == null)
              return false;

        for (Object prop : attachment.getObjectData().getProperties().getValues())
        {
              MapiProperty property = (MapiProperty)prop;
              if ("\u0003ObjInfo".equals(property.getName()))
              {
                    byte[] data = property.getData();
                    int odtPersist1 = data[1] << 8 | data[0];
                    return (odtPersist1 & 0x40) == 0;
              }
        }
        return false;
  }
  static void SaveAttachment(MapiAttachment attachment, String fileName) throws IOException, FileNotFoundException
  {
        for (Object prop : attachment.getObjectData().getProperties().getValues())
        {
              MapiProperty property = (MapiProperty)prop;
              if ("Package".equals(property.getName()))
          {
                FileOutputStream fs;
                try
                {
                      fs = new FileOutputStream(fileName);
                      fs.write(property.getData(), 0, property.getData().length);
                }
                catch (java.io.IOException e)
                {
                      // TODO Auto-generated catch block
                          e.printStackTrace();
                    }
              }
        }
  }
<style type="text/css">
@media screen and (-webkit-min-device-pixel-ratio:0) {
    H5 { color:red; }
    P { margin-left:20px; }
    /* other special styles for Chrome here */
}
</style>
// source: http://www.apphp.com/index.php?snippet=css-targeting-chrome-only
class WeatherController < ApplicationController
  
  def home
    @report = nil
  end
  
  def find
    @city = params[:q]
   @weather = WeatherModel.get("http://api.worldweatheronline.com/free/v1/weather.ashx?q=#{@city}&format=json&num_of_days=1&key=KEY")
  
  respond_to do |format|
    format.js { render 'find.js.erb'}
  end
   
   
  end
  
  
end
require "sinatra"
require "asposecloudsdk"


get "/" do
  erb :index
end

post "/convert" do
  unless params[:input_file] && (tmpfile = params[:input_file][:tempfile]) && (name = params[:input_file][:filename])
    return "No file selected"
  end

  app_sid = "67xxxxxd-xxx2-7xx3-1xx7-2xxxxxxxxxxd"
  app_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
  Aspose::Cloud::Common::AsposeApp.new(app_sid, app_key)

  request_url = "http://api.aspose.com/v1.1/"
  if /^.+\.(docx|doc|rtf)$/ =~ params[:input_file][:filename]
    request_url += "words/convert"
  elsif /^.+\.(xlsx|xls)$/ =~ params[:input_file][:filename]
    request_url += "cells/convert"
  elsif /^.+\.(pptx|ppt)$/ =~ params[:input_file][:filename]
    request_url += "slides/convert"
  elsif /^.+\.(pdf)$/ =~ params[:input_file][:filename]
    request_url += "pdf/convert"
  else
    return "Error: wrong file selected"
  end
  request_url += "?format=" + params[:format]
  signed_request_url = Aspose::Cloud::Common::Utils.sign(request_url)

  converted_file_stream = RestClient.put(signed_request_url, params[:input_file][:tempfile])
  response.headers["Content-Type"] = "application/octect-stream"
  response.headers["Content-Disposition"] = "attachment; filename=" + params[:input_file][:filename] + "." + params[:format]
  return converted_file_stream

end

//HTML Code Page for selecting file to upload
//views/index.erb

<html>
<head><title>doconv</title></head>
<body>
  <form action="convert" method="post" enctype="multipart/form-data">
    <label>Input file
      <input type="file" name="input_file"/>
    </label>
    <br/>
    <label>Output format
      <select name="format">
        <option value="pdf">PDF</option><option value="tiff">TIFF</option>
        <option value="xps">XPS</option><option value="svg">SVG</option>
        <option value="docx">DOCX</option><option value="doc">DOC</option>
        <option value="xlsx">XLSX</option><option value="xls">XLS</option>
        <option value="text">Text</option>
      </select>
    </label>
    <br/>
    <button type=submit>Upload</button>
  </form>
</body>
</html>

<?php

// Include the SDK files that we need here
require_once(dirname(__FILE__)."/Aspose_Cloud_SDK_For_PHP/src/Aspose/Cloud/Common/AsposeApp.php");
require_once(dirname(__FILE__)."/Aspose_Cloud_SDK_For_PHP/src/Aspose/Cloud/Common/Product.php");
require_once(dirname(__FILE__)."/Aspose_Cloud_SDK_For_PHP/src/Aspose/Cloud/Common/Utils.php");
require_once(dirname(__FILE__)."/Aspose_Cloud_SDK_For_PHP/src/Aspose/Cloud/Exception/AsposeCloudException.php");
require_once(dirname(__FILE__)."/Aspose_Cloud_SDK_For_PHP/src/Aspose/Cloud/Storage/Folder.php");
require_once(dirname(__FILE__)."/Aspose_Cloud_SDK_For_PHP/src/Aspose/Cloud/Pdf/Converter.php");

//The appSID and appKey are used for authentication
Aspose\Cloud\Common\AsposeApp::$appSID = "..."; 
Aspose\Cloud\Common\AsposeApp::$appKey = "..."; 
// The output location is the directory where we hold the converted images
// It should be have writable permissions. There should be a / at the end of this.
Aspose\Cloud\Common\AsposeApp::$outPutLocation = getcwd() . "/Output/";


$input = "Sample.pdf";
$format = "jpeg";
$page = 1;

// We shall use the Folder and Converter component of SDK
$folder = new Aspose\Cloud\Storage\Folder();
$converter = new Aspose\Cloud\Pdf\Converter($input);

try {

  // Upload the $input file to Aspose Cloud Storage
  $folder->UploadFile($input, "");

  // Convert $page into specified $format and save the result in $output file
  $output = $converter->ConvertToImage($page, $format);

  // Tell the web browser that the PHP script is about to send a JPG image
  header("image/jpeg");

  // Send the contents our $output file to the browser
  echo file_get_contents($output);

  // Delete the generated $output file. We don't need it anymore
  unlink($output);

  // Delete the uploaded PDF too. We are all done with it.
  // It is a good practice to keep the uploaded document until all operation
  // are complete and the file is no more needed. Uploading the file
  // again on each request will waste time :-)
  $folder->DeleteFile($input);

} catch (Exception $x) {
  // Ooops! let the user know what happened
  echo $x->getMessage();
}
?>
<script type="text/javascript">
var className = "PluginClass";
// get a reference to the class object itself
// (we've assumed the class is defined in a global scope)
var myclass = window[className];
// now you have a reference to the object, the new keyword will work:
var inst = new myclass();
// now call to the required method of your class
// alert(inst.validate("4111111111111111", "visa"));
</script>
#!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'open-uri'
require 'digest'

EMAIL_LIST = 'http://pastebin.com/raw.php?i=KdDrmNsX'
SAVE_TO = '/home/eelsaid/Desktop/gravatar/'

# read emails from source
emails = open(EMAIL_LIST).read.lines

# iterate over all emails, get the gravatar image
# and save it locally with the email as file name
# but i convert the @ character to a dot .
emails.each do | email |
  gravatar_id = Digest::MD5::hexdigest(email.strip.downcase)
  gravatar_url = "http://secure.gravatar.com/avatar/#{gravatar_id}"
  image_data = open(gravatar_url).read
  file_name = email.strip.downcase.gsub '@', '.'
  File.write "#{SAVE_TO}#{file_name}", image_data
end
#!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)

require 'gtk2' # gem install gtk2

# lets define some constants we need
WORKING_HOURS = 8 # hours
WORKING_SECONDS = WORKING_HOURS * 60 * 60
ALERT = "Your working hours have been ended,\n go out and enjoy your life."

# we'll inherit the Gtk window
# and make our custom behaviour inside it
class WorkEndWindow < Gtk::Window

  # set some window properties
  # and insert a label with the desired text
  # then link the window destroy event with a
  # method to exit the application
  def initialize
    super

    self.title = ':D'
    self.border_width = 20
    self.window_position = Gtk::Window::POS_CENTER_ALWAYS

    add Gtk::Label.new ALERT
    signal_connect("destroy") { Gtk.main_quit }
    show_all
  end
end

# this will wait for you to finish work and 
# then pops up the amazing window that will
# tell you to go home ^_^ 
# it will create a window then start 
# the Gtk main loop
sleep WORKING_SECONDS
WorkEndWindow.new
Gtk.main
#!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
def swap_methods(from_obj, from_method, to_obj, to_method)
  
  from_alias  = "#{from_method}_#{rand 1000}"
  to_alias    = "#{to_method}_#{rand 1000}"

  # alias methods in both objects
  from_obj.class.class_eval do
    alias_method from_alias, from_method
  end

  to_obj.class.class_eval do
    alias_method to_alias, to_method
  end

  # override methods and call aliases in both direction
  from_obj.define_singleton_method(from_method) do |*params, &block|
    to_obj.send(to_alias, *params, &block)
  end

  to_obj.define_singleton_method(to_method) do |*params, &block|
    from_obj.send(from_alias, *params, &block)
  end

end

# calling swap between two methods on two objects
# should swap them, so if you call obj1.method1 
# will execute obj2.method2 and vice versa
obj1 = "this is my first string object"
obj2 = "this is my second string object"
swap_methods obj1, :to_s, obj2, :to_s

# this should print the second string
puts obj1.to_s
#  and this should print the first one
puts obj2.to_s

# swapping String new method with
# other class new method, so whenever
# you create a new String an instance of
# the other class
class X
  attr_accessor :value
  def initialize(value)
    @value = value
  end
end
swap_methods String, :new, X, :new
x_instance = String.new "Heeeey"
puts x_instance.class

# this code will output the following lines:
# 
# this is my second string object
# 
# this is my first string object
# 
# X
# 
# 
# it normally should be :
# 
# this is my frist string object
# 
# this is my second string object
# 
# String