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
Some of my friends who practise mindfulness meditation
use an alarm device that vibrate every 2 minutes and
he will become mindful then.
Danny O'Brien of Life Hacks fame asked me about this too.
So, here's a short example (without parameter setting GUI)
that does exactly this.
You need to have miso library install. Only Series 60
2nd Ed FP2 device (Nokia 6630, Nokia 6680) can be used.
See vibrate(...) in miso documentation
http://pdis.hiit.fi/pdis/download/miso/miso-1.40-api.html
import appuifw, miso, e32
# run-and-break type of app
running = 1
def set_exit():
global running
running = 0
appuifw.app.exit_key_handler= set_exit
# main loop
while running:
miso.vibrate(500, 100) # vibrate for 500 millisec, at full speed
e32.ao_sleep(10) # vibrate every 10 seconds
I don't have a FP2 phone to test this. Though the code is pretty straight forward, please report if there is a problem.
py_s60 1.1.3 was released a week ago.
I wonder why there's no more people playing with it.
So, I have created a simple game as an example.
I don't know what this game is called. It has 4x4 square box
with 15 pieces (1 piece missing). You need to move all the
pieces into sorting order.
Since the program is so simple, I decided to make the
moving of a piece smoother by moving it bit by bit.
Hope this doesn't make the code to hard to read.
from appuifw import *
from key_codes import *
import e32, random
# run and break-loop type of app
sleep = e32.ao_sleep
running = 1
def set_exit():
global running
running = 0
app.exit_key_handler= set_exit
# canvas and typical colors
c = Canvas()
app.body = c
red, green, blue, gray, white = 0xff0000, 0x00ff00, 0x0000ff, 0x777777, 0xffffff
# randomize number order for pieces
seq = range(1,17)
random.shuffle(seq)
b = [seq[0:4], seq[4:8], seq[8:12], seq[12:16]]
def piece(i, j, n):
if n < 10:
c.text( (12+20*i, 20+20*j), unicode(n))
else:
c.text( (7+20*i, 20+20*j), unicode(n))
def box(i, j, color, fill=None):
c.rectangle( [5+20*i, 5+20*j, 25+20*i, 25+20*j], color, fill)
# draw board pieces
for k in range(16):
j, i = divmod(k, 4)
piece(i, j, b[j][i])
y, x = divmod(seq.index(16), 4)
box(x, y, white, white)
moving = 0 # cursor to lock if animating
# move cursor in dx, dy direction
def move(dx, dy):
global x,y, moving
if moving:
return
moving = 1
if 0 <= x-dx < 4 and 0 <= y-dy < 4:
b[y][x] = b[y-dy][x-dx]
animate(x-dx, y-dy, dx, dy, b[y][x])
x -= dx # the hole move in opposite direction
y -= dy
moving = 0
# moving a piece for x,y to dx, dy direction
def animate(x, y, dx, dy, n):
if n < 10:
px = 12
else:
px = 7
for i in range(5):
c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n))
sleep(0.05)
c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n), white)
c.text( [px+20*(x+dx), 20+20*(y+dy)], unicode(n) )
# bind arrow keys
c.bind(EKeyRightArrow,lambda:move(1, 0))
c.bind(EKeyLeftArrow,lambda:move(-1, 0))
c.bind(EKeyUpArrow,lambda:move(0, -1))
c.bind(EKeyDownArrow,lambda:move(0, 1))
# main loop, just wait
while running:
sleep(0.1)
py_s60 1.1.3 has its drawing API very similar to PIL.
Porting from PIL to S60 is very easy. Here's an example
that I port a sparkline drawing function from
Joe Gregorio's article at xml.com
# modified from Joe Gregorio's article at
# http://www.xml.com/pub/a/2005/06/22/sparklines.html
from appuifw import *
import e32
lock = e32.Ao_lock()
c = Canvas()
app.body = c
draw = c._draw
red, green, blue, gray = 0xff0000, 0x00ff00, 0x0000ff, 0x777777
def plot_sparkline(results, step=2, height=20, \
min_m=None, max_m=None, last_m=None, \
min_color=blue, max_color=green, last_color=red):
coords = zip(range(1,len(results)*step+1, step), \
[height - 3 - y/(101.0/(height-4)) for y in results])
draw.line(coords, gray)
if min_m:
min_pt = coords[results.index(min(results))]
draw.rectangle([min_pt[0]-1, min_pt[1]-1, min_pt[0]+1, min_pt[1]+1], fill=min_color)
if max_m:
max_pt = coords[results.index(max(results))]
draw.rectangle([max_pt[0]-1, max_pt[1]-1, max_pt[0]+1, max_pt[1]+1], fill=max_color)
if last_m:
end = coords[-1]
draw.rectangle([end[0]-1, end[1]-1, end[0]+1, end[1]+1], fill=last_color)
results = [88,84,82,92,82,86,66,82,44,64,66,88,96,80,24,26, \
14,0,0,26,8,6,6,24,52,66,36,6,10,14,30]
plot_sparkline(results, 3, 30, min_m=1, max_m=1, last_m=1)
app.exit_key_handler = lock.signal
lock.wait()
This will take a phrase and truncate it at the word level
<?php
function trunc($phrase, $max_words)
{
$phrase_array = explode(' ',$phrase);
if(count($phrase_array) > $max_words && $max_words > 0)
$phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...'
return $phrase;
}
?>
This is a tidy way of alternating classes on some element.
In the view:
<tr class="<%= alternate %>">
In your application helper:
def alternate(str1 = "odd", str2 = "even") @alternate_odd_even_state = true if @alternate_odd_even_state.nil? @alternate_odd_even_state = !@alternate_odd_even_state @alternate_odd_even_state ? str2 : str1 end
Just to make drawing a circle easier.
Here is a function that will draw yellow circle with black outline.
# from appuifw import * # c = Canvas() # app.body = c def circle(x,y,radius=5, outline=0, fill=0xffff00, width=1): c.ellipse((x-radius, y-radius, x+radius, y+radius), outline, fill, width)
You may use other default values. Then I create a function to show circles randomly
import e32
from random import randint, choice
sleep = e32.ao_sleep
colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xffffff]
def rand_circle(n):
c.clear()
for i in range(n):
circle(randint(0,176), randint(0,144), randint(5,20), fill=choice(colors))
sleep(0.1)
# now show it
rand_circle(30)
def sorted(seq): seq.sort() return seq
<% @projects.each_with_index do |project, i| %> <% row_class = i%2 == 0 ? "even" : "odd" %> <tr class="<%= row_class %>"> ...... <% end %>
In the CSS:
TR.even { background-color: #f00; }
TR.odd { background-color: #f00; }etc..
A few days ago, I posted an example for py_s60 1.1.0
Now that 1.1.3 is released, here's an updated version.
# mincanvas.py : minimal canvas example
# It draws to screen directly (doesn't use canvas callback)
# this code is for 1.1.3 version
import e32, appuifw, graphics
from key_codes import *
app = appuifw.app
screen_x, screen_y = 176, 208
x = y = 0
vx = vy = 1
running = 1
def set_exit():
global running
running = 0
def add_dir(dx, dy):
global vx, vy
vx += dx
vy += dy
# change screen, body
app.screen = 'full'
c = appuifw.Canvas()
app.body = c
draw = graphics.Draw(c)
# bind 6 keys
app.exit_key_handler= set_exit
c.bind(EKeyRightArrow,lambda:add_dir(1, 0))
c.bind(EKeyLeftArrow,lambda:add_dir(-1, 0))
c.bind(EKeyUpArrow,lambda:add_dir(0, -1))
c.bind(EKeyDownArrow,lambda:add_dir(0, 1))
c.bind(EKeyDevice3, draw.clear) # press joy stick
# main loop
while running:
# move x, y
x = (x + vx) % screen_x
y = (y + vy) % screen_y
# plot a red dot at (x, y)
draw.point((x, y), 0xff0000)
e32.ao_sleep(0.1)
Found this here:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/122906
def Hash.from_pairs_e(keys,values)
hash = {}
keys.size.times { |i| hash[ keys[i] ] = values[i] }
hash
end
// ==UserScript==
// @name amazon-sponsored-links
// @namespace chillihead
// @description Remove sponsored links from Amazons search results
// @include http://www.amazon.co.uk*
// ==/UserScript==
if(document.getElementsByTagName("span")!=null)
{
var s = document.getElementsByTagName("span");
for(var i = 0; i < s.length; i++)
{
if(s[i].getAttribute("class") != null)
{
var cls = s[i].getAttribute("class");
if(cls == "h1")
{
if(s[i].innerHTML != null)
{
var txt = s[i].innerHTML;
if(txt == "Sponsored Links:")
{
// great-grandparent of this span is the containing table.
var theTable = s[i].parentNode.parentNode.parentNode;
// get the tables parent
var tableParent = theTable.parentNode;
// remove the table of sponsored links.
tableParent.removeChild(theTable);
}
}
}
}
}
}
py_s60 1.1.3 provides calendar module where you can manipulate
your calendar and todo items. Many item types (called entry) are
contained in the calendar. They are
- Appointment
- Event
- Aniversary
- Todo
There is also a TodoList type to group each TodoEntry
into many lists.
Since the official document (a programming guide) is not
finished yet, I will just shown some simple tasks.
(I don't have time to try everything)
import time, calendar
now = time.time()
cal = calendar.open()
day_all = cal.daily_instances(now) # all entries today
# if you specify any of the 4 types, it will show only those
month_ev = cal.monthly_instances(now, events=1) # events this month
# search for keyword within duration
jan01 = mktime((2005,1,1, 0,0,0, 0,0,0))
first_km = cal.find_instances(jan01, now, u'km')[0] # first in this year
# display entry information
e = cal[first_km['id']] # or use any entry found above
print e.type, strftime('%b %d %H:%M', localtime(e.start_time))
print e.content, '(', e.location, ')'
# other properties are id, last_modified, priority, alarm,
# replication, crossed_out, and end_time
# add new appointment
a = cal.add_appointment()
a.content = 'urgent meeting'
a.set_time(now, now) # start and end time
a.commit()
There's a bug with find_instances. It return only 1 matching entry. (should return all)
py_s60 1.1.3 provide audio module which allow you to record sound.
import e32, audio
s = audio.Sound.open('C:\\test.amr')
s.record() # start recording
e32.ao_sleep(5) # do if for 5 seconds
s.stop() # stop recording
# the file is now created, ready to be played
s.play()
Using this code, I can record sound longer than the 1 minute limit by Nokia's 'Recorder' program. Update: It can record in 'wav', 'amr','au'. I can't play the file recorded with 'wav', though. It seems 6600 has the problem with uncompressed 16-bit wave. (It can play other wave files fine.)
py_s60 1.1.3 provides audio module which allow you to
play sound. This should let people write some fun games.
Here's a quick example.
from audio import * f = 'C:\\Nokia\\Sounds\\Digital\\28050.amr' s = Sound.open(f) s.play()
I have tried calling Sound.open(f).play() directly, but it doesn't seem to work. I may be waiting for file loading or wait for some callback. I don't know. You can play it many times or repeat forever
s.play(3) # 3 times s.play(KMdaRepeatForever) # or just use -2 s.stop() # Ok, enough of it
Trace your website visitors (and referrers) as they come using this bash script.
# CONFIGURATION
# =============
# Where your httpd log file is
log="current-http-accesslog"
# What files to exclude (request for those files won't be shown)
exclude="\.gif|\.jpg|\.png|\.ico|\.css|\.js"
# Width of request and referer columns (set it to match your terminal)
col_width=35
# MAIN SCRIPT
# ===========
# Check if log file actually exists (and is readable)
if [ ! -r "${log}" ]; then
echo "Cannot access log file: $log"
exit 0
fi
# After startup we will output few lines
start=`wc -l < "${log}"`
start=$(( $start - 30 ))
if (( ${start} < 0 ))
then start=$((0))
fi
# Main loop
while :
do
end=`wc -l < "${log}"`
end="${end##* }"
if (( ${end} > ${start} ))
then
start=$(( $start + 1 ))
sed -n "${start},${end}p" "${log}" | egrep -v "${exclude}" | awk -v col_width=$col_width '{
# we are only interested in GET/POST requests
if ( match($0, /"(GET|POST).*?"/) > 0 )
{
split($0, fields, "\"")
# IP_ADDRESS
tmp = $1
while ( length(tmp) < 15 ) tmp = tmp " "
printf "%s", tmp " "
# HTTP_REQUEST (GET/POST)
tmp = substr(fields[2], 0, index(fields[2], "HTTP/") - 1 )
tmp = substr(tmp, index(tmp, " ") + 1, col_width)
while ( length(tmp) < col_width ) tmp = tmp " "
printf "%s", tmp " "
# REFERER (the juice)
tmp = fields[4]
while ( length(tmp) < col_width ) tmp = tmp " "
printf "%s", tmp " "
# USER_AGENT
printf "%s", fields[6]
# new line at the end
printf "\n"
}
}'
start=${end}
fi
# this is an endless loop that sleeps every second
sleep 1
done





