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
# generate a single sentence from a canonical form
# canonical sentence is a multi sentences combined in one
# form, generator will generate a sentence from it randomly
# based on the form, for example:
# "Hello [Emad|Elsaid]" , may generate "Hello Emad" or
# "Hello Elsaid" the result is random.
# also you could nest [] inside each other to gain a multi level
# canonical sentence example:
# "[[Hi|Hello] [Emad|elsaid] | good [morning|night] sir]"
def generate(result)
	while result.include? '[' 
		s_start = result.index '['
		s_end = s_start+1
		while s_end<result.length and result[s_end]!=']'
			s_start = s_end if result[s_end] == '['
			s_end += 1
		end
		sentence = result[(s_start+1)...s_end]
		sentence = sentence.split '|'
		result = result[0...s_start] + sentence.sample + result[s_end+1...result.length]
	end
	result
end

10.times do
	puts generate '[Hello|Hi] my [friend|dear], how [are you [today|these days]|is your brother]?'
end

# Hello my friend, how is your brother?
# Hi my dear, how is your brother?
# Hello my dear, how is your brother?
# Hello my dear, how is your brother?
# Hi my friend, how is your brother?
# Hi my friend, how is your brother?
# Hello my friend, how are you these days?
# Hello my friend, how is your brother?
# Hello my friend, how are you these days?
# Hi my friend, how is your brother?                
                    #!/usr/bin/env ruby
require 'digest/md5'
require "addressable/uri"

# this is based on gravatar image API
# https://en.gravatar.com/site/implement/images/
# options :
# size : <integer> size of image
# default: <string> url of image if email not found or:
#  * 404
#  * mm
#  * identicon
#  * monsterid
#  * wavatar
#  * retro
#  * blank
# forcedefault: "y" force default image to load
# rating: <string> one of the values : g, pg, r, x
def gravatar email, *options
	email_md5 = Digest::MD5.hexdigest email
	unless options.empty?
		params = Addressable::URI.new
		params.query_values = options.first
		params_query = "?#{params.query}"
	end
	"http://www.gravatar.com/avatar/#{email_md5}#{params_query}"
end


puts gravatar('blazeeboy@gmail.com')
puts gravatar(
	'blazeeboy@gmail.com', 
	size: 200, 
	default: 'https://pbs.twimg.com/media/BheUcQMIAAA0Gns.jpg:large'
	)
                
                    #!/usr/bin/env ruby
require 'mail' # gem install mail --no-document

# Credit to : 
# http://stackoverflow.com/questions/12884711/how-to-send-email-via-smtp-with-rubys-mail-gem

def ask question
  print "#{question} ? : "
  $stdin.gets.chomp!
end

# get it from : 
# https://www.tumblr.com/settings/blog/yourBlogName
# in the Post by Email section
tumblr_email = 'xxxxxxx@tumblr.com'

email = ask('what is your gmail address')

$options = { 
	:address              => "smtp.gmail.com",
  :port                 => 587,
  :domain               => email,
  :user_name            => email,
  :password             => ask('what is your password'),
  :authentication       => 'plain',
  :enable_starttls_auto => true  
}

Mail.defaults do
  delivery_method :smtp, $options
end


Mail.deliver do
  from     $options[:user_name]
  to       tumblr_email
  body     ask('write any message associated with the image')
  ARGV.each do |file|
    add_file file
  end
end

puts 'Posting to tumblr succeeded :)'
                
                    #!/usr/bin/env ruby

# Credits to :
# http://stackoverflow.com/questions/16365553/creating-gist-from-a-ruby-script
# i modified the script alittle bit to read files from params
require 'net/http'
require 'json'


uri = URI("https://api.github.com/gists")

files = {}
ARGV.each do |f|
	files[f] = {
		content: File.read(f)
	}
end

payload = {
  'public' => true,
  'files' => files
}

req = Net::HTTP::Post.new(uri.path)
req.body = payload.to_json

puts req.inspect
puts req.body.inspect

# GitHub API is strictly via HTTPS, so SSL is mandatory
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
  http.request(req)
end

response = JSON.parse res.body
puts response['html_url']                
                    #!/usr/bin/env ruby
require 'mail'

mysql_username = 'root'
mysql_password = '123456'
mysql_database = 'test'
system("mysqldump --user=#{mysql_username} --password=#{mysql_password} #{mysql_database} > backup.sql")


# Credit to : 
# http://stackoverflow.com/questions/12884711/how-to-send-email-via-smtp-with-rubys-mail-gem
options = { 
	:address              => "smtp.gmail.com",
    :port                 => 587,
    :domain               => 'xxxxxxxxx@gmail.com',
    :user_name            => 'xxxxxxxxx@gmail.com',
    :password             => 'xxxxxxxxx',
    :authentication       => 'plain',
    :enable_starttls_auto => true  
}

