code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
"""
None Object implementation
ok and tested
"""
from pypy.objspace.std.objspace import *
class W_NoneObject(W_Object):
from pypy.objspace.std.nonetype import none_typedef as typedef
def unwrap(w_self, space):
return None
registerimplementation(W_NoneObject)
W_NoneObject.w_None = W_NoneObject... | Python |
from pypy.objspace.std.objspace import *
from pypy.objspace.std.stringobject import W_StringObject
from pypy.objspace.std.unicodeobject import delegate_String2Unicode
from pypy.objspace.std.stringtype import joined, wrapstr
class W_StringJoinObject(W_Object):
from pypy.objspace.std.stringtype import str_typedef a... | Python |
"""
Reviewed 03-06-22
Sequence-iteration is correctly implemented, thoroughly
tested, and complete. The only missing feature is support
for function-iteration.
"""
from pypy.objspace.std.objspace import *
class W_SeqIterObject(W_Object):
from pypy.objspace.std.itertype import iter_typedef as typedef
def ... | Python |
"""
For reference, the MRO algorithm of Python 2.3.
"""
def mro(cls):
order = []
orderlists = [mro(base) for base in cls.__bases__]
orderlists.append([cls] + list(cls.__bases__))
while orderlists:
for candidatelist in orderlists:
candidate = candidatelist[0]
if blockin... | Python |
from pypy.objspace.std.register_all import register_all
from pypy.interpreter.baseobjspace import ObjSpace, Wrappable
from pypy.interpreter.error import OperationError, debug_print
from pypy.interpreter.typedef import get_unique_interplevel_subclass
from pypy.interpreter.argument import Arguments
from pypy.interpreter ... | Python |
from pypy.interpreter.error import OperationError
from pypy.objspace.std.objspace import register_all
from pypy.objspace.std.stdtypedef import StdTypeDef, newmethod
from pypy.objspace.std.stdtypedef import SMM
from pypy.interpreter.gateway import NoneNotWrapped
from pypy.interpreter import gateway
frozenset_copy ... | Python |
from pypy.objspace.std.objspace import *
from pypy.objspace.std.stringobject import W_StringObject
from pypy.objspace.std.unicodeobject import delegate_String2Unicode
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.objspace.std.tupleobject import W_TupleObject
from pypy.objspace.std import slicetype
f... | Python |
from pypy.objspace.std.objspace import *
def descr_get_dictproxy(space, w_obj):
return W_DictProxyObject(w_obj.getdict())
class W_DictProxyObject(W_Object):
from pypy.objspace.std.dictproxytype import dictproxy_typedef as typedef
def __init__(w_self, w_dict):
w_self.w_dict = w_dict
registeri... | Python |
from pypy.objspace.std.stdtypedef import *
from pypy.interpreter.error import OperationError
# ____________________________________________________________
def _proxymethod(name):
def fget(space, w_obj):
from pypy.objspace.std.dictproxyobject import W_DictProxyObject
if not isinstance(w_obj, W_Dic... | Python |
""" some simple benchmarikng stuff
"""
import random, time
def sample(population, num):
l = len(population)
retval = []
for i in xrange(num):
retval.append(population[random.randrange(l)])
return retval
random.sample = sample
def get_random_string(l):
strings = 'qwertyuiopasdfghjklzxcvb... | Python |
import py
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
from pypy.module.__builtin__.__init__ import BUILTIN_TO_INDEX, OPTIMIZED_BUILTINS
from pypy.rlib.objectmodel import r_dict, we_are_translated
def _is_str(space, w_key):
return space.is_w(space.type(w_key), space.w_str)
def _i... | Python |
import py
import sys
from pypy.rlib.rarithmetic import intmask, _hash_string, ovfcheck
from pypy.rlib.objectmodel import we_are_translated
import math
LOG2 = math.log(2)
NBITS = int(math.log(sys.maxint) / LOG2) + 2
# XXX should optimize the numbers
NEW_NODE_WHEN_LENGTH = 16
MAX_DEPTH = 32 # maybe should be smaller
MI... | Python |
from pypy.interpreter import gateway, baseobjspace, argument
from pypy.interpreter.error import OperationError
from pypy.interpreter.typedef import TypeDef, GetSetProperty, Member
from pypy.interpreter.typedef import descr_get_dict, descr_set_dict
from pypy.interpreter.typedef import no_hash_descr
from pypy.interpreter... | Python |
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.strutil import string_to_w_long, ParseStringError
from pypy.interpreter.error import OperationError
from pypy.interpreter.gateway import NoneNotWrapped
def descr__new__(space, w_longtype, w_x=0, w_base=NoneNotWrapped):
from pypy.objspace.std.longobj... | Python |
from pypy.objspace.std.objspace import *
from pypy.objspace.std.intobject import W_IntObject
class W_BoolObject(W_Object):
from pypy.objspace.std.booltype import bool_typedef as typedef
def __init__(w_self, boolval):
w_self.boolval = not not boolval
def __nonzero__(w_self):
raise Excepti... | Python |
from pypy.objspace.std.stdtypedef import *
from pypy.interpreter.error import OperationError
from pypy.objspace.std.strutil import string_to_float, ParseStringError
from pypy.objspace.std.strutil import interp_string_to_float
USE_NEW_S2F = True
def descr__new__(space, w_floattype, w_x=0.0):
from pypy.objspace.std... | Python |
from pypy.objspace.std.objspace import *
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.rlib.rarithmetic import ovfcheck, ovfcheck_lshift, LONG_BIT, r_uint
from pypy.rlib.rbigint import rbigint
from pypy.objspace.std.inttype import wrapint
"""
In order to have the same behavior running
on CPython, and... | Python |
# -*- coding: latin-1 -*-
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
from pypy.rlib.rarithmetic import ovfcheck, _hash_string
from pypy.rlib.objectmodel import we_are_translated
from pypy.objspace.std.inttype import wrapint
from pypy.objspace.std.sliceobject import W_SliceObject
from... | Python |
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
from pypy.rlib.objectmodel import we_are_translated
from pypy.objspace.std.inttype import wrapint
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.objspace.std import slicetype
from pypy.objspace.std.listobject import W_ListO... | Python |
from pypy.objspace.std.objspace import *
from pypy.objspace.std.inttype import wrapint
from pypy.rlib.rarithmetic import intmask
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.interpreter import gateway
class W_TupleObject(W_Object):
from pypy.objspace.std.tupletype import tuple_typedef as typed... | Python |
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.strutil import string_to_int, string_to_w_long, ParseStringError, ParseStringOverflowError
from pypy.interpreter.error import OperationError
from pypy.interpreter.gateway import NoneNotWrapped
from pypy.rlib.rarithmetic import r_uint
from pypy.rlib.objec... | Python |
from objspace import StdObjSpace
Space = StdObjSpace
| Python |
from pypy.interpreter import gateway
from pypy.objspace.std.objspace import W_Object, OperationError
from pypy.objspace.std.objspace import registerimplementation, register_all
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.objspace.std.floatobject import W_FloatObject, _hash_float
import math
class ... | Python |
from pypy.objspace.std.objspace import *
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.objspace.std.inttype import wrapint
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.objspace.std.listobject import W_ListObject
from pypy.objspace.std import listtype
from pypy.objspace.std import... | Python |
import sys
from pypy.objspace.std.objspace import *
from pypy.objspace.std.intobject import W_IntObject
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.rlib.rbigint import rbigint, SHIFT
class W_LongObject(W_Object):
"""This is a wrapper of rbigint."""
from pypy.objspace.std.longtype import lon... | Python |
from pypy.interpreter.error import OperationError
from pypy.objspace.std.objspace import register_all
from pypy.objspace.std.stdtypedef import StdTypeDef, newmethod, no_hash_descr
from pypy.objspace.std.stdtypedef import SMM
from pypy.interpreter.gateway import NoneNotWrapped
from pypy.interpreter import gateway
set_a... | Python |
"""Default implementation for some operation."""
from pypy.objspace.std.objspace import *
# The following default implementations are used before delegation is tried.
# 'id' is normally the address of the wrapper.
def id__ANY(space, w_obj):
#print 'id:', w_obj
return space.wrap(id(w_obj))
# __init__ should... | Python |
from pypy.interpreter import gateway
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.basestringtype import basestring_typedef
from pypy.interpreter.error import OperationError
from sys import maxint
unicode_capitalize = SMM('capitalize', 1,
doc='S.capitalize() -> unicode\n\n... | Python |
from pypy.objspace.std.stdtypedef import *
from pypy.interpreter.gateway import NoneNotWrapped
def descr__new__(space, w_tupletype, w_sequence=NoneNotWrapped):
from pypy.objspace.std.tupleobject import W_TupleObject
if w_sequence is None:
tuple_w = []
elif (space.is_w(w_tupletype, space.w_tuple) an... | Python |
from pypy.interpreter.error import OperationError
from pypy.interpreter import gateway
from pypy.interpreter.argument import Arguments
from pypy.interpreter.typedef import weakref_descr
from pypy.objspace.std.stdtypedef import *
def descr__new__(space, w_typetype, w_name, w_bases, w_dict):
"This is used to create ... | Python |
def raises(excp, func, *args):
try:
func(*args)
assert 1 == 0
except excp:pass
def assertEqual(a, b):
assert a == b
def assertNotEqual(a, b):
assert a != b
def assertIs(a, b):
assert a is b
# complex specific tests
EPS = 1e-9
def assertAlmostEqual(a, b):
if isinstance(a, co... | Python |
# empty
| Python |
def conference_scheduling():
dom_values = [(room,slot)
for room in ('room A','room B','room C')
for slot in ('day 1 AM','day 1 PM','day 2 AM',
'day 2 PM')]
variables = {}
for v in ('c01','c02','c03','c04','c05', 'c06','c07','c08','c09','c10'):
variabl... | Python |
def dummy_problem(computation_space):
ret = computation_space.var('__dummy__')
computation_space.set_dom(ret, c.FiniteDomain([]))
return (ret,)
def send_more_money(computation_space):
#FIXME: this problem needs propagators for integer finite domains
# performance is terrible without it
c... | Python |
#
| Python |
import inspect
import os
from cclp import switch_debug_info
def raises(exception, call, *args):
try:
call(*args)
except exception:
return True
except:
pass
return False
class Skip(Exception): pass
def skip(desc):
raise Skip, desc
def out(obj):
os.write(1, str(obj))
d... | Python |
"""
This file defines restricted arithmetic:
classes and operations to express integer arithmetic,
such that before and after translation semantics are
consistent
r_uint an unsigned integer which has not overflow
checking. It is always positive and always
truncated to the internal machine word siz... | Python |
""" simple non-constant constant. Ie constant which does not get annotated as constant
"""
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.annotation.bookkeeper import getbookkeeper
from pypy.objspace.flow.model import Variable, Constant
from pypy.rpython.lltypesystem import lltype
class NonConstant(... | Python |
"""
An RPython implementation of getaddrinfo() based on ctypes.
This is a rewrite of the CPython source: Modules/getaddrinfo.c
"""
from ctypes import POINTER, sizeof, cast, pointer
from pypy.rlib import _rsocket_ctypes as _c
from pypy.rlib.rsocket import GAIError, CSocketError
from pypy.rlib.rsocket import gethost_com... | Python |
"""
Helper file for Python equivalents of os specific calls.
"""
import os
def putenv(name_eq_value):
# we fake it with the real one
global _initial_items
name, value = name_eq_value.split('=', 1)
os.environ[name] = value
_initial_items = os.environ.items()
putenv._annenforceargs_ = (str,)
_initi... | Python |
from pypy.rlib.rarithmetic import LONG_BIT, intmask, r_uint, r_ulonglong, ovfcheck
import math, sys
# It took many days of debugging and testing, until
# I (chris) finally understood how things work and where
# to expect overflows in the division code.
# In the end, I decided to throw this all out and to use
# plain ... | Python |
import os, sys, new
# WARNING: this is all nicely RPython, but there is no RPython code around
# to *compile* regular expressions, so outside of PyPy this is only useful
# for RPython applications that just need precompiled regexps.
#
# XXX However it's not even clear how to get such prebuilt regexps...
import rsre_c... | Python |
"""
Core routines for regular expression matching and searching.
"""
# This module should not be imported directly; it is execfile'd by rsre.py,
# possibly more than once. This is done to create specialized version of
# this code: each copy is used with a 'state' that is an instance of a
# specific subclass of BaseSt... | Python |
"""
Character categories and charsets.
"""
import sys
# Note: the unicode parts of this module require you to call
# rsre.set_unicode_db() first, to select one of the modules
# pypy.module.unicodedata.unicodedb_x_y_z. This allows PyPy to use sre
# with the same version of the unicodedb as it uses for
# unicodeobject.... | Python |
"""
An RPython implementation of sockets based on ctypes.
Note that the interface has to be slightly different - this is not
a drop-in replacement for the 'socket' module.
"""
# Known missing features:
#
# - support for non-Linux platforms
# - address families other than AF_INET, AF_INET6, AF_UNIX
# - methods ma... | Python |
from pypy.rpython.extregistry import ExtRegistryEntry
# ____________________________________________________________
# Framework GC features
class GcPool(object):
pass
def gc_swap_pool(newpool):
"""Set newpool as the current pool (create one if newpool is None).
All malloc'ed objects are put into the curr... | Python |
# This are here only because it's always better safe than sorry.
# The issue is that from-time-to-time CPython's termios.tcgetattr
# returns list of mostly-strings of length one, but with few ints
# inside, so we make sure it works
import termios
from termios import *
def tcgetattr(fd):
# NOT_RPYTHON
lst = li... | Python |
"""
This file defines utilities for manipulating the stack in an
RPython-compliant way, intended mostly for use by the Stackless PyPy.
"""
import inspect
def stack_unwind():
raise RuntimeError("cannot unwind stack in non-translated versions")
def stack_capture():
raise RuntimeError("cannot unwind stack in no... | Python |
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.rlib.objectmodel import CDefinedIntSymbolic
def purefunction(func):
func._pure_function_ = True
return func
def hint(x, **kwds):
return x
class Entry(ExtRegistryEntry):
_about_ = hint
def compute_result_annotation(self, s_x, **kwds_... | Python |
from pypy.rlib.rctypes.implementation import CTypeController, getcontroller
from pypy.rlib.rctypes import rctypesobject
from pypy.rpython.lltypesystem import lltype
from ctypes import ARRAY, c_int, c_char
ArrayType = type(ARRAY(c_int, 10))
class ArrayCTypeController(CTypeController):
def __init__(self, ctype)... | Python |
from pypy.rlib.rctypes.implementation import CTypeController
from pypy.rlib.rctypes import rctypesobject
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.rctypes import rcarithmetic as rcarith
from ctypes import c_char, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint
from ctypes import c_long, c_ulong,... | Python |
from pypy.rlib.rctypes.implementation import CTypeController
from pypy.rlib.rctypes import rctypesobject
from ctypes import c_char_p
class CCharPCTypeController(CTypeController):
knowntype = rctypesobject.rc_char_p
def new(self, initialvalue=None):
obj = rctypesobject.rc_char_p.allocate()
ob... | Python |
from pypy.annotation import model as annmodel
from pypy.rlib.rctypes.implementation import CTypeController, getcontroller
from pypy.rlib.rctypes import rctypesobject
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.rpython.lltypesystem import lltype
from pypy.rlib.unroll import unrolling_iterable
from c... | Python |
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.rpython import annlowlevel
from pypy.interpreter.miscutils import InitializedClass
from pypy.tool.sourcetools import func_with_new_name
from pypy.rlib.objectmodel import keepalive_until_here
class RawMemBlock(object):
ofs_keepalives = 0
def __in... | Python |
from pypy.annotation import model as annmodel
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.error import TyperError
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.rpython.controllerentry import SomeControlledInstance
from pypy.rlib.rctypes.implementation import getcontroller
from pypy.... | Python |
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.rlib.rctypes.implementation import CTypeController, getcontroller
from pypy.rlib.rctypes import rctypesobject
from pypy.rpython.lltypesystem import lltype
from ctypes import pointer, POINTER, byref, c_int
PointerType = type(POINTER(c_int))
class Point... | Python |
# empty
| Python |
from pypy.annotation import model as annmodel
from pypy.rlib.rctypes.implementation import CTypeController, getcontroller
from pypy.rlib.rctypes import rctypesobject
from pypy.rpython.lltypesystem import lltype
import ctypes
CFuncPtrType = type(ctypes.CFUNCTYPE(None))
class FuncPtrCTypeController(CTypeController):
... | Python |
import py
py.test.skip("extregistry conflicts with the other rctypes :-(")
from pypy.annotation import model as annmodel
from pypy.tool.tls import tlsobject
from pypy.rlib.rctypes import rctypesobject
from pypy.rpython import extregistry, controllerentry
from pypy.rpython.error import TyperError
from pypy.rpython.contr... | Python |
from pypy.rlib.cslib.btree import BTreeNode
from pypy.rlib.cslib.rdomain import BaseFiniteDomain, ConsistencyError
class AbstractConstraint:
def __init__(self, variables):
"""variables is a list of variables which appear in the formula"""
assert isinstance(variables, list)
self._vari... | Python |
class ConsistencyError(Exception):
pass
class BaseFiniteDomain:
"""
Variable Domain with a finite set of int values
"""
def __init__(self, values):
"""values is a list of values in the domain
This class uses a dictionnary to make sure that there are
no duplicate values"""
... | Python |
"""
distributors - part of constraint satisfaction solver.
"""
def make_new_domains(domains):
"""return a shallow copy of dict of domains passed in argument"""
new_domains = {}
for key, domain in domains.items():
new_domains[key] = domain.copy()
return new_domains
class AbstractDistributor:
... | Python |
"""
A minimalist binary tree implementation
whose values are (descendants of) BTreeNodes.
This alleviates some typing difficulties when
using TimSort on lists of the form [(key, Thing), ...]
"""
class BTreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
... | Python |
"""The code of the constraint propagation algorithms"""
from pypy.rlib.cslib.rconstraint import AbstractConstraint, ConsistencyError
class Repository:
"""Stores variables, domains and constraints
Propagates domain changes to constraints
Manages the constraint evaluation queue"""
def __init__(self, dom... | Python |
#
| Python |
from pypy.rlib.rarithmetic import ovfcheck, ovfcheck_lshift
## ------------------------------------------------------------------------
## Lots of code for an adaptive, stable, natural mergesort. There are many
## pieces to this algorithm; read listsort.txt for overviews and details.
## -----------------------------... | Python |
"""
An RPython implementation of getnameinfo() based on ctypes.
This is a rewrite of the CPython source: Modules/getaddrinfo.c
"""
from ctypes import POINTER, sizeof, cast, pointer
from pypy.rlib import _rsocket_ctypes as _c
from pypy.rlib.rsocket import RSocketError, GAIError
NI_NOFQDN = 0x00000001
NI_NUMERICHOST = 0... | Python |
# this code is a version of the mersenne twister random number generator which
# is supposed to be used from RPython without the Python interpreter wrapping
# machinery etc.
# this is stolen from CPython's _randommodule.c
from pypy.rlib.rarithmetic import r_uint
N = 624
M = 397
MATRIX_A = r_uint(0x9908b0df) # consta... | Python |
import os
from pypy.rpython.rctypes.tool import ctypes_platform
from pypy.rpython.rctypes.tool import util # ctypes.util from 0.9.9.6
# Not used here, but exported for other code.
from pypy.rpython.rctypes.aerrno import geterrno
from ctypes import c_ushort, c_int, c_uint, c_char_p, c_void_p, c_char, c_ubyte
fro... | Python |
"""
This file defines utilities for manipulating objects in an
RPython-compliant way.
"""
import sys, new
# specialize is a decorator factory for attaching _annspecialcase_
# attributes to functions: for example
#
# f._annspecialcase_ = 'specialize:memo' can be expressed with:
# @specialize.memo()
# def f(...
#
# f._... | Python |
import py
try:
set
except NameError:
from sets import Set as set, ImmutableSet as frozenset
def compress_char_set(chars):
chars = list(chars)
chars.sort()
result = [chars[0], 1]
for a, b in zip(chars[:-1], chars[1:]):
if ord(a) == ord(b) - 1:
result.append(result.pop() + 1)... | Python |
from pypy.rlib.parsing.tree import Nonterminal, Symbol
from makepackrat import PackratParser, BacktrackException, Status
class Parser(object):
def NAME(self):
return self._NAME().result
def _NAME(self):
_key = self._pos
_status = self._dict_NAME.get(_key, None)
if _status is Non... | Python |
class Codebuilder(object):
def __init__(self):
self.blocks = []
self.code = []
def get_code(self):
assert not self.blocks
return "\n".join([" " * depth + line for depth, line in self.code])
def make_parser(self):
m = {'Status': Status,
'Nonterminal':... | Python |
import py
from pypy.rlib.parsing.lexer import SourcePos
from pypy.rlib.parsing.tree import Node, Symbol, Nonterminal
class Rule(object):
def __init__(self, nonterminal, expansions):
self.nonterminal = nonterminal
self.expansions = expansions
def getkey(self):
return (self.nonterminal, ... | Python |
import py
from pypy.rlib.objectmodel import we_are_translated
from pypy.rlib.parsing import deterministic, regex
class Token(object):
def __init__(self, name, source, source_pos):
self.name = name
self.source = source
self.source_pos = source_pos
def __eq__(self, other):
# for ... | Python |
import py
from pypy.rlib.parsing.parsing import PackratParser, Rule
from pypy.rlib.parsing.tree import Nonterminal, Symbol, RPythonVisitor
from pypy.rlib.parsing.codebuilder import Codebuilder
from pypy.rlib.parsing.regexparse import parse_regex
import string
from pypy.rlib.parsing.regex import *
from pypy.rlib.parsing... | Python |
import py
class Node(object):
def view(self):
from dotviewer import graphclient
content = ["digraph G{"]
content.extend(self.dot())
content.append("}")
p = py.test.ensuretemp("automaton").join("temp.dot")
p.write("\n".join(content))
graphclient.display_dot_fi... | Python |
import py
from pypy.rlib.parsing.parsing import PackratParser, Rule
from pypy.rlib.parsing.tree import Nonterminal
from pypy.rlib.parsing.regex import StringExpression, RangeExpression
from pypy.rlib.parsing.lexer import Lexer, DummyLexer
from pypy.rlib.parsing.deterministic import compress_char_set, DFA
import string
... | Python |
import py
import string
from pypy.rlib.parsing.deterministic import NFA
set = py.builtin.set
class RegularExpression(object):
def __init__(self):
raise NotImplementedError("abstract base class")
def make_automaton(self):
raise NotImplementedError("abstract base class")
def __add_... | Python |
import py
import sys
from pypy.rlib.parsing.tree import Nonterminal, Symbol, RPythonVisitor
from pypy.rlib.parsing.codebuilder import Codebuilder
from pypy.rlib.objectmodel import we_are_translated
class BacktrackException(Exception):
def __init__(self, error=None):
self.error = error
if not we_are... | Python |
from pypy.tool.uid import uid
# Support for explicit specialization: in code using global constants
# that are instances of SpecTag, code paths are not merged when
# the same variable holds a different SpecTag instance.
class SpecTag(object):
__slots__ = ()
def __repr__(self):
return '%s(0x%x)' %... | Python |
"""New standard I/O library.
Based on sio.py from Guido van Rossum.
- This module contains various stream classes which provide a subset of the
classic Python I/O API: read(n), write(s), tell(), seek(offset, whence=0),
readall(), readline(), truncate(size), flush(), close(), peek(),
flushable(), try_to_find_fil... | Python |
"""
Usage:
python alarm.py <timeout> <scriptname> <args...>
Run the given script. If the timeout elapses, trying interrupting it by
sending KeyboardInterrupts.
"""
import traceback
def _main_with_alarm(finished):
import sys, os
import time
import thread
def timeout_thread(timeout, finished):... | Python |
import types
class AbstractMethods(type):
def __new__(cls, cls_name, bases, cls_dict):
for key, value in cls_dict.iteritems():
if isinstance(value, types.FunctionType):
cls_dict[key] = cls.decorator(value)
return type.__new__(cls, cls_name, bases, cls_dict)
class Static... | Python |
# XXX this does not produce a correct _exceptions anymore because the logic to reconstruct
# type checks is broken
# this script is used for extracting
# the information available for exceptions
# via introspection.
# The idea is to use it once to create
# a template for a re-birth of exceptions.py
import autopath
i... | Python |
"""disassembler of Python byte code into mnemonics.
XXX this only works for python-2.3 because of the linenumber
optimization
"""
import autopath
import sys
from pypy.tool import stdlib_opcode
from pypy.tool.stdlib_opcode import *
__all__ = ["dis","pydisassemble","distb","disco"] + stdlib_opcode.__all__
EXT... | Python |
import sys
from py.__.misc.terminal_helper import ansi_print, get_terminal_width
"""
Black 0;30 Dark Gray 1;30
Blue 0;34 Light Blue 1;34
Green 0;32 Light Green 1;32
Cyan 0;36 Light Cyan 1;36
Red 0;31 Light Red 1;31
Purple 0;35 Light Purple... | Python |
"""
Two magic tricks for classes:
class X:
__metaclass__ = extendabletype
...
# in some other file...
class __extend__(X):
... # and here you can add new methods and class attributes to X
Mostly useful together with the second trick, which lets you build
methods whose 'self' ... | Python |
""" error handling features, just a way of displaying errors
"""
from pypy.tool.ansi_print import ansi_log, raise_nicer_exception
from pypy.objspace.flow.model import Constant, Variable
import sys
import py
log = py.log.Producer("error")
py.log.setconsumer("error", ansi_log)
SHOW_TRACEBACK = False
SHOW_ANNOTATION... | Python |
from __future__ import generators
import autopath
import py
from py.__.magic import exprinfo
from pypy.interpreter import gateway
from pypy.interpreter.error import OperationError
from py.__.test.outcome import ExceptionFailure
# ____________________________________________________________
class AppCode(object):
... | Python |
#! /usr/bin/env python
"""
the html test reporter
"""
import sys, os, re
import pprint
import py
from pypy.tool.pytest import result
from pypy.tool.pytest.overview import ResultCache
#
# various interesting path objects
#
html = py.xml.html
NBSP = py.xml.raw(" ")
class HtmlReport(object):
def __init... | Python |
from pypy.tool.pytest import result
import sys
class ResultCache:
def __init__(self, resultdir):
self.resultdir = resultdir
self.name2result = {}
def parselatest(self):
def filefilter(p):
return p.check(fnmatch='test_*.txt', file=1)
def rec(p):
retu... | Python |
import py
def skipimporterror(name):
if not hasimport(name):
__tracebackhide__ = True
py.test.skip("cannot import %r module" % (name,))
def hasimport(name):
try:
__import__(name)
except ImportError:
return False
else:
return True
| Python |
import sys
import py
import re
class Result(object):
def __init__(self, init=True):
self._headers = {}
self._blocks = {}
self._blocknames = []
if init:
stdinit(self)
def __setitem__(self, name, value):
self._headers[name.lower()] = value
def __ge... | Python |
import autopath
import py
import pypy
pypydir = py.path.local(pypy.__file__).dirpath()
distdir = pypydir.dirpath()
testresultdir = distdir.join('testresult')
assert pypydir.check(dir=1)
libpythondir = distdir.join('lib-python')
regrtestdir = libpythondir.join('2.4.1', 'test')
modregrtestdir = libpythondir.join('m... | Python |
#! /usr/bin/env python
"""
the html test reporter
"""
import sys, os, re
import pprint
import py
from pypy.tool.pytest import result
from pypy.tool.pytest.overview import ResultCache
#
# various interesting path objects
#
html = py.xml.html
NBSP = py.xml.raw(" ")
class HtmlReport(object):
def __init... | Python |
#! /usr/bin/env python
import autopath
import py
import sys
mydir = py.magic.autopath().dirpath().realpath()
from pypy.tool.pytest import htmlreport
from pypy.tool.pytest import confpath
if __name__ == '__main__':
if len(sys.argv) > 1:
testresultdir = py.path.local(sys.argv[1])
assert te... | Python |
class AppTestTest:
def test_app_method(self):
assert 42 == 41
def app_test_app_func():
assert 41 == 42
def test_interp_func(space):
assert space.is_true(space.w_None)
class TestInterpTest:
def test_interp_method(self):
assert self.space.is_true(self.space.w_False)
def app_te... | Python |
# refer to 2.4.1/test/regrtest.py's runtest() for comparison
import sys
from test import test_support
test_support.verbose = int(sys.argv[1])
sys.argv[:] = sys.argv[2:]
modname = sys.argv[0]
impname = 'test.' + modname
mod = __import__(impname, globals(), locals(), [modname])
indirect_test = getattr(mod, 'test_main'... | Python |
"""
self cloning, automatic path configuration
copy this into any subdirectory of pypy from which scripts need
to be run, typically all of the test subdirs.
The idea is that any such script simply issues
import autopath
and this will make sure that the parent directory containing "pypy"
is in sys.path.
If y... | 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.