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

                    //Sample Code for Adding and Retrieving Attachments from Calendar Items

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2012, Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2012, Calendar.DECEMBER, 1);
Date endDate = calendar.getTime();

MailAddressCollection attendees = new MailAddressCollection();
attendees.add(new MailAddress("attendee_address@domain.com", "Attendee"));
WeeklyRecurrencePattern expected = new WeeklyRecurrencePattern(3);

Appointment app = new Appointment("Appointment Location", "Appointment Summary", "Appointment Description",
									startDate, endDate,
									new MailAddress("organizer_address@domain.com", "Organizer"), attendees, expected);

//Attach a file from disc to this appointment
File file = new File("OutputXLS.xls");
FileInputStream fis = new FileInputStream(file);

Attachment att = new Attachment(fis, file.getName());
app.getAttachments().add(att);
fis.close();
String savedFile = "appWithAttachments.ics";
app.save(savedFile, AppointmentSaveFormat.Ics);

Appointment app2 = Appointment.load(savedFile);
System.out.println("Total Attachments: "  + app2.getAttachments().size());
for (int i=0; i< app2.getAttachments().size();i++)
{
	att = app2.getAttachments().get(i);
	System.out.println(att.getName());

        //Save the attachment to disc
        att.save(att.getName());
}
 
                
                    private void btnRun_Click(object sender, EventArgs e)
        {
            //create PPT document
            Presentation presentation = new Presentation();

            //load PPT file from disk
            presentation.LoadFromFile(@"..\..\..\..\..\..\Data\sample2.pptx");

            //save PPT document to images
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                String fileName = String.Format("result-img-{0}.png", i);
                Image image = presentation.Slides[i].SaveAsImage();
                image.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
                System.Diagnostics.Process.Start(fileName);
            }

        }                
                    import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
public class FindItemFromMap
{
public static void main(String args[])
{
Map<String,List<String>> map = new HashMap<>();
		List<String> fruits = Arrays.asList("apple","orange","banana");
		List<String> juice=   Arrays.asList("pepsi","fanta","sprite");
		map.put("fruits",fruits);
		map.put("juice", juice);
		String result = Iterables.find(Iterables.concat(map.values()), new Predicate<String>()
		{
		@Override
		public boolean apply(@Nullable String input) {
			return "banana".equals(input);
		}
	}) ;
	System.out.println("Found "+result);
}
}                
                    function prime($n){
 
      //all numbers that will be evaluated as prime       
     for($i=1;$i<=$n;$i++){     
               $counter = 0; 
              //all probability of divisible factors
              for($j=1;$j<=$i;$j++){                   
                    //$i is divisible by $j, increament the counter
                     if($i % $j==0){                       
                          $counter++;
                    }
              }          
           /*how many greens? they have to be 2 
            ( each prime number has exactly 2 (two) divisors)*/
             if($counter==2){
                 print $i." is Prime <br/>";
             }
      }
} 


prime(20);  //find the Prime for 1-20 range                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'linkedin' # gem install linkedin
require 'json'

# create an appliation then
# get your api keys at https://www.linkedin.com/secure/developer
config = {
	your_consumer_key: 		'xxxxxxxxxxxxxxxx',
	your_consumer_secret: 	'xxxxxxxxxxxxxxxx',
	oauth_user_token: 		'xxxxxxxxxxxxxxxx',
	oauth_user_secret: 		'xxxxxxxxxxxxxxxx'
}
client = LinkedIn::Client.new(
						config[:your_consumer_key], 
						config[:your_consumer_secret] 
					)

client.authorize_from_access(
		config[:oauth_user_token],
		config[:oauth_user_secret]
	)

client.add_share(
	comment: 'Good Morning', 
	content: {'submitted-url' => 'http://www.github.com/blazeeboy' }
)                
                    //The programming sample below shows how to DXF Drawings to PDF file using default settings.

 [C# Code Sample]

using Aspose.Imaging.FileFormats.Cad;
using Aspose.Imaging.ImageOptions;

namespace DxfExamples
{
    /// <summary>
    /// Represents test examples for DXF -> PDF export
    /// </summary>
    public class DxfExamples
    {
        /// <summary>
        /// Default export.
        /// </summary>
        public void DefaultExport()
        {
            // Name of the file
            string filename = "Drawing1.dxf";

            // Load an image
            using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(filename))
            {
                // Create options
                PdfOptions pdfOptions = new PdfOptions();

                // Set output file size
                pdfOptions.PageWidth = 800;
                pdfOptions.PageHeight = 600;

                // Export
                image.Save(filename + ".pdf", pdfOptions);
            }
        }
    }
}

//[VB.NET Code Sample]

Imports Aspose.Imaging.FileFormats.Cad
Imports Aspose.Imaging.ImageOptions

Namespace DxfExamples
        ''' <summary>
        ''' Represents test examples for DXF -> PDF export
        ''' </summary>
        Public Class DxfExamples
            ''' <summary>
            ''' Default export.
            ''' </summary>
            Public Sub DefaultExport()
                ' Name of the file
                Dim filename As String = "Drawing1.dxf"

                ' Load an image
                Using image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load(filename)
                    ' Create options
                    Dim pdfOptions As New PdfOptions()

                    ' Set output file size
                    pdfOptions.PageWidth = 800
                    pdfOptions.PageHeight = 600

                    ' Export
                    image.Save(filename & Convert.ToString(".pdf"), pdfOptions)
                End Using
            End Sub
        End Class
    End Namespace

