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

                    //Programming Sample for reading embedded email attachments from an existing email message

public static void ReadEmbeddedAttachments()
{
    // Base folder to load and save files used in this demo
    private static String strBaseFolder = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";

    try
    {
        System.out.print("Reading message with embedded messages....");

        MailMessage message = MailMessage.load(strBaseFolder + "/embedded.msg", MessageFormat.getMsg());
        ParseMessage(message);

        System.out.println("Success");
    }
    catch (Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}

private static void ParseMessage(MailMessage message)
{
    System.out.println("Subject: " + message.getSubject());
    System.out.println("Extracting attachments....");
    for (int i = 0; i < message.getAttachments().size(); i++)
    {
        Attachment att = (Attachment) message.getAttachments().get(i);
        System.out.println("Attachment Name: " + att.getName());

        // Get the name of attachment. If msg subject contains characters like :, /, \ etc., replace with space
        // because windows cannot save files with these characters
        // also save first 50 characters as file name to avoid long file names
        String attFileName = att.getName().replace(".eml", "").replace(":", " ").replace("\\", " ").replace("/", " ").replace("?", "");
        if (attFileName.length() > 50)
        {
            attFileName = attFileName.substring(0, 50);
        }
        String attExt = (att.getName().substring(att.getName().lastIndexOf("."), att.getName().lastIndexOf(".") + 4));

        // Save the attachment to disk
        att.save(strBaseFolder + attFileName + attExt);

        // Check if it is an orphaned text attachment file (ATT00001.txt....) and of type eml
        if ((attExt.equals(".eml")) || (att.getContentType().getMediaType().equals("text/plain") && att.getName().contains(".txt") == true && att.getName().contains("ATT") == true))
        {
            // Try to load this text file in MailMessage
            MailMessage attMsg = MailMessage.load(strBaseFolder + "/" + attFileName + attExt, MessageFormat.getEml());
            // Call the function recursively to parse this message and attachments
            ParseMessage(attMsg);
        }
    }
}
                
                    //The sample code below creates RE (Reply/Reply All) and FW (Forward) messages from a source message.

//[C# Code Sample]

public static IEWSClient GetEWSClient()
{
    const string mailboxUri = "https://exchange.domain.com/ews/Exchange.asmx";
    const string domain = @"";
    const string username = @"username";
    const string password = @"password";
    NetworkCredential credential = new NetworkCredential(username, password, domain);
    IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credential);
    return client;
}
public static void TestMailReFw()
{
    using (IEWSClient client = GetAsposeEWSClient2())
    {
        try
        {

            MailMessage message = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");

            client.Send(message);
            // Wait for a while

            ExchangeMessageInfoCollection messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri);
            if(messageInfoCol.Count == 1)
                Console.WriteLine("1 message in Inbox");
            else
                Console.WriteLine("Error! No message in Inbox");

            MailMessage message1 = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");

            client.Send(message1);
            // Wait for a while
            messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri);

            if(messageInfoCol.Count == 2)
                Console.WriteLine("2 messages in Inbox");
            else
                Console.WriteLine("Error! No new message in Inbox");


            MailMessage message2 = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");
            message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 1", "Attachment Name 1"));
            message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 2", "Attachment Name 2"));

            client.Reply(message2, messageInfoCol[0]);
            client.ReplyAll(message2, messageInfoCol[0]);
            client.Forward(message2, messageInfoCol[0]);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error in program");
        }
    }
}

//[VB.NET Code Sample]

Public Shared Function GetEWSClient() As IEWSClient
	Const  mailboxUri As String = "https://exchange.domain.com/ews/Exchange.asmx"
	Const  domain As String = ""
	Const  username As String = "username"
	Const  password As String = "password"
	Dim credential As New NetworkCredential(username, password, domain)
	Dim client As IEWSClient = EWSClient.GetEWSClient(mailboxUri, credential)
	Return client
