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
<a href="http://jsfromhell.com/math/closest-circle-point">
Given a dot and a circle, it returns the nearest dot over the circle.
[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/closest-circle-point [v1.0]
closestCirclePoint = function( px, py, x, y, ray ){
var tg = ( x += ray, y += ray, 0 );
return function( x, y, x0, y0 ){ return Math.sqrt( ( x -= x0 ) * x + ( y -= y0 ) * y ); }( px, py, x, y ) > ray ?
{ x: Math.cos( tg = Math.atan2( py - y, px - x ) ) * ray + x, y: Math.sin( tg ) * ray + y }
//{ x: ( px - x ) / ( length / ray ) + x, y: ( py - y ) / ( length / ray ) + y }
: { x: px, y: py };
};
<a href="http://jsfromhell.com/math/closest-line-point">
Given a dot and a line, it returns the nearest dot over the line.
[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/closest-line-point [v1.0]
closestLinePoint = function( px, py, x, y, angle ){
var tg = ( ( angle %= 360 ) < 0 && ( angle += 180 ), Math.tan( -angle * Math.PI / 180 ) );
return angle < 45 || angle > 135 ? { x: px, y: ( px - x ) * tg + y } : { x: ( py - y ) / tg + x, y: py };
};
<a href="http://jsfromhell.com/forms/masked-input">
Simple and generic mask routine.
[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>
@REQUIRES <a href="http://www.jsfromhell.com/geral/event-listener">Event-Listener</a>
// REQUIRES: http://jsfromhell.com/geral/event-listener
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/masked-input [v1.0]
MaskInput = function(f, m){ //v1.0
function mask(e){
var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[À-ÿ]/i, "8": /./ },
rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
function accept(c, rule){
for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
if(r & i && patterns[i].test(c))
break;
return i <= r || c == rule;
}
var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
}
for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
addEvent(f, i, mask);
};
//]]>
</script>
Usage (sorry, i'm lazy to write a help hahaha)
<form action="">
telephone "(99)9999-9999"
<input type="text" />
date "99/99/9999"
<input type="text" />
máscara = letter + letter withou accent + 2 numbers + "-" + anything + letter "Cc99-*C"
<input type="text" />
everything, but a, b or c "E^abc"
<input type="text" />
only a, b or c "O^abc"
<input type="text" />
just letters "C^"
<input type="text" />
just letters and also white-space "C^ "
<input type="text" />
just numbers and also the letters a, b e c "9^abc"
<input type="text" />
</form>
<script>
with( document.forms[0] ){
MaskedInput.apply( elements[0], '(99)9999-9999' );
MaskedInput.apply( elements[1], '99/99/9999' );
MaskedInput.apply( elements[2], 'Cc99-*C' );
MaskedInput.apply( elements[3], 'E^abc' );
MaskedInput.apply( elements[4], 'O^abc' );
MaskedInput.apply( elements[5], 'C^' );
MaskedInput.apply( elements[6], 'C^ ' );
MaskedInput.apply( elements[7], '9^abc' );
}
</script>
<a href="http://jsfromhell.com/classes/randomizer">
Simple randomizer, also with probability randomizing.
[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>
Code
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/randomizer [v1.0]
Randomizer = function( type ){
var o = this;
( o.d = [], o.t = type || Randomizer.RANDOMIZED, o.x = -1, o.u = 0 );
};
with( { o: Randomizer, p: Randomizer.prototype } ){
o.SEQUENCED = ( o.PROBABILITY = ( o.RANDOMIZED = 0 ) + 1 ) + 1;
p.add = function( object, probability ){
this.u += ( this.d[ this.d.length ] = { o: object, p: Math.abs( probability || 1 ) } ).p;
};
p.remove = function( index ){
if( index > -1 && index < this.d.length )
this.u -= this.d.splice( index, 1 ).p;
};
p.next = function(){
if( !this.u ) return null;
var i = 0, m = 0, x = this.t == Randomizer.SEQUENCED ? ( this.x = ( this.x + 1 ) % this.d.length ) : Math.round( Math.random() * ( this.t == Randomizer.PROBABILITY ? this.u : this.d.length - 1 ) );
if( this.t == Randomizer.PROBABILITY ){
do m += this.d[ i++ ].p;
while( x > m || !( ( x = --i ) + 1 ) );
}
return this.d[ x ].o;
};
}
Example
//can be also RANDOMIZED and SEQUENCED... x = new Randomizer( Randomizer.PROBABILITY ); x.add( "I have more chances than everybody :]", 20 ); x.add( "I have good chances", 10 ); x.add( "I'm difficult to appear...", 1 ); for( i = 10; i--; document.write( x.next(), '\n' ) );
taken from http://www.cherrypy.org/wiki/CherryPyTutorial
in the browser, return a "Hello world!" at http://localhost:8080(/index)
from cherrypy import cpg
class HelloWorld:
@cpg.expose
def index(self):
return "Hello world!"
cpg.root = HelloWorld()
cpg.server.start()
myObject is an instance of a class
myMethod is the name of the method (string)
myArgs is a dict for named arguments
if hasattr(myObject,myMethod):
try:
retValue = getattr(myObject,myMethod)(*(),**(myArgs))
except TypeError:
# arguments mismatch
else:
# there is no "myMethod" method in myObject
could be a good start for a new script
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys
if __name__ == "__main__":
_path = os.path.split(sys.argv[0])[0]
if _path: os.chdir(_path)
import sys, traceback, string def myExceptHook(type, value, tb): sys.__excepthook__(type, value, tb) lines = traceback.format_exception(type, value, tb) print string.join(lines) sys.excepthook = myExceptHook
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<title>XHTML Template</title>
</head>
<body>
</body>
</html>
import smtplib
from email.MIMEText import MIMEText
def sendTextMail(to,sujet,text,server="localhost"):
fro = "Expediteur <expediteur@mail.com>"
mail = MIMEText(text)
mail['From'] = fro
mail['Subject'] =sujet
mail['To'] = to
smtp = smtplib.SMTP(server)
smtp.sendmail(fro, [to], mail.as_string())
smtp.close()
sendTextMail("toto@titi.com","hello","cheers")
a = set("ABC")
b = set("CDE")
print "A:",a
print "B:",b
print "Intersection:\t",a & b
print "Union:\t\t",a | b
print "Diff a-b:\t\t",a - b
print "Diff b-a:\t\t",b - a
print "Exclusive:\t\t",a ^ b
because translate and maketrans don't love utf-8 ;-(
import string
french=u"15 résultats trouvés".encode("utf_16")
sfrom = u"à âäéèêëïîôöûùüç".encode("utf_16")
sto = u"aaaeeeeiioouuuc".encode("utf_16")
print french.translate( string.maketrans(sfrom,sto) )
free adaptation of http://slugathon.python-hosting.com/changeset/205
import gtk
import Image
def image2pixbuf(im):
file1 = StringIO.StringIO()
im.save(file1, "ppm")
contents = file1.getvalue()
file1.close()
loader = gtk.gdk.PixbufLoader("pnm")
loader.write(contents, len(contents))
pixbuf = loader.get_pixbuf()
loader.close()
return pixbuf
responding "hello" at http://localhost:8080
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200, 'OK')
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write( "hello" )
@staticmethod
def serve_forever(port):
HTTPServer(('', port), MyServer).serve_forever()
if __name__ == "__main__":
MyServer.serve_forever(8080)
import sqlite
con = sqlite.connect('mydatabase.db')
cur = con.cursor()
#~ cur.execute('CREATE TABLE foo (o_id INTEGER PRIMARY KEY, fruit VARCHAR(20), veges VARCHAR(30))')
#~ con.commit()
cur.execute('INSERT INTO foo (o_id, fruit, veges) VALUES(NULL, "apple", "broccoli")')
con.commit()
print cur.lastrowid
cur.execute('SELECT * FROM foo')
print cur.fetchall()




