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

                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'pygmentize' # gem install pygmentize
require 'redcarpet' # gem install redcarpet

# consecutive lines of code
# should be highlighted using pygmentize
# and converter to markdown block simply
# using the markdown syntax for code
# used by github flavored markdown
class CodeBlock < Array

  def to_html
    Pygmentize.process join, :ruby
  end

  def to_md
    "```ruby\n#{join}\n```"
  end
  alias_method :to_markdown, :to_md
end

# set of consecutive lines of comments
class CommentBlock < Array

  # will use this Redcarpet renderer to convert 
  # markdown to html
  @@renderer = Redcarpet::Markdown.new(Redcarpet::Render::HTML, 
                            fenced_code_blocks: true,
                            disable_indented_code_blocks: true,
                            strikethrough: true,
                            superscript: true,
                            underline: true,
                            autolink: true )

  # use the renderer on the content
  def to_html
    @@renderer.render join("\n")
  end

  # convert the block to markdown format
  # and also give it a full name alias
  def to_md
    join("\n")
  end
  alias_method :to_markdown, :to_md

end 

# container class will have multiple blocks of 
# comments and code
class CodeConverter < Array

  # you should pass code when
  # initializing new instance
  # in order to parse it
  def initialize( code )
    parse code
  end

  # add new line of code to the class
  # it start new code block if the last block is
  # not code block then adds the line of code
  # to the last block
  def add_code( line )
    self << CodeBlock.new unless last.is_a? CodeBlock
    last << line
  end

  # add new comment line to the class
  # it adds new comment block if the last block is not 
  # comments block then add the comment line to the block
  def add_comment( line )
    self << CommentBlock.new unless last.is_a? CommentBlock
    last << line
  end

  # parse code and put result to this class
  # first insert a comment block then
  # parse each line and add it according 
  # to the line type
  def parse(code)
    replace [CommentBlock.new]

    code.lines.each do |line|
      case
        when line.strip.start_with?('# ')
          add_comment line.strip[2..-1]

        when line.strip.start_with?('#!')
          add_code line

        when line.strip.start_with?('#')
          add_comment line.strip[1..-1]

        else
          add_code line
      end
    end

  end

  # convert each block to html
  # and wrap it in a styled page
  # if a file path passed it'll write output to it
  # in all cases it'll return the output
  def to_html(file = nil)
    code = map.with_index do |block, i| 
          # each cell in resulted table 
          # will have a class same as the 
          # class name of teh block downcased
          klass = block.class.to_s.downcase
          # start table row or end it
          # according to the current block index
          prefix = i.even? ? '<tr>' : ''
          suffix = i.odd? ? '</tr>' : ''
          # produced block html
          "#{prefix}<td class=\"section #{klass}\">#{block.to_html}</td>#{suffix}" 
        end

    # add a closing cell if the code 
    # ends with comments lines
    code << "<td></td></tr>" if last.is_a? CommentBlock

    # here is the full page with embeded style
    # i had to add the css here to make sure script stay as 
    # one file not multiple dependent files.
    html = <<-EOT
