desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error.'
def seek(self, pos, whence=0):
if self.closed: raise ValueError('I/O operation on closed file') if (not self.seekable): raise OSError('cannot seek') if (whence == 1): pos = (pos + self.size_read) elif (whence == 2): pos = (pos + self.chunksize) if ((pos < 0) or (pos > self.chunksize)...
'Read at most size bytes from the chunk. If size is omitted or negative, read until the end of the chunk.'
def read(self, size=(-1)):
if self.closed: raise ValueError('I/O operation on closed file') if (self.size_read >= self.chunksize): return '' if (size < 0): size = (self.chunksize - self.size_read) if (size > (self.chunksize - self.size_read)): size = (self.chunksize - self.size_read) ...
'Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk.'
def skip(self):
if self.closed: raise ValueError('I/O operation on closed file') if self.seekable: try: n = (self.chunksize - self.size_read) if (self.align and (self.chunksize & 1)): n = (n + 1) self.file.seek(n, 1) self.size_read = (s...
'Return list of C argument into, one for each field. Argument info is 3-tuple of a C type, variable name, and flag that is true if type can be NULL.'
def get_args(self, fields):
args = [] unnamed = {} for f in fields: if (f.name is None): name = f.type c = unnamed[name] = (unnamed.get(name, 0) + 1) if (c > 1): name = ('name%d' % (c - 1)) else: name = f.name if f.seq: if (f.type.value...
'[\w\.]+'
def t_id(self, s):
self.rv.append(Id(s, self.lineno))
''
def t_string(self, s):
self.rv.append(String(s, self.lineno))
''
def t_xxx(self, s):
self.rv.append(Token(s, self.lineno))
''
def t_punctuation(self, s):
self.rv.append(Token(s, self.lineno))
'\-\-[^\n]*'
def t_comment(self, s):
pass
'\n'
def t_newline(self, s):
self.lineno += 1
'[ \t]+'
def t_whitespace(self, s):
pass
''
def t_default(self, s):
raise ValueError(('unmatched input: %r' % s))
'module ::= Id Id { }'
def p_module_0(self, info):
(module, name, _0, _1) = info if (module.value != 'module'): raise ASDLSyntaxError(module.lineno, msg=("expected 'module', found %s" % module)) return Module(name, None)
'module ::= Id Id { definitions }'
def p_module(self, info):
(module, name, _0, definitions, _1) = info if (module.value != 'module'): raise ASDLSyntaxError(module.lineno, msg=("expected 'module', found %s" % module)) return Module(name, definitions)
'definitions ::= definition'
def p_definition_0(self, definition):
return definition[0]
'definitions ::= definition definitions'
def p_definition_1(self, definitions):
return (definitions[0] + definitions[1])
'definition ::= Id = type'
def p_definition(self, info):
(id, _, type) = info return [Type(id, type)]
'type ::= product'
def p_type_0(self, product):
return product[0]
'type ::= sum'
def p_type_1(self, sum):
return Sum(sum[0])
'type ::= sum Id ( fields )'
def p_type_2(self, info):
(sum, id, _0, attributes, _1) = info if (id.value != 'attributes'): raise ASDLSyntaxError(id.lineno, msg=('expected attributes, found %s' % id)) return Sum(sum, attributes)
'product ::= ( fields )'
def p_product_0(self, info):
(_0, fields, _1) = info return Product(fields)
'product ::= ( fields ) Id ( fields )'
def p_product_1(self, info):
(_0, fields, _1, id, _2, attributes, _3) = info if (id.value != 'attributes'): raise ASDLSyntaxError(id.lineno, msg=('expected attributes, found %s' % id)) return Product(fields, attributes)
'sum ::= constructor'
def p_sum_0(self, constructor):
return [constructor[0]]
'sum ::= constructor | sum'
def p_sum_1(self, info):
(constructor, _, sum) = info return ([constructor] + sum)
'sum ::= constructor | sum'
def p_sum_2(self, info):
(constructor, _, sum) = info return ([constructor] + sum)
'constructor ::= Id'
def p_constructor_0(self, id):
return Constructor(id[0])
'constructor ::= Id ( fields )'
def p_constructor_1(self, info):
(id, _0, fields, _1) = info return Constructor(id, fields)
'fields ::= field'
def p_fields_0(self, field):
return [field[0]]
'fields ::= fields , field'
def p_fields_1(self, info):
(fields, _, field) = info return (fields + [field])
'field ::= Id'
def p_field_0(self, type_):
return Field(type_[0])
'field ::= Id Id'
def p_field_1(self, info):
(type, name) = info return Field(type, name)
'field ::= Id * Id'
def p_field_2(self, info):
(type, _, name) = info return Field(type, name, seq=True)
'field ::= Id ? Id'
def p_field_3(self, info):
(type, _, name) = info return Field(type, name, opt=True)
'field ::= Id *'
def p_field_4(self, type_):
return Field(type_[0], seq=True)
'field ::= Id ?'
def p_field_5(self, type_):
return Field(type[0], opt=True)
'( . | \n )+'
def t_default(self, s):
output('Specification error: unmatched input') raise SystemExit
'Initialization is from the C context'
def __init__(self, c_ctx=None, p_ctx=None):
self.c = (C.getcontext() if (c_ctx is None) else c_ctx) self.p = (P.getcontext() if (p_ctx is None) else p_ctx) self.p.prec = self.c.prec self.p.Emin = self.c.Emin self.p.Emax = self.c.Emax self.p.rounding = self.c.rounding self.p.capitals = self.c.capitals self.settraps([sig for sig in ...
'lst: C signal list'
def settraps(self, lst):
self.clear_traps() for signal in lst: self.c.traps[signal] = True self.p.traps[CondMap[signal]] = True
'lst: C signal list'
def setstatus(self, lst):
self.clear_status() for signal in lst: self.c.flags[signal] = True self.p.flags[CondMap[signal]] = True
'assert equality of C and P status'
def assert_eq_status(self):
for signal in self.c.flags: if (self.c.flags[signal] == (not self.p.flags[CondMap[signal]])): return False return True
'ftp://ftp.inria.fr/INRIA/publication/publi-pdf/RR/RR-5504.pdf'
def harrison_ulp(self, dec):
a = dec.next_plus() b = dec.next_minus() return abs((a - b))
'Determine the effective direction of the rounding when the exact result x is rounded according to mode. Return -1 for downwards, 0 for undirected, 1 for upwards, 2 for ROUND_05UP.'
def rounding_direction(self, x, mode):
cmp = (1 if (x.compare_total(P.Decimal('+0')) >= 0) else (-1)) if (mode in (P.ROUND_HALF_EVEN, P.ROUND_HALF_UP, P.ROUND_HALF_DOWN)): return 0 elif (mode == P.ROUND_CEILING): return 1 elif (mode == P.ROUND_FLOOR): return (-1) elif (mode == P.ROUND_UP): return cmp e...
'Check if results of _decimal\'s power function are within the allowed ulp ranges.'
def bin_resolve_ulp(self, t):
if (t.rc.is_nan() or t.rp.is_nan()): return False self.maxctx.prec = (context.p.prec * 2) (op1, op2) = (t.pop[0], t.pop[1]) if t.contextfunc: exact = getattr(self.maxctx, t.funcname)(op1, op2) else: exact = getattr(op1, t.funcname)(op2, context=self.maxctx) rounded = P.De...
'In extremely rare cases where the infinite precision result is just below etiny, cdecimal does not set Subnormal/Underflow. Example: setcontext(Context(prec=21, rounding=ROUND_UP, Emin=-55, Emax=85)) Decimal("1.00000000000000000000000000000000000000000000000" "0000000100000000000000000000000000000000000000000" "000000...
def resolve_underflow(self, t):
if (t.cresults != t.presults): return False if (context.c.flags[C.Rounded] and context.c.flags[C.Inexact] and context.p.flags[P.Rounded] and context.p.flags[P.Inexact]): return True return False
'Resolve Underflow or ULP difference.'
def exp(self, t):
return self.resolve_underflow(t)
'Resolve Underflow or ULP difference.'
def log10(self, t):
return self.resolve_underflow(t)
'Resolve Underflow or ULP difference.'
def ln(self, t):
return self.resolve_underflow(t)
'Always calls the resolve function. C.Decimal does not have correct rounding for the power function.'
def __pow__(self, t):
if (context.c.flags[C.Rounded] and context.c.flags[C.Inexact] and context.p.flags[P.Rounded] and context.p.flags[P.Inexact]): return self.bin_resolve_ulp(t) else: return False
'NaN comparison in the verify() function obviously gives an incorrect answer: nan == nan -> False'
def __float__(self, t):
if (t.cop[0].is_nan() and t.pop[0].is_nan()): return True return False
'decimal.py gives precedence to the first NaN; this is not important, as __radd__ will not be called for two decimal arguments.'
def __radd__(self, t):
if (t.rc.is_nan() and t.rp.is_nan()): return True return False
'Exception: Decimal(\'1\').__round__(-100000000000000000000000000) Should it really be InvalidOperation?'
def __round__(self, t):
if ((t.rc is None) and t.rp.is_nan()): return True return False
'A rule for ignoring issues'
def __init__(self, docname, lineno, issue, line):
self.docname = docname self.lineno = lineno self.issue = issue self.line = line self.used = False
'Determine whether this issue should be ignored.'
def is_ignored(self, line, lineno, issue):
docname = self.docname for rule in self.rules: if (rule.docname != docname): continue if (rule.issue != issue): continue if (rule.line not in line): continue if ((rule.lineno is not None) and (abs((rule.lineno - lineno)) > 5)): cont...
'Load database of previously ignored issues. A csv file, with exactly the same format as suspicious.csv Fields: document name (normalized), line number, issue, surrounding text'
def load_rules(self, filename):
self.info('loading ignore rules... ', nonl=1) self.rules = rules = [] try: if py3: f = open(filename, 'r') else: f = open(filename, 'rb') except IOError: return for (i, row) in enumerate(csv.reader(f)): if (len(row) != 4): ...
'Add a new Option instance to the Application dynamically. Note that this has to be done *before* .parse() is being executed.'
def add_option(self, option):
self.options.append(option) self.option_map[option.name] = option
'Set user defined instance variables. If this method returns anything other than None, the process is terminated with the return value as exit code.'
def startup(self):
return None
'Exit the program. rc is used as exit code and passed back to the calling program. It defaults to 0 which usually means: OK.'
def exit(self, rc=0):
raise SystemExit(rc)
'Parse the command line and fill in self.values and self.files. After having parsed the options, the remaining command line arguments are interpreted as files and passed to .handle_files() for processing. As final step the option handlers are called in the order of the options given on the command line.'
def parse(self):
self.values = values = {} for o in self.options: if o.has_default: values[(o.prefix + o.name)] = o.default else: values[(o.prefix + o.name)] = 0 (flags, lflags) = _getopt_flags(self.options) try: (optlist, files) = getopt.getopt(self.arguments, flags, lfla...
'Apply some user defined checks on the files given in filelist. This may modify filelist in place. A typical application is checking that at least n files are given. If this method returns anything other than None, the process is terminated with the return value as exit code.'
def check_files(self, filelist):
return None
'This may process the files list in place.'
def handle_files(self, files):
return None
'Turn on verbose output.'
def handle_v(self, value):
self.verbose = 1
'Override this method as program entry point. The return value is passed to sys.exit() as argument. If it is None, 0 is assumed (meaning OK). Unhandled exceptions are reported with exit status code 1 (see __init__ for further details).'
def main(self):
return None
'Return the timer function to use for the test.'
def get_timer(self):
return get_timer(self.timer)
'Return 1/0 depending on whether the test is compatible with the other Test instance or not.'
def compatible(self, other):
if (self.version != other.version): return 0 if (self.rounds != other.rounds): return 0 return 1
'Run the test in two phases: first calibrate, then do the actual test. Be careful to keep the calibration timing low w/r to the test timing.'
def run(self):
test = self.test timer = self.get_timer() min_overhead = min(self.overhead_times) t = timer() test() t = (timer() - t) if (t < MIN_TEST_RUNTIME): raise ValueError('warp factor too high: test times are < 10ms') eff_time = (t - min_overhead) if (eff_time...
'Calibrate the test. This method should execute everything that is needed to setup and run the test - except for the actual operations that you intend to measure. pybench uses this method to measure the test implementation overhead.'
def calibrate(self):
return
'Run the test. The test needs to run self.rounds executing self.operations number of operations each.'
def test(self):
return
'Return test run statistics as tuple: (minimum run time, average run time, total run time, average time per operation, minimum overhead time)'
def stat(self):
runs = len(self.times) if (runs == 0): return (0.0, 0.0, 0.0, 0.0) min_time = min(self.times) total_time = sum(self.times) avg_time = (total_time / float(runs)) operation_avg = (total_time / float(((runs * self.rounds) * self.operations))) if self.overhead_times: min_overhead...
'Return the timer function to use for the test.'
def get_timer(self):
return get_timer(self.timer)
'Return 1/0 depending on whether the benchmark is compatible with the other Benchmark instance or not.'
def compatible(self, other):
if (self.version != other.version): return 0 if ((self.machine_details == other.machine_details) and (self.timer != other.timer)): return 0 if ((self.calibration_runs == 0) and (other.calibration_runs != 0)): return 0 if ((self.calibration_runs != 0) and (other.calibration_runs =...
'Return benchmark run statistics as tuple: (minimum round time, average round time, maximum round time) XXX Currently not used, since the benchmark does test statistics across all rounds.'
def stat(self):
runs = len(self.roundtimes) if (runs == 0): return (0.0, 0.0) min_time = min(self.roundtimes) total_time = sum(self.roundtimes) avg_time = (total_time / float(runs)) max_time = max(self.roundtimes) return (min_time, avg_time, max_time)
'openssl CLI binary'
@property def openssl_cli(self):
return os.path.join(self.install_dir, 'bin', 'openssl')
'output of \'bin/openssl version\''
@property def openssl_version(self):
env = os.environ.copy() env['LD_LIBRARY_PATH'] = self.lib_dir cmd = [self.openssl_cli, 'version'] return self._subprocess_output(cmd, env=env)
'Value of ssl.OPENSSL_VERSION'
@property def pyssl_version(self):
env = os.environ.copy() env['LD_LIBRARY_PATH'] = self.lib_dir cmd = ['./python', '-c', 'import ssl; print(ssl.OPENSSL_VERSION)'] return self._subprocess_output(cmd, env=env)
'Download OpenSSL source dist'
def _download_openssl(self):
src_dir = os.path.dirname(self.src_file) if (not os.path.isdir(src_dir)): os.makedirs(src_dir) url = self.url_template.format(self.version) log.info('Downloading OpenSSL from {}'.format(url)) req = urlopen(url, cadefault=CADEFAULT) data = req.read() log.info('Storing {}'....
'Unpack tar.gz bundle'
def _unpack_openssl(self):
if os.path.isdir(self.build_dir): shutil.rmtree(self.build_dir) os.makedirs(self.build_dir) tf = tarfile.open(self.src_file) base = 'openssl-{}/'.format(self.version) members = tf.getmembers() for member in members: if (not member.name.startswith(base)): raise ValueEr...
'Now build openssl'
def _build_openssl(self):
log.info('Running build in {}'.format(self.install_dir)) cwd = self.build_dir cmd = ['./config', 'shared', '--prefix={}'.format(self.install_dir)] cmd.extend(self.openssl_compile_args) self._subprocess_call(cmd, cwd=cwd) self._subprocess_call(['make'], cwd=cwd)
'Constructor. Load the sheet from the filename argument. Set up the Tk widget tree.'
def __init__(self, filename='sheet1.xml', rows=10, columns=5):
self.filename = filename self.sheet = Sheet() if os.path.isfile(filename): self.sheet.load(filename) (maxx, maxy) = self.sheet.getsize() rows = max(rows, maxy) columns = max(columns, maxx) self.root = Tk.Tk() self.root.wm_title(('Spreadsheet: %s' % self.filename)) self.bea...
'Helper to create the grid of GUI cells. The edge (x==0 or y==0) is filled with labels; the rest is real cells.'
def makegrid(self, rows, columns):
self.rows = rows self.columns = columns self.gridcells = {} cell = Tk.Label(self.cellgrid, relief='raised') cell.grid_configure(column=0, row=0, sticky='NSWE') cell.bind('<ButtonPress-1>', self.selectall) for x in range(1, (columns + 1)): self.cellgrid.grid_columnconfigure(x, minsize...
'Make (x, y) the current cell.'
def setcurrent(self, x, y):
if (self.currentxy is not None): self.change_cell() self.clearfocus() self.beacon['text'] = cellname(x, y) self.load_entry(x, y) self.entry.focus_set() self.currentxy = (x, y) self.cornerxy = None gridcell = self.gridcells.get(self.currentxy) if (gridcell is not None): ...
'Callback for the Return key.'
def return_event(self, event):
self.change_cell() (x, y) = self.currentxy self.setcurrent(x, (y + 1)) return 'break'
'Callback for the Return key with Shift modifier.'
def shift_return_event(self, event):
self.change_cell() (x, y) = self.currentxy self.setcurrent(x, max(1, (y - 1))) return 'break'
'Callback for the Tab key.'
def tab_event(self, event):
self.change_cell() (x, y) = self.currentxy self.setcurrent((x + 1), y) return 'break'
'Callback for the Tab key with Shift modifier.'
def shift_tab_event(self, event):
self.change_cell() (x, y) = self.currentxy self.setcurrent(max(1, (x - 1)), y) return 'break'
'Set the current cell from the entry widget.'
def change_cell(self):
(x, y) = self.currentxy text = self.entry.get() cell = None if text.startswith('='): cell = FormulaCell(text[1:]) else: for cls in (int, float, complex): try: value = cls(text) except: continue else: ...
'Fill the GUI cells from the sheet cells.'
def sync(self):
self.sheet.recalc() for ((x, y), gridcell) in self.gridcells.items(): if ((x == 0) or (y == 0)): continue cell = self.sheet.getcell(x, y) if (cell is None): gridcell['text'] = '' else: if hasattr(cell, 'format'): (text, alignmen...
'Create a new LifeBoard instance. scr -- curses screen object to use for display char -- character used to render live cells (default: \'*\')'
def __init__(self, scr, char=ord('*')):
self.state = {} self.scr = scr (Y, X) = self.scr.getmaxyx() (self.X, self.Y) = ((X - 2), ((Y - 2) - 1)) self.char = char self.scr.clear() border_line = (('+' + (self.X * '-')) + '+') self.scr.addstr(0, 0, border_line) self.scr.addstr((self.Y + 1), 0, border_line) for y in range(0...
'Set a cell to the live state'
def set(self, y, x):
if ((x < 0) or (self.X <= x) or (y < 0) or (self.Y <= y)): raise ValueError(('Coordinates out of range %i,%i' % (y, x))) self.state[(x, y)] = 1
'Toggle a cell\'s state between live and dead'
def toggle(self, y, x):
if ((x < 0) or (self.X <= x) or (y < 0) or (self.Y <= y)): raise ValueError(('Coordinates out of range %i,%i' % (y, x))) if ((x, y) in self.state): del self.state[(x, y)] self.scr.addch((y + 1), (x + 1), ' ') else: self.state[(x, y)] = 1 if curses.has_c...
'Clear the entire board and update the board display'
def erase(self):
self.state = {} self.display(update_board=False)
'Display the whole board, optionally computing one generation'
def display(self, update_board=True):
(M, N) = (self.X, self.Y) if (not update_board): for i in range(0, M): for j in range(0, N): if ((i, j) in self.state): self.scr.addch((j + 1), (i + 1), self.char) else: self.scr.addch((j + 1), (i + 1), ' ') s...
'Fill the board with a random pattern'
def make_random(self):
self.state = {} for i in range(0, self.X): for j in range(0, self.Y): if (random.random() > 0.5): self.set(j, i)
'Override to display an error arising from GUI usage'
def errorDialog(self, title, message):
pass
'Override to prompt user for directory to perform test discovery'
def getDirectoryToDiscover(self):
pass
'To be called in response to user choosing to run a test'
def runClicked(self):
if self.running: return if (not self.test_suite): self.errorDialog('Test Discovery', 'You discover some tests first!') return self.currentResult = GUITestResult(self) self.totalTests = self.test_suite.countTestCases() self.running = 1 self.notifyRunning() ...
'To be called in response to user stopping the running of a test'
def stopClicked(self):
if self.currentResult: self.currentResult.stop()
'Override to display information about the suite of discovered tests'
def notifyTestsDiscovered(self, test_suite):
pass
'Override to set GUI in \'running\' mode, enabling \'stop\' button etc.'
def notifyRunning(self):
pass
'Override to set GUI in \'stopped\' mode, enabling \'run\' button etc.'
def notifyStopped(self):
pass
'Override to indicate that a test has just failed'
def notifyTestFailed(self, test, err):
pass