Mail.defaults do
  delivery_method :smtp, options
end


Mail.deliver do
  from     options[:user_name]
  to       options[:user_name]
  subject  "Database #{mysql_database} backup #{Time.new}"
  body     "Database #{mysql_database} backup #{Time.new}"
  add_file 'backup.sql'
end

File.delete 'backup.sql'                
                    #!/usr/bin/env ruby
require 'koala' # gem install koala --no-ri --no-rdoc

# create a facebook app and get access token from here
# https://developers.facebook.com/tools/explorer
# select "groups", "photos" when authenticating
oauth_access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
group_filtering_words = ['ruby']
image_path = 'image.png' #change to your image path
message = 'My Cool image.' # your message

graph = Koala::Facebook::API.new(oauth_access_token)

# getting groups of interest
groups = graph.get_connections("me", "groups").select do |group|
	group_filtering_words.any? do |word|
		group["name"].downcase.include? word
	end
end

index = 0
groups.each do |group|
	index += 1
	puts "[#{index}/#{groups.size}] Posting to group #{group["name"]}."
	graph.put_picture(
		image_path, 
		{:message => message}, 
		group['id']
	)
end                
                    #!/usr/bin/env ruby
require 'cinch' # gem install cinch --no-ri --no-rdoc
require 'askwiki' # gem install askwiki --no-ri --no-rdoc

bot = Cinch::Bot.new do
  configure do |c|

    c.server = "irc.freenode.org"
    c.nick = "Ask_wikipedia"
    c.channels = ["#cinch-bots"]
    
  end

  on :message do |m|
  	if m.message.start_with? 'askwiki'
  		query = m.message.gsub('askwiki','').strip
    	m.reply Askwiki.ask(query), true
	end
  end
end

bot.start                
                    require 'sinatra' # gem install sinatra --no-rdoc --no-ri
set :port, 3000
set :environment, :production

html = <<-EOT
<html><head><style>
#text{width:100%; font-size: 15px; padding: 5px; display: block;}
</style></head><body>
	<input id="text" placeholder="Write then press Enter."/>
	<div id="chat"></div>
	<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
	<script>
	$('#text').keypress(function(e){
		if( e.keyCode==13 ){
			$.get('/send',{text:$('#text').val()});
			$('#text').val('');
		}
	});
	last = 0;
	setInterval(function(){
		$.get('/update',{last:last},
			function(response){
				last = $('<p>').html(response).find('span').data('last');
				$('#chat').append(response);
				});
		},1000);
	</script>
</body></html>
EOT

chat = ['welcome..']
get('/') { html }
get '/send' do
	chat << "#{request.ip} : #{params['text']}"
	nil
end
get '/update' do
	updates = chat[params['last'].to_i..-1]
	last = "<span data-last=\"#{chat.size}\"></span>"
	if updates.size>0
	updates.join('</br>') + "#{last}</br>"
	else
		last
	end
end                
                    require 'sinatra' # gem install sinatra --no-ri --no-rdoc
set :port, 3000
html = <<-EOT
<html><head><style>
#regex,#text{ width:100%; font-size:15px; display:block; margin-bottom:5px; }
#text{ height: 200px; }
span{ background:rgb(230,191,161); display:inline-block; border-radius:3px;}
</style></head><body>

	<input id="regex" placeholder="Regex"/>
	<textarea id="text" placeholder="Text"></textarea>
	<div id="result"></div>

	<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
	<script>
	$('#regex,#text').keyup(function(){
			$.get('/preview',{
				reg:$('#regex').val(),
				text:$('#text').val()
			},function(r){
				$('#result').html(r);
			});
	});
	</script>

</body></html>
EOT

get('/'){ html }
get '/preview' do 
	begin
		params['text'].gsub(/(#{params['reg']})/,'<span>\1</span>')
	rescue
		'Your regex is invalid'
	end
end
                
                    #!/usr/bin/env ruby
require 'Twitter'
# Create a read write application from : 
# https://apps.twitter.com
# authenticate it for your account
# fill in the following
config = {consumer_key:        '',  consumer_secret:     '',
          access_token:        '',  access_token_secret: ''}
me = 'Blaze Boy' # to prevent DM yourself

Thread.new do
  loop do
    begin
      
      rClient = Twitter::REST::Client.new config
      sClient = Twitter::Streaming::Client.new(config)
      sClient.user do |object|
        if object.is_a? Twitter::Streaming::Event and object.name==:follow
          user = object.source
          if user.name != me
            rClient.create_direct_message user, "Thanks for following me #{user.name} :)"
            puts "New follower : #{object.source.name}"
          end
        end
      end

    rescue
      puts 'error occurred, sleeping for 5 seconds'
      sleep 5
    end
  end
end

loop { sleep 5 }