End Function
Public Shared Sub TestMailReFw()
	Using client As IEWSClient = GetAsposeEWSClient2()
		Try

			Dim message As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")

			client.Send(message)
			' Wait for a while

			Dim messageInfoCol As ExchangeMessageInfoCollection = client.ListMessages(client.MailboxInfo.InboxUri)
			If messageInfoCol.Count = 1 Then
				Console.WriteLine("1 message in Inbox")
			Else
				Console.WriteLine("Error! No message in Inbox")
			End If

			Dim message1 As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")

			client.Send(message1)
			' Wait for a while
			messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri)

			If messageInfoCol.Count = 2 Then
				Console.WriteLine("2 messages in Inbox")
			Else
				Console.WriteLine("Error! No new message in Inbox")
			End If


			Dim message2 As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")
			message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 1", "Attachment Name 1"))
			message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 2", "Attachment Name 2"))

			client.Reply(message2, messageInfoCol(0))
			client.ReplyAll(message2, messageInfoCol(0))
			client.Forward(message2, messageInfoCol(0))
		Catch ex As Exception
			Console.WriteLine("Error in program")
		End Try
	End Using
End Sub
                
                    $ git show $COMMIT

# OR

$ git diff HEAD^ HEAD                
                    //Create a Draft Appointment Request
 
String sender = "test@gmail.com";
String recipient = "test@email.com";

MailMessage message = new MailMessage(sender, recipient, "", "");

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@aspose.com", "Attendee"));
WeeklyRecurrencePattern expected = new WeeklyRecurrencePattern(3);

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

//Set the Appointment as Draft
app.setMethod(AppointmentMethodType.Publish);//.Method = AppointmentMethodType.Publish;
message.addAlternateView(app.requestApointment());
MapiMessage msg = MapiMessage.fromMailMessage(message);

// Save the appointment as draft.
msg.save("Draft.msg");

//Draft Appointment Creation from Text
 
String ical = "BEGIN:VCALENDAR\r\nMETHOD:PUBLISH\r\nPRODID:-//Aspose Ltd//iCalender Builder (v3.0)//EN\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nATTENDEE;CN=test@gmail.com:mailto:test@gmail.com\r\nDTSTART:20130220T171439\r\nDTEND:20130220T174439\r\nDTSTAMP:20130220T161439Z\r\nEND:VEVENT\r\nEND:VCALENDAR";

String sender = "test@gmail.com";
String recipient = "test@email.com";

MailMessage message = new MailMessage(sender, recipient, "", "");

AlternateView av = AlternateView.createAlternateViewFromString(ical, new ContentType("text/calendar"));

message.getAlternateViews().add(av);

MapiMessage msg = MapiMessage.fromMailMessage(message);

// Save the appointment as draft.
msg.save("DraftAppointment.msg");

                
                    //Example-1
public class SwitcherDemo
{
	public static void main(String args[])
	{
		Switcher generic = new Switcher()
				.addCase(1, "Integer")
				.addCase(1.1, "Double")
				.addCase(1.1f,"Float")
				.addCase("S","String")
				.setDefault("Others");
		System.out.println("Switch type "+generic.exec(1.1f));
		System.out.println("Switch type "+generic.exec("S"));
		System.out.println("Switch type "+generic.exec(1));
		System.out.println("Switch type "+generic.exec(1.1));
		System.out.println("Switch type "+generic.exec("SS"));
	}
}

//Example-2
import ch.lambdaj.function.closure.Switcher;

import java.util.Arrays;
import java.util.List;

public class SwitcherDemo {



	public static void main(String args[])
	{
		Employee fulltime = new Employee(JOB_TYPE.FULL_TIME);
		Employee partime = new Employee(JOB_TYPE.PART_TIME);
		Employee contract = new Employee(JOB_TYPE.CONTRACT);
		Employee intern = new Employee(JOB_TYPE.INTERN);
		List<Employee>  employeeList = Arrays.asList(fulltime,partime,contract,intern);

		Switcher<Salary> salarySwitcher = new Switcher<Salary>();
		salarySwitcher.addCase(JOB_TYPE.FULL_TIME, new Salary(100000));
		salarySwitcher.addCase(JOB_TYPE.PART_TIME, new Salary(50000));
		salarySwitcher.addCase(JOB_TYPE.CONTRACT, new Salary(120000));
		salarySwitcher.addCase(JOB_TYPE.INTERN, new Salary(45000));
		salarySwitcher.setDefault(new Salary(0));

		for(Employee e: employeeList)
		{
                     Salary sal = salarySwitcher.exec(e.getJobtype());
			e.setSalary(sal);
			System.out.println("Salary "+e.getSalary().getSalary()+" Offered Job type "+e.getJobtype());
		}

	}
}
enum JOB_TYPE
{
	FULL_TIME,CONTRACT,INTERN,PART_TIME
}

