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

                    require 'open-uri'
require 'json'

language = 'en'

print 'What do you need to know? : '
article = URI::encode gets.chomp

request_url = "http://#{language}.wikipedia.org/w/api.php?action=parse&page=#{article}&format=json&prop=text§ion=0"

open(request_url) do |file|
  content = JSON.parse(file.read())['parse']['text'].first[1]
  content_text = content.gsub(/<\/?[^>]+>/, '')
  content_text = content_text.gsub(/[[:space:]]+/, ' ')
  content_text = content_text.gsub(/&#[0-9]+;/,'')
  content_text = content_text.gsub(/\[[0-9]+\]/,'')
  puts content_text
end                
                    require 'time'

Date_of_birth = '1988-8-31'

# Credit to : http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails
# and modified a little bit
def humanize secs
  [	
  	[60, :seconds], 
  	[60, :minutes], 
  	[24, :hours], 
  	[365, :days], 
  	[100, :years]
  ].map do |count, name|
    if secs > 0
      secs, n = secs.divmod(count)
      "#{n.to_i} #{name}"
    end
  end.compact.reverse.join(' ')
end

loop do
	distance = Time.new - Time.parse(Date_of_birth)
	print humanize(distance)+"\r"
	sleep 1
end                
                    require 'Twitter' #gem install twitter
while true
	begin
		# 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: ''
		}
		rClient = Twitter::REST::Client.new config
		sClient = Twitter::Streaming::Client.new(config)

		# topics to watch
		topics = ['#rails', '#ruby', '#coding', '#codepen']
		sClient.filter(:track => topics.join(',')) do |tweet|
			if tweet.is_a?(Twitter::Tweet)
			  puts tweet.text 
			  rClient.fav tweet
			end
		end
	rescue
		puts 'error occurred, waiting for 5 seconds'
		sleep 5
	end

end                
                    require 'socket'
require 'base64'

Refresh = 1 # seconds to refresh image on server
screen_capture_command = 'screencapture -C -x tmp.png'
image = ''
latest = Time.now
server = TCPServer.new 3000

loop do
  Thread.start(server.accept) do |client|
	if Time.now-latest>=Refresh
		system(screen_capture_command)
		latest = Time.now
		File.open('tmp.png', 'rb') do |file| 
			image = 'data:image/png;base64,'+Base64.encode64(file.read) 
		end
	end
  	client.puts '<html><head>'+
				"<script>setTimeout(function(){document.location.reload();},#{Refresh*1000});</script>"+
				'</head><body style="padding:0px;margin:0px;">'+
				"<img src=\"#{image}\" style=\"height:100%;\"/>"+
				'</body></html>'
    client.close
  end
end                
                    class Integer
	def to_a
		arr = []
		tmp = self
		while tmp>0
			arr << tmp%10
			tmp /= 10
		end
		arr.reverse
	end
end

# usage
print 32455.to_a
print 433456.to_a
print 345434.to_a.sort
print 344543.to_a.join '-'                
                    class Array
	def same?
		uniq.length==1
	end
end

x = 1
y = 2
z = 2
l = 2

# old way : x==y and y==z
puts [x,y,z].same? # false
# old way : y==z and z==l
puts [y,z,l].same? # true
                
                    require 'webrick'
 
Port = 3000
Directory = Dir::pwd

WEBrick::HTTPServer.new(
	Port: Port,
	DocumentRoot: Directory
).start                
                    require 'open-uri'
require 'json'
require 'psych'

city = 'portsaid,egypt'
request = "http://api.openweathermap.org/data/2.5/weather?q=#{city}"
response = open(request).readlines.join
print Psych.dump( JSON.parse(response) )                
                    //The following example shows how to convert a chart to render an image file.
//Create a new Workbook.
Workbook workbook = new Workbook();

//Get the first worksheet.
Worksheet sheet = workbook.getWorksheets().get(0);

//Set the name of worksheet
sheet.setName("Data");

//Get the cells collection in the sheet.
Cells cells = workbook.getWorksheets().get(0).getCells();

//Put some values into a cells of the Data sheet.
cells.get("A1").setValue("Region");
cells.get("A2").setValue("France");
cells.get("A3").setValue("Germany");
cells.get("A4").setValue("England");
cells.get("A5").setValue("Sweden");
cells.get("A6").setValue("Italy");
cells.get("A7").setValue("Spain");
cells.get("A8").setValue("Portugal");
cells.get("B1").setValue("Sale");
cells.get("B2").setValue(70000);
cells.get("B3").setValue(55000);
cells.get("B4").setValue(30000);
cells.get("B5").setValue(40000);
cells.get("B6").setValue(35000);
cells.get("B7").setValue(32000);
cells.get("B8").setValue(10000);

//Create chart
int chartIndex = sheet.getCharts().add(ChartType.COLUMN, 12, 1, 33, 12);
Chart chart = sheet.getCharts().get(chartIndex);

//Set properties of chart title
chart.getTitle().setText("Sales By Region");
chart.getTitle().getTextFont().setBold(true);
chart.getTitle().getTextFont().setSize(12);

//Set properties of nseries
chart.getNSeries().add("Data!B2:B8", true);
chart.getNSeries().setCategoryData("Data!A2:A8");

//Set the fill colors for the series's data points (France - Portugal(7 points))
ChartPointCollection chartPoints = chart.getNSeries().get(0).getPoints();

ChartPoint point = chartPoints.get(0);
point.getArea().setForegroundColor(Color.getCyan());

point = chartPoints.get(1);
point.getArea().setForegroundColor(Color.getBlue());

point = chartPoints.get(2);
point.getArea().setForegroundColor(Color.getYellow());

point = chartPoints.get(3);
point.getArea().setForegroundColor(Color.getRed());

point = chartPoints.get(4);
point.getArea().setForegroundColor(Color.getBlack());

point = chartPoints.get(5);
point.getArea().setForegroundColor(Color.getGreen());

point = chartPoints.get(6);
point.getArea().setForegroundColor(Color.getMaroon());

//Set the legend invisible
chart.setShowLegend(false);

//Get the Chart image
ImageOrPrintOptions imgOpts = new ImageOrPrintOptions();
imgOpts.setImageFormat(ImageFormat.getPng());

//Save the chart image file.
chart.toImage(new FileOutputStream("D:\\Files\\MyChartImage.png"), imgOpts);