id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
185,931 | import fnmatch
import glob
import os
import os.path
import shutil
import stat
from .iterutil import iter_many
S_IRANY = stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
def _get_file_info(file):
filename = st = mode = None
if isinstance(file, int):
mode = file
elif isinstance(file, os.stat_result):
st = file
else:
if isinstance(file, str):
filename = file
elif hasattr(file, 'name') and os.path.exists(file.name):
filename = file.name
else:
raise NotImplementedError(file)
st = os.stat(filename)
return filename, st, mode or st.st_mode
def _check_file(filename, check):
if not isinstance(filename, str):
raise Exception(f'filename required to check file, got {filename}')
if check & S_IRANY:
flags = os.O_RDONLY
elif check & S_IWANY:
flags = os.O_WRONLY
elif check & S_IXANY:
# We can worry about S_IXANY later
return NotImplemented
else:
raise NotImplementedError(check)
try:
fd = os.open(filename, flags)
except PermissionError:
return False
# We do not ignore other exceptions.
else:
os.close(fd)
return True
def _check_mode(st, mode, check, user):
orig = check
_, uid, gid, groups = _get_user_info(user)
if check & S_IRANY:
check -= S_IRANY
matched = False
if mode & stat.S_IRUSR:
if st.st_uid == uid:
matched = True
if mode & stat.S_IRGRP:
if st.st_uid == gid or st.st_uid in groups:
matched = True
if mode & stat.S_IROTH:
matched = True
if not matched:
return False
if check & S_IWANY:
check -= S_IWANY
matched = False
if mode & stat.S_IWUSR:
if st.st_uid == uid:
matched = True
if mode & stat.S_IWGRP:
if st.st_uid == gid or st.st_uid in groups:
matched = True
if mode & stat.S_IWOTH:
matched = True
if not matched:
return False
if check & S_IXANY:
check -= S_IXANY
matched = False
if mode & stat.S_IXUSR:
if st.st_uid == uid:
matched = True
if mode & stat.S_IXGRP:
if st.st_uid == gid or st.st_uid in groups:
matched = True
if mode & stat.S_IXOTH:
matched = True
if not matched:
return False
if check:
raise NotImplementedError((orig, check))
return True
def is_readable(file, *, user=None, check=False):
filename, st, mode = _get_file_info(file)
if check:
try:
okay = _check_file(filename, S_IRANY)
except NotImplementedError:
okay = NotImplemented
if okay is not NotImplemented:
return okay
# Fall back to checking the mode.
return _check_mode(st, mode, S_IRANY, user) | null |
185,932 | import fnmatch
import glob
import os
import os.path
import shutil
import stat
from .iterutil import iter_many
S_IWANY = stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH
def _get_file_info(file):
def _check_file(filename, check):
def _check_mode(st, mode, check, user):
def is_writable(file, *, user=None, check=False):
filename, st, mode = _get_file_info(file)
if check:
try:
okay = _check_file(filename, S_IWANY)
except NotImplementedError:
okay = NotImplemented
if okay is not NotImplemented:
return okay
# Fall back to checking the mode.
return _check_mode(st, mode, S_IWANY, user) | null |
185,933 | def chain_test(n):
"""
This is the standard DeltaBlue benchmark. A long chain of equality
constraints is constructed with a stay constraint on one end. An
edit constraint is then added to the opposite end and the time is
measured for adding and removing this constraint, and extracting
and executing a constraint satisfaction plan. There are two cases.
In case 1, the added constraint is stronger than the stay
constraint and values must propagate down the entire length of the
chain. In case 2, the added constraint is weaker than the stay
constraint so it cannot be accomodated. The cost in this case is,
of course, very low. Typical situations lie somewhere between these
two extremes.
"""
planner = recreate_planner()
prev = None
first = None
last = None
# We need to go up to n inclusively.
i = 0
end = n + 1
while i < n + 1:
name = "v%s" % i
v = Variable(name)
if prev is not None:
EqualityConstraint(prev, v, Strength.REQUIRED)
if i == 0:
first = v
if i == n:
last = v
prev = v
i = i + 1
StayConstraint(last, Strength.STRONG_DEFAULT)
edit = EditConstraint(first, Strength.PREFERRED)
edits = OrderedCollection()
edits.append(edit)
plan = planner.extract_plan_from_constraints(edits)
i = 0
while i < 100:
first.value = i
plan.execute()
if last.value != i:
print("Chain test failed.")
i = i + 1
def projection_test(n):
"""
This test constructs a two sets of variables related to each
other by a simple linear transformation (scale and offset). The
time is measured to change a variable on either side of the
mapping and to change the scale and offset factors.
"""
planner = recreate_planner()
scale = Variable("scale", 10)
offset = Variable("offset", 1000)
src = None
dests = OrderedCollection()
i = 0
while i < n:
src = Variable("src%s" % i, i)
dst = Variable("dst%s" % i, i)
dests.append(dst)
StayConstraint(src, Strength.NORMAL)
ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED)
i = i + 1
change(src, 17)
if dst.value != 1170:
print("Projection 1 failed")
change(dst, 1050)
if src.value != 5:
print("Projection 2 failed")
change(scale, 5)
i = 0
while i < n - 1:
if dests[i].value != (i * 5 + 1000):
print("Projection 3 failed")
i = i + 1
change(offset, 2000)
i = 0
while i < n - 1:
if dests[i].value != (i * 5 + 2000):
print("Projection 4 failed")
i = i + 1
def delta_blue(n):
chain_test(n)
projection_test(n) | null |
185,934 | from __future__ import annotations
import __static__
from __static__ import cast
import sys
from typing import Final, List
tracing: bool = False
def trace(a):
taskWorkArea: Final[TaskWorkArea] = TaskWorkArea()
class Task(TaskState):
def __init__(self, i: int, p: int, w: Packet | None, initialState: TaskState, r: TaskRec) -> None:
def fn(self, pkt: Packet | None, r: TaskRec) -> Task | None:
def addPacket(self, p: Packet, old: Task) -> Task:
def runTask(self) -> Task | None:
def waitTask(self) -> Task:
def hold(self) -> Task | None:
def release(self, i: int) -> Task:
def qpkt(self, pkt: Packet) -> Task:
def findtcb(self, id: int) -> Task:
def schedule() -> None:
t: Task | None = taskWorkArea.taskList
while t is not None:
if tracing:
print("tcb =", t.ident)
if t.isTaskHoldingOrWaiting():
t = t.link
else:
if tracing:
trace(chr(ord("0") + t.ident))
t = t.runTask() | null |
185,935 | from __future__ import annotations
import __static__
from __static__ import int64, box
from typing import Callable, List
class int64(int):
pass
def box(o):
return o
Callable = _CallableType(collections.abc.Callable, 2)
Callable.__doc__ = \
"""Callable type; Callable[[int], str] is a function of (int) -> str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type. The argument list
must be a list of types or ellipsis; the return type must be a single type.
There is no syntax to indicate optional or keyword arguments,
such function types are rarely used as callback types.
"""
List = _alias(list, 1, inst=False, name='List')
def fannkuch(n: int) -> int:
count: List[int] = list(range(1, n + 1))
max_flips: int64 = 0
m: int = n - 1
n64: int64 = int64(n)
r: int64 = n64
perm1: List[int] = list(range(n))
perm: List[int] = list(range(n))
perm1_ins: Callable[[int, int], None] = perm1.insert
perm1_pop: Callable[[int], int] = perm1.pop
while 1:
while r != 1:
count[r - 1] = box(r)
r -= 1
if perm1[0] != 0 and perm1[m] != m:
perm = perm1[:]
flips_count: int64 = 0
k: int = perm[0]
while k:
perm[: k + 1] = perm[k::-1]
flips_count += 1
k = perm[0]
if flips_count > max_flips:
max_flips = flips_count
while r != n64:
perm1_ins(box(r), perm1_pop(0))
count[r] -= 1
if count[r] > 0:
break
r += 1
else:
return box(max_flips) | null |
185,936 | def bench_n_queens(queen_count):
return list(n_queens(queen_count))
def run():
queen_count = 8
bench_n_queens(queen_count) | null |
185,938 | DEFAULT_ITERATIONS = 20000
DEFAULT_REFERENCE = "sun"
def bench_nbody(loops, reference, iterations):
# Set up global state
offset_momentum(BODIES[reference])
range_it = range(loops)
for _ in range_it:
report_energy()
advance(0.01, iterations)
report_energy()
def run():
num_loops = 5
bench_nbody(num_loops, DEFAULT_REFERENCE, DEFAULT_ITERATIONS) | null |
185,939 | from __future__ import annotations
import __static__
from __static__ import CheckedList, cast
from typing import final
from enum import IntEnum
def chain_test(n: int) -> None:
"""
This is the standard DeltaBlue benchmark. A long chain of equality
constraints is constructed with a stay constraint on one end. An
edit constraint is then added to the opposite end and the time is
measured for adding and removing this constraint, and extracting
and executing a constraint satisfaction plan. There are two cases.
In case 1, the added constraint is stronger than the stay
constraint and values must propagate down the entire length of the
chain. In case 2, the added constraint is weaker than the stay
constraint so it cannot be accomodated. The cost in this case is,
of course, very low. Typical situations lie somewhere between these
two extremes.
"""
planner = recreate_planner()
prev: Variable | None = None
first: Variable | None = None
last: Variable | None = None
# We need to go up to n inclusively.
i = 0
end = n + 1
while i < n + 1:
name = "v%s" % i
v = Variable(name)
if prev is not None:
EqualityConstraint(prev, v, Strength.REQUIRED)
if i == 0:
first = v
if i == n:
last = v
prev = v
i = i + 1
first = cast(Variable, first)
last = cast(Variable, last)
StayConstraint(last, Strength.STRONG_DEFAULT)
edit = EditConstraint(first, Strength.PREFERRED)
edits: CheckedList[Constraint] = []
edits.append(edit)
plan = planner.extract_plan_from_constraints(edits)
i = 0
while i < 100:
first.value = i
plan.execute()
if last.value != i:
print("Chain test failed.")
i = i + 1
def projection_test(n: int) -> None:
"""
This test constructs a two sets of variables related to each
other by a simple linear transformation (scale and offset). The
time is measured to change a variable on either side of the
mapping and to change the scale and offset factors.
"""
planner = recreate_planner()
scale = Variable("scale", 10)
offset = Variable("offset", 1000)
src: Variable | None = None
dests: CheckedList[Variable] = []
i = 0
dst = Variable("dst%s" % i, i)
while i < n:
src = Variable("src%s" % i, i)
dst = Variable("dst%s" % i, i)
dests.append(dst)
StayConstraint(src, Strength.NORMAL)
ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED)
i = i + 1
src = cast(Variable, src)
change(src, 17)
if dst.value != 1170:
print("Projection 1 failed")
change(dst, 1050)
if src.value != 5:
print("Projection 2 failed")
change(scale, 5)
i = 0
while i < n - 1:
if dests[i].value != (i * 5 + 1000):
print("Projection 3 failed")
i = i + 1
change(offset, 2000)
i = 0
while i < n - 1:
if dests[i].value != (i * 5 + 2000):
print("Projection 4 failed")
i = i + 1
def delta_blue(n: int) -> None:
chain_test(n)
projection_test(n) | null |
185,940 | DEFAULT_ARG = 9
def fannkuch(n):
count = list(range(1, n + 1))
max_flips = 0
m = n - 1
r = n
perm1 = list(range(n))
perm = list(range(n))
perm1_ins = perm1.insert
perm1_pop = perm1.pop
while 1:
while r != 1:
count[r - 1] = r
r -= 1
if perm1[0] != 0 and perm1[m] != m:
perm = perm1[:]
flips_count = 0
k = perm[0]
while k:
perm[: k + 1] = perm[k::-1]
flips_count += 1
k = perm[0]
if flips_count > max_flips:
max_flips = flips_count
while r != n:
perm1_ins(r, perm1_pop(0))
count[r] -= 1
if count[r] > 0:
break
r += 1
else:
return max_flips
def run():
arg = DEFAULT_ARG
fannkuch(arg) | null |
185,941 | from __future__ import annotations
import __static__
from __static__ import box, int64, Array
ArrayI64 = Array[int64]
class int64(int):
pass
def box(o):
return o
def fannkuch(nb: int) -> int:
n: int64 = int64(nb)
count: ArrayI64 = ArrayI64(range(1, nb + 1))
max_flips: int64 = 0
m: int64 = n - 1
r: int64 = n
perm1: ArrayI64 = ArrayI64(range(nb))
perm: ArrayI64 = ArrayI64(range(nb))
perm0: ArrayI64 = ArrayI64(range(nb))
while 1:
while r != 1:
count[r - 1] = r
r -= 1
if perm1[0] != 0 and perm1[m] != m:
i: int64 = 0
while i < n:
perm[i] = perm1[i]
i += 1
flips_count: int64 = 0
k: int64 = perm[0]
while k:
i = k
while i >= 0:
perm0[i] = perm[k-i]
i -= 1
i = k
while i >= 0:
perm[i] = perm0[i]
i -= 1
flips_count += 1
k = perm[0]
if flips_count > max_flips:
max_flips = flips_count
while r != n:
first: int64 = perm1[0]
i = 1
while i <= r:
perm1[i-1] = perm1[i]
i += 1
perm1[r] = first
count[r] -= 1
if count[r] > 0:
break
r += 1
else:
return box(max_flips) | null |
185,942 | from __future__ import annotations
import __static__
from __static__ import int64, box, Array, cbool, clen
from typing import List, Generator, Iterator
ArrayI64 = Array[int64]
def solve(queen_count: int) -> Iterator[ArrayI64]:
"""N-Queens solver.
Args:
queen_count: the number of queens to solve for. This is also the
board size.
Yields:
Solutions to the problem. Each yielded value is looks like
(3, 8, 2, 1, 4, ..., 6) where each number is the column position for the
queen, and the index into the tuple indicates the row.
"""
# The generator is still needed as it is being used to check if it is a valid configuration using sets
cols: Iterator[int] = range(queen_count)
static_cols: ArrayI64 = create_array(0, int64(queen_count), 1)
for vec in permutations(static_cols):
if (
queen_count
== len(set(vec[i] + i for i in cols)) # noqa: C401
== len(set(vec[i] - i for i in cols)) # noqa: C401
):
yield vec
List = _alias(list, 1, inst=False, name='List')
The provided code snippet includes necessary dependencies for implementing the `bench_n_queens` function. Write a Python function `def bench_n_queens(queen_count: int) -> List[ArrayI64]` to solve the following problem:
Return all the possible valid configurations of the queens in a board of size queen_count. See solve method to understand it better
Here is the function:
def bench_n_queens(queen_count: int) -> List[ArrayI64]:
"""
Return all the possible valid configurations of the queens
in a board of size queen_count.
See solve method to understand it better
"""
return list(solve(queen_count)) | Return all the possible valid configurations of the queens in a board of size queen_count. See solve method to understand it better |
185,943 | from __future__ import annotations
import __static__
from __static__ import cast
from typing import Final, List
LOOPS: Final[int] = 50000
def pystones(loops=LOOPS):
def run() -> None:
loops: int = LOOPS
pystones(loops) | null |
185,944 | import __static__
from __static__ import double, CheckedList, CheckedDict, box
The provided code snippet includes necessary dependencies for implementing the `combinations` function. Write a Python function `def combinations(l)` to solve the following problem:
Pure-Python implementation of itertools.combinations(l, 2).
Here is the function:
def combinations(l):
"""Pure-Python implementation of itertools.combinations(l, 2)."""
result = []
for x in range(len(l) - 1):
ls = l[x + 1 :]
for y in ls:
result.append((l[x], y))
return result | Pure-Python implementation of itertools.combinations(l, 2). |
185,945 | import __static__
from __static__ import double, CheckedList, CheckedDict, box
DEFAULT_ITERATIONS = 20000
DEFAULT_REFERENCE = "sun"
def bench_nbody(loops, reference, iterations):
# Set up global state
offset_momentum(BODIES[reference], SYSTEM)
range_it = range(loops)
for _ in range_it:
report_energy(SYSTEM, PAIRS)
advance(0.01, iterations, SYSTEM, PAIRS)
report_energy(SYSTEM, PAIRS)
def run():
num_loops = 5
bench_nbody(num_loops, DEFAULT_REFERENCE, DEFAULT_ITERATIONS) | null |
185,946 | from __future__ import annotations
import __static__
from typing import Generator, Tuple, Iterator
def n_queens(queen_count: int) -> Iterator[List[int]]:
"""N-Queens solver.
Args:
queen_count: the number of queens to solve for. This is also the
board size.
Yields:
Solutions to the problem. Each yielded value is looks like
(3, 8, 2, 1, 4, ..., 6) where each number is the column position for the
queen, and the index into the tuple indicates the row.
"""
cols: Iterator[int] = range(queen_count)
for vec in permutations(cols):
if (
queen_count
== len(set(vec[i] + i for i in cols)) # noqa: C401
== len(set(vec[i] - i for i in cols)) # noqa: C401
):
yield vec
def bench_n_queens(queen_count: int) -> List[List[int]]:
return list(n_queens(queen_count)) | null |
185,947 | import sys
tracing = False
def trace(a):
taskWorkArea = TaskWorkArea()
def schedule():
t = taskWorkArea.taskList
while t is not None:
if tracing:
print("tcb =", t.ident)
if t.isTaskHoldingOrWaiting():
t = t.link
else:
if tracing:
trace(chr(ord("0") + t.ident))
t = t.runTask() | null |
185,948 | import __static__
from typing import List, Mapping, Tuple, TypeVar
T = TypeVar("T")
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
Tuple.__doc__ = \
"""Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Example: Tuple[T1, T2] is a tuple of two elements corresponding
to type variables T1 and T2. Tuple[int, float, str] is a tuple
of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
"""
List = _alias(list, 1, inst=False, name='List')
The provided code snippet includes necessary dependencies for implementing the `combinations` function. Write a Python function `def combinations(l: List[T]) -> List[Tuple[T, T]]` to solve the following problem:
Pure-Python implementation of itertools.combinations(l, 2).
Here is the function:
def combinations(l: List[T]) -> List[Tuple[T, T]]:
"""Pure-Python implementation of itertools.combinations(l, 2)."""
result: List[Tuple[T, T]] = []
for x in range(len(l) - 1):
ls = l[x + 1 :]
for y in ls:
result.append((l[x], y))
return result | Pure-Python implementation of itertools.combinations(l, 2). |
185,949 | import __static__
from typing import List, Mapping, Tuple, TypeVar
DEFAULT_ITERATIONS: int = 20000
DEFAULT_REFERENCE: str = "sun"
def bench_nbody(loops: int, reference: str, iterations: int):
# Set up global state
offset_momentum(BODIES[reference])
range_it = range(loops)
for _ in range_it:
report_energy()
advance(0.01, iterations)
report_energy()
def run():
num_loops = 5
bench_nbody(num_loops, DEFAULT_REFERENCE, DEFAULT_ITERATIONS) | null |
185,950 | import asyncio
import math
import random
import time
from argparse import ArgumentParser
DEFAULT_MEMOIZABLE_PERCENTAGE = 90
DEFAULT_CPU_PROBABILITY = 0.5
class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects.
Keyword Arguments:
- prog -- The name of the program (default:
``os.path.basename(sys.argv[0])``)
- usage -- A usage message (default: auto-generated from arguments)
- description -- A description of what the program does
- epilog -- Text following the argument descriptions
- parents -- Parsers whose arguments should be copied into this one
- formatter_class -- HelpFormatter class for printing help messages
- prefix_chars -- Characters that prefix optional arguments
- fromfile_prefix_chars -- Characters that prefix files containing
additional arguments
- argument_default -- The default value for all arguments
- conflict_handler -- String indicating how to handle conflicts
- add_help -- Add a -h/-help option
- allow_abbrev -- Allow long options to be abbreviated unambiguously
- exit_on_error -- Determines whether or not ArgumentParser exits with
error info when an error occurs
"""
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=[],
formatter_class=HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True,
allow_abbrev=True,
exit_on_error=True):
superinit = super(ArgumentParser, self).__init__
superinit(description=description,
prefix_chars=prefix_chars,
argument_default=argument_default,
conflict_handler=conflict_handler)
# default setting for prog
if prog is None:
prog = _os.path.basename(_sys.argv[0])
self.prog = prog
self.usage = usage
self.epilog = epilog
self.formatter_class = formatter_class
self.fromfile_prefix_chars = fromfile_prefix_chars
self.add_help = add_help
self.allow_abbrev = allow_abbrev
self.exit_on_error = exit_on_error
add_group = self.add_argument_group
self._positionals = add_group(_('positional arguments'))
self._optionals = add_group(_('options'))
self._subparsers = None
# register types
def identity(string):
return string
self.register('type', None, identity)
# add help argument if necessary
# (using explicit default to override global argument_default)
default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
if self.add_help:
self.add_argument(
default_prefix+'h', default_prefix*2+'help',
action='help', default=SUPPRESS,
help=_('show this help message and exit'))
# add parent arguments and defaults
for parent in parents:
self._add_container_actions(parent)
try:
defaults = parent._defaults
except AttributeError:
pass
else:
self._defaults.update(defaults)
# =======================
# Pretty __repr__ methods
# =======================
def _get_kwargs(self):
names = [
'prog',
'usage',
'description',
'formatter_class',
'conflict_handler',
'add_help',
]
return [(name, getattr(self, name)) for name in names]
# ==================================
# Optional/Positional adding methods
# ==================================
def add_subparsers(self, **kwargs):
if self._subparsers is not None:
self.error(_('cannot have multiple subparser arguments'))
# add the parser class to the arguments if it's not present
kwargs.setdefault('parser_class', type(self))
if 'title' in kwargs or 'description' in kwargs:
title = _(kwargs.pop('title', 'subcommands'))
description = _(kwargs.pop('description', None))
self._subparsers = self.add_argument_group(title, description)
else:
self._subparsers = self._positionals
# prog defaults to the usage message of this parser, skipping
# optional arguments and with no "usage:" prefix
if kwargs.get('prog') is None:
formatter = self._get_formatter()
positionals = self._get_positional_actions()
groups = self._mutually_exclusive_groups
formatter.add_usage(self.usage, positionals, groups, '')
kwargs['prog'] = formatter.format_help().strip()
# create the parsers action and add it to the positionals list
parsers_class = self._pop_action_class(kwargs, 'parsers')
action = parsers_class(option_strings=[], **kwargs)
self._subparsers._add_action(action)
# return the created parsers action
return action
def _add_action(self, action):
if action.option_strings:
self._optionals._add_action(action)
else:
self._positionals._add_action(action)
return action
def _get_optional_actions(self):
return [action
for action in self._actions
if action.option_strings]
def _get_positional_actions(self):
return [action
for action in self._actions
if not action.option_strings]
# =====================================
# Command line argument parsing methods
# =====================================
def parse_args(self, args=None, namespace=None):
args, argv = self.parse_known_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
def parse_known_args(self, args=None, namespace=None):
if args is None:
# args default to the system args
args = _sys.argv[1:]
else:
# make sure that args are mutable
args = list(args)
# default Namespace built from parser defaults
if namespace is None:
namespace = Namespace()
# add any action defaults that aren't present
for action in self._actions:
if action.dest is not SUPPRESS:
if not hasattr(namespace, action.dest):
if action.default is not SUPPRESS:
setattr(namespace, action.dest, action.default)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
# parse the arguments and exit if there are any errors
if self.exit_on_error:
try:
namespace, args = self._parse_known_args(args, namespace)
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))
else:
namespace, args = self._parse_known_args(args, namespace)
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
return namespace, args
def _parse_known_args(self, arg_strings, namespace):
# replace arg strings that are file references
if self.fromfile_prefix_chars is not None:
arg_strings = self._read_args_from_files(arg_strings)
# map all mutually exclusive arguments to the other arguments
# they can't occur with
action_conflicts = {}
for mutex_group in self._mutually_exclusive_groups:
group_actions = mutex_group._group_actions
for i, mutex_action in enumerate(mutex_group._group_actions):
conflicts = action_conflicts.setdefault(mutex_action, [])
conflicts.extend(group_actions[:i])
conflicts.extend(group_actions[i + 1:])
# find all option indices, and determine the arg_string_pattern
# which has an 'O' if there is an option at an index,
# an 'A' if there is an argument, or a '-' if there is a '--'
option_string_indices = {}
arg_string_pattern_parts = []
arg_strings_iter = iter(arg_strings)
for i, arg_string in enumerate(arg_strings_iter):
# all args after -- are non-options
if arg_string == '--':
arg_string_pattern_parts.append('-')
for arg_string in arg_strings_iter:
arg_string_pattern_parts.append('A')
# otherwise, add the arg to the arg strings
# and note the index if it was an option
else:
option_tuple = self._parse_optional(arg_string)
if option_tuple is None:
pattern = 'A'
else:
option_string_indices[i] = option_tuple
pattern = 'O'
arg_string_pattern_parts.append(pattern)
# join the pieces together to form the pattern
arg_strings_pattern = ''.join(arg_string_pattern_parts)
# converts arg strings to the appropriate and then takes the action
seen_actions = set()
seen_non_default_actions = set()
def take_action(action, argument_strings, option_string=None):
seen_actions.add(action)
argument_values = self._get_values(action, argument_strings)
# error if this argument is not allowed with other previously
# seen arguments, assuming that actions that use the default
# value don't really count as "present"
if argument_values is not action.default:
seen_non_default_actions.add(action)
for conflict_action in action_conflicts.get(action, []):
if conflict_action in seen_non_default_actions:
msg = _('not allowed with argument %s')
action_name = _get_action_name(conflict_action)
raise ArgumentError(action, msg % action_name)
# take the action if we didn't receive a SUPPRESS value
# (e.g. from a default)
if argument_values is not SUPPRESS:
action(self, namespace, argument_values, option_string)
# function to convert arg_strings into an optional action
def consume_optional(start_index):
# get the optional identified at this index
option_tuple = option_string_indices[start_index]
action, option_string, explicit_arg = option_tuple
# identify additional optionals in the same arg string
# (e.g. -xyz is the same as -x -y -z if no args are required)
match_argument = self._match_argument
action_tuples = []
while True:
# if we found no optional action, skip it
if action is None:
extras.append(arg_strings[start_index])
return start_index + 1
# if there is an explicit argument, try to match the
# optional's string arguments to only this
if explicit_arg is not None:
arg_count = match_argument(action, 'A')
# if the action is a single-dash option and takes no
# arguments, try to parse more single-dash options out
# of the tail of the option string
chars = self.prefix_chars
if arg_count == 0 and option_string[1] not in chars:
action_tuples.append((action, [], option_string))
char = option_string[0]
option_string = char + explicit_arg[0]
new_explicit_arg = explicit_arg[1:] or None
optionals_map = self._option_string_actions
if option_string in optionals_map:
action = optionals_map[option_string]
explicit_arg = new_explicit_arg
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if the action expect exactly one argument, we've
# successfully matched the option; exit the loop
elif arg_count == 1:
stop = start_index + 1
args = [explicit_arg]
action_tuples.append((action, args, option_string))
break
# error if a double-dash option did not use the
# explicit argument
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if there is no explicit argument, try to match the
# optional's string arguments with the following strings
# if successful, exit the loop
else:
start = start_index + 1
selected_patterns = arg_strings_pattern[start:]
arg_count = match_argument(action, selected_patterns)
stop = start + arg_count
args = arg_strings[start:stop]
action_tuples.append((action, args, option_string))
break
# add the Optional to the list and return the index at which
# the Optional's string args stopped
assert action_tuples
for action, args, option_string in action_tuples:
take_action(action, args, option_string)
return stop
# the list of Positionals left to be parsed; this is modified
# by consume_positionals()
positionals = self._get_positional_actions()
# function to convert arg_strings into positional actions
def consume_positionals(start_index):
# match as many Positionals as possible
match_partial = self._match_arguments_partial
selected_pattern = arg_strings_pattern[start_index:]
arg_counts = match_partial(positionals, selected_pattern)
# slice off the appropriate arg strings for each Positional
# and add the Positional and its args to the list
for action, arg_count in zip(positionals, arg_counts):
args = arg_strings[start_index: start_index + arg_count]
start_index += arg_count
take_action(action, args)
# slice off the Positionals that we just parsed and return the
# index at which the Positionals' string args stopped
positionals[:] = positionals[len(arg_counts):]
return start_index
# consume Positionals and Optionals alternately, until we have
# passed the last option string
extras = []
start_index = 0
if option_string_indices:
max_option_string_index = max(option_string_indices)
else:
max_option_string_index = -1
while start_index <= max_option_string_index:
# consume any Positionals preceding the next option
next_option_string_index = start_index
while next_option_string_index <= max_option_string_index:
if next_option_string_index in option_string_indices:
break
next_option_string_index += 1
if start_index != next_option_string_index:
positionals_end_index = consume_positionals(start_index)
# only try to parse the next optional if we didn't consume
# the option string during the positionals parsing
if positionals_end_index > start_index:
start_index = positionals_end_index
continue
else:
start_index = positionals_end_index
# if we consumed all the positionals we could and we're not
# at the index of an option string, there were extra arguments
if start_index not in option_string_indices:
strings = arg_strings[start_index:next_option_string_index]
extras.extend(strings)
start_index = next_option_string_index
# consume the next optional and any arguments for it
start_index = consume_optional(start_index)
# consume any positionals following the last Optional
stop_index = consume_positionals(start_index)
# if we didn't consume all the argument strings, there were extras
extras.extend(arg_strings[stop_index:])
# make sure all required actions were present and also convert
# action defaults which were not given as arguments
required_actions = []
for action in self._actions:
if action not in seen_actions:
if action.required:
required_actions.append(_get_action_name(action))
else:
# Convert action default now instead of doing it before
# parsing arguments to avoid calling convert functions
# twice (which may fail) if the argument was given, but
# only if it was defined already in the namespace
if (action.default is not None and
isinstance(action.default, str) and
hasattr(namespace, action.dest) and
action.default is getattr(namespace, action.dest)):
setattr(namespace, action.dest,
self._get_value(action, action.default))
if required_actions:
self.error(_('the following arguments are required: %s') %
', '.join(required_actions))
# make sure all required groups had one option present
for group in self._mutually_exclusive_groups:
if group.required:
for action in group._group_actions:
if action in seen_non_default_actions:
break
# if no actions were used, report the error
else:
names = [_get_action_name(action)
for action in group._group_actions
if action.help is not SUPPRESS]
msg = _('one of the arguments %s is required')
self.error(msg % ' '.join(names))
# return the updated namespace and the extra arguments
return namespace, extras
def _read_args_from_files(self, arg_strings):
# expand arguments referencing files
new_arg_strings = []
for arg_string in arg_strings:
# for regular arguments, just add them back into the list
if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
new_arg_strings.append(arg_string)
# replace arguments referencing files with the file content
else:
try:
with open(arg_string[1:]) as args_file:
arg_strings = []
for arg_line in args_file.read().splitlines():
for arg in self.convert_arg_line_to_args(arg_line):
arg_strings.append(arg)
arg_strings = self._read_args_from_files(arg_strings)
new_arg_strings.extend(arg_strings)
except OSError:
err = _sys.exc_info()[1]
self.error(str(err))
# return the modified argument list
return new_arg_strings
def convert_arg_line_to_args(self, arg_line):
return [arg_line]
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
msg = nargs_errors.get(action.nargs)
if msg is None:
msg = ngettext('expected %s argument',
'expected %s arguments',
action.nargs) % action.nargs
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def _match_arguments_partial(self, actions, arg_strings_pattern):
# progressively shorten the actions list by slicing off the
# final actions until we find a match
result = []
for i in range(len(actions), 0, -1):
actions_slice = actions[:i]
pattern = ''.join([self._get_nargs_pattern(action)
for action in actions_slice])
match = _re.match(pattern, arg_strings_pattern)
if match is not None:
result.extend([len(string) for string in match.groups()])
break
# return the list of arg string counts
return result
def _parse_optional(self, arg_string):
# if it's an empty string, it was meant to be a positional
if not arg_string:
return None
# if it doesn't start with a prefix, it was meant to be positional
if not arg_string[0] in self.prefix_chars:
return None
# if the option string is present in the parser, return the action
if arg_string in self._option_string_actions:
action = self._option_string_actions[arg_string]
return action, arg_string, None
# if it's just a single character, it was meant to be positional
if len(arg_string) == 1:
return None
# if the option string before the "=" is present, return the action
if '=' in arg_string:
option_string, explicit_arg = arg_string.split('=', 1)
if option_string in self._option_string_actions:
action = self._option_string_actions[option_string]
return action, option_string, explicit_arg
# search through all possible prefixes of the option string
# and all actions in the parser for possible interpretations
option_tuples = self._get_option_tuples(arg_string)
# if multiple actions match, the option string was ambiguous
if len(option_tuples) > 1:
options = ', '.join([option_string
for action, option_string, explicit_arg in option_tuples])
args = {'option': arg_string, 'matches': options}
msg = _('ambiguous option: %(option)s could match %(matches)s')
self.error(msg % args)
# if exactly one action matched, this segmentation is good,
# so return the parsed action
elif len(option_tuples) == 1:
option_tuple, = option_tuples
return option_tuple
# if it was not found as an option, but it looks like a negative
# number, it was meant to be positional
# unless there are negative-number-like options
if self._negative_number_matcher.match(arg_string):
if not self._has_negative_number_optionals:
return None
# if it contains a space, it was meant to be a positional
if ' ' in arg_string:
return None
# it was meant to be an optional but there is no such option
# in this parser (though it might be a valid option in a subparser)
return None, arg_string, None
def _get_option_tuples(self, option_string):
result = []
# option strings starting with two prefix characters are only
# split at the '='
chars = self.prefix_chars
if option_string[0] in chars and option_string[1] in chars:
if self.allow_abbrev:
if '=' in option_string:
option_prefix, explicit_arg = option_string.split('=', 1)
else:
option_prefix = option_string
explicit_arg = None
for option_string in self._option_string_actions:
if option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# single character options can be concatenated with their arguments
# but multiple character options always have to have their argument
# separate
elif option_string[0] in chars and option_string[1] not in chars:
option_prefix = option_string
explicit_arg = None
short_option_prefix = option_string[:2]
short_explicit_arg = option_string[2:]
for option_string in self._option_string_actions:
if option_string == short_option_prefix:
action = self._option_string_actions[option_string]
tup = action, option_string, short_explicit_arg
result.append(tup)
elif option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# shouldn't ever get here
else:
self.error(_('unexpected option string: %s') % option_string)
# return the collected option tuples
return result
def _get_nargs_pattern(self, action):
# in all examples below, we have to allow for '--' args
# which are represented as '-' in the pattern
nargs = action.nargs
# the default (None) is assumed to be a single argument
if nargs is None:
nargs_pattern = '(-*A-*)'
# allow zero or one arguments
elif nargs == OPTIONAL:
nargs_pattern = '(-*A?-*)'
# allow zero or more arguments
elif nargs == ZERO_OR_MORE:
nargs_pattern = '(-*[A-]*)'
# allow one or more arguments
elif nargs == ONE_OR_MORE:
nargs_pattern = '(-*A[A-]*)'
# allow any number of options or arguments
elif nargs == REMAINDER:
nargs_pattern = '([-AO]*)'
# allow one argument followed by any number of options or arguments
elif nargs == PARSER:
nargs_pattern = '(-*A[-AO]*)'
# suppress action, like nargs=0
elif nargs == SUPPRESS:
nargs_pattern = '(-*-*)'
# all others should be integers
else:
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
# if this is an optional action, -- is not allowed
if action.option_strings:
nargs_pattern = nargs_pattern.replace('-*', '')
nargs_pattern = nargs_pattern.replace('-', '')
# return the pattern
return nargs_pattern
# ========================
# Alt command line argument parsing, allowing free intermix
# ========================
def parse_intermixed_args(self, args=None, namespace=None):
args, argv = self.parse_known_intermixed_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
def parse_known_intermixed_args(self, args=None, namespace=None):
# returns a namespace and list of extras
#
# positional can be freely intermixed with optionals. optionals are
# first parsed with all positional arguments deactivated. The 'extras'
# are then parsed. If the parser definition is incompatible with the
# intermixed assumptions (e.g. use of REMAINDER, subparsers) a
# TypeError is raised.
#
# positionals are 'deactivated' by setting nargs and default to
# SUPPRESS. This blocks the addition of that positional to the
# namespace
positionals = self._get_positional_actions()
a = [action for action in positionals
if action.nargs in [PARSER, REMAINDER]]
if a:
raise TypeError('parse_intermixed_args: positional arg'
' with nargs=%s'%a[0].nargs)
if [action.dest for group in self._mutually_exclusive_groups
for action in group._group_actions if action in positionals]:
raise TypeError('parse_intermixed_args: positional in'
' mutuallyExclusiveGroup')
try:
save_usage = self.usage
try:
if self.usage is None:
# capture the full usage for use in error messages
self.usage = self.format_usage()[7:]
for action in positionals:
# deactivate positionals
action.save_nargs = action.nargs
# action.nargs = 0
action.nargs = SUPPRESS
action.save_default = action.default
action.default = SUPPRESS
namespace, remaining_args = self.parse_known_args(args,
namespace)
for action in positionals:
# remove the empty positional values from namespace
if (hasattr(namespace, action.dest)
and getattr(namespace, action.dest)==[]):
from warnings import warn
warn('Do not expect %s in %s' % (action.dest, namespace))
delattr(namespace, action.dest)
finally:
# restore nargs and usage before exiting
for action in positionals:
action.nargs = action.save_nargs
action.default = action.save_default
optionals = self._get_optional_actions()
try:
# parse positionals. optionals aren't normally required, but
# they could be, so make sure they aren't.
for action in optionals:
action.save_required = action.required
action.required = False
for group in self._mutually_exclusive_groups:
group.save_required = group.required
group.required = False
namespace, extras = self.parse_known_args(remaining_args,
namespace)
finally:
# restore parser values before exiting
for action in optionals:
action.required = action.save_required
for group in self._mutually_exclusive_groups:
group.required = group.save_required
finally:
self.usage = save_usage
return namespace, extras
# ========================
# Value conversion methods
# ========================
def _get_values(self, action, arg_strings):
# for everything but PARSER, REMAINDER args, strip out first '--'
if action.nargs not in [PARSER, REMAINDER]:
try:
arg_strings.remove('--')
except ValueError:
pass
# optional argument produces a default when not present
if not arg_strings and action.nargs == OPTIONAL:
if action.option_strings:
value = action.const
else:
value = action.default
if isinstance(value, str):
value = self._get_value(action, value)
self._check_value(action, value)
# when nargs='*' on a positional, if there were no command-line
# args, use the default if it is anything other than None
elif (not arg_strings and action.nargs == ZERO_OR_MORE and
not action.option_strings):
if action.default is not None:
value = action.default
else:
value = arg_strings
self._check_value(action, value)
# single argument or optional argument produces a single value
elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
arg_string, = arg_strings
value = self._get_value(action, arg_string)
self._check_value(action, value)
# REMAINDER arguments convert all values, checking none
elif action.nargs == REMAINDER:
value = [self._get_value(action, v) for v in arg_strings]
# PARSER arguments convert all values, but check only the first
elif action.nargs == PARSER:
value = [self._get_value(action, v) for v in arg_strings]
self._check_value(action, value[0])
# SUPPRESS argument does not put anything in the namespace
elif action.nargs == SUPPRESS:
value = SUPPRESS
# all other types of nargs produce a list
else:
value = [self._get_value(action, v) for v in arg_strings]
for v in value:
self._check_value(action, v)
# return the converted value
return value
def _get_value(self, action, arg_string):
type_func = self._registry_get('type', action.type, action.type)
if not callable(type_func):
msg = _('%r is not callable')
raise ArgumentError(action, msg % type_func)
# convert the value to the appropriate type
try:
result = type_func(arg_string)
# ArgumentTypeErrors indicate errors
except ArgumentTypeError:
name = getattr(action.type, '__name__', repr(action.type))
msg = str(_sys.exc_info()[1])
raise ArgumentError(action, msg)
# TypeErrors or ValueErrors also indicate errors
except (TypeError, ValueError):
name = getattr(action.type, '__name__', repr(action.type))
args = {'type': name, 'value': arg_string}
msg = _('invalid %(type)s value: %(value)r')
raise ArgumentError(action, msg % args)
# return the converted value
return result
def _check_value(self, action, value):
# converted value must be one of the choices (if specified)
if action.choices is not None and value not in action.choices:
args = {'value': value,
'choices': ', '.join(map(repr, action.choices))}
msg = _('invalid choice: %(value)r (choose from %(choices)s)')
raise ArgumentError(action, msg % args)
# =======================
# Help-formatting methods
# =======================
def format_usage(self):
formatter = self._get_formatter()
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
return formatter.format_help()
def format_help(self):
formatter = self._get_formatter()
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
# positionals, optionals and user-defined groups
for action_group in self._action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(self.epilog)
# determine help from format above
return formatter.format_help()
def _get_formatter(self):
return self.formatter_class(prog=self.prog)
# =====================
# Help-printing methods
# =====================
def print_usage(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_usage(), file)
def print_help(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_help(), file)
def _print_message(self, message, file=None):
if message:
if file is None:
file = _sys.stderr
file.write(message)
# ===============
# Exiting methods
# ===============
def exit(self, status=0, message=None):
if message:
self._print_message(message, _sys.stderr)
_sys.exit(status)
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(_sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
def parse_args():
parser = ArgumentParser(
description="""\
Benchmark script for recursive async tree workloads. It can be run as a standalone
script, in which case you can specify the microbenchmark scenario to run and whether
to print the results.
"""
)
parser.add_argument(
"-s",
"--scenario",
choices=["no_suspension", "suspense_all", "memoization", "cpu_io_mixed"],
default="no_suspension",
help="""\
Determines which microbenchmark scenario to run. Defaults to no_suspension. Options:
1) "no_suspension": No suspension in the async tree.
2) "suspense_all": Suspension (simulating IO) at all leaf nodes in the async tree.
3) "memoization": Simulated IO calls at all leaf nodes, but with memoization. Only
un-memoized IO calls will result in suspensions.
4) "cpu_io_mixed": A mix of CPU-bound workload and IO-bound workload (with
memoization) at the leaf nodes.
""",
)
parser.add_argument(
"-m",
"--memoizable-percentage",
type=int,
default=DEFAULT_MEMOIZABLE_PERCENTAGE,
help="""\
Sets the percentage (0-100) of the data that should be memoized, defaults to 90. For
example, at the default 90 percent, data 1-90 will be memoized and data 91-100 will not.
""",
)
parser.add_argument(
"-c",
"--cpu-probability",
type=float,
default=DEFAULT_CPU_PROBABILITY,
help="""\
Sets the probability (0-1) that a leaf node will execute a cpu-bound workload instead
of an io-bound workload. Defaults to 0.5. Only applies to the "cpu_io_mixed"
microbenchmark scenario.
""",
)
parser.add_argument(
"-p",
"--print",
action="store_true",
default=False,
help="Print the results (runtime and number of Tasks created).",
)
return parser.parse_args() | null |
185,951 | LOOPS = 50000
def pystones(loops=LOOPS):
Proc0(loops)
def run():
loops = LOOPS
pystones(loops) | null |
185,952 | from __future__ import annotations
import __static__
from __static__ import CheckedList, box, cast, cbool, clen, int64, inline
from typing import final
from enum import IntEnum
class Strength:
def __init__(self, strength: int64, name: str) -> None:
self.strength: int64 = strength
self.name: str = name
def next_weaker(self) -> Strength:
return STRENGTHS[self.strength]
class cbool(int):
pass
def stronger(s1: Strength, s2: Strength) -> cbool:
return s1.strength < s2.strength | null |
185,953 | from __future__ import annotations
import __static__
from __static__ import CheckedList, box, cast, cbool, clen, int64, inline
from typing import final
from enum import IntEnum
class Strength:
def __init__(self, strength: int64, name: str) -> None:
self.strength: int64 = strength
self.name: str = name
def next_weaker(self) -> Strength:
return STRENGTHS[self.strength]
class cbool(int):
pass
def weaker(s1: Strength, s2: Strength) -> cbool:
return s1.strength > s2.strength | null |
185,954 | from __future__ import annotations
import __static__
from __static__ import CheckedList, box, cast, cbool, clen, int64, inline
from typing import final
from enum import IntEnum
class Strength:
def __init__(self, strength: int64, name: str) -> None:
def next_weaker(self) -> Strength:
def weakest_of(s1: Strength, s2: Strength) -> Strength:
return s1 if s1.strength > s2.strength else s2 | null |
185,955 | from __future__ import annotations
import __static__
from __static__ import CheckedList, box, cast, cbool, clen, int64, inline
from typing import final
from enum import IntEnum
def chain_test(n: int64) -> None:
"""
This is the standard DeltaBlue benchmark. A long chain of equality
constraints is constructed with a stay constraint on one end. An
edit constraint is then added to the opposite end and the time is
measured for adding and removing this constraint, and extracting
and executing a constraint satisfaction plan. There are two cases.
In case 1, the added constraint is stronger than the stay
constraint and values must propagate down the entire length of the
chain. In case 2, the added constraint is weaker than the stay
constraint so it cannot be accomodated. The cost in this case is,
of course, very low. Typical situations lie somewhere between these
two extremes.
"""
planner = recreate_planner()
prev: Variable | None = None
first: Variable | None = None
last: Variable | None = None
# We need to go up to n inclusively.
i: int64 = 0
end: int64 = n + 1
while i < n + 1:
name = "v%s" % box(i)
v = Variable(name)
if prev is not None:
EqualityConstraint(prev, v, REQUIRED)
if i == 0:
first = v
if i == n:
last = v
prev = v
i = i + 1
first = cast(Variable, first)
last = cast(Variable, last)
StayConstraint(last, STRONG_DEFAULT)
edit = EditConstraint(first, PREFERRED)
edits: CheckedList[UrnaryConstraint] = []
edits.append(edit)
plan = planner.extract_plan_from_constraints(edits)
i = 0
while i < 100:
first.value = i
plan.execute()
if last.value != i:
print("Chain test failed.")
i = i + 1
def projection_test(n: int64) -> None:
"""
This test constructs a two sets of variables related to each
other by a simple linear transformation (scale and offset). The
time is measured to change a variable on either side of the
mapping and to change the scale and offset factors.
"""
planner = recreate_planner()
scale = Variable("scale", 10)
offset = Variable("offset", 1000)
src: Variable | None = None
dests: CheckedList[Variable] = []
i: int64 = 0
bi = box(i)
dst = Variable("dst%s" % bi, i)
while i < n:
bi = box(i)
src = Variable("src%s" % bi, i)
dst = Variable("dst%s" % bi, i)
dests.append(dst)
StayConstraint(src, NORMAL)
ScaleConstraint(src, scale, offset, dst, REQUIRED)
i = i + 1
src = cast(Variable, src)
change(src, 17)
if dst.value != 1170:
print("Projection 1 failed")
change(dst, 1050)
if src.value != 5:
print("Projection 2 failed")
change(scale, 5)
i = 0
while i < n - 1:
if dests[i].value != (i * 5 + 1000):
print("Projection 3 failed")
i = i + 1
change(offset, 2000)
i = 0
while i < n - 1:
if dests[i].value != (i * 5 + 2000):
print("Projection 4 failed")
i = i + 1
class int64(int):
pass
def delta_blue(n: int64) -> None:
chain_test(n)
projection_test(n) | null |
185,956 | from __future__ import annotations
import __static__
from __static__ import cast, cbool, int64, box, inline
from typing import Final, Optional, List
from typing import Optional
class TaskState(object):
def __init__(self) -> None:
self.packet_pending: cbool = True
self.task_waiting: cbool = False
self.task_holding: cbool = False
def packetPending(self) -> TaskState:
self.packet_pending = True
self.task_waiting = False
self.task_holding = False
return self
def waiting(self) -> TaskState:
self.packet_pending = False
self.task_waiting = True
self.task_holding = False
return self
def running(self) -> TaskState:
self.packet_pending = False
self.task_waiting = False
self.task_holding = False
return self
def waitingWithPacket(self) -> TaskState:
self.packet_pending = True
self.task_waiting = True
self.task_holding = False
return self
def isPacketPending(self) -> cbool:
return self.packet_pending
def isTaskWaiting(self) -> cbool:
return self.task_waiting
def isTaskHolding(self) -> cbool:
return self.task_holding
def isTaskHoldingOrWaiting(self) -> cbool:
return self.task_holding or (not self.packet_pending and self.task_waiting)
def isWaitingWithPacket(self) -> cbool:
return self.packet_pending and self.task_waiting and not self.task_holding
tracing = False
def trace(a):
global layout
layout -= 1
if layout <= 0:
print()
layout = 50
print(a, end="")
taskWorkArea: TaskWorkArea = TaskWorkArea()
class Task(TaskState):
def __init__(
self,
i: int64,
p: int64,
w: Optional[Packet],
initialState: TaskState,
r: TaskRec,
) -> None:
wa: TaskWorkArea = taskWorkArea
self.link: Optional[Task] = wa.taskList
self.ident: int64 = i
self.priority: int64 = p
self.input: Optional[Packet] = w
self.packet_pending = initialState.isPacketPending()
self.task_waiting = initialState.isTaskWaiting()
self.task_holding = initialState.isTaskHolding()
self.handle = r
wa.taskList = self
wa.taskTab[i] = self
def fn(self, pkt: Optional[Packet], r: TaskRec) -> Optional[Task]:
raise NotImplementedError
def addPacket(self, p: Packet, old: Task) -> Task:
if self.input is None:
self.input = p
self.packet_pending = True
if self.priority > old.priority:
return self
else:
p.append_to(self.input)
return old
def runTask(self) -> Optional[Task]:
if TaskState.isWaitingWithPacket(self):
msg: Optional[Packet] = self.input
if msg is not None:
self.input = msg.link
if self.input is None:
self.running()
else:
self.packetPending()
else:
msg = None
return self.fn(msg, self.handle)
def waitTask(self) -> Task:
self.task_waiting = True
return self
def hold(self) -> Optional[Task]:
taskWorkArea.holdCount += 1
self.task_holding = True
return self.link
def release(self, i: int64) -> Task:
t: Task = Task.findtcb(self, i)
t.task_holding = False
if t.priority > self.priority:
return t
else:
return self
def qpkt(self, pkt: Packet) -> Task:
t: Task = Task.findtcb(self, pkt.ident)
taskWorkArea.qpktCount += 1
pkt.link = None
pkt.ident = self.ident
return t.addPacket(pkt, self)
def findtcb(self, id: int64) -> Task:
t = taskWorkArea.taskTab[id]
return cast(Task, t)
def box(o):
return o
def Optional(self, parameters):
"""Optional type.
Optional[X] is equivalent to Union[X, None].
"""
arg = _type_check(parameters, f"{self} requires a single type.")
return Union[arg, type(None)]
def schedule() -> None:
t: Optional[Task] = taskWorkArea.taskList
while t is not None:
if tracing:
print("tcb =", box(t.ident))
if TaskState.isTaskHoldingOrWaiting(t):
t = t.link
else:
if tracing:
trace(chr(ord("0") + box(t.ident)))
t = t.runTask() | null |
185,957 | from __future__ import annotations
import __static__
from typing import Callable, List
Callable = _CallableType(collections.abc.Callable, 2)
Callable.__doc__ = \
"""Callable type; Callable[[int], str] is a function of (int) -> str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type. The argument list
must be a list of types or ellipsis; the return type must be a single type.
There is no syntax to indicate optional or keyword arguments,
such function types are rarely used as callback types.
"""
List = _alias(list, 1, inst=False, name='List')
def fannkuch(n: int) -> int:
count: List[int] = list(range(1, n + 1))
max_flips: int = 0
m: int = n - 1
r: int = n
perm1: List[int] = list(range(n))
perm: List[int] = list(range(n))
perm1_ins: Callable[[int, int], None] = perm1.insert
perm1_pop: Callable[[int], int] = perm1.pop
while 1:
while r != 1:
count[r - 1] = r
r -= 1
if perm1[0] != 0 and perm1[m] != m:
perm = perm1[:]
flips_count: int = 0
k: int = perm[0]
while k:
perm[: k + 1] = perm[k::-1]
flips_count += 1
k = perm[0]
if flips_count > max_flips:
max_flips = flips_count
while r != n:
perm1_ins(r, perm1_pop(0))
count[r] -= 1
if count[r] > 0:
break
r += 1
else:
return max_flips | null |
185,958 | from __future__ import annotations
import __static__
from __static__ import cast
from typing import final
def chain_test(n: int) -> None:
def projection_test(n: int) -> None:
def delta_blue(n: int) -> None:
chain_test(n)
projection_test(n) | null |
185,966 | import sys
import os
import marshal
The provided code snippet includes necessary dependencies for implementing the `get_module_code` function. Write a Python function `def get_module_code(filename)` to solve the following problem:
Compile 'filename' and return the module code as a marshalled byte string.
Here is the function:
def get_module_code(filename):
"""Compile 'filename' and return the module code as a marshalled byte
string.
"""
with open(filename, 'r') as fp:
src = fp.read()
co = compile(src, 'none', 'exec')
co_bytes = marshal.dumps(co)
return co_bytes | Compile 'filename' and return the module code as a marshalled byte string. |
185,967 | import sys
import os
import marshal
SYMBOL = 'M___hello__'
The provided code snippet includes necessary dependencies for implementing the `gen_c_code` function. Write a Python function `def gen_c_code(fp, co_bytes)` to solve the following problem:
Generate C code for the module code in 'co_bytes', write it to 'fp'.
Here is the function:
def gen_c_code(fp, co_bytes):
"""Generate C code for the module code in 'co_bytes', write it to 'fp'.
"""
def write(*args, **kwargs):
print(*args, **kwargs, file=fp)
write('/* Generated with Tools/freeze/regen_frozen.py */')
write('static unsigned char %s[] = {' % SYMBOL, end='')
bytes_per_row = 13
for i, opcode in enumerate(co_bytes):
if (i % bytes_per_row) == 0:
# start a new row
write()
write(' ', end='')
write('%d,' % opcode, end='')
write()
write('};') | Generate C code for the module code in 'co_bytes', write it to 'fp'. |
185,995 | import locale
import sys
def check(data):
def optimize(data):
locale_alias = locale.locale_alias
locale.locale_alias = data.copy()
for k, v in data.items():
del locale.locale_alias[k]
if locale.normalize(k) != v:
locale.locale_alias[k] = v
newdata = locale.locale_alias
errors = check(data)
locale.locale_alias = locale_alias
if errors:
sys.exit(1)
return newdata | null |
186,009 | from __future__ import print_function
import gdb
import os
import locale
import sys
def pformat(object, indent=1, width=80, depth=None, *,
compact=False, sort_dicts=True, underscore_numbers=False):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth,
compact=compact, sort_dicts=sort_dicts,
underscore_numbers=underscore_numbers).pformat(object)
def stringify(val):
# TODO: repr() puts everything on one line; pformat can be nicer, but
# can lead to v.long results; this function isolates the choice
if True:
return repr(val)
else:
from pprint import pformat
return pformat(val) | null |
186,010 | from __future__ import print_function
import gdb
import os
import locale
import sys
def pretty_printer_lookup(gdbval):
type = gdbval.type.unqualified()
if type.code != gdb.TYPE_CODE_PTR:
return None
type = type.target().unqualified()
t = str(type)
if t in ("PyObject", "PyFrameObject", "PyUnicodeObject", "wrapperobject"):
return PyObjectPtrPrinter(gdbval)
def register (obj):
if obj is None:
obj = gdb
# Wire up the pretty-printer
obj.pretty_printers.append(pretty_printer_lookup) | null |
186,011 | from __future__ import print_function
import gdb
import os
import locale
import sys
class Frame(object):
'''
Wrapper for gdb.Frame, adding various methods
'''
def __init__(self, gdbframe):
self._gdbframe = gdbframe
def older(self):
older = self._gdbframe.older()
if older:
return Frame(older)
else:
return None
def newer(self):
newer = self._gdbframe.newer()
if newer:
return Frame(newer)
else:
return None
def select(self):
'''If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot'''
if not hasattr(self._gdbframe, 'select'):
print ('Unable to select frame: '
'this build of gdb does not expose a gdb.Frame.select method')
return False
self._gdbframe.select()
return True
def get_index(self):
'''Calculate index of frame, starting at 0 for the newest frame within
this thread'''
index = 0
# Go down until you reach the newest frame:
iter_frame = self
while iter_frame.newer():
index += 1
iter_frame = iter_frame.newer()
return index
# We divide frames into:
# - "python frames":
# - "bytecode frames" i.e. PyEval_EvalFrameEx
# - "other python frames": things that are of interest from a python
# POV, but aren't bytecode (e.g. GC, GIL)
# - everything else
def is_python_frame(self):
'''Is this a _PyEval_EvalFrameDefault frame, or some other important
frame? (see is_other_python_frame for what "important" means in this
context)'''
if self.is_evalframe():
return True
if self.is_other_python_frame():
return True
return False
def is_evalframe(self):
'''Is this a _PyEval_EvalFrameDefault frame?'''
if self._gdbframe.name() == EVALFRAME:
'''
I believe we also need to filter on the inline
struct frame_id.inline_depth, only regarding frames with
an inline depth of 0 as actually being this function
So we reject those with type gdb.INLINE_FRAME
'''
if self._gdbframe.type() == gdb.NORMAL_FRAME:
# We have a _PyEval_EvalFrameDefault frame:
return True
return False
def is_other_python_frame(self):
'''Is this frame worth displaying in python backtraces?
Examples:
- waiting on the GIL
- garbage-collecting
- within a CFunction
If it is, return a descriptive string
For other frames, return False
'''
if self.is_waiting_for_gil():
return 'Waiting for the GIL'
if self.is_gc_collect():
return 'Garbage-collecting'
# Detect invocations of PyCFunction instances:
frame = self._gdbframe
caller = frame.name()
if not caller:
return False
if (caller.startswith('cfunction_vectorcall_') or
caller == 'cfunction_call'):
arg_name = 'func'
# Within that frame:
# "func" is the local containing the PyObject* of the
# PyCFunctionObject instance
# "f" is the same value, but cast to (PyCFunctionObject*)
# "self" is the (PyObject*) of the 'self'
try:
# Use the prettyprinter for the func:
func = frame.read_var(arg_name)
return str(func)
except ValueError:
return ('PyCFunction invocation (unable to read %s: '
'missing debuginfos?)' % arg_name)
except RuntimeError:
return 'PyCFunction invocation (unable to read %s)' % arg_name
if caller == 'wrapper_call':
arg_name = 'wp'
try:
func = frame.read_var(arg_name)
return str(func)
except ValueError:
return ('<wrapper_call invocation (unable to read %s: '
'missing debuginfos?)>' % arg_name)
except RuntimeError:
return '<wrapper_call invocation (unable to read %s)>' % arg_name
# This frame isn't worth reporting:
return False
def is_waiting_for_gil(self):
'''Is this frame waiting on the GIL?'''
# This assumes the _POSIX_THREADS version of Python/ceval_gil.h:
name = self._gdbframe.name()
if name:
return (name == 'take_gil')
def is_gc_collect(self):
'''Is this frame gc_collect_main() within the garbage-collector?'''
return self._gdbframe.name() in ('collect', 'gc_collect_main')
def get_pyop(self):
try:
f = self._gdbframe.read_var('f')
frame = PyFrameObjectPtr.from_pyobject_ptr(f)
if not frame.is_optimized_out():
return frame
# gdb is unable to get the "f" argument of PyEval_EvalFrameEx()
# because it was "optimized out". Try to get "f" from the frame
# of the caller, PyEval_EvalCodeEx().
orig_frame = frame
caller = self._gdbframe.older()
if caller:
f = caller.read_var('f')
frame = PyFrameObjectPtr.from_pyobject_ptr(f)
if not frame.is_optimized_out():
return frame
return orig_frame
except ValueError:
return None
def get_selected_frame(cls):
_gdbframe = gdb.selected_frame()
if _gdbframe:
return Frame(_gdbframe)
return None
def get_selected_python_frame(cls):
'''Try to obtain the Frame for the python-related code in the selected
frame, or None'''
try:
frame = cls.get_selected_frame()
except gdb.error:
# No frame: Python didn't start yet
return None
while frame:
if frame.is_python_frame():
return frame
frame = frame.older()
# Not found:
return None
def get_selected_bytecode_frame(cls):
'''Try to obtain the Frame for the python bytecode interpreter in the
selected GDB frame, or None'''
frame = cls.get_selected_frame()
while frame:
if frame.is_evalframe():
return frame
frame = frame.older()
# Not found:
return None
def print_summary(self):
if self.is_evalframe():
pyop = self.get_pyop()
if pyop:
line = pyop.get_truncated_repr(MAX_OUTPUT_LEN)
write_unicode(sys.stdout, '#%i %s\n' % (self.get_index(), line))
if not pyop.is_optimized_out():
line = pyop.current_line()
if line is not None:
sys.stdout.write(' %s\n' % line.strip())
else:
sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index())
else:
info = self.is_other_python_frame()
if info:
sys.stdout.write('#%i %s\n' % (self.get_index(), info))
else:
sys.stdout.write('#%i\n' % self.get_index())
def print_traceback(self):
if self.is_evalframe():
pyop = self.get_pyop()
if pyop:
pyop.print_traceback()
if not pyop.is_optimized_out():
line = pyop.current_line()
if line is not None:
sys.stdout.write(' %s\n' % line.strip())
else:
sys.stdout.write(' (unable to read python frame information)\n')
else:
info = self.is_other_python_frame()
if info:
sys.stdout.write(' %s\n' % info)
else:
sys.stdout.write(' (not a python frame)\n')
The provided code snippet includes necessary dependencies for implementing the `move_in_stack` function. Write a Python function `def move_in_stack(move_up)` to solve the following problem:
Move up or down the stack (for the py-up/py-down command)
Here is the function:
def move_in_stack(move_up):
'''Move up or down the stack (for the py-up/py-down command)'''
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
while frame:
if move_up:
iter_frame = frame.older()
else:
iter_frame = frame.newer()
if not iter_frame:
break
if iter_frame.is_python_frame():
# Result:
if iter_frame.select():
iter_frame.print_summary()
return
frame = iter_frame
if move_up:
print('Unable to find an older python frame')
else:
print('Unable to find a newer python frame') | Move up or down the stack (for the py-up/py-down command) |
186,012 | from __future__ import print_function
import gdb
import os
import locale
import sys
class PyTraceBreakpoint(gdb.Breakpoint):
def __init__(self):
super().__init__('gdb_tracefunc')
self.silent = True
def stop(self):
global _PyRunningTargetFrameAddress
global _PyRunningTargetFrameBackAddress
if _PyRunningTargetFrameAddress is not None:
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return True
pyop_frame = frame.get_pyop()
if not pyop_frame:
print(UNABLE_READ_INFO_PYTHON_FRAME)
return True
if (pyop_frame.as_address() != _PyRunningTargetFrameAddress
and pyop_frame.as_address() != _PyRunningTargetFrameBackAddress):
return False
_PyRunningTargetFrameBackAddress = None
_PyRunningTargetFrameAddress = None
#gdb.execute("call gdb_disable_trace(0, 0)")
self.enabled = False
PyList.invoke(None, "", False)
return True
PY_TRACE_POINT = None
def enable_breakpoint():
global PY_TRACE_POINT
if PY_TRACE_POINT is None:
PY_TRACE_POINT = PyTraceBreakpoint()
else:
PY_TRACE_POINT.enabled = True | null |
186,013 | import abc
import argparse
import collections
import io
import locale
import re
import shlex
import struct
import lldb
import six
def write_string(result, string, end=u'\n', encoding=locale.getpreferredencoding()):
"""Helper function for writing to SBCommandReturnObject that expects bytes on py2 and str on py3."""
if six.PY3:
result.write(string + end)
else:
result.write((string + end).encode(encoding=encoding))
The provided code snippet includes necessary dependencies for implementing the `print_frame_summary` function. Write a Python function `def print_frame_summary(result, frame)` to solve the following problem:
Print a short summary of a given Python frame: module and the line being executed.
Here is the function:
def print_frame_summary(result, frame):
"""Print a short summary of a given Python frame: module and the line being executed."""
write_string(result, u' ' + frame.to_pythonlike_string())
write_string(result, u' ' + frame.line.strip()) | Print a short summary of a given Python frame: module and the line being executed. |
186,014 | import abc
import argparse
import collections
import io
import locale
import re
import shlex
import struct
import lldb
import six
class PyFrameObject(PyObject):
typename = 'frame'
def __init__(self, lldb_value):
super(PyFrameObject, self).__init__(lldb_value)
self.co = PyCodeObject(self.child('f_code'))
def _from_frame_no_walk(cls, frame):
"""
Extract PyFrameObject object from current frame w/o stack walking.
"""
f = frame.variables['f']
if f and is_available(f[0]):
return cls(f[0])
else:
return None
def _from_frame_heuristic(cls, frame):
"""Extract PyFrameObject object from current frame using heuristic.
When CPython is compiled with aggressive optimizations, the location
of PyFrameObject variable f can sometimes be lost. Usually, we still
can figure it out by analyzing the state of CPU registers. This is not
very reliable, because we basically try to cast the value stored in
each register to (PyFrameObject*) and see if it produces a valid
PyObject object.
This becomes especially ugly when there is more than one PyFrameObject*
in CPU registers at the same time. In this case we are looking for the
frame with a parent, that we have not seen yet.
"""
target = frame.GetThread().GetProcess().GetTarget()
object_type = target.FindFirstType('PyObject')
# in CPython >= 3.9, PyFrameObject is an opaque type that does not
# expose its own structure. Unfortunately, we can't make any function
# calls here, so we resort to using the internal counterpart instead
public_frame_type = target.FindFirstType('PyFrameObject')
internal_frame_type = target.FindFirstType('_frame')
frame_type = (public_frame_type
if public_frame_type.members
else internal_frame_type)
found_frames = []
for register in general_purpose_registers(frame):
sbvalue = frame.register[register]
# ignore unavailable registers or null pointers
if not sbvalue or not sbvalue.unsigned:
continue
# and things that are not valid PyFrameObjects
pyobject = PyObject(sbvalue.Cast(object_type.GetPointerType()))
if pyobject.typename != PyFrameObject.typename:
continue
found_frames.append(PyFrameObject(sbvalue.Cast(frame_type.GetPointerType())))
# sometimes the parent _PyEval_EvalFrameDefault frame contains two
# PyFrameObject's - the one that is currently being executed and its
# parent, so we need to filter out the latter
found_frames_addresses = [frame.lldb_value.unsigned for frame in found_frames]
eligible_frames = [
frame for frame in found_frames
if frame.child('f_back').unsigned not in found_frames_addresses
]
if eligible_frames:
return eligible_frames[0]
def from_frame(cls, frame):
if frame is None:
return None
# check if we are in a potential function
if frame.name not in ('_PyEval_EvalFrameDefault', 'PyEval_EvalFrameEx'):
return None
# try different methods of getting PyFrameObject before giving up
methods = (
# normally, we just need to check the location of `f` variable in the current frame
cls._from_frame_no_walk,
# but sometimes, it's only available in the parent frame
lambda frame: frame.parent and cls._from_frame_no_walk(frame.parent),
# when aggressive optimizations are enabled, we need to check the CPU registers
cls._from_frame_heuristic,
# and the registers in the parent frame as well
lambda frame: frame.parent and cls._from_frame_heuristic(frame.parent),
)
for method in methods:
result = method(frame)
if result is not None:
return result
def get_pystack(cls, thread):
pyframes = []
frame = thread.GetSelectedFrame()
while frame:
pyframe = cls.from_frame(frame)
if pyframe is not None:
pyframes.append(pyframe)
frame = frame.get_parent_frame()
return pyframes
def filename(self):
return PyObject.from_value(self.co.child('co_filename')).value
def line_number(self):
f_lineno = self.child('f_lineno').signed
f_lasti = self.child('f_lasti').signed
return self.co.addr2line(f_lineno, f_lasti)
def line(self):
try:
encoding = source_file_encoding(self.filename)
return source_file_lines(self.filename,
self.line_number, self.line_number + 1,
encoding=encoding)[0]
except (IOError, IndexError):
return u'<source code is not available>'
def to_pythonlike_string(self):
lineno = self.line_number
co_name = PyObject.from_value(self.co.child('co_name')).value
return u'File "{filename}", line {lineno}, in {co_name}'.format(
filename=self.filename,
co_name=co_name,
lineno=lineno,
)
class Direction(object):
DOWN = -1
UP = 1
def move_python_frame(debugger, direction):
"""Select the next Python frame up or down the call stack."""
target = debugger.GetSelectedTarget()
thread = target.GetProcess().GetSelectedThread()
current_frame = thread.GetSelectedFrame()
if direction == Direction.UP:
index_range = range(current_frame.idx + 1, thread.num_frames)
else:
index_range = reversed(range(0, current_frame.idx))
for index in index_range:
python_frame = PyFrameObject.from_frame(thread.GetFrameAtIndex(index))
if python_frame is not None:
thread.SetSelectedFrame(index)
return python_frame
The provided code snippet includes necessary dependencies for implementing the `select_closest_python_frame` function. Write a Python function `def select_closest_python_frame(debugger, direction=Direction.UP)` to solve the following problem:
Select and return the closest Python frame (or do nothing if the current frame is a Python frame).
Here is the function:
def select_closest_python_frame(debugger, direction=Direction.UP):
"""Select and return the closest Python frame (or do nothing if the current frame is a Python frame)."""
target = debugger.GetSelectedTarget()
thread = target.GetProcess().GetSelectedThread()
frame = thread.GetSelectedFrame()
python_frame = PyFrameObject.from_frame(frame)
if python_frame is None:
return move_python_frame(debugger, direction)
return python_frame | Select and return the closest Python frame (or do nothing if the current frame is a Python frame). |
186,015 | import abc
import argparse
import collections
import io
import locale
import re
import shlex
import struct
import lldb
import six
The provided code snippet includes necessary dependencies for implementing the `is_available` function. Write a Python function `def is_available(lldb_value)` to solve the following problem:
Helper function to check if a variable is available and was not optimized out.
Here is the function:
def is_available(lldb_value):
"""
Helper function to check if a variable is available and was not optimized out.
"""
return lldb_value.error.Success() | Helper function to check if a variable is available and was not optimized out. |
186,016 | import abc
import argparse
import collections
import io
import locale
import re
import shlex
import struct
import lldb
import six
ENCODING_RE = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)')
The provided code snippet includes necessary dependencies for implementing the `source_file_encoding` function. Write a Python function `def source_file_encoding(filename)` to solve the following problem:
Determine the text encoding of a Python source file.
Here is the function:
def source_file_encoding(filename):
"""Determine the text encoding of a Python source file."""
with io.open(filename, 'rt', encoding='latin-1') as f:
# according to PEP-263 the magic comment must be placed on one of the first two lines
for _ in range(2):
line = f.readline()
match = re.match(ENCODING_RE, line)
if match:
return match.group(1)
# if not defined explicitly, assume it's UTF-8 (which is ASCII-compatible)
return 'utf-8' | Determine the text encoding of a Python source file. |
186,017 | import abc
import argparse
import collections
import io
import locale
import re
import shlex
import struct
import lldb
import six
The provided code snippet includes necessary dependencies for implementing the `source_file_lines` function. Write a Python function `def source_file_lines(filename, start, end, encoding='utf-8')` to solve the following problem:
Return the contents of [start; end) lines of the source file. 1 based indexing is used for convenience.
Here is the function:
def source_file_lines(filename, start, end, encoding='utf-8'):
"""Return the contents of [start; end) lines of the source file.
1 based indexing is used for convenience.
"""
lines = []
with io.open(filename, 'rt', encoding=encoding) as f:
for (line_num, line) in enumerate(f, 1):
if start <= line_num < end:
lines.append(line)
elif line_num > end:
break
return lines | Return the contents of [start; end) lines of the source file. 1 based indexing is used for convenience. |
186,018 | import abc
import argparse
import collections
import io
import locale
import re
import shlex
import struct
import lldb
import six
The provided code snippet includes necessary dependencies for implementing the `general_purpose_registers` function. Write a Python function `def general_purpose_registers(frame)` to solve the following problem:
Return a list of general purpose register names.
Here is the function:
def general_purpose_registers(frame):
"""Return a list of general purpose register names."""
REGISTER_CLASS = 'General Purpose Registers'
try:
gpr = next(reg_class for reg_class in frame.registers
if reg_class.name == REGISTER_CLASS)
return [reg.name for reg in gpr.children]
except StopIteration:
return [] | Return a list of general purpose register names. |
186,019 | import abc
import argparse
import collections
import io
import locale
import re
import shlex
import struct
import lldb
import six
def register_commands(debugger):
for cls in Command.__subclasses__():
debugger.HandleCommand(
'command script add -c cpython_lldb.{cls} {command}'.format(
cls=cls.__name__,
command=cls.command,
)
)
def register_summaries(debugger):
# normally, PyObject instances are referenced via a generic PyObject* pointer.
# pretty_printer() will read the value of ob_type->tp_name to determine the
# concrete type of the object being inspected
debugger.HandleCommand(
'type summary add -F cpython_lldb.pretty_printer PyObject'
)
# at the same time, built-in types can be referenced directly via pointers to
# CPython structs. In this case, we also want to be able to print type summaries
cpython_structs = {
cls.cpython_struct: cls
for cls in PyObject.__subclasses__()
if hasattr(cls, 'cpython_struct')
}
for type_ in cpython_structs:
debugger.HandleCommand(
'type summary add -F cpython_lldb.pretty_printer {}'.format(type_)
)
# cache the result of the lookup, so that we do not need to repeat that at runtime
pretty_printer._cpython_structs = cpython_structs
def __lldb_init_module(debugger, internal_dict):
register_summaries(debugger)
register_commands(debugger) | null |
186,039 | from test.test_importlib import util
import decimal
import imp
import importlib
import importlib.machinery
import json
import os
import py_compile
import sys
import tabnanny
import timeit
def bench(name, cleanup=lambda: None, *, seconds=1, repeat=3):
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--builtin', dest='builtin', action='store_true',
default=False, help="use the built-in __import__")
parser.add_argument('-r', '--read', dest='source_file',
type=argparse.FileType('r'),
help='file to read benchmark data from to compare '
'against')
parser.add_argument('-w', '--write', dest='dest_file',
type=argparse.FileType('w'),
help='file to write benchmark data to')
parser.add_argument('--benchmark', dest='benchmark',
help='specific benchmark to run')
options = parser.parse_args()
import_ = __import__
if not options.builtin:
import_ = importlib.__import__
main(import_, options)
def _writing_bytecode(module):
name = module.__name__
def writing_bytecode_benchmark(seconds, repeat):
"""Source writing bytecode: {}"""
assert not sys.dont_write_bytecode
def cleanup():
sys.modules.pop(name)
os.unlink(imp.cache_from_source(module.__file__))
yield from bench(name, cleanup, repeat=repeat, seconds=seconds)
writing_bytecode_benchmark.__doc__ = (
writing_bytecode_benchmark.__doc__.format(name))
return writing_bytecode_benchmark | null |
186,043 | import re, os, marshal, codecs
def readmap(filename):
with open(filename) as f:
lines = f.readlines()
enc2uni = {}
identity = []
unmapped = list(range(256))
# UTC mapping tables per convention don't include the identity
# mappings for code points 0x00 - 0x1F and 0x7F, unless these are
# explicitly mapped to different characters or undefined
for i in list(range(32)) + [127]:
identity.append(i)
unmapped.remove(i)
enc2uni[i] = (i, 'CONTROL CHARACTER')
for line in lines:
line = line.strip()
if not line or line[0] == '#':
continue
m = mapRE.match(line)
if not m:
#print '* not matched: %s' % repr(line)
continue
enc,uni,comment = m.groups()
enc = parsecodes(enc)
uni = parsecodes(uni)
if comment is None:
comment = ''
else:
comment = comment[1:].strip()
if not isinstance(enc, tuple) and enc < 256:
if enc in unmapped:
unmapped.remove(enc)
if enc == uni:
identity.append(enc)
enc2uni[enc] = (uni,comment)
else:
enc2uni[enc] = (uni,comment)
# If there are more identity-mapped entries than unmapped entries,
# it pays to generate an identity dictionary first, and add explicit
# mappings to None for the rest
if len(identity) >= len(unmapped):
for enc in unmapped:
enc2uni[enc] = (MISSING_CODE, "")
enc2uni['IDENTITY'] = 256
return enc2uni
def pymap(name,map,pyfile,encodingname,comments=1):
code = codegen(name,map,encodingname,comments)
with open(pyfile,'w') as f:
f.write(code)
def marshalmap(name,map,marshalfile):
d = {}
for e,(u,c) in map.items():
d[e] = (u,c)
with open(marshalfile,'wb') as f:
marshal.dump(d,f)
def convertdir(dir, dirprefix='', nameprefix='', comments=1):
mapnames = os.listdir(dir)
for mapname in mapnames:
mappathname = os.path.join(dir, mapname)
if not os.path.isfile(mappathname):
continue
name = os.path.split(mapname)[1]
name = name.replace('-','_')
name = name.split('.')[0]
name = name.lower()
name = nameprefix + name
codefile = name + '.py'
marshalfile = name + '.mapping'
print('converting %s to %s and %s' % (mapname,
dirprefix + codefile,
dirprefix + marshalfile))
try:
map = readmap(os.path.join(dir,mapname))
if not map:
print('* map is empty; skipping')
else:
pymap(mappathname, map, dirprefix + codefile,name,comments)
marshalmap(mappathname, map, dirprefix + marshalfile)
except ValueError as why:
print('* conversion failed: %s' % why)
raise | null |
186,061 | import re
from unicodedata import ucd_3_2_0 as unicodedata
def map_table_b3(code):
r = b3_exceptions.get(ord(code))
if r is not None: return r
return code.lower()
def map_table_b2(a):
al = map_table_b3(a)
b = unicodedata.normalize("NFKC", al)
bl = "".join([map_table_b3(ch) for ch in b])
c = unicodedata.normalize("NFKC", bl)
if b != c:
return c
else:
return al | null |
186,153 | import timeit
import itertools
import operator
import re
import sys
import datetime
import optparse
_RANGE_10 = list(range(10))
def _get_dna(STR):
def split_multichar_sep_dna(STR):
s = _get_dna(STR)
s_split = s.split
pat = STR("ACTAT")
for x in _RANGE_10:
s_split(pat) | null |
186,159 | import timeit
import itertools
import operator
import re
import sys
import datetime
import optparse
_RANGE_10 = list(range(10))
def _get_2000_lines(STR):
def count_newlines(STR):
s = _get_2000_lines(STR)
s_count = s.count
nl = STR("\n")
for x in _RANGE_10:
s_count(nl) | null |
186,179 | import timeit
import itertools
import operator
import re
import sys
import datetime
import optparse
_RANGE_10 = list(range(10))
def _get_2000_lines(STR):
if STR is UNICODE:
return _text_with_2000_lines_unicode
if STR is BYTES:
return _text_with_2000_lines_bytes
raise AssertionError
def replace_single_character_big_re(STR):
s = _get_2000_lines(STR)
pat = re.compile(STR("\n"))
to_str = STR(" ")
pat_sub = pat.sub
for x in _RANGE_10:
pat_sub(to_str, s) | null |
186,190 | import sys
import argparse
from pprint import pprint
def pprint(object, stream=None, indent=1, width=80, depth=None, *,
compact=False, sort_dicts=True, underscore_numbers=False):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth,
compact=compact, sort_dicts=sort_dicts,
underscore_numbers=underscore_numbers)
printer.pprint(object)
def _dump_state(args):
print(sys.version)
for name in args.attributes:
print("sys.{}:".format(name))
pprint(getattr(sys, name)) | null |
186,194 | import sys, os, difflib, argparse
from datetime import datetime, timezone
class datetime(date):
def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
microsecond=0, tzinfo=None, *, fold=0):
def hour(self):
def minute(self):
def second(self):
def microsecond(self):
def tzinfo(self):
def fold(self):
def _fromtimestamp(cls, t, utc, tz):
def fromtimestamp(cls, t, tz=None):
def utcfromtimestamp(cls, t):
def now(cls, tz=None):
def utcnow(cls):
def combine(cls, date, time, tzinfo=True):
def fromisoformat(cls, date_string):
def timetuple(self):
def _mktime(self):
def local(u):
def timestamp(self):
def utctimetuple(self):
def date(self):
def time(self):
def timetz(self):
def replace(self, year=None, month=None, day=None, hour=None,
minute=None, second=None, microsecond=None, tzinfo=True,
*, fold=None):
def _local_timezone(self):
def astimezone(self, tz=None):
def ctime(self):
def isoformat(self, sep='T', timespec='auto'):
def __repr__(self):
def __str__(self):
def strptime(cls, date_string, format):
def utcoffset(self):
def tzname(self):
def dst(self):
def __eq__(self, other):
def __le__(self, other):
def __lt__(self, other):
def __ge__(self, other):
def __gt__(self, other):
def _cmp(self, other, allow_mixed=False):
def __add__(self, other):
def __sub__(self, other):
def __hash__(self):
def _getstate(self, protocol=3):
def __setstate(self, string, tzinfo):
def __reduce_ex__(self, protocol):
def __reduce__(self):
datetime.min = datetime(1, 1, 1)
datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
datetime.resolution = timedelta(microseconds=1)
class timezone(tzinfo):
def __new__(cls, offset, name=_Omitted):
def _create(cls, offset, name=None):
def __getinitargs__(self):
def __eq__(self, other):
def __hash__(self):
def __repr__(self):
def __str__(self):
def utcoffset(self, dt):
def tzname(self, dt):
def dst(self, dt):
def fromutc(self, dt):
def _name_from_offset(delta):
timezone.utc = timezone._create(timedelta(0))
timezone.min = timezone._create(-timedelta(hours=23, minutes=59))
timezone.max = timezone._create(timedelta(hours=23, minutes=59))
def file_mtime(path):
t = datetime.fromtimestamp(os.stat(path).st_mtime,
timezone.utc)
return t.astimezone().isoformat() | null |
186,195 | import difflib
import re
import shlex
import subprocess
from typing import Dict, List, Union
def Union(self, parameters):
"""Union type; Union[X, Y] means either X or Y.
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
"""
if parameters == ():
raise TypeError("Cannot take a Union of no types.")
if not isinstance(parameters, tuple):
parameters = (parameters,)
msg = "Union[arg, ...]: each arg must be a type."
parameters = tuple(_type_check(p, msg) for p in parameters)
parameters = _remove_dups_flatten(parameters)
if len(parameters) == 1:
return parameters[0]
if len(parameters) == 2 and type(None) in parameters:
return _UnionGenericAlias(self, parameters, name="Optional")
return _UnionGenericAlias(self, parameters)
List = _alias(list, 1, inst=False, name='List')
The provided code snippet includes necessary dependencies for implementing the `_run` function. Write a Python function `def _run(cmd: Union[str, List[str]]) -> List[str]` to solve the following problem:
Run a 'cmd', returning stdout as a list of strings.
Here is the function:
def _run(cmd: Union[str, List[str]]) -> List[str]:
"""Run a 'cmd', returning stdout as a list of strings."""
cmd_list = shlex.split(cmd) if type(cmd) == str else cmd
result = subprocess.run(cmd_list, capture_output=True)
return result.stdout.decode('utf-8').split("\n") | Run a 'cmd', returning stdout as a list of strings. |
186,196 | import difflib
import re
import shlex
import subprocess
from typing import Dict, List, Union
def _split_diff_to_context_free_file_diffs(
diff: List[str], src: str) -> Dict[str, List[str]]:
"""Take a noisy diff-like input covering many files and return a purified
map of file name -> hunk changes. Strips out all line info, metadata, and
context along the way. E.g. for input:
Summary
diff --git a/dir/fileXYZ b/dir/fileXYZ
--- a/dir/fileXYZ
+++ b/dir/fileXYZ
context
-badline
+goodline
context
Produce:
{"fileXYZ": [
"@@",
"-badline",
"+goodline",
]}
"""
res: Dict[str, List[str]] = {}
current_diff_file_lines: List[str] = []
line_n = 0
while line_n < len(diff):
line = diff[line_n]
m = re.match(r'^--- a/(.*)$', line)
if m:
current_diff_file_lines = []
filename = m.group(1)
res[filename] = current_diff_file_lines
if line_n > len(diff) - 1:
raise Exception(f'{src}:{line_n} - missing +++ after ---')
line_n += 1
line = diff[line_n]
if not re.match(rf'^\+\+\+ b/{filename}', line):
raise Exception(f'{src}:{line_n} - invalid +++ line after ---')
else:
if line:
if line[:2] == "@@":
# Some tools add inferred context to their @@ lines e.g. the
# function the hunk appears in and other tools do not. As we
# don't use line info anyway, simply strip all context.
current_diff_file_lines.append("@@")
elif line[0] in ['+', '-']:
current_diff_file_lines.append(diff[line_n])
line_n += 1
return res
def _do_diff_2o(diff_a: str, src_a: str, diff_b: str, src_b: str) -> None:
file_diffs_a = _split_diff_to_context_free_file_diffs(diff_a, src_a)
file_diffs_b = _split_diff_to_context_free_file_diffs(diff_b, src_b)
modifiedfiles = set(file_diffs_a) & set(file_diffs_b)
for f in modifiedfiles:
diff_lines = difflib.unified_diff(file_diffs_a[f], file_diffs_b[f], n=0)
# Turn from generator to list and skip first --- and +++ lines
diff_lines = list(diff_lines)[2:]
i = 0
changelines = []
while i < len(diff_lines):
line = diff_lines[i]
i += 1
if line[:2] == "++":
changelines.append("+" + line[2:])
elif line[:2] == "+-":
changelines.append("-" + line[2:])
elif line[:2] == "-+":
changelines.append("-" + line[2:])
elif line[:2] == "--":
changelines.append("+" + line[2:])
elif line[:2] == "@@" or line[1:3] == "@@":
if len(changelines) < 1 or changelines[-1] != "...\n":
changelines.append("...\n")
else:
changelines.append(line)
if len(changelines):
print(f"Changed: {f}")
for line in changelines:
print(f"| {line.strip()}")
wholefilechanges = set(file_diffs_a) ^ set(file_diffs_b)
for f in wholefilechanges:
print(f"Added/removed: {f}") | null |
186,199 | import sys
import itertools
class RecursiveBlowup4:
def __add__(self, x):
return x + self
def test_add():
return RecursiveBlowup4() + RecursiveBlowup4() | null |
186,207 | import argparse
import dis
import types
from typing import Dict, List, Tuple
Histogram = Dict[str, int]
def count_bytecode(func: types.FunctionType, histo: Histogram) -> None:
"""Return a distribution of bytecode in func"""
for instr in dis.get_instructions(func):
if instr.opname in histo:
histo[instr.opname] += 1
else:
histo[instr.opname] = 1
The provided code snippet includes necessary dependencies for implementing the `summarize` function. Write a Python function `def summarize(obj: object, histo: Histogram) -> None` to solve the following problem:
Compute the bytecode histogram of all functions reachable from obj
Here is the function:
def summarize(obj: object, histo: Histogram) -> None:
"""Compute the bytecode histogram of all functions reachable from obj"""
if isinstance(obj, types.FunctionType):
count_bytecode(obj, histo)
elif isinstance(obj, type):
for child in obj.__dict__.values():
summarize(child, histo) | Compute the bytecode histogram of all functions reachable from obj |
186,208 | import argparse
import dis
import types
from typing import Dict, List, Tuple
CountAssocs = List[Tuple[str, int]]
Histogram = Dict[str, int]
def sort_alpha(histo: Histogram) -> CountAssocs:
ordered = sorted(histo.items(), key=lambda p: p[0])
return list(ordered) | null |
186,209 | import argparse
import dis
import types
from typing import Dict, List, Tuple
CountAssocs = List[Tuple[str, int]]
Histogram = Dict[str, int]
def sort_count(histo: Histogram) -> CountAssocs:
ordered = sorted(histo.items(), key=lambda p: p[1], reverse=True)
return list(ordered) | null |
186,217 | NT_OFFSET = 256
def load_tokens(path):
def update_file(file, content):
token_h_template = """\
/* Auto-generated by Tools/scripts/generate_token.py */
/* Token types */
#ifndef Py_LIMITED_API
#ifndef Py_TOKEN_H
#define Py_TOKEN_H
#ifdef __cplusplus
extern "C" {
#endif
#undef TILDE /* Prevent clash of our definition with system macro. Ex AIX, ioctl.h */
%s\
#define N_TOKENS %d
#define NT_OFFSET %d
/* Special definitions for cooperation with parser */
#define ISTERMINAL(x) ((x) < NT_OFFSET)
#define ISNONTERMINAL(x) ((x) >= NT_OFFSET)
#define ISEOF(x) ((x) == ENDMARKER)
#define ISWHITESPACE(x) ((x) == ENDMARKER || \\
(x) == NEWLINE || \\
(x) == INDENT || \\
(x) == DEDENT)
PyAPI_DATA(const char * const) _PyParser_TokenNames[]; /* Token names */
PyAPI_FUNC(int) PyToken_OneChar(int);
PyAPI_FUNC(int) PyToken_TwoChars(int, int);
PyAPI_FUNC(int) PyToken_ThreeChars(int, int, int);
#ifdef __cplusplus
}
#endif
#endif /* !Py_TOKEN_H */
#endif /* Py_LIMITED_API */
"""
def make_h(infile, outfile='Include/token.h'):
tok_names, ERRORTOKEN, string_to_tok = load_tokens(infile)
defines = []
for value, name in enumerate(tok_names[:ERRORTOKEN + 1]):
defines.append("#define %-15s %d\n" % (name, value))
if update_file(outfile, token_h_template % (
''.join(defines),
len(tok_names),
NT_OFFSET
)):
print("%s regenerated from %s" % (outfile, infile)) | null |
186,218 | def load_tokens(path):
def update_file(file, content):
token_c_template = """\
/* Auto-generated by Tools/scripts/generate_token.py */
#include "Python.h"
#include "token.h"
/* Token names */
const char * const _PyParser_TokenNames[] = {
%s\
};
/* Return the token corresponding to a single character */
int
PyToken_OneChar(int c1)
{
%s\
return OP;
}
int
PyToken_TwoChars(int c1, int c2)
{
%s\
return OP;
}
int
PyToken_ThreeChars(int c1, int c2, int c3)
{
%s\
return OP;
}
"""
def generate_chars_to_token(mapping, n=1):
def make_c(infile, outfile='Parser/token.c'):
tok_names, ERRORTOKEN, string_to_tok = load_tokens(infile)
string_to_tok['<>'] = string_to_tok['!=']
chars_to_token = {}
for string, value in string_to_tok.items():
assert 1 <= len(string) <= 3
name = tok_names[value]
m = chars_to_token.setdefault(len(string), {})
for c in string[:-1]:
m = m.setdefault(c, {})
m[string[-1]] = name
names = []
for value, name in enumerate(tok_names):
if value >= ERRORTOKEN:
name = '<%s>' % name
names.append(' "%s",\n' % name)
names.append(' "<N_TOKENS>",\n')
if update_file(outfile, token_c_template % (
''.join(names),
generate_chars_to_token(chars_to_token[1]),
generate_chars_to_token(chars_to_token[2]),
generate_chars_to_token(chars_to_token[3])
)):
print("%s regenerated from %s" % (outfile, infile)) | null |
186,223 | STEPSIZE = 8
TABSIZE = 8
EXPANDTABS = False
import io
import re
import sys
class PythonIndenter:
def __init__(self, fpi = sys.stdin, fpo = sys.stdout,
indentsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
def write(self, line):
def readline(self):
def error(self, fmt, *args):
def getline(self):
def putline(self, line, indent):
def reformat(self):
def delete(self):
def complete(self):
def reformat_filter(input = sys.stdin, output = sys.stdout,
stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
pi.reformat() | null |
186,229 | import sys
from dataclasses import dataclass
class Entry:
base: int
size: int
name: str
def load_perf_map(filepath):
result = []
with open(filepath, "r") as perfmap:
for line in perfmap.readlines():
line = line.strip()
b, s, n = line.split(" ")
entry = Entry(int(b, 16), int(s, 16), n)
result.append(entry)
return result | null |
186,231 | import functools
import sys
import tokenize
UINT32_MASK = (1<<32)-1
def write_int_array_from_ops(name, ops, out):
bits = 0
for op in ops:
bits |= 1<<op
out.write(f"static uint32_t {name}[8] = {{\n")
for i in range(8):
out.write(f" {bits & UINT32_MASK}U,\n")
bits >>= 32
assert bits == 0
out.write(f"}};\n") | null |
186,238 | import argparse
import dis
import marshal
import sys
from types import CodeType
def dis(code, file=None):
Disassembler().dump_code(code, file=sys.stdout) | null |
186,239 | import argparse
import dis
import marshal
import sys
from types import CodeType
CodeType = type(_f.__code__)
def _get_code(root, item_path=None):
if not item_path:
return root
code = root
for chunk in item_path.split("."):
for subcode in code.co_consts:
if isinstance(subcode, CodeType):
if subcode.co_name == chunk:
code = subcode
break
else:
print(f'Could not find code object for "{chunk}" in "{item_path}"')
sys.exit(1)
return code | null |
186,243 | import argparse
import collections
import os
import re
import shlex
import subprocess
import sys
from typing import Dict, Iterable, NamedTuple, Sequence
class Stat(NamedTuple):
hits: int
stddev: float
min: float
max: float
Sequence = _alias(collections.abc.Sequence, 1)
Dict = _alias(dict, 2, inst=False, name='Dict')
def diff_perf_stats(binaries: Sequence[str], stats: Sequence[Dict[str, Stat]]) -> None:
max_stat_len = 0
for stats_dict in stats:
for counter in stats_dict.keys():
max_stat_len = max(max_stat_len, len(counter))
stat_format = (
f" {{:{max_stat_len}}}" + " : {:+5.1f}% to {:+5.1f}%, mean {:+5.1f}%{}"
)
extra_line = ""
for i in range(len(binaries)):
for j in range(i + 1, len(binaries)):
print(extra_line, end="")
extra_line = "\n"
prog1, stats1 = binaries[i], stats[i]
prog2, stats2 = binaries[j], stats[j]
print(f"{prog1} -> {prog2}")
for counter, stat1 in stats1.items():
stat2 = stats2[counter]
min_change = (stat2.min / stat1.max - 1) * 100
max_change = (stat2.max / stat1.min - 1) * 100
change = (stat2.hits / stat1.hits - 1) * 100
# Indicate results that have a very small delta or include 0 in
# their range.
tail = ""
if (
abs(min_change) < 0.1
or abs(max_change) < 0.1
or (min_change < 0 and max_change > 0)
):
tail = " ✗"
print(stat_format.format(counter, min_change, max_change, change, tail)) | null |
186,244 | import argparse
import collections
import os
import re
import shlex
import subprocess
import sys
from typing import Dict, Iterable, NamedTuple, Sequence
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="""
Run the given binaries under `perf stat` and print pairwise comparisons of the
results. Delta ranges are printed using one standard deviation from the mean in
either direction. When either side of the interval is within 0.1% of 0, an '✗'
is used to indicate a probably-insignificant result.
"""
)
parser.add_argument("--binary", "-b", action="append", default=[])
parser.add_argument(
"-r", "--repeat", default="12", help="Number of repetitions for each binary."
)
parser.add_argument(
"common_args", nargs=argparse.REMAINDER, help="Arguments to pass to each binary"
)
parser.add_argument(
"-e",
"--event",
action="append",
help="Events to pass to `perf stat`. Defaults to cycles, instructions, "
"branches, and branch-misses if not given.",
)
return parser.parse_args() | null |
186,245 | import argparse
import collections
import os
import re
import shlex
import subprocess
import sys
from typing import Dict, Iterable, NamedTuple, Sequence
class Stat(NamedTuple):
hits: int
stddev: float
min: float
max: float
def measure_binary(
binary: str, repetitions: int, events: Iterable[str], common_args: Iterable[str]
) -> str:
events_args = []
for event in events:
events_args += ["-e", event]
env = dict(os.environ)
env["PYTHONHASHSEED"] = "0"
try:
return subprocess.run(
[
"perf",
"stat",
"--field-separator",
";",
"--repeat",
repetitions,
*events_args,
*shlex.split(binary),
*common_args,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding=sys.stderr.encoding,
env=env,
check=True,
).stderr
except subprocess.CalledProcessError as cpe:
print(
f"Command {cpe.cmd} failed with exit status {cpe.returncode}:\n\nstdout:\n{cpe.stdout}\n\nstderr:\n{cpe.stderr}",
file=sys.stderr,
)
raise
class RetryMeasurement(Exception):
pass
def parse_perf_stat_output(output: str) -> Dict[str, Stat]:
stats = {}
for line in output.split("\n"):
line = line.strip()
if line in IGNORE_LINES:
continue
parts = line.split(";")
if len(parts) != 8 and len(parts) != 10:
continue
run_ratio = float(parts[5].replace("%", ""))
if run_ratio != 100.0:
raise RetryMeasurement()
count = int(parts[0])
event = parts[2]
stddev = float(parts[3].replace("%", "")) / 100 * count
stats[event] = Stat(count, stddev, count - stddev, count + stddev)
return stats
Iterable = _alias(collections.abc.Iterable, 1)
Dict = _alias(dict, 2, inst=False, name='Dict')
def collect_events(
binary: str, repeat: int, events: Iterable[str], common_args: Iterable[str]
) -> Dict[str, Stat]:
tries = 10
while True:
output = measure_binary(binary, repeat, events, common_args)
if "nmi_watchdog" in output:
# Results reported when the nmi_watchdog interfered are useless.
sys.stderr.write("\n\nError: perf stat complained about nmi_watchdog\n")
sys.stderr.write(output)
sys.stderr.write("\n\nAborting\n")
sys.exit(1)
try:
return parse_perf_stat_output(output)
except RetryMeasurement:
if tries == 1:
print(f"Failed to measure {events} for {binary}", file=sys.stderr)
sys.exit(1)
tries -= 1
print(
f"Re-measuring {events} for {binary}, {tries} attempts left",
file=sys.stderr,
) | null |
186,246 | import calendar
import email.message
import re
import os
import sys
class Unparseable(Exception):
emparse_list_list = [
'error: (?P<reason>unresolvable): (?P<email>.+)',
('----- The following addresses had permanent fatal errors -----\n',
'(?P<email>[^ \n].*)\n( .*\n)?'),
'remote execution.*\n.*rmail (?P<email>.+)',
('The following recipients did not receive your message:\n\n',
' +(?P<email>.*)\n(The following recipients did not receive your message:\n\n)?'),
'------- Failure Reasons --------\n\n(?P<reason>.*)\n(?P<email>.*)',
'^<(?P<email>.*)>:\n(?P<reason>.*)',
'^(?P<reason>User mailbox exceeds allowed size): (?P<email>.+)',
'^5\\d{2} <(?P<email>[^\n>]+)>\\.\\.\\. (?P<reason>.+)',
'^Original-Recipient: rfc822;(?P<email>.*)',
'^did not reach the following recipient\\(s\\):\n\n(?P<email>.*) on .*\n +(?P<reason>.*)',
'^ <(?P<email>[^\n>]+)> \\.\\.\\. (?P<reason>.*)',
'^Report on your message to: (?P<email>.*)\nReason: (?P<reason>.*)',
'^Your message was not delivered to +(?P<email>.*)\n +for the following reason:\n +(?P<reason>.*)',
'^ was not +(?P<email>[^ \n].*?) *\n.*\n.*\n.*\n because:.*\n +(?P<reason>[^ \n].*?) *\n',
]
for i in range(len(emparse_list_list)):
x = emparse_list_list[i]
if type(x) is type(''):
x = re.compile(x, re.MULTILINE)
else:
xl = []
for x in x:
xl.append(re.compile(x, re.MULTILINE))
x = tuple(xl)
del xl
emparse_list_list[i] = x
del x
del i
emparse_list_reason = [
r'^5\d{2} <>\.\.\. (?P<reason>.*)',
r'<>\.\.\. (?P<reason>.*)',
re.compile(r'^<<< 5\d{2} (?P<reason>.*)', re.MULTILINE),
re.compile('===== stderr was =====\nrmail: (?P<reason>.*)'),
re.compile('^Diagnostic-Code: (?P<reason>.*)', re.MULTILINE),
]
emparse_list_from = re.compile('^From:', re.IGNORECASE|re.MULTILINE)
def emparse_list(fp, sub):
data = fp.read()
res = emparse_list_from.search(data)
if res is None:
from_index = len(data)
else:
from_index = res.start(0)
errors = []
emails = []
reason = None
for regexp in emparse_list_list:
if type(regexp) is type(()):
res = regexp[0].search(data, 0, from_index)
if res is not None:
try:
reason = res.group('reason')
except IndexError:
pass
while 1:
res = regexp[1].match(data, res.end(0), from_index)
if res is None:
break
emails.append(res.group('email'))
break
else:
res = regexp.search(data, 0, from_index)
if res is not None:
emails.append(res.group('email'))
try:
reason = res.group('reason')
except IndexError:
pass
break
if not emails:
raise Unparseable
if not reason:
reason = sub
if reason[:15] == 'returned mail: ':
reason = reason[15:]
for regexp in emparse_list_reason:
if type(regexp) is type(''):
for i in range(len(emails)-1,-1,-1):
email = emails[i]
exp = re.compile(re.escape(email).join(regexp.split('<>')), re.MULTILINE)
res = exp.search(data)
if res is not None:
errors.append(' '.join((email.strip()+': '+res.group('reason')).split()))
del emails[i]
continue
res = regexp.search(data)
if res is not None:
reason = res.group('reason')
break
for email in emails:
errors.append(' '.join((email.strip()+': '+reason).split()))
return errors | null |
186,247 | import calendar
import email.message
import re
import os
import sys
class Unparseable(Exception):
class ErrorMessage(email.message.Message):
def __init__(self):
def is_warning(self):
def get_errors(self):
def sort_numeric(a, b):
def parsedir(dir, modify):
os.chdir(dir)
pat = re.compile('^[0-9]*$')
errordict = {}
errorfirst = {}
errorlast = {}
nok = nwarn = nbad = 0
# find all numeric file names and sort them
files = list(filter(lambda fn, pat=pat: pat.match(fn) is not None, os.listdir('.')))
files.sort(sort_numeric)
for fn in files:
# Lets try to parse the file.
fp = open(fn)
m = email.message_from_file(fp, _class=ErrorMessage)
sender = m.getaddr('From')
print('%s\t%-40s\t'%(fn, sender[1]), end=' ')
if m.is_warning():
fp.close()
print('warning only')
nwarn = nwarn + 1
if modify:
os.rename(fn, ','+fn)
## os.unlink(fn)
continue
try:
errors = m.get_errors()
except Unparseable:
print('** Not parseable')
nbad = nbad + 1
fp.close()
continue
print(len(errors), 'errors')
# Remember them
for e in errors:
try:
mm, dd = m.getdate('date')[1:1+2]
date = '%s %02d' % (calendar.month_abbr[mm], dd)
except:
date = '??????'
if e not in errordict:
errordict[e] = 1
errorfirst[e] = '%s (%s)' % (fn, date)
else:
errordict[e] = errordict[e] + 1
errorlast[e] = '%s (%s)' % (fn, date)
fp.close()
nok = nok + 1
if modify:
os.rename(fn, ','+fn)
## os.unlink(fn)
print('--------------')
print(nok, 'files parsed,',nwarn,'files warning-only,', end=' ')
print(nbad,'files unparseable')
print('--------------')
list = []
for e in errordict.keys():
list.append((errordict[e], errorfirst[e], errorlast[e], e))
list.sort()
for num, first, last, e in list:
print('%d %s - %s\t%s' % (num, first, last, e)) | null |
186,263 | import os.path
import re
import subprocess
import sys
import sysconfig
IGNORE = {
'__init__',
'__pycache__',
'site-packages',
# Test modules and packages
'__hello__',
'__phello__',
'_ctypes_test',
'_testbuffer',
'_testcapi',
'_testconsole',
'_testimportmultiple',
'_testinternalcapi',
'_testmultiphase',
'_xxsubinterpreters',
'_xxtestfuzz',
'distutils.tests',
'idlelib.idle_test',
'lib2to3.tests',
'test',
'xxlimited',
'xxlimited_35',
'xxsubtype',
}
WINDOWS_MODULES = (
'_msi',
'_overlapped',
'_testconsole',
'_winapi',
'msvcrt',
'nt',
'winreg',
'winsound'
)
MACOS_MODULES = (
'_scproxy',
)
def list_python_modules(names):
for filename in os.listdir(STDLIB_PATH):
if not filename.endswith(".py"):
continue
name = filename.removesuffix(".py")
names.add(name)
def list_packages(names):
for name in os.listdir(STDLIB_PATH):
if name in IGNORE:
continue
package_path = os.path.join(STDLIB_PATH, name)
if not os.path.isdir(package_path):
continue
if any(package_file.endswith(".py")
for package_file in os.listdir(package_path)):
names.add(name)
def list_setup_extensions(names):
cmd = [sys.executable, SETUP_PY, "-q", "build", "--list-module-names"]
output = subprocess.check_output(cmd)
output = output.decode("utf8")
extensions = output.splitlines()
names |= set(extensions)
def list_modules_setup_extensions(names):
assign_var = re.compile("^[A-Z]+=")
with open(MODULES_SETUP, encoding="utf-8") as modules_fp:
for line in modules_fp:
# Strip comment
line = line.partition("#")[0]
line = line.rstrip()
if not line:
continue
if assign_var.match(line):
# Ignore "VAR=VALUE"
continue
if line in ("*disabled*", "*shared*"):
continue
parts = line.split()
if len(parts) < 2:
continue
# "errno errnomodule.c" => write "errno"
name = parts[0]
names.add(name)
def list_frozen(names):
args = [TEST_EMBED, 'list_frozen']
proc = subprocess.run(args, stdout=subprocess.PIPE, text=True)
exitcode = proc.returncode
if exitcode:
cmd = ' '.join(args)
print(f"{cmd} failed with exitcode {exitcode}")
sys.exit(exitcode)
for line in proc.stdout.splitlines():
name = line.strip()
names.add(name)
def list_modules():
names = set(sys.builtin_module_names) | set(WINDOWS_MODULES) | set(MACOS_MODULES)
list_modules_setup_extensions(names)
list_setup_extensions(names)
list_packages(names)
list_python_modules(names)
list_frozen(names)
# Remove ignored packages and modules
for name in list(names):
package_name = name.split('.')[0]
# package_name can be equal to name
if package_name in IGNORE:
names.discard(name)
for name in names:
if "." in name:
raise Exception("sub-modules must not be listed")
return names | null |
186,264 | import os.path
import re
import subprocess
import sys
import sysconfig
def write_modules(fp, names):
print("// Auto-generated by Tools/scripts/generate_stdlib_module_names.py.",
file=fp)
print("// List used to create sys.stdlib_module_names.", file=fp)
print(file=fp)
print("static const char* _Py_stdlib_module_names[] = {", file=fp)
for name in sorted(names):
print(f'"{name}",', file=fp)
print("};", file=fp) | null |
186,266 | import argparse
import collections
import os
import re
import subprocess
import sys
from enum import Enum
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument(
"command",
help="Path to runtime_tests binary, optionally with extra arguments to filter which tests run",
nargs=argparse.REMAINDER,
)
parser.add_argument(
"--text-input",
"-t",
help="File containing output from a previous run of runtime_tests",
)
return parser.parse_args() | null |
186,267 | import argparse
import collections
import os
import re
import subprocess
import sys
from enum import Enum
TEST_RUN_RE = re.compile(r"^\[ RUN +\] ([^.]+)\.(.+)$")
ACTUAL_TEXT_RE = re.compile(r'^ Which is: "(.+)\\n"$')
EXPECTED_VAR_RE = re.compile(r"^ ([^ ]+)$")
FINISHED_LINE = "[----------] Global test environment tear-down"
def unescape_gtest_string(s):
def get_failed_tests(args):
if args.text_input:
with open(args.text_input, "r") as f:
stdout = f.read()
elif args.command:
proc = subprocess.run(
args.command + ["--gtest_color=no"],
stdout=subprocess.PIPE,
encoding=sys.stdout.encoding,
)
if proc.returncode == 0:
raise RuntimeError("No tests failed!")
elif proc.returncode != 1:
raise RuntimeError(
f"Command exited with {proc.returncode}, suggesting tests did not run to completion"
)
stdout = proc.stdout
else:
raise RuntimeError("Must give either --text-input or a command")
failed_tests = collections.defaultdict(lambda: {})
line_iter = iter(stdout.split("\n"))
while True:
line = next(line_iter)
if line == FINISHED_LINE:
break
match = TEST_RUN_RE.match(line)
if match:
test_name = (match[1], match[2])
test_dict = dict()
continue
match = ACTUAL_TEXT_RE.match(line)
if not match:
continue
actual_text = unescape_gtest_string(match[1]).split("\n")
line = next(line_iter)
match = EXPECTED_VAR_RE.match(line)
if not match:
raise RuntimeError(f"Unexpected line '{line}' after actual text")
varname = match[1]
if varname in test_dict:
raise RuntimeError(
f"Duplicate expect variable name '{varname}' in {test_name[0]}.{test_name[1]}"
)
test_dict[varname] = actual_text
failed_tests[test_name[0]][test_name[1]] = test_dict
# Skip the "Which is: ..." line after the expect variable name.
next(line_iter)
return failed_tests | null |
186,268 | import argparse
import collections
import os
import re
import subprocess
import sys
from enum import Enum
TESTS_DIR = os.path.normpath(
os.path.join(os.path.dirname(__file__), "..", "..", "cinderx", "RuntimeTests")
)
def map_suite_to_file_basename(suite_name):
assert map_suite_to_file_basename("CleanCFGTest") == "clean_cfg_test"
assert map_suite_to_file_basename("HIRBuilderTest") == "hir_builder_test"
assert (
map_suite_to_file_basename("ProfileDataStaticHIRTest")
== "profile_data_static_hir_test"
)
assert (
map_suite_to_file_basename("SomethingEndingWithHIR") == "something_ending_with_hir"
)
def map_suite_to_file(suite_name):
snake_name = map_suite_to_file_basename(suite_name)
return os.path.join(TESTS_DIR, "hir_tests", snake_name + ".txt") | null |
186,269 | import argparse
import collections
import os
import re
import subprocess
import sys
from enum import Enum
def update_text_test(old_lines, suite_name, failed_tests):
line_iter = iter(old_lines)
new_lines = []
def expect(exp):
line = next(line_iter)
if line != exp:
raise RuntimeError(f"Expected '{exp}', got '{line}'")
new_lines.append(line)
expect(suite_name)
expect("---")
# Optional pass names
line = next(line_iter)
new_lines.append(line)
while line != "---":
line = next(line_iter)
new_lines.append(line)
try:
while True:
test_case = next(line_iter)
if test_case == "@disabled":
test_case += "\n" + next(line_iter)
new_lines.append(test_case)
expect("---")
while True:
line = next(line_iter)
new_lines.append(line)
if line == "---":
break
hir_lines = []
line = next(line_iter)
while line != "---":
hir_lines.append(line)
line = next(line_iter)
if test_case in failed_tests:
# For text HIR tests, there should only be one element in the
# failed test dict.
hir_lines = next(iter(failed_tests[test_case].values()))
new_lines += hir_lines
new_lines.append("---")
except StopIteration:
pass
return new_lines | null |
186,270 | import argparse
import collections
import os
import re
import subprocess
import sys
from enum import Enum
TESTS_DIR = os.path.normpath(
os.path.join(os.path.dirname(__file__), "..", "..", "cinderx", "RuntimeTests")
)
def write_if_changed(filename, old_lines, new_lines):
if new_lines == old_lines:
return
with open(filename, "w") as f:
print(f"Rewriting {filename}")
f.write("\n".join(new_lines))
CPP_TEST_NAME_RE = re.compile(r"^TEST(_F)?\(([^,]+), ([^)]+)\) {")
CPP_EXPECTED_START_RE = re.compile(r"^( const char\* ([^ ]+) =)")
CPP_EXPECTED_END = ')";'
def find_cpp_files(root):
for dirpath, dirnames, filenames in os.walk(root):
for filename in filenames:
if filename.endswith(".cpp"):
yield os.path.join(dirpath, filename)
class State(Enum):
# Active before the first test is found, or during a passing test.
WAIT_FOR_TEST = 1
# Active while reading a test that has failed, either waiting for an
# expected variable or a new test.
PROCESS_FAILED_TEST = 2
# Active while skipping lines of an expected variable.
SKIP_EXPECTED = 3
def update_cpp_tests(failed_suites, failed_cpp_tests):
def expect_state(estate):
nonlocal state, lineno, cpp_filename
if state is not estate:
sys.exit(
f"Expected state {estate} at {cpp_filename}:{lineno}, actual {state}"
)
def expect_empty_test_dict():
if test_dict is not None and len(test_dict) > 0:
print(
f"Coudln't find {len(test_dict)} expected variables in {suite_name}.{test_name}:"
)
print(list(test_dict.keys()))
for cpp_filename in find_cpp_files(TESTS_DIR):
with open(cpp_filename, "r") as f:
old_lines = f.read().split("\n")
state = State.WAIT_FOR_TEST
test_dict = None
new_lines = []
for lineno, line in enumerate(old_lines, 1):
m = CPP_TEST_NAME_RE.match(line)
if m is not None:
new_lines.append(line)
expect_empty_test_dict()
test_dict = None
suite_name = m[2]
test_name = m[3]
try:
failed_cpp_tests.remove((suite_name, test_name))
except KeyError:
state = State.WAIT_FOR_TEST
continue
test_dict = failed_suites[suite_name][test_name]
state = State.PROCESS_FAILED_TEST
continue
if state is State.WAIT_FOR_TEST:
new_lines.append(line)
continue
m = CPP_EXPECTED_START_RE.match(line)
if m is not None:
expect_state(State.PROCESS_FAILED_TEST)
decl = m[1]
varname = m[2]
try:
actual_lines = test_dict[varname]
del test_dict[varname]
except KeyError:
# This test has multiple expected variables, and this one
# is OK.
new_lines.append(line)
continue
# This may collapse a two-line start to the variable onto one
# line, which clang-format will clean up.
new_lines.append(decl + ' R"(' + actual_lines[0])
new_lines += actual_lines[1:]
state = State.SKIP_EXPECTED
continue
if state is State.SKIP_EXPECTED:
if line == CPP_EXPECTED_END:
new_lines.append(line)
state = State.PROCESS_FAILED_TEST
continue
new_lines.append(line)
expect_empty_test_dict()
write_if_changed(cpp_filename, old_lines, new_lines)
if len(failed_cpp_tests) > 0:
print(f"\nCouldn't find {len(failed_cpp_tests)} failed test(s):")
for test in failed_cpp_tests:
print(f"{test[0]}.{test[1]}") | null |
186,271 | import argparse
import re
import subprocess
import sys
from enum import Enum
COMMIT_START_RE = re.compile(r"^commit ([a-f0-9]{40})$")
REVISION_RE = re.compile(r" Differential Revision: https.+(D[0-9]+)$")
class State(Enum):
WAIT_FOR_COMMIT = 1
WAIT_FOR_TITLE = 2
WAIT_FOR_REVISION = 3
def find_commits(args):
stdout = subprocess.run(
[
"git",
"log",
"--reverse",
f"{args.base_commit}..{args.end_commit}",
"--",
*args.files,
],
check=True,
encoding=sys.stdin.encoding,
stdout=subprocess.PIPE,
).stdout
commits = {}
commit_hash = None
title = None
state = State.WAIT_FOR_COMMIT
for line in stdout.splitlines():
if state is State.WAIT_FOR_COMMIT:
if m := COMMIT_START_RE.match(line):
state = State.WAIT_FOR_TITLE
commit_hash = m[1]
elif state is State.WAIT_FOR_TITLE:
if line.startswith(" "):
title = line.strip()
state = State.WAIT_FOR_REVISION
elif state is State.WAIT_FOR_REVISION:
if m := REVISION_RE.match(line):
commits[commit_hash] = f"{m[1]}: {title}"
commit_hash = None
title = None
state = State.WAIT_FOR_COMMIT
return commits | null |
186,272 | import argparse
import re
import subprocess
import sys
from enum import Enum
BLAME_LINE_RE = re.compile(r"^([0-9a-f]{40}) ")
def collect_blamed_commits(args, filename, commits):
stdout = subprocess.run(
["git", "blame", "-l", args.end_commit, "--", filename],
check=True,
encoding=sys.stdin.encoding,
stdout=subprocess.PIPE,
).stdout
blamed_commits = set()
for line in stdout.splitlines():
m = BLAME_LINE_RE.match(line)
if not m:
raise RuntimeError(f"Don't understand line '{line}'")
commit_hash = m[1]
if commit_hash in commits:
blamed_commits.add(commit_hash)
return blamed_commits | null |
186,273 | import argparse
import re
import subprocess
import sys
from enum import Enum
def parse_args():
parser = argparse.ArgumentParser(
description="Generate an abbreviated list of commits from Cinder 3.8, optionally limited to commits that contributed to the current version of a given set of files (as determined by `git blame`)."
)
parser.add_argument(
"--base-commit", default="origin/3.8", help="Beginning of commit search range"
)
parser.add_argument(
"--end-commit",
default="cinder/310-phase1-target",
help="End of commit search range",
)
parser.add_argument(
"files", nargs="*", help="Restrict search to the given files, if any"
)
return parser.parse_args() | null |
186,289 | from collections import deque, namedtuple
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = ', '.join(field_names)
if num_fields == 1:
arg_list += ','
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
# Create all the named tuple methods to be added to the class namespace
namespace = {
'_tuple_new': tuple_new,
'__builtins__': {},
'__name__': f'namedtuple_{typename}',
}
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
__new__ = eval(code, namespace)
__new__.__name__ = '__new__'
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new dict which maps field names to their values.'
return _dict(_zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (
__new__,
_make.__func__,
_replace,
__repr__,
_asdict,
__getnewargs__,
):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
'__match_args__': field_names,
}
for index, name in enumerate(field_names):
doc = _sys.intern(f'Alias for field number {index}')
class_namespace[name] = _tuplegetter(index, doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
def read_namedtuple(trials=trials, D=namedtuple('D', ['x'])):
a = D(1)
for t in trials:
a.x; a.x; a.x; a.x; a.x
a.x; a.x; a.x; a.x; a.x
a.x; a.x; a.x; a.x; a.x
a.x; a.x; a.x; a.x; a.x
a.x; a.x; a.x; a.x; a.x | null |
186,310 | import sys
import re
import os
m_import = re.compile('^[ \t]*from[ \t]+([^ \t]+)[ \t]+')
m_from = re.compile('^[ \t]*import[ \t]+([^#]+)')
def process(filename, table):
with open(filename, encoding='utf-8') as fp:
mod = os.path.basename(filename)
if mod[-3:] == '.py':
mod = mod[:-3]
table[mod] = list = []
while 1:
line = fp.readline()
if not line: break
while line[-1:] == '\\':
nextline = fp.readline()
if not nextline: break
line = line[:-1] + nextline
m_found = m_import.match(line) or m_from.match(line)
if m_found:
(a, b), (a1, b1) = m_found.regs[:2]
else: continue
words = line[a1:b1].split(',')
# print '#', line, words
for word in words:
word = word.strip()
if word not in list:
list.append(word) | null |
186,314 | import re
import os
import sys
import tempfile
PIPE = -1
STDOUT = -2
class Popen:
""" Execute a child program in a new process.
For a complete description of the arguments see the Python documentation.
Arguments:
args: A string, or a sequence of program arguments.
bufsize: supplied as the buffering argument to the open() function when
creating the stdin/stdout/stderr pipe file objects
executable: A replacement program to execute.
stdin, stdout and stderr: These specify the executed programs' standard
input, standard output and standard error file handles, respectively.
preexec_fn: (POSIX only) An object to be called in the child process
just before the child is executed.
close_fds: Controls closing or inheriting of file descriptors.
shell: If true, the command will be executed through the shell.
cwd: Sets the current directory before the child is executed.
env: Defines the environment variables for the new process.
text: If true, decode stdin, stdout and stderr using the given encoding
(if set) or the system default otherwise.
universal_newlines: Alias of text, provided for backwards compatibility.
startupinfo and creationflags (Windows only)
restore_signals (POSIX only)
start_new_session (POSIX only)
group (POSIX only)
extra_groups (POSIX only)
user (POSIX only)
umask (POSIX only)
pass_fds (POSIX only)
encoding and errors: Text mode encoding and error handling to use for
file objects stdin, stdout and stderr.
Attributes:
stdin, stdout, stderr, pid, returncode
"""
_child_created = False # Set here since __del__ checks it
def __init__(self, args, bufsize=-1, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True,
shell=False, cwd=None, env=None, universal_newlines=None,
startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False,
pass_fds=(), *, user=None, group=None, extra_groups=None,
encoding=None, errors=None, text=None, umask=-1, pipesize=-1):
"""Create new Popen instance."""
_cleanup()
# Held while anything is calling waitpid before returncode has been
# updated to prevent clobbering returncode if wait() or poll() are
# called from multiple threads at once. After acquiring the lock,
# code must re-check self.returncode to see if another thread just
# finished a waitpid() call.
self._waitpid_lock = threading.Lock()
self._input = None
self._communication_started = False
if bufsize is None:
bufsize = -1 # Restore default
if not isinstance(bufsize, int):
raise TypeError("bufsize must be an integer")
if pipesize is None:
pipesize = -1 # Restore default
if not isinstance(pipesize, int):
raise TypeError("pipesize must be an integer")
if _mswindows:
if preexec_fn is not None:
raise ValueError("preexec_fn is not supported on Windows "
"platforms")
else:
# POSIX
if pass_fds and not close_fds:
warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
close_fds = True
if startupinfo is not None:
raise ValueError("startupinfo is only supported on Windows "
"platforms")
if creationflags != 0:
raise ValueError("creationflags is only supported on Windows "
"platforms")
self.args = args
self.stdin = None
self.stdout = None
self.stderr = None
self.pid = None
self.returncode = None
self.encoding = encoding
self.errors = errors
self.pipesize = pipesize
# Validate the combinations of text and universal_newlines
if (text is not None and universal_newlines is not None
and bool(universal_newlines) != bool(text)):
raise SubprocessError('Cannot disambiguate when both text '
'and universal_newlines are supplied but '
'different. Pass one or the other.')
# Input and output objects. The general principle is like
# this:
#
# Parent Child
# ------ -----
# p2cwrite ---stdin---> p2cread
# c2pread <--stdout--- c2pwrite
# errread <--stderr--- errwrite
#
# On POSIX, the child objects are file descriptors. On
# Windows, these are Windows file handles. The parent objects
# are file descriptors on both platforms. The parent objects
# are -1 when not using PIPEs. The child objects are -1
# when not redirecting.
(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
# We wrap OS handles *before* launching the child, otherwise a
# quickly terminating child could make our fds unwrappable
# (see #8458).
if _mswindows:
if p2cwrite != -1:
p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
if c2pread != -1:
c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
if errread != -1:
errread = msvcrt.open_osfhandle(errread.Detach(), 0)
self.text_mode = encoding or errors or text or universal_newlines
# PEP 597: We suppress the EncodingWarning in subprocess module
# for now (at Python 3.10), because we focus on files for now.
# This will be changed to encoding = io.text_encoding(encoding)
# in the future.
if self.text_mode and encoding is None:
self.encoding = encoding = "locale"
# How long to resume waiting on a child after the first ^C.
# There is no right value for this. The purpose is to be polite
# yet remain good for interactive users trying to exit a tool.
self._sigint_wait_secs = 0.25 # 1/xkcd221.getRandomNumber()
self._closed_child_pipe_fds = False
if self.text_mode:
if bufsize == 1:
line_buffering = True
# Use the default buffer size for the underlying binary streams
# since they don't support line buffering.
bufsize = -1
else:
line_buffering = False
gid = None
if group is not None:
if not hasattr(os, 'setregid'):
raise ValueError("The 'group' parameter is not supported on the "
"current platform")
elif isinstance(group, str):
try:
import grp
except ImportError:
raise ValueError("The group parameter cannot be a string "
"on systems without the grp module")
gid = grp.getgrnam(group).gr_gid
elif isinstance(group, int):
gid = group
else:
raise TypeError("Group must be a string or an integer, not {}"
.format(type(group)))
if gid < 0:
raise ValueError(f"Group ID cannot be negative, got {gid}")
gids = None
if extra_groups is not None:
if not hasattr(os, 'setgroups'):
raise ValueError("The 'extra_groups' parameter is not "
"supported on the current platform")
elif isinstance(extra_groups, str):
raise ValueError("Groups must be a list, not a string")
gids = []
for extra_group in extra_groups:
if isinstance(extra_group, str):
try:
import grp
except ImportError:
raise ValueError("Items in extra_groups cannot be "
"strings on systems without the "
"grp module")
gids.append(grp.getgrnam(extra_group).gr_gid)
elif isinstance(extra_group, int):
gids.append(extra_group)
else:
raise TypeError("Items in extra_groups must be a string "
"or integer, not {}"
.format(type(extra_group)))
# make sure that the gids are all positive here so we can do less
# checking in the C code
for gid_check in gids:
if gid_check < 0:
raise ValueError(f"Group ID cannot be negative, got {gid_check}")
uid = None
if user is not None:
if not hasattr(os, 'setreuid'):
raise ValueError("The 'user' parameter is not supported on "
"the current platform")
elif isinstance(user, str):
try:
import pwd
except ImportError:
raise ValueError("The user parameter cannot be a string "
"on systems without the pwd module")
uid = pwd.getpwnam(user).pw_uid
elif isinstance(user, int):
uid = user
else:
raise TypeError("User must be a string or an integer")
if uid < 0:
raise ValueError(f"User ID cannot be negative, got {uid}")
try:
if p2cwrite != -1:
self.stdin = io.open(p2cwrite, 'wb', bufsize)
if self.text_mode:
self.stdin = io.TextIOWrapper(self.stdin, write_through=True,
line_buffering=line_buffering,
encoding=encoding, errors=errors)
if c2pread != -1:
self.stdout = io.open(c2pread, 'rb', bufsize)
if self.text_mode:
self.stdout = io.TextIOWrapper(self.stdout,
encoding=encoding, errors=errors)
if errread != -1:
self.stderr = io.open(errread, 'rb', bufsize)
if self.text_mode:
self.stderr = io.TextIOWrapper(self.stderr,
encoding=encoding, errors=errors)
self._execute_child(args, executable, preexec_fn, close_fds,
pass_fds, cwd, env,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
restore_signals,
gid, gids, uid, umask,
start_new_session)
except:
# Cleanup if the child failed starting.
for f in filter(None, (self.stdin, self.stdout, self.stderr)):
try:
f.close()
except OSError:
pass # Ignore EBADF or other errors.
if not self._closed_child_pipe_fds:
to_close = []
if stdin == PIPE:
to_close.append(p2cread)
if stdout == PIPE:
to_close.append(c2pwrite)
if stderr == PIPE:
to_close.append(errwrite)
if hasattr(self, '_devnull'):
to_close.append(self._devnull)
for fd in to_close:
try:
if _mswindows and isinstance(fd, Handle):
fd.Close()
else:
os.close(fd)
except OSError:
pass
raise
def __repr__(self):
obj_repr = (
f"<{self.__class__.__name__}: "
f"returncode: {self.returncode} args: {self.args!r}>"
)
if len(obj_repr) > 80:
obj_repr = obj_repr[:76] + "...>"
return obj_repr
__class_getitem__ = classmethod(types.GenericAlias)
def universal_newlines(self):
# universal_newlines as retained as an alias of text_mode for API
# compatibility. bpo-31756
return self.text_mode
def universal_newlines(self, universal_newlines):
self.text_mode = bool(universal_newlines)
def _translate_newlines(self, data, encoding, errors):
data = data.decode(encoding, errors)
return data.replace("\r\n", "\n").replace("\r", "\n")
def __enter__(self):
return self
def __exit__(self, exc_type, value, traceback):
if self.stdout:
self.stdout.close()
if self.stderr:
self.stderr.close()
try: # Flushing a BufferedWriter may raise an error
if self.stdin:
self.stdin.close()
finally:
if exc_type == KeyboardInterrupt:
# https://bugs.python.org/issue25942
# In the case of a KeyboardInterrupt we assume the SIGINT
# was also already sent to our child processes. We can't
# block indefinitely as that is not user friendly.
# If we have not already waited a brief amount of time in
# an interrupted .wait() or .communicate() call, do so here
# for consistency.
if self._sigint_wait_secs > 0:
try:
self._wait(timeout=self._sigint_wait_secs)
except TimeoutExpired:
pass
self._sigint_wait_secs = 0 # Note that this has been done.
return # resume the KeyboardInterrupt
# Wait for the process to terminate, to avoid zombies.
self.wait()
def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn):
if not self._child_created:
# We didn't get to successfully create a child process.
return
if self.returncode is None:
# Not reading subprocess exit status creates a zombie process which
# is only destroyed at the parent python process exit
_warn("subprocess %s is still running" % self.pid,
ResourceWarning, source=self)
# In case the child hasn't been waited on, check if it's done.
self._internal_poll(_deadstate=_maxsize)
if self.returncode is None and _active is not None:
# Child is still running, keep us alive until we can wait on it.
_active.append(self)
def _get_devnull(self):
if not hasattr(self, '_devnull'):
self._devnull = os.open(os.devnull, os.O_RDWR)
return self._devnull
def _stdin_write(self, input):
if input:
try:
self.stdin.write(input)
except BrokenPipeError:
pass # communicate() must ignore broken pipe errors.
except OSError as exc:
if exc.errno == errno.EINVAL:
# bpo-19612, bpo-30418: On Windows, stdin.write() fails
# with EINVAL if the child process exited or if the child
# process is still running but closed the pipe.
pass
else:
raise
try:
self.stdin.close()
except BrokenPipeError:
pass # communicate() must ignore broken pipe errors.
except OSError as exc:
if exc.errno == errno.EINVAL:
pass
else:
raise
def communicate(self, input=None, timeout=None):
"""Interact with process: Send data to stdin and close it.
Read data from stdout and stderr, until end-of-file is
reached. Wait for process to terminate.
The optional "input" argument should be data to be sent to the
child process, or None, if no data should be sent to the child.
communicate() returns a tuple (stdout, stderr).
By default, all communication is in bytes, and therefore any
"input" should be bytes, and the (stdout, stderr) will be bytes.
If in text mode (indicated by self.text_mode), any "input" should
be a string, and (stdout, stderr) will be strings decoded
according to locale encoding, or by "encoding" if set. Text mode
is triggered by setting any of text, encoding, errors or
universal_newlines.
"""
if self._communication_started and input:
raise ValueError("Cannot send input after starting communication")
# Optimization: If we are not worried about timeouts, we haven't
# started communicating, and we have one or zero pipes, using select()
# or threads is unnecessary.
if (timeout is None and not self._communication_started and
[self.stdin, self.stdout, self.stderr].count(None) >= 2):
stdout = None
stderr = None
if self.stdin:
self._stdin_write(input)
elif self.stdout:
stdout = self.stdout.read()
self.stdout.close()
elif self.stderr:
stderr = self.stderr.read()
self.stderr.close()
self.wait()
else:
if timeout is not None:
endtime = _time() + timeout
else:
endtime = None
try:
stdout, stderr = self._communicate(input, endtime, timeout)
except KeyboardInterrupt:
# https://bugs.python.org/issue25942
# See the detailed comment in .wait().
if timeout is not None:
sigint_timeout = min(self._sigint_wait_secs,
self._remaining_time(endtime))
else:
sigint_timeout = self._sigint_wait_secs
self._sigint_wait_secs = 0 # nothing else should wait.
try:
self._wait(timeout=sigint_timeout)
except TimeoutExpired:
pass
raise # resume the KeyboardInterrupt
finally:
self._communication_started = True
sts = self.wait(timeout=self._remaining_time(endtime))
return (stdout, stderr)
def poll(self):
"""Check if child process has terminated. Set and return returncode
attribute."""
return self._internal_poll()
def _remaining_time(self, endtime):
"""Convenience for _communicate when computing timeouts."""
if endtime is None:
return None
else:
return endtime - _time()
def _check_timeout(self, endtime, orig_timeout, stdout_seq, stderr_seq,
skip_check_and_raise=False):
"""Convenience for checking if a timeout has expired."""
if endtime is None:
return
if skip_check_and_raise or _time() > endtime:
raise TimeoutExpired(
self.args, orig_timeout,
output=b''.join(stdout_seq) if stdout_seq else None,
stderr=b''.join(stderr_seq) if stderr_seq else None)
def wait(self, timeout=None):
"""Wait for child process to terminate; returns self.returncode."""
if timeout is not None:
endtime = _time() + timeout
try:
return self._wait(timeout=timeout)
except KeyboardInterrupt:
# https://bugs.python.org/issue25942
# The first keyboard interrupt waits briefly for the child to
# exit under the common assumption that it also received the ^C
# generated SIGINT and will exit rapidly.
if timeout is not None:
sigint_timeout = min(self._sigint_wait_secs,
self._remaining_time(endtime))
else:
sigint_timeout = self._sigint_wait_secs
self._sigint_wait_secs = 0 # nothing else should wait.
try:
self._wait(timeout=sigint_timeout)
except TimeoutExpired:
pass
raise # resume the KeyboardInterrupt
def _close_pipe_fds(self,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
# self._devnull is not always defined.
devnull_fd = getattr(self, '_devnull', None)
with contextlib.ExitStack() as stack:
if _mswindows:
if p2cread != -1:
stack.callback(p2cread.Close)
if c2pwrite != -1:
stack.callback(c2pwrite.Close)
if errwrite != -1:
stack.callback(errwrite.Close)
else:
if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
stack.callback(os.close, p2cread)
if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
stack.callback(os.close, c2pwrite)
if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
stack.callback(os.close, errwrite)
if devnull_fd is not None:
stack.callback(os.close, devnull_fd)
# Prevent a double close of these handles/fds from __init__ on error.
self._closed_child_pipe_fds = True
if _mswindows:
#
# Windows methods
#
def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
if stdin is None and stdout is None and stderr is None:
return (-1, -1, -1, -1, -1, -1)
p2cread, p2cwrite = -1, -1
c2pread, c2pwrite = -1, -1
errread, errwrite = -1, -1
if stdin is None:
p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
if p2cread is None:
p2cread, _ = _winapi.CreatePipe(None, 0)
p2cread = Handle(p2cread)
_winapi.CloseHandle(_)
elif stdin == PIPE:
p2cread, p2cwrite = _winapi.CreatePipe(None, 0)
p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
elif stdin == DEVNULL:
p2cread = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stdin, int):
p2cread = msvcrt.get_osfhandle(stdin)
else:
# Assuming file-like object
p2cread = msvcrt.get_osfhandle(stdin.fileno())
p2cread = self._make_inheritable(p2cread)
if stdout is None:
c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
if c2pwrite is None:
_, c2pwrite = _winapi.CreatePipe(None, 0)
c2pwrite = Handle(c2pwrite)
_winapi.CloseHandle(_)
elif stdout == PIPE:
c2pread, c2pwrite = _winapi.CreatePipe(None, 0)
c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
elif stdout == DEVNULL:
c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stdout, int):
c2pwrite = msvcrt.get_osfhandle(stdout)
else:
# Assuming file-like object
c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
c2pwrite = self._make_inheritable(c2pwrite)
if stderr is None:
errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
if errwrite is None:
_, errwrite = _winapi.CreatePipe(None, 0)
errwrite = Handle(errwrite)
_winapi.CloseHandle(_)
elif stderr == PIPE:
errread, errwrite = _winapi.CreatePipe(None, 0)
errread, errwrite = Handle(errread), Handle(errwrite)
elif stderr == STDOUT:
errwrite = c2pwrite
elif stderr == DEVNULL:
errwrite = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stderr, int):
errwrite = msvcrt.get_osfhandle(stderr)
else:
# Assuming file-like object
errwrite = msvcrt.get_osfhandle(stderr.fileno())
errwrite = self._make_inheritable(errwrite)
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
def _make_inheritable(self, handle):
"""Return a duplicate of handle, which is inheritable"""
h = _winapi.DuplicateHandle(
_winapi.GetCurrentProcess(), handle,
_winapi.GetCurrentProcess(), 0, 1,
_winapi.DUPLICATE_SAME_ACCESS)
return Handle(h)
def _filter_handle_list(self, handle_list):
"""Filter out console handles that can't be used
in lpAttributeList["handle_list"] and make sure the list
isn't empty. This also removes duplicate handles."""
# An handle with it's lowest two bits set might be a special console
# handle that if passed in lpAttributeList["handle_list"], will
# cause it to fail.
return list({handle for handle in handle_list
if handle & 0x3 != 0x3
or _winapi.GetFileType(handle) !=
_winapi.FILE_TYPE_CHAR})
def _execute_child(self, args, executable, preexec_fn, close_fds,
pass_fds, cwd, env,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
unused_restore_signals,
unused_gid, unused_gids, unused_uid,
unused_umask,
unused_start_new_session):
"""Execute program (MS Windows version)"""
assert not pass_fds, "pass_fds not supported on Windows."
if isinstance(args, str):
pass
elif isinstance(args, bytes):
if shell:
raise TypeError('bytes args is not allowed on Windows')
args = list2cmdline([args])
elif isinstance(args, os.PathLike):
if shell:
raise TypeError('path-like args is not allowed when '
'shell is true')
args = list2cmdline([args])
else:
args = list2cmdline(args)
if executable is not None:
executable = os.fsdecode(executable)
# Process startup details
if startupinfo is None:
startupinfo = STARTUPINFO()
else:
# bpo-34044: Copy STARTUPINFO since it is modified above,
# so the caller can reuse it multiple times.
startupinfo = startupinfo.copy()
use_std_handles = -1 not in (p2cread, c2pwrite, errwrite)
if use_std_handles:
startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES
startupinfo.hStdInput = p2cread
startupinfo.hStdOutput = c2pwrite
startupinfo.hStdError = errwrite
attribute_list = startupinfo.lpAttributeList
have_handle_list = bool(attribute_list and
"handle_list" in attribute_list and
attribute_list["handle_list"])
# If we were given an handle_list or need to create one
if have_handle_list or (use_std_handles and close_fds):
if attribute_list is None:
attribute_list = startupinfo.lpAttributeList = {}
handle_list = attribute_list["handle_list"] = \
list(attribute_list.get("handle_list", []))
if use_std_handles:
handle_list += [int(p2cread), int(c2pwrite), int(errwrite)]
handle_list[:] = self._filter_handle_list(handle_list)
if handle_list:
if not close_fds:
warnings.warn("startupinfo.lpAttributeList['handle_list'] "
"overriding close_fds", RuntimeWarning)
# When using the handle_list we always request to inherit
# handles but the only handles that will be inherited are
# the ones in the handle_list
close_fds = False
if shell:
startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = _winapi.SW_HIDE
comspec = os.environ.get("COMSPEC", "cmd.exe")
args = '{} /c "{}"'.format (comspec, args)
if cwd is not None:
cwd = os.fsdecode(cwd)
sys.audit("subprocess.Popen", executable, args, cwd, env)
# Start the process
try:
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
# no special security
None, None,
int(not close_fds),
creationflags,
env,
cwd,
startupinfo)
finally:
# Child is launched. Close the parent's copy of those pipe
# handles that only the child should have open. You need
# to make sure that no handles to the write end of the
# output pipe are maintained in this process or else the
# pipe will not close when the child process exits and the
# ReadFile will hang.
self._close_pipe_fds(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
# Retain the process handle, but close the thread handle
self._child_created = True
self._handle = Handle(hp)
self.pid = pid
_winapi.CloseHandle(ht)
def _internal_poll(self, _deadstate=None,
_WaitForSingleObject=_winapi.WaitForSingleObject,
_WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
_GetExitCodeProcess=_winapi.GetExitCodeProcess):
"""Check if child process has terminated. Returns returncode
attribute.
This method is called by __del__, so it can only refer to objects
in its local scope.
"""
if self.returncode is None:
if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
self.returncode = _GetExitCodeProcess(self._handle)
return self.returncode
def _wait(self, timeout):
"""Internal implementation of wait() on Windows."""
if timeout is None:
timeout_millis = _winapi.INFINITE
else:
timeout_millis = int(timeout * 1000)
if self.returncode is None:
# API note: Returns immediately if timeout_millis == 0.
result = _winapi.WaitForSingleObject(self._handle,
timeout_millis)
if result == _winapi.WAIT_TIMEOUT:
raise TimeoutExpired(self.args, timeout)
self.returncode = _winapi.GetExitCodeProcess(self._handle)
return self.returncode
def _readerthread(self, fh, buffer):
buffer.append(fh.read())
fh.close()
def _communicate(self, input, endtime, orig_timeout):
# Start reader threads feeding into a list hanging off of this
# object, unless they've already been started.
if self.stdout and not hasattr(self, "_stdout_buff"):
self._stdout_buff = []
self.stdout_thread = \
threading.Thread(target=self._readerthread,
args=(self.stdout, self._stdout_buff))
self.stdout_thread.daemon = True
self.stdout_thread.start()
if self.stderr and not hasattr(self, "_stderr_buff"):
self._stderr_buff = []
self.stderr_thread = \
threading.Thread(target=self._readerthread,
args=(self.stderr, self._stderr_buff))
self.stderr_thread.daemon = True
self.stderr_thread.start()
if self.stdin:
self._stdin_write(input)
# Wait for the reader threads, or time out. If we time out, the
# threads remain reading and the fds left open in case the user
# calls communicate again.
if self.stdout is not None:
self.stdout_thread.join(self._remaining_time(endtime))
if self.stdout_thread.is_alive():
raise TimeoutExpired(self.args, orig_timeout)
if self.stderr is not None:
self.stderr_thread.join(self._remaining_time(endtime))
if self.stderr_thread.is_alive():
raise TimeoutExpired(self.args, orig_timeout)
# Collect the output from and close both pipes, now that we know
# both have been read successfully.
stdout = None
stderr = None
if self.stdout:
stdout = self._stdout_buff
self.stdout.close()
if self.stderr:
stderr = self._stderr_buff
self.stderr.close()
# All data exchanged. Translate lists into strings.
stdout = stdout[0] if stdout else None
stderr = stderr[0] if stderr else None
return (stdout, stderr)
def send_signal(self, sig):
"""Send a signal to the process."""
# Don't signal a process that we know has already died.
if self.returncode is not None:
return
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError("Unsupported signal: {}".format(sig))
def terminate(self):
"""Terminates the process."""
# Don't terminate a process that we know has already died.
if self.returncode is not None:
return
try:
_winapi.TerminateProcess(self._handle, 1)
except PermissionError:
# ERROR_ACCESS_DENIED (winerror 5) is received when the
# process already died.
rc = _winapi.GetExitCodeProcess(self._handle)
if rc == _winapi.STILL_ACTIVE:
raise
self.returncode = rc
kill = terminate
else:
#
# POSIX methods
#
def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
p2cread, p2cwrite = -1, -1
c2pread, c2pwrite = -1, -1
errread, errwrite = -1, -1
if stdin is None:
pass
elif stdin == PIPE:
p2cread, p2cwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(p2cwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stdin == DEVNULL:
p2cread = self._get_devnull()
elif isinstance(stdin, int):
p2cread = stdin
else:
# Assuming file-like object
p2cread = stdin.fileno()
if stdout is None:
pass
elif stdout == PIPE:
c2pread, c2pwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(c2pwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stdout == DEVNULL:
c2pwrite = self._get_devnull()
elif isinstance(stdout, int):
c2pwrite = stdout
else:
# Assuming file-like object
c2pwrite = stdout.fileno()
if stderr is None:
pass
elif stderr == PIPE:
errread, errwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(errwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stderr == STDOUT:
if c2pwrite != -1:
errwrite = c2pwrite
else: # child's stdout is not set, use parent's stdout
errwrite = sys.__stdout__.fileno()
elif stderr == DEVNULL:
errwrite = self._get_devnull()
elif isinstance(stderr, int):
errwrite = stderr
else:
# Assuming file-like object
errwrite = stderr.fileno()
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
def _posix_spawn(self, args, executable, env, restore_signals,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
"""Execute program using os.posix_spawn()."""
if env is None:
env = os.environ
kwargs = {}
if restore_signals:
# See _Py_RestoreSignals() in Python/pylifecycle.c
sigset = []
for signame in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'):
signum = getattr(signal, signame, None)
if signum is not None:
sigset.append(signum)
kwargs['setsigdef'] = sigset
file_actions = []
for fd in (p2cwrite, c2pread, errread):
if fd != -1:
file_actions.append((os.POSIX_SPAWN_CLOSE, fd))
for fd, fd2 in (
(p2cread, 0),
(c2pwrite, 1),
(errwrite, 2),
):
if fd != -1:
file_actions.append((os.POSIX_SPAWN_DUP2, fd, fd2))
if file_actions:
kwargs['file_actions'] = file_actions
self.pid = os.posix_spawn(executable, args, env, **kwargs)
self._child_created = True
self._close_pipe_fds(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
def _execute_child(self, args, executable, preexec_fn, close_fds,
pass_fds, cwd, env,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
restore_signals,
gid, gids, uid, umask,
start_new_session):
"""Execute program (POSIX version)"""
if isinstance(args, (str, bytes)):
args = [args]
elif isinstance(args, os.PathLike):
if shell:
raise TypeError('path-like args is not allowed when '
'shell is true')
args = [args]
else:
args = list(args)
if shell:
# On Android the default shell is at '/system/bin/sh'.
unix_shell = ('/system/bin/sh' if
hasattr(sys, 'getandroidapilevel') else '/bin/sh')
args = [unix_shell, "-c"] + args
if executable:
args[0] = executable
if executable is None:
executable = args[0]
sys.audit("subprocess.Popen", executable, args, cwd, env)
if (_USE_POSIX_SPAWN
and os.path.dirname(executable)
and preexec_fn is None
and not close_fds
and not pass_fds
and cwd is None
and (p2cread == -1 or p2cread > 2)
and (c2pwrite == -1 or c2pwrite > 2)
and (errwrite == -1 or errwrite > 2)
and not start_new_session
and gid is None
and gids is None
and uid is None
and umask < 0):
self._posix_spawn(args, executable, env, restore_signals,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
return
orig_executable = executable
# For transferring possible exec failure from child to parent.
# Data format: "exception name:hex errno:description"
# Pickle is not used; it is complex and involves memory allocation.
errpipe_read, errpipe_write = os.pipe()
# errpipe_write must not be in the standard io 0, 1, or 2 fd range.
low_fds_to_close = []
while errpipe_write < 3:
low_fds_to_close.append(errpipe_write)
errpipe_write = os.dup(errpipe_write)
for low_fd in low_fds_to_close:
os.close(low_fd)
try:
try:
# We must avoid complex work that could involve
# malloc or free in the child process to avoid
# potential deadlocks, thus we do all this here.
# and pass it to fork_exec()
if env is not None:
env_list = []
for k, v in env.items():
k = os.fsencode(k)
if b'=' in k:
raise ValueError("illegal environment variable name")
env_list.append(k + b'=' + os.fsencode(v))
else:
env_list = None # Use execv instead of execve.
executable = os.fsencode(executable)
if os.path.dirname(executable):
executable_list = (executable,)
else:
# This matches the behavior of os._execvpe().
executable_list = tuple(
os.path.join(os.fsencode(dir), executable)
for dir in os.get_exec_path(env))
fds_to_keep = set(pass_fds)
fds_to_keep.add(errpipe_write)
self.pid = _posixsubprocess.fork_exec(
args, executable_list,
close_fds, tuple(sorted(map(int, fds_to_keep))),
cwd, env_list,
p2cread, p2cwrite, c2pread, c2pwrite,
errread, errwrite,
errpipe_read, errpipe_write,
restore_signals, start_new_session,
gid, gids, uid, umask,
preexec_fn)
self._child_created = True
finally:
# be sure the FD is closed no matter what
os.close(errpipe_write)
self._close_pipe_fds(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
# Wait for exec to fail or succeed; possibly raising an
# exception (limited in size)
errpipe_data = bytearray()
while True:
part = os.read(errpipe_read, 50000)
errpipe_data += part
if not part or len(errpipe_data) > 50000:
break
finally:
# be sure the FD is closed no matter what
os.close(errpipe_read)
if errpipe_data:
try:
pid, sts = os.waitpid(self.pid, 0)
if pid == self.pid:
self._handle_exitstatus(sts)
else:
self.returncode = sys.maxsize
except ChildProcessError:
pass
try:
exception_name, hex_errno, err_msg = (
errpipe_data.split(b':', 2))
# The encoding here should match the encoding
# written in by the subprocess implementations
# like _posixsubprocess
err_msg = err_msg.decode()
except ValueError:
exception_name = b'SubprocessError'
hex_errno = b'0'
err_msg = 'Bad exception data from child: {!r}'.format(
bytes(errpipe_data))
child_exception_type = getattr(
builtins, exception_name.decode('ascii'),
SubprocessError)
if issubclass(child_exception_type, OSError) and hex_errno:
errno_num = int(hex_errno, 16)
child_exec_never_called = (err_msg == "noexec")
if child_exec_never_called:
err_msg = ""
# The error must be from chdir(cwd).
err_filename = cwd
else:
err_filename = orig_executable
if errno_num != 0:
err_msg = os.strerror(errno_num)
raise child_exception_type(errno_num, err_msg, err_filename)
raise child_exception_type(err_msg)
def _handle_exitstatus(self, sts,
waitstatus_to_exitcode=os.waitstatus_to_exitcode,
_WIFSTOPPED=os.WIFSTOPPED,
_WSTOPSIG=os.WSTOPSIG):
"""All callers to this function MUST hold self._waitpid_lock."""
# This method is called (indirectly) by __del__, so it cannot
# refer to anything outside of its local scope.
if _WIFSTOPPED(sts):
self.returncode = -_WSTOPSIG(sts)
else:
self.returncode = waitstatus_to_exitcode(sts)
def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
_WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
"""Check if child process has terminated. Returns returncode
attribute.
This method is called by __del__, so it cannot reference anything
outside of the local scope (nor can any methods it calls).
"""
if self.returncode is None:
if not self._waitpid_lock.acquire(False):
# Something else is busy calling waitpid. Don't allow two
# at once. We know nothing yet.
return None
try:
if self.returncode is not None:
return self.returncode # Another thread waited.
pid, sts = _waitpid(self.pid, _WNOHANG)
if pid == self.pid:
self._handle_exitstatus(sts)
except OSError as e:
if _deadstate is not None:
self.returncode = _deadstate
elif e.errno == _ECHILD:
# This happens if SIGCLD is set to be ignored or
# waiting for child processes has otherwise been
# disabled for our process. This child is dead, we
# can't get the status.
# http://bugs.python.org/issue15756
self.returncode = 0
finally:
self._waitpid_lock.release()
return self.returncode
def _try_wait(self, wait_flags):
"""All callers to this function MUST hold self._waitpid_lock."""
try:
(pid, sts) = os.waitpid(self.pid, wait_flags)
except ChildProcessError:
# This happens if SIGCLD is set to be ignored or waiting
# for child processes has otherwise been disabled for our
# process. This child is dead, we can't get the status.
pid = self.pid
sts = 0
return (pid, sts)
def _wait(self, timeout):
"""Internal implementation of wait() on POSIX."""
if self.returncode is not None:
return self.returncode
if timeout is not None:
endtime = _time() + timeout
# Enter a busy loop if we have a timeout. This busy loop was
# cribbed from Lib/threading.py in Thread.wait() at r71065.
delay = 0.0005 # 500 us -> initial delay of 1 ms
while True:
if self._waitpid_lock.acquire(False):
try:
if self.returncode is not None:
break # Another thread waited.
(pid, sts) = self._try_wait(os.WNOHANG)
assert pid == self.pid or pid == 0
if pid == self.pid:
self._handle_exitstatus(sts)
break
finally:
self._waitpid_lock.release()
remaining = self._remaining_time(endtime)
if remaining <= 0:
raise TimeoutExpired(self.args, timeout)
delay = min(delay * 2, remaining, .05)
time.sleep(delay)
else:
while self.returncode is None:
with self._waitpid_lock:
if self.returncode is not None:
break # Another thread waited.
(pid, sts) = self._try_wait(0)
# Check the pid and loop as waitpid has been known to
# return 0 even without WNOHANG in odd situations.
# http://bugs.python.org/issue14396.
if pid == self.pid:
self._handle_exitstatus(sts)
return self.returncode
def _communicate(self, input, endtime, orig_timeout):
if self.stdin and not self._communication_started:
# Flush stdio buffer. This might block, if the user has
# been writing to .stdin in an uncontrolled fashion.
try:
self.stdin.flush()
except BrokenPipeError:
pass # communicate() must ignore BrokenPipeError.
if not input:
try:
self.stdin.close()
except BrokenPipeError:
pass # communicate() must ignore BrokenPipeError.
stdout = None
stderr = None
# Only create this mapping if we haven't already.
if not self._communication_started:
self._fileobj2output = {}
if self.stdout:
self._fileobj2output[self.stdout] = []
if self.stderr:
self._fileobj2output[self.stderr] = []
if self.stdout:
stdout = self._fileobj2output[self.stdout]
if self.stderr:
stderr = self._fileobj2output[self.stderr]
self._save_input(input)
if self._input:
input_view = memoryview(self._input)
with _PopenSelector() as selector:
if self.stdin and input:
selector.register(self.stdin, selectors.EVENT_WRITE)
if self.stdout and not self.stdout.closed:
selector.register(self.stdout, selectors.EVENT_READ)
if self.stderr and not self.stderr.closed:
selector.register(self.stderr, selectors.EVENT_READ)
while selector.get_map():
timeout = self._remaining_time(endtime)
if timeout is not None and timeout < 0:
self._check_timeout(endtime, orig_timeout,
stdout, stderr,
skip_check_and_raise=True)
raise RuntimeError( # Impossible :)
'_check_timeout(..., skip_check_and_raise=True) '
'failed to raise TimeoutExpired.')
ready = selector.select(timeout)
self._check_timeout(endtime, orig_timeout, stdout, stderr)
# XXX Rewrite these to use non-blocking I/O on the file
# objects; they are no longer using C stdio!
for key, events in ready:
if key.fileobj is self.stdin:
chunk = input_view[self._input_offset :
self._input_offset + _PIPE_BUF]
try:
self._input_offset += os.write(key.fd, chunk)
except BrokenPipeError:
selector.unregister(key.fileobj)
key.fileobj.close()
else:
if self._input_offset >= len(self._input):
selector.unregister(key.fileobj)
key.fileobj.close()
elif key.fileobj in (self.stdout, self.stderr):
data = os.read(key.fd, 32768)
if not data:
selector.unregister(key.fileobj)
key.fileobj.close()
self._fileobj2output[key.fileobj].append(data)
self.wait(timeout=self._remaining_time(endtime))
# All data exchanged. Translate lists into strings.
if stdout is not None:
stdout = b''.join(stdout)
if stderr is not None:
stderr = b''.join(stderr)
# Translate newlines, if requested.
# This also turns bytes into strings.
if self.text_mode:
if stdout is not None:
stdout = self._translate_newlines(stdout,
self.stdout.encoding,
self.stdout.errors)
if stderr is not None:
stderr = self._translate_newlines(stderr,
self.stderr.encoding,
self.stderr.errors)
return (stdout, stderr)
def _save_input(self, input):
# This method is called from the _communicate_with_*() methods
# so that if we time out while communicating, we can continue
# sending input if we retry.
if self.stdin and self._input is None:
self._input_offset = 0
self._input = input
if input is not None and self.text_mode:
self._input = self._input.encode(self.stdin.encoding,
self.stdin.errors)
def send_signal(self, sig):
"""Send a signal to the process."""
# bpo-38630: Polling reduces the risk of sending a signal to the
# wrong process if the process completed, the Popen.returncode
# attribute is still None, and the pid has been reassigned
# (recycled) to a new different process. This race condition can
# happens in two cases.
#
# Case 1. Thread A calls Popen.poll(), thread B calls
# Popen.send_signal(). In thread A, waitpid() succeed and returns
# the exit status. Thread B calls kill() because poll() in thread A
# did not set returncode yet. Calling poll() in thread B prevents
# the race condition thanks to Popen._waitpid_lock.
#
# Case 2. waitpid(pid, 0) has been called directly, without
# using Popen methods: returncode is still None is this case.
# Calling Popen.poll() will set returncode to a default value,
# since waitpid() fails with ProcessLookupError.
self.poll()
if self.returncode is not None:
# Skip signalling a process that we know has already died.
return
# The race condition can still happen if the race condition
# described above happens between the returncode test
# and the kill() call.
try:
os.kill(self.pid, sig)
except ProcessLookupError:
# Supress the race condition error; bpo-40550.
pass
def terminate(self):
"""Terminate the process with SIGTERM
"""
self.send_signal(signal.SIGTERM)
def kill(self):
"""Kill the process with SIGKILL
"""
self.send_signal(signal.SIGKILL)
def fetch_server_certificate (host, port):
def subproc(cmd):
from subprocess import Popen, PIPE, STDOUT
proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
status = proc.wait()
output = proc.stdout.read()
return status, output
def strip_to_x509_cert(certfile_contents, outfile=None):
m = re.search(br"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n"
br".*[\r]*^[-]+END CERTIFICATE[-]+)$",
certfile_contents, re.MULTILINE | re.DOTALL)
if not m:
return None
else:
tn = tempfile.mktemp()
with open(tn, "wb") as fp:
fp.write(m.group(1) + b"\n")
try:
tn2 = (outfile or tempfile.mktemp())
status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
(tn, tn2))
if status != 0:
raise RuntimeError('OpenSSL x509 failed with status %s and '
'output: %r' % (status, output))
with open(tn2, 'rb') as fp:
data = fp.read()
os.unlink(tn2)
return data
finally:
os.unlink(tn)
if sys.platform.startswith("win"):
tfile = tempfile.mktemp()
with open(tfile, "w") as fp:
fp.write("quit\n")
try:
status, output = subproc(
'openssl s_client -connect "%s:%s" -showcerts < "%s"' %
(host, port, tfile))
finally:
os.unlink(tfile)
else:
status, output = subproc(
'openssl s_client -connect "%s:%s" -showcerts < /dev/null' %
(host, port))
if status != 0:
raise RuntimeError('OpenSSL connect failed with status %s and '
'output: %r' % (status, output))
certtext = strip_to_x509_cert(output)
if not certtext:
raise ValueError("Invalid response received from server at %s:%s" %
(host, port))
return certtext | null |
186,317 | import argparse
import html
import http.server
import json
import mimetypes
import os
import re
import shlex
import shutil
import socket
import ssl
import subprocess
import tempfile
import urllib.parse
from xml.etree import ElementTree as ET
def annotate_assembly(ir_json, perf_annotations):
events = perf_annotations["annotations"]
asm = ir_json["cols"][-1]
assert asm["name"] == "Assembly"
for block in asm["blocks"]:
for instr in block["instrs"]:
instr_events = events.get(instr["address"])
if instr_events is not None:
instr["events"] = instr_events
def gen_html_from_json(ir_json, passes=None):
with open(TEMPLATE_FILENAME, "r") as f:
template = f.read()
if not passes:
passes = ["Source", "Assembly"]
template = template.replace("@EXPANDED@", json.dumps(passes))
return template.replace("@JSON@", json.dumps(ir_json))
def gen_html(args):
print("Generating HTML ...")
json_filename = args.json
with open(json_filename, "r") as f:
ir_json = json.load(f)
json_basename = os.path.basename(json_filename)
json_dir = os.path.dirname(os.path.realpath(json_filename))
if args.perf is not None:
with open(args.perf, "r") as f:
perf_annotations = json.load(f)
annotate_assembly(ir_json, perf_annotations)
perf_output = os.path.join(
json_dir, json_basename.replace(".json", ".perf.json")
)
with open(perf_output, "w+") as f:
json.dump(ir_json, f)
html_output = os.path.join(json_dir, json_basename.replace(".json", ".html"))
with open(html_output, "w+") as f:
f.write(gen_html_from_json(ir_json)) | null |
186,318 | import argparse
import html
import http.server
import json
import mimetypes
import os
import re
import shlex
import shutil
import socket
import ssl
import subprocess
import tempfile
import urllib.parse
from xml.etree import ElementTree as ET
def make_server_class(process_args):
if process_args.perf is not None:
with open(process_args.perf, "r") as f:
perf_summary = json.load(f)
else:
perf_summary = None
json_dir = process_args.json
class IRServer(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
handler = self.routes.get(self.path, self.__class__.do_404)
return handler(self)
def do_404(self):
if self.path.startswith("/function"):
return self.do_function()
self.wfile.write(f"<b>404 not found: {self.path}</b>".encode("utf-8"))
def do_index(self):
write_links(self.wfile, self.routes.keys())
def do_all(self):
function_names = sorted(
removesuffix(removeprefix(filename, "function_"), ".json")
for filename in os.listdir(json_dir)
if filename.endswith(".json") and not filename.endswith(".perf.json")
)
write_all(self.wfile, function_names)
def do_top(self):
if not perf_summary:
self.wfile.write(b"no performance data")
return
write_hottest(self.wfile, perf_summary)
def do_function(self):
match = re.findall(r"(function_.+).html", self.path)
if not match:
self.wfile.write(b"malformed function path")
return
basename = match[0]
with open(os.path.join(json_dir, f"{basename}.json"), "r") as f:
ir_json = json.load(f)
if perf_summary:
annotate_assembly(ir_json, perf_summary)
self.wfile.write(gen_html_from_json(ir_json).encode("utf-8"))
routes = {
"/": do_index,
"/all": do_all,
"/top": do_top,
}
return IRServer
class HTTPServerIPV6(http.server.HTTPServer):
address_family = socket.AF_INET6
def use_tls(self, certfile, keyfile=None):
self.socket = ssl.wrap_socket(
self.socket,
server_side=True,
certfile=certfile,
keyfile=keyfile,
ssl_version=ssl.PROTOCOL_TLS,
)
def gen_server(args):
host = args.host
port = args.port
server_address = (host, port)
IRServer = make_server_class(args)
httpd = HTTPServerIPV6(server_address, IRServer)
if args.tls_certfile:
httpd.use_tls(args.tls_certfile, args.tls_keyfile)
print(f"Serving traffic on {host}:{port} ...")
httpd.serve_forever() | null |
186,319 | import argparse
import html
import http.server
import json
import mimetypes
import os
import re
import shlex
import shutil
import socket
import ssl
import subprocess
import tempfile
import urllib.parse
from xml.etree import ElementTree as ET
def make_explorer_class(process_args, prod_hostname=None):
runtime = args.runtime
# args.host is for listen address, whereas prod_hostname is for CSP header.
# If it's set and non-empty, we're in a prod deployment.
security_headers = {
"X-Frame-Options": "SAMEORIGIN",
"X-XSS-Protection": "1; mode=block",
"X-Content-Type-Options": "nosniff",
}
if prod_hostname:
print("Running a prod deployment...")
# Don't set HSTS or CSP for local development
security_headers["Content-Security-Policy"] = (
f"default-src https://{prod_hostname}/vendor/ http://{prod_hostname}/vendor/ 'self'; "
"img-src data: 'self';"
"style-src 'self' 'unsafe-inline';"
"script-src 'self' 'unsafe-inline'"
)
security_headers[
"Strict-Transport-Security"
] = "max-age=31536000; includeSubDomains; preload"
use_strict_compiler = args.strict
class ExplorerServer(http.server.SimpleHTTPRequestHandler):
def _begin_response(self, code, content_type):
self.send_response(code)
self.send_header("Content-type", content_type)
for header, value in security_headers.items():
self.send_header(header, value)
def _get_post_params(self):
content_length = int(self.headers["Content-Length"])
post_data = self.rfile.read(content_length)
bytes_params = urllib.parse.parse_qs(post_data)
str_params = {
param.decode("utf-8"): [value.decode("utf-8") for value in values]
for param, values in bytes_params.items()
}
return str_params
def do_GET(self):
handler = self.routes.get(self.path, self.__class__.do_404)
return handler(self)
def do_POST(self):
self.params = self._get_post_params()
handler = self.post_routes.get(self.path, self.__class__.do_404)
return handler(self)
def do_404(self):
try:
static_file = os.path.join(TEMPLATE_DIR, self.path.lstrip("/"))
content_type = mimetypes.guess_type(static_file)[0] or "text/html"
with open(static_file, "rb") as f:
self._begin_response(200, content_type)
self.end_headers()
self.wfile.write(f.read())
except FileNotFoundError:
self._begin_response(404, "text/html")
self.end_headers()
self.wfile.write(f"<b>404 not found: {self.path}</b>".encode("utf-8"))
def do_compile_get(self):
self._begin_response(200, "text/html")
self.end_headers()
self.wfile.write(b"Waiting for input...")
def do_helth(self):
self._begin_response(200, "text/plain")
self.end_headers()
self.wfile.write(b"I'm not dead yet")
def do_explore(self):
self._begin_response(200, "text/html")
self.end_headers()
with open(os.path.join(TEMPLATE_DIR, "explorer.html.in"), "r") as f:
template = f.read()
try:
version_cmd = run(
[runtime, "-c", "import sys; print(sys.version)"],
capture_output=True,
)
version = version_cmd.stdout.partition("\n")[0]
except Exception:
version = "unknown"
template = template.replace("@VERSION@", version)
self.wfile.write(template.encode("utf-8"))
def _render_options(self, *options):
result = []
for option in options:
result.append("-X")
if isinstance(option, str):
result.append(option)
else:
result.append("=".join(option))
return result
def do_compile_post(self):
self._begin_response(200, "text/html")
self.end_headers()
passes = self.params["passes"]
user_code = self.params["code"][0]
use_static_python = (
"static-python" in self.params
and self.params["static-python"][0] == "on"
)
if use_strict_compiler and not use_static_python:
# Static implies strict
# TODO(T120976390): Put this after future imports
user_code = "import __strict__\n" + user_code
asm_syntax = self.params["asm-syntax"][0]
with tempfile.TemporaryDirectory() as tmp:
lib_name = "explorer_lib"
with open(os.path.join(tmp, f"{lib_name}.py"), "w+") as f:
f.write(user_code)
main_code_path = os.path.join(tmp, "main.py")
with open(main_code_path, "w+") as f:
f.write(
f"from {lib_name} import *\n"
"import cinderjit\n"
"cinderjit.disable()\n"
)
jitlist_path = os.path.join(tmp, "jitlist.txt")
with open(jitlist_path, "w+") as f:
f.write(f"{lib_name}:test\n")
json_dir = os.path.join(tmp, "json")
jit_options = self._render_options(
"jit",
"jit-enable-jit-list-wildcards",
"jit-enable-hir-inliner",
"jit-shadow-frame",
("jit-list-file", jitlist_path),
("jit-dump-hir-passes-json", json_dir),
("jit-asm-syntax", asm_syntax),
"usepycompiler",
)
timeout = ["timeout", "--signal=KILL", f"{TIMEOUT_SEC}s"]
if use_static_python or use_strict_compiler:
jit_options += ["-X", "install-strict-loader"]
try:
run(
[*timeout, runtime, *jit_options, main_code_path],
capture_output=True,
cwd=tmp,
)
except subprocess.CalledProcessError as e:
if e.returncode == -9:
self.wfile.write(b"Command timed out")
return
if "SyntaxError" in e.stderr or "StrictModuleError" in e.stderr:
escaped = html.escape(e.stderr)
self.wfile.write(f"<pre>{escaped}</pre>".encode("utf-8"))
return
print(e.stderr)
self.wfile.write(b"Internal server error")
return
# TODO(emacs): Render more than one function
files = os.listdir(json_dir)
if not files:
self.wfile.write(
b"No compiled code found. Did you remember to name your function <code>test</code>?"
)
return
func_json_filename = files[0]
with open(os.path.join(json_dir, func_json_filename), "r") as f:
ir_json = json.load(f)
ir_json["cols"] = [col for col in ir_json["cols"] if col["name"] in passes]
generated_html = gen_html_from_json(ir_json, passes)
with_code = generated_html.replace("@CODE@", user_code)
self.wfile.write(with_code.encode("utf-8"))
routes = {
"/": do_explore,
"/compile": do_compile_get,
"/helth": do_helth,
}
post_routes = {
"/compile": do_compile_post,
}
return ExplorerServer
class HTTPServerIPV6(http.server.HTTPServer):
address_family = socket.AF_INET6
def use_tls(self, certfile, keyfile=None):
self.socket = ssl.wrap_socket(
self.socket,
server_side=True,
certfile=certfile,
keyfile=keyfile,
ssl_version=ssl.PROTOCOL_TLS,
)
def gen_explorer(args):
host = args.host
port = args.port
explorer_address = (host, port)
prod_hostname = os.getenv("CINDER_EXPLORER_HOSTNAME")
IRServer = make_explorer_class(args, prod_hostname)
httpd = HTTPServerIPV6(explorer_address, IRServer)
if args.tls_certfile:
httpd.use_tls(args.tls_certfile, args.tls_keyfile)
print(f"Serving traffic on {host}:{port} ...")
httpd.serve_forever() | null |
186,320 | import argparse
import html
import http.server
import json
import mimetypes
import os
import re
import shlex
import shutil
import socket
import ssl
import subprocess
import tempfile
import urllib.parse
from xml.etree import ElementTree as ET
def executable_file(arg):
if not shutil.which(arg, mode=os.F_OK | os.X_OK):
parser.error(f"The file {arg} does not exist or is not an executable file")
return arg | null |
186,321 | import argparse
import html
import http.server
import json
import mimetypes
import os
import re
import shlex
import shutil
import socket
import ssl
import subprocess
import tempfile
import urllib.parse
from xml.etree import ElementTree as ET
def readable_file(arg):
if not shutil.which(arg, mode=os.F_OK):
parser.error(f"The file {arg} does not exist or is not a readable file")
return arg
def add_server_args(parser):
parser.add_argument(
"--host",
type=str,
help="Listen address for serving traffic",
default="::",
)
parser.add_argument(
"--port",
type=int,
help="Port for serving traffic",
default=8081,
)
parser.add_argument(
"--tls-certfile",
type=readable_file,
help="Path to TLS certificate file. If .crt, also provide --tls-keyfile.",
default=None,
)
parser.add_argument(
"--tls-keyfile",
type=readable_file,
help="Path to TLS key file. Use with --tls-certfile.",
default=None,
) | null |
186,326 | import os.path
import subprocess
import sys
import sysconfig
IGNORED_EXTENSION = "_ctypes_test"
def check_library(library, dynamic=False):
nm_output = get_exported_symbols(library, dynamic)
smelly_symbols, python_symbols = get_smelly_symbols(nm_output)
if not smelly_symbols:
print(f"OK: no smelly symbol found ({len(python_symbols)} Python symbols)")
return 0
print()
smelly_symbols.sort()
for symbol in smelly_symbols:
print("Smelly symbol: %s" % symbol)
print()
print("ERROR: Found %s smelly symbols!" % len(smelly_symbols))
return len(smelly_symbols)
def check_extensions():
print(__file__)
# This assumes pybuilddir.txt is in same directory as pyconfig.h.
# In the case of out-of-tree builds, we can't assume pybuilddir.txt is
# in the source folder.
config_dir = os.path.dirname(sysconfig.get_config_h_filename())
filename = os.path.join(config_dir, "pybuilddir.txt")
try:
with open(filename, encoding="utf-8") as fp:
pybuilddir = fp.readline()
except FileNotFoundError:
print(f"Cannot check extensions because {filename} does not exist")
return True
print(f"Check extension modules from {pybuilddir} directory")
builddir = os.path.join(config_dir, pybuilddir)
nsymbol = 0
for name in os.listdir(builddir):
if not name.endswith(".so"):
continue
if IGNORED_EXTENSION in name:
print()
print(f"Ignore extension: {name}")
continue
print()
filename = os.path.join(builddir, name)
nsymbol += check_library(filename, dynamic=True)
return nsymbol | null |
186,342 | import argparse
import os
import re
import shutil
import subprocess
import sys
from typing import List, NamedTuple
def create_port_branch(args):
def generate_upstream_patches(args):
def parse_args():
args = argparse.ArgumentParser()
subparsers = args.add_subparsers(required=True)
create = subparsers.add_parser(
"create_branch", help="Create initial Cinder 3.10 branch locally"
)
create.set_defaults(func=create_port_branch)
create.add_argument(
"--cinder-head",
default="origin/cinder/3.8",
help="Cinder commit to use as the head",
)
create.add_argument(
"--cinder-fork-point",
default="origin/3.8",
help="Upstream commit Cinder was forked from",
)
create.add_argument(
"--upstream-head",
default="origin/3.10",
help="Upstream commit to merge into Cinder",
)
create.add_argument("--branch-name", required=True, help="Name of branch to create")
patches = subparsers.add_parser(
"generate_upstream_patches",
help="Generate a directory of patches from Cinder 3.8",
)
patches.add_argument(
"--output", "-o", required=True, help="Directory to write patches to"
)
patches.add_argument(
"--all",
"-a",
action="store_true",
help="Include all patches, not just patches to upstream files",
)
patches.set_defaults(func=generate_upstream_patches)
return args.parse_args() | null |
186,343 | import os
import sys
import json
from urllib.request import urlopen
from html.entities import html5
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
*, cafile=None, capath=None, cadefault=False, context=None):
'''Open the URL url, which can be either a string or a Request object.
*data* must be an object specifying additional data to be sent to
the server, or None if no such data is needed. See Request for
details.
urllib.request module uses HTTP/1.1 and includes a "Connection:close"
header in its HTTP requests.
The optional *timeout* parameter specifies a timeout in seconds for
blocking operations like the connection attempt (if not specified, the
global default timeout setting will be used). This only works for HTTP,
HTTPS and FTP connections.
If *context* is specified, it must be a ssl.SSLContext instance describing
the various SSL options. See HTTPSConnection for more details.
The optional *cafile* and *capath* parameters specify a set of trusted CA
certificates for HTTPS requests. cafile should point to a single file
containing a bundle of CA certificates, whereas capath should point to a
directory of hashed certificate files. More information can be found in
ssl.SSLContext.load_verify_locations().
The *cadefault* parameter is ignored.
This function always returns an object which can work as a
context manager and has the properties url, headers, and status.
See urllib.response.addinfourl for more detail on these properties.
For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse
object slightly modified. In addition to the three new methods above, the
msg attribute contains the same information as the reason attribute ---
the reason phrase returned by the server --- instead of the response
headers as it is specified in the documentation for HTTPResponse.
For FTP, file, and data URLs and requests explicitly handled by legacy
URLopener and FancyURLopener classes, this function returns a
urllib.response.addinfourl object.
Note that None may be returned if no handler handles the request (though
the default installed global OpenerDirector uses UnknownHandler to ensure
this never happens).
In addition, if proxy settings are detected (for example, when a *_proxy
environment variable like http_proxy is set), ProxyHandler is default
installed and makes sure the requests are handled through the proxy.
'''
global _opener
if cafile or capath or cadefault:
import warnings
warnings.warn("cafile, capath and cadefault are deprecated, use a "
"custom context instead.", DeprecationWarning, 2)
if context is not None:
raise ValueError(
"You can't pass both context and any of cafile, capath, and "
"cadefault"
)
if not _have_ssl:
raise ValueError('SSL support not available')
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
cafile=cafile,
capath=capath)
# send ALPN extension to indicate HTTP/1.1 protocol
context.set_alpn_protocols(['http/1.1'])
https_handler = HTTPSHandler(context=context)
opener = build_opener(https_handler)
elif context:
https_handler = HTTPSHandler(context=context)
opener = build_opener(https_handler)
elif _opener is None:
_opener = opener = build_opener()
else:
opener = _opener
return opener.open(url, data, timeout)
The provided code snippet includes necessary dependencies for implementing the `get_json` function. Write a Python function `def get_json(url)` to solve the following problem:
Download the json file from the url and returns a decoded object.
Here is the function:
def get_json(url):
"""Download the json file from the url and returns a decoded object."""
with urlopen(url) as f:
data = f.read().decode('utf-8')
return json.loads(data) | Download the json file from the url and returns a decoded object. |
186,348 | from functools import partial
from pathlib import Path
import dataclasses
import subprocess
import sysconfig
import argparse
import textwrap
import difflib
import shutil
import sys
import os
import os.path
import io
import re
import csv
class Manifest:
"""Collection of `ABIItem`s forming the stable ABI/limited API."""
kind = 'manifest'
contents: dict = dataclasses.field(default_factory=dict)
def add(self, item):
if item.name in self.contents:
# We assume that stable ABI items do not share names,
# even if they're different kinds (e.g. function vs. macro).
raise ValueError(f'duplicate ABI item {item.name}')
self.contents[item.name] = item
def feature_defines(self):
"""Return all feature defines which affect what's available
These are e.g. HAVE_FORK and MS_WINDOWS.
"""
return set(item.ifdef for item in self.contents.values()) - {None}
def select(self, kinds, *, include_abi_only=True, ifdef=None):
"""Yield selected items of the manifest
kinds: set of requested kinds, e.g. {'function', 'macro'}
include_abi_only: if True (default), include all items of the
stable ABI.
If False, include only items from the limited API
(i.e. items people should use today)
ifdef: set of feature defines (e.g. {'HAVE_FORK', 'MS_WINDOWS'}).
If None (default), items are not filtered by this. (This is
different from the empty set, which filters out all such
conditional items.)
"""
for name, item in sorted(self.contents.items()):
if item.kind not in kinds:
continue
if item.abi_only and not include_abi_only:
continue
if (ifdef is not None
and item.ifdef is not None
and item.ifdef not in ifdef):
continue
yield item
def dump(self):
"""Yield lines to recreate the manifest file (sans comments/newlines)"""
# Recursive in preparation for struct member & function argument nodes
for item in self.contents.values():
yield from item.dump(indent=0)
class ABIItem:
"""Information on one item (function, macro, struct, etc.)"""
kind: str
name: str
added: str = None
contents: list = dataclasses.field(default_factory=list)
abi_only: bool = False
ifdef: str = None
KINDS = frozenset({
'struct', 'function', 'macro', 'data', 'const', 'typedef',
})
def dump(self, indent=0):
yield f"{' ' * indent}{self.kind} {self.name}"
if self.added:
yield f"{' ' * (indent+1)}added {self.added}"
if self.ifdef:
yield f"{' ' * (indent+1)}ifdef {self.ifdef}"
if self.abi_only:
yield f"{' ' * (indent+1)}abi_only"
The provided code snippet includes necessary dependencies for implementing the `parse_manifest` function. Write a Python function `def parse_manifest(file)` to solve the following problem:
Parse the given file (iterable of lines) to a Manifest
Here is the function:
def parse_manifest(file):
"""Parse the given file (iterable of lines) to a Manifest"""
LINE_RE = re.compile('(?P<indent>[ ]*)(?P<kind>[^ ]+)[ ]*(?P<content>.*)')
manifest = Manifest()
# parents of currently processed line, each with its indentation level
levels = [(manifest, -1)]
def raise_error(msg):
raise SyntaxError(f'line {lineno}: {msg}')
for lineno, line in enumerate(file, start=1):
line, sep, comment = line.partition('#')
line = line.rstrip()
if not line:
continue
match = LINE_RE.fullmatch(line)
if not match:
raise_error(f'invalid syntax: {line}')
level = len(match['indent'])
kind = match['kind']
content = match['content']
while level <= levels[-1][1]:
levels.pop()
parent = levels[-1][0]
entry = None
if kind in ABIItem.KINDS:
if parent.kind not in {'manifest'}:
raise_error(f'{kind} cannot go in {parent.kind}')
entry = ABIItem(kind, content)
parent.add(entry)
elif kind in {'added', 'ifdef'}:
if parent.kind not in ABIItem.KINDS:
raise_error(f'{kind} cannot go in {parent.kind}')
setattr(parent, kind, content)
elif kind in {'abi_only'}:
if parent.kind not in {'function', 'data'}:
raise_error(f'{kind} cannot go in {parent.kind}')
parent.abi_only = True
else:
raise_error(f"unknown kind {kind!r}")
levels.append((entry, level))
return manifest | Parse the given file (iterable of lines) to a Manifest |
186,349 | from functools import partial
from pathlib import Path
import dataclasses
import subprocess
import sysconfig
import argparse
import textwrap
import difflib
import shutil
import sys
import os
import os.path
import io
import re
import csv
generators = []
The provided code snippet includes necessary dependencies for implementing the `generator` function. Write a Python function `def generator(var_name, default_path)` to solve the following problem:
Decorates a file generator: function that writes to a file
Here is the function:
def generator(var_name, default_path):
"""Decorates a file generator: function that writes to a file"""
def _decorator(func):
func.var_name = var_name
func.arg_name = '--' + var_name.replace('_', '-')
func.default_path = default_path
generators.append(func)
return func
return _decorator | Decorates a file generator: function that writes to a file |
186,350 | from functools import partial
from pathlib import Path
import dataclasses
import subprocess
import sysconfig
import argparse
import textwrap
import difflib
import shutil
import sys
import os
import os.path
import io
import re
import csv
class partial:
"""New function with partial application of the given arguments
and keywords.
"""
__slots__ = "func", "args", "keywords", "__dict__", "__weakref__"
def __new__(cls, func, /, *args, **keywords):
if not callable(func):
raise TypeError("the first argument must be callable")
if hasattr(func, "func"):
args = func.args + args
keywords = {**func.keywords, **keywords}
func = func.func
self = super(partial, cls).__new__(cls)
self.func = func
self.args = args
self.keywords = keywords
return self
def __call__(self, /, *args, **keywords):
keywords = {**self.keywords, **keywords}
return self.func(*self.args, *args, **keywords)
def __repr__(self):
qualname = type(self).__qualname__
args = [repr(self.func)]
args.extend(repr(x) for x in self.args)
args.extend(f"{k}={v!r}" for (k, v) in self.keywords.items())
if type(self).__module__ == "functools":
return f"functools.{qualname}({', '.join(args)})"
return f"{qualname}({', '.join(args)})"
def __reduce__(self):
return type(self), (self.func,), (self.func, self.args,
self.keywords or None, self.__dict__ or None)
def __setstate__(self, state):
if not isinstance(state, tuple):
raise TypeError("argument to __setstate__ must be a tuple")
if len(state) != 4:
raise TypeError(f"expected 4 items in state, got {len(state)}")
func, args, kwds, namespace = state
if (not callable(func) or not isinstance(args, tuple) or
(kwds is not None and not isinstance(kwds, dict)) or
(namespace is not None and not isinstance(namespace, dict))):
raise TypeError("invalid partial state")
args = tuple(args) # just in case it's a subclass
if kwds is None:
kwds = {}
elif type(kwds) is not dict: # XXX does it need to be *exactly* dict?
kwds = dict(kwds)
if namespace is None:
namespace = {}
self.__dict__ = namespace
self.func = func
self.args = args
self.keywords = kwds
The provided code snippet includes necessary dependencies for implementing the `gen_python3dll` function. Write a Python function `def gen_python3dll(manifest, args, outfile)` to solve the following problem:
Generate/check the source for the Windows stable ABI library
Here is the function:
def gen_python3dll(manifest, args, outfile):
"""Generate/check the source for the Windows stable ABI library"""
write = partial(print, file=outfile)
write(textwrap.dedent(r"""
/* Re-export stable Python ABI */
/* Generated by Tools/scripts/stable_abi.py */
#ifdef _M_IX86
#define DECORATE "_"
#else
#define DECORATE
#endif
#define EXPORT_FUNC(name) \
__pragma(comment(linker, "/EXPORT:" DECORATE #name "=" PYTHON_DLL_NAME "." #name))
#define EXPORT_DATA(name) \
__pragma(comment(linker, "/EXPORT:" DECORATE #name "=" PYTHON_DLL_NAME "." #name ",DATA"))
"""))
def sort_key(item):
return item.name.lower()
for item in sorted(
manifest.select(
{'function'}, include_abi_only=True, ifdef={'MS_WINDOWS'}),
key=sort_key):
write(f'EXPORT_FUNC({item.name})')
write()
for item in sorted(
manifest.select(
{'data'}, include_abi_only=True, ifdef={'MS_WINDOWS'}),
key=sort_key):
write(f'EXPORT_DATA({item.name})') | Generate/check the source for the Windows stable ABI library |
186,351 | from functools import partial
from pathlib import Path
import dataclasses
import subprocess
import sysconfig
import argparse
import textwrap
import difflib
import shutil
import sys
import os
import os.path
import io
import re
import csv
IFDEF_DOC_NOTES = {
'MS_WINDOWS': 'on Windows',
'HAVE_FORK': 'on platforms with fork()',
'USE_STACKCHECK': 'on platforms with USE_STACKCHECK',
}
REST_ROLES = {
'function': 'function',
'data': 'var',
'struct': 'type',
'macro': 'macro',
# 'const': 'const', # all undocumented
'typedef': 'type',
}
The provided code snippet includes necessary dependencies for implementing the `gen_doc_annotations` function. Write a Python function `def gen_doc_annotations(manifest, args, outfile)` to solve the following problem:
Generate/check the stable ABI list for documentation annotations
Here is the function:
def gen_doc_annotations(manifest, args, outfile):
"""Generate/check the stable ABI list for documentation annotations"""
writer = csv.DictWriter(
outfile, ['role', 'name', 'added', 'ifdef_note'], lineterminator='\n')
writer.writeheader()
for item in manifest.select(REST_ROLES.keys(), include_abi_only=False):
if item.ifdef:
ifdef_note = IFDEF_DOC_NOTES[item.ifdef]
else:
ifdef_note = None
writer.writerow({
'role': REST_ROLES[item.kind],
'name': item.name,
'added': item.added,
'ifdef_note': ifdef_note}) | Generate/check the stable ABI list for documentation annotations |
186,352 | from functools import partial
from pathlib import Path
import dataclasses
import subprocess
import sysconfig
import argparse
import textwrap
import difflib
import shutil
import sys
import os
import os.path
import io
import re
import csv
The provided code snippet includes necessary dependencies for implementing the `generate_or_check` function. Write a Python function `def generate_or_check(manifest, args, path, func)` to solve the following problem:
Generate/check a file with a single generator Return True if successful; False if a comparison failed.
Here is the function:
def generate_or_check(manifest, args, path, func):
"""Generate/check a file with a single generator
Return True if successful; False if a comparison failed.
"""
outfile = io.StringIO()
func(manifest, args, outfile)
generated = outfile.getvalue()
existing = path.read_text()
if generated != existing:
if args.generate:
path.write_text(generated)
else:
print(f'File {path} differs from expected!')
diff = difflib.unified_diff(
generated.splitlines(), existing.splitlines(),
str(path), '<expected>',
lineterm='',
)
for line in diff:
print(line)
return False
return True | Generate/check a file with a single generator Return True if successful; False if a comparison failed. |
186,353 | from functools import partial
from pathlib import Path
import dataclasses
import subprocess
import sysconfig
import argparse
import textwrap
import difflib
import shutil
import sys
import os
import os.path
import io
import re
import csv
def _report_unexpected_items(items, msg):
"""If there are any `items`, report them using "msg" and return false"""
if items:
print(msg, file=sys.stderr)
for item in sorted(items):
print(' -', item, file=sys.stderr)
return False
return True
def binutils_check_library(manifest, library, expected_symbols, dynamic):
"""Check that library exports all expected_symbols"""
available_symbols = set(binutils_get_exported_symbols(library, dynamic))
missing_symbols = expected_symbols - available_symbols
if missing_symbols:
print(textwrap.dedent(f"""\
Some symbols from the limited API are missing from {library}:
{', '.join(missing_symbols)}
This error means that there are some missing symbols among the
ones exported in the library.
This normally means that some symbol, function implementation or
a prototype belonging to a symbol in the limited API has been
deleted or is missing.
"""), file=sys.stderr)
return False
return True
def gcc_get_limited_api_macros(headers):
"""Get all limited API macros from headers.
Runs the preprocessor over all the header files in "Include" setting
"-DPy_LIMITED_API" to the correct value for the running version of the
interpreter and extracting all macro definitions (via adding -dM to the
compiler arguments).
Requires Python built with a GCC-compatible compiler. (clang might work)
"""
api_hexversion = sys.version_info.major << 24 | sys.version_info.minor << 16
preprocesor_output_with_macros = subprocess.check_output(
sysconfig.get_config_var("CC").split()
+ [
# Prevent the expansion of the exported macros so we can
# capture them later
"-DSIZEOF_WCHAR_T=4", # The actual value is not important
f"-DPy_LIMITED_API={api_hexversion}",
"-I.",
"-I./Include",
"-dM",
"-E",
]
+ [str(file) for file in headers],
text=True,
)
return {
target
for target in re.findall(
r"#define (\w+)", preprocesor_output_with_macros
)
}
def gcc_get_limited_api_definitions(headers):
"""Get all limited API definitions from headers.
Run the preprocessor over all the header files in "Include" setting
"-DPy_LIMITED_API" to the correct value for the running version of the
interpreter.
The limited API symbols will be extracted from the output of this command
as it includes the prototypes and definitions of all the exported symbols
that are in the limited api.
This function does *NOT* extract the macros defined on the limited API
Requires Python built with a GCC-compatible compiler. (clang might work)
"""
api_hexversion = sys.version_info.major << 24 | sys.version_info.minor << 16
preprocesor_output = subprocess.check_output(
sysconfig.get_config_var("CC").split()
+ [
# Prevent the expansion of the exported macros so we can capture
# them later
"-DPyAPI_FUNC=__PyAPI_FUNC",
"-DPyAPI_DATA=__PyAPI_DATA",
"-DEXPORT_DATA=__EXPORT_DATA",
"-D_Py_NO_RETURN=",
"-DSIZEOF_WCHAR_T=4", # The actual value is not important
f"-DPy_LIMITED_API={api_hexversion}",
"-I.",
"-I./Include",
"-E",
]
+ [str(file) for file in headers],
text=True,
stderr=subprocess.DEVNULL,
)
stable_functions = set(
re.findall(r"__PyAPI_FUNC\(.*?\)\s*(.*?)\s*\(", preprocesor_output)
)
stable_exported_data = set(
re.findall(r"__EXPORT_DATA\((.*?)\)", preprocesor_output)
)
stable_data = set(
re.findall(r"__PyAPI_DATA\(.*?\)[\s\*\(]*([^);]*)\)?.*;", preprocesor_output)
)
return stable_data | stable_exported_data | stable_functions
The provided code snippet includes necessary dependencies for implementing the `do_unixy_check` function. Write a Python function `def do_unixy_check(manifest, args)` to solve the following problem:
Check headers & library using "Unixy" tools (GCC/clang, binutils)
Here is the function:
def do_unixy_check(manifest, args):
"""Check headers & library using "Unixy" tools (GCC/clang, binutils)"""
okay = True
# Get all macros first: we'll need feature macros like HAVE_FORK and
# MS_WINDOWS for everything else
present_macros = gcc_get_limited_api_macros(['Include/Python.h'])
feature_defines = manifest.feature_defines & present_macros
# Check that we have all needed macros
expected_macros = set(
item.name for item in manifest.select({'macro'})
)
missing_macros = expected_macros - present_macros
okay &= _report_unexpected_items(
missing_macros,
'Some macros from are not defined from "Include/Python.h"'
+ 'with Py_LIMITED_API:')
expected_symbols = set(item.name for item in manifest.select(
{'function', 'data'}, include_abi_only=True, ifdef=feature_defines,
))
# Check the static library (*.a)
LIBRARY = sysconfig.get_config_var("LIBRARY")
if not LIBRARY:
raise Exception("failed to get LIBRARY variable from sysconfig")
if os.path.exists(LIBRARY):
okay &= binutils_check_library(
manifest, LIBRARY, expected_symbols, dynamic=False)
# Check the dynamic library (*.so)
LDLIBRARY = sysconfig.get_config_var("LDLIBRARY")
if not LDLIBRARY:
raise Exception("failed to get LDLIBRARY variable from sysconfig")
okay &= binutils_check_library(
manifest, LDLIBRARY, expected_symbols, dynamic=False)
# Check definitions in the header files
expected_defs = set(item.name for item in manifest.select(
{'function', 'data'}, include_abi_only=False, ifdef=feature_defines,
))
found_defs = gcc_get_limited_api_definitions(['Include/Python.h'])
missing_defs = expected_defs - found_defs
okay &= _report_unexpected_items(
missing_defs,
'Some expected declarations were not declared in '
+ '"Include/Python.h" with Py_LIMITED_API:')
# Some Limited API macros are defined in terms of private symbols.
# These are not part of Limited API (even though they're defined with
# Py_LIMITED_API). They must be part of the Stable ABI, though.
private_symbols = {n for n in expected_symbols if n.startswith('_')}
extra_defs = found_defs - expected_defs - private_symbols
okay &= _report_unexpected_items(
extra_defs,
'Some extra declarations were found in "Include/Python.h" '
+ 'with Py_LIMITED_API:')
return okay | Check headers & library using "Unixy" tools (GCC/clang, binutils) |
186,354 | from functools import partial
from pathlib import Path
import dataclasses
import subprocess
import sysconfig
import argparse
import textwrap
import difflib
import shutil
import sys
import os
import os.path
import io
import re
import csv
The provided code snippet includes necessary dependencies for implementing the `check_private_names` function. Write a Python function `def check_private_names(manifest)` to solve the following problem:
Ensure limited API doesn't contain private names Names prefixed by an underscore are private by definition.
Here is the function:
def check_private_names(manifest):
"""Ensure limited API doesn't contain private names
Names prefixed by an underscore are private by definition.
"""
for name, item in manifest.contents.items():
if name.startswith('_') and not item.abi_only:
raise ValueError(
f'`{name}` is private (underscore-prefixed) and should be '
+ 'removed from the stable ABI list or or marked `abi_only`') | Ensure limited API doesn't contain private names Names prefixed by an underscore are private by definition. |
186,357 | import argparse
import logging
import os
import re
import shlex
import subprocess
import sys
import tempfile
JITLIST_FILENAME = "jitlist.txt"
def write_jitlist(jitlist):
with open(JITLIST_FILENAME, "w") as file:
for func in jitlist:
print(func, file=file)
def read_jitlist(jit_list_file):
with open(jit_list_file, "r") as file:
return [line.strip() for line in file.readlines()]
def run_with_jitlist(command, jitlist):
write_jitlist(jitlist)
environ = dict(os.environ)
environ.update({"PYTHONJITLISTFILE": JITLIST_FILENAME, "IS_BISECTING_JITLIST": "1"})
logging.debug(
f"Running '{shlex.join(command)}' with jitlist of size {len(jitlist)}"
)
proc = subprocess.run(
command,
env=environ,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding=sys.stdout.encoding,
)
logging.debug(
f"Finished with exit status {proc.returncode}\n\nstdout:\n{proc.stdout}\n\nstderr:\n{proc.stderr}"
)
return proc.returncode == 0
def get_compiled_funcs(command):
environ = dict(os.environ)
environ.update({"PYTHONJITDEBUG": "1"})
logging.info("Generating initial jit-list")
proc = subprocess.run(
command,
env=environ,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
encoding=sys.stderr.encoding,
)
if proc.returncode == 0:
sys.exit(f"Command succeeded during jit-list generation")
funcs = set()
for line in proc.stderr.splitlines():
m = COMPILED_FUNC_RE.search(line)
if m is None:
continue
funcs.add(m[1])
if len(funcs) == 0:
sys.exit(f"No compiled functions found")
# We want a deterministic jitlist, unaffected by the order functions happen
# to be compiled in.
return sorted(funcs)
def bisect_impl(command, fixed, jitlist, indent=""):
logging.info(f"{indent}step fixed[{len(fixed)}] and jitlist[{len(jitlist)}]")
while len(jitlist) > 1:
logging.info(f"{indent}{len(fixed) + len(jitlist)} candidates")
left, right = split_list(jitlist)
if not run_with_jitlist(command, fixed + left):
jitlist = left
continue
if not run_with_jitlist(command, fixed + right):
jitlist = right
continue
# We need something from both halves to trigger the failure. Try
# holding each half fixed and bisecting the other half to reduce the
# candidates.
new_right = bisect_impl(command, fixed + left, right, indent + "< ")
new_left = bisect_impl(command, fixed + new_right, left, indent + "> ")
return new_left + new_right
return jitlist
def run_bisect(command, jit_list_file):
prev_arg = ""
for arg in command:
if arg.startswith("-Xjit-log-file") or (
prev_arg == "-X" and arg.startswith("jit-log-file")
):
sys.exit(
"Your command includes -X jit-log-file, which is incompatible "
"with this script. Please remove it and try again."
)
prev_arg = arg
if jit_list_file is None:
jitlist = get_compiled_funcs(command)
else:
jitlist = read_jitlist(jit_list_file)
logging.info("Verifying jit-list")
if run_with_jitlist(command, jitlist):
sys.exit(f"Command succeeded with full jit-list")
if not run_with_jitlist(command, []):
sys.exit(f"Command failed with empty jit-list")
jitlist = bisect_impl(command, [], jitlist)
write_jitlist(jitlist)
print(f"Bisect finished with {len(jitlist)} functions in {JITLIST_FILENAME}") | null |
186,358 | import argparse
import logging
import os
import re
import shlex
import subprocess
import sys
import tempfile
def parse_args():
parser = argparse.ArgumentParser(
description="When given a command that fails with the jit enabled (including -X jit as appropriate), bisects to find a minimal jit-list that preserves the failure"
)
parser.add_argument(
"--verbose", "-v", action="store_true", help="Enable verbose logging"
)
parser.add_argument("--initial-jit-list-file", help="initial jitlist file (default: auto-detect the initial jit list)", default=None)
parser.add_argument("command", nargs=argparse.REMAINDER)
return parser.parse_args() | null |
186,369 | import sys, re
def generate_typeslots(out=sys.stdout):
out.write("/* Generated by typeslots.py */\n")
res = {}
for line in sys.stdin:
m = re.match("#define Py_([a-z_]+) ([0-9]+)", line)
if not m:
continue
member = m.group(1)
if member.startswith("tp_"):
member = f'{{-1, offsetof(PyTypeObject, {member})}}'
elif member.startswith("am_"):
member = (f'{{offsetof(PyAsyncMethods, {member}),'+
' offsetof(PyTypeObject, tp_as_async)}')
elif member.startswith("nb_"):
member = (f'{{offsetof(PyNumberMethods, {member}),'+
' offsetof(PyTypeObject, tp_as_number)}')
elif member.startswith("mp_"):
member = (f'{{offsetof(PyMappingMethods, {member}),'+
' offsetof(PyTypeObject, tp_as_mapping)}')
elif member.startswith("sq_"):
member = (f'{{offsetof(PySequenceMethods, {member}),'+
' offsetof(PyTypeObject, tp_as_sequence)}')
elif member.startswith("bf_"):
member = (f'{{offsetof(PyBufferProcs, {member}),'+
' offsetof(PyTypeObject, tp_as_buffer)}')
res[int(m.group(2))] = member
M = max(res.keys())+1
for i in range(1,M):
if i in res:
out.write("%s,\n" % res[i])
else:
out.write("{0, 0},\n") | null |
186,370 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
The provided code snippet includes necessary dependencies for implementing the `get_c_type` function. Write a Python function `def get_c_type(name)` to solve the following problem:
Return a string for the C name of the type. This function special cases the default types provided by asdl.
Here is the function:
def get_c_type(name):
"""Return a string for the C name of the type.
This function special cases the default types provided by asdl.
"""
if name in asdl.builtin_types:
return name
else:
return "%s_ty" % name | Return a string for the C name of the type. This function special cases the default types provided by asdl. |
186,371 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
TABSIZE = 4
MAX_COL = 80
The provided code snippet includes necessary dependencies for implementing the `reflow_lines` function. Write a Python function `def reflow_lines(s, depth)` to solve the following problem:
Reflow the line s indented depth tabs. Return a sequence of lines where no line extends beyond MAX_COL when properly indented. The first line is properly indented based exclusively on depth * TABSIZE. All following lines -- these are the reflowed lines generated by this function -- start at the same column as the first character beyond the opening { in the first line.
Here is the function:
def reflow_lines(s, depth):
"""Reflow the line s indented depth tabs.
Return a sequence of lines where no line extends beyond MAX_COL
when properly indented. The first line is properly indented based
exclusively on depth * TABSIZE. All following lines -- these are
the reflowed lines generated by this function -- start at the same
column as the first character beyond the opening { in the first
line.
"""
size = MAX_COL - depth * TABSIZE
if len(s) < size:
return [s]
lines = []
cur = s
padding = ""
while len(cur) > size:
i = cur.rfind(' ', 0, size)
# XXX this should be fixed for real
if i == -1 and 'GeneratorExp' in cur:
i = size + 3
assert i != -1, "Impossible line %d to reflow: %r" % (size, s)
lines.append(padding + cur[:i])
if len(lines) == 1:
# find new size based on brace
j = cur.find('{', 0, i)
if j >= 0:
j += 2 # account for the brace and the space after it
size -= j
padding = " " * j
else:
j = cur.find('(', 0, i)
if j >= 0:
j += 1 # account for the paren (no space after it)
size -= j
padding = " " * j
cur = cur[i+1:]
else:
lines.append(padding + cur)
return lines | Reflow the line s indented depth tabs. Return a sequence of lines where no line extends beyond MAX_COL when properly indented. The first line is properly indented based exclusively on depth * TABSIZE. All following lines -- these are the reflowed lines generated by this function -- start at the same column as the first character beyond the opening { in the first line. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.