code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
import cv
import cv2
import numpy as np
import collections
def extract( image, region ):
histogram = dict()
imgcp = cv.CreateImage( cv.GetSize( image ), image.depth, image.nChannels )
cv.Copy( image, imgcp )
for pixel in region:
color = imgcp[pixel[1], pixel[0]]
if color not in histogra... | Python |
import tesseract
import sys
api = tesseract.TessBaseAPI()
api.Init(".","eng",tesseract.OEM_DEFAULT)
api.SetVariable("tessedit_char_whitelist", "0123456789\.\:")
api.SetPageSegMode(tesseract.PSM_AUTO)
mImgFile = sys.argv[1]
mBuffer=open(mImgFile,"rb").read()
result = tesseract.ProcessPagesBuffer(mBuffer,len(mBuffer),a... | Python |
"""Utility functions for processing images for delivery to Tesseract"""
import os
def image_to_scratch(im, scratch_image_name):
"""Saves image in memory to scratch file. .bmp format will be read correctly by Tesseract"""
im.save(scratch_image_name, dpi=(200,200))
def retrieve_text(scratch_text_name_root):... | Python |
"""Test for exceptions raised in the tesseract.exe logfile"""
class Tesser_General_Exception(Exception):
pass
class Tesser_Invalid_Filetype(Tesser_General_Exception):
pass
def check_for_errors(logfile = "tesseract.log"):
inf = file(logfile)
text = inf.read()
inf.close()
# All error conditions resul... | Python |
import cv2
import numpy as np
img = cv2.imread('meat/551054_346968652052693_986626722_n.jpg')
h = np.zeros((300,256,3))
bins = np.arange(256).reshape(256,1)
color = [ (255,0,0),(0,255,0),(0,0,255) ]
for ch, col in enumerate(color):
hist_item = cv2.calcHist([img],[ch],None,[256],[0,255])
cv2.normalize(hist_i... | Python |
from PIL import Image
import ImageEnhance
from pytesser import *
from urllib import urlretrieve
import sys
im = Image.open(sys.argv[1])
nx, ny = im.size
im2 = im.resize((int(nx*5), int(ny*5)), Image.BICUBIC)
im2.save("temp2.png")
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")
imgx = Im... | Python |
import cv2.cv as cv
import tesseract
import sys
api = tesseract.TessBaseAPI()
api.Init(".","eng",tesseract.OEM_DEFAULT)
api.SetPageSegMode(tesseract.PSM_AUTO)
image=cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_GRAYSCALE)
tesseract.SetCvImage(image,api)
text=api.GetUTF8Text()
conf=api.MeanTextConf()
print "scanned text:... | Python |
#!/usr/bin/env python
# -*- encoding:utf8 -*-
# protoc-gen-erl
# Google's Protocol Buffers project, ported to lua.
# https://code.google.com/p/protoc-gen-lua/
#
# Copyright (c) 2010 , 林卓毅 (Zhuoyi Lin) netsnail@gmail.com
# All rights reserved.
#
# Use, modification and distribution are subject to the "New BSD License"
#... | Python |
#!/usr/bin/env python
"""
tesshelper.py -- Utility operations to compare, report stats, and copy
public headers for tesseract 3.0x VS2008 Project
$RCSfile: tesshelper.py,v $ $Revision: 7ca575b377aa $ $Date: 2012/03/07 17:26:31 $
"""
r"""
Requires:
python 2.7 or greater: activestate.co... | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2012 Zdenko Podobný
# Author: Zdenko Podobný
#
# Licensed 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/LIC... | Python |
#!/usr/bin/python -u
#-*- coding: UTF-8 -*-
import subprocess
import MySQLdb
import os
import re
import sys
import time
import statvfs
ip="114.80.213.44"
ping = subprocess.Popen(["ping", "-c", "2", "-w", "500", ip], shell=False)
ping.wait()
if ping.returncode != 0:
#print ping.returncode, "ERROR: failed to ping ho... | Python |
#!/usr/bin/python -u
#-*- coding: UTF-8 -*-
import os
import re
import sys
import time
import statvfs
import subprocess
import MySQLdb
import datetime
# globa re
re_meminfo_parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB')
#
class OSstatus:
"""
result = report client status.
"""
def __in... | Python |
#!/usr/bin/python -u
#-*- coding: UTF-8 -*-
import subprocess
import MySQLdb
import os
import re
import sys
import time
import statvfs
ip="114.80.213.44"
ping = subprocess.Popen(["ping", "-c", "2", "-w", "500", ip], shell=False)
ping.wait()
if ping.returncode != 0:
#print ping.returncode, "ERROR: failed to ping ho... | Python |
#!/usr/bin/python -u
#-*- coding: UTF-8 -*-
import os
import re
import sys
import time
import statvfs
import subprocess
import MySQLdb
import datetime
# globa re
re_meminfo_parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB')
#
class OSstatus:
"""
result = report client status.
"""
def __in... | Python |
#!/usr/bin/python -u
#-*- coding: UTF-8 -*-
import subprocess
import MySQLdb
import os
import re
import sys
import time
import statvfs
ip="114.80.213.44"
ping = subprocess.Popen(["ping", "-c", "2", "-w", "500", ip], shell=False)
ping.wait()
if ping.returncode != 0:
#print ping.returncode, "ERROR: failed to ping ho... | Python |
#!/usr/bin/python -u
#-*- coding: UTF-8 -*-
import os
import re
import sys
import time
import statvfs
import subprocess
import MySQLdb
import datetime
# globa re
re_meminfo_parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB')
#
class OSstatus:
"""
result = report client status.
"""
def __in... | Python |
#!/usr/bin/python -u
#-*- coding: UTF-8 -*-
import subprocess
import MySQLdb
import os
import re
import sys
import time
import statvfs
ip="114.80.213.44"
ping = subprocess.Popen(["ping", "-c", "2", "-w", "500", ip], shell=False)
ping.wait()
if ping.returncode != 0:
#print ping.returncode, "ERROR: failed to ping ho... | Python |
#!/usr/bin/python -u
#-*- coding: UTF-8 -*-
import os
import re
import sys
import time
import statvfs
import subprocess
import MySQLdb
import datetime
# globa re
re_meminfo_parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB')
#
class OSstatus:
"""
result = report client status.
"""
def __in... | Python |
#!/usr/bin/python
# Copyright 2011 Google, Inc. All Rights Reserved.
# simple script to walk source tree looking for third-party licenses
# dumps resulting html page to stdout
import os, re, mimetypes, sys
# read source directories to scan from command line
SOURCE = sys.argv[1:]
# regex to find /* */ style commen... | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Dieses Script kontrolliert eine Lösung. Es wird ausgegeben, wie viele Farben
# verwendet wurden und wie groß das Dreieck ist.
# Funktioniert nur mit korrekter Eingabedatei (keine Leerzeichen zum trennen der
# Farben, neue Zeilen für eine neue Ebene des n-Traumrechtecks)
i... | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Dieses Script kontrolliert eine Lösung. Es wird ausgegeben, wie viele Farben
# verwendet wurden und wie groß das Dreieck ist.
# Funktioniert nur mit korrekter Eingabedatei (keine Leerzeichen zum trennen der
# Farben, neue Zeilen für eine neue Ebene des n-Traumrechtecks)
i... | Python |
'''
Module which brings history information about files from Mercurial.
@author: Rodrigo Damazio
'''
import re
import subprocess
REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*')
def _GetOutputLines(args):
'''
Runs an external process and returns its output as a list of lines.
@param args: the argume... | Python |
#!/usr/bin/python
'''
Entry point for My Tracks i18n tool.
@author: Rodrigo Damazio
'''
import mytracks.files
import mytracks.translate
import mytracks.validate
import sys
def Usage():
print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0]
print 'Commands are:'
print ' cleanup'
print ' translate'
p... | Python |
'''
Module which prompts the user for translations and saves them.
TODO: implement
@author: Rodrigo Damazio
'''
class Translator(object):
'''
classdocs
'''
def __init__(self, language):
'''
Constructor
'''
self._language = language
def Translate(self, string_names):
print string_names | Python |
'''
Module which compares languague files to the master file and detects
issues.
@author: Rodrigo Damazio
'''
import os
from mytracks.parser import StringsParser
import mytracks.history
class Validator(object):
def __init__(self, languages):
'''
Builds a strings file validator.
Params:
@para... | Python |
'''
Module for dealing with resource files (but not their contents).
@author: Rodrigo Damazio
'''
import os.path
from glob import glob
import re
MYTRACKS_RES_DIR = 'MyTracks/res'
ANDROID_MASTER_VALUES = 'values'
ANDROID_VALUES_MASK = 'values-*'
def GetMyTracksDir():
'''
Returns the directory in which the MyTrac... | Python |
'''
Module which parses a string XML file.
@author: Rodrigo Damazio
'''
from xml.parsers.expat import ParserCreate
import re
#import xml.etree.ElementTree as ET
class StringsParser(object):
'''
Parser for string XML files.
This object is not thread-safe and should be used for parsing a single file at
a time... | Python |
'''
Created on 18 avr. 12
@author: peterd
'''
class CalculationError:
pass
def get_1d_cutting_plan(stock_piece_length, custom_pieces, cut_thickness):
num_custom_pieces = len(custom_pieces)
cutting_schema = {}
i = 0
while i < num_custom_pieces:
num_elem = 1
prev_custom_packs = []
wh... | Python |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('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 custo... | Python |
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^solver$', '1d-cutter.views.cutting_plan_solver'),
url(r'^1d-cutter/solver', '1d-cutter.views.cutting_plan_so... | Python |
# Django settings for app project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
... | Python |
from django.views.generic.simple import direct_to_template
from solver import *
def init(request):
return direct_to_template(request, '1d-cutter/1d_cutting_plan_form.html', {})
def cutting_plan_solver(request):
order_num = request.GET['order_num']
stock_type = request.GET['stock_type']
stock_length... | Python |
import time, urllib , sys, threading
workers = []
pendingurls = []
def ex(line):
if "http://" in line: #and (".pls" in line.lower() or ".m3u" in line.lower()):
url = line.split("'")[1].replace("''", "")
pendingurls.append(url)
class Worker(threading.Thread):
def run(self):
... | Python |
import struct, string, time, os
pasw = 704
dst = []
def crypt(text):
text = text.replace("http://", "")
key = len(text) % 10
result = ""
for i in xrange(len(text)):
result += chr( ( ord(text[i]) ^ ( (pasw * (i+1)) + key ) ) % 256)
return result
def writeint8(num):
data... | Python |
import struct, string, time, os
pasw = 704
dst = []
def crypt(text):
text = text.replace("http://", "")
return text
#key = len(text) % 10
#result = ""
#for i in xrange(len(text)):
# result += chr( ( ord(text[i]) ^ ( (pasw * (i+1)) + key ) ) % 256)
#return result
def wri... | Python |
extlist = [".bk1",".bk2",".$$$",".local",".a",".tmp",".drc",".o",".cfg",".ddp",
".stat",".pec2bac",".identcache",".dcu",".ppu",".depend",".layout",".win"] #put extensions to delete
import sys, os, subprocess
print "START THE CLEARING PROCESS"
print "DELETING FILES WITH THE FOLLOWING EXT"
print extlist
i = ... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: models.py
Type: Class definition
Last modified: 2010-05-24 22:27
Description:
This file contains a class that would turn a dictionary containing user
information as was returned by json request into a T163User... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: utils.py
Type: Utility
Last modified: 2010-07-18 14:06
Description:
Utility functions for this project.
"""
import locale
import os
import urllib2
from datetime import datetime, timedelta
##############
# E... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: session.py
Type: Class definitions
Last modified: 2010-07-18 14:10
Description:
Official APIs(2010.04.27)
-------------------------
/friendships/show.json done
... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: __init__.py
Type: Module meta information holder
Last modified: 2010-05-16 20:44
Description:
"""
__author__ = "xiaket"
__version__ = "0.2b"
| Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: models.py
Type: Class definition
Last modified: 2010-05-24 22:27
Description:
This file contains a class that would turn a dictionary containing user
information as was returned by json request into a T163User... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: tests.py
Type: Unit test module
Last modified: 2010-05-21 16:51
Description:
This file contains unit test cases for this project.
"""
import os
import time
import unittest
from models import T163UserBase, Use... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: utils.py
Type: Utility
Last modified: 2010-07-18 14:06
Description:
Utility functions for this project.
"""
import locale
import os
import urllib2
from datetime import datetime, timedelta
##############
# E... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: tests.py
Type: Unit test module
Last modified: 2010-05-21 16:51
Description:
This file contains unit test cases for this project.
"""
import os
import time
import unittest
from models import T163UserBase, Use... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: session.py
Type: Class definitions
Last modified: 2010-07-18 14:10
Description:
Official APIs(2010.04.27)
-------------------------
/friendships/show.json done
... | Python |
#!/usr/bin/env python
#coding=utf-8
"""
Author: Xia Kai <xiaket@gmail.com>
Filename: __init__.py
Type: Module meta information holder
Last modified: 2010-05-16 20:44
Description:
"""
__author__ = "xiaket"
__version__ = "0.2b"
| Python |
import pygtk
pygtk.require('2.0')
import gtk
class TreeViewColumnExample(object):
# close the window and quit
def delete_event(self, widget, event, data=None):
gtk.main_quit()
return False
def __init__(self):
# Create a new window
self.window = gtk.Window(gtk.WINDOW_TOPLEV... | Python |
# MySQL for Python
import MySQLdb
db = MySQLdb.connect (
host = 'localhost',
user = 'root',
passwd = '',
db = 'db_1clic2learn'
#bd = 'mysql'
)
cursor = db.cursor()
cursor.execute('SELECT * FROM db.PL_SQLINJECTION')
result = cursor.fetchall()
if result:
for z in result:
print z | Python |
import sys
import time, tkMessageBox
import Controller
try:
import pygtk
pygtk.require("2.0")
except:
pass
try:
import gtk
import gtk.glade
except:
sys.exit(1)
########################################################################
class JanelaPrincipal:
... | Python |
#!/usr/bin/env python
import urllib,requests,urllib2,socket,mechanize
from urlparse import urlsplit,urlparse,urlunparse,urljoin
from Data import Data_Access
########################################################################
# CLASSE PLUGINSQL FILHO DE PLUGINS
class PluginSQL (object):
"""
Responsavel por... | Python |
import urllib,requests,urllib2,socket,time,mechanize
from Business import PluginSQL
from bs4 import BeautifulSoup
from urlparse import urlsplit,urlparse,urlunparse,urljoin
from socket import timeout
########################################################################
class Exploiter(object):
"""
Classe re... | Python |
#!/usr/bin/env python
import urllib,requests,urllib2,socket,mechanize
from urlparse import urlsplit,urlparse,urlunparse,urljoin
from Data import Data_Access
########################################################################
# CLASSE PLUGINSQL FILHO DE PLUGINS
class PluginSQL (object):
"""
Responsavel por... | Python |
#!/usr/bin/env python
import urllib,requests,urllib2,socket,mechanize
from urlparse import urlsplit,urlparse,urlunparse,urljoin
from Data import Data_Access
from bs4 import BeautifulSoup
########################################################################
class PluginXSS (object):
"""
Responsavel por monta... | Python |
import urllib
from Business import PluginSQL
from bs4 import BeautifulSoup
from urlparse import urlparse
# Estava pensando em colocar o Exploiter para fazer o ataque e a análise
########################################################################
class Exploiter(object):
""""""
#-------------------------... | Python |
from urlparse import urlparse
from Business import Exploiter
from Business import PluginSQL
from Business import PluginXSS
from bs4 import BeautifulSoup
########################################################################
class Controller (object):
""""""
#--------------------------------------------------... | Python |
#!/usr/bin/env python
import urllib,requests,urllib2,socket,mechanize
from urlparse import urlsplit,urlparse,urlunparse,urljoin
from Data import Data_Access
from bs4 import BeautifulSoup
########################################################################
class PluginXSS (object):
"""
Responsavel por monta... | Python |
import MySQLdb
########################################################################
class Data_Access (object):
#----------------------------------------------------------------------
def __init__ (self, id_vulnerability, pl_attack):
"""
Construtor:
Cria conexão com a Base de Dados
... | Python |
import MySQLdb
########################################################################
class Data_Access (object):
"""
Cria conexao com a Base de Dados
"""
dba = MySQLdb.connect (host = 'localhost', user = 'root', passwd = '', db = 'DB_1CLIC2LEARN')
#---------------------------------------... | Python |
import os
import urllib
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
class MainPage(webapp... | Python |
#! /usr/bin/env python
# encoding: utf-8
# waf 1.6.10
VERSION='0.3.3'
import sys
APPNAME='p2t'
top = '.'
out = 'build'
CPP_SOURCES = ['poly2tri/common/shapes.cc',
'poly2tri/sweep/cdt.cc',
'poly2tri/sweep/advancing_front.cc',
'poly2tri/sweep/sweep_context.cc',
... | Python |
#!/usr/bin/python
# Copyright 2011 Google, Inc. All Rights Reserved.
# simple script to walk source tree looking for third-party licenses
# dumps resulting html page to stdout
import os, re, mimetypes, sys
# read source directories to scan from command line
SOURCE = sys.argv[1:]
# regex to find /* */ style commen... | Python |
#!/usr/bin/env python
"""
tesshelper.py -- Utility operations to compare, report stats, and copy
public headers for tesseract 3.0x VS2008 Project
$RCSfile: tesshelper.py,v $ $Revision: 7ca575b377aa $ $Date: 2012/03/07 17:26:31 $
"""
r"""
Requires:
python 2.7 or greater: activestate.co... | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2012 Zdenko Podobný
# Author: Zdenko Podobný
#
# Licensed 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/LIC... | Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import os
import cgi
import time
import logging
import simplejson
from datetime import date
from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.uti... | Python |
# $Id: CheetahWrapper.py,v 1.26 2007/10/02 01:22:04 tavis_rudd Exp $
"""Cheetah command-line interface.
2002-09-03 MSO: Total rewrite.
2002-09-04 MSO: Bugfix, compile command was using wrong output ext.
2002-11-08 MSO: Another rewrite.
Meta-Data
========================================================================... | Python |
'''
Provides an abstract Servlet baseclass for Cheetah's Template class
'''
import sys
import os.path
isWebwareInstalled = False
try:
try:
from ds.appserver.Servlet import Servlet as BaseServlet
except:
from WebKit.Servlet import Servlet as BaseServlet
isWebwareInstalled = True
if not... | Python |
# $Id: TemplateCmdLineIface.py,v 1.13 2006/01/10 20:34:35 tavis_rudd Exp $
"""Provides a command line interface to compiled Cheetah template modules.
Meta-Data
================================================================================
Author: Tavis Rudd <tavis@damnsimple.com>
Version: $Revision: 1.13 $
Start Da... | Python |
# $Id: ErrorCatchers.py,v 1.7 2005/01/03 19:59:07 tavis_rudd Exp $
"""ErrorCatcher class for Cheetah Templates
Meta-Data
================================================================================
Author: Tavis Rudd <tavis@damnsimple.com>
Version: $Revision: 1.7 $
Start Date: 2001/08/01
Last Revision Date: $Date:... | Python |
"""
Nothing, but in a friendly way. Good for filling in for objects you want to
hide. If $form.f1 is a RecursiveNull object, then
$form.f1.anything["you"].might("use") will resolve to the empty string.
This module was contributed by Ian Bicking.
"""
class RecursiveNull(object):
def __getattr__(self, attr):
... | Python |
"""
@@TR: This code is pretty much unsupported.
MondoReport.py -- Batching module for Python and Cheetah.
Version 2001-Nov-18. Doesn't do much practical yet, but the companion
testMondoReport.py passes all its tests.
-Mike Orr (Iron)
TODO: BatchRecord.prev/next/prev_batches/next_batches/query, prev.query,
next.quer... | Python |
"""This package contains classes, functions, objects and packages contributed
by Cheetah users. They are not used by Cheetah itself. There is no
guarantee that this directory will be included in Cheetah releases, that
these objects will remain here forever, or that they will remain
backward-compatible.
""... | Python |
# $Id: CGITemplate.py,v 1.6 2006/01/29 02:09:59 tavis_rudd Exp $
"""A subclass of Cheetah.Template for use in CGI scripts.
Usage in a template:
#extends Cheetah.Tools.CGITemplate
#implements respond
$cgiHeaders#slurp
Usage in a template inheriting a Python class:
1. The template
#extends MyPythonClass... | Python |
# $Id: SiteHierarchy.py,v 1.1 2001/10/11 03:25:54 tavis_rudd Exp $
"""Create menus and crumbs from a site hierarchy.
You define the site hierarchy as lists/tuples. Each location in the hierarchy
is a (url, description) tuple. Each list has the base URL/text in the 0
position, and all the children coming after it. A... | Python |
#
| Python |
from turbocheetah import cheetahsupport
TurboCheetah = cheetahsupport.TurboCheetah
__all__ = ["TurboCheetah"] | Python |
"Template support for Cheetah"
import sys, os, imp
from Cheetah import Compiler
import pkg_resources
def _recompile_template(package, basename, tfile, classname):
tmpl = pkg_resources.resource_string(package, "%s.tmpl" % basename)
c = Compiler.Compiler(source=tmpl, mainClassName='GenTemplate')
code = str... | Python |
'''
Provides dummy Transaction and Response classes is used by Cheetah in place
of real Webware transactions when the Template obj is not used directly as a
Webware servlet.
Warning: This may be deprecated in the future, please do not rely on any
specific DummyTransaction or DummyResponse behavior
'''
import loggin... | Python |
import Cheetah.Template
def render(template_file, **kwargs):
'''
Cheetah.Django.render() takes the template filename
(the filename should be a file in your Django
TEMPLATE_DIRS)
Any additional keyword arguments are passed into the
template are propogated into the templat... | Python |
'''
Filters for the #filter directive as well as #transform
#filter results in output filters Cheetah's $placeholders .
#transform results in a filter on the entirety of the output
'''
import sys
# Additional entities WebSafe knows how to transform. No need to include
# '<', '>' or '&' since those wi... | Python |
'''
Provides several CacheStore backends for Cheetah's caching framework. The
methods provided by these classes have the same semantics as those in the
python-memcached API, except for their return values:
set(key, val, time=0)
set the value unconditionally
add(key, val, time=0)
set only if the server doesn't alr... | Python |
try:
from ds.sys.Unspecified import Unspecified
except ImportError:
class _Unspecified:
def __repr__(self):
return 'Unspecified'
def __str__(self):
return 'Unspecified'
Unspecified = _Unspecified()
| Python |
# $Id: CacheRegion.py,v 1.3 2006/01/28 04:19:30 tavis_rudd Exp $
'''
Cache holder classes for Cheetah:
Cache regions are defined using the #cache Cheetah directive. Each
cache region can be viewed as a dictionary (keyed by cacheRegionID)
handling at least one cache item (the default one). It's possible to add
cacheIte... | Python |
# $Id: NameMapper.py,v 1.32 2007/12/10 19:20:09 tavis_rudd Exp $
"""This module supports Cheetah's optional NameMapper syntax.
Overview
================================================================================
NameMapper provides a simple syntax for accessing Python data structures,
functions, and methods fro... | Python |
#!/usr/bin/env python
'''
Tests for the 'cheetah' command.
Besides unittest usage, recognizes the following command-line options:
--list CheetahWrapper.py
List all scenarios that are tested. The argument is the path
of this script.
--nodelete
Don't delete scratch directory at end.
... | Python |
#!/usr/bin/env python
'''
Core module of Cheetah's Unit-testing framework
TODO
================================================================================
# combo tests
# negative test cases for expected exceptions
# black-box vs clear-box testing
# do some tests that run the Template for long enough to check tha... | Python |
"""
XML Test Runner for PyUnit
"""
# Written by Sebastian Rittau <srittau@jroger.in-berlin.de> and placed in
# the Public Domain. With contributions by Paolo Borelli.
__revision__ = "$Id: /private/python/stdlib/xmlrunner.py 16654 2007-11-12T12:46:35.368945Z srittau $"
import os.path
import re
import sys
import time... | Python |
#!/usr/bin/env python
import unittest
import Cheetah
import Cheetah.Parser
import Cheetah.Template
class Chep_2_Conditionalized_Import_Behavior(unittest.TestCase):
def test_ModuleLevelImport(self):
''' Verify module level (traditional) import behavior '''
pass
def test_InlineImport(self):
... | Python |
#!/usr/bin/env python
# -*- encoding: utf8 -*-
from Cheetah.Template import Template
from Cheetah import CheetahWrapper
from Cheetah import DummyTransaction
import imp
import os
import sys
import tempfile
import unittest
class CommandLineTest(unittest.TestCase):
def createAndCompile(self, source):
sourcef... | Python |
#!/usr/bin/env python
import sys
import unittest
import Cheetah.Template
import Cheetah.Filters
majorVer, minorVer = sys.version_info[0], sys.version_info[1]
versionTuple = (majorVer, minorVer)
class BasicMarkdownFilterTest(unittest.TestCase):
'''
Test that our markdown filter works
'''
def test... | Python |
#!/usr/bin/env python
import sys
import types
import os
import os.path
import unittest
from Cheetah.NameMapper import NotFound, valueForKey, \
valueForName, valueFromSearchList, valueFromFrame, valueFromFrameOrSearchList
class DummyClass:
classVar1 = 123
def __init__(self):
self.instanceVar1 ... | Python |
#!/usr/bin/env python
import hotshot
import hotshot.stats
import os
import sys
import unittest
from test import pystone
import time
import Cheetah.NameMapper
import Cheetah.Template
# This can be turned on with the `--debug` flag when running the test
# and will cause the tests to all just dump out how long they t... | Python |
#!/usr/bin/env python
import unittest
from Cheetah import DirectiveAnalyzer
class AnalyzerTests(unittest.TestCase):
def test_set(self):
template = '''
#set $foo = "bar"
Hello ${foo}!
'''
calls = DirectiveAnalyzer.analyze(template)
self.assertEquals(1, calls.get('s... | Python |
#!/usr/bin/env python
import pdb
import sys
import types
import os
import os.path
import tempfile
import shutil
import unittest
from Cheetah.Template import Template
majorVer, minorVer = sys.version_info[0], sys.version_info[1]
versionTuple = (majorVer, minorVer)
class TemplateTest(unittest.TestCase):
pass
clas... | Python |
#!/usr/bin/env python
import unittest
from Cheetah import SettingsManager
class SettingsManagerTests(unittest.TestCase):
def test_mergeDictionaries(self):
left = {'foo' : 'bar', 'abc' : {'a' : 1, 'b' : 2, 'c' : (3,)}}
right = {'xyz' : (10, 9)}
expect = {'xyz': (10, 9), 'foo': 'bar', 'abc... | Python |
#
| Python |
#!/usr/bin/env python
import Cheetah.NameMapper
import Cheetah.Template
import sys
import unittest
majorVer, minorVer = sys.version_info[0], sys.version_info[1]
versionTuple = (majorVer, minorVer)
def isPython23():
''' Python 2.3 is still supported by Cheetah, but doesn't support decorators '''
return maj... | Python |
#!/usr/bin/env python
import unittest
from Cheetah import Parser
class ArgListTest(unittest.TestCase):
def setUp(self):
super(ArgListTest, self).setUp()
self.al = Parser.ArgList()
def test_merge1(self):
'''
Testing the ArgList case results from Template.Preprocessors.tes... | Python |
from glob import glob
import os
from os import listdir
import os.path
import re
from tempfile import mktemp
def _escapeRegexChars(txt,
escapeRE=re.compile(r'([\$\^\*\+\.\?\{\}\[\]\(\)\|\\])')):
return escapeRE.sub(r'\\\1', txt)
def findFiles(*args, **kw):
"""Recursively find all the file... | Python |
'''
Provides the core API for Cheetah.
See the docstring in the Template class and the Users' Guide for more information
'''
################################################################################
## DEPENDENCIES
import sys # used in the error handling code
import re ... | Python |
#
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.