class Employee
{

	private final JOB_TYPE jobtype;
	private Salary salary;

	Employee(JOB_TYPE job_type)
	{
		this.jobtype=job_type;
	}
	public JOB_TYPE getJobtype()
	{
		return jobtype;
	}

	Salary getSalary()
	{
		return salary;
	}

	void setSalary(Salary salary)
	{
		this.salary = salary;
	}
}
class Salary
{
	private final double sal;

	public Salary(double sal)
	{
		this.sal=sal;
	}
	public double getSalary()
	{
		return sal;
	}
}                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)

# monkey batch, yup that a bad practice,
# but lets say that this is a proof of concept
# 
# we'll open the object class and handle the 
# method missing situation, we'll claculate
# distance between the requested method and 
# all methods available in object, then the nearest
# method if distance doesn't exceed certain number
# then execute it.
class Object
  def method_missing(meth, *args, &block)
    threshold = 3
    all_meth = methods.sort
    all_meth.sort_by! do |m| 
      string_distance m, meth
    end
    if string_distance(all_meth.first, meth) <= 3
      send all_meth.first, *args, &block
    else
      super
    end
  end

  # we'll calculate distance between 2 string by
  # getting number of characters in 1 and not in 2
  # and number chars in 2 not in 1, sum the two
  # differences and return that weight
  # less weight is more similar method
  def string_distance(str1, str2)
    one_way = str1.to_s.chars - str2.to_s.chars 
    the_other_way = str2.to_s.chars - str1.to_s.chars 
    one_way.size + the_other_way.size
  end
end

# ## UseCase ?
# you can use `nil` instead of `nil?`
p "26512135".nil
# you can use `toi` and `tof` instead of `to_i` and `to_f`
p "12123".tof

# this way ruby will be more forgiving if you wrote
# method name with wrong character or less character or more 
# with 1 character, when you increate the `threshold` it'll
# be more forgiving :D, 
# 
# happy coding.                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)

# it turns out that BBC website has a printable version of
# the top 40 UK singles chart, that made me jump of joy :D
require 'open-uri'

# get BBC singles chart printable version
page = open('http://www.bbc.co.uk/radio1/chart/singles/print').read
# result has data as table so we'll extract keys from TH tags
keys = page.scan(/<th>(.+)<\/th>/).map{ |k| k.first.downcase }
# extract cells from TD tags
cells = page.scan(/<td>(.*)<\/td>/).map{ |c| c.first }
# split cells to arrays each equal to keys
rows = cells.each_slice keys.size

# container to join data as Hash objects and push to it
data = []
# now iterate on each row and join keys with their
# respective values then convert them to arrays
rows.each do |row|
  data << Hash[ [keys, row].transpose ] # this is a good trick ;)
end

# show us what you got sir.
puts data
                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# 
# Output example : 
# http://imgur.com/Z1LfLn1
# 
# install ruby-graphviz then install graphviz from 
# http://graphviz.org/
require 'graphviz' # gem install ruby-graphviz --no-document

# get all constants in namespace
# then convert them from symbols
# to their objects and select 
# the classes out of them, 
# you may include modules if you wish
classes = Class.constants
                      .map { |c| Class.const_get c }
                      .select { |c| c.is_a? Class }
g = GraphViz.new( :G, :type => :digraph )

# Create nodes
nodes = Hash[classes.map {|c| [c, g.add_nodes( c.to_s )] }]
nodes.each do |klass,node|
  begin
    g.add_edges node, nodes[klass.superclass]
  rescue # do nothing
  end
end

# Generate output image
g.output( :png => "/Users/blaze/Desktop/classes_graph.png" )
# you can output PDF with small modification
g.output( :pdf => "/Users/blaze/Desktop/classes_graph.pdf" )                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# **Usage** : 
# 
# * `ruby evalin_comodor.rb <accesstoken>`
# this will get a long term access token from the short term one
# * `ruby evalin_comodor.rb`
# will start the script
require './evalin.rb' # https://github.com/blazeeboy/RubyScripts/blob/master/2014-3-30/evalin.rb
require 'koala' # gem install koala

