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
See this article in Guido's blog
http://www.artima.com/weblogs/viewpost.jsp?thread=122250
I then try to implement M Clock on pys60. I remove a few
things to make the code short.
from __future__ import division
from appuifw import *
import math, time, e32
app.body = c = Canvas()
radius = 72
bigsize = radius * .975
litsize = radius * .67
mx, my = 88, 72
N = 9 # 2,3,4,5,6, 32, 128
def draw(hh, mm, ss, colors=(0, 1, 2)):
# Set bigd, litd to angles in degrees for big, little hands
# 12 => 90, 3 => 0, etc.
bigd = (90 - (mm*60 + ss) / 10) % 360
litd = (90 - (hh*3600 + mm*60 + ss) / 120) % 360
# Set bigr, litr to the same values in radians
bigr = bigd * math.pi / 180
litr = litd * math.pi / 180
# Draw the background colored arcs
drawbg(bigd, litd, colors)
# Draw the hands
c.line([mx, my,
mx + bigsize*math.cos(bigr),
my - bigsize*math.sin(bigr)],
0, width = radius/50)
c.line([mx, my,
mx + litsize*math.cos(litr),
my - litsize*math.sin(litr)],
0, width = radius/33)
# Draw the text
c.text([5, 144-5], u"%02d:%02d:%02d" % (hh, mm, ss), 0xffffff)
def drawbg(bigd, litd, colors=(0, 1, 2)):
c.clear(0)
table = []
for angle, colorindex in [(bigd - 180/N, 0),
(litd - 180/N, 1),
( 90 - 180/N, 2)]:
angle %= 360
for i in range(N):
color = 255
if colorindex in colors:
color = (N-1-i)*color//(N-1)
table.append((angle, color, colorindex))
angle += 360/N
if angle >= 360:
angle -= 360
table.append((0, color, colorindex))
table.sort()
table.append((360, None))
fill = [0, 0, 0]
for i in range(len(table)-1):
angle, color, colorindex = table[i]
fill[colorindex] = color
if angle < 359: # for bug when 359==360==0
c.pieslice([mx-radius,my-radius,mx+radius,my+radius],
angle * math.pi/180, 0, # start, end
fill=tuple(fill), width=0)
c.line([mx+1, my, mx+radius-1, my], tuple(fill)) # complete at 360 deg
running = 1
def quit():
global running
running = 0
app.exit_key_handler= quit
while running: # redraw loop
t = time.time() + time.clock()%1 # time() lack decimal precision
hh, mm, ss = time.localtime(t)[3:6] # +7*60*60
draw(hh, mm, ss, (0,1,2))
e32.ao_sleep(1-t%1)
You can see the sceenshot from here. http://flickr.com/photos/korakot/32337789/
from win32com.shell import shell
df = shell.SHGetDesktopFolder()
pidl = df.ParseDisplayName(0, None,
"::{450d8fba-ad25-11d0-98a8-0800361b1103}")[1]
mydocs = shell.SHGetPathFromIDList(pidl)
Copied from Kevin Dangoor's blog here http://www.blueskyonmars.com/2005/08/05/finding-a-users-my-documents-folder-on-windows/
File f = new File(path);
File [] files = f.listFiles();
Arrays.sort( files, new Comparator()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
# There's another process you want to wait on. In this example, # you know the pid, and it's contained in the file $PID_FILE. while ps -p `cat $PID_FILE` > /dev/null; do sleep 1; done # Now you can continue knowing that process has finished...
(in quicksilver)
.tm ~/path/to/project && logout <TAB> term
Executes in terminal, opens the folder or file with textmate, and closes.
Here's a simple Ruby script to remove CVS directories. Useful if you move a large codebase from one repository to another. To use it just go to the root directory where you want to start the deleting and run the script. The script will start in the current working directory and apply the removal recursively.
def deleteDir(dir)
puts "cd #{dir}"
Dir.chdir(dir)
Dir.foreach(dir) do |file|
if file != "." and file != ".."
if File.directory?(file)
deleteDir("#{dir}/#{file}")
else
puts "delete file #{file}"
File.delete(file)
end
end
end
Dir.chdir("..")
puts "delete directory #{dir}"
Dir.delete(dir)
end
def processDir(dir)
#puts "Processing directory #{dir}"
Dir.chdir(dir)
Dir.foreach(dir) do |file|
if File.directory?(file)
if file == "CVS"
puts "Deleting directory #{dir}/#{file}"
deleteDir("#{dir}/#{file}")
elsif file != "." and file != ".."
processDir("#{dir}/#{file}")
end
end
end
Dir.chdir("..")
end
puts "Working directory: #{Dir.pwd}"
processDir(Dir.pwd)
Chris Houser writes an easy HTML API for Google Maps.
Here's the simplest example
<html> <head> <script src="http://maps.google.com/maps?file=api&v=1&key=yourgmapskey"></script> <script src="http://bluweb.com/chouser/gmapez/gmapez.js"></script> </head> <body> <div class="GMapEZ" style="width: 300px; height: 300px;"></div> </body> </html>
See more examples here http://bluweb.com/us/chouser/gmapez/docs.html
I didn't write this, I'm just posting it in case someone else finds it useful. I needed to parse a file that turned out to be windows .ini. gdsx in #ruby-lang came up with this for me.
#thanks to gdsx in #ruby-lang
def tame(input)
tamed = {}
# split data on city names, throwing out surrounding brackets
input = input.split(/\[([^\]]+)\]/)[1..-1]
# sort the data into key/value pairs
input.inject([]) {|tary, field|
tary << field
if(tary.length == 2)
# we have a key and value; put 'em to use
tamed[tary[0]] = tary[1].sub(/^\s+/,'').sub(/\s+$/,'')
# pass along a fresh temp-array
tary.clear
end
tary
}
tamed.dup.each { |tkey, tval|
tvlist = tval.split(/[\r\n]+/)
p tvlist
tamed[tkey] = tvlist.inject({}) { |hash, val|
k, v = val.split(/=/)
hash[k]=v
hash
}
}
tamed
end
here's what the input looks like
[Amsterdam] Address=Amstelveenseweg 438;1084 JH;Amsterdam [Antwerp] Address=Uitbreidingstraat 4;4-600;Antwerp [Austin] Address=4221 South Harbor Expressway, Suite 400;Austin, Texas 78746 [Baltimore / Smith] City=Baltimore Address=225 Johnson Avenue;Baltimore, Maryland 21209-3600 [Baltimore / Calvert] City=Baltimore Address=151 South Belmont Street, Suite 2350;Baltimore, Maryland 21202-6832 [Bangkok] Address=Unit 543, London Tower;495 North Sathorn Road, Yannawa, Sathorn Bangkok 45467 Country=Thailand [Bergen] Country=Norway City=Bergen Address=Torgallmenningen 4B;PO Box 2153 Sentrum, N-5811;Bergen
here's the output
{"Bergen"=>{"City"=>"Bergen", "Country"=>"Norway", "Address"=>"Torgallmenningen 4B;PO Box 2153 Sentrum, N-5811;Bergen"}, "Antwerp"=>{"Address"=>"Uitbreidingstraat 4;4-600;Antwerp"}, "Baltimore / Smith"=>{"City"=>"Baltimore", "Address"=>"225 Johnson Avenue;Baltimore, Maryland 21209-3600"}, "Amsterdam"=>{"Address"=>"Amstelveenseweg 438;1084 JH;Amsterdam"}, "Bangkok"=>{"Country"=>"Thailand", "Address"=>"Unit 543, London Tower;495 North Sathorn Road, Yannawa, Sathorn Bangkok 45467"}, "Austin"=>{"Address"=>"4221 South Harbor Expressway, Suite 400;Austin, Texas 78746"}, "Baltimore / Calvert"=>{"City"=>"Baltimore", "Address"=>"151 South Belmont Street, Suite 2350;Baltimore, Maryland 21202-6832"}
Is this also an example of a state machine in Ruby?
irb --simple-prompt -r yaml
>> d = YAML.load <<-TEXT
line_with_breaks: >
My name is Simon
Things I like:
* drawings
TEXT
=> {"line_with_breaks"=>"My name is Simon Things I like:\n * drawings\n"}
ripped from noradio
In .htaccess:
AuthUserFile (your path here)/.htpasswd AuthGroupFile /dev/null AuthName hold AuthType Basic <Limit GET> require valid-user </Limit>
Then su to same directory with SSH and:
root> htpasswd -c .htpasswd (username)
At the prompts, enter and reenter the password. Done.
Snippets is at bigbold.com/snippets/ but bigbold.com/snippets always failed with "Bad Request". bigbold.com/snippets always seemed to rewrite into 'snippets.html' for some reason, so this change to .htaccess cures it:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !snippets\.html
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
RewriteRule snippets\.html /snippets/ [R]Replace snippets with the name of your own folder, obviously.
This rxml template (modified from the one in blinksale.com) generates valid Atom 1.0 feeds. If you have a partial to create HTML for each item, they can be included in the feed's "content" elements.
xml.instruct!
xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do
xml.title "Feed Name"
xml.link "rel" => "self", "href" => url_for(:only_path => false, :controller => 'feeds', :action => 'atom')
xml.link "rel" => "alternate", "href" => url_for(:only_path => false, :controller => 'posts')
xml.id url_for(:only_path => false, :controller => 'posts')
xml.updated @posts.first.updated_at.strftime "%Y-%m-%dT%H:%M:%SZ" if @posts.any?
xml.author { xml.name "Author Name" }
@posts.each do |post|
xml.entry do
xml.title post.title
xml.link "rel" => "alternate", "href" => url_for(:only_path => false, :controller => 'posts', :action => 'show', :id => post.id)
xml.id url_for(:only_path => false, :controller => 'posts', :action => 'show', :id => post.id)
xml.updated post.updated_at.strftime "%Y-%m-%dT%H:%M:%SZ"
xml.author { xml.name post.author.name }
xml.summary "Post summary"
xml.content "type" => "html" do
xml.text! render(:partial => "posts/post", :post => post)
end
end
end
end
Some of the rxml RSS 2 templates posted here will work, but have small validation problems. As far as I can tell, this one passes validation every time, given an instance variable @posts, with the appropriate methods. From the source of blinksale.com:
xml.instruct!
xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
xml.channel do
xml.title "Feed Name"
xml.link url_for :only_path => false, :controller => 'posts'
xml.pubDate CGI.rfc1123_date @posts.first.updated_at if @posts.any?
xml.description "Feed Description"
@posts.each do |posts|
xml.item do
xml.title post.name
xml.link url_for :only_path => false, :controller => 'posts', :action => 'show', :id => post.id
xml.description post.body
xml.pubDate CGI.rfc1123_date post.updated_at
xml.guid url_for :only_path => false, :controller => 'posts', :action => 'show', :id => post.id
xml.author "#{post.author.email} (#{post.author.name})"
end
end
end
end
This code was inspired by Peter's code from May 17...
I basically extended his idea to be more flexible and added ! methods to modify the string in place. I chose to use a different regex selector because using "\b" breaks on apostrophes and leave you with words like "You'Re" instead of "You're"...
class String
def titlecase()
ignore_list = %w{of etc and by the for on is at to but nor or a via}
capitalize_all_ex(ignore_list)
end
def titlecase!()
ignore_list = %w{of etc and by the for on is at to but nor or a via}
capitalize_all_ex!(ignore_list)
end
def capitalize_all(force_downcase = true)
ignore_list = %w{}
capitalize_all_ex(ignore_list, force_downcase)
end
def capitalize_all!(force_downcase = true)
ignore_list = %w{}
capitalize_all_ex!(ignore_list, force_downcase)
end
def capitalize_all_ex(ignore_list, force_downcase = true)
# if force_downcase is true then the
# string is, um, downcased first :-)
if force_downcase
self.downcase.gsub(/[\w\']+/){ |w|
ignore_list.include?(w) ? w : w.capitalize
}
else
self.gsub(/[\w\']+/){ |w|
ignore_list.include?(w) ? w : w.capitalize
}
end
end
def capitalize_all_ex!(ignore_list, force_downcase = true)
if force_downcase
self.replace(self.downcase.gsub(/[\w\']+/){ |w|
ignore_list.include?(w) ? w : w.capitalize
})
else
self.replace(self.gsub(/[\w\']+/){ |w|
ignore_list.include?(w) ? w : w.capitalize
})
end
end
end
Add to your model:
GreenPastures < ActiveRecord::Base
alias_column "new_name" => "crappy_old_nAmE"
Include this code in a file in /lib
module Legacy
def self.append_features(base)
super
base.extend(ClassMethods)
end
module ClassMethods
def alias_column(options)
options.each do |new_name, old_name|
self.send(:define_method, new_name) { self.send(old_name) }
self.send(:define_method, "#{new_name}=") { |value| self.send("#{old_name}=", value) }
end
end
end
end
ActiveRecord::Base.class_eval do
include Legacy
end





