code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#!/usr/bin/python -w
import subprocess
import math
# This code does not need to be very fast; it will have maybe 2-3 ops per frame.
class Matrix4(object):
def __init__(self, coefficients):
"""Initialize the matrix from the given coefficients"""
assert len(coefficients) == 4
for c in coefficients:
assert len(c) == 4
self.coeff = tuple(map(tuple,coefficients))
def __mul__(self, other):
return Matrix4([ [ sum(self[i][k] * other[k][j] for k in range(4))
for j in range(4) ]
for i in range(4) ])
def __getitem__(self, n):
return self.coeff[n]
@classmethod
def _Rotation(cls, r1, r2, rad):
c = range(4)
mat = [ [ (1 if i == j else 0) for i in c ] for j in c]
mat[r1][r1] = math.cos(rad)
mat[r1][r2] = -math.sin(rad)
mat[r2][r1] = math.sin(rad)
mat[r2][r2] = math.cos(rad)
return cls(mat)
@classmethod
def Identity(cls):
c = range(4)
mat = [ [ (1 if i == j else 0) for i in c ] for j in c]
return cls(mat)
# SO(4) transformations
@classmethod
def RotWX(cls, rad):
return cls._Rotation(0,1,rad)
@classmethod
def RotXY(cls, rad):
return cls._Rotation(1,2,rad)
@classmethod
def RotYZ(cls, rad):
return cls._Rotation(2,3,rad)
@classmethod
def RotZW(cls, rad):
return cls._Rotation(3,1,rad)
@classmethod
def RotWY(cls, rad):
return cls._Rotation(0,2,rad)
@classmethod
def RotXZ(cls, rad):
return cls._Rotation(1,3,rad)
def as_list(self):
return [self[i][j]
for i in range(4)
for j in range(4)]
class Driver(object):
"""Helper class for generating movies. Carries basic state between
frames, which can be modiied using the various modifier functions.
Use write_image() to save the current frame to disk"""
def __init__(self):
self.xform = Matrix4.Identity()
self.frame = 0
def write_image(self):
proc = subprocess.Popen(['./mk_image', '-b', '-i', 'starting_points.txt'],
stdin=subprocess.PIPE)
s = " ".join(map(str, [150,200, 70,170, 0,80] + self.xform.as_list() + ["py_%09d.png" % self.frame])) + "\n"
print s
proc.stdin.write(s)
proc.stdin.close()
self.frame += 1
print proc.wait()
def load_identity(self):
self.xform = Matrix4.Identity()
return self
def rot_WX(self,r):
self.xform *= Matrix4.RotWX(r)
return self
def rot_XY(self,r):
self.xform *= Matrix4.RotXY(r)
return self
def rot_YZ(self,r):
self.xform *= Matrix4.RotYZ(r)
return self
def rot_ZW(self,r):
self.xform *= Matrix4.RotZW(r)
return self
def rot_WY(self,r):
self.xform *= Matrix4.RotWY(r)
return self
def rot_XZ(self,r):
self.xform *= Matrix4.RotXZ(r)
return self
# Shortcuts...
I = load_identity
WX = rot_WX
XY = rot_XY
YZ = rot_YZ
ZW = rot_ZW
WY = rot_WY
XZ = rot_XZ
F = write_image
def main():
d = Driver()
d.load_identity()
for x in range(4096):
print x
d.WY(0.01).XZ(0.01).XY(0.005).write_image()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0144,
0.0072,
0,
0.66,
0,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.0216,
0.0072,
0,
0.66,
0.2,
526,
0,
1,
0,
0,
526,
0,
0
],
[
3,
0,
0.259,
0.4388,
0,
0.66... | [
"import subprocess",
"import math",
"class Matrix4(object):\n def __init__(self, coefficients):\n \"\"\"Initialize the matrix from the given coefficients\"\"\"\n assert len(coefficients) == 4\n for c in coefficients:\n assert len(c) == 4\n self.coeff = tuple(map(tuple,c... |
#!/usr/bin/python -w
import subprocess
import math
# This code does not need to be very fast; it will have maybe 2-3 ops per frame.
class Matrix4(object):
def __init__(self, coefficients):
"""Initialize the matrix from the given coefficients"""
assert len(coefficients) == 4
for c in coefficients:
assert len(c) == 4
self.coeff = tuple(map(tuple,coefficients))
def __mul__(self, other):
return Matrix4([ [ sum(self[i][k] * other[k][j] for k in range(4))
for j in range(4) ]
for i in range(4) ])
def __getitem__(self, n):
return self.coeff[n]
@classmethod
def _Rotation(cls, r1, r2, rad):
c = range(4)
mat = [ [ (1 if i == j else 0) for i in c ] for j in c]
mat[r1][r1] = math.cos(rad)
mat[r1][r2] = -math.sin(rad)
mat[r2][r1] = math.sin(rad)
mat[r2][r2] = math.cos(rad)
return cls(mat)
@classmethod
def Identity(cls):
c = range(4)
mat = [ [ (1 if i == j else 0) for i in c ] for j in c]
return cls(mat)
# SO(4) transformations
@classmethod
def RotWX(cls, rad):
return cls._Rotation(0,1,rad)
@classmethod
def RotXY(cls, rad):
return cls._Rotation(1,2,rad)
@classmethod
def RotYZ(cls, rad):
return cls._Rotation(2,3,rad)
@classmethod
def RotZW(cls, rad):
return cls._Rotation(3,1,rad)
@classmethod
def RotWY(cls, rad):
return cls._Rotation(0,2,rad)
@classmethod
def RotXZ(cls, rad):
return cls._Rotation(1,3,rad)
def as_list(self):
return [self[i][j]
for i in range(4)
for j in range(4)]
class Driver(object):
"""Helper class for generating movies. Carries basic state between
frames, which can be modiied using the various modifier functions.
Use write_image() to save the current frame to disk"""
def __init__(self):
self.xform = Matrix4.Identity()
self.frame = 0
def write_image(self):
proc = subprocess.Popen(['./mk_image', '-b', '-i', 'starting_points.txt'],
stdin=subprocess.PIPE)
s = " ".join(map(str, [150,200, 70,170, 0,80] + self.xform.as_list() + ["py_%09d.png" % self.frame])) + "\n"
print s
proc.stdin.write(s)
proc.stdin.close()
self.frame += 1
print proc.wait()
def load_identity(self):
self.xform = Matrix4.Identity()
return self
def rot_WX(self,r):
self.xform *= Matrix4.RotWX(r)
return self
def rot_XY(self,r):
self.xform *= Matrix4.RotXY(r)
return self
def rot_YZ(self,r):
self.xform *= Matrix4.RotYZ(r)
return self
def rot_ZW(self,r):
self.xform *= Matrix4.RotZW(r)
return self
def rot_WY(self,r):
self.xform *= Matrix4.RotWY(r)
return self
def rot_XZ(self,r):
self.xform *= Matrix4.RotXZ(r)
return self
# Shortcuts...
I = load_identity
WX = rot_WX
XY = rot_XY
YZ = rot_YZ
ZW = rot_ZW
WY = rot_WY
XZ = rot_XZ
F = write_image
def main():
d = Driver()
d.load_identity()
for x in range(4096):
print x
d.WY(0.01).XZ(0.01).XY(0.005).write_image()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0144,
0.0072,
0,
0.66,
0,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.0216,
0.0072,
0,
0.66,
0.2,
526,
0,
1,
0,
0,
526,
0,
0
],
[
3,
0,
0.259,
0.4388,
0,
0.66... | [
"import subprocess",
"import math",
"class Matrix4(object):\n def __init__(self, coefficients):\n \"\"\"Initialize the matrix from the given coefficients\"\"\"\n assert len(coefficients) == 4\n for c in coefficients:\n assert len(c) == 4\n self.coeff = tuple(map(tuple,c... |
'''###########################################################################################################################
### File: Player.py
### Name: Patrick Delaney, Tom WIlliams, John Mannix
### Class: CSE 487
### Instructor: Dr.Zmuda
### Assignment: Assignment 3
### Files included: Utilities.py, brickout.py
### Description: This class contains all of my methods that were global in nature in brickout.py
################
'''
### Name:
### Author: Patrick Delaney
### Parameters:
### Description:
'''
###########################################################################################################################'''
import direct.directbase.DirectStart # starts Panda
import sys
from pandac.PandaModules import * # basic Panda modules
from direct.showbase.DirectObject import DirectObject # for event handling
from direct.actor.Actor import Actor # Actor class
from direct.interval.IntervalGlobal import * # Intervals (Parallel, Sequence, etc)
from direct.task import Task # for task contants
import math
import random
######CONSTANTS######
#CHOICE OF MODELS
RALPH = 0
SONIC = 1
TAILS = 2
EVE = 3
BUNNY = 4
STARTING_VELOCITY = Vec3(0,0,-10)
#################
SONIC_SCALE = .25
STARTING_POS = Vec3(0,0,0)
#####################
class Player:
'''
### Name: __init__ (Overriden Constructor)
### Author: Patrick Delaney
### Parameters: choice - Choice of Model
### Description: Constructs the Player Object
'''
def __init__(self,choice):
#self.avatarNode = render.attachNewNode("player_dummy_node")
if(choice == RALPH):
self.avatar = loader.loadModel("models/ralph")
elif(choice == SONIC):
self.avatar = loader.loadModel("models/sonic")
self.avatar.setScale(SONIC_SCALE)
elif(choice == TAILS):
self.avatar = loader.loadModel("models/tails")
self.avatar.setScale(SONIC_SCALE)
elif(choice == EVE):
self.avatar = loader.loadModel("models/eve")
elif(choice == BUNNY):
self.avatar = loader.loadModel("models/bunny")
self.avatar.reparentTo(render)
self.avatar.setPos(STARTING_POS)
self.avatar.setHpr(180,90,0)
self.avatar.setTransparency(False)
self.velocity = STARTING_VELOCITY
self.avatarChoice = choice
def getVelocity(self):
return self.velocity
def setVelocity(self,val):
self.velocity = val
| [
[
8,
0,
0.0724,
0.1316,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.2039,
0.0263,
0,
0.66,
0.0526,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2237,
0.0132,
0,
0.66,
... | [
"'''###########################################################################################################################\n### File: Player.py\n### Name: Patrick Delaney, Tom WIlliams, John Mannix\n### Class: CSE 487\n### Instructor: Dr.Zmuda\n### Assignment: Assignment 3\n### Files included: Utilities.py, br... |
from pandac.PandaModules import *
class Picker:
def __init__(self, parent=None, fromMask=BitMask32(0), collideWithGeom=False, intoMask=BitMask32(0)):
if (parent==None):
parent = camera
self.cRay = CollisionRay()
self.cNode = CollisionNode('PickRay')
self.cNode.addSolid(self.cRay)
self.cNode.setIntoCollideMask(intoMask)
if collideWithGeom:
fromMask = fromMask | GeomNode.getDefaultCollideMask()
self.cNode.setFromCollideMask(fromMask)
self.cNodePath = parent.attachNewNode(self.cNode)
# self.cNodePath.show()
self.cHandler = CollisionHandlerQueue()
self.cTrav = CollisionTraverser()
self.cTrav.addCollider(self.cNodePath,self.cHandler)
def pick(self,traverseRoot=None):
return self.pickFromScreen(base.mouseWatcherNode.getMouseX(),base.mouseWatcherNode.getMouseY(),traverseRoot)
def pickFromScreen(self, screenX, screenY, traverseRoot=None):
self.cRay.setFromLens(base.camNode,screenX,screenY)
dir = self.cRay.getDirection()
self.cRay.setDirection(dir)
return self.__doPick(traverseRoot)
def __doPick(self,traverseRoot=None):
if (not traverseRoot):
traverseRoot=render
self.cTrav.traverse(traverseRoot)
self.cHandler.sortEntries()
for i in range(self.cHandler.getNumEntries()):
entry = self.cHandler.getEntry(i)
if (not (isinstance(entry.getIntoNode(),GeomNode) and entry.getIntoNodePath().isHidden()) and entry.hasSurfacePoint()):
return entry
return None
| [
[
1,
0,
0.025,
0.025,
0,
0.66,
0,
6,
0,
1,
0,
0,
6,
0,
0
],
[
3,
0,
0.5375,
0.95,
0,
0.66,
1,
223,
0,
4,
0,
0,
0,
0,
29
],
[
2,
1,
0.275,
0.375,
1,
0.4,
0,
... | [
"from pandac.PandaModules import *",
"class Picker:\n def __init__(self, parent=None, fromMask=BitMask32(0), collideWithGeom=False, intoMask=BitMask32(0)):\n if (parent==None):\n parent = camera\n self.cRay = CollisionRay()\n self.cNode = CollisionNode('PickRay')\n self.c... |
'''###########################################################################################################################
### File: Objects.py
### Name: Patrick Delaney, Tom Williams, John Mannix
### Class: CSE 487
### Instructor: Dr.Zmuda
### Assignment: Assignment 3
### Files included: Utilities.py, brickout.py
### Description: This class makes all of the objects for our game. (An Object Factory)
################
'''
### Name:
### Author: Patrick Delaney
### Parameters:
### Description:
'''
###########################################################################################################################'''
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.gui.DirectGui import *
from direct.showbase.DirectObject import *
from math import sin, cos, pi,sqrt
from random import randint, choice, random
import cPickle, sys
#####CONSTANTS######
#Identifiers for objects
TORUS = 1 #Loop
RING = 2 # Used as a different score modifer / Possible win condition. Just an idea. - Patrick
ANVIL = 3
#Ideas for TORUS
#Speed up loop - Makes you move faster
#Slow down loop - Makes you move slower
# These can stack/ undo each other
#Double Points loop - Doubles the amount of points you can get
#Damage loop - Takes points away
# All these loops could be designated by color
class Objects:
#Once we determine what objects we want to use - I will modify the constructor here. It will be similar to the player
#Constructor. We should also implement a score. Maybe a special attribute as well. - Patrick
'''
### Name: __init__ (Overridden Constructor)
### Author: Patrick Delaney
### Parameters: type - integer identifer signifying what type of object. See Constants above.
### pos - position, num- Used in naming the object's collision node. E.g Ring1
### Description:
'''
def __init__(self,type,pos):
self.type = type;
if(type == TORUS):
self.object = loader.loadModel("models/torus")
self.object.setScale(2)
self.object.setColor(255,215,0,1) # Gold
elif(type == RING):
self.object = loader.loadModel("models/torus")
self.object.setScale(0.5)
self.object.setColor(255,215,0,1) # Gold
self.object.setTransparency(True)
elif( type == ANVIL):
self.object = loader.loadModel("models/anvil");
self.object.setTransparency( True);
self.object.setScale(5);
else:
self.object = loader.loadModel("models/torus")
self.object.setPos(pos)
self.object.reparentTo(render)
| [
[
8,
0,
0.0786,
0.1429,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.2214,
0.0286,
0,
0.66,
0.0833,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2429,
0.0143,
0,
0.66,
... | [
"'''###########################################################################################################################\n### File: Objects.py\n### Name: Patrick Delaney, Tom Williams, John Mannix\n### Class: CSE 487\n### Instructor: Dr.Zmuda\n### Assignment: Assignment 3\n### Files included: Utilities.py, b... |
'''###########################################################################################################################
### File: Utilities.py
### Name: Patrick Delaney
### Class: CSE 487
### Instructor: Dr.Zmuda
### Assignment: Assignment 3
### Files included: Utilities.py, brickout.py
### Description: This class contains all of my methods that were global in nature in brickout.py
################
'''
### Name:
### Author: Patrick Delaney
### Parameters:
### Description:
'''
###########################################################################################################################'''
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.gui.DirectGui import *
from direct.showbase.DirectObject import *
from math import sin, cos, pi,sqrt
from random import randint, choice, random
import cPickle, sys
#############METHODS USED FROM TUT-ASTEROIDS###############################################################################
#This helps reduce the amount of code used by loading objects, since all of the
#objects are pretty much the same.
def loadObject(tex = None, pos = Point2(0,0), depth = 0, scale = 15, transparency = True):
obj = loader.loadModelCopy("plane") #Every object uses the plane model
obj.reparentTo(render)
obj.setPos(Vec3(pos.getX(), pos.getY(), depth)) #Set initial position
obj.setHpr(Vec3(0, -90, 0)) # -90 since egg file is Y-Up format
obj.setScale(scale) #Set initial scale
obj.setBin("unsorted", 0) #This tells Panda not to worry about the
#order this is drawn in. (it prevents an
#effect known as z-fighting)
obj.setDepthTest(True ) #Tells panda not to check if something
#has already drawn in front of it
#(Everything in this game is at the same
#depth anyway)
if transparency: obj.setTransparency(1) #All of our objects are trasnparent
if tex:
tex = loader.loadTexture("textures/"+tex+".png") #Load the texture
obj.setTexture(tex, 1) #Set the texture
return obj
def setVelocity(obj, val):
list = [val[0], val[1], val[2]]
obj.setTag("velocity", cPickle.dumps(list))
def getVelocity(obj):
list = cPickle.loads(obj.getTag("velocity"))
return Vec3(list[0], list[1], list[2])
def genLabelText(text, i):
return OnscreenText(text = text, pos = (-1.25, .95-.05*i), fg=(1,0.3,0.3,1),
align = TextNode.ALeft, scale = .05)
##############################END METHODS USED FROM TUT-ASTEROIDS###################################################
'''
### Name: reflection
### Author: Dr.Zmuda (Modifed by Patrick Delaney, I wasn't sure if my reflection code was wrong, so I used the solution from the
### s drive)
### Parameters: wallEndPt1 - First endpoint of the wall, wallEndPt2 - second endpoint of the wall,
### projectileStartingPt - Starting point of the projectile,
### projectileIntersectionPt - where the projectile hits the wall
### Description: Computes the reflection of the projectile with a wall and returns the reflection vector
'''
def reflection(wallEndPt1, wallEndPt2, projectileStartingPt, projectileIntersectionPt):
wallVec = wallEndPt1 - wallEndPt2
n = Vec2(-wallVec[1], wallVec[0])
n.normalize()
v = projectileStartingPt - projectileIntersectionPt
r = n * 2 * v.dot(n) - v
r.normalize()
return r
'''
### Name: distance
### Author: Patrick Delaney
### Parameters: objOne - objectOne, objTwo - objectTwo
### Description: Computes the distance between two objects in the xy plane.
'''
def distance(objOne,objTwo):
return sqrt( (objTwo[1] - objOne[1])**2 + (objTwo[0] - objOne[0])**2)
'''
### Name: setHits
### Author: Patrick Delaney
### Parameters: obj - brick, val - value to set the hits at
### Description: Sets the amount of hits a brick can take
'''
def setHits(obj,val):
obj.setTag("hits", cPickle.dumps(val))
'''
### Name: getHits
### Author: Patrick Delaney
### Parameters: obj - brick
### Description: Returns the amount of hits a brick has left
'''
def getHits(obj):
return cPickle.loads(obj.getTag("hits"))
'''
### Name: genLabelText2
### Author: Patrick Delaney
### Parameters: text - String to be displayed, x - xPos, y - yPos
### Description: Displays the string inputted on the screen at the x and y position.
'''
def genLabelText2(text, x,y):
return OnscreenText(text = text, pos = (x,y), fg=(1,0.3,0.3,1),
align = TextNode.ALeft, scale = .1)
| [
[
8,
0,
0.0519,
0.0943,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.1462,
0.0189,
0,
0.66,
0.0455,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1604,
0.0094,
0,
0.66,
... | [
"'''###########################################################################################################################\n### File: Utilities.py\n### Name: Patrick Delaney\n### Class: CSE 487\n### Instructor: Dr.Zmuda\n### Assignment: Assignment 3\n### Files included: Utilities.py, brickout.py\n### Descripti... |
#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
| [
[
1,
0,
0.1818,
0.0909,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
14,
0,
0.2727,
0.0909,
0,
0.66,
0.1111,
15,
3,
0,
0,
0,
654,
10,
1
],
[
14,
0,
0.3636,
0.0909,
0,
... | [
"import time",
"t = time.time()",
"u = time.gmtime(t)",
"s = time.strftime('%a, %e %b %Y %T GMT', u)",
"print('Content-Type: text/javascript')",
"print('Cache-Control: no-cache')",
"print('Date: ' + s)",
"print('Expires: ' + s)",
"print('')",
"print('var timeskew = new Date().getTime() - ' + str(t... |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| [
[
1,
0,
0.1111,
0.037,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.6... | [
"import os",
"import subprocess",
"import sys",
"BASEDIR = '../main/src/com/joelapenna/foursquare'",
"TYPESDIR = '../captures/types/v1'",
"captures = sys.argv[1:]",
"if not captures:\n captures = os.listdir(TYPESDIR)",
" captures = os.listdir(TYPESDIR)",
"for f in captures:\n basename = f.split('... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
#====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ====================================================================
#
# This software consists of voluntary contributions made by many
# individuals on behalf of the Apache Software Foundation. For more
# information on the Apache Software Foundation, please see
# <http://www.apache.org/>.
#
import os
import re
import tempfile
import shutil
ignore_pattern = re.compile('^(.svn|target|bin|classes)')
java_pattern = re.compile('^.*\.java')
annot_pattern = re.compile('import org\.apache\.http\.annotation\.')
def process_dir(dir):
files = os.listdir(dir)
for file in files:
f = os.path.join(dir, file)
if os.path.isdir(f):
if not ignore_pattern.match(file):
process_dir(f)
else:
if java_pattern.match(file):
process_source(f)
def process_source(filename):
tmp = tempfile.mkstemp()
tmpfd = tmp[0]
tmpfile = tmp[1]
try:
changed = False
dst = os.fdopen(tmpfd, 'w')
try:
src = open(filename)
try:
for line in src:
if annot_pattern.match(line):
changed = True
line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.')
dst.write(line)
finally:
src.close()
finally:
dst.close();
if changed:
shutil.move(tmpfile, filename)
else:
os.remove(tmpfile)
except:
os.remove(tmpfile)
process_dir('.')
| [
[
1,
0,
0.3514,
0.0135,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3649,
0.0135,
0,
0.66,
0.1111,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.3784,
0.0135,
0,
... | [
"import os",
"import re",
"import tempfile",
"import shutil",
"ignore_pattern = re.compile('^(.svn|target|bin|classes)')",
"java_pattern = re.compile('^.*\\.java')",
"annot_pattern = re.compile('import org\\.apache\\.http\\.annotation\\.')",
"def process_dir(dir):\n files = os.listdir(dir)\n for... |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
print "%.3lf" % ((a+b+c)/3.0)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
256,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"a, b, c = map(int, stdin.readline().strip().split())",
"print(\"%.3lf\" % ((a+b+c)/3.0))"
] |
from sys import stdin
from math import *
r, h = map(float, stdin.readline().strip().split())
print "Area = %.3lf" % (pi*r*r*2 + 2*pi*r*h)
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.75,
0.25,
0,
0.66,
0.... | [
"from sys import stdin",
"from math import *",
"r, h = map(float, stdin.readline().strip().split())",
"print(\"Area = %.3lf\" % (pi*r*r*2 + 2*pi*r*h))"
] |
from sys import stdin
from math import *
n, = map(int, stdin.readline().strip().split())
rad = radians(n)
print "%.3lf %.3lf" % (sin(rad), cos(rad))
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.25,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"from math import *",
"n, = map(int, stdin.readline().strip().split())",
"rad = radians(n)",
"print(\"%.3lf %.3lf\" % (sin(rad), cos(rad)))"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print n*(n+1)/2
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"print(n*(n+1)/2)"
] |
from sys import stdin
a, b = map(int, stdin.readline().strip().split())
print b, a
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.5,
0.25,
0,
0.66,
0.5,
127,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
0.75,
0.25,
0,
0.66,
1,
... | [
"from sys import stdin",
"a, b = map(int, stdin.readline().strip().split())",
"print(b, a)"
] |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
a = (4*n-m)/2
b = n-a
if m % 2 == 1 or a < 0 or b < 0: print "No answer"
else: print a, b
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.3333,
51,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"n, m = map(int, stdin.readline().strip().split())",
"a = (4*n-m)/2",
"b = n-a"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
money = n * 95
if money >= 300: money *= 0.85
print "%.2lf" % money
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.25,
773,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"money = n * 95",
"if money >= 300: money *= 0.85",
"print(\"%.2lf\" % money)"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print ["yes", "no"][n % 2]
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"print [\"yes\", \"no\"][n % 2]"
] |
from sys import stdin
from math import *
x1, y1, x2, y2 = map(float, stdin.readline().strip().split())
print "%.3lf" % hypot((x1-x2), (y1-y2))
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.75,
0.25,
0,
0.66,
0.... | [
"from sys import stdin",
"from math import *",
"x1, y1, x2, y2 = map(float, stdin.readline().strip().split())",
"print(\"%.3lf\" % hypot((x1-x2), (y1-y2)))"
] |
from sys import stdin
n = stdin.readline().strip().split()[0]
print '%c%c%c' % (n[2], n[1], n[0])
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.5,
0.25,
0,
0.66,
0.5,
773,
6,
0,
0,
0,
0,
0,
3
],
[
8,
0,
0.75,
0.25,
0,
0.66,
1,
... | [
"from sys import stdin",
"n = stdin.readline().strip().split()[0]",
"print('%c%c%c' % (n[2], n[1], n[0]))"
] |
from sys import stdin
x, = map(float, stdin.readline().strip().split())
print abs(x)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
190,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"x, = map(float, stdin.readline().strip().split())",
"print(abs(x))"
] |
from sys import stdin
from calendar import isleap
year, = map(int, stdin.readline().strip().split())
if isleap(year): print "yes"
else: print "no"
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
917,
0,
1,
0,
0,
917,
0,
0
],
[
14,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"from calendar import isleap",
"year, = map(int, stdin.readline().strip().split())"
] |
from sys import stdin
f, = map(float, stdin.readline().strip().split())
print "%.3lf" % (5*(f-32)/9)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
899,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"f, = map(float, stdin.readline().strip().split())",
"print(\"%.3lf\" % (5*(f-32)/9))"
] |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes"
elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle"
else: print "no"
| [
[
1,
0,
1,
1,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
]
] | [
"from sys import stdin"
] |
from sys import stdin
a = map(int, stdin.readline().strip().split())
a.sort()
print a[0], a[1], a[2]
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.3333,
475,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"a = map(int, stdin.readline().strip().split())",
"a.sort()",
"print(a[0], a[1], a[2])"
] |
s = i = 0
while True:
term = 1.0 / (i*2+1)
s += term * ((-1)**i)
if term < 1e-6: break
i += 1
print "%.6lf" % s
| [
[
14,
0,
0.1429,
0.1429,
0,
0.66,
0,
553,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.5714,
0.7143,
0,
0.66,
0.5,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.4286,
0.1429,
1,
0.78,
... | [
"s = i = 0",
"while True:\n term = 1.0 / (i*2+1)\n s += term * ((-1)**i)\n if term < 1e-6: break\n i += 1",
" term = 1.0 / (i*2+1)",
" if term < 1e-6: break",
"print(\"%.6lf\" % s)"
] |
from sys import stdin
from decimal import *
a, b, c = map(int, stdin.readline().strip().split())
getcontext().prec = c
print Decimal(a) / Decimal(b)
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.25,
349,
0,
1,
0,
0,
349,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"from decimal import *",
"a, b, c = map(int, stdin.readline().strip().split())",
"getcontext().prec = c",
"print(Decimal(a) / Decimal(b))"
] |
from sys import stdin
n = int(stdin.readline().strip())
print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
1,
0,
0,
901,
10,
3
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n = int(stdin.readline().strip())",
"print(\"%.3lf\" % sum([1.0/x for x in range(1,n+1)]))"
] |
from sys import stdin
print len(stdin.readline().strip())
| [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
8,
0,
1,
0.5,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
4
]
] | [
"from sys import stdin",
"print(len(stdin.readline().strip()))"
] |
from itertools import product
from math import *
def issqrt(n):
s = int(floor(sqrt(n)))
return s*s == n
aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]
print ' '.join(map(str, filter(issqrt, aabb)))
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
808,
0,
1,
0,
0,
808,
0,
0
],
[
1,
0,
0.2222,
0.1111,
0,
0.66,
0.25,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.5556,
0.3333,
0,
0.... | [
"from itertools import product",
"from math import *",
"def issqrt(n):\n s = int(floor(sqrt(n)))\n return s*s == n",
" s = int(floor(sqrt(n)))",
" return s*s == n",
"aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]",
"print(' '.join(map(str, filter(issqrt, aabb))))"
] |
from sys import stdin
a = map(int, stdin.readline().strip().split())
print "%d %d %.3lf" % (min(a), max(a), float(sum(a)) / len(a))
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
475,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"a = map(int, stdin.readline().strip().split())",
"print(\"%d %d %.3lf\" % (min(a), max(a), float(sum(a)) / len(a)))"
] |
from sys import stdin
def cycle(n):
if n == 1: return 0
elif n % 2 == 1: return cycle(n*3+1) + 1
else: return cycle(n/2) + 1
n = int(stdin.readline().strip())
print cycle(n)
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5,
0.4444,
0,
0.66,
0.3333,
276,
0,
1,
1,
0,
0,
0,
2
],
[
4,
1,
0.5556,
0.3333,
1,
0.27,... | [
"from sys import stdin",
"def cycle(n):\n if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1",
" if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1",
" if n == 1: return 0",
" elif n % 2 == 1: return cycle(n*3+1) + 1... |
from sys import stdin
n = int(stdin.readline().strip())
count = n*2-1
for i in range(n):
print ' '*i + '#'*count
count -= 2
| [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.3333,
0.1667,
0,
0.66,
0.3333,
773,
3,
1,
0,
0,
901,
10,
3
],
[
14,
0,
0.5,
0.1667,
0,
... | [
"from sys import stdin",
"n = int(stdin.readline().strip())",
"count = n*2-1",
"for i in range(n):\n print(' '*i + '#'*count)\n count -= 2",
" print(' '*i + '#'*count)"
] |
for abc in range(123, 329):
big = str(abc) + str(abc*2) + str(abc*3)
if(''.join(sorted(big)) == '123456789'): print abc, abc*2, abc*3
| [
[
6,
0,
0.75,
1,
0,
0.66,
0,
38,
3,
0,
0,
0,
0,
0,
4
],
[
14,
1,
1,
0.5,
1,
0.9,
0,
235,
4,
0,
0,
0,
0,
0,
3
]
] | [
"for abc in range(123, 329):\n big = str(abc) + str(abc*2) + str(abc*3)",
" big = str(abc) + str(abc*2) + str(abc*3)"
] |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
print "%.5lf" % sum([1.0/i/i for i in range(n,m+1)])
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
51,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, m = map(int, stdin.readline().strip().split())",
"print(\"%.5lf\" % sum([1.0/i/i for i in range(n,m+1)]))"
] |
from sys import stdin
data = map(int, stdin.readline().strip().split())
n, m = data[0], data[-1]
data = data[1:-1]
print len(filter(lambda x: x < m, data))
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.25,
929,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"data = map(int, stdin.readline().strip().split())",
"n, m = data[0], data[-1]",
"data = data[1:-1]",
"print(len(filter(lambda x: x < m, data)))"
] |
from sys import stdin
def solve(a, b, c):
for i in range(10, 101):
if i % 3 == a and i % 5 == b and i % 7 == c:
print i
return
print 'No answer'
a, b, c = map(int, stdin.readline().strip().split())
solve(a, b, c)
| [
[
1,
0,
0.0909,
0.0909,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5,
0.5455,
0,
0.66,
0.3333,
599,
0,
3,
0,
0,
0,
0,
3
],
[
6,
1,
0.5,
0.3636,
1,
0.68,
... | [
"from sys import stdin",
"def solve(a, b, c):\n for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return\n print('No answer')",
" for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return",
" if i % 3 == a and... |
from itertools import product
sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]
print '\n'.join(map(str, sol))
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
808,
0,
1,
0,
0,
808,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
723,
5,
0,
0,
0,
0,
0,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from itertools import product",
"sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]",
"print('\\n'.join(map(str, sol)))"
] |
from sys import stdin
from math import *
n = int(stdin.readline().strip())
print sum(map(factorial, range(1,n+1))) % (10**6)
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"from math import *",
"n = int(stdin.readline().strip())",
"print(sum(map(factorial, range(1,n+1))) % (10**6))"
] |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
print "%.3lf" % ((a+b+c)/3.0)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
256,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"a, b, c = map(int, stdin.readline().strip().split())",
"print(\"%.3lf\" % ((a+b+c)/3.0))"
] |
from sys import stdin
from math import *
r, h = map(float, stdin.readline().strip().split())
print "Area = %.3lf" % (pi*r*r*2 + 2*pi*r*h)
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.75,
0.25,
0,
0.66,
0.... | [
"from sys import stdin",
"from math import *",
"r, h = map(float, stdin.readline().strip().split())",
"print(\"Area = %.3lf\" % (pi*r*r*2 + 2*pi*r*h))"
] |
from sys import stdin
from math import *
n, = map(int, stdin.readline().strip().split())
rad = radians(n)
print "%.3lf %.3lf" % (sin(rad), cos(rad))
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.25,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"from math import *",
"n, = map(int, stdin.readline().strip().split())",
"rad = radians(n)",
"print(\"%.3lf %.3lf\" % (sin(rad), cos(rad)))"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print n*(n+1)/2
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"print(n*(n+1)/2)"
] |
from sys import stdin
a, b = map(int, stdin.readline().strip().split())
print b, a
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.5,
0.25,
0,
0.66,
0.5,
127,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
0.75,
0.25,
0,
0.66,
1,
... | [
"from sys import stdin",
"a, b = map(int, stdin.readline().strip().split())",
"print(b, a)"
] |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
a = (4*n-m)/2
b = n-a
if m % 2 == 1 or a < 0 or b < 0: print "No answer"
else: print a, b
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.3333,
51,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"n, m = map(int, stdin.readline().strip().split())",
"a = (4*n-m)/2",
"b = n-a"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
money = n * 95
if money >= 300: money *= 0.85
print "%.2lf" % money
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.25,
773,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"money = n * 95",
"if money >= 300: money *= 0.85",
"print(\"%.2lf\" % money)"
] |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print ["yes", "no"][n % 2]
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, = map(int, stdin.readline().strip().split())",
"print [\"yes\", \"no\"][n % 2]"
] |
from sys import stdin
from math import *
x1, y1, x2, y2 = map(float, stdin.readline().strip().split())
print "%.3lf" % hypot((x1-x2), (y1-y2))
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.75,
0.25,
0,
0.66,
0.... | [
"from sys import stdin",
"from math import *",
"x1, y1, x2, y2 = map(float, stdin.readline().strip().split())",
"print(\"%.3lf\" % hypot((x1-x2), (y1-y2)))"
] |
from sys import stdin
n = stdin.readline().strip().split()[0]
print '%c%c%c' % (n[2], n[1], n[0])
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.5,
0.25,
0,
0.66,
0.5,
773,
6,
0,
0,
0,
0,
0,
3
],
[
8,
0,
0.75,
0.25,
0,
0.66,
1,
... | [
"from sys import stdin",
"n = stdin.readline().strip().split()[0]",
"print('%c%c%c' % (n[2], n[1], n[0]))"
] |
from sys import stdin
x, = map(float, stdin.readline().strip().split())
print abs(x)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
190,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"x, = map(float, stdin.readline().strip().split())",
"print(abs(x))"
] |
from sys import stdin
from calendar import isleap
year, = map(int, stdin.readline().strip().split())
if isleap(year): print "yes"
else: print "no"
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
917,
0,
1,
0,
0,
917,
0,
0
],
[
14,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"from calendar import isleap",
"year, = map(int, stdin.readline().strip().split())"
] |
from sys import stdin
f, = map(float, stdin.readline().strip().split())
print "%.3lf" % (5*(f-32)/9)
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
899,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"f, = map(float, stdin.readline().strip().split())",
"print(\"%.3lf\" % (5*(f-32)/9))"
] |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes"
elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle"
else: print "no"
| [
[
1,
0,
1,
1,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
]
] | [
"from sys import stdin"
] |
from sys import stdin
a = map(int, stdin.readline().strip().split())
a.sort()
print a[0], a[1], a[2]
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.3333,
475,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"a = map(int, stdin.readline().strip().split())",
"a.sort()",
"print(a[0], a[1], a[2])"
] |
s = i = 0
while True:
term = 1.0 / (i*2+1)
s += term * ((-1)**i)
if term < 1e-6: break
i += 1
print "%.6lf" % s
| [
[
14,
0,
0.1429,
0.1429,
0,
0.66,
0,
553,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.5714,
0.7143,
0,
0.66,
0.5,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.4286,
0.1429,
1,
0.74,
... | [
"s = i = 0",
"while True:\n term = 1.0 / (i*2+1)\n s += term * ((-1)**i)\n if term < 1e-6: break\n i += 1",
" term = 1.0 / (i*2+1)",
" if term < 1e-6: break",
"print(\"%.6lf\" % s)"
] |
from sys import stdin
from decimal import *
a, b, c = map(int, stdin.readline().strip().split())
getcontext().prec = c
print Decimal(a) / Decimal(b)
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.25,
349,
0,
1,
0,
0,
349,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"from decimal import *",
"a, b, c = map(int, stdin.readline().strip().split())",
"getcontext().prec = c",
"print(Decimal(a) / Decimal(b))"
] |
from sys import stdin
n = int(stdin.readline().strip())
print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
773,
3,
1,
0,
0,
901,
10,
3
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n = int(stdin.readline().strip())",
"print(\"%.3lf\" % sum([1.0/x for x in range(1,n+1)]))"
] |
from sys import stdin
print len(stdin.readline().strip())
| [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
8,
0,
1,
0.5,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
4
]
] | [
"from sys import stdin",
"print(len(stdin.readline().strip()))"
] |
from itertools import product
from math import *
def issqrt(n):
s = int(floor(sqrt(n)))
return s*s == n
aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]
print ' '.join(map(str, filter(issqrt, aabb)))
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
808,
0,
1,
0,
0,
808,
0,
0
],
[
1,
0,
0.2222,
0.1111,
0,
0.66,
0.25,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.5556,
0.3333,
0,
0.... | [
"from itertools import product",
"from math import *",
"def issqrt(n):\n s = int(floor(sqrt(n)))\n return s*s == n",
" s = int(floor(sqrt(n)))",
" return s*s == n",
"aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]",
"print(' '.join(map(str, filter(issqrt, aabb))))"
] |
from sys import stdin
a = map(int, stdin.readline().strip().split())
print "%d %d %.3lf" % (min(a), max(a), float(sum(a)) / len(a))
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
475,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"a = map(int, stdin.readline().strip().split())",
"print(\"%d %d %.3lf\" % (min(a), max(a), float(sum(a)) / len(a)))"
] |
from sys import stdin
def cycle(n):
if n == 1: return 0
elif n % 2 == 1: return cycle(n*3+1) + 1
else: return cycle(n/2) + 1
n = int(stdin.readline().strip())
print cycle(n)
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5,
0.4444,
0,
0.66,
0.3333,
276,
0,
1,
1,
0,
0,
0,
2
],
[
4,
1,
0.5556,
0.3333,
1,
0.71,... | [
"from sys import stdin",
"def cycle(n):\n if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1",
" if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1",
" if n == 1: return 0",
" elif n % 2 == 1: return cycle(n*3+1) + 1... |
from sys import stdin
n = int(stdin.readline().strip())
count = n*2-1
for i in range(n):
print ' '*i + '#'*count
count -= 2
| [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.3333,
0.1667,
0,
0.66,
0.3333,
773,
3,
1,
0,
0,
901,
10,
3
],
[
14,
0,
0.5,
0.1667,
0,
... | [
"from sys import stdin",
"n = int(stdin.readline().strip())",
"count = n*2-1",
"for i in range(n):\n print(' '*i + '#'*count)\n count -= 2",
" print(' '*i + '#'*count)"
] |
for abc in range(123, 329):
big = str(abc) + str(abc*2) + str(abc*3)
if(''.join(sorted(big)) == '123456789'): print abc, abc*2, abc*3
| [
[
6,
0,
0.75,
1,
0,
0.66,
0,
38,
3,
0,
0,
0,
0,
0,
4
],
[
14,
1,
1,
0.5,
1,
0.75,
0,
235,
4,
0,
0,
0,
0,
0,
3
]
] | [
"for abc in range(123, 329):\n big = str(abc) + str(abc*2) + str(abc*3)",
" big = str(abc) + str(abc*2) + str(abc*3)"
] |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
print "%.5lf" % sum([1.0/i/i for i in range(n,m+1)])
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
51,
3,
2,
0,
0,
53,
10,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from sys import stdin",
"n, m = map(int, stdin.readline().strip().split())",
"print(\"%.5lf\" % sum([1.0/i/i for i in range(n,m+1)]))"
] |
from sys import stdin
data = map(int, stdin.readline().strip().split())
n, m = data[0], data[-1]
data = data[1:-1]
print len(filter(lambda x: x < m, data))
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.25,
929,
3,
2,
0,
0,
53,
10,
4
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.5,
... | [
"from sys import stdin",
"data = map(int, stdin.readline().strip().split())",
"n, m = data[0], data[-1]",
"data = data[1:-1]",
"print(len(filter(lambda x: x < m, data)))"
] |
from sys import stdin
def solve(a, b, c):
for i in range(10, 101):
if i % 3 == a and i % 5 == b and i % 7 == c:
print i
return
print 'No answer'
a, b, c = map(int, stdin.readline().strip().split())
solve(a, b, c)
| [
[
1,
0,
0.0909,
0.0909,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5,
0.5455,
0,
0.66,
0.3333,
599,
0,
3,
0,
0,
0,
0,
3
],
[
6,
1,
0.5,
0.3636,
1,
0.89,
... | [
"from sys import stdin",
"def solve(a, b, c):\n for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return\n print('No answer')",
" for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return",
" if i % 3 == a and... |
from itertools import product
sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]
print '\n'.join(map(str, sol))
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
808,
0,
1,
0,
0,
808,
0,
0
],
[
14,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
723,
5,
0,
0,
0,
0,
0,
4
],
[
8,
0,
1,
0.3333,
0,
0.66,
... | [
"from itertools import product",
"sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]",
"print('\\n'.join(map(str, sol)))"
] |
from sys import stdin
from math import *
n = int(stdin.readline().strip())
print sum(map(factorial, range(1,n+1))) % (10**6)
| [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from sys import stdin",
"from math import *",
"n = int(stdin.readline().strip())",
"print(sum(map(factorial, range(1,n+1))) % (10**6))"
] |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
# @author Sam Pullara, samp@yahoo-inc.com
import logging
import wsgiref.handlers
import os
from google.appengine.ext.webapp import template
from datetime import datetime
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import users
from yos.boss.ysearch import search
from yos.boss.ysearch import suggest
from yos.boss.ysearch import glue
from yos.crawl.rest import load_json
from yos.crawl.rest import load_xml
from django.utils import simplejson
from urllib import quote_plus
from types import *
from google.appengine.api import memcache
class Search(webapp.RequestHandler):
def get(self):
q = self.request.get("q")
m = self.request.get("m")
if q:
start = self.request.get("p")
query = q
if m:
query = m
if start:
result = search(query, count=10, start=int(start))
images = search(query, vertical="images", count=1, start=int(start), filter="yes")
else:
result = search(query, count=10)
images = search(query, vertical="images", count=1, filter="yes")
resultset_glue = glue(q)
ysr = result['ysearchresponse']
if ysr.has_key('resultset_web'):
results = ysr['resultset_web']
template_values = {
'query': q,
'totalhits': int(ysr['totalhits']) + int(ysr['deephits']),
'results': results,
'stats': memcache.get_stats()
}
if images:
image_response = images['ysearchresponse']
if int(image_response['count']) > 0:
template_values['image'] = image_response['resultset_images'][0]
if resultset_glue:
categories = []
if resultset_glue.has_key('glue') and resultset_glue['glue'].has_key('navbar'):
navbars = resultset_glue['glue']['navbar']
if navbars:
for navbar in navbars:
if isinstance(navbar, DictType):
if navbar.has_key('navEntry'):
if navbar['type'] == 'disambiguation':
navEntries = navbar['navEntry']
if isinstance(navEntries, DictType):
categories.append(navEntries)
else:
for navEntry in navEntries:
categories.append(navEntry)
template_values['categories'] = categories
if m:
template_values['category'] = m.replace(" ", "%20")
if start and int(start) != 0:
template_values['start'] = start
template_values['prev'] = int(start) - 10
template_values['next'] = int(start) + 10
else:
template_values['next'] = 10
path = os.path.join(os.path.dirname(__file__), "search.html")
self.response.out.write(template.render(path, template_values))
else:
template_values = {
'query': q,
}
path = os.path.join(os.path.dirname(__file__), "empty.html")
self.response.out.write(template.render(path, template_values))
else:
self.redirect("/")
class Suggest(webapp.RequestHandler):
def get(self):
q = self.request.get("q")
if q:
suggests = suggest(q)
self.response.headers['Content-Type'] = 'application/json'
resultset = suggests['ResultSet']
if isinstance(resultset, DictType):
self.response.out.write("{ 'Results':[")
results = resultset['Result']
for result in results:
self.response.out.write("{'v':'" + result + "'},")
self.response.out.write("{}] }")
else:
self.response.out.write("{ 'Results':[]}")
class Index(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "index.html")
self.response.out.write(template.render(path, None))
def main():
application = webapp.WSGIApplication([('/', Index),
('/search', Search),
('/suggest', Suggest)
],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == "__main__":
main()
| [
[
1,
0,
0.0424,
0.0085,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0508,
0.0085,
0,
0.66,
0.0476,
709,
0,
1,
0,
0,
709,
0,
0
],
[
1,
0,
0.0593,
0.0085,
0,
... | [
"import logging",
"import wsgiref.handlers",
"import os",
"from google.appengine.ext.webapp import template",
"from datetime import datetime",
"from google.appengine.ext import webapp",
"from google.appengine.ext import db",
"from google.appengine.api import users",
"from yos.boss.ysearch import sea... |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
""" A simple text library for normalizing, cleaning, and overlapping strings """
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
STOPWORDS = set(["I", "a", "about", "an", "are", "as", "at", "be", "by", "com", "de", "en", "for", "from",
"how", "in", "is", "it", "it's", "la", "of", "on", "or", "that", "the", "this", "to", "was",
"what", "when", "where", "who", "will", "with", "und", "the", "to", "www", "your", "you're"])
def strip_enclosed_carrots(s):
i = s.find("<")
if i >= 0:
j = s.find(">", i)
if j > i:
j1 = j + 1
if j1 >= len(s):
return strip_enclosed_carrots(s[:i])
else:
return strip_enclosed_carrots(s[:i] + s[j1:])
return s
def filter_stops(words):
return filter(lambda w: w not in STOPWORDS, words)
def uniques(s):
return set( tokenize(s) )
def tokenize(s):
return filter_stops(map(lambda t: t.lower().strip("\'\"`,.;-!"), s.split()))
def norm(s):
return "".join( sorted( tokenize(s) ) )
def overlap(s1, s2):
return len(uniques(s1) & uniques(s2))
| [
[
8,
0,
0.1316,
0.0263,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1842,
0.0263,
0,
0.66,
0.125,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.2632,
0.0789,
0,
0.66,... | [
"\"\"\" A simple text library for normalizing, cleaning, and overlapping strings \"\"\"",
"__author__ = \"Vik Singh (viksi@yahoo-inc.com)\"",
"STOPWORDS = set([\"I\", \"a\", \"about\", \"an\", \"are\", \"as\", \"at\", \"be\", \"by\", \"com\", \"de\", \"en\", \"for\", \"from\",\n \"how\", \"in\",... |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["console", "text", "typechecks"]
| [
[
14,
0,
1,
0.25,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\"console\", \"text\", \"typechecks\"]"
] |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
from yos.crawl import object_dict
from types import DictType, ListType, TupleType
OBJ_DICT_TYPE = type(object_dict.object_dict())
def is_dict(td):
return td is DictType or td is OBJ_DICT_TYPE
def is_ordered(to):
return to is ListType or to is TupleType
def is_list(o):
return o is ListType
| [
[
14,
0,
0.2632,
0.0526,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3684,
0.0526,
0,
0.66,
0.1667,
48,
0,
1,
0,
0,
48,
0,
0
],
[
1,
0,
0.4211,
0.0526,
0,
0.6... | [
"__author__ = \"Vik Singh (viksi@yahoo-inc.com)\"",
"from yos.crawl import object_dict",
"from types import DictType, ListType, TupleType",
"OBJ_DICT_TYPE = type(object_dict.object_dict())",
"def is_dict(td):\n return td is DictType or td is OBJ_DICT_TYPE",
" return td is DictType or td is OBJ_DICT_TYPE... |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
def strfix(msg):
"""
Copies this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523011
Constants out any characters that spew encoding errors
"""
goodchars = {}
try:
return str(msg)
except UnicodeEncodeError:
res=''
for i in list(msg):
if i not in goodchars:
try:
str(i)
goodchars[i] = i
except UnicodeEncodeError:
# format character as python string constant
code = ord(i)
t = None
if code < 256:
t ='\\x%02x' % code # 8-bit value
elif code < 65536:
t ='\\u%04x' % code # 16-bit value unicode
else:
t = '\\U%08x' % code # other values as 32-bit unicode
goodchars[i] = t # or '.' for readability ;-)
res += goodchars[i]
return res
def write(msg):
print strfix(msg)
| [
[
14,
0,
0.1351,
0.027,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
2,
0,
0.5541,
0.7568,
0,
0.66,
0.5,
928,
0,
1,
1,
0,
0,
0,
4
],
[
8,
1,
0.2568,
0.1081,
1,
0.24,
... | [
"__author__ = \"Vik Singh (viksi@yahoo-inc.com)\"",
"def strfix(msg):\n \"\"\"\n Copies this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523011\n Constants out any characters that spew encoding errors\n \"\"\"\n goodchars = {}\n try:\n return str(msg)",
" \"\"\"\n Copies this reci... |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["ysearch"]
| [
[
14,
0,
1,
0.25,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\"ysearch\"]"
] |
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
""" Dictionary to XML - Library to convert a python dictionary to XML output
Copyleft (C) 2007 Pianfetti Maurizio <boymix81@gmail.com>
Package site : http://boymix81.altervista.org/files/dict2xml.tar.gz
Revision 1.0 2007/12/15 11:57:20 Maurizio
- First stable version
"""
__author__ = "Pianfetti Maurizio <boymix81@gmail.com>"
__contributors__ = []
__date__ = "$Date: 2007/12/15 11:57:20 $"
__credits__ = """..."""
__version__ = "$Revision: 1.0.0 $"
class Dict2XML:
#XML output
xml = ""
#Tab level
level = 0
def __init__(self):
self.xml = ""
self.level = 0
#end def
def __del__(self):
pass
#end def
def setXml(self,Xml):
self.xml = Xml
#end if
def setLevel(self,Level):
self.level = Level
#end if
def dict2xml(self,map):
if (str(type(map)) == "<class 'object_dict.object_dict'>" or str(type(map)) == "<type 'dict'>"):
for key, value in map.items():
if (str(type(value)) == "<class 'object_dict.object_dict'>" or str(type(value)) == "<type 'dict'>"):
if(len(value) > 0):
self.xml += "\t"*self.level
self.xml += "<%s>\n" % (key)
self.level += 1
self.dict2xml(value)
self.level -= 1
self.xml += "\t"*self.level
self.xml += "</%s>\n" % (key)
else:
self.xml += "\t"*(self.level)
self.xml += "<%s></%s>\n" % (key,key)
#end if
else:
self.xml += "\t"*(self.level)
self.xml += "<%s>%s</%s>\n" % (key,value, key)
#end if
else:
self.xml += "\t"*self.level
self.xml += "<%s>%s</%s>\n" % (key,value, key)
#end if
return self.xml
#end def
#end class
def createXML(dict,xml):
xmlout = Dict2XML()
xmlout.setXml(xml)
return xmlout.dict2xml(dict)
#end def
dict2Xml = createXML
if __name__ == "__main__":
#Define the dict
d={}
d['root'] = {}
d['root']['v1'] = "";
d['root']['v2'] = "hi";
d['root']['v3'] = {};
d['root']['v3']['v31']="hi";
#xml='<?xml version="1.0"?>\n'
xml = ""
print dict2Xml(d,xml)
#end if | [
[
8,
0,
0.0798,
0.0851,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1383,
0.0106,
0,
0.66,
0.1111,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.1489,
0.0106,
0,
0.66... | [
"\"\"\" Dictionary to XML - Library to convert a python dictionary to XML output\n Copyleft (C) 2007 Pianfetti Maurizio <boymix81@gmail.com>\n Package site : http://boymix81.altervista.org/files/dict2xml.tar.gz\n\n Revision 1.0 2007/12/15 11:57:20 Maurizio\n - First stable version\n\n\"\"\"",
"__aut... |
#!/usr/local/bin/python25
# Thunder Chen<nkchenz@gmail.com> 2007.9.1
#
#
import xml.etree.ElementTree as ET
from object_dict import object_dict
def __parse_node(node):
tmp = object_dict()
# save attrs and text, hope there will not be a child with same name
if node.text:
tmp['value'] = node.text
for (k,v) in node.attrib.items():
tmp[k] = v
for ch in node.getchildren():
cht = ch.tag
chp = __parse_node(ch)
if cht not in tmp: # the first time, so store it in dict
tmp[cht] = chp
continue
old = tmp[cht]
if not isinstance(old, list):
tmp.pop(cht)
tmp[cht] = [old] # multi times, so change old dict to a list
tmp[cht].append(chp) # add the new one
return tmp
def parse(file):
"""parse a xml file to a dict"""
f = open(file, 'r')
t = ET.parse(f).getroot()
return object_dict({t.tag: __parse_node(t)})
def fromstring(s):
"""parse a string"""
t = ET.fromstring(s)
return object_dict({t.tag: __parse_node(t)})
if __name__ == '__main__':
s = """<?xml version="1.0" encoding="utf-8" ?>
<result>
<count n="1">10</count>
<data><id>491691</id><name>test</name></data>
<data><id>491692</id><name>test2</name></data>
<data><id>503938</id><name>hello, world</name></data>
</result>"""
r = fromstring(s)
import pprint
pprint.pprint(r)
print r.result.count.value
print r.result.count.n
for data in r.result.data:
print data.id, data.name
| [
[
1,
0,
0.0952,
0.0159,
0,
0.66,
0,
902,
0,
1,
0,
0,
902,
0,
0
],
[
1,
0,
0.1111,
0.0159,
0,
0.66,
0.2,
814,
0,
1,
0,
0,
814,
0,
0
],
[
2,
0,
0.3175,
0.3651,
0,
0.6... | [
"import xml.etree.ElementTree as ET",
"from object_dict import object_dict",
"def __parse_node(node):\n tmp = object_dict()\n # save attrs and text, hope there will not be a child with same name\n if node.text:\n tmp['value'] = node.text\n for (k,v) in node.attrib.items():\n tmp[k] = v... |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
""" Functions for downloading REST API's and converting their responses into dictionaries """
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
import logging
import xml2dict
from django.utils import simplejson
from google.appengine.api import urlfetch
HEADERS = {"User-Agent": simplejson.load(open("config.json", "r"))["agent"]}
def download(url):
result = urlfetch.fetch(url)
if result.status_code == 200:
return result.content
def load_json(url):
return simplejson.loads(download(url))
def load_xml(url):
return xml2dict.fromstring(download(url))
def load(url):
dl = download(url)
try:
return simplejson.loads(dl)
except:
return xml2dict.fromstring(dl)
| [
[
8,
0,
0.1515,
0.0303,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2121,
0.0303,
0,
0.66,
0.1,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2727,
0.0303,
0,
0.66,
... | [
"\"\"\" Functions for downloading REST API's and converting their responses into dictionaries \"\"\"",
"__author__ = \"Vik Singh (viksi@yahoo-inc.com)\"",
"import logging",
"import xml2dict",
"from django.utils import simplejson",
"from google.appengine.api import urlfetch",
"HEADERS = {\"User-Agent\": ... |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["dict2xml", "object_dict", "rest", "xml2dict"]
| [
[
14,
0,
1,
0.25,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\"dict2xml\", \"object_dict\", \"rest\", \"xml2dict\"]"
] |
# object_dict
# Thunder Chen<nkchenz@gmail.com> 2007
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
class object_dict(dict):
"""object view of dict, you can
>>> a = object_dict()
>>> a.fish = 'fish'
>>> a['fish']
'fish'
>>> a['water'] = 'water'
>>> a.water
'water'
>>> a.test = {'value': 1}
>>> a.test2 = object_dict({'name': 'test2', 'value': 2})
>>> a.test, a.test2.name, a.test2.value
(1, 'test2', 2)
"""
def __init__(self, initd=None):
if initd is None:
initd = {}
dict.__init__(self, initd)
def __getattr__(self, item):
d = self.__getitem__(item)
# if value is the only key in object, you can omit it
if isinstance(d, dict) and 'value' in d and len(d) == 1:
return d['value']
else:
return d
def __setattr__(self, item, value):
self.__setitem__(item, value)
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
| [
[
3,
0,
0.4634,
0.7073,
0,
0.66,
0,
814,
0,
3,
0,
0,
827,
0,
5
],
[
8,
1,
0.2927,
0.3171,
1,
0.1,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
1,
0.5,
0.0976,
1,
0.1,
0.33... | [
"class object_dict(dict):\n \"\"\"object view of dict, you can \n >>> a = object_dict()\n >>> a.fish = 'fish'\n >>> a['fish']\n 'fish'\n >>> a['water'] = 'water'\n >>> a.water",
" \"\"\"object view of dict, you can \n >>> a = object_dict()\n >>> a.fish = 'fish'\n >>> a['fish']\n ... |
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
""" Dictionary to XML - Library to convert a python dictionary to XML output
Copyleft (C) 2007 Pianfetti Maurizio <boymix81@gmail.com>
Package site : http://boymix81.altervista.org/files/dict2xml.tar.gz
Revision 1.0 2007/12/15 11:57:20 Maurizio
- First stable version
"""
__author__ = "Pianfetti Maurizio <boymix81@gmail.com>"
__contributors__ = []
__date__ = "$Date: 2007/12/15 11:57:20 $"
__credits__ = """..."""
__version__ = "$Revision: 1.0.0 $"
class Dict2XML:
#XML output
xml = ""
#Tab level
level = 0
def __init__(self):
self.xml = ""
self.level = 0
#end def
def __del__(self):
pass
#end def
def setXml(self,Xml):
self.xml = Xml
#end if
def setLevel(self,Level):
self.level = Level
#end if
def dict2xml(self,map):
if (str(type(map)) == "<class 'object_dict.object_dict'>" or str(type(map)) == "<type 'dict'>"):
for key, value in map.items():
if (str(type(value)) == "<class 'object_dict.object_dict'>" or str(type(value)) == "<type 'dict'>"):
if(len(value) > 0):
self.xml += "\t"*self.level
self.xml += "<%s>\n" % (key)
self.level += 1
self.dict2xml(value)
self.level -= 1
self.xml += "\t"*self.level
self.xml += "</%s>\n" % (key)
else:
self.xml += "\t"*(self.level)
self.xml += "<%s></%s>\n" % (key,key)
#end if
else:
self.xml += "\t"*(self.level)
self.xml += "<%s>%s</%s>\n" % (key,value, key)
#end if
else:
self.xml += "\t"*self.level
self.xml += "<%s>%s</%s>\n" % (key,value, key)
#end if
return self.xml
#end def
#end class
def createXML(dict,xml):
xmlout = Dict2XML()
xmlout.setXml(xml)
return xmlout.dict2xml(dict)
#end def
dict2Xml = createXML
if __name__ == "__main__":
#Define the dict
d={}
d['root'] = {}
d['root']['v1'] = "";
d['root']['v2'] = "hi";
d['root']['v3'] = {};
d['root']['v3']['v31']="hi";
#xml='<?xml version="1.0"?>\n'
xml = ""
print dict2Xml(d,xml)
#end if | [
[
8,
0,
0.0798,
0.0851,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1383,
0.0106,
0,
0.66,
0.1111,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.1489,
0.0106,
0,
0.66... | [
"\"\"\" Dictionary to XML - Library to convert a python dictionary to XML output\n Copyleft (C) 2007 Pianfetti Maurizio <boymix81@gmail.com>\n Package site : http://boymix81.altervista.org/files/dict2xml.tar.gz\n\n Revision 1.0 2007/12/15 11:57:20 Maurizio\n - First stable version\n\n\"\"\"",
"__aut... |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["boss", "crawl", "yql"]
| [
[
14,
0,
1,
0.25,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\"boss\", \"crawl\", \"yql\"]"
] |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
""" Some handy user defined functions to plug in db.select """
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
from util.typechecks import is_dict
def unnest_value(row):
"""
For data collections which have nested value parameters (like RSS)
this function will unnest the value to the higher level.
For example, say the row is {"title":{"value":"yahoo wins search"}}
This function will take that row and return the following row {"title": "yahoo wins search"}
"""
nr = {}
for k, v in row.iteritems():
if is_dict(type(v)) and "value" in v:
nr[k] = v["value"]
else:
nr[k] = v
return nr
| [
[
8,
0,
0.2083,
0.0417,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2917,
0.0417,
0,
0.66,
0.3333,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.375,
0.0417,
0,
0.66,
... | [
"\"\"\" Some handy user defined functions to plug in db.select \"\"\"",
"__author__ = \"Vik Singh (viksi@yahoo-inc.com)\"",
"from util.typechecks import is_dict",
"def unnest_value(row):\n \"\"\"\n For data collections which have nested value parameters (like RSS)\n this function will unnest the value to t... |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["asizeof", "db", "udfs"]
| [
[
14,
0,
1,
0.25,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\"asizeof\", \"db\", \"udfs\"]"
] |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
"""
Calculate the size of an object in python
This code used to be very complicated, and then realized in certain cases it failed
Given the structures handled in this framework, string'ing it and computing the length works fine
Especially since the # of bytes is not important - just need the relative sizes between objects
relsize is used to rank candidate collections of objects inferred from a REST response
The largest sized one wins
"""
__author__ = "Vik Singh (viksi@yahoo-inc)"
def relsize(o):
return len(str(o))
| [
[
8,
0,
0.5,
0.4706,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.8235,
0.0588,
0,
0.66,
0.5,
777,
1,
0,
0,
0,
0,
3,
0
],
[
2,
0,
0.9706,
0.1176,
0,
0.66,
1... | [
"\"\"\"\nCalculate the size of an object in python\nThis code used to be very complicated, and then realized in certain cases it failed\nGiven the structures handled in this framework, string'ing it and computing the length works fine\nEspecially since the # of bytes is not important - just need the relative sizes ... |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| [
[
1,
0,
0.1111,
0.037,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.6... | [
"import os",
"import subprocess",
"import sys",
"BASEDIR = '../main/src/com/joelapenna/foursquare'",
"TYPESDIR = '../captures/types/v1'",
"captures = sys.argv[1:]",
"if not captures:\n captures = os.listdir(TYPESDIR)",
" captures = os.listdir(TYPESDIR)",
"for f in captures:\n basename = f.split('... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| [
[
1,
0,
0.1111,
0.037,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.6... | [
"import os",
"import subprocess",
"import sys",
"BASEDIR = '../main/src/com/joelapenna/foursquare'",
"TYPESDIR = '../captures/types/v1'",
"captures = sys.argv[1:]",
"if not captures:\n captures = os.listdir(TYPESDIR)",
" captures = os.listdir(TYPESDIR)",
"for f in captures:\n basename = f.split('... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
#!/usr/bin/python
import sys, hashlib
def write_file(fn, buf):
fp = open(fn, "wb")
fp.write(buf)
fp.close()
def usage():
print ("Usage: " + sys.argv[0] + " infile outfile label")
def main():
if( len(sys.argv) != 4):
usage()
sys.exit()
fp = open( sys.argv[1] , "rb")
hash_str = hashlib.md5( fp.read() ).hexdigest()
fp.close()
out_str = "u8 " + sys.argv[3] + "[16] = { "
i=0
for str in hash_str:
if i % 2 == 0:
out_str += "0x" + str
else:
out_str += str
if i < 31:
out_str += ", "
i += 1
out_str += " };"
print out_str
write_file( sys.argv[2] , out_str )
if __name__ == "__main__":
main()
| [
[
1,
0,
0.0714,
0.0238,
0,
0.66,
0,
509,
0,
2,
0,
0,
509,
0,
0
],
[
2,
0,
0.1548,
0.0952,
0,
0.66,
0.25,
725,
0,
2,
0,
0,
0,
0,
3
],
[
14,
1,
0.1429,
0.0238,
1,
0.5... | [
"import sys, hashlib",
"def write_file(fn, buf):\n\tfp = open(fn, \"wb\")\n\tfp.write(buf)\n\tfp.close()",
"\tfp = open(fn, \"wb\")",
"\tfp.write(buf)",
"\tfp.close()",
"def usage():\n\tprint (\"Usage: \" + sys.argv[0] + \" infile outfile label\")",
"\tprint (\"Usage: \" + sys.argv[0] + \" infile outfi... |
#!/usr/bin/python
import sys, re, os
def write_file(fn, buf):
fp = open(fn, "wb")
fp.write(buf)
fp.close()
def usage():
print ("Usage: " + os.path.split(__file__)[1] + " version outfile")
def crete_version_str(ver):
base = list("0.00")
version = str(ver)
ret = []
base[0] = version[0]
base[2] = version[1]
base[3] = version[2]
ret.append("".join(base))
version = str(int(ver) + 1)
base[0] = version[0]
base[2] = version[1]
base[3] = version[2]
ret.append("".join(base))
return ret
def main():
if( len(sys.argv) != 3):
usage()
sys.exit()
if len( sys.argv[1]) != 3:
print sys.argv[1] + ":Version error."
sys.exit()
fp = open( os.path.dirname(os.path.abspath(__file__)) + "/update_base.sfo" , "rb")
sfo_buf = fp.read()
fp.close()
after_str = crete_version_str(sys.argv[1])
print "Target version:" + after_str[0]
sfo_buf = re.sub("X.YZ", after_str[0], sfo_buf )
sfo_buf = re.sub("Z.YX", after_str[1], sfo_buf )
write_file( sys.argv[2] , sfo_buf )
if __name__ == "__main__":
main()
| [
[
1,
0,
0.0577,
0.0192,
0,
0.66,
0,
509,
0,
3,
0,
0,
509,
0,
0
],
[
2,
0,
0.125,
0.0769,
0,
0.66,
0.2,
725,
0,
2,
0,
0,
0,
0,
3
],
[
14,
1,
0.1154,
0.0192,
1,
0.34,... | [
"import sys, re, os",
"def write_file(fn, buf):\n\tfp = open(fn, \"wb\")\n\tfp.write(buf)\n\tfp.close()",
"\tfp = open(fn, \"wb\")",
"\tfp.write(buf)",
"\tfp.close()",
"def usage():\n\tprint (\"Usage: \" + os.path.split(__file__)[1] + \" version outfile\")",
"\tprint (\"Usage: \" + os.path.split(__file... |
#!/usr/bin/python
""" PRO build script"""
import os, shutil, sys
NIGHTLY=0
VERSION="B9"
PRO_BUILD = [
{ "fn": "620PRO-%s.rar", "config": "CONFIG_620=1" },
{ "fn": "635PRO-%s.rar", "config": "CONFIG_635=1" },
{ "fn": "639PRO-%s.rar", "config": "CONFIG_639=1" },
{ "fn": "660PRO-%s.rar", "config": "CONFIG_660=1" },
# { "fn": "620PRO-%s.zip", "config": "CONFIG_620=1" },
# { "fn": "635PRO-%s.zip", "config": "CONFIG_635=1" },
# { "fn": "639PRO-%s.zip", "config": "CONFIG_639=1" },
# { "fn": "660PRO-%s.zip", "config": "CONFIG_660=1" },
# { "fn": "620PRO-%s.tar.gz", "config": "CONFIG_620=1" },
# { "fn": "635PRO-%s.tar.gz", "config": "CONFIG_635=1" },
# { "fn": "639PRO-%s.tar.gz", "config": "CONFIG_639=1" },
# { "fn": "660PRO-%s.tar.gz", "config": "CONFIG_660=1" },
# { "fn": "620PRO-%s.tar.bz2", "config": "CONFIG_620=1" },
# { "fn": "635PRO-%s.tar.bz2", "config": "CONFIG_635=1" },
# { "fn": "639PRO-%s.tar.bz2", "config": "CONFIG_639=1" },
# { "fn": "660PRO-%s.tar.bz2", "config": "CONFIG_660=1" },
]
OPT_FLAG = ""
def build_pro(build_conf):
global OPT_FLAG
if NIGHTLY:
build_conf += " " + "NIGHTLY=1"
build_conf += " " + OPT_FLAG
os.system("make clean %s" % (build_conf))
os.system("make deps %s" % (build_conf))
build_conf = "make " + build_conf
os.system(build_conf)
def copy_sdk():
try:
os.mkdir("dist/sdk")
os.mkdir("dist/sdk/lib")
os.mkdir("dist/sdk/include")
except OSError:
pass
shutil.copytree("kuBridgeTest", "dist/sdk/kuBridgeTest")
shutil.copy("include/kubridge.h", "dist/sdk/include")
shutil.copy("include/systemctrl.h", "dist/sdk/include")
shutil.copy("include/systemctrl_se.h", "dist/sdk/include")
shutil.copy("include/pspvshbridge.h", "dist/sdk/include")
shutil.copy("libs/libpspkubridge.a", "dist/sdk/lib")
shutil.copy("libs/libpspsystemctrl_kernel.a", "dist/sdk/lib")
shutil.copy("libs/libpspsystemctrl_user.a", "dist/sdk/lib")
def restore_chdir():
os.chdir(os.path.join(os.path.dirname(sys.argv[0]), ".."))
def make_archive(fn):
shutil.copy("credit.txt", "dist")
copy_sdk()
ext = os.path.splitext(fn)[-1].lower()
try:
os.remove(fn)
except OSError:
pass
path = os.getcwd()
os.chdir("dist");
if ext == ".rar":
os.system("rar a -r ../%s ." % (fn))
elif ext == ".gz":
os.system("tar -zcvf ../%s ." % (fn))
elif ext == ".bz2":
os.system("tar -jcvf ../%s ." % (fn))
elif ext == ".zip":
os.system("zip -r ../%s ." % (fn))
os.chdir(path)
def main():
global OPT_FLAG
OPT_FLAG = os.getenv("PRO_OPT_FLAG", "")
restore_chdir()
for conf in PRO_BUILD:
build_pro(conf["config"])
make_archive(conf["fn"] % (VERSION))
if __name__ == "__main__":
main()
| [
[
8,
0,
0.0297,
0.0099,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0495,
0.0099,
0,
0.66,
0.0909,
688,
0,
3,
0,
0,
688,
0,
0
],
[
14,
0,
0.0693,
0.0099,
0,
0.6... | [
"\"\"\" PRO build script\"\"\"",
"import os, shutil, sys",
"NIGHTLY=0",
"VERSION=\"B9\"",
"PRO_BUILD = [\n\t\t\t{ \"fn\": \"620PRO-%s.rar\", \"config\": \"CONFIG_620=1\" },\n\t\t\t{ \"fn\": \"635PRO-%s.rar\", \"config\": \"CONFIG_635=1\" },\n\t\t\t{ \"fn\": \"639PRO-%s.rar\", \"config\": \"CONFIG_639=1\" },... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.