code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
# -*- coding: utf-8 -*- ######################################################################### ## This scaffolding model makes your app work on Google App Engine too ## File is released under public domain and you can use without limitations ######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions ## (more options discussed in gluon/tools.py) ######################################################################### from gluon.tools import Auth, Crud, Service, PluginManager, prettydate auth = Auth(db) crud, service, plugins = Crud(db), Service(), PluginManager() ## create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False) ## configure email mail = auth.settings.mailer mail.settings.server = 'logging' or 'smtp.gmail.com:587' mail.settings.sender = 'you@gmail.com' mail.settings.login = 'username:password' ## configure auth policy auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True ## if you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc. ## register with janrain.com, write your domain:api_key in private/janrain.key from gluon.contrib.login_methods.rpx_account import use_janrain use_janrain(auth, filename='private/janrain.key') ######################################################################### ## Define your tables below (or better in another model file) for example ## ## >>> db.define_table('mytable',Field('myfield','string')) ## ## Fields can be 'string','text','password','integer','double','boolean' ## 'date','time','datetime','blob','upload', 'reference TABLENAME' ## There is an implicit 'id integer autoincrement' field ## Consult manual for more options, validators, etc. ## ## More API examples for controllers: ## ## >>> db.mytable.insert(myfield='value') ## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL) ## >>> for row in rows: print row.id, row.myfield ######################################################################### ## after defining tables, uncomment below to enable auditing # auth.enable_record_versioning(db)
[ [ 4, 0, 0.1867, 0.0964, 0, 0.66, 0, 0, 0, 0, 0, 0, 0, 0, 3 ], [ 14, 1, 0.1687, 0.012, 1, 0.44, 0, 761, 3, 3, 0, 0, 18, 10, 1 ], [ 14, 1, 0.2048, 0.012, 1, 0.44, ...
[ "if not request.env.web2py_runtime_gae:\n ## if NOT running on Google App Engine use SQLite or other DB\n db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all'])\nelse:\n ## connect to Google BigTable (optional 'google:datastore://namespace')\n db = DAL('google:datastore')\n ## store s...
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization ## - download is for downloading files uploaded in the db (does streaming) ## - call exposes all registered services (none by default) ######################################################################### def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simple replace the two lines below with: return auth.wiki() """ response.flash = T("Welcome to web2py!") return dict(message=T('Hello World')) def user(): """ exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control """ return dict(form=auth()) @cache.action() def download(): """ allows downloading of uploaded files http://..../[app]/default/download/[filename] """ return response.download(request, db) def call(): """ exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv """ return service() @auth.requires_signature() def data(): """ http://..../[app]/default/data/tables http://..../[app]/default/data/create/[table] http://..../[app]/default/data/read/[table]/[id] http://..../[app]/default/data/update/[table]/[id] http://..../[app]/default/data/delete/[table]/[id] http://..../[app]/default/data/select/[table] http://..../[app]/default/data/search/[table] but URLs must be signed, i.e. linked with A('table',_href=URL('data/tables',user_signature=True)) or with the signed load operator LOAD('default','data.load',args='tables',ajax=True,user_signature=True) """ return dict(form=crud())
[ [ 2, 0, 0.2303, 0.1316, 0, 0.66, 0, 780, 0, 0, 1, 0, 0, 0, 3 ], [ 8, 1, 0.2237, 0.0921, 1, 0.74, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.2763, 0.0132, 1, 0.74, ...
[ "def index():\n \"\"\"\n example action using the internationalization operator T and flash\n rendered by views/default/index.html or views/generic.html\n\n if you need a simple wiki simple replace the two lines below with:\n return auth.wiki()\n \"\"\"", " \"\"\"\n example action using th...
# -*- coding: utf-8 -*- # This is an app-specific example router # # This simple router is used for setting languages from app/languages directory # as a part of the application path: app/<lang>/controller/function # Language from default.py or 'en' (if the file is not found) is used as # a default_language # # See <web2py-root-dir>/router.example.py for parameter's detail #------------------------------------------------------------------------------------- # To enable this route file you must do the steps: # # 1. rename <web2py-root-dir>/router.example.py to routes.py # 2. rename this APP/routes.example.py to APP/routes.py # (where APP - is your application directory) # 3. restart web2py (or reload routes in web2py admin interfase) # # YOU CAN COPY THIS FILE TO ANY APLLICATION'S ROOT DIRECTORY WITHOUT CHANGES! from fileutils import abspath from languages import read_possible_languages possible_languages = read_possible_languages(abspath('applications', app)) #NOTE! app - is an application based router's parameter with name of an # application. E.g.'welcome' routers = { app: dict( default_language = possible_languages['default'][0], languages = [lang for lang in possible_languages if lang != 'default'] ) } #NOTE! To change language in your application using these rules add this line #in one of your models files: # if request.uri_language: T.force(request.uri_language)
[ [ 1, 0, 0.5526, 0.0263, 0, 0.66, 0, 687, 0, 1, 0, 0, 687, 0, 0 ], [ 1, 0, 0.5789, 0.0263, 0, 0.66, 0.3333, 126, 0, 1, 0, 0, 126, 0, 0 ], [ 14, 0, 0.6316, 0.0263, 0, ...
[ "from fileutils import abspath", "from languages import read_possible_languages", "possible_languages = read_possible_languages(abspath('applications', app))", "routers = {\n app: dict(\n default_language = possible_languages['default'][0],\n languages = [lang for lang in possible_languages\n...
#!/usr/bin/env python from setuptools import setup from gluon.fileutils import tar, untar, read_file, write_file import tarfile import sys def tar(file, filelist, expression='^.+$'): """ tars dir/files into file, only tars file that match expression """ tar = tarfile.TarFile(file, 'w') try: for element in filelist: try: for file in listdir(element, expression, add_dirs=True): tar.add(os.path.join(element, file), file, False) except: tar.add(element) finally: tar.close() def start(): if 'sdist' in sys.argv: tar('gluon/env.tar', ['applications', 'VERSION', 'splashlogo.gif']) setup(name='web2py', version=read_file("VERSION").split()[1], description="""full-stack framework for rapid development and prototyping of secure database-driven web-based applications, written and programmable in Python.""", long_description=""" Everything in one package with no dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface. web2py has no configuration files, requires no installation, can run off a USB drive. web2py uses Python for the Model, the Views and the Controllers, has a built-in ticketing system to manage errors, an internationalization engine, works with SQLite, PostgreSQL, MySQL, MSSQL, FireBird, Oracle, IBM DB2, Informix, Ingres, sybase and Google App Engine via a Database Abstraction Layer. web2py includes libraries to handle HTML/XML, RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI markup. Production ready, capable of upload/download streaming of very large files, and always backward compatible. """, author='Massimo Di Pierro', author_email='mdipierro@cs.depaul.edu', license='http://web2py.com/examples/default/license', classifiers=["Development Status :: 5 - Production/Stable"], url='http://web2py.com', platforms='Windows, Linux, Mac, Unix,Windows Mobile', packages=['gluon', 'gluon/contrib', 'gluon/contrib/gateways', 'gluon/contrib/login_methods', 'gluon/contrib/markdown', 'gluon/contrib/markmin', 'gluon/contrib/memcache', 'gluon/contrib/fpdf', 'gluon/contrib/pymysql', 'gluon/contrib/pyrtf', 'gluon/contrib/pysimplesoap', 'gluon/contrib/simplejson', 'gluon/tests', ], package_data={'gluon': ['env.tar']}, scripts=['w2p_apps', 'w2p_run', 'w2p_clone'], ) if __name__ == '__main__': #print "web2py does not require installation and" #print "you should just start it with:" #print #print "$ python web2py.py" #print #print "are you sure you want to install it anyway (y/n)?" #s = raw_input('>') #if s.lower()[:1]=='y': start()
[ [ 1, 0, 0.037, 0.0123, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0494, 0.0123, 0, 0.66, 0.1667, 948, 0, 4, 0, 0, 948, 0, 0 ], [ 1, 0, 0.0617, 0.0123, 0, 0...
[ "from setuptools import setup", "from gluon.fileutils import tar, untar, read_file, write_file", "import tarfile", "import sys", "def tar(file, filelist, expression='^.+$'):\n \"\"\"\n tars dir/files into file, only tars file that match expression\n \"\"\"\n\n tar = tarfile.TarFile(file, 'w')\n ...
""" web2py handler for isapi-wsgi for IIS. Requires: http://code.google.com/p/isapi-wsgi/ """ # The entry point for the ISAPI extension. def __ExtensionFactory__(): import os import sys path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] import gluon.main import isapi_wsgi application = gluon.main.wsgibase return isapi_wsgi.ISAPIThreadPoolHandler(application) # ISAPI installation: if __name__ == '__main__': import sys if len(sys.argv) < 2: print "USAGE: python isapiwsgihandler.py install --server=Sitename" sys.exit(0) from isapi.install import ISAPIParameters from isapi.install import ScriptMapParams from isapi.install import VirtualDirParameters from isapi.install import HandleCommandLine params = ISAPIParameters() sm = [ScriptMapParams(Extension="*", Flags=0)] vd = VirtualDirParameters(Name="appname", Description="Web2py in Python", ScriptMaps=sm, ScriptMapUpdate="replace") params.VirtualDirs = [vd] HandleCommandLine(params)
[ [ 8, 0, 0.0676, 0.1081, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.3378, 0.2703, 0, 0.66, 0.5, 892, 0, 0, 1, 0, 0, 0, 4 ], [ 1, 1, 0.2432, 0.027, 1, 0.87, ...
[ "\"\"\"\nweb2py handler for isapi-wsgi for IIS. Requires:\nhttp://code.google.com/p/isapi-wsgi/\n\"\"\"", "def __ExtensionFactory__():\n import os\n import sys\n path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(path)\n sys.path = [path] + [p for p in sys.path if not p == path]\n impo...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This is a CGI handler for Apache Requires apache+[mod_cgi or mod_cgid]. In httpd.conf put something like: LoadModule cgi_module modules/mod_cgi.so ScriptAlias / /path/to/cgihandler.py/ Example of httpd.conf ------------ <VirtualHost *:80> ServerName web2py.example.com ScriptAlias / /users/www-data/web2py/cgihandler.py/ <Directory /users/www-data/web2py> AllowOverride None Order Allow,Deny Deny from all <Files cgihandler.py> Allow from all </Files> </Directory> AliasMatch ^/([^/]+)/static/(.*) \ /users/www-data/web2py/applications/$1/static/$2 <Directory /users/www-data/web2py/applications/*/static/> Order Allow,Deny Allow from all </Directory> <Location /admin> Deny from all </Location> <LocationMatch ^/([^/]+)/appadmin> Deny from all </LocationMatch> CustomLog /private/var/log/apache2/access.log common ErrorLog /private/var/log/apache2/error.log </VirtualHost> ---------------------------------- """ import os import sys import wsgiref.handlers path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] import gluon.main wsgiref.handlers.CGIHandler().run(gluon.main.wsgibase)
[ [ 8, 0, 0.4365, 0.7619, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.8413, 0.0159, 0, 0.66, 0.125, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.8571, 0.0159, 0, 0.66,...
[ "\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nThis is a CGI handler for Apache\nRequires apache+[mod_cgi or mod_cgid].", "import os", "import sys", "import wsgiref.handlers", "pat...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Sropulpof is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s\n' % module for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, module, opts) toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) toc.append(subroot) elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
[ [ 8, 0, 0.093, 0.0194, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1085, 0.0039, 0, 0.66, 0.0588, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1124, 0.0039, 0, 0.66,...
[ "\"\"\"\nThis script parse a directory tree looking for python modules and packages and\ncreate ReST files appropriately to create code documentation with Sphinx.\nIt also create a modules index. \n\"\"\"", "import os", "import optparse", "options = ['members',\n 'undoc-members',\n# 'inh...
"""Convert a FAQ (AlterEgo) markdown dump into ReSt documents using pandoc **Todo** #. add titles #. add logging #. add CLI with optparse """ import os import sys import glob import subprocess import logging indir = 'faq_markdown' outdir = 'faq_rst' inpath = os.path.join('.', indir) outpath = os.path.join('.', outdir) pattern = inpath + '/*.txt' out_ext = 'rst' for file in glob.glob(pattern): infile = file file_basename = os.path.basename(file) outfile_name = os.path.splitext(file_basename)[0] + '.' + out_ext outfile = os.path.join(outpath, outfile_name) # pandoc -s -w rst --toc README -o example6.text logging.info("converting file %s to format <%s>" % (file_basename, out_ext)) convert_call = ["pandoc", "-s", "-w", out_ext, infile, "-o", outfile ] p = subprocess.call(convert_call) logging.info("Finshed!")
[ [ 8, 0, 0.0952, 0.1667, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.2381, 0.0238, 0, 0.66, 0.0769, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.2619, 0.0238, 0, 0.66...
[ "\"\"\"Convert a FAQ (AlterEgo) markdown dump into ReSt documents using pandoc\n\n**Todo**\n#. add titles\n#. add logging\n#. add CLI with optparse\n\"\"\"", "import os", "import sys", "import glob", "import subprocess", "import logging", "indir = 'faq_markdown'", "outdir = 'faq_rst'", "inpath = os....
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Sropulpof is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(package, module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s.%s\n' % (package, module) for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, package, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(package, module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ package_name = os.path.split(path)[-1] print 'package name', package_name toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, package_name, module, opts) if not check_for_code(os.path.join(path, module+'.py')): # don't build the file if there's no code in it pass else: toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) # FIXME: HERE THE __init__.py should go into the toc only if it contains # code! if not check_for_code(subroot): # don't build the file if there's no code in it continue toc.append(subroot) print 'here' elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) print 'hello' # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
[ [ 8, 0, 0.0886, 0.0185, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1033, 0.0037, 0, 0.66, 0.0588, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.107, 0.0037, 0, 0.66,...
[ "\"\"\"\nThis script parse a directory tree looking for python modules and packages and\ncreate ReST files appropriately to create code documentation with Sphinx.\nIt also create a modules index. \n\"\"\"", "import os", "import optparse", "options = ['members',\n 'undoc-members',\n# 'inh...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Sropulpof is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s\n' % module for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, module, opts) toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) toc.append(subroot) elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
[ [ 8, 0, 0.093, 0.0194, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1085, 0.0039, 0, 0.66, 0.0588, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1124, 0.0039, 0, 0.66,...
[ "\"\"\"\nThis script parse a directory tree looking for python modules and packages and\ncreate ReST files appropriately to create code documentation with Sphinx.\nIt also create a modules index. \n\"\"\"", "import os", "import optparse", "options = ['members',\n 'undoc-members',\n# 'inh...
import os import subprocess import codecs #--- BZR: changelog information def write_changelog_bzr(repo_path, output_dir, output_file='bzr_revision_log.txt', target_encoding='utf-8'): """Write the bzr changelog to a file which can then be included in the documentation """ bzr_logfile_path = os.path.join(output_dir, output_file) bzr_logfile = codecs.open(bzr_logfile_path, 'w', encoding=target_encoding) try: p_log = subprocess.Popen(('bzr log --short'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) (stdout, stderr) = p_log.communicate() bzr_logfile.write(stdout) finally: bzr_logfile.close() #UnicodeDecodeError: 'ascii' codec can't decode byte 0x81 in position 2871: ordinal not in range(128) # like bzr version-info --format python > vers_test.py #--- BZR: version info def write_version_info_bzr(repo_path, output_dir, output_file='_version.py'): """Write the version information from BZR repository into a version file. Parameters ---------- repo_path : string Path to the BZR repository root repo_path : string Path to the output directory where the version info is saved detail, e.g. ``(N,) ndarray`` or ``array_like``. output_file : string output file name Returns ------- p_info : subprocess_obj contents of the `func:`suprocess.Popen` returns """ bzr_version_filepath = os.path.join(output_dir, output_file) bzr_version_file = open(bzr_version_filepath, 'w') p_info = subprocess.Popen(('bzr version-info --format python'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) (stdout, stderr) = p_info.communicate() bzr_version_file.write(stdout) bzr_version_file.close() return p_info #--- auto generate documentation def autogenerate_package_doc(script_path, dest_dir, package_dir, doc_header, suffix='rst', overwrite=False): """Autogenerate package API ReSt documents """ print script_path if overwrite: force = '--force' p_apidoc = subprocess.Popen(('python', script_path, '--dest-dir='+dest_dir, '--suffix='+suffix, '--doc-header='+doc_header, force, package_dir), bufsize=-1) 'sphinxext\local\generate_modules_modif.py --dest-dir=source\contents\lib\auxilary\generated --suffix=rst --force --doc-header=Auxilary ..\..\modules_local\auxilary' return p_apidoc if __name__ == "__main__": repo_path = os.path.join('..', '.') output_dir = os.path.join('.') write_changelog_bzr(repo_path, output_dir, output_file='changelog.txt')
[ [ 1, 0, 0.0115, 0.0115, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.023, 0.0115, 0, 0.66, 0.1667, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.0345, 0.0115, 0, 0...
[ "import os", "import subprocess", "import codecs", "def write_changelog_bzr(repo_path, output_dir, \n output_file='bzr_revision_log.txt', \n target_encoding='utf-8'):\n \"\"\"Write the bzr changelog to a file which can then be in...
# # A pair of directives for inserting content that will only appear in # either html or latex. # from docutils.nodes import Body, Element from docutils.writers.html4css1 import HTMLTranslator try: from sphinx.latexwriter import LaTeXTranslator except ImportError: from sphinx.writers.latex import LaTeXTranslator import warnings warnings.warn("The numpydoc.only_directives module is deprecated;" "please use the only:: directive available in Sphinx >= 0.6", DeprecationWarning, stacklevel=2) from docutils.parsers.rst import directives class html_only(Body, Element): pass class latex_only(Body, Element): pass def run(content, node_class, state, content_offset): text = '\n'.join(content) node = node_class(text) state.nested_parse(content, content_offset, node) return [node] try: from docutils.parsers.rst import Directive except ImportError: from docutils.parsers.rst.directives import _directives def html_only_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(content, html_only, state, content_offset) def latex_only_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(content, latex_only, state, content_offset) for func in (html_only_directive, latex_only_directive): func.content = 1 func.options = {} func.arguments = None _directives['htmlonly'] = html_only_directive _directives['latexonly'] = latex_only_directive else: class OnlyDirective(Directive): has_content = True required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True option_spec = {} def run(self): self.assert_has_content() return run(self.content, self.node_class, self.state, self.content_offset) class HtmlOnlyDirective(OnlyDirective): node_class = html_only class LatexOnlyDirective(OnlyDirective): node_class = latex_only directives.register_directive('htmlonly', HtmlOnlyDirective) directives.register_directive('latexonly', LatexOnlyDirective) def setup(app): app.add_node(html_only) app.add_node(latex_only) # Add visit/depart methods to HTML-Translator: def visit_perform(self, node): pass def depart_perform(self, node): pass def visit_ignore(self, node): node.children = [] def depart_ignore(self, node): node.children = [] HTMLTranslator.visit_html_only = visit_perform HTMLTranslator.depart_html_only = depart_perform HTMLTranslator.visit_latex_only = visit_ignore HTMLTranslator.depart_latex_only = depart_ignore LaTeXTranslator.visit_html_only = visit_ignore LaTeXTranslator.depart_html_only = depart_ignore LaTeXTranslator.visit_latex_only = visit_perform LaTeXTranslator.depart_latex_only = depart_perform
[ [ 1, 0, 0.0625, 0.0104, 0, 0.66, 0, 127, 0, 2, 0, 0, 127, 0, 0 ], [ 1, 0, 0.0729, 0.0104, 0, 0.66, 0.125, 949, 0, 1, 0, 0, 949, 0, 0 ], [ 7, 0, 0.125, 0.0938, 0, 0....
[ "from docutils.nodes import Body, Element", "from docutils.writers.html4css1 import HTMLTranslator", "try:\n from sphinx.latexwriter import LaTeXTranslator\nexcept ImportError:\n from sphinx.writers.latex import LaTeXTranslator\n\n import warnings\n warnings.warn(\"The numpydoc.only_directives modul...
from cStringIO import StringIO import compiler import inspect import textwrap import tokenize from compiler_unparse import unparse class Comment(object): """ A comment block. """ is_comment = True def __init__(self, start_lineno, end_lineno, text): # int : The first line number in the block. 1-indexed. self.start_lineno = start_lineno # int : The last line number. Inclusive! self.end_lineno = end_lineno # str : The text block including '#' character but not any leading spaces. self.text = text def add(self, string, start, end, line): """ Add a new comment line. """ self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0]) self.text += string def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno, self.end_lineno, self.text) class NonComment(object): """ A non-comment block of code. """ is_comment = False def __init__(self, start_lineno, end_lineno): self.start_lineno = start_lineno self.end_lineno = end_lineno def add(self, string, start, end, line): """ Add lines to the block. """ if string.strip(): # Only add if not entirely whitespace. self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0]) def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno, self.end_lineno) class CommentBlocker(object): """ Pull out contiguous comment blocks. """ def __init__(self): # Start with a dummy. self.current_block = NonComment(0, 0) # All of the blocks seen so far. self.blocks = [] # The index mapping lines of code to their associated comment blocks. self.index = {} def process_file(self, file): """ Process a file object. """ for token in tokenize.generate_tokens(file.next): self.process_token(*token) self.make_index() def process_token(self, kind, string, start, end, line): """ Process a single token. """ if self.current_block.is_comment: if kind == tokenize.COMMENT: self.current_block.add(string, start, end, line) else: self.new_noncomment(start[0], end[0]) else: if kind == tokenize.COMMENT: self.new_comment(string, start, end, line) else: self.current_block.add(string, start, end, line) def new_noncomment(self, start_lineno, end_lineno): """ We are transitioning from a noncomment to a comment. """ block = NonComment(start_lineno, end_lineno) self.blocks.append(block) self.current_block = block def new_comment(self, string, start, end, line): """ Possibly add a new comment. Only adds a new comment if this comment is the only thing on the line. Otherwise, it extends the noncomment block. """ prefix = line[:start[1]] if prefix.strip(): # Oops! Trailing comment, not a comment block. self.current_block.add(string, start, end, line) else: # A comment block. block = Comment(start[0], end[0], string) self.blocks.append(block) self.current_block = block def make_index(self): """ Make the index mapping lines of actual code to their associated prefix comments. """ for prev, block in zip(self.blocks[:-1], self.blocks[1:]): if not block.is_comment: self.index[block.start_lineno] = prev def search_for_comment(self, lineno, default=None): """ Find the comment block just before the given line number. Returns None (or the specified default) if there is no such block. """ if not self.index: self.make_index() block = self.index.get(lineno, None) text = getattr(block, 'text', default) return text def strip_comment_marker(text): """ Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = textwrap.dedent('\n'.join(lines)) return text def get_class_traits(klass): """ Yield all of the documentation for trait definitions on a class object. """ # FIXME: gracefully handle errors here or in the caller? source = inspect.getsource(klass) cb = CommentBlocker() cb.process_file(StringIO(source)) mod_ast = compiler.parse(source) class_ast = mod_ast.node.nodes[0] for node in class_ast.code.nodes: # FIXME: handle other kinds of assignments? if isinstance(node, compiler.ast.Assign): name = node.nodes[0].name rhs = unparse(node.expr).strip() doc = strip_comment_marker(cb.search_for_comment(node.lineno, default='')) yield name, rhs, doc
[ [ 1, 0, 0.0063, 0.0063, 0, 0.66, 0, 764, 0, 1, 0, 0, 764, 0, 0 ], [ 1, 0, 0.0127, 0.0063, 0, 0.66, 0.1, 738, 0, 1, 0, 0, 738, 0, 0 ], [ 1, 0, 0.019, 0.0063, 0, 0.66...
[ "from cStringIO import StringIO", "import compiler", "import inspect", "import textwrap", "import tokenize", "from compiler_unparse import unparse", "class Comment(object):\n \"\"\" A comment block.\n \"\"\"\n is_comment = True\n def __init__(self, start_lineno, end_lineno, text):\n #...
from distutils.core import setup import setuptools import sys, os version = "0.2.dev" setup( name="numpydoc", packages=["numpydoc"], package_dir={"numpydoc": ""}, version=version, description="Sphinx extension to support docstrings in Numpy format", # classifiers from http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=["Development Status :: 3 - Alpha", "Environment :: Plugins", "License :: OSI Approved :: BSD License", "Topic :: Documentation"], keywords="sphinx numpy", author="Pauli Virtanen and others", author_email="pav@iki.fi", url="http://projects.scipy.org/numpy/browser/trunk/doc/sphinxext", license="BSD", zip_safe=False, install_requires=["Sphinx >= 0.5"], package_data={'numpydoc': 'tests'}, entry_points={ "console_scripts": [ "autosummary_generate = numpydoc.autosummary_generate:main", ], }, )
[ [ 1, 0, 0.0323, 0.0323, 0, 0.66, 0, 152, 0, 1, 0, 0, 152, 0, 0 ], [ 1, 0, 0.0645, 0.0323, 0, 0.66, 0.25, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0968, 0.0323, 0, 0....
[ "from distutils.core import setup", "import setuptools", "import sys, os", "version = \"0.2.dev\"", "setup(\n name=\"numpydoc\",\n packages=[\"numpydoc\"],\n package_dir={\"numpydoc\": \"\"},\n version=version,\n description=\"Sphinx extension to support docstrings in Numpy format\",\n # c...
""" Turn compiler.ast structures back into executable python code. The unparse method takes a compiler.ast tree and transforms it back into valid python code. It is incomplete and currently only works for import statements, function calls, function definitions, assignments, and basic expressions. Inspired by python-2.5-svn/Demo/parser/unparse.py fixme: We may want to move to using _ast trees because the compiler for them is about 6 times faster than compiler.compile. """ import sys import cStringIO from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add def unparse(ast, single_line_functions=False): s = cStringIO.StringIO() UnparseCompilerAst(ast, s, single_line_functions) return s.getvalue().lstrip() op_precedence = { 'compiler.ast.Power':3, 'compiler.ast.Mul':2, 'compiler.ast.Div':2, 'compiler.ast.Add':1, 'compiler.ast.Sub':1 } class UnparseCompilerAst: """ Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarged. """ ######################################################################### # object interface. ######################################################################### def __init__(self, tree, file = sys.stdout, single_line_functions=False): """ Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file. """ self.f = file self._single_func = single_line_functions self._do_indent = True self._indent = 0 self._dispatch(tree) self._write("\n") self.f.flush() ######################################################################### # Unparser private interface. ######################################################################### ### format, output, and dispatch methods ################################ def _fill(self, text = ""): "Indent a piece of text, according to the current indentation level" if self._do_indent: self._write("\n"+" "*self._indent + text) else: self._write(text) def _write(self, text): "Append a piece of text to the current line." self.f.write(text) def _enter(self): "Print ':', and increase the indentation." self._write(": ") self._indent += 1 def _leave(self): "Decrease the indentation level." self._indent -= 1 def _dispatch(self, tree): "_dispatcher function, _dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self._dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) if tree.__class__.__name__ == 'NoneType' and not self._do_indent: return meth(tree) ######################################################################### # compiler.ast unparsing methods. # # There should be one method per concrete grammar type. They are # organized in alphabetical order. ######################################################################### def _Add(self, t): self.__binary_op(t, '+') def _And(self, t): self._write(" (") for i, node in enumerate(t.nodes): self._dispatch(node) if i != len(t.nodes)-1: self._write(") and (") self._write(")") def _AssAttr(self, t): """ Handle assigning an attribute of an object """ self._dispatch(t.expr) self._write('.'+t.attrname) def _Assign(self, t): """ Expression Assignment such as "a = 1". This only handles assignment in expressions. Keyword assignment is handled separately. """ self._fill() for target in t.nodes: self._dispatch(target) self._write(" = ") self._dispatch(t.expr) if not self._do_indent: self._write('; ') def _AssName(self, t): """ Name on left hand side of expression. Treat just like a name on the right side of an expression. """ self._Name(t) def _AssTuple(self, t): """ Tuple on left hand side of an expression. """ # _write each elements, separated by a comma. for element in t.nodes[:-1]: self._dispatch(element) self._write(", ") # Handle the last one without writing comma last_element = t.nodes[-1] self._dispatch(last_element) def _AugAssign(self, t): """ +=,-=,*=,/=,**=, etc. operations """ self._fill() self._dispatch(t.node) self._write(' '+t.op+' ') self._dispatch(t.expr) if not self._do_indent: self._write(';') def _Bitand(self, t): """ Bit and operation. """ for i, node in enumerate(t.nodes): self._write("(") self._dispatch(node) self._write(")") if i != len(t.nodes)-1: self._write(" & ") def _Bitor(self, t): """ Bit or operation """ for i, node in enumerate(t.nodes): self._write("(") self._dispatch(node) self._write(")") if i != len(t.nodes)-1: self._write(" | ") def _CallFunc(self, t): """ Function call. """ self._dispatch(t.node) self._write("(") comma = False for e in t.args: if comma: self._write(", ") else: comma = True self._dispatch(e) if t.star_args: if comma: self._write(", ") else: comma = True self._write("*") self._dispatch(t.star_args) if t.dstar_args: if comma: self._write(", ") else: comma = True self._write("**") self._dispatch(t.dstar_args) self._write(")") def _Compare(self, t): self._dispatch(t.expr) for op, expr in t.ops: self._write(" " + op + " ") self._dispatch(expr) def _Const(self, t): """ A constant value such as an integer value, 3, or a string, "hello". """ self._dispatch(t.value) def _Decorators(self, t): """ Handle function decorators (eg. @has_units) """ for node in t.nodes: self._dispatch(node) def _Dict(self, t): self._write("{") for i, (k, v) in enumerate(t.items): self._dispatch(k) self._write(": ") self._dispatch(v) if i < len(t.items)-1: self._write(", ") self._write("}") def _Discard(self, t): """ Node for when return value is ignored such as in "foo(a)". """ self._fill() self._dispatch(t.expr) def _Div(self, t): self.__binary_op(t, '/') def _Ellipsis(self, t): self._write("...") def _From(self, t): """ Handle "from xyz import foo, bar as baz". """ # fixme: Are From and ImportFrom handled differently? self._fill("from ") self._write(t.modname) self._write(" import ") for i, (name,asname) in enumerate(t.names): if i != 0: self._write(", ") self._write(name) if asname is not None: self._write(" as "+asname) def _Function(self, t): """ Handle function definitions """ if t.decorators is not None: self._fill("@") self._dispatch(t.decorators) self._fill("def "+t.name + "(") defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults) for i, arg in enumerate(zip(t.argnames, defaults)): self._write(arg[0]) if arg[1] is not None: self._write('=') self._dispatch(arg[1]) if i < len(t.argnames)-1: self._write(', ') self._write(")") if self._single_func: self._do_indent = False self._enter() self._dispatch(t.code) self._leave() self._do_indent = True def _Getattr(self, t): """ Handle getting an attribute of an object """ if isinstance(t.expr, (Div, Mul, Sub, Add)): self._write('(') self._dispatch(t.expr) self._write(')') else: self._dispatch(t.expr) self._write('.'+t.attrname) def _If(self, t): self._fill() for i, (compare,code) in enumerate(t.tests): if i == 0: self._write("if ") else: self._write("elif ") self._dispatch(compare) self._enter() self._fill() self._dispatch(code) self._leave() self._write("\n") if t.else_ is not None: self._write("else") self._enter() self._fill() self._dispatch(t.else_) self._leave() self._write("\n") def _IfExp(self, t): self._dispatch(t.then) self._write(" if ") self._dispatch(t.test) if t.else_ is not None: self._write(" else (") self._dispatch(t.else_) self._write(")") def _Import(self, t): """ Handle "import xyz.foo". """ self._fill("import ") for i, (name,asname) in enumerate(t.names): if i != 0: self._write(", ") self._write(name) if asname is not None: self._write(" as "+asname) def _Keyword(self, t): """ Keyword value assignment within function calls and definitions. """ self._write(t.name) self._write("=") self._dispatch(t.expr) def _List(self, t): self._write("[") for i,node in enumerate(t.nodes): self._dispatch(node) if i < len(t.nodes)-1: self._write(", ") self._write("]") def _Module(self, t): if t.doc is not None: self._dispatch(t.doc) self._dispatch(t.node) def _Mul(self, t): self.__binary_op(t, '*') def _Name(self, t): self._write(t.name) def _NoneType(self, t): self._write("None") def _Not(self, t): self._write('not (') self._dispatch(t.expr) self._write(')') def _Or(self, t): self._write(" (") for i, node in enumerate(t.nodes): self._dispatch(node) if i != len(t.nodes)-1: self._write(") or (") self._write(")") def _Pass(self, t): self._write("pass\n") def _Printnl(self, t): self._fill("print ") if t.dest: self._write(">> ") self._dispatch(t.dest) self._write(", ") comma = False for node in t.nodes: if comma: self._write(', ') else: comma = True self._dispatch(node) def _Power(self, t): self.__binary_op(t, '**') def _Return(self, t): self._fill("return ") if t.value: if isinstance(t.value, Tuple): text = ', '.join([ name.name for name in t.value.asList() ]) self._write(text) else: self._dispatch(t.value) if not self._do_indent: self._write('; ') def _Slice(self, t): self._dispatch(t.expr) self._write("[") if t.lower: self._dispatch(t.lower) self._write(":") if t.upper: self._dispatch(t.upper) #if t.step: # self._write(":") # self._dispatch(t.step) self._write("]") def _Sliceobj(self, t): for i, node in enumerate(t.nodes): if i != 0: self._write(":") if not (isinstance(node, Const) and node.value is None): self._dispatch(node) def _Stmt(self, tree): for node in tree.nodes: self._dispatch(node) def _Sub(self, t): self.__binary_op(t, '-') def _Subscript(self, t): self._dispatch(t.expr) self._write("[") for i, value in enumerate(t.subs): if i != 0: self._write(",") self._dispatch(value) self._write("]") def _TryExcept(self, t): self._fill("try") self._enter() self._dispatch(t.body) self._leave() for handler in t.handlers: self._fill('except ') self._dispatch(handler[0]) if handler[1] is not None: self._write(', ') self._dispatch(handler[1]) self._enter() self._dispatch(handler[2]) self._leave() if t.else_: self._fill("else") self._enter() self._dispatch(t.else_) self._leave() def _Tuple(self, t): if not t.nodes: # Empty tuple. self._write("()") else: self._write("(") # _write each elements, separated by a comma. for element in t.nodes[:-1]: self._dispatch(element) self._write(", ") # Handle the last one without writing comma last_element = t.nodes[-1] self._dispatch(last_element) self._write(")") def _UnaryAdd(self, t): self._write("+") self._dispatch(t.expr) def _UnarySub(self, t): self._write("-") self._dispatch(t.expr) def _With(self, t): self._fill('with ') self._dispatch(t.expr) if t.vars: self._write(' as ') self._dispatch(t.vars.name) self._enter() self._dispatch(t.body) self._leave() self._write('\n') def _int(self, t): self._write(repr(t)) def __binary_op(self, t, symbol): # Check if parenthesis are needed on left side and then dispatch has_paren = False left_class = str(t.left.__class__) if (left_class in op_precedence.keys() and op_precedence[left_class] < op_precedence[str(t.__class__)]): has_paren = True if has_paren: self._write('(') self._dispatch(t.left) if has_paren: self._write(')') # Write the appropriate symbol for operator self._write(symbol) # Check if parenthesis are needed on the right side and then dispatch has_paren = False right_class = str(t.right.__class__) if (right_class in op_precedence.keys() and op_precedence[right_class] < op_precedence[str(t.__class__)]): has_paren = True if has_paren: self._write('(') self._dispatch(t.right) if has_paren: self._write(')') def _float(self, t): # if t is 0.1, str(t)->'0.1' while repr(t)->'0.1000000000001' # We prefer str here. self._write(str(t)) def _str(self, t): self._write(repr(t)) def _tuple(self, t): self._write(str(t)) ######################################################################### # These are the methods from the _ast modules unparse. # # As our needs to handle more advanced code increase, we may want to # modify some of the methods below so that they work for compiler.ast. ######################################################################### # # stmt # def _Expr(self, tree): # self._fill() # self._dispatch(tree.value) # # def _Import(self, t): # self._fill("import ") # first = True # for a in t.names: # if first: # first = False # else: # self._write(", ") # self._write(a.name) # if a.asname: # self._write(" as "+a.asname) # ## def _ImportFrom(self, t): ## self._fill("from ") ## self._write(t.module) ## self._write(" import ") ## for i, a in enumerate(t.names): ## if i == 0: ## self._write(", ") ## self._write(a.name) ## if a.asname: ## self._write(" as "+a.asname) ## # XXX(jpe) what is level for? ## # # def _Break(self, t): # self._fill("break") # # def _Continue(self, t): # self._fill("continue") # # def _Delete(self, t): # self._fill("del ") # self._dispatch(t.targets) # # def _Assert(self, t): # self._fill("assert ") # self._dispatch(t.test) # if t.msg: # self._write(", ") # self._dispatch(t.msg) # # def _Exec(self, t): # self._fill("exec ") # self._dispatch(t.body) # if t.globals: # self._write(" in ") # self._dispatch(t.globals) # if t.locals: # self._write(", ") # self._dispatch(t.locals) # # def _Print(self, t): # self._fill("print ") # do_comma = False # if t.dest: # self._write(">>") # self._dispatch(t.dest) # do_comma = True # for e in t.values: # if do_comma:self._write(", ") # else:do_comma=True # self._dispatch(e) # if not t.nl: # self._write(",") # # def _Global(self, t): # self._fill("global") # for i, n in enumerate(t.names): # if i != 0: # self._write(",") # self._write(" " + n) # # def _Yield(self, t): # self._fill("yield") # if t.value: # self._write(" (") # self._dispatch(t.value) # self._write(")") # # def _Raise(self, t): # self._fill('raise ') # if t.type: # self._dispatch(t.type) # if t.inst: # self._write(", ") # self._dispatch(t.inst) # if t.tback: # self._write(", ") # self._dispatch(t.tback) # # # def _TryFinally(self, t): # self._fill("try") # self._enter() # self._dispatch(t.body) # self._leave() # # self._fill("finally") # self._enter() # self._dispatch(t.finalbody) # self._leave() # # def _excepthandler(self, t): # self._fill("except ") # if t.type: # self._dispatch(t.type) # if t.name: # self._write(", ") # self._dispatch(t.name) # self._enter() # self._dispatch(t.body) # self._leave() # # def _ClassDef(self, t): # self._write("\n") # self._fill("class "+t.name) # if t.bases: # self._write("(") # for a in t.bases: # self._dispatch(a) # self._write(", ") # self._write(")") # self._enter() # self._dispatch(t.body) # self._leave() # # def _FunctionDef(self, t): # self._write("\n") # for deco in t.decorators: # self._fill("@") # self._dispatch(deco) # self._fill("def "+t.name + "(") # self._dispatch(t.args) # self._write(")") # self._enter() # self._dispatch(t.body) # self._leave() # # def _For(self, t): # self._fill("for ") # self._dispatch(t.target) # self._write(" in ") # self._dispatch(t.iter) # self._enter() # self._dispatch(t.body) # self._leave() # if t.orelse: # self._fill("else") # self._enter() # self._dispatch(t.orelse) # self._leave # # def _While(self, t): # self._fill("while ") # self._dispatch(t.test) # self._enter() # self._dispatch(t.body) # self._leave() # if t.orelse: # self._fill("else") # self._enter() # self._dispatch(t.orelse) # self._leave # # # expr # def _Str(self, tree): # self._write(repr(tree.s)) ## # def _Repr(self, t): # self._write("`") # self._dispatch(t.value) # self._write("`") # # def _Num(self, t): # self._write(repr(t.n)) # # def _ListComp(self, t): # self._write("[") # self._dispatch(t.elt) # for gen in t.generators: # self._dispatch(gen) # self._write("]") # # def _GeneratorExp(self, t): # self._write("(") # self._dispatch(t.elt) # for gen in t.generators: # self._dispatch(gen) # self._write(")") # # def _comprehension(self, t): # self._write(" for ") # self._dispatch(t.target) # self._write(" in ") # self._dispatch(t.iter) # for if_clause in t.ifs: # self._write(" if ") # self._dispatch(if_clause) # # def _IfExp(self, t): # self._dispatch(t.body) # self._write(" if ") # self._dispatch(t.test) # if t.orelse: # self._write(" else ") # self._dispatch(t.orelse) # # unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} # def _UnaryOp(self, t): # self._write(self.unop[t.op.__class__.__name__]) # self._write("(") # self._dispatch(t.operand) # self._write(")") # # binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", # "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&", # "FloorDiv":"//", "Pow": "**"} # def _BinOp(self, t): # self._write("(") # self._dispatch(t.left) # self._write(")" + self.binop[t.op.__class__.__name__] + "(") # self._dispatch(t.right) # self._write(")") # # boolops = {_ast.And: 'and', _ast.Or: 'or'} # def _BoolOp(self, t): # self._write("(") # self._dispatch(t.values[0]) # for v in t.values[1:]: # self._write(" %s " % self.boolops[t.op.__class__]) # self._dispatch(v) # self._write(")") # # def _Attribute(self,t): # self._dispatch(t.value) # self._write(".") # self._write(t.attr) # ## def _Call(self, t): ## self._dispatch(t.func) ## self._write("(") ## comma = False ## for e in t.args: ## if comma: self._write(", ") ## else: comma = True ## self._dispatch(e) ## for e in t.keywords: ## if comma: self._write(", ") ## else: comma = True ## self._dispatch(e) ## if t.starargs: ## if comma: self._write(", ") ## else: comma = True ## self._write("*") ## self._dispatch(t.starargs) ## if t.kwargs: ## if comma: self._write(", ") ## else: comma = True ## self._write("**") ## self._dispatch(t.kwargs) ## self._write(")") # # # slice # def _Index(self, t): # self._dispatch(t.value) # # def _ExtSlice(self, t): # for i, d in enumerate(t.dims): # if i != 0: # self._write(': ') # self._dispatch(d) # # # others # def _arguments(self, t): # first = True # nonDef = len(t.args)-len(t.defaults) # for a in t.args[0:nonDef]: # if first:first = False # else: self._write(", ") # self._dispatch(a) # for a,d in zip(t.args[nonDef:], t.defaults): # if first:first = False # else: self._write(", ") # self._dispatch(a), # self._write("=") # self._dispatch(d) # if t.vararg: # if first:first = False # else: self._write(", ") # self._write("*"+t.vararg) # if t.kwarg: # if first:first = False # else: self._write(", ") # self._write("**"+t.kwarg) # ## def _keyword(self, t): ## self._write(t.arg) ## self._write("=") ## self._dispatch(t.value) # # def _Lambda(self, t): # self._write("lambda ") # self._dispatch(t.args) # self._write(": ") # self._dispatch(t.body)
[ [ 8, 0, 0.0076, 0.014, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0163, 0.0012, 0, 0.66, 0.1667, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0174, 0.0012, 0, 0.66,...
[ "\"\"\" Turn compiler.ast structures back into executable python code.\n\n The unparse method takes a compiler.ast tree and transforms it back into\n valid python code. It is incomplete and currently only works for\n import statements, function calls, function definitions, assignments, and\n basic expr...
""" ============== phantom_import ============== Sphinx extension to make directives from ``sphinx.ext.autodoc`` and similar extensions to use docstrings loaded from an XML file. This extension loads an XML file in the Pydocweb format [1] and creates a dummy module that contains the specified docstrings. This can be used to get the current docstrings from a Pydocweb instance without needing to rebuild the documented module. .. [1] http://code.google.com/p/pydocweb """ import imp, sys, compiler, types, os, inspect, re def setup(app): app.connect('builder-inited', initialize) app.add_config_value('phantom_import_file', None, True) def initialize(app): fn = app.config.phantom_import_file if (fn and os.path.isfile(fn)): print "[numpydoc] Phantom importing modules from", fn, "..." import_phantom_module(fn) #------------------------------------------------------------------------------ # Creating 'phantom' modules from an XML description #------------------------------------------------------------------------------ def import_phantom_module(xml_file): """ Insert a fake Python module to sys.modules, based on a XML file. The XML file is expected to conform to Pydocweb DTD. The fake module will contain dummy objects, which guarantee the following: - Docstrings are correct. - Class inheritance relationships are correct (if present in XML). - Function argspec is *NOT* correct (even if present in XML). Instead, the function signature is prepended to the function docstring. - Class attributes are *NOT* correct; instead, they are dummy objects. Parameters ---------- xml_file : str Name of an XML file to read """ import lxml.etree as etree object_cache = {} tree = etree.parse(xml_file) root = tree.getroot() # Sort items so that # - Base classes come before classes inherited from them # - Modules come before their contents all_nodes = dict([(n.attrib['id'], n) for n in root]) def _get_bases(node, recurse=False): bases = [x.attrib['ref'] for x in node.findall('base')] if recurse: j = 0 while True: try: b = bases[j] except IndexError: break if b in all_nodes: bases.extend(_get_bases(all_nodes[b])) j += 1 return bases type_index = ['module', 'class', 'callable', 'object'] def base_cmp(a, b): x = cmp(type_index.index(a.tag), type_index.index(b.tag)) if x != 0: return x if a.tag == 'class' and b.tag == 'class': a_bases = _get_bases(a, recurse=True) b_bases = _get_bases(b, recurse=True) x = cmp(len(a_bases), len(b_bases)) if x != 0: return x if a.attrib['id'] in b_bases: return -1 if b.attrib['id'] in a_bases: return 1 return cmp(a.attrib['id'].count('.'), b.attrib['id'].count('.')) nodes = root.getchildren() nodes.sort(base_cmp) # Create phantom items for node in nodes: name = node.attrib['id'] doc = (node.text or '').decode('string-escape') + "\n" if doc == "\n": doc = "" # create parent, if missing parent = name while True: parent = '.'.join(parent.split('.')[:-1]) if not parent: break if parent in object_cache: break obj = imp.new_module(parent) object_cache[parent] = obj sys.modules[parent] = obj # create object if node.tag == 'module': obj = imp.new_module(name) obj.__doc__ = doc sys.modules[name] = obj elif node.tag == 'class': bases = [object_cache[b] for b in _get_bases(node) if b in object_cache] bases.append(object) init = lambda self: None init.__doc__ = doc obj = type(name, tuple(bases), {'__doc__': doc, '__init__': init}) obj.__name__ = name.split('.')[-1] elif node.tag == 'callable': funcname = node.attrib['id'].split('.')[-1] argspec = node.attrib.get('argspec') if argspec: argspec = re.sub('^[^(]*', '', argspec) doc = "%s%s\n\n%s" % (funcname, argspec, doc) obj = lambda: 0 obj.__argspec_is_invalid_ = True obj.func_name = funcname obj.__name__ = name obj.__doc__ = doc if inspect.isclass(object_cache[parent]): obj.__objclass__ = object_cache[parent] else: class Dummy(object): pass obj = Dummy() obj.__name__ = name obj.__doc__ = doc if inspect.isclass(object_cache[parent]): obj.__get__ = lambda: None object_cache[name] = obj if parent: if inspect.ismodule(object_cache[parent]): obj.__module__ = parent setattr(object_cache[parent], name.split('.')[-1], obj) # Populate items for node in root: obj = object_cache.get(node.attrib['id']) if obj is None: continue for ref in node.findall('ref'): if node.tag == 'class': if ref.attrib['ref'].startswith(node.attrib['id'] + '.'): setattr(obj, ref.attrib['name'], object_cache.get(ref.attrib['ref'])) else: setattr(obj, ref.attrib['name'], object_cache.get(ref.attrib['ref']))
[ [ 8, 0, 0.0525, 0.0988, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1049, 0.0062, 0, 0.66, 0.25, 201, 0, 7, 0, 0, 201, 0, 0 ], [ 2, 0, 0.1235, 0.0185, 0, 0.66, ...
[ "\"\"\"\n==============\nphantom_import\n==============\n\nSphinx extension to make directives from ``sphinx.ext.autodoc`` and similar\nextensions to use docstrings loaded from an XML file.", "import imp, sys, compiler, types, os, inspect, re", "def setup(app):\n app.connect('builder-inited', initialize)\n ...
from numpydoc import setup
[ [ 1, 0, 1, 1, 0, 0.66, 0, 32, 0, 1, 0, 0, 32, 0, 0 ] ]
[ "from numpydoc import setup" ]
import re, inspect, textwrap, pydoc import sphinx from docscrape import NumpyDocString, FunctionDoc, ClassDoc class SphinxDocString(NumpyDocString): # string conversion routines def _str_header(self, name, symbol='`'): return ['.. rubric:: ' + name, ''] def _str_field_list(self, name): return [':' + name + ':'] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): return [''] if self['Signature']: return ['``%s``' % self['Signature']] + [''] else: return [''] def _str_summary(self): return self['Summary'] + [''] def _str_extended_summary(self): return self['Extended Summary'] + [''] def _str_param_list(self, name): out = [] if self[name]: out += self._str_field_list(name) out += [''] for param,param_type,desc in self[name]: out += self._str_indent(['**%s** : %s' % (param.strip(), param_type)]) out += [''] out += self._str_indent(desc,8) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += [''] content = textwrap.dedent("\n".join(self[name])).split("\n") out += content out += [''] return out def _str_see_also(self, func_role): out = [] if self['See Also']: see_also = super(SphinxDocString, self)._str_see_also(func_role) out = ['.. seealso::', ''] out += self._str_indent(see_also[2:]) return out def _str_warnings(self): out = [] if self['Warnings']: out = ['.. warning::', ''] out += self._str_indent(self['Warnings']) return out def _str_index(self): idx = self['index'] out = [] if len(idx) == 0: return out out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.iteritems(): if section == 'default': continue elif section == 'refguide': out += [' single: %s' % (', '.join(references))] else: out += [' %s: %s' % (section, ','.join(references))] return out def _str_references(self): out = [] if self['References']: out += self._str_header('References') if isinstance(self['References'], str): self['References'] = [self['References']] out.extend(self['References']) out += [''] # Latex collects all references to a separate bibliography, # so we need to insert links to it if sphinx.__version__ >= 0.6: out += ['.. only:: latex',''] else: out += ['.. latexonly::',''] items = [] for line in self['References']: m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] return out def __str__(self, indent=0, func_role="obj"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Attributes', 'Methods', 'Returns','Raises'): out += self._str_param_list(param_list) out += self._str_warnings() out += self._str_see_also(func_role) out += self._str_section('Notes') out += self._str_references() out += self._str_section('Examples') out = self._str_indent(out,indent) return '\n'.join(out) class SphinxFunctionDoc(SphinxDocString, FunctionDoc): pass class SphinxClassDoc(SphinxDocString, ClassDoc): pass def get_doc_object(obj, what=None, doc=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif callable(obj): what = 'function' else: what = 'object' if what == 'class': return SphinxClassDoc(obj, '', func_doc=SphinxFunctionDoc, doc=doc) elif what in ('function', 'method'): return SphinxFunctionDoc(obj, '', doc=doc) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxDocString(doc)
[ [ 1, 0, 0.0067, 0.0067, 0, 0.66, 0, 540, 0, 4, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0134, 0.0067, 0, 0.66, 0.1667, 522, 0, 1, 0, 0, 522, 0, 0 ], [ 1, 0, 0.0201, 0.0067, 0, ...
[ "import re, inspect, textwrap, pydoc", "import sphinx", "from docscrape import NumpyDocString, FunctionDoc, ClassDoc", "class SphinxDocString(NumpyDocString):\n # string conversion routines\n def _str_header(self, name, symbol='`'):\n return ['.. rubric:: ' + name, '']\n\n def _str_field_list(...
""" ======== numpydoc ======== Sphinx extension that handles docstrings in the Numpy standard format. [1] It will: - Convert Parameters etc. sections to field lists. - Convert See Also section to a See also entry. - Renumber references. - Extract the signature from the docstring, if it can't be determined otherwise. .. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard """ import os, re, pydoc from docscrape_sphinx import get_doc_object, SphinxDocString import inspect def mangle_docstrings(app, what, name, obj, options, lines, reference_offset=[0]): if what == 'module': # Strip top title title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*', re.I|re.S) lines[:] = title_re.sub('', "\n".join(lines)).split("\n") else: doc = get_doc_object(obj, what, "\n".join(lines)) lines[:] = str(doc).split("\n") if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \ obj.__name__: if hasattr(obj, '__module__'): v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__)) else: v = dict(full_name=obj.__name__) lines += ['', '.. htmlonly::', ''] lines += [' %s' % x for x in (app.config.numpydoc_edit_link % v).split("\n")] # replace reference numbers so that there are no duplicates references = [] for line in lines: line = line.strip() m = re.match(r'^.. \[([a-z0-9_.-])\]', line, re.I) if m: references.append(m.group(1)) # start renaming from the longest string, to avoid overwriting parts references.sort(key=lambda x: -len(x)) if references: for i, line in enumerate(lines): for r in references: if re.match(r'^\d+$', r): new_r = "R%d" % (reference_offset[0] + int(r)) else: new_r = "%s%d" % (r, reference_offset[0]) lines[i] = lines[i].replace('[%s]_' % r, '[%s]_' % new_r) lines[i] = lines[i].replace('.. [%s]' % r, '.. [%s]' % new_r) reference_offset[0] += len(references) def mangle_signature(app, what, name, obj, options, sig, retann): # Do not try to inspect classes that don't define `__init__` if (inspect.isclass(obj) and 'initializes x; see ' in pydoc.getdoc(obj.__init__)): return '', '' if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): return if not hasattr(obj, '__doc__'): return doc = SphinxDocString(pydoc.getdoc(obj)) if doc['Signature']: sig = re.sub("^[^(]*", "", doc['Signature']) return sig, '' def initialize(app): try: app.connect('autodoc-process-signature', mangle_signature) except: monkeypatch_sphinx_ext_autodoc() def setup(app, get_doc_object_=get_doc_object): global get_doc_object get_doc_object = get_doc_object_ app.connect('autodoc-process-docstring', mangle_docstrings) app.connect('builder-inited', initialize) app.add_config_value('numpydoc_edit_link', None, True) #------------------------------------------------------------------------------ # Monkeypatch sphinx.ext.autodoc to accept argspecless autodocs (Sphinx < 0.5) #------------------------------------------------------------------------------ def monkeypatch_sphinx_ext_autodoc(): global _original_format_signature import sphinx.ext.autodoc if sphinx.ext.autodoc.format_signature is our_format_signature: return print "[numpydoc] Monkeypatching sphinx.ext.autodoc ..." _original_format_signature = sphinx.ext.autodoc.format_signature sphinx.ext.autodoc.format_signature = our_format_signature def our_format_signature(what, obj): r = mangle_signature(None, what, None, obj, None, None, None) if r is not None: return r[0] else: return _original_format_signature(what, obj)
[ [ 8, 0, 0.0769, 0.1453, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1624, 0.0085, 0, 0.66, 0.1111, 688, 0, 3, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1709, 0.0085, 0, 0.66...
[ "\"\"\"\n========\nnumpydoc\n========\n\nSphinx extension that handles docstrings in the Numpy standard format. [1]\n\nIt will:", "import os, re, pydoc", "from docscrape_sphinx import get_doc_object, SphinxDocString", "import inspect", "def mangle_docstrings(app, what, name, obj, options, lines,\n ...
# -*- coding: utf-8 -*- # default_application, default_controller, default_function # are used when the respective element is missing from the # (possibly rewritten) incoming URL # default_application = 'init' # ordinarily set in base routes.py default_controller = 'default' # ordinarily set in app-specific routes.py default_function = 'index' # ordinarily set in app-specific routes.py # routes_app is a tuple of tuples. The first item in each is a regexp that will # be used to match the incoming request URL. The second item in the tuple is # an applicationname. This mechanism allows you to specify the use of an # app-specific routes.py. This entry is meaningful only in the base routes.py. # # Example: support welcome, admin, app and myapp, with myapp the default: routes_app = ((r'/(?P<app>welcome|admin|app)\b.*', r'\g<app>'), (r'(.*)', r'myapp'), (r'/?(.*)', r'myapp')) # routes_in is a tuple of tuples. The first item in each is a regexp that will # be used to match the incoming request URL. The second item in the tuple is # what it will be replaced with. This mechanism allows you to redirect incoming # routes to different web2py locations # # Example: If you wish for your entire website to use init's static directory: # # routes_in=( (r'/static/(?P<file>[\w./-]+)', r'/init/static/\g<file>') ) # BASE = '' # optonal prefix for incoming URLs routes_in = ( # do not reroute admin unless you want to disable it (BASE + '/admin', '/admin/default/index'), (BASE + '/admin/$anything', '/admin/$anything'), # do not reroute appadmin unless you want to disable it (BASE + '/$app/appadmin', '/$app/appadmin/index'), (BASE + '/$app/appadmin/$anything', '/$app/appadmin/$anything'), # do not reroute static files (BASE + '/$app/static/$anything', '/$app/static/$anything'), # reroute favicon and robots, use exable for lack of better choice ('/favicon.ico', '/examples/static/favicon.ico'), ('/robots.txt', '/examples/static/robots.txt'), # do other stuff ((r'.*http://otherdomain.com.* (?P<any>.*)', r'/app/ctr\g<any>')), # remove the BASE prefix (BASE + '/$anything', '/$anything'), ) # routes_out, like routes_in translates URL paths created with the web2py URL() # function in the same manner that route_in translates inbound URL paths. # routes_out = ( # do not reroute admin unless you want to disable it ('/admin/$anything', BASE + '/admin/$anything'), # do not reroute appadmin unless you want to disable it ('/$app/appadmin/$anything', BASE + '/$app/appadmin/$anything'), # do not reroute static files ('/$app/static/$anything', BASE + '/$app/static/$anything'), # do other stuff (r'.*http://otherdomain.com.* /app/ctr(?P<any>.*)', r'\g<any>'), (r'/app(?P<any>.*)', r'\g<any>'), # restore the BASE prefix ('/$anything', BASE + '/$anything'), ) # Specify log level for rewrite's debug logging # Possible values: debug, info, warning, error, critical (loglevels), # off, print (print uses print statement rather than logging) # GAE users may want to use 'off' to suppress routine logging. # logging = 'debug' # Error-handling redirects all HTTP errors (status codes >= 400) to a specified # path. If you wish to use error-handling redirects, uncomment the tuple # below. You can customize responses by adding a tuple entry with the first # value in 'appName/HTTPstatusCode' format. ( Only HTTP codes >= 400 are # routed. ) and the value as a path to redirect the user to. You may also use # '*' as a wildcard. # # The error handling page is also passed the error code and ticket as # variables. Traceback information will be stored in the ticket. # # routes_onerror = [ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] # specify action in charge of error handling # # error_handler = dict(application='error', # controller='default', # function='index') # In the event that the error-handling page itself returns an error, web2py will # fall back to its old static responses. You can customize them here. # ErrorMessageTicket takes a string format dictionary containing (only) the # "ticket" key. # error_message = '<html><body><h1>%s</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href="/admin/default/ticket/%(ticket)s" target="_blank">%(ticket)s</a></body></html>' # specify a list of apps that bypass args-checking and use request.raw_args # #routes_apps_raw=['myapp'] #routes_apps_raw=['myapp', 'myotherapp'] def __routes_doctest(): ''' Dummy function for doctesting routes.py. Use filter_url() to test incoming or outgoing routes; filter_err() for error redirection. filter_url() accepts overrides for method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application and ticket: filter_err(status, application='app', ticket='tkt') >>> import os >>> import gluon.main >>> from gluon.rewrite import regex_select, load, filter_url, regex_filter_out, filter_err, compile_regex >>> regex_select() >>> load(routes=os.path.basename(__file__)) >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/examples/static/favicon.ico' >>> os.path.relpath(filter_url('http://domain.com/robots.txt')) 'applications/examples/static/robots.txt' >>> filter_url('http://domain.com') '/init/default/index' >>> filter_url('http://domain.com/') '/init/default/index' >>> filter_url('http://domain.com/init/default/fcn') '/init/default/fcn' >>> filter_url('http://domain.com/init/default/fcn/') '/init/default/fcn' >>> filter_url('http://domain.com/app/ctr/fcn') '/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn/arg1') "/app/ctr/fcn ['arg1']" >>> filter_url('http://domain.com/app/ctr/fcn/arg1/') "/app/ctr/fcn ['arg1']" >>> filter_url('http://domain.com/app/ctr/fcn/arg1//') "/app/ctr/fcn ['arg1', '']" >>> filter_url('http://domain.com/app/ctr/fcn//arg1') "/app/ctr/fcn ['', 'arg1']" >>> filter_url('HTTP://DOMAIN.COM/app/ctr/fcn') '/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn?query') '/app/ctr/fcn ?query' >>> filter_url('http://otherdomain.com/fcn') '/app/ctr/fcn' >>> regex_filter_out('/app/ctr/fcn') '/ctr/fcn' >>> filter_url('https://otherdomain.com/app/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://otherdomain.com/app/ctr/fcn/arg1//', out=True) '/ctr/fcn/arg1//' >>> filter_url('http://otherdomain.com/app/ctr/fcn', out=True) '/fcn' >>> filter_url('http://otherdomain.com/app/ctr/fcn?query', out=True) '/fcn?query' >>> filter_url('http://otherdomain.com/app/ctr/fcn#anchor', out=True) '/fcn#anchor' >>> filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400) 400 >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> filter_url('http://domain.com/', app=True) 'myapp' >>> filter_url('http://domain.com', app=True) 'myapp' >>> compile_regex('.*http://otherdomain.com.* (?P<any>.*)', '/app/ctr\g<any>')[0].pattern '^.*http://otherdomain.com.* (?P<any>.*)$' >>> compile_regex('.*http://otherdomain.com.* (?P<any>.*)', '/app/ctr\g<any>')[1] '/app/ctr\\\\g<any>' >>> compile_regex('/$c/$f', '/init/$c/$f')[0].pattern '^.*?:https?://[^:/]+:[a-z]+ /(?P<c>\\\\w+)/(?P<f>\\\\w+)$' >>> compile_regex('/$c/$f', '/init/$c/$f')[1] '/init/\\\\g<c>/\\\\g<f>' ''' pass if __name__ == '__main__': import doctest doctest.testmod()
[ [ 14, 0, 0.0352, 0.005, 0, 0.66, 0, 558, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0402, 0.005, 0, 0.66, 0.1111, 335, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0452, 0.005, 0, 0.66...
[ "default_application = 'init' # ordinarily set in base routes.py", "default_controller = 'default' # ordinarily set in app-specific routes.py", "default_function = 'index' # ordinarily set in app-specific routes.py", "routes_app = ((r'/(?P<app>welcome|admin|app)\\b.*', r'\\g<app>'),\n (r...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys if '__file__' in globals(): path = os.path.dirname(os.path.abspath(__file__)) elif hasattr(sys, 'frozen'): path = os.path.dirname(os.path.abspath(sys.executable)) # for py2exe else: # should never happen path = os.getcwd() os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] # import gluon.import_all ##### This should be uncommented for py2exe.py import gluon.widget # Start Web2py and Web2py cron service! if __name__ == '__main__': try: from multiprocessing import freeze_support freeze_support() except: sys.stderr.write('Sorry, -K only supported for python 2.6-2.7\n') if os.environ.has_key("COVERAGE_PROCESS_START"): try: import coverage coverage.process_startup() except: pass gluon.widget.start(cron=True)
[ [ 1, 0, 0.1212, 0.0303, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1515, 0.0303, 0, 0.66, 0.1667, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 4, 0, 0.2879, 0.1818, 0, ...
[ "import os", "import sys", "if '__file__' in globals():\n path = os.path.dirname(os.path.abspath(__file__))\nelif hasattr(sys, 'frozen'):\n path = os.path.dirname(os.path.abspath(sys.executable)) # for py2exe\nelse: # should never happen\n path = os.getcwd()", " path = os.path.dirname(os.path.ab...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ ############################################################################## # Configuration parameters for Google App Engine ############################################################################## LOG_STATS = False # web2py level log statistics APPSTATS = True # GAE level usage statistics and profiling DEBUG = False # debug mode # # Read more about APPSTATS here # http://googleappengine.blogspot.com/2010/03/easy-performance-profiling-with.html # can be accessed from: # http://localhost:8080/_ah/stats ############################################################################## # All tricks in this file developed by Robin Bhattacharyya ############################################################################## import time import os import sys import logging import cPickle import pickle import wsgiref.handlers import datetime path = os.path.dirname(os.path.abspath(__file__)) sys.path = [path] + [p for p in sys.path if not p == path] sys.modules['cPickle'] = sys.modules['pickle'] from gluon.settings import global_settings from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app global_settings.web2py_runtime_gae = True global_settings.db_sessions = True if os.environ.get('SERVER_SOFTWARE', '').startswith('Devel'): (global_settings.web2py_runtime, DEBUG) = \ ('gae:development', True) else: (global_settings.web2py_runtime, DEBUG) = \ ('gae:production', False) import gluon.main def log_stats(fun): """Function that will act as a decorator to make logging""" def newfun(env, res): """Log the execution time of the passed function""" timer = lambda t: (t.time(), t.clock()) (t0, c0) = timer(time) executed_function = fun(env, res) (t1, c1) = timer(time) log_info = """**** Request: %.2fms/%.2fms (real time/cpu time)""" log_info = log_info % ((t1 - t0) * 1000, (c1 - c0) * 1000) logging.info(log_info) return executed_function return newfun logging.basicConfig(level=logging.INFO) def wsgiapp(env, res): """Return the wsgiapp""" env['PATH_INFO'] = env['PATH_INFO'].decode('latin1').encode('utf8') #when using the blobstore image uploader GAE dev SDK passes these as unicode # they should be regular strings as they are parts of URLs env['wsgi.url_scheme'] = str(env['wsgi.url_scheme']) env['QUERY_STRING'] = str(env['QUERY_STRING']) env['SERVER_NAME'] = str(env['SERVER_NAME']) #this deals with a problem where GAE development server seems to forget # the path between requests if global_settings.web2py_runtime == 'gae:development': gluon.admin.create_missing_folders() web2py_path = global_settings.applications_parent # backward compatibility return gluon.main.wsgibase(env, res) if LOG_STATS or DEBUG: wsgiapp = log_stats(wsgiapp) def main(): """Run the wsgi app""" run_wsgi_app(wsgiapp) if __name__ == '__main__': main()
[ [ 8, 0, 0.0566, 0.0472, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1226, 0.0094, 0, 0.66, 0.037, 779, 1, 0, 0, 0, 0, 4, 0 ], [ 14, 0, 0.1321, 0.0094, 0, 0.66,...
[ "\"\"\"\nThis file is part of the web2py Web Framework\nCopyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>\nLicense: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\"\"\"", "LOG_STATS = False # web2py level log statistics", "APPSTATS = True # GAE level usage statistics and profiling", "D...
import logging logger = logging.getLogger('x90-analyze') logger.setLevel(logging.DEBUG) # File Handler hdlr = logging.FileHandler('logs/run.log') formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) hdlr.setLevel(logging.DEBUG) # Stream handler ch = logging.StreamHandler() formatter = logging.Formatter('[%(levelname)s] %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) ch.setLevel(logging.INFO) def printerror (msg): logger.error(msg) def printwarning (msg): logger.warning(msg) def printinfo (msg): logger.info(msg)
[ [ 1, 0, 0.037, 0.037, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 14, 0, 0.1111, 0.037, 0, 0.66, 0.0667, 532, 3, 1, 0, 0, 71, 10, 1 ], [ 8, 0, 0.1481, 0.037, 0, 0.6...
[ "import logging", "logger = logging.getLogger('x90-analyze')", "logger.setLevel(logging.DEBUG)", "hdlr = logging.FileHandler('logs/run.log')", "formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')", "hdlr.setFormatter(formatter)", "logger.addHandler(hdlr)", "hdlr.setLevel(logging.D...
import os import re import shutil import commands import _mysql import hashlib import logger # Analyze project. def analyze_metrics(project, revision, url, db, folder): analyze_code_metrics(project, revision, url, db, folder) analyze_filemetrics(project, revision, url, db, folder) # Get code metrics: def analyze_code_metrics(project, revision, url, db, folder): logger.printinfo("Analyzing code") phand = os.popen("cloc "+folder) # read output from the command while 1: line = phand.readline() if line == "": break # Find the sum of the code calculations with regex. m = re.search('SUM:.*?(?P<FILES>[0-9]+).*? (?P<BLANK>[0-9]+).*? (?P<COMMENT>[0-9]+).*? (?P<CODE>[0-9]+)', line) if m is not None: files = m.group("FILES") blank = m.group("BLANK") comment = m.group("COMMENT") code = m.group("CODE") db.insertmetric(project, revision, url, files, blank, comment, code) phand.close() return phand.close() return # Code metrics by file: def analyze_filemetrics (project, revision, url, db, folder): logger.printinfo("Analyzing files") phand = os.popen("cloc --by-file --sql=1 " + folder) # read output from the command while 1: line = phand.readline() if line == "": break m = re.search('\',\ \'(?P<LANG>.*?)\',\ \'(?P<FILE>.*?)\',\ (?P<BLANK>[0-9]+),\ (?P<COMMENT>[0-9]+),\ (?P<CODE>[0-9]+),\ ', line) if m is not None: filename = m.group("FILE"); blank = m.group("BLANK"); comment = m.group("COMMENT"); code = m.group("CODE"); lang = m.group("LANG"); db.insertfilemetric(project, revision, url, filename, blank, comment, code, lang) phand.close()
[ [ 1, 0, 0.0175, 0.0175, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0351, 0.0175, 0, 0.66, 0.1111, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0526, 0.0175, 0, ...
[ "import os", "import re", "import shutil", "import commands", "import _mysql", "import hashlib", "import logger", "def analyze_metrics(project, revision, url, db, folder):\n\tanalyze_code_metrics(project, revision, url, db, folder)\n\tanalyze_filemetrics(project, revision, url, db, folder)", "\tanal...
## ## Mercurial-analyzer ## ## Todo: skriv om... from xml.dom import minidom import logger ## Parses a dom file def parsedom(file): try: dom = minidom.parse(file) except Exception: logger.printerror("Failed to parse the xml file " + file); exit() return dom class Project: name="-noname-" type="svn" urls = [] def getprojects (file = 'settings/projects.xml'): projects = []; dom = parsedom(file) logger.printinfo("Parsing project-settings") try: for node in dom.getElementsByTagName('project'): proj = Project(); tmp = []; for xnode in node.getElementsByTagName("name"): proj.name = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("type"): proj.type = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("url"): tmp.append(xnode.firstChild.wholeText); proj.urls = tmp; projects.append(proj); except Exception: logger.printerror("Malformed xml elements") exit() return projects; class DbSettings: host="" username="" password="" schema="" def getdbsettings (file = 'settings/db.xml'): logger.printinfo("Parsing database-settings") dom = parsedom(file) dbsetting = DbSettings() try: for node in dom.getElementsByTagName('database'): for xnode in node.getElementsByTagName("host"): dbsetting.host = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("username"): dbsetting.username = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("password"): dbsetting.password = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("schema"): dbsetting.schema = xnode.firstChild.wholeText except Exception: logger.printerror("Malformed xml elements") exit() # Validate, or atleast check that variables have been changed... if(dbsetting.host==""): logger.printerror("Missing host") exit() if(dbsetting.username==""): logger.printerror("Missing username") exit() if(dbsetting.password==""): logger.printerror("Missing password") exit() if(dbsetting.schema==""): logger.printerror("Missing schema") exit() return dbsetting; class Type: name="-noname-" changelog="" regex="" checkout="" def gettypes (file = 'settings/types.xml'): types = {}; dom = parsedom(file) logger.printinfo("Parsing supported vcs info") try: for node in dom.getElementsByTagName('type'): proj = Type(); for xnode in node.getElementsByTagName("name"): proj.name = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("changelog"): proj.changelog = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("regex"): proj.regex = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("checkout"): proj.checkout = xnode.firstChild.wholeText types[proj.name]=proj; except Exception: logger.printerror("Malformed xml elements") exit() return types;
[ [ 1, 0, 0.0496, 0.0083, 0, 0.66, 0, 290, 0, 1, 0, 0, 290, 0, 0 ], [ 1, 0, 0.0579, 0.0083, 0, 0.66, 0.125, 532, 0, 1, 0, 0, 532, 0, 0 ], [ 2, 0, 0.1116, 0.0661, 0, 0...
[ "from xml.dom import minidom", "import logger", "def parsedom(file):\n\ttry:\n\t\tdom = minidom.parse(file)\n\texcept Exception:\n\t logger.printerror(\"Failed to parse the xml file \" + file);\n\t exit()\n\n\treturn dom", "\ttry:\n\t\tdom = minidom.parse(file)\n\texcept Exception:\n\t logger.printerror(\"...
## ## mercurial-analyzer ## ## Requires: Cloc (sudo apt-get install cloc) import analyzelib import settingsreader from database import DbHandler import logger def getType(types, name): try: ret = types[name]; return ret except Exception: logger.printerror("Missing type "+name) exit(); logger.printinfo("\t------------------------") logger.printinfo("\t 0x90-analyzer ") logger.printinfo("\t------------------------") # Connect to mysql-db with settings from settings.xml dbsettings = settingsreader.getdbsettings() db = DbHandler(dbsettings) types = settingsreader.gettypes() # Find and analyze projects from settings.xml projects = settingsreader.getprojects() for project in projects: type = getType(types, project.type); analyzelib.analyze_project(project, type, db) logger.printinfo("Done.")
[ [ 1, 0, 0.1667, 0.0278, 0, 0.66, 0, 443, 0, 1, 0, 0, 443, 0, 0 ], [ 1, 0, 0.1944, 0.0278, 0, 0.66, 0.0769, 621, 0, 1, 0, 0, 621, 0, 0 ], [ 1, 0, 0.2222, 0.0278, 0, ...
[ "import analyzelib", "import settingsreader", "from database import DbHandler", "import logger", "def getType(types, name):\n\ttry:\n\t\tret = types[name];\n\t\treturn ret\n\texcept Exception:\n\t\tlogger.printerror(\"Missing type \"+name)\n\t\texit();", "\ttry:\n\t\tret = types[name];\n\t\treturn ret\n\t...
#==================================================================== # 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...
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
[ [ 8, 0, 0.1875, 0.0081, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1976, 0.004, 0, 0.66, 0.0833, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.2056, 0.004, 0, 0.66, ...
[ "\"\"\"Google Code file uploader script.\n\"\"\"", "__author__ = 'danderson@google.com (David Anderson)'", "import httplib", "import os.path", "import optparse", "import getpass", "import base64", "import sys", "def upload(file, project_name, user_name, password, summary, labels=None):\n \"\"\"Uplo...
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
[ [ 8, 0, 0.1875, 0.0081, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1976, 0.004, 0, 0.66, 0.0833, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.2056, 0.004, 0, 0.66, ...
[ "\"\"\"Google Code file uploader script.\n\"\"\"", "__author__ = 'danderson@google.com (David Anderson)'", "import httplib", "import os.path", "import optparse", "import getpass", "import base64", "import sys", "def upload(file, project_name, user_name, password, summary, labels=None):\n \"\"\"Uplo...
#!/usr/bin/env python3 import random class MastermindGame(): def __init__(self): self._generated_string = "" used_digits = set() for i in range(4): digit = random.randrange(0, 10, 1) while digit in used_digits: digit = random.randrange(0, 10, 1) used_digits.add(digit) self._generated_string += str(digit) def guess(self, attempt_string): if len(attempt_string) != len(self._generated_string): return False bulls = 0 cows = 0 used_digits = set() for digit1, digit2 in zip(self._generated_string, attempt_string): if digit1 == digit2: bulls += 1 else: used_digits.add(digit1) for digit in attempt_string: if digit in used_digits: cows += 1 if bulls == 4: return "Epic Win, bro!" return (bulls, cows) if __name__ == "__main__": game = MastermindGame() while 1: s = input() print(game.guess(s))
[ [ 1, 0, 0.05, 0.025, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 3, 0, 0.475, 0.725, 0, 0.66, 0.5, 894, 0, 2, 0, 0, 0, 0, 11 ], [ 2, 1, 0.25, 0.225, 1, 0.96, 0,...
[ "import random", "class MastermindGame():\n def __init__(self):\n self._generated_string = \"\"\n used_digits = set()\n for i in range(4):\n digit = random.randrange(0, 10, 1)\n while digit in used_digits:\n digit = random.randrange(0, 10, 1)", " d...
#!/usr/bin/env python3 import random class MastermindGame(): def __init__(self): self._generated_string = "" used_digits = set() for i in range(4): digit = random.randrange(0, 10, 1) while digit in used_digits: digit = random.randrange(0, 10, 1) used_digits.add(digit) self._generated_string += str(digit) def guess(self, attempt_string): if len(attempt_string) != len(self._generated_string): return False bulls = 0 cows = 0 used_digits = set() for digit1, digit2 in zip(self._generated_string, attempt_string): if digit1 == digit2: bulls += 1 else: used_digits.add(digit1) for digit in attempt_string: if digit in used_digits: cows += 1 if bulls == 4: return "Epic Win, bro!" return (bulls, cows) if __name__ == "__main__": game = MastermindGame() while 1: s = input() print(game.guess(s))
[ [ 1, 0, 0.05, 0.025, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 3, 0, 0.475, 0.725, 0, 0.66, 0.5, 894, 0, 2, 0, 0, 0, 0, 11 ], [ 2, 1, 0.25, 0.225, 1, 0.68, 0,...
[ "import random", "class MastermindGame():\n def __init__(self):\n self._generated_string = \"\"\n used_digits = set()\n for i in range(4):\n digit = random.randrange(0, 10, 1)\n while digit in used_digits:\n digit = random.randrange(0, 10, 1)", " d...
import time def yesno(question): val = raw_input(question + " ") return val.startswith("y") or val.startswith("Y") use_pysqlite2 = yesno("Use pysqlite 2.0?") use_autocommit = yesno("Use autocommit?") use_executemany= yesno("Use executemany?") if use_pysqlite2: from pysqlite2 import dbapi2 as sqlite else: import sqlite def create_db(): con = sqlite.connect(":memory:") if use_autocommit: if use_pysqlite2: con.isolation_level = None else: con.autocommit = True cur = con.cursor() cur.execute(""" create table test(v text, f float, i integer) """) cur.close() return con def test(): row = ("sdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasfd", 3.14, 42) l = [] for i in range(1000): l.append(row) con = create_db() cur = con.cursor() if sqlite.version_info > (2, 0): sql = "insert into test(v, f, i) values (?, ?, ?)" else: sql = "insert into test(v, f, i) values (%s, %s, %s)" starttime = time.time() for i in range(50): if use_executemany: cur.executemany(sql, l) else: for r in l: cur.execute(sql, r) endtime = time.time() print "elapsed", endtime - starttime cur.execute("select count(*) from test") print "rows:", cur.fetchone()[0] if __name__ == "__main__": test()
[ [ 1, 0, 0.0164, 0.0164, 0, 0.66, 0, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 2, 0, 0.0656, 0.0492, 0, 0.66, 0.125, 796, 0, 1, 1, 0, 0, 0, 3 ], [ 14, 1, 0.0656, 0.0164, 1, 0....
[ "import time", "def yesno(question):\n val = raw_input(question + \" \")\n return val.startswith(\"y\") or val.startswith(\"Y\")", " val = raw_input(question + \" \")", " return val.startswith(\"y\") or val.startswith(\"Y\")", "use_pysqlite2 = yesno(\"Use pysqlite 2.0?\")", "use_autocommit = y...
import time def yesno(question): val = raw_input(question + " ") return val.startswith("y") or val.startswith("Y") use_pysqlite2 = yesno("Use pysqlite 2.0?") if use_pysqlite2: use_custom_types = yesno("Use custom types?") use_dictcursor = yesno("Use dict cursor?") use_rowcursor = yesno("Use row cursor?") else: use_tuple = yesno("Use rowclass=tuple?") if use_pysqlite2: from pysqlite2 import dbapi2 as sqlite else: import sqlite def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d if use_pysqlite2: def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d class DictCursor(sqlite.Cursor): def __init__(self, *args, **kwargs): sqlite.Cursor.__init__(self, *args, **kwargs) self.row_factory = dict_factory class RowCursor(sqlite.Cursor): def __init__(self, *args, **kwargs): sqlite.Cursor.__init__(self, *args, **kwargs) self.row_factory = sqlite.Row def create_db(): if sqlite.version_info > (2, 0): if use_custom_types: con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) sqlite.register_converter("text", lambda x: "<%s>" % x) else: con = sqlite.connect(":memory:") if use_dictcursor: cur = con.cursor(factory=DictCursor) elif use_rowcursor: cur = con.cursor(factory=RowCursor) else: cur = con.cursor() else: if use_tuple: con = sqlite.connect(":memory:") con.rowclass = tuple cur = con.cursor() else: con = sqlite.connect(":memory:") cur = con.cursor() cur.execute(""" create table test(v text, f float, i integer) """) return (con, cur) def test(): row = ("sdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasfd", 3.14, 42) l = [] for i in range(1000): l.append(row) con, cur = create_db() if sqlite.version_info > (2, 0): sql = "insert into test(v, f, i) values (?, ?, ?)" else: sql = "insert into test(v, f, i) values (%s, %s, %s)" for i in range(50): cur.executemany(sql, l) cur.execute("select count(*) as cnt from test") starttime = time.time() for i in range(50): cur.execute("select v, f, i from test") l = cur.fetchall() endtime = time.time() print "elapsed:", endtime - starttime if __name__ == "__main__": test()
[ [ 1, 0, 0.0103, 0.0103, 0, 0.66, 0, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 2, 0, 0.0412, 0.0309, 0, 0.66, 0.1111, 796, 0, 1, 1, 0, 0, 0, 3 ], [ 14, 1, 0.0412, 0.0103, 1, 0...
[ "import time", "def yesno(question):\n val = raw_input(question + \" \")\n return val.startswith(\"y\") or val.startswith(\"Y\")", " val = raw_input(question + \" \")", " return val.startswith(\"y\") or val.startswith(\"Y\")", "use_pysqlite2 = yesno(\"Use pysqlite 2.0?\")", "if use_pysqlite2:\...
#!/usr/bin/env python from pysqlite2.test import test test()
[ [ 1, 0, 0.6667, 0.3333, 0, 0.66, 0, 472, 0, 1, 0, 0, 472, 0, 0 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1, 224, 3, 0, 0, 0, 0, 0, 1 ] ]
[ "from pysqlite2.test import test", "test()" ]
from pysqlite2 import dbapi2 as sqlite import os, threading def getcon(): #con = sqlite.connect("db", isolation_level=None, timeout=5.0) con = sqlite.connect(":memory:") cur = con.cursor() cur.execute("create table test(i, s)") for i in range(10): cur.execute("insert into test(i, s) values (?, 'asfd')", (i,)) con.commit() cur.close() return con def reader(what): con = getcon() while 1: cur = con.cursor() cur.execute("select i, s from test where i % 1000=?", (what,)) res = cur.fetchall() cur.close() con.close() def appender(): con = getcon() counter = 0 while 1: cur = con.cursor() cur.execute("insert into test(i, s) values (?, ?)", (counter, "foosadfasfasfsfafs")) #cur.execute("insert into test(foo) values (?)", (counter,)) counter += 1 if counter % 100 == 0: #print "appender committing", counter con.commit() cur.close() con.close() def updater(): con = getcon() counter = 0 while 1: cur = con.cursor() counter += 1 if counter % 5 == 0: cur.execute("update test set s='foo' where i % 50=0") #print "updater committing", counter con.commit() cur.close() con.close() def deleter(): con = getcon() counter = 0 while 1: cur = con.cursor() counter += 1 if counter % 5 == 0: #print "deleter committing", counter cur.execute("delete from test where i % 20=0") con.commit() cur.close() con.close() threads = [] for i in range(10): continue threads.append(threading.Thread(target=lambda: reader(i))) for i in range(5): threads.append(threading.Thread(target=appender)) #threads.append(threading.Thread(target=updater)) #threads.append(threading.Thread(target=deleter)) for t in threads: t.start()
[ [ 1, 0, 0.0125, 0.0125, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.025, 0.0125, 0, 0.66, 0.1, 688, 0, 2, 0, 0, 688, 0, 0 ], [ 2, 0, 0.1062, 0.125, 0, 0.66,...
[ "from pysqlite2 import dbapi2 as sqlite", "import os, threading", "def getcon():\n #con = sqlite.connect(\"db\", isolation_level=None, timeout=5.0)\n con = sqlite.connect(\":memory:\")\n cur = con.cursor()\n cur.execute(\"create table test(i, s)\")\n for i in range(10):\n cur.execute(\"ins...
from __future__ import with_statement from pysqlite2 import dbapi2 as sqlite3 from datetime import datetime, timedelta import time def read_modify_write(): # Open connection and create example schema and data. # In reality, open a database file instead of an in-memory database. con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table test(id integer primary key, data); insert into test(data) values ('foo'); insert into test(data) values ('bar'); insert into test(data) values ('baz'); """) # The read part. There are two ways for fetching data using pysqlite. # 1. "Lazy-reading" # cur.execute("select ...") # for row in cur: # ... # # Advantage: Low memory consumption, good for large resultsets, data is # fetched on demand. # Disadvantage: Database locked as long as you iterate over cursor. # # 2. "Eager reading" # cur.fetchone() to fetch one row # cur.fetchall() to fetch all rows # Advantage: Locks cleared ASAP. # Disadvantage: fetchall() may build large lists. cur.execute("select id, data from test where id=?", (2,)) row = cur.fetchone() # Stupid way to modify the data column. lst = list(row) lst[1] = lst[1] + " & more" # This is the suggested recipe to modify data using pysqlite. We use # pysqlite's proprietary API to use the connection object as a context # manager. This is equivalent to the following code: # # try: # cur.execute("...") # except: # con.rollback() # raise # finally: # con.commit() # # This makes sure locks are cleared - either by commiting or rolling back # the transaction. # # If the rollback happens because of concurrency issues, you just have to # try again until it succeeds. Much more likely is that the rollback and # the raised exception happen because of other reasons, though (constraint # violation, etc.) - don't forget to roll back on errors. # # Or use this recipe. It's useful and gets everything done in two lines of # code. with con: cur.execute("update test set data=? where id=?", (lst[1], lst[0])) def delete_older_than(): # Use detect_types if you want to use date/time types in pysqlite. con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) cur = con.cursor() # With "DEFAULT current_timestamp" we have SQLite fill the timestamp column # automatically. cur.executescript(""" create table test(id integer primary key, data, created timestamp default current_timestamp); """) with con: for i in range(3): cur.execute("insert into test(data) values ('foo')") time.sleep(1) # Delete older than certain interval # SQLite uses UTC time, so we need to create these timestamps in Python, too. with con: delete_before = datetime.utcnow() - timedelta(seconds=2) cur.execute("delete from test where created < ?", (delete_before,)) def modify_insert(): # Use a unique index and the REPLACE command to have the "insert if not # there, but modify if it is there" pattern. Race conditions are taken care # of by transactions. con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table test(id integer primary key, name, age); insert into test(name, age) values ('Adam', 18); insert into test(name, age) values ('Eve', 21); create unique index idx_test_data_unique on test(name); """) with con: # Make Adam age 19 cur.execute("replace into test(name, age) values ('Adam', 19)") # Create new entry cur.execute("replace into test(name, age) values ('Abel', 3)") if __name__ == "__main__": read_modify_write() delete_older_than() modify_insert()
[ [ 1, 0, 0.0091, 0.0091, 0, 0.66, 0, 777, 0, 1, 0, 0, 777, 0, 0 ], [ 1, 0, 0.0182, 0.0091, 0, 0.66, 0.1429, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.0273, 0.0091, 0, ...
[ "from __future__ import with_statement", "from pysqlite2 import dbapi2 as sqlite3", "from datetime import datetime, timedelta", "import time", "def read_modify_write():\n # Open connection and create example schema and data.\n # In reality, open a database file instead of an in-memory database.\n c...
from pysqlite2 import dbapi2 as sqlite3 Cursor = sqlite3.Cursor class EagerCursor(Cursor): def __init__(self, con): Cursor.__init__(self, con) self.rows = [] self.pos = 0 def execute(self, *args): sqlite3.Cursor.execute(self, *args) self.rows = Cursor.fetchall(self) self.pos = 0 def fetchone(self): try: row = self.rows[self.pos] self.pos += 1 return row except IndexError: return None def fetchmany(self, num=None): if num is None: num = self.arraysize result = self.rows[self.pos:self.pos+num] self.pos += num return result def fetchall(self): result = self.rows[self.pos:] self.pos = len(self.rows) return result def test(): con = sqlite3.connect(":memory:") cur = con.cursor(EagerCursor) cur.execute("create table test(foo)") cur.executemany("insert into test(foo) values (?)", [(3,), (4,), (5,)]) cur.execute("select * from test") print cur.fetchone() print cur.fetchone() print cur.fetchone() print cur.fetchone() print cur.fetchone() if __name__ == "__main__": test()
[ [ 1, 0, 0.0196, 0.0196, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.0588, 0.0196, 0, 0.66, 0.25, 647, 7, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.3922, 0.6078, 0, 0.6...
[ "from pysqlite2 import dbapi2 as sqlite3", "Cursor = sqlite3.Cursor", "class EagerCursor(Cursor):\n def __init__(self, con):\n Cursor.__init__(self, con)\n self.rows = []\n self.pos = 0\n\n def execute(self, *args):\n sqlite3.Cursor.execute(self, *args)", " def __init__(se...
#!/usr/bin/env python # # Cross-compile and build pysqlite installers for win32 on Linux or Mac OS X. # # The way this works is very ugly, but hey, it *works*! And I didn't have to # reinvent the wheel using NSIS. import os import sys import urllib import zipfile from setup import get_amalgamation # Cross-compiler if sys.platform == "darwin": CC = "/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc" LIBDIR = "lib.macosx-10.6-i386-2.5" STRIP = "/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc --strip-all" else: CC = "/usr/bin/i586-mingw32msvc-gcc" LIBDIR = "lib.linux-i686-2.5" STRIP = "strip --strip-all" # Optimization settings OPT = "-O2" # pysqlite sources + SQLite amalgamation SRC = "src/module.c src/connection.c src/cursor.c src/cache.c src/microprotocols.c src/prepare_protocol.c src/statement.c src/util.c src/row.c amalgamation/sqlite3.c" # You will need to fetch these from # https://pyext-cross.pysqlite.googlecode.com/hg/ CROSS_TOOLS = "../pysqlite-pyext-cross" def execute(cmd): print cmd return os.system(cmd) def compile_module(pyver): VER = pyver.replace(".", "") INC = "%s/python%s/include" % (CROSS_TOOLS, VER) vars = locals() vars.update(globals()) cmd = '%(CC)s -mno-cygwin %(OPT)s -mdll -DMODULE_NAME=\\"pysqlite2._sqlite\\" -DSQLITE_ENABLE_RTREE=1 -DSQLITE_ENABLE_FTS3=1 -I amalgamation -I %(INC)s -I . %(SRC)s -L %(CROSS_TOOLS)s/python%(VER)s/libs -lpython%(VER)s -o build/%(LIBDIR)s/pysqlite2/_sqlite.pyd' % vars execute(cmd) execute("%(STRIP)s build/%(LIBDIR)s/pysqlite2/_sqlite.pyd" % vars) def main(): vars = locals() vars.update(globals()) get_amalgamation() for ver in ["2.5", "2.6", "2.7"]: execute("rm -rf build") # First, compile the host version. This is just to get the .py files in place. execute("python2.5 setup.py build") # Yes, now delete the host extension module. What a waste of time. os.unlink("build/%(LIBDIR)s/pysqlite2/_sqlite.so" % vars) # Cross-compile win32 extension module. compile_module(ver) # Prepare for target Python version. libdir_ver = LIBDIR[:-3] + ver os.rename("build/%(LIBDIR)s" % vars, "build/" + libdir_ver) # And create the installer! os.putenv("PYEXT_CROSS", CROSS_TOOLS) execute("python2.5 setup.py cross_bdist_wininst --skip-build --target-version=" + ver) if __name__ == "__main__": main()
[ [ 1, 0, 0.1176, 0.0147, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1324, 0.0147, 0, 0.66, 0.0833, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.1471, 0.0147, 0, ...
[ "import os", "import sys", "import urllib", "import zipfile", "from setup import get_amalgamation", "if sys.platform == \"darwin\":\n CC = \"/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc\"\n LIBDIR = \"lib.macosx-10.6-i386-2.5\"\n STRIP = \"/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc ...
# -*- coding: utf-8 -*- # # pysqlite documentation build configuration file, created by # sphinx-quickstart.py on Sat Mar 22 02:47:54 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys # If your extensions are in another directory, add it here. #sys.path.append('some/directory') # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.addons.*') or your custom ones. #extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General substitutions. project = 'pysqlite' copyright = u'2008-2009, Gerhard Häring' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = '2.6' # The full version, including alpha/beta/rc tags. release = '2.6.0' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['.static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Content template for the index page. #html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # Output file base name for HTML help builder. htmlhelp_basename = 'pysqlitedoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). #latex_documents = [] # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
[ [ 1, 0, 0.1061, 0.0076, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.2045, 0.0076, 0, 0.66, 0.0769, 518, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.2273, 0.0076, 0, ...
[ "import sys", "templates_path = ['.templates']", "source_suffix = '.rst'", "master_doc = 'index'", "project = 'pysqlite'", "copyright = u'2008-2009, Gerhard Häring'", "version = '2.6'", "release = '2.6.0'", "today_fmt = '%B %d, %Y'", "pygments_style = 'sphinx'", "html_style = 'default.css'", "...
from pysqlite2 import dbapi2 as sqlite3 FIELD_MAX_WIDTH = 20 TABLE_NAME = 'people' SELECT = 'select * from %s order by age, name_last' % TABLE_NAME con = sqlite3.connect("mydb") cur = con.cursor() cur.execute(SELECT) # Print a header. for fieldDesc in cur.description: print fieldDesc[0].ljust(FIELD_MAX_WIDTH) , print # Finish the header with a newline. print '-' * 78 # For each row, print the value of each field left-justified within # the maximum possible width of that field. fieldIndices = range(len(cur.description)) for row in cur: for fieldIndex in fieldIndices: fieldValue = str(row[fieldIndex]) print fieldValue.ljust(FIELD_MAX_WIDTH) , print # Finish the row with a newline.
[ [ 1, 0, 0.5, 0.5, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ] ]
[ "from pysqlite2 import dbapi2 as sqlite3" ]
from pysqlite2 import dbapi2 as sqlite3 def progress(): print "Query still executing. Please wait ..." con = sqlite3.connect(":memory:") con.execute("create table test(x)") # Let's create some data con.executemany("insert into test(x) values (?)", [(x,) for x in xrange(300)]) # A progress handler, executed every 10 million opcodes con.set_progress_handler(progress, 10000000) # A particularly long-running query killer_stament = """ select count(*) from ( select t1.x from test t1, test t2, test t3 ) """ con.execute(killer_stament) print "-" * 50 # Clear the progress handler con.set_progress_handler(None, 0) con.execute(killer_stament)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 2, 0, 0.1207, 0.069, 0, 0.66, 0.1, 82, 0, 0, 0, 0, 0, 0, 1 ], [ 8, 1, 0.1379, 0.0345, 1, 0.66, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "def progress():\n print(\"Query still executing. Please wait ...\")", " print(\"Query still executing. Please wait ...\")", "con = sqlite3.connect(\":memory:\")", "con.execute(\"create table test(x)\")", "con.executemany(\"insert into test(x) values (?)\",...
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb") cur = con.cursor() SELECT = "select name_last, age from people order by age, name_last" # 1. Iterate over the rows available from the cursor, unpacking the # resulting sequences to yield their elements (name_last, age): cur.execute(SELECT) for (name_last, age) in cur: print '%s is %d years old.' % (name_last, age) # 2. Equivalently: cur.execute(SELECT) for row in cur: print '%s is %d years old.' % (row[0], row[1])
[ [ 1, 0, 0.0588, 0.0588, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.1765, 0.0588, 0, 0.66, 0.1429, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.2941, 0.0588, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\"mydb\")", "cur = con.cursor()", "SELECT = \"select name_last, age from people order by age, name_last\"", "cur.execute(SELECT)", "for (name_last, age) in cur:\n print('%s is %d years old.' % (name_last, age))", " print('%s is %d y...
from pysqlite2 import dbapi2 as sqlite3 # Create a connection to the database file "mydb": con = sqlite3.connect("mydb") # Get a Cursor object that operates in the context of Connection con: cur = con.cursor() # Execute the SELECT statement: cur.execute("select * from people order by age") # Retrieve all rows as a sequence and print that sequence: print cur.fetchall()
[ [ 1, 0, 0.0769, 0.0769, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.3077, 0.0769, 0, 0.66, 0.25, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.5385, 0.0769, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\"mydb\")", "cur = con.cursor()", "cur.execute(\"select * from people order by age\")", "print(cur.fetchall())" ]
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb")
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 1, 0.3333, 0, 0.66, 1, 761, 3, 1, 0, 0, 242, 10, 1 ] ]
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\"mydb\")" ]
from pysqlite2 import dbapi2 as sqlite3 class MySum: def __init__(self): self.count = 0 def step(self, value): self.count += value def finalize(self): return self.count con = sqlite3.connect(":memory:") con.create_aggregate("mysum", 1, MySum) cur = con.cursor() cur.execute("create table test(i)") cur.execute("insert into test(i) values (1)") cur.execute("insert into test(i) values (2)") cur.execute("select mysum(i) from test") print cur.fetchone()[0]
[ [ 1, 0, 0.05, 0.05, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 3, 0, 0.35, 0.45, 0, 0.66, 0.1111, 865, 0, 3, 0, 0, 0, 0, 0 ], [ 2, 1, 0.225, 0.1, 1, 0.21, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "class MySum:\n def __init__(self):\n self.count = 0\n\n def step(self, value):\n self.count += value\n\n def finalize(self):", " def __init__(self):\n self.count = 0", " self.count = 0", " def step(self, value):\n ...
# A minimal SQLite shell for experiments from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:") con.isolation_level = None cur = con.cursor() buffer = "" print "Enter your SQL commands to execute in SQLite." print "Enter a blank line to exit." while True: line = raw_input() if line == "": break buffer += line if sqlite3.complete_statement(buffer): try: buffer = buffer.strip() cur.execute(buffer) if buffer.lstrip().upper().startswith("SELECT"): print cur.fetchall() except sqlite3.Error, e: print "An error occurred:", e.args[0] buffer = "" con.close()
[ [ 1, 0, 0.5, 0.5, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ] ]
[ "from pysqlite2 import dbapi2 as sqlite3" ]
from pysqlite2 import dbapi2 as sqlite3 def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d con = sqlite3.connect(":memory:") con.row_factory = dict_factory cur = con.cursor() cur.execute("select 1 as a") print cur.fetchone()["a"]
[ [ 1, 0, 0.0769, 0.0769, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 2, 0, 0.3846, 0.3846, 0, 0.66, 0.1667, 131, 0, 2, 1, 0, 0, 0, 1 ], [ 14, 1, 0.3077, 0.0769, 1, 0...
[ "from pysqlite2 import dbapi2 as sqlite3", "def dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d", " d = {}", " for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]", " d[col[0]] = row[...
from pysqlite2 import dbapi2 as sqlite3 import datetime con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) cur = con.cursor() cur.execute("create table test(d date, ts timestamp)") today = datetime.date.today() now = datetime.datetime.now() cur.execute("insert into test(d, ts) values (?, ?)", (today, now)) cur.execute("select d, ts from test") row = cur.fetchone() print today, "=>", row[0], type(row[0]) print now, "=>", row[1], type(row[1]) cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"') row = cur.fetchone() print "current_date", row[0], type(row[0]) print "current_timestamp", row[1], type(row[1])
[ [ 1, 0, 0.05, 0.05, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.1, 0.05, 0, 0.66, 0.0667, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 14, 0, 0.2, 0.05, 0, 0.66, 0.1...
[ "from pysqlite2 import dbapi2 as sqlite3", "import datetime", "con = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)", "cur = con.cursor()", "cur.execute(\"create table test(d date, ts timestamp)\")", "today = datetime.date.today()", "now = datetime.datetime.no...
from pysqlite2 import dbapi2 as sqlite3 def authorizer_callback(action, arg1, arg2, dbname, source): if action != sqlite3.SQLITE_SELECT: return sqlite3.SQLITE_DENY if arg1 == "private_table": return sqlite3.SQLITE_DENY return sqlite3.SQLITE_OK con = sqlite3.connect(":memory:") con.executescript(""" create table public_table(c1, c2); create table private_table(c1, c2); """) con.set_authorizer(authorizer_callback) try: con.execute("select * from private_table") except sqlite3.DatabaseError, e: print "SELECT FROM private_table =>", e.args[0] # access ... prohibited try: con.execute("insert into public_table(c1, c2) values (1, 2)") except sqlite3.DatabaseError, e: print "DML command =>", e.args[0] # access ... prohibited
[ [ 1, 0, 0.1111, 0.1111, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 2, 0, 0.6111, 0.6667, 0, 0.66, 1, 423, 0, 5, 1, 0, 0, 0, 0 ], [ 4, 1, 0.5, 0.2222, 1, 0.96, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "def authorizer_callback(action, arg1, arg2, dbname, source):\n if action != sqlite3.SQLITE_SELECT:\n return sqlite3.SQLITE_DENY\n if arg1 == \"private_table\":\n return sqlite3.SQLITE_DENY\n return sqlite3.SQLITE_OK", " if action != sqlite3.S...
from pysqlite2 import dbapi2 as sqlite3 # The shared cache is only available in SQLite versions 3.3.3 or later # See the SQLite documentaton for details. sqlite3.enable_shared_cache(True)
[ [ 1, 0, 0.1667, 0.1667, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 8, 0, 1, 0.1667, 0, 0.66, 1, 965, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "from pysqlite2 import dbapi2 as sqlite3", "sqlite3.enable_shared_cache(True)" ]
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:")
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 1, 0.3333, 0, 0.66, 1, 761, 3, 1, 0, 0, 242, 10, 1 ] ]
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\":memory:\")" ]
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb") cur = con.cursor() who = "Yeltsin" age = 72 cur.execute("select name_last, age from people where name_last=? and age=?", (who, age)) print cur.fetchone()
[ [ 1, 0, 0.0909, 0.0909, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.2727, 0.0909, 0, 0.66, 0.1667, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.4545, 0.0909, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\"mydb\")", "cur = con.cursor()", "who = \"Yeltsin\"", "age = 72", "cur.execute(\"select name_last, age from people where name_last=? and age=?\", (who, age))", "print(cur.fetchone())" ]
from __future__ import with_statement from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:") con.execute("create table person (id integer primary key, firstname varchar unique)") # Successful, con.commit() is called automatically afterwards with con: con.execute("insert into person(firstname) values (?)", ("Joe",)) # con.rollback() is called after the with block finishes with an exception, the # exception is still raised and must be catched try: with con: con.execute("insert into person(firstname) values (?)", ("Joe",)) except sqlite3.IntegrityError: print "couldn't add Joe twice"
[ [ 1, 0, 0.0526, 0.0526, 0, 0.66, 0, 777, 0, 1, 0, 0, 777, 0, 0 ], [ 1, 0, 0.1053, 0.0526, 0, 0.66, 0.25, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.2105, 0.0526, 0, 0...
[ "from __future__ import with_statement", "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\":memory:\")", "con.execute(\"create table person (id integer primary key, firstname varchar unique)\")", " con.execute(\"insert into person(firstname) values (?)\", (\"Joe\",))", "try:\n with...
from pysqlite2 import dbapi2 as sqlite3 import md5 def md5sum(t): return md5.md5(t).hexdigest() con = sqlite3.connect(":memory:") con.create_function("md5", 1, md5sum) cur = con.cursor() cur.execute("select md5(?)", ("foo",)) print cur.fetchone()[0]
[ [ 1, 0, 0.0909, 0.0909, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.1818, 0.0909, 0, 0.66, 0.1429, 604, 0, 1, 0, 0, 604, 0, 0 ], [ 2, 0, 0.4091, 0.1818, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "import md5", "def md5sum(t):\n return md5.md5(t).hexdigest()", " return md5.md5(t).hexdigest()", "con = sqlite3.connect(\":memory:\")", "con.create_function(\"md5\", 1, md5sum)", "cur = con.cursor()", "cur.execute(\"select md5(?)\", (\"foo\",))", "pr...
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb") con.row_factory = sqlite3.Row cur = con.cursor() cur.execute("select name_last, age from people") for row in cur: assert row[0] == row["name_last"] assert row["name_last"] == row["nAmE_lAsT"] assert row[1] == row["age"] assert row[1] == row["AgE"]
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.25, 0.0833, 0, 0.66, 0.2, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.3333, 0.0833, 0, 0....
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\"mydb\")", "con.row_factory = sqlite3.Row", "cur = con.cursor()", "cur.execute(\"select name_last, age from people\")", "for row in cur:\n assert row[0] == row[\"name_last\"]\n assert row[\"name_last\"] == row[\"nAmE_lAsT\"]\n ass...
from pysqlite2 import dbapi2 as sqlite3 class Point(object): def __init__(self, x, y): self.x, self.y = x, y def adapt_point(point): return "%f;%f" % (point.x, point.y) sqlite3.register_adapter(Point, adapt_point) con = sqlite3.connect(":memory:") cur = con.cursor() p = Point(4.0, -3.2) cur.execute("select ?", (p,)) print cur.fetchone()[0]
[ [ 1, 0, 0.0588, 0.0588, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 3, 0, 0.2353, 0.1765, 0, 0.66, 0.125, 652, 0, 1, 0, 0, 186, 0, 0 ], [ 2, 1, 0.2647, 0.1176, 1, 0...
[ "from pysqlite2 import dbapi2 as sqlite3", "class Point(object):\n def __init__(self, x, y):\n self.x, self.y = x, y", " def __init__(self, x, y):\n self.x, self.y = x, y", " self.x, self.y = x, y", "def adapt_point(point):\n return \"%f;%f\" % (point.x, point.y)", " retur...
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() # Create the table con.execute("create table person(lastname, firstname)") AUSTRIA = u"\xd6sterreich" # by default, rows are returned as Unicode cur.execute("select ?", (AUSTRIA,)) row = cur.fetchone() assert row[0] == AUSTRIA # but we can make pysqlite always return bytestrings ... con.text_factory = str cur.execute("select ?", (AUSTRIA,)) row = cur.fetchone() assert type(row[0]) == str # the bytestrings will be encoded in UTF-8, unless you stored garbage in the # database ... assert row[0] == AUSTRIA.encode("utf-8") # we can also implement a custom text_factory ... # here we implement one that will ignore Unicode characters that cannot be # decoded from UTF-8 con.text_factory = lambda x: unicode(x, "utf-8", "ignore") cur.execute("select ?", ("this is latin1 and would normally create errors" + u"\xe4\xf6\xfc".encode("latin1"),)) row = cur.fetchone() assert type(row[0]) == unicode # pysqlite offers a builtin optimized text_factory that will return bytestring # objects, if the data is in ASCII only, and otherwise return unicode objects con.text_factory = sqlite3.OptimizedUnicode cur.execute("select ?", (AUSTRIA,)) row = cur.fetchone() assert type(row[0]) == unicode cur.execute("select ?", ("Germany",)) row = cur.fetchone() assert type(row[0]) == str
[ [ 1, 0, 0.0238, 0.0238, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.0714, 0.0238, 0, 0.66, 0.0588, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.0952, 0.0238, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\":memory:\")", "cur = con.cursor()", "con.execute(\"create table person(lastname, firstname)\")", "AUSTRIA = u\"\\xd6sterreich\"", "cur.execute(\"select ?\", (AUSTRIA,))", "row = cur.fetchone()", "con.text_factory = str", "cur.execut...
from pysqlite2 import dbapi2 as sqlite3 class CountCursorsConnection(sqlite3.Connection): def __init__(self, *args, **kwargs): sqlite3.Connection.__init__(self, *args, **kwargs) self.numcursors = 0 def cursor(self, *args, **kwargs): self.numcursors += 1 return sqlite3.Connection.cursor(self, *args, **kwargs) con = sqlite3.connect(":memory:", factory=CountCursorsConnection) cur1 = con.cursor() cur2 = con.cursor() print con.numcursors
[ [ 1, 0, 0.0667, 0.0667, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 3, 0, 0.4333, 0.5333, 0, 0.66, 0.2, 293, 0, 2, 0, 0, 809, 0, 2 ], [ 2, 1, 0.3333, 0.2, 1, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "class CountCursorsConnection(sqlite3.Connection):\n def __init__(self, *args, **kwargs):\n sqlite3.Connection.__init__(self, *args, **kwargs)\n self.numcursors = 0\n\n def cursor(self, *args, **kwargs):\n self.numcursors += 1\n return s...
from pysqlite2 import dbapi2 as sqlite3 def collate_reverse(string1, string2): return -cmp(string1, string2) con = sqlite3.connect(":memory:") con.create_collation("reverse", collate_reverse) cur = con.cursor() cur.execute("create table test(x)") cur.executemany("insert into test(x) values (?)", [("a",), ("b",)]) cur.execute("select x from test order by x collate reverse") for row in cur: print row con.close()
[ [ 1, 0, 0.0667, 0.0667, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 2, 0, 0.2333, 0.1333, 0, 0.66, 0.1111, 722, 0, 2, 1, 0, 0, 0, 1 ], [ 13, 1, 0.2667, 0.0667, 1, 0...
[ "from pysqlite2 import dbapi2 as sqlite3", "def collate_reverse(string1, string2):\n return -cmp(string1, string2)", " return -cmp(string1, string2)", "con = sqlite3.connect(\":memory:\")", "con.create_collation(\"reverse\", collate_reverse)", "cur = con.cursor()", "cur.execute(\"create table test...
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table person( firstname, lastname, age ); create table book( title, author, published ); insert into book(title, author, published) values ( 'Dirk Gently''s Holistic Detective Agency', 'Douglas Adams', 1987 ); """)
[ [ 1, 0, 0.0417, 0.0417, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.125, 0.0417, 0, 0.66, 0.3333, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.1667, 0.0417, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\":memory:\")", "cur = con.cursor()", "cur.executescript(\"\"\"\n create table person(\n firstname,\n lastname,\n age\n );\n\n create table book(" ]
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:") # enable extension loading con.enable_load_extension(True) # Load the fulltext search extension con.execute("select load_extension('./fts3.so')") # alternatively you can load the extension using an API call: # con.load_extension("./fts3.so") # disable extension laoding again con.enable_load_extension(False) # example from SQLite wiki con.execute("create virtual table recipe using fts3(name, ingredients)") con.executescript(""" insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes'); insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery'); insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour'); insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter'); """) for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"): print row
[ [ 1, 0, 0.0357, 0.0357, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.1071, 0.0357, 0, 0.66, 0.1429, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 8, 0, 0.2143, 0.0357, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\":memory:\")", "con.enable_load_extension(True)", "con.execute(\"select load_extension('./fts3.so')\")", "con.enable_load_extension(False)", "con.execute(\"create virtual table recipe using fts3(name, ingredients)\")", "con.executescript...
from pysqlite2 import dbapi2 as sqlite3 persons = [ ("Hugo", "Boss"), ("Calvin", "Klein") ] con = sqlite3.connect(":memory:") # Create the table con.execute("create table person(firstname, lastname)") # Fill the table con.executemany("insert into person(firstname, lastname) values (?, ?)", persons) # Print the table contents for row in con.execute("select firstname, lastname from person"): print row # Using a dummy WHERE clause to not let SQLite take the shortcut table deletes. print "I just deleted", con.execute("delete from person where 1=1").rowcount, "rows"
[ [ 1, 0, 0.0476, 0.0476, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.2143, 0.1905, 0, 0.66, 0.1667, 70, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.381, 0.0476, 0, 0....
[ "from pysqlite2 import dbapi2 as sqlite3", "persons = [\n (\"Hugo\", \"Boss\"),\n (\"Calvin\", \"Klein\")\n ]", "con = sqlite3.connect(\":memory:\")", "con.execute(\"create table person(firstname, lastname)\")", "con.executemany(\"insert into person(firstname, lastname) values (?, ?)\", persons)", ...
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb") cur = con.cursor() who = "Yeltsin" age = 72 cur.execute("select name_last, age from people where name_last=:who and age=:age", locals()) print cur.fetchone()
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.25, 0.0833, 0, 0.66, 0.1667, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.4167, 0.0833, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\"mydb\")", "cur = con.cursor()", "who = \"Yeltsin\"", "age = 72", "cur.execute(\"select name_last, age from people where name_last=:who and age=:age\",\n locals())", "print(cur.fetchone())" ]
# Not referenced from the documentation, but builds the database file the other # code snippets expect. from pysqlite2 import dbapi2 as sqlite3 import os DB_FILE = "mydb" if os.path.exists(DB_FILE): os.remove(DB_FILE) con = sqlite3.connect(DB_FILE) cur = con.cursor() cur.execute(""" create table people ( name_last varchar(20), age integer ) """) cur.execute("insert into people (name_last, age) values ('Yeltsin', 72)") cur.execute("insert into people (name_last, age) values ('Putin', 51)") con.commit() cur.close() con.close()
[ [ 1, 0, 0.1429, 0.0357, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.1786, 0.0357, 0, 0.66, 0.0909, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 14, 0, 0.25, 0.0357, 0, 0...
[ "from pysqlite2 import dbapi2 as sqlite3", "import os", "DB_FILE = \"mydb\"", "if os.path.exists(DB_FILE):\n os.remove(DB_FILE)", " os.remove(DB_FILE)", "con = sqlite3.connect(DB_FILE)", "cur = con.cursor()", "cur.execute(\"\"\"\n create table people\n (\n name_last v...
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb") cur = con.cursor() who = "Yeltsin" age = 72 cur.execute("select name_last, age from people where name_last=:who and age=:age", {"who": who, "age": age}) print cur.fetchone()
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.25, 0.0833, 0, 0.66, 0.1667, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.4167, 0.0833, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\"mydb\")", "cur = con.cursor()", "who = \"Yeltsin\"", "age = 72", "cur.execute(\"select name_last, age from people where name_last=:who and age=:age\",\n {\"who\": who, \"age\": age})", "print(cur.fetchone())" ]
from pysqlite2 import dbapi2 as sqlite3 import datetime con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) cur = con.cursor() cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),)) dt = cur.fetchone()[0] print dt, type(dt)
[ [ 1, 0, 0.125, 0.125, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.25, 0.125, 0, 0.66, 0.1667, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 14, 0, 0.5, 0.125, 0, 0.66, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "import datetime", "con = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_COLNAMES)", "cur = con.cursor()", "cur.execute('select ? as \"x [timestamp]\"', (datetime.datetime.now(),))", "dt = cur.fetchone()[0]", "print(dt, type(dt))" ]
from pysqlite2 import dbapi2 as sqlite3 def char_generator(): import string for c in string.letters[:26]: yield (c,) con = sqlite3.connect(":memory:") cur = con.cursor() cur.execute("create table characters(c)") cur.executemany("insert into characters(c) values (?)", char_generator()) cur.execute("select c from characters") print cur.fetchall()
[ [ 1, 0, 0.0667, 0.0667, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 2, 0, 0.3, 0.2667, 0, 0.66, 0.1429, 806, 0, 0, 0, 0, 0, 0, 0 ], [ 1, 1, 0.2667, 0.0667, 1, 0.17,...
[ "from pysqlite2 import dbapi2 as sqlite3", "def char_generator():\n import string\n for c in string.letters[:26]:\n yield (c,)", " import string", " for c in string.letters[:26]:\n yield (c,)", " yield (c,)", "con = sqlite3.connect(\":memory:\")", "cur = con.cursor()", ...
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb") cur = con.cursor() newPeople = ( ('Lebed' , 53), ('Zhirinovsky' , 57), ) for person in newPeople: cur.execute("insert into people (name_last, age) values (?, ?)", person) # The changes will not be saved unless the transaction is committed explicitly: con.commit()
[ [ 1, 0, 0.0625, 0.0625, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 14, 0, 0.1875, 0.0625, 0, 0.66, 0.2, 761, 3, 1, 0, 0, 242, 10, 1 ], [ 14, 0, 0.3125, 0.0625, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "con = sqlite3.connect(\"mydb\")", "cur = con.cursor()", "newPeople = (\n ('Lebed' , 53),\n ('Zhirinovsky' , 57),\n )", "for person in newPeople:\n cur.execute(\"insert into people (name_last, age) values (?, ?)\", person)", " cur.execute(\"ins...
from pysqlite2 import dbapi2 as sqlite3 class Point(object): def __init__(self, x, y): self.x, self.y = x, y def __conform__(self, protocol): if protocol is sqlite3.PrepareProtocol: return "%f;%f" % (self.x, self.y) con = sqlite3.connect(":memory:") cur = con.cursor() p = Point(4.0, -3.2) cur.execute("select ?", (p,)) print cur.fetchone()[0]
[ [ 1, 0, 0.0625, 0.0625, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 3, 0, 0.375, 0.4375, 0, 0.66, 0.1667, 652, 0, 2, 0, 0, 186, 0, 0 ], [ 2, 1, 0.2812, 0.125, 1, 0....
[ "from pysqlite2 import dbapi2 as sqlite3", "class Point(object):\n def __init__(self, x, y):\n self.x, self.y = x, y\n\n def __conform__(self, protocol):\n if protocol is sqlite3.PrepareProtocol:\n return \"%f;%f\" % (self.x, self.y)", " def __init__(self, x, y):\n self....
from pysqlite2 import dbapi2 as sqlite3 class Point(object): def __init__(self, x, y): self.x, self.y = x, y def __repr__(self): return "(%f;%f)" % (self.x, self.y) def adapt_point(point): return "%f;%f" % (point.x, point.y) def convert_point(s): x, y = map(float, s.split(";")) return Point(x, y) # Register the adapter sqlite3.register_adapter(Point, adapt_point) # Register the converter sqlite3.register_converter("point", convert_point) p = Point(4.0, -3.2) ######################### # 1) Using declared types con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) cur = con.cursor() cur.execute("create table test(p point)") cur.execute("insert into test(p) values (?)", (p,)) cur.execute("select p from test") print "with declared types:", cur.fetchone()[0] cur.close() con.close() ####################### # 1) Using column names con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) cur = con.cursor() cur.execute("create table test(p)") cur.execute("insert into test(p) values (?)", (p,)) cur.execute('select p as "p [point]" from test') print "with column names:", cur.fetchone()[0] cur.close() con.close()
[ [ 1, 0, 0.0213, 0.0213, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 3, 0, 0.117, 0.1277, 0, 0.66, 0.0455, 652, 0, 2, 0, 0, 186, 0, 0 ], [ 2, 1, 0.0957, 0.0426, 1, 0...
[ "from pysqlite2 import dbapi2 as sqlite3", "class Point(object):\n def __init__(self, x, y):\n self.x, self.y = x, y\n\n def __repr__(self):\n return \"(%f;%f)\" % (self.x, self.y)", " def __init__(self, x, y):\n self.x, self.y = x, y", " self.x, self.y = x, y", " def...
from pysqlite2 import dbapi2 as sqlite3 class IterChars: def __init__(self): self.count = ord('a') def __iter__(self): return self def next(self): if self.count > ord('z'): raise StopIteration self.count += 1 return (chr(self.count - 1),) # this is a 1-tuple con = sqlite3.connect(":memory:") cur = con.cursor() cur.execute("create table characters(c)") theIter = IterChars() cur.executemany("insert into characters(c) values (?)", theIter) cur.execute("select c from characters") print cur.fetchall()
[ [ 1, 0, 0.0417, 0.0417, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 3, 0, 0.3542, 0.5, 0, 0.66, 0.125, 192, 0, 3, 0, 0, 0, 0, 3 ], [ 2, 1, 0.1875, 0.0833, 1, 0.68, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "class IterChars:\n def __init__(self):\n self.count = ord('a')\n\n def __iter__(self):\n return self\n\n def next(self):", " def __init__(self):\n self.count = ord('a')", " self.count = ord('a')", " def __iter__(self):\n ...
from pysqlite2 import dbapi2 as sqlite3 import apsw apsw_con = apsw.Connection(":memory:") apsw_con.createscalarfunction("times_two", lambda x: 2*x, 1) # Create pysqlite connection from APSW connection con = sqlite3.connect(apsw_con) result = con.execute("select times_two(15)").fetchone()[0] assert result == 30 con.close()
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.1667, 0.0833, 0, 0.66, 0.1667, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 14, 0, 0.3333, 0.0833, 0, ...
[ "from pysqlite2 import dbapi2 as sqlite3", "import apsw", "apsw_con = apsw.Connection(\":memory:\")", "apsw_con.createscalarfunction(\"times_two\", lambda x: 2*x, 1)", "con = sqlite3.connect(apsw_con)", "result = con.execute(\"select times_two(15)\").fetchone()[0]", "con.close()" ]
from pysqlite2 import dbapi2 as sqlite3 import datetime, time def adapt_datetime(ts): return time.mktime(ts.timetuple()) sqlite3.register_adapter(datetime.datetime, adapt_datetime) con = sqlite3.connect(":memory:") cur = con.cursor() now = datetime.datetime.now() cur.execute("select ?", (now,)) print cur.fetchone()[0]
[ [ 1, 0, 0.0714, 0.0714, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.1429, 0.0714, 0, 0.66, 0.125, 426, 0, 2, 0, 0, 426, 0, 0 ], [ 2, 0, 0.3214, 0.1429, 0, 0...
[ "from pysqlite2 import dbapi2 as sqlite3", "import datetime, time", "def adapt_datetime(ts):\n return time.mktime(ts.timetuple())", " return time.mktime(ts.timetuple())", "sqlite3.register_adapter(datetime.datetime, adapt_datetime)", "con = sqlite3.connect(\":memory:\")", "cur = con.cursor()", "...
# Author: Paul Kippes <kippesp@gmail.com> import unittest from pysqlite2 import dbapi2 as sqlite class DumpTests(unittest.TestCase): def setUp(self): self.cx = sqlite.connect(":memory:") self.cu = self.cx.cursor() def tearDown(self): self.cx.close() def CheckTableDump(self): expected_sqls = [ "CREATE TABLE t1(id integer primary key, s1 text, " \ "t1_i1 integer not null, i2 integer, unique (s1), " \ "constraint t1_idx1 unique (i2));" , "INSERT INTO \"t1\" VALUES(1,'foo',10,20);" , "INSERT INTO \"t1\" VALUES(2,'foo2',30,30);" , "CREATE TABLE t2(id integer, t2_i1 integer, " \ "t2_i2 integer, primary key (id)," \ "foreign key(t2_i1) references t1(t1_i1));" , "CREATE TRIGGER trigger_1 update of t1_i1 on t1 " \ "begin " \ "update t2 set t2_i1 = new.t1_i1 where t2_i1 = old.t1_i1; " \ "end;" , "CREATE VIEW v1 as select * from t1 left join t2 " \ "using (id);" ] [self.cu.execute(s) for s in expected_sqls] i = self.cx.iterdump() actual_sqls = [s for s in i] expected_sqls = ['BEGIN TRANSACTION;'] + expected_sqls + \ ['COMMIT;'] [self.assertEqual(expected_sqls[i], actual_sqls[i]) for i in xrange(len(expected_sqls))] def suite(): return unittest.TestSuite(unittest.makeSuite(DumpTests, "Check")) def test(): runner = unittest.TextTestRunner() runner.run(suite()) if __name__ == "__main__": test()
[ [ 1, 0, 0.0577, 0.0192, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0769, 0.0192, 0, 0.66, 0.2, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 3, 0, 0.4615, 0.7115, 0, 0.66,...
[ "import unittest", "from pysqlite2 import dbapi2 as sqlite", "class DumpTests(unittest.TestCase):\n def setUp(self):\n self.cx = sqlite.connect(\":memory:\")\n self.cu = self.cx.cursor()\n\n def tearDown(self):\n self.cx.close()", " def setUp(self):\n self.cx = sqlite.conn...
# Mimic the sqlite3 console shell's .dump command # Author: Paul Kippes <kippesp@gmail.com> def _iterdump(connection): """ Returns an iterator to the dump of the database in an SQL text format. Used to produce an SQL dump of the database. Useful to save an in-memory database for later restoration. This function should not be called directly but instead called from the Connection method, iterdump(). """ cu = connection.cursor() yield('BEGIN TRANSACTION;') # sqlite_master table contains the SQL CREATE statements for the database. q = """ SELECT name, type, sql FROM sqlite_master WHERE sql NOT NULL AND type == 'table' """ schema_res = cu.execute(q) for table_name, type, sql in schema_res.fetchall(): if table_name == 'sqlite_sequence': yield('DELETE FROM sqlite_sequence;') elif table_name == 'sqlite_stat1': yield('ANALYZE sqlite_master;') elif table_name.startswith('sqlite_'): continue # NOTE: Virtual table support not implemented #elif sql.startswith('CREATE VIRTUAL TABLE'): # qtable = table_name.replace("'", "''") # yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\ # "VALUES('table','%s','%s',0,'%s');" % # qtable, # qtable, # sql.replace("''")) else: yield('%s;' % sql) # Build the insert statement for each row of the current table res = cu.execute("PRAGMA table_info('%s')" % table_name) column_names = [str(table_info[1]) for table_info in res.fetchall()] q = "SELECT 'INSERT INTO \"%(tbl_name)s\" VALUES(" q += ",".join(["'||quote(" + col + ")||'" for col in column_names]) q += ")' FROM '%(tbl_name)s'" query_res = cu.execute(q % {'tbl_name': table_name}) for row in query_res: yield("%s;" % row[0]) # Now when the type is 'index', 'trigger', or 'view' q = """ SELECT name, type, sql FROM sqlite_master WHERE sql NOT NULL AND type IN ('index', 'trigger', 'view') """ schema_res = cu.execute(q) for name, type, sql in schema_res.fetchall(): yield('%s;' % sql) yield('COMMIT;')
[ [ 2, 0, 0.5317, 0.9524, 0, 0.66, 0, 339, 0, 1, 0, 0, 0, 0, 11 ], [ 8, 1, 0.127, 0.1111, 1, 0.03, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.2063, 0.0159, 1, 0.03, ...
[ "def _iterdump(connection):\n \"\"\"\n Returns an iterator to the dump of the database in an SQL text format.\n\n Used to produce an SQL dump of the database. Useful to save an in-memory\n database for later restoration. This function should not be called\n directly but instead called from the Conn...
#!/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...
# Run from the commandline: # # python server.py # POST audio to http://localhost:9000 # GET audio from http://localhost:9000 # # A simple server to collect audio using python. To be more secure, # you might want to check the file names and place size restrictions # on the incoming data. import cgi from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class WamiHandler(BaseHTTPRequestHandler): dirname = "/tmp/" def do_GET(self): f = open(self.get_name()) self.send_response(200) self.send_header('content-type','audio/x-wav') self.end_headers() self.wfile.write(f.read()) f.close() def do_POST(self): f = open(self.get_name(), "wb") # Note that python's HTTPServer doesn't support chunked transfer. # Thus, it requires a content-length. length = int(self.headers.getheader('content-length')) print "POST of length " + str(length) f.write(self.rfile.read(length)) f.close(); def get_name(self): filename = 'output.wav'; qs = self.path.split('?',1); if len(qs) == 2: params = cgi.parse_qs(qs[1]) if params['name']: filename = params['name'][0]; return WamiHandler.dirname + filename def main(): try: server = HTTPServer(('', 9000), WamiHandler) print 'Started server...' server.serve_forever() except KeyboardInterrupt: print 'Stopping server' server.socket.close() if __name__ == '__main__': main()
[ [ 1, 0, 0.2075, 0.0189, 0, 0.66, 0, 934, 0, 1, 0, 0, 934, 0, 0 ], [ 1, 0, 0.2264, 0.0189, 0, 0.66, 0.25, 801, 0, 2, 0, 0, 801, 0, 0 ], [ 3, 0, 0.5189, 0.5283, 0, 0....
[ "import cgi", "from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer", "class WamiHandler(BaseHTTPRequestHandler):\n dirname = \"/tmp/\"\n \n def do_GET(self):\n f = open(self.get_name())\n self.send_response(200)\n self.send_header('content-type','audio/x-wav')\n se...
''' Created on 21-03-2011 @author: maciek ''' def formatString(format, **kwargs): ''' ''' if not format: return '' for arg in kwargs.keys(): format = format.replace("{" + arg + "}", "##" + arg + "##") format = format.replace ("{", "{{") format = format.replace("}", "}}") for arg in kwargs.keys(): format = format.replace("##" + arg + "##", "{" + arg + "}") res = format.format(**kwargs) res = res.replace("{{", "{") res = res.replace("}}", "}") return res
[ [ 8, 0, 0.1304, 0.2174, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.6739, 0.6957, 0, 0.66, 1, 798, 0, 2, 1, 0, 0, 0, 9 ], [ 8, 1, 0.413, 0.087, 1, 0.05, 0, ...
[ "'''\nCreated on 21-03-2011\n\n@author: maciek\n'''", "def formatString(format, **kwargs):\n '''\n '''\n if not format: return ''\n \n for arg in kwargs.keys():\n format = format.replace(\"{\" + arg + \"}\", \"##\" + arg + \"##\")\n format = format.replace (\"{\", \"{{\")", " '''\n ...
''' Created on 21-03-2011 @author: maciek ''' from IndexGenerator import IndexGenerator from optparse import OptionParser import os import tempfile import shutil import logging logging.basicConfig(level = logging.DEBUG) parser = OptionParser() parser.add_option('-n', '--app-name', action='store', dest='appName', help='aplication name') parser.add_option('-u', '--release-urls', action='store', dest='releaseUrls', help='URLs of download files - as coma separated list of entrires') parser.add_option('-d', '--destination-directory', action='store', dest='otaAppDir', help='Directory where OTA files are created') parser.add_option('-v', '--version', action='store', dest='version', help='Version of the application') parser.add_option('-r', '--releases', action='store', dest='releases', help='Release names of the application') parser.add_option('-R', '--release-notes', action='store', dest='releaseNotes', help='Release notes of the application (in txt2tags format)') parser.add_option('-D', '--description', action='store', dest='description', help='Description of the application (in txt2tags format)') (options, args) = parser.parse_args() if options.appName == None: parser.error("Please specify the appName.") elif options.releaseUrls == None: parser.error("Please specify releaseUrls") elif options.otaAppDir == None: parser.error("Please specify destination directory") elif options.version == None: parser.error("Please specify version") elif options.releases == None: parser.error("Please specify releases") elif options.releaseNotes == None: parser.error("Please specify releaseNotes") elif options.description == None: parser.error("Please specify description") appName = options.appName releaseUrls = options.releaseUrls otaAppDir = options.otaAppDir version = options.version releases = options.releases releaseNotes = options.releaseNotes description = options.description def findIconFilename(): iconPath = "res/drawable-hdpi/icon.png" if not os.path.exists(iconPath): iconPath = "res/drawable-mdpi/icon.png" if not os.path.exists(iconPath): iconPath = "res/drawable-ldpi/icon.png" if not os.path.exists(iconPath): iconPath = "res/drawable/icon.png" logging.debug("IconPath: "+iconPath) return iconPath def createOTApackage(): ''' crates all needed files in tmp dir ''' releaseNotesContent = open(releaseNotes).read() descriptionContent = open(description).read() indexGenerator = IndexGenerator(appName, releaseUrls, releaseNotesContent, descriptionContent, version, releases) index = indexGenerator.get(); tempIndexFile = tempfile.TemporaryFile() tempIndexFile.write(index) tempIndexFile.flush() tempIndexFile.seek(0) return tempIndexFile tempIndexFile = createOTApackage() if not os.path.isdir(otaAppDir): logging.debug("creating dir: "+otaAppDir) os.mkdir(otaAppDir) else: logging.warning("dir: "+otaAppDir+" exists") indexFile = open(os.path.join(otaAppDir,"index.html"),'w') shutil.copyfileobj(tempIndexFile, indexFile) srcIconFileName = findIconFilename() disIconFileName = os.path.join(otaAppDir,"Icon.png") shutil.copy(srcIconFileName,disIconFileName)
[ [ 8, 0, 0.0341, 0.0568, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0682, 0.0114, 0, 0.66, 0.0303, 933, 0, 1, 0, 0, 933, 0, 0 ], [ 1, 0, 0.0795, 0.0114, 0, 0.66...
[ "'''\nCreated on 21-03-2011\n\n@author: maciek\n'''", "from IndexGenerator import IndexGenerator", "from optparse import OptionParser", "import os", "import tempfile", "import shutil", "import logging", "logging.basicConfig(level = logging.DEBUG)", "parser = OptionParser()", "parser.add_option('-n...
''' Created on 21-03-2011 @author: maciek ''' from formater import formatString import os class IndexGenerator(object): ''' Generates Index.html for iOS app OTA distribution ''' basePath = os.path.dirname(__file__) templateFile = os.path.join(basePath,"templates/index.tmpl") releaseUrls = "" appName = "" changeLog = "" description = "" version = "" release = "" def __init__(self,appName, releaseUrls, changeLog, description, version, releases): ''' Constructor ''' self.appName = appName self.releaseUrls = releaseUrls self.changeLog = changeLog self.description = description self.version = version self.releases = releases def get(self): ''' returns index.html source code from template file ''' urlList = self.releaseUrls.split(",") releaseList = self.releases.split(",") generatedHtml="" count=0; for release in releaseList: generatedHtml += " <li>\n" generatedHtml += " <h3><a href=\"javascript:load('" + urlList[count] + "')\">" + release + "</a></h3>\n" generatedHtml += " </li>\n" count += 1 template = open(self.templateFile).read() index = formatString(template, downloads=generatedHtml, changeLog=self.changeLog, appName=self.appName, description=self.description, version = self.version); return index
[ [ 8, 0, 0.0526, 0.0877, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1053, 0.0175, 0, 0.66, 0.3333, 11, 0, 1, 0, 0, 11, 0, 0 ], [ 1, 0, 0.1228, 0.0175, 0, 0.66, ...
[ "'''\nCreated on 21-03-2011\n\n@author: maciek\n'''", "from formater import formatString", "import os", "class IndexGenerator(object):\n '''\n Generates Index.html for iOS app OTA distribution\n '''\n basePath = os.path.dirname(__file__)\n templateFile = os.path.join(basePath,\"templates/index....
# Django settings for iphone12580 project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'w%4yt1@#$mqd$*_ip%1xhl+(mbg$+4i5qa5t#kp@ac5eyvp40d' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'iphone12580.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. '/Users/uc0079/iphone12580/templates' ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', )
[ [ 14, 0, 0.0375, 0.0125, 0, 0.66, 0, 309, 1, 0, 0, 0, 0, 4, 0 ], [ 14, 0, 0.05, 0.0125, 0, 0.66, 0.0455, 7, 2, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0875, 0.0375, 0, 0.66,...
[ "DEBUG = True", "TEMPLATE_DEBUG = DEBUG", "ADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)", "MANAGERS = ADMINS", "DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.", "DATABASE_NAME = '' # Or path to database file if using sqlite...
from django.db import models # Create your models here.
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 40, 0, 1, 0, 0, 40, 0, 0 ] ]
[ "from django.db import models" ]
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
[ [ 8, 0, 0.1522, 0.2609, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3478, 0.0435, 0, 0.66, 0.3333, 944, 0, 1, 0, 0, 944, 0, 0 ], [ 3, 0, 0.5435, 0.2609, 0, 0.66...
[ "\"\"\"\nThis file demonstrates two different styles of tests (one doctest and one\nunittest). These will both pass when you run \"manage.py test\".\n\nReplace these with more appropriate tests for your application.\n\"\"\"", "from django.test import TestCase", "class SimpleTest(TestCase):\n def test_basic_a...
# -*- coding: utf-8 -*- from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.shortcuts import render_to_response from django.core.paginator import Paginator,InvalidPage,EmptyPage def test(request): return HttpResponse("hello iphone") def index(request): return render_to_response("index.html",locals()) def dis_info(request): return render_to_response("discount.html",locals()) def hotel_info(request): return render_to_response("hotel_info.html",locals()) def flight_info(request): return render_to_response("flight_info.html",locals())
[ [ 1, 0, 0.1053, 0.0526, 0, 0.66, 0, 779, 0, 3, 0, 0, 779, 0, 0 ], [ 1, 0, 0.1579, 0.0526, 0, 0.66, 0.1429, 852, 0, 1, 0, 0, 852, 0, 0 ], [ 1, 0, 0.2105, 0.0526, 0, ...
[ "from django.http import HttpResponseRedirect, HttpResponse, Http404", "from django.shortcuts import render_to_response", "from django.core.paginator import Paginator,InvalidPage,EmptyPage", "def test(request):\n return HttpResponse(\"hello iphone\")", " return HttpResponse(\"hello iphone\")", "def ...
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
[ [ 1, 0, 0.1818, 0.0909, 0, 0.66, 0, 879, 0, 1, 0, 0, 879, 0, 0 ], [ 7, 0, 0.5, 0.5455, 0, 0.66, 0.5, 0, 0, 1, 0, 0, 0, 0, 2 ], [ 1, 1, 0.3636, 0.0909, 1, 0.47, ...
[ "from django.core.management import execute_manager", "try:\n import settings # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\\nYou'll have to run dj...
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^iphone12580/', include('iphone12580.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^$','iphone12580.coupon.views.index'), (r'^discount','iphone12580.coupon.views.dis_info'), #优惠券信息 (r'^hotel','iphone12580.coupon.views.hotel_info'), #酒店信息 (r'^flight','iphone12580.coupon.views.flight_info') #机票信息 (r'^test/','iphone12580.coupon.views.test'), #临时测试 )
[ [ 1, 0, 0.0455, 0.0455, 0, 0.66, 0, 341, 0, 1, 0, 0, 341, 0, 0 ], [ 1, 0, 0.1818, 0.0455, 0, 0.66, 0.3333, 302, 0, 1, 0, 0, 302, 0, 0 ], [ 8, 0, 0.2273, 0.0455, 0, ...
[ "from django.conf.urls.defaults import *", "from django.contrib import admin", "admin.autodiscover()", "urlpatterns = patterns('',\n # Example:\n # (r'^iphone12580/', include('iphone12580.foo.urls')),\n\n # Uncomment the admin/doc line below and add 'django.contrib.admindocs' \n # to INSTALLED_APP...
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
[ [ 1, 0, 0.1818, 0.0909, 0, 0.66, 0, 879, 0, 1, 0, 0, 879, 0, 0 ], [ 7, 0, 0.5, 0.5455, 0, 0.66, 0.5, 0, 0, 1, 0, 0, 0, 0, 2 ], [ 1, 1, 0.3636, 0.0909, 1, 0.05, ...
[ "from django.core.management import execute_manager", "try:\n import settings # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\\nYou'll have to run dj...
import sys import os from PIL import Image def detectEdge(img, w, h): left, upper, right, lower = w,h,0,0 pixels = img.load() threshold = 10 for x in range(0,w): for y in xrange(0,h): pix = pixels[x,y] if (pix[0]<(254-threshold) or pix[1]<(254-threshold) or pix[2]<(254-threshold)) and pix[3]>0: left, upper, right, lower = min(x,left),min(y,upper),max(x,right),max(y,lower) return (left, upper, right, lower) if __name__ == '__main__': dirList=os.listdir(sys.argv[1]) for fname in dirList: if fname.endswith(sys.argv[3]): img = Image.open(os.path.join(sys.argv[1],fname)) width, height = img.size box = detectEdge(img,width,height) print fname, box img2 = img.crop(box) # img2 = img2.resize((width, height), Image.ANTIALIAS) img2 = img2.resize(((box[2]-box[0]), (box[3]-box[1])), Image.ANTIALIAS) img2.save(os.path.join(sys.argv[2],fname))
[ [ 1, 0, 0.0645, 0.0323, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0968, 0.0323, 0, 0.66, 0.25, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.129, 0.0323, 0, 0.6...
[ "import sys", "import os", "from PIL import Image", "def detectEdge(img, w, h):\n \n left, upper, right, lower = w,h,0,0\n pixels = img.load()\n threshold = 10\n for x in range(0,w):\n for y in xrange(0,h):\n pix = pixels[x,y]", " left, upper, right, lower = w,h,0,0", "...
# Run from the commandline: # # python server.py # POST audio to http://localhost:9000 # GET audio from http://localhost:9000 # # A simple server to collect audio using python. To be more secure, # you might want to check the file names and place size restrictions # on the incoming data. import cgi from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class WamiHandler(BaseHTTPRequestHandler): dirname = "/tmp/" def do_GET(self): f = open(self.get_name()) self.send_response(200) self.send_header('content-type','audio/x-wav') self.end_headers() self.wfile.write(f.read()) f.close() def do_POST(self): f = open(self.get_name(), "wb") # Note that python's HTTPServer doesn't support chunked transfer. # Thus, it requires a content-length. length = int(self.headers.getheader('content-length')) print "POST of length " + str(length) f.write(self.rfile.read(length)) f.close(); def get_name(self): filename = 'output.wav'; qs = self.path.split('?',1); if len(qs) == 2: params = cgi.parse_qs(qs[1]) if params['name']: filename = params['name'][0]; return WamiHandler.dirname + filename def main(): try: server = HTTPServer(('', 9000), WamiHandler) print 'Started server...' server.serve_forever() except KeyboardInterrupt: print 'Stopping server' server.socket.close() if __name__ == '__main__': main()
[ [ 1, 0, 0.2075, 0.0189, 0, 0.66, 0, 934, 0, 1, 0, 0, 934, 0, 0 ], [ 1, 0, 0.2264, 0.0189, 0, 0.66, 0.25, 801, 0, 2, 0, 0, 801, 0, 0 ], [ 3, 0, 0.5189, 0.5283, 0, 0....
[ "import cgi", "from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer", "class WamiHandler(BaseHTTPRequestHandler):\n dirname = \"/tmp/\"\n \n def do_GET(self):\n f = open(self.get_name())\n self.send_response(200)\n self.send_header('content-type','audio/x-wav')\n se...
#!/usr/bin/env python import time import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) DEBUG = 0 # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7) def readadc(adcnum, clockpin, mosipin, misopin, cspin): if ((adcnum > 7) or (adcnum < 0)): return -1 GPIO.output(cspin, True) GPIO.output(clockpin, False) # start clock low GPIO.output(cspin, False) # bring CS low commandout = adcnum print "---------------------------" displayNumber("Base:", adcnum) commandout |= 0x18 # start bit + single-ended bit displayNumber("0x18:", adcnum) commandout <<= 3 # we only need to send 5 bits here for i in range(5): displayNumber(("i:%i" % i), adcnum) if (commandout & 0x80): # 0x80 = 10000000 GPIO.output(mosipin, True) else: GPIO.output(mosipin, False) commandout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout = 0 # read in one empty bit, one null bit and 10 ADC bits for i in range(12): GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout <<= 1 if (GPIO.input(misopin)): adcout |= 0x1 displayNumber(("ADCOUT i:%i" % i), adcout) GPIO.output(cspin, True) adcout >>= 1 # first bit is 'null' so drop it displayNumber("final ADCOUT:", adcout) return adcout def displayNumber(prefix, num): print prefix, num, "\t", hex(num), "\t", bin(num) # change these as desired - they're the pins connected from the # SPI port on the ADC to the Cobbler SPICLK = 18 SPIMISO = 23 SPIMOSI = 24 SPICS = 25 # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) # 10k trim pot connected to adc #0 potentiometer_adc = 0; last_read = 0 # this keeps track of the last potentiometer value tolerance = 5 # to keep from being jittery we'll only change # volume when the pot has moved more than 5 'counts' while True: # we'll assume that the pot didn't move trim_pot_changed = False # read the analog pin trim_pot = readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS) # how much has it changed since the last read? pot_adjust = abs(trim_pot - last_read) if DEBUG: print "trim_pot :", trim_pot print "pot_adjust:", pot_adjust print "last_read :", last_read if ( pot_adjust > tolerance ): trim_pot_changed = True if DEBUG: print "trim_pot_changed", trim_pot_changed if ( trim_pot_changed ): set_volume = trim_pot / 10.24 # convert 10bit adc0 (0-1024) trim pot read into 0-100 volume level set_volume = round(set_volume) # round out decimal value set_volume = int(set_volume) # cast volume as integer print 'Volume = {volume}%' .format(volume = set_volume) # set_vol_cmd = 'sudo amixer cset numid=1 -- {volume}% > /dev/null' .format(volume = set_volume) # os.system(set_vol_cmd) # set volume if DEBUG: print "set_volume", set_volume print "tri_pot_changed", set_volume # save the potentiometer reading for the next loop last_read = trim_pot # hang out and do nothing for a half second time.sleep(0.5)
[ [ 1, 0, 0.0182, 0.0091, 0, 0.66, 0, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 1, 0, 0.0273, 0.0091, 0, 0.66, 0.0556, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0364, 0.0091, 0, ...
[ "import time", "import os", "import RPi.GPIO as GPIO", "GPIO.setmode(GPIO.BCM)", "DEBUG = 0", "def readadc(adcnum, clockpin, mosipin, misopin, cspin):\n if ((adcnum > 7) or (adcnum < 0)):\n return -1\n GPIO.output(cspin, True)\n\n GPIO.output(clockpin, False) # start c...
#coding=utf8 from django.db import models class Address(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=100) pub_date = models.DateField()
[ [ 1, 0, 0.2857, 0.1429, 0, 0.66, 0, 40, 0, 1, 0, 0, 40, 0, 0 ], [ 3, 0, 0.7857, 0.5714, 0, 0.66, 1, 149, 0, 0, 0, 0, 996, 0, 3 ], [ 14, 1, 0.7143, 0.1429, 1, 0.28, ...
[ "from django.db import models", "class Address(models.Model):\n name = models.CharField(max_length=20)\n address = models.CharField(max_length=100)\n pub_date = models.DateField()", " name = models.CharField(max_length=20)", " address = models.CharField(max_length=100)", " pub_date = models.Date...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
[ [ 8, 0, 0.2188, 0.375, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.5, 0.0625, 0, 0.66, 0.5, 944, 0, 1, 0, 0, 944, 0, 0 ], [ 3, 0, 0.8438, 0.375, 0, 0.66, 1,...
[ "\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"", "from django.test import TestCase", "class SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\...
from django.conf.urls.defaults import patterns, url __author__ = 'Administrator' urlpatterns = patterns('address.views', url(r'^test/$','test') )
[ [ 1, 0, 0.1667, 0.1667, 0, 0.66, 0, 341, 0, 2, 0, 0, 341, 0, 0 ], [ 14, 0, 0.5, 0.1667, 0, 0.66, 0.5, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.8333, 0.5, 0, 0.66, ...
[ "from django.conf.urls.defaults import patterns, url", "__author__ = 'Administrator'", "urlpatterns = patterns('address.views',\n url(r'^test/$','test')\n)" ]
from django.contrib import admin from address.models import Address __author__ = 'Administrator' admin.site.register(Address)
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 302, 0, 1, 0, 0, 302, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.3333, 980, 0, 1, 0, 0, 980, 0, 0 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.6667,...
[ "from django.contrib import admin", "from address.models import Address", "__author__ = 'Administrator'", "admin.site.register(Address)" ]
# Create your views here. import urllib2 from django.http import HttpResponse from django.shortcuts import render_to_response from models import Address def latest_address(request): addresslist = Address.objects.order_by('-pub_date')[:10] return render_to_response('latest_address.html', {'addresslist':addresslist}) def test(request): ret = urllib2.urlopen("http://friend.renren.com/GetFriendList.do?id=227638867").read() print ret return HttpResponse(ret)
[ [ 1, 0, 0.1429, 0.0714, 0, 0.66, 0, 345, 0, 1, 0, 0, 345, 0, 0 ], [ 1, 0, 0.2143, 0.0714, 0, 0.66, 0.2, 779, 0, 1, 0, 0, 779, 0, 0 ], [ 1, 0, 0.2857, 0.0714, 0, 0.6...
[ "import urllib2", "from django.http import HttpResponse", "from django.shortcuts import render_to_response", "from models import Address", "def latest_address(request):\n addresslist = Address.objects.order_by('-pub_date')[:10]\n return render_to_response('latest_address.html', {'addresslist':addressl...
from BeautifulSoup import BeautifulSoup __author__ = 'Administrator' import urllib,urllib2,cookielib from BeautifulSoup import BeautifulSoup myCookie = urllib2.HTTPCookieProcessor(cookielib.CookieJar()) openner = urllib2.build_opener(myCookie) post_data = {'email':'yinjj472@nenu.edu.cn', 'password':'112074', 'origURL':'http://www.renren.com/Home.do', 'domain':'renren.com'} req = urllib2.Request('http://www.renren.com/PLogin.do', urllib.urlencode(post_data)) html_src = openner.open(req).read() #print(html_src),"####################" #parser = BeautifulSoup(html_src) # #article_list = parser.find('div', 'feed-list').findAll('article') #for my_article in article_list: # state = [] # for my_tag in my_article.h3.contents: # factor = my_tag.string # if factor != None: # factor = factor.replace(u'\xa0','') # factor = factor.strip(u'\r\n') # factor = factor.strip(u'\n') # state.append(factor) # print ' '.join(state) req = urllib2.Request('http://friend.renren.com/GetFriendList.do?curpage=2&id=227638867') html_src = openner.open(req).read() print(html_src)
[ [ 1, 0, 0.0312, 0.0312, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 14, 0, 0.0938, 0.0312, 0, 0.66, 0.0909, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.1562, 0.0312, 0, 0...
[ "from BeautifulSoup import BeautifulSoup", "__author__ = 'Administrator'", "import urllib,urllib2,cookielib", "from BeautifulSoup import BeautifulSoup", "myCookie = urllib2.HTTPCookieProcessor(cookielib.CookieJar())", "openner = urllib2.build_opener(myCookie)", "post_data = {'email':'yinjj472@nenu.edu.c...