//Setting the Image Size

//[C# Code Sample]

//The code sample below shows the auto-scaling option in use.
using Aspose.Imaging.FileFormats.Cad;
using Aspose.Imaging.ImageOptions;

namespace DxfExamples
{
    /// <summary>
    /// Represents test examples for DXF -> PDF export
    /// </summary>
    public class DxfExamples
    {
/// <summary>
        /// Export with automatical up-scaling.
        /// </summary>
        public void ExportAutoUpScale()
        {
            // Name of the file
            string filename = "Drawing2.dxf";

            // Load an image
            using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(filename))
            {
                // Create options
                PdfOptions pdfOptions = new PdfOptions();

                // Set output file size
                pdfOptions.PageWidth = 850;
                pdfOptions.PageHeight = 600;

                // Allow upscaling
                pdfOptions.ScaleMethod = ScaleType.GrowToFit;

                // Export
                image.Save(filename + "_UpScale.pdf", pdfOptions);
            }
        }
    }
}

//[VB.NET Code Sample]

Imports Aspose.Imaging.FileFormats.Cad
Imports Aspose.Imaging.ImageOptions

Namespace DxfExamples
	''' <summary>
	''' Represents test examples for DXF -> PDF export
	''' </summary>
	Public Class DxfExamples
		''' <summary>
		''' Export with automatical up-scaling.
		''' </summary>
		Public Sub ExportAutoUpScale()
			' Name of the file
			Dim filename As String = "Drawing2.dxf"

			' Load an image
			Using image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load(filename)
				' Create options
				Dim pdfOptions As New PdfOptions()

				' Set output file size
				pdfOptions.PageWidth = 850
				pdfOptions.PageHeight = 600

				' Allow upscaling
				pdfOptions.ScaleMethod = ScaleType.GrowToFit

				' Export
				image.Save(filename & Convert.ToString("_UpScale.pdf"), pdfOptions)
			End Using
		End Sub
	End Class
End Namespace

                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'koala' # gem install koala --no-document
# create a facebook app and get access token from here
# https://developers.facebook.com/tools/explorer
# select "user_status", "friends_status", "user_checkins" when authenticating
oauth_access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
graph = Koala::Facebook::API.new(oauth_access_token)

places = []
page = graph.get_connections('me', 'checkins')
begin
	places += page.map {|p| p['place']}
end while page = page.next_page

places.each do |place|
	unless place['location'].is_a? String
		puts "#{place['name']} lat:#{place['location']['latitude']} long:#{place['location']['longitude']}"
	else
		puts "#{place['name']} location:#{place['location']}"
	end
end                
                    Steps to do the Contextual Logging

Configuring one time which is very efficient.

log4j.properties -- text highlighted in green specifies contextual information

1) log4j.appender.stdout.layout.ConversionPattern=%-5p %-23d{MM-dd-yyyy HH:mm:ss:S} [%t] %X{clientRequestIP} %X{timestamp} %X{session} %X{loggedinuserid} %X{loggedinusername} %X{httpmethod}  %X{requesturl} %c:%L %m%n


2) Code Snippet
Put this code in Filter class. This will be invoked once per request and attach unique timestamp which will be prepended for each controller, service, dao, adapter methods

		import org.apache.log4j.MDC;
	    	. . . . . .
		. . . . . .
		final long timestamp = (new Date()).getTime();
		MDC.put("timestamp", timestamp);
		MDC.put("httpmethod", httpmethod);
		MDC.put("session", sessionid);
		MDC.put("requesturl", requestUrl);
		MDC.put("loggedinusername", username);                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
FILENAME = 'db.txt'
OPEN, CLOSE = 1 , 0

file = File.open(FILENAME, 'a')
file.write "#{OPEN} : #{Time.new}\n"
file.flush

begin
	loop { sleep 60 } # sleep for an hour in an endless loop

rescue SystemExit, Interrupt # on exit
	file.write "#{CLOSE} : #{Time.new}\n"
	file.close
end                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'json'
require 'open-uri'
require 'uri'
require 'net/http'

CODE_LIMIT = 10
$url = "https://eval.in/"
$languages = {
	'c' => 'c/gcc-4.7.2',					'c++' => 'c++/gcc-4.7.2',
	'fortran' => 'fortran/f95-4.4.3',		'haskell' => 'haskell/hugs98-sep-2006',
	'io' => 'io/io-20110912',				'javascript' => 'javascript/node-0.10.26',
	'lua' => 'lua/lua-5.2.1',				'ocaml' => 'ocaml/ocaml-4.00.1',
	'php' => 'php/php-5.5.1',				'perl' => 'perl/perl-5.16.1',
	'python' => 'python/cpython-3.2.3',		'ruby' => 'ruby/mri-2.1.0',
	'slash' => 'slash/slash-head',			'assembly' => 'assembly/nasm-2.07'
}

def evalin code, language

	return nil unless $languages.keys.include? language
	return nil if code.length < CODE_LIMIT

	params = {
		code: code,			lang: $languages[language],
		execute: 'on',		input: ''
	}

	postData = Net::HTTP.post_form(URI.parse($url), params)
	location = postData['location']
	if location
		evalin_data = JSON.parse open("#{location.gsub 'http://', 'https://'}.json").read
		return "#{evalin_data['output']}\n#{evalin_data['status']}\n#{location}"
	end
	return nil
end

puts evalin('10.times{ puts "done."}', 'ruby')