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

                    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                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# 
# this script will get your followers count
# across socsial media, i get the user profile
# page and use Regex to grab the followers number
require 'open-uri'

# Getting github followers
def github( username )
  page = open("https://github.com/#{username}").read
  followers = page.scan(/<.+>([0-9]+)<.+>[[:space:]]+followers/i).flatten.first
  puts "Github : #{followers} Followers"
end

# get twitter followers by twitter handle
def twitter( username )
  page = open("https://twitter.com/#{username}").read
  followers = page.scan(/followers<.+>[[:space:]]+<.+>([0-9]+)<.+>/i).flatten.first
  puts "Twitter : #{followers} Followers"
end

# use them to print your followers
# using github username and
# twitter handle
github 'blazeeboy'
twitter 'blaz_boy'