code
stringlengths
1
1.72M
language
stringclasses
1 value
# coding: utf8 EXPERIMENTAL_STUFF = True if EXPERIMENTAL_STUFF: if is_mobile: response.view = response.view.replace('default/', 'default.mobile/') response.menu = [] import re from gluon.admin import * from gluon.fileutils import abspath, read_file, write_file from gluon.utils import web2py_uuid ...
Python
response.files = response.files[:3] response.menu = [] def index(): return locals() def about(): return locals()
Python
# -*- coding: utf-8 -*- import os import uuid import re import pickle import urllib import glob from gluon.admin import app_create, plugin_install from gluon.fileutils import abspath, read_file, write_file def reset(session): session.app = { 'name': '', 'params': [('title', 'My New App'), ...
Python
# -*- coding: utf-8 -*- response.menu = [ (T('Home'), False, URL('default', 'index')), (T('About'), False, URL('default', 'what')), (T('Download'), False, URL('default', 'download')), (T('Docs & Resources'), False, URL('default', 'documentation')), (T('Support'), False, URL('default', 'support')), ...
Python
session.connect(request,response,cookie_key='yoursecret')
Python
def group_feed_reader(group, mode='div', counter='5'): """parse group feeds""" url = "http://groups.google.com/group/%s/feed/rss_v2_0_topics.xml?num=%s" %\ (group, counter) from gluon.contrib import feedparser g = feedparser.parse(url) if mode == 'div': html = XML(TAG.BLOCKQUOTE(...
Python
import gluon.template markmin_dict = dict( code_python=lambda code: str(CODE(code)), template=lambda code: gluon.template.render(code, context=globals()), sup=lambda code: '<sup style="font-size:0.5em;">%s</sup>' % code, br=lambda n: '<br>' * int(n), groupdates=lambda group: group_feed_read...
Python
def hello1(): """ simple page without template """ return 'Hello World' def hello2(): """ simple page without template but with internationalization """ return T('Hello World') def hello3(): """ page rendered by template simple_examples/index3.html or generic.html""" return dict(message=...
Python
def index(): return dict() def data(): if not session.m or len(session.m) == 10: session.m = [] if request.vars.q: session.m.append(request.vars.q) session.m.sort() return TABLE(*[TR(v) for v in session.m]).xml() def flash(): response.flash = 'this text should appear!' re...
Python
def variables(): return dict(a=10, b=20) def test_for(): return dict() def test_if(): return dict() def test_try(): return dict() def test_def(): return dict() def escape(): return dict(message='<h1>text is scaped</h1>') def xml(): return dict(message=XML('<h1>text is not escaped...
Python
def form(): """ a simple entry form with various types of objects """ form = FORM(TABLE( TR('Your name:', INPUT(_type='text', _name='name', requires=IS_NOT_EMPTY())), TR('Your email:', INPUT(_type='text', _name='email', requires=IS_EMAIL())), TR('Admin', INPUT(_typ...
Python
# -*- coding: utf-8 -*- # ########################################################## # ## make sure administrator is on localhost # ########################################################### import os import socket import datetime import copy import gluon.contenttype import gluon.fileutils try: import pygraphvi...
Python
def counter(): """ every time you reload, it increases the session.counter """ if not session.counter: session.counter = 0 session.counter += 1 return dict(counter=session.counter)
Python
# -*- coding: utf-8 -*- from gluon.fileutils import read_file response.title = T('web2py Web Framework') response.keywords = T('web2py, Python, Web Framework') response.description = T('web2py Web Framework') session.forget() cache_expire = not request.is_local and 300 or 0 @cache('index', time_expire=cache_expire...
Python
def civilized(): response.menu = [['civilized', True, URL('civilized' )], ['slick', False, URL('slick')], ['basic', False, URL('basic')]] response.flash = 'you clicked on civilized' return dict(message='you clicked on civilized') def slick(...
Python
session.forget() def get(args): if args[0].startswith('__'): return None try: obj = globals(),get(args[0]) for k in range(1,len(args)): obj = getattr(obj,args[k]) return obj except: return None def vars(): """the running controlle...
Python
import time def cache_in_ram(): """cache the output of the lambda function in ram""" t = cache.ram('time', lambda: time.ctime(), time_expire=5) return dict(time=t, link=A('click to reload', _href=URL(r=request))) def cache_on_disk(): """cache the output of the lambda function on disk""" t = ca...
Python
from gluon.contrib.spreadsheet import Sheet def callback(): return cache.ram('sheet1', lambda: None, None).process(request) def index(): sheet = cache.ram('sheet1', lambda: Sheet(10, 10, URL('callback')), 0) #sheet.cell('r0c3',value='=r0c0+r0c1+r0c2',readonly=True) return dict(sheet=sheet)
Python
# coding: utf8 { '!langcode!': 'zh-tw', '!langname!': '中文', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新" 是選擇性的條件式, 格式就像 "欄位1=\'值\'". 但是 JOIN 的資料不可以使用 update 或是 delete"', '%s %%{row} deleted': '已刪除 %s 筆', '%s %%{row} updated': '已更新 %s 筆', '%s s...
Python
# coding: utf8 { '!=': '!=', '!langcode!': 'it', '!langname!': 'Italiano', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOI...
Python
# coding: utf8 { '!langcode!': 'es', '!langname!': 'Español', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"actualice" es una expresión opcional como "campo1=\'nuevo_valor\'". No se puede actualizar o eliminar resultados de un JOIN', '%s %%{row} de...
Python
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'выбрана': ['выбраны','выбрано'], 'запись': ['записи','записей'], 'изменена': ['изменены','изменено'], 'строка': ['строки','строк'], 'удалена': ['удалены','удалено'], 'день': ['дня', 'дней'], 'месяц': ['месяца','мес...
Python
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'account': ['accounts'], 'book': ['books'], 'is': ['are'], 'man': ['men'], 'miss': ['misses'], 'person': ['people'], 'quark': ['quarks'], 'shop': ['shops'], 'this': ['these'], 'was': ['were'], 'woman': ['women'], }
Python
# coding: utf8 { '!langcode!': 'cs-cz', '!langname!': 'čeština', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': 'Kolonka "Upravit" je nepovinný výraz, například "pole1=\'nováhodnota\'". Výsledky databázového JOINu nemůžete mazat ani upravovat.', ...
Python
# coding: utf8 { '!langcode!': 'my', '!langname!': 'Malay', '%d days ago': '%d hari yang lalu', '%d hours ago': '%d jam yang lalu', '%d minutes ago': '%d minit yang lalu', '%d months ago': '%d bulan yang lalu', '%d seconds ago': '%d saat yang lalu', '%d seconds from now': '%d saat dari sekarang', '%d weeks ago': '%d mi...
Python
# coding: utf8 { '!langcode!': 'sk', '!langname!': 'Slovenský', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" je voliteľný výraz ako "field1=\'newvalue\'". Nemôžete upravovať alebo zmazať výsledky JOINu', '%s %%{row} deleted': '%s zmazaných...
Python
# coding: utf8 { '!langcode!': 'uk', '!langname!': 'Українська', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Оновити" це додатковий вираз, такий, як "field1=\'нове_значення\'". Ви не можете змінювати або вилучати дані об\'єднаних таблиць.', '%d d...
Python
# coding: utf8 { '!langcode!': 'pl', '!langname!': 'Polska', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:', '%s %%{row} delete...
Python
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'vteřina': ['vteřiny', 'vteřin'], 'vteřinou': ['vteřinami', 'vteřinami'], 'minuta': ['minuty', 'minut'], 'minutou': ['minutami', 'minutami'], 'hodina': ['hodiny','hodin'], 'hodinou': ['hodinami','hodinami'],...
Python
# coding: utf8 { '!langcode!': 'ru', '!langname!': 'Русский', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Изменить" - необязательное выражение вида "field1=\'новое значение\'". Результаты операции JOIN нельзя изменить или удалить.', '%d days ago'...
Python
# coding: utf8 { '!langcode!': 'pt', '!langname!': 'Português', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "field1=\'newvalue\'". Não pode actualizar ou eliminar os resultados de um JOIN', '%s %%{row} delete...
Python
# coding: utf8 { '!langcode!': 'hi-in', '!langname!': 'हिन्दी', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%s %%{row} deleted': '%...
Python
# coding: utf8 { '!langcode!': 'hu', '!langname!': 'Magyar', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%s %%{row} deleted': '%s s...
Python
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'байт': ['байти','байтів'], 'годину': ['години','годин'], 'елемент': ['елементи','елементів'], 'запис': ['записи','записів'], 'поцілювання': ['поцілювання','поцілювань'], 'рядок': ['рядки','рядків'], 'секунду': ['се...
Python
# coding: utf8 { '!langcode!': 'pt-br', '!langname!': 'Português (do Brasil)', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1=\'novovalor\'". Você não pode atualizar ou apagar os resultados de um JOIN', ...
Python
# coding: utf8 { '!langcode!': 'fr', '!langname!': 'Français', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOI...
Python
# coding: utf8 { '!langcode!': 'fr-ca', '!langname!': 'Français (Canadien)', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résul...
Python
# coding: utf8 { '!langcode!': 'nl', '!langname!': 'Nederlands', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%(nrows)s records foun...
Python
# coding: utf8 { '!langcode!': 'en-us', '!langname!': 'English (US)', '%s %%(shop)': '%s %%(shop)', '%s %%(shop[0])': '%s %%(shop[0])', '%s %%{quark[0]}': '%s %%{quark[0]}', '%s %%{shop[0]}': '%s %%{shop[0]}', '%s %%{shop}': '%s %%{shop}', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '@markmin\x01*...
Python
# coding: utf8 { '!=': '!=', '!langcode!': 'ro', '!langname!': 'Română', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" (actualizează) este o expresie opțională precum "câmp1=\'valoare_nouă\'". Nu puteți actualiza sau șterge rezultatele unui...
Python
# coding: utf8 { '!langcode!': 'id', '!langname!': 'Indonesian', '%d days ago': '%d hari yang lalu', '%d hours ago': '%d jam yang lalu', '%d minutes ago': '%d menit yang lalu', '%d months ago': '%d bulan yang lalu', '%d seconds ago': '%d detik yang lalu', '%d seconds from now': '%d detik dari sekarang', '%d weeks ago':...
Python
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### response.logo...
Python
# -*- 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 ######################################################################### ...
Python
# -*- coding: utf-8 -*- # ########################################################## # ## make sure administrator is on localhost # ########################################################### import os import socket import datetime import copy import gluon.contenttype import gluon.fileutils try: import pygraphvi...
Python
# -*- 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...
Python
# -*- 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 # # ...
Python
#!/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: ...
Python
""" 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...
Python
#!/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: ...
Python
#!/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 Soft...
Python
"""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('.', out...
Python
#!/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 Soft...
Python
#!/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 Soft...
Python
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 whi...
Python
""" A special directive for generating a matplotlib plot. .. warning:: This is a hacked version of plot_directive.py from Matplotlib. It's very much subject to change! Usage ----- Can be used like this:: .. plot:: examples/example.py .. plot:: import matplotlib.pyplot as plt plt.plot(...
Python
"""Extract reference documentation from the NumPy source tree. """ import inspect import textwrap import re import pydoc from StringIO import StringIO from warnings import warn 4 class Reader(object): """A line-based string reader. """ def __init__(self, data): """ Parameters ----...
Python
# # 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 LaTeXTranslat...
Python
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. ...
Python
""" =========== autosummary =========== Sphinx extension that adds an autosummary:: directive, which can be used to generate function/method/attribute/etc. summary lists, similar to those output eg. by Epydoc and other API doc generation tools. An :autolink: role is also provided. autosummary directive -------------...
Python
#!/usr/bin/env python r""" autosummary_generate.py OPTIONS FILES Generate automatic RST source files for items referred to in autosummary:: directives. Each generated RST file contains a single auto*:: directive which extracts the docstring of the referred item. Example Makefile rule:: generate: ./e...
Python
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/py...
Python
""" 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. ...
Python
""" ============== 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 ...
Python
from numpydoc import setup
Python
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): ret...
Python
""" ======== 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....
Python
# -*- 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...
Python
#!/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)...
Python
#!/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 paramete...
Python
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 handle...
Python
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_co...
Python
import _mysql import logger import hashlib class DbHandler: ## ## Ansluter till databas of verifierar att tabellerna finns. ## Om de inte finns, skapa dem.. ## def __init__(self, pSettings): # Connect to database: try: self.db=_mysql.connect(host=pSettings.host, user=pSettings.username, passwd=pSetti...
Python
## ## 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" u...
Python
import os import sys import re import shutil import commands import _mysql import logger import metrics # Find and insert commits to database def analyze_scmlog(project, url, vcsinfo, db): logger.printinfo("Getting changelog from vcs") if os.path.exists ('/tmp/x90analy'): shutil.rmtree("/tmp/x90analy") # Chec...
Python
## ## 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("...
Python
#==================================================================== # 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 ...
Python
# coding=utf-8 # (The line above is necessary so that I can use 世界 in the # *comment* below without Python getting all bent out of shape.) # Copyright 2007-2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may o...
Python
#!/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 ...
Python
#!/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 ...
Python
#!/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) ...
Python
#!/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) ...
Python
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 s...
Python
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("...
Python
#!/usr/bin/env python from pysqlite2.test import test test()
Python
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 ...
Python
# Gerhard Haering <gh@gharing.d> is responsible for the hacked version of this # module. # # This is a modified version of the bdist_wininst distutils command to make it # possible to build installers *with extension modules* on Unix. """distutils.command.bdist_wininst Implements the Distutils 'bdist_wininst' command...
Python
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(":memo...
Python
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) ...
Python
#!/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 ...
Python
# -*- 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 pic...
Python
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) ,...
Python
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 ever...
Python
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 (na...
Python
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 ...
Python
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb")
Python
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("creat...
Python
# 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 == ""...
Python
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"]
Python
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,...
Python
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.executes...
Python