# create a facebook app and get access token from here
# https://developers.facebook.com/tools/explorer
# scopes required : 
# public_profile, basic_info, publish_checkins, status_update, photo_upload, video_upload, create_note, share_item, publish_stream, manage_notifications, publish_actions, user_friends

APP_ID      = 'xxxxxxxxxxxxxxxx'
APP_SECRET  = 'xxxxxxxxxxxxxxxx'
NOTIFICATIONS_LIMIT = 100

if ARGV.size > 0
  oauth = Koala::Facebook::OAuth.new(APP_ID, APP_SECRET)
    new_access_info = oauth.exchange_access_token_info ARGV.first
    File.write 'token', new_access_info['access_token']
  puts 'New Access Token written'
  exit
end

# respond to comment with mention
def respond_to(graph, comment_id, post_id)

  comment = graph.get_object(comment_id)

  username = comment['from']['name']
  message = comment['message']
  puts "responding to : #{message}"

  # read comment parts languages and code
  groups = message.scan /#{$name}\s+([a-zA-Z+]+)(.+)/m
  return if groups.length != 1

  language = groups.first[0]
  code = groups.first[1].strip
  return unless output = evalin(code, language)

  # posting comment reply
  graph.put_object post_id, 'comments', {message: "#{username} \n#{output}"}

end

loop do
  begin
    # yes each time will read token
    # in case you started it then added access token
    # or refreshed it you won't need to restart it
    oauth_access_token = File.read('token')
    $graph = Koala::Facebook::API.new(oauth_access_token)

    # get your name
    $name = $graph.get_object('me')['name']

    # get notifications
    notifications = []
    page = $graph.get_connections('me','notifications')
    begin
      notifications += page
    end while page = page.next_page and notifications.length<=NOTIFICATIONS_LIMIT

    # 
    # Now lets head to parse and respond to them
    # 
    notifications.reverse_each do |n|
      begin
        if n['application'] and n['application']['name'] == 'Groups' and n['title'].include? 'mentioned you'

          ids = n['link'].scan /comment_id=([0-9]+)&/
          post_ids = n['link'].scan /permalink\/([0-9]+)\//
          if ids.size == 1 and post_ids.size == 1
            respond_to $graph, ids.first.first, post_ids.first.first 
          end

        end
      rescue 
        # ignore it
      end

      # mark notification as read
      $graph.put_object(n['id'],'', {unread: false})
    end
    puts "Notifications found : #{notifications.size}"

  # please rescue if something went wrong
  # thanks,
  rescue Exception => e
    puts "Error : #{e}"
  end

  # wait for 60 seconds and try again
  sleep 60
end                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# 
# this script is a small practice in implementing 
# simple sorting algorithms in ruby, i converted
# the sorting algorithms from wikipedia pages

class Array
  # Insertion sort is a simple sorting algorithm that builds 
  # the final sorted array (or list) one item at a time. 
  # It is much less efficient on large lists than more advanced 
  # algorithms such as quicksort, heapsort, or merge sort.
  # **wikipedia**
  def insertion_sort!

    (1...size).each do |i|
      j = i
      while j > 0 and self[j-1] > self[j]
          self[j], self[j-1] = self[j-1], self[j]
          j = j - 1
      end
    end

  end

  # selection sort is a sorting algorithm, specifically an in-place 
  # comparison sort. It has O(n2) time complexity, making it 
  # inefficient on large lists, and generally performs worse 
  # than the similar insertion sort. Selection sort is noted for 
  # its simplicity, and it has performance advantages over more 
  # complicated algorithms in certain situations, 
  # particularly where auxiliary memory is limited.
  # **wikipedia**
  def selection_sort!
     
    (0...size).each do |j|
      # find index of minimum element in the unsorted part 
      iMin = j
      (j+1...size).each do |i|
        iMin = i if self[i] < self[iMin]
      end
      
      # then swap it
      self[j], self[iMin] = self[iMin], self[j]
    end
  end

end

# lets try our algorithms
x = (1..10).to_a.shuffle
p 'before sort : ', x
x.insertion_sort!
p 'after sort : ', x

x.shuffle!
p 'before sort : ', x
x.selection_sort!
p 'after sort : ', x