<html>
<head>
<style>
body { background: #29281e; padding:0px; margin:0px; font-family: verdana, tahoma; font-size: 13px; }
.content{ border-collapse: collapse; }
.section{ padding: 5px; border-top: 1px solid #333; } 
.commentblock{ width: 40%;text-align: right; vertical-align: top; font-size: 13px; color: #ddd; text-shadow: 1px 1px 0px black; }
.codeblock{ width: 60%; background: #29281e; border-left: 1px solid #333; padding-left: 10px; }
.commentblock a{ color: #fff; }
.codeblock pre{ white-space: pre-wrap; margin: 0px; }
.highlight { padding: 0px; font-size: 13px; }
div.highlight, div.highlight code, div.highlight pre  { padding: 0px; }div.highlight code { padding: 0; }div.highlight .c { color: #75715e }div.highlight .err { color: #960050; background-color: #1e0010 }div.highlight .k { color: #66d9ef }div.highlight .l { color: #ae81ff }div.highlight .n { color: #f8f8f2 }div.highlight .o { color: #f92672 }div.highlight .p { color: #f8f8f2 }div.highlight .cm { color: #75715e }div.highlight .cp { color: #75715e }div.highlight .c1 { color: #75715e }div.highlight .cs { color: #75715e }div.highlight .ge { font-style: italic }div.highlight .gs { font-weight: bold }div.highlight .kc { color: #66d9ef }div.highlight .kd { color: #66d9ef }div.highlight .kn { color: #f92672 }div.highlight .kp { color: #66d9ef }div.highlight .kr { color: #66d9ef }div.highlight .kt { color: #66d9ef }div.highlight .ld { color: #e6db74 }div.highlight .m { color: #ae81ff }div.highlight .s { color: #e6db74 }div.highlight .na { color: #a6e22e }div.highlight .nb { color: #f8f8f2 }div.highlight .nc { color: #a6e22e }div.highlight .no { color: #66d9ef }div.highlight .nd { color: #a6e22e }div.highlight .ni { color: #f8f8f2 }div.highlight .ne { color: #a6e22e }div.highlight .nf { color: #a6e22e }div.highlight .nl { color: #f8f8f2 }div.highlight .nn { color: #f8f8f2 }div.highlight .nx { color: #a6e22e }div.highlight .py { color: #f8f8f2 }div.highlight .nt { color: #f92672 }div.highlight .nv { color: #f8f8f2 }div.highlight .ow { color: #f92672 }div.highlight .w { color: #f8f8f2 }div.highlight .mf { color: #ae81ff }div.highlight .mh { color: #ae81ff }div.highlight .mi { color: #ae81ff }div.highlight .mo { color: #ae81ff }div.highlight .sb { color: #e6db74 }div.highlight .sc { color: #e6db74 }div.highlight .sd { color: #e6db74 }div.highlight .s2 { color: #e6db74 }div.highlight .se { color: #ae81ff }div.highlight .sh { color: #e6db74 }div.highlight .si { color: #e6db74 }div.highlight .sx { color: #e6db74 }div.highlight .sr { color: #e6db74 }div.highlight .s1 { color: #e6db74 }div.highlight .ss { color: #e6db74 }div.highlight .bp { color: #f8f8f2 }div.highlight .vc { color: #f8f8f2 }div.highlight .vg { color: #f8f8f2 }div.highlight .vi { color: #f8f8f2 }div.highlight .il { color: #ae81ff }
</style>
</head>
<body>
<table class="content">#{code.join}</table>
</body>
</html>
EOT
  
    # write output to file if a path is passed
    # and return html
    File.write file, html unless file.nil?
    html
  end

  # Convert the analyzed code into Markdown
  # this is easier than HTML as you'll need
  # to convert each block to markdown and
  # join them with new line
  # write output to file if a path is passed
  def to_md(file=nil)
    
    md = map {|b| b.to_md }.join "\n"
    
    File.write file, md unless file.nil?
    md
  end
  alias_method :to_markdown, :to_md

end

# ## How to use ?
# create new Code Converter class with code
blocks = CodeConverter.new( File.read('/path/to/code/file.rb') )
# and convert to html and markdown and save it to this file path
blocks.to_html '/path/to/html/code.html'
blocks.to_md '/path/to/md/markdown.md'                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'cairo' # gem install cairo

IMAGE_PATH = '/path/to/image/file.png'

# open image as Cairo surface
image = Cairo::ImageSurface.from_png(IMAGE_PATH)
# this is out target surface we will paint on it
# and save it at the end, we created it a perfect Square
target = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, image.width, image_width)
# context is what enable us to paint
# a wrapper of any surface and used to
# define what we'll paint and where (the source and mask)
cr = Cairo::Context.new(target)

# to crop `image` we'll
# put it as source, then
# draw a mask on the target
# then fill the space with this image
cr.set_source image
cr.rectangle 0, 0, image.width, image_width
cr.fill

# draw a white semi-transparent
# rectangle on it that we will
# write the post title on it.
cr.set_source_rgba 1, 1, 1, 0.8 # white with 80% alpha
cr.rectangle 0, image_width - 80, image.width, 80
cr.fill

# write title using Futura font in 30 pixels
cr.set_source_rgb 207.0/255, 35.0/255, 64.0/255
cr.select_font_face "Futura", 
                    Cairo::FONT_SLANT_NORMAL, 
                    Cairo::FONT_WEIGHT_BOLD
cr.move_to 25, image_width - 40
cr.set_font_size 30
cr.show_text title
cr.fill

# write a small text under the title to tell
# user that we cropped the original image
cr.set_source_rgb 131.0/255, 17.0/255, 45.0/255
cr.select_font_face "Verdana", 
                    Cairo::FONT_SLANT_NORMAL, 
                    Cairo::FONT_SLANT_NORMAL
cr.move_to 25, image_width - 15
cr.set_font_size 14
cr.show_text "As this script is too long, check the rest of it from the link in description"
cr.fill

# then save the target surface to disk :)
cr.target.write_to_png IMAGE_PATH                
                    //Please take a look over the following code snippet for Protecting Excel Workbooks

//[C#]
 
//build URI
string strURI = "http://api.aspose.com/v1.1/cells/input.xls/protection"

string signedURI = Sign(strURI);

//serialize the JSON request content
Protection protection = new Protection();
protection.ProtectionType = protectionType;
protection.Password = password;

string strJSON = JsonConvert.SerializeObject(protection);

Stream responseStream = ProcessCommand(signedURI, "POST", strJSON);

StreamReader reader = new StreamReader(responseStream);
string strResponse = reader.ReadToEnd();

//Parse the json string to JObject
JObject pJSON = JObject.Parse(strResponse);

//Here is the Protection Class used above
public class Protection
{
    public Protection()
    {

    }

    public ProtectionType ProtectionType { get; set;}
    public string Password { get; set;}

}

/// <summary>
/// Represents Protection Types
/// </summary>
public enum ProtectionType
{
    All,
    Structure,
    Windows,
    None
}

//[Java Code]
 
AsposeApp.setAppSID("77******-1***-4***-a***-8***********");
AsposeApp.setAppKey("89******************************");

//build URI to Protect Workbook
string strURI = "http://api.aspose.com/v1.1/cells/input.xls/protection";

//sign URI
string signedURI = Sign(strURI);

//serialize the JSON request content
Protection protection = new Protection();
protection.setProtectionType(ProtectionType.All);
protection.setPassword("password");

String strJSON = "";

Gson gson = new Gson();

strJSON = gson.toJson(encryption, Encryption.class);

InputStream responseStream = ProcessCommand(signedURI, "POST", strJSON);

String strResponse = StreamToString(responseStream);

//Following is the Protection Class used above
public class Protection
    {
        public Protection()
        {

        }

        private ProtectionType ProtectionType;
        private String Password;

        public ProtectionType getProtectionType(){return ProtectionType;}
        public String getPassword(){return Password;}

        public void setProtectionType(ProtectionType ProtectionType){ this.ProtectionType=ProtectionType;}
        public void setPassword(String Password ){ this.Password=Password;}


    }

    /// <summary>
    /// Represents Protection Types
    /// </summary>
    public enum ProtectionType
    {
        All,
        Structure,
        Windows,
        None
    }

//[PHP Code]
 
AsposeApp::$appSID = "77******-1***-4***-a***-80**********";
AsposeApp::$appKey = "********************************";

AsposeApp::$outPutLocation = getcwd() . "/Output/";

//build URI to protect workbook
$strURI = 'http://api.aspose.com/v1.1/cells/Sample.xlsx/protection';

//Build JSON to post
$fieldsArray["ProtectionType"] = "all";
$fieldsArray["Password"] = "abc";
$json = json_encode($fieldsArray);

$signedURI = Utils::sign($strURI);

$responseStream = Utils::processCommand($signedURI, "POST", "json", $json);

//Download output file
$strURI = "http://api.aspose.com/v1.1/storage/file/Sample.xlsx";
$signedURI = Utils::sign($strURI);

$responseStream = Utils::processCommand($signedURI, "GET", "", "");
Utils::saveFile($responseStream, AsposeApp::$outPutLocation . "Sample.xlsx");
                
                    package org.gopaldas.readsps;
 
import java.io.IOException;
import java.net.URL;
 
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.util.ServiceException;
 
public class ReadSpreadsheet {
 
    public static final String GOOGLE_ACCOUNT_USERNAME = "xxxx@gmail.com"; // Fill in google account username
      public static final String GOOGLE_ACCOUNT_PASSWORD = "xxxx"; // Fill in google account password
      public static final String SPREADSHEET_URL = "https://spreadsheets.google.com/feeds/spreadsheets/1L8xtAJfOObsXL-XemliUV10wkDHQNxjn6jKS4XwzYZ8"; //Fill in google spreadsheet URI
 
      public static void main(String[] args) throws IOException, ServiceException
      {
        /** Our view of Google Spreadsheets as an authenticated Google user. */
        SpreadsheetService service = new SpreadsheetService("Print Google Spreadsheet Demo");
 
        // Login and prompt the user to pick a sheet to use.
        service.setUserCredentials(GOOGLE_ACCOUNT_USERNAME, GOOGLE_ACCOUNT_PASSWORD);
 
        // Load sheet
        URL metafeedUrl = new URL(SPREADSHEET_URL);
        SpreadsheetEntry spreadsheet = service.getEntry(metafeedUrl, SpreadsheetEntry.class);
        URL listFeedUrl = ((WorksheetEntry) spreadsheet.getWorksheets().get(0)).getListFeedUrl();
 
        // Print entries
        ListFeed feed = (ListFeed) service.getFeed(listFeedUrl, ListFeed.class);
        for(ListEntry entry : feed.getEntries())
        {
          System.out.println("new row");
          for(String tag : entry.getCustomElements().getTags())
          {
            System.out.println("     "+tag + ": " + entry.getCustomElements().getValue(tag));
          }
        }
      }
}                
                    //The sample code below sends email messages using Exchange Server.

//[C# Code Sample]

/ Create instance of ExchangeClient class by giving credentials
ExchangeClient client = new ExchangeClient("http://MachineName/exchange/username",
    "username", "password", "domain");

// Create instance of type MailMessage
MailMessage msg = new MailMessage();
msg.From = "sender@domain.com";
msg.To = "recipient@ domain.com ";
msg.Subject = "Sending message from exchange server";
msg.HtmlBody = "<h3>sending message from exchange server</h3>";

// Send the message
client.Send(msg);
 
//[VB.NET Code Sample]

‘Create instance of ExchangeClient class by giving credentials
Dim client As ExchangeClient = New ExchangeClient("http://MachineName/exchange/username", "username", "password", "domain")

' Create instance of type MailMessage
Dim msg As MailMessage = New MailMessage()
msg.From = "sender@domain.com"
msg.To = "recipient@ domain.com "
msg.Subject = "Sending message from exchange server"
msg.HtmlBody = "<h3>sending message from exchange server</h3>"

' Send the message
client.Send(msg)

///Send Email using Exchange Web Services

//[C# Code Sample]

// Create instance of IEWSClient class by giving credentials
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");

// Create instance of type MailMessage
MailMessage msg = new MailMessage();
msg.From = "sender@domain.com";
msg.To = "recipient@ domain.com ";
msg.Subject = "Sending message from exchange server";
msg.HtmlBody = "<h3>sending message from exchange server</h3>";

// Send the message
client.Send(msg);
 
//[VB.NET Code Sample]

' Create instance of EWSClient class by giving credentials
Dim client As IEWSClient = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain")

' Create instance of type MailMessage
Dim msg As MailMessage = New MailMessage()
msg.From = "sender@domain.com"
msg.To = "recipient@ domain.com "
msg.Subject = "Sending message from exchange server"
msg.HtmlBody = "<h3>sending message from exchange server</h3>"

' Send the message
client.Send(msg)
                
                    //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' }
)