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

Snippets

  • submit to reddit

Recent Snippets

                    Launch Facebook oAuth Box

<?php
    $stoken = Util::getMD5GUID();
    $gWeb->store("fb_state",$stoken);
    $fbAppId = Config::getInstance()->get_value("facebook.app.id");
    $host = "http://".$_SERVER["HTTP_HOST"];
    $fbCallback = $host."/callback/fb2.php" ;
    
    $fbDialogUrl = "https://www.facebook.com/dialog/oauth?client_id=".$fbAppId ;
    $fbDialogUrl .= "&redirect_uri=".urlencode($fbCallback)."&scope=email&state=".$stoken ;
?>

  <a href="<?php echo $fbDialogUrl; ?>"> Login with Facebook</a>

Example of error handler

function login_error_handler($errorno,$errorstr,$file,$line) {

    if(error_reporting() == 0 ) {
        // do nothing for silenced errors
        return true ;
    }
    
    switch($errorno) {

        case E_STRICT :
            return true;
        case E_NOTICE :
        case E_USER_NOTICE :
            Logger->error(" $file :: $line :: $errorstr");
            break ;

        case E_USER_ERROR:
            Logger->trace($file,$line,$errorstr,'TRACE');
            $_SESSION["form.errors"] = array($errorstr);
            header('Location: /user/login.php');
            exit(1);
   

        default:
            Logger->trace($file,$line,$errorstr,'TRACE');
            $_SESSION["form.errors"] = array("Error happened during login");
            header('Location: /user/login.php');
            exit(1);
            
    }
    
    //do not execute PHP error handler
    return true ;
}

Code for error check and user data

 include ($_SERVER['APP_WEB_DIR'].'/callback/error.inc');
    set_error_handler('login_error_handler');
   
    $fbAppId = Config::getInstance()->get_value("facebook.app.id");
    $fbAppSecret = Config::getInstance()->get_value("facebook.app.secret");

    $host = "http://".$_SERVER["HTTP_HOST"];
    $fbCallback = $host. "/callback/fb2.php";
  
    $code = NULL;
    if(array_key_exists('code',$_REQUEST)) {
        $code = $_REQUEST["code"];
    }
 
    $error = NULL ;
    if(array_key_exists('error',$_REQUEST)) {
       $error = $_REQUEST['error'] ;
       $description = $_REQUEST['error_description'] ;
       $message = sprintf(" Facebook returned error :: %s :: %s ",$error,$description);
       trigger_error($message,E_USER_ERROR);

       exit ;
     }


     if(empty($code) && empty($error)) {
        //see how to launch an FB dialog again on Facebook URL given above
     }

    //last state token
    $stoken = $gWeb->find('fb_state',true);
 
    if(!empty($code) && ($_REQUEST['state'] == $stoken)) {
    
    //request to get access token
    $fbTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=".$fbAppId ;
    $fbTokenUrl .= "&redirect_uri=" . urlencode($fbCallback). "&client_secret=" . $fbAppSecret ;
    $fbTokenUrl .= "&code=" . $code;
  
    $response = file_get_contents($fbTokenUrl);
    $params = null;
    parse_str($response, $params);

    $graph_url = "https://graph.facebook.com/me?access_token=".$params['access_token'];
    $user = json_decode(file_get_contents($graph_url));
    processUser($user);

}
   else {
    $message = "http://www.bestfishingrodsreview.com and Facebook state mismatch";
    trigger_error($message,E_USER_ERROR);
  }

Code to process User Info

function processUser($user) {
    
    $id = $user->id;
    $name = $user->name;
    $firstName = $user->first_name ;
    $lastName = $user->last_name ;
    $link = $user->link ;
    $gender = $user->gender ;
    $email = $user->email ;

    if(empty($name) && empty($firstName)) {
        $name = "Anonymous" ;
    }

    $message = sprintf("Login:Facebook :: id %d ,email %s \n",$id,$email); 
    Logger::getInstance()->info($message);

    $facebookDao = new \com\indigloo\sc\dao\Facebook();
    $loginId = $facebookDao->getOrCreate($id,$name,$firstName,$lastName,$link,$gender,$email);


    if(empty($loginId)) {
        trigger_error("Unable to create login",E_USER_ERROR);
    }

    \com\indigloo\sc\auth\Login::startFacebookSession($loginId,$name);
    header("Location: / ");
}
                
                    //[C#]

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Reflection;

using Aspose.Words;

namespace MultipleDocsInMailMerge
{
    class Program
    {
        public static void Main(string[] args)
        {
            //Sample infrastructure.
            string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
            string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;

            ProduceMultipleDocuments(dataDir, "TestFile.doc");
        }

        public static void ProduceMultipleDocuments(string dataDir, string srcDoc)
        {
            // Open the database connection.
            string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataDir + "Customers.mdb";
            OleDbConnection conn = new OleDbConnection(connString);
            conn.Open();
            try
            {
                // Get data from a database.
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers", conn);
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                DataTable data = new DataTable();
                da.Fill(data);

                // Open the template document.
                Document doc = new Document(dataDir + srcDoc);

                int counter = 1;
                // Loop though all records in the data source.
                foreach (DataRow row in data.Rows)
                {
                    // Clone the template instead of loading it from disk (for speed).
                    Document dstDoc = (Document)doc.Clone(true);

                    // Execute mail merge.
                    dstDoc.MailMerge.Execute(row);

                    // Save the document.
                    dstDoc.Save(string.Format(dataDir + "TestFile Out {0}.doc", counter++));
                }
            }
            finally
            {
                // Close the database.
                conn.Close();
            }
        }
    }
}
 
//[VB.NET]
 

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports System.Reflection

Imports Aspose.Words

Namespace MultipleDocsInMailMerge
    Friend Class Program
        Public Shared Sub Main(ByVal args() As String)
            'Sample infrastructure.
            Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
            Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath

            ProduceMultipleDocuments(dataDir, "TestFile.doc")
        End Sub

        Public Shared Sub ProduceMultipleDocuments(ByVal dataDir As String, ByVal srcDoc As String)
            ' Open the database connection.
            Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dataDir & "Customers.mdb"
            Dim conn As New OleDbConnection(connString)
            conn.Open()
            Try
                ' Get data from a database.
                Dim cmd As New OleDbCommand("SELECT * FROM Customers", conn)
                Dim da As New OleDbDataAdapter(cmd)
                Dim data As New DataTable()
                da.Fill(data)

                ' Open the template document.
                Dim doc As New Document(dataDir & srcDoc)

                Dim counter As Integer = 1
                ' Loop though all records in the data source.
                For Each row As DataRow In data.Rows
                    ' Clone the template instead of loading it from disk (for speed).
                    Dim dstDoc As Document = CType(doc.Clone(True), Document)

                    ' Execute mail merge.
                    dstDoc.MailMerge.Execute(row)

                    ' Save the document.
                    dstDoc.Save(String.Format(dataDir & "TestFile Out {0}.doc", counter))
                    counter += 1
                Next row
            Finally
                ' Close the database.
                conn.Close()
            End Try
        End Sub
    End Class
End Namespace
                
                    <!DOCTYPE html>
<html lang="en">
	<head>
		<title>Gallery</title>
		<style>
		
		body {
			width: 830px; 
			
		}
		
			#gallery-wrap {
				/* border: 1px solid #000; */
				width: 777px; 
				height: 450px; 
				border: 3px solid #000; 
				margin: 0 auto; 
			}
			
			#gallery-container {
				width: 600px; 
				height: 450px; 
				overflow:hidden; 
				border-right: 3px solid #000;
				float: left; 
			}
			
			.description {
				position: absolute; 
				width: 600px; 
				height: 70px; 
				top: 465px; 
				opacity: 0.5; 
				background-color: #000; 
				color: #fff;
				font-family: Arial, Helvetica, sans-serif; 
				font-size: 13px; 
				text-align: center; 
			
			}
			#thumbnail-container {
				width: 165px; 
				height: 447px;
				padding-top: 3px; 
				overflow: scroll; 
				float: right; 
			}
			
			#thumbnail-container img {
				cursor: pointer; 
			}
			
			#disclaimer {
				padding-left: 25px; 
				font-family: sans-serif; 
				font-size: 14px;
			}
			
			footer {
				font-family: serif; 
				font-size: 13px;
				margin-left: 28px;  
			}
		</style>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>		
		
		<script>
			$(document).ready(function(){
				$("#thumbnail-container img").click(function(){
					$("#largeImage").attr("src", $(this).attr('src').replace('thumb', 'large')); 
					$(".description p").html($(this).attr('alt')); 
				}); 
				
				
			}); 
		
		</script>
	
	</head>
	<body>
		
	<header>
		<h1 style="text-align: center">A Visit To The National Zoo, D.C.</h1>
	</header>
	
	<div id="gallery-wrap">
		<div id="gallery-container">
			
			<img id="largeImage" src="images/image_01_large.jpg" alt="Thumbnail"/>
			<div class="description"><p>A day at the Smithsonian's National Zoo, Washington, D.C.</p></div>
			<!--<div id=""><img src="images/zooimage2.jpg"/></div>
			<div id=""><img src="images/zooimage3.jpg"/></div>
			<div id=""><img src="images/zooimage4.jpg"/></div>
			<div id=""><img src="images/zooimage5.jpg"/></div>
			<div id=""><img src="images/zooimage6.jpg"/></div>
			<div id=""><img src="images/zooimage7.jpg"/></div>
			<div id=""><img src="images/zooimage8.jpg"/></div>-->
			
		</div><!-- Gallery Container -->
			
		<div id="thumbnail-container">
			<img src="images/image_01_thumb.jpg" alt="A day at the Smithsonian's National Zoo, Washington, D.C." />
			<img src="images/image_02_thumb.jpg" alt="The lions yawns either in boredom or hunger."/>
			<img src="images/image_03_thumb.jpg" alt="In a video captured by our journalist, the female lion here goes ahead to massage the male lion's back, a gesture that appears well received at first 
			but eventually leads up to a brief, but fiesty ruffle."/>
			<img src="images/image_04_thumb.jpg" alt="This tiger prawls in search for his prey, a bouncing ball containing meat and simulating an animal on the run."/>
			<img src="images/image_05_thumb.jpg" alt="This elephant, out from a bath in the pond, is picking up the sand with his trunk and throwing it onto his back."/>
			<img src="images/image_06_thumb.jpg" alt="A panda lays leisurely in his man-made territory."/>
			<img src="images/image_07_thumb.jpg" alt="This special breed of a lizard gazes curiously as a camera clicks in his direction."/>
			<img src="images/image_08_thumb.jpg" alt="A gorrilla, done with his meal of bananas, watches the curious passerbys atop his little jungle."/>
		</div><!-- Thumbnail container -->
		
	</div><!-- Gallery Wrap-->
	
	<div id="disclaimer">
		<p>Note: The pictures are only for demonstration. The captions may or may not actually go along with the event's occurences.
			 </p>
	</div>
	<footer>
			<p>
					© Copyright  by Faithful Okoye
			</p>
	</footer>
	</body>
</html>
                
                    def format_with_separator(number)
  whole_part, decimal_part = number.to_s.split('.')
  [whole_part.gsub(/(\d)(?=\d{3}+$)/, '\1,'), decimal_part].compact.join('.')
end                
                    // [C#]

//Create a copy of original image to avoid any alteration
File.Copy(MyDir + "sample.tif", MyDir + "Testconct.tif", true);


//Create an instance of TiffImage and load the copied destination image
using (TiffImage image = (TiffImage)Aspose.Imaging.Image.Load(MyDir + "Testconct.tif"))
            {
 //Create an instance of TiffImage and load the source image
                using (TiffImage image1 = (TiffImage)Aspose.Imaging.Image.Load(MyDir + "sample1.tif"))
                {
 // Create an instance of TIffFrame and copy active frame of source image
                    TiffFrame frame = TiffFrame.CopyFrame(image1.ActiveFrame);
                    // Add copied frame to destination image
                    image.AddFrame(frame);
                    // save the image with changes.
                    image.Save();

   }
}

//[VB.NET]

'Create a copy of original image to avoid any alteration
File.Copy(MyDir&"sample.tif", MyDir&"Testconct.tif", True)


'Create an instance of TiffImage and load the copied destination image
Using image As TiffImage = CType(Aspose.Imaging.Image.Load(MyDir&"Testconct.tif"), TiffImage)

'Create an instance of TiffImage and load the source image
Using image1 As TiffImage = CType(Aspose.Imaging.Image.Load(MyDir&"sample1.tif"), TiffImage)

' Create an instance of TIffFrame and copy active frame of source image
Dim frame As TiffFrame = TiffFrame.CopyFrame(image1.ActiveFrame)


' Add copied frame to destination image
image.AddFrame(frame)
save the image with changes.
image.Save()
EndUsing

EndUsing
                
                    package com.javatechig.example.ui;
 
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.Menu;
import android.widget.TextView;
 /*
*  @author: nilanchala
*  http://javatechig.com/
*/
public class MainActivity extends Activity {
 
private final String htmlText = "<body><h1>Heading Text</h1><p>This tutorial " +
            "explains how to display " +
            "<strong>HTML </strong>text in android text view. </p>" +
            "<img src="hughjackman.jpg">" +
            "<blockquote>Example from <a href="www.javatechig.com">" +
            "Javatechig.com<a></blockquote></body>";
 
@Override
protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
 
          TextView htmlTextView = (TextView)findViewById(R.id.html_text);
          htmlTextView.setText(Html.fromHtml(htmlText, new ImageGetter(), null));
 
}
 
@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;
}
 
private class ImageGetter implements Html.ImageGetter {
 
public Drawable getDrawable(String source) {
        int id;
        if (source.equals("hughjackman.jpg")) {
               id = R.drawable.hughjackman;
        }
        else {
            return null;
        }
 
       Drawable d = getResources().getDrawable(id);
       d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
       return d;
     }
};
 
}                
                    // Use median smoothing, HLS and gray-scale image processing techniques while recognizing the barcode.

//[C#]

string image = @"code39Extended.jpg";

// create an instance of BarCodeReader and set image and symbology type to recognize
BarCodeReader reader = new BarCodeReader(image, BarCodeReadType.Code39Standard);
// set grayscale image processing
reader.ImageBinarizationHints = RecognitionHints.ImageBinarization.Grayscale;
// try to recognize all possible barcodes in the image
while (reader.Read())
{
    // display the codetext
    Console.WriteLine("Codetext: " + reader.GetCodeText());
}
// close the reader
reader.Close();

//[VB.NET]

Dim image As String = "code39Extended.jpg"

' create an instance of BarCodeReader and set image and symbology type to recognize
Dim reader As BarCodeReader = New BarCodeReader(image, BarCodeReadType.Code39Standard)
' set grayscale image processing
reader.ImageBinarizationHints = RecognitionHints.ImageBinarization.Grayscale
' try to recognize all possible barcodes in the image
Do While reader.Read()
	' display the codetext
	Console.WriteLine("Codetext: " & reader.GetCodeText())
Loop
' close the reader
reader.Close()
                
                    <!-- Grab Google CDN's jQuery and load local version if necessary -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>                
                    <style type="text/css">
/* Center your website horizontally */
.wrapper{
   width:960px;
   display:table;
   margin:auto;
}
 
/* Center certain content vertically */
.container{
   min-height: 10em;
   display: table-cell;
   vertical-align: middle;
}
</style>
 
<div class="wrapper">
    <div class="container">
        <p>Content goes here</p>
    </div>
</div>                
                    This example shows you how to define custom error pages in .htaccess file and also how to display the error page on your site.