_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q235600 | ElementList._find_name | train | def _find_name(self, name):
"""
Find the reference of a child having the given name
:type name: ``str``
:param name: the child name (e.g. PID)
:return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the
element has not been... | python | {
"resource": ""
} |
q235601 | ElementFinder.get_structure | train | def get_structure(element, reference=None):
"""
Get the element structure
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference... | python | {
"resource": ""
} |
q235602 | ElementFinder._parse_structure | train | def _parse_structure(element, reference):
"""
Parse the given reference
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>`... | python | {
"resource": ""
} |
q235603 | Message.to_mllp | train | def to_mllp(self, encoding_chars=None, trailing_children=False):
"""
Returns the er7 representation of the message wrapped with mllp encoding characters
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
... | python | {
"resource": ""
} |
q235604 | Redis.get_app | train | def get_app(self):
"""Get current app from Flast stack to use.
This will allow to ensure which Redis connection to be used when
accessing Redis connection public methods via plugin.
"""
# First see to connection stack
ctx = connection_stack.top
if ctx is not None... | python | {
"resource": ""
} |
q235605 | Redis.init_app | train | def init_app(self, app, config_prefix=None):
"""
Actual method to read redis settings from app configuration, initialize
Redis connection and copy all public connection methods to current
instance.
:param app: :class:`flask.Flask` application instance.
:param config_pref... | python | {
"resource": ""
} |
q235606 | Redis._build_connection_args | train | def _build_connection_args(self, klass):
"""Read connection args spec, exclude self from list of possible
:param klass: Redis connection class.
"""
bases = [base for base in klass.__bases__ if base is not object]
all_args = []
for cls in [klass] + bases:
try:... | python | {
"resource": ""
} |
q235607 | Redis._include_public_methods | train | def _include_public_methods(self, connection):
"""Include public methods from Redis connection to current instance.
:param connection: Redis connection instance.
"""
for attr in dir(connection):
value = getattr(connection, attr)
if attr.startswith('_') or not cal... | python | {
"resource": ""
} |
q235608 | ScubaDive.prepare | train | def prepare(self):
'''Prepare to run the docker command'''
self.__make_scubadir()
if self.is_remote_docker:
'''
Docker is running remotely (e.g. boot2docker on OSX).
We don't need to do any user setup whatsoever.
TODO: For now, remote instances w... | python | {
"resource": ""
} |
q235609 | ScubaDive.add_env | train | def add_env(self, name, val):
'''Add an environment variable to the docker run invocation
'''
if name in self.env_vars:
raise KeyError(name)
self.env_vars[name] = val | python | {
"resource": ""
} |
q235610 | ScubaDive.__locate_scubainit | train | def __locate_scubainit(self):
'''Determine path to scubainit binary
'''
pkg_path = os.path.dirname(__file__)
self.scubainit_path = os.path.join(pkg_path, 'scubainit')
if not os.path.isfile(self.scubainit_path):
raise ScubaError('scubainit not found at "{}"'.format(se... | python | {
"resource": ""
} |
q235611 | ScubaDive.__load_config | train | def __load_config(self):
'''Find and load .scuba.yml
'''
# top_path is where .scuba.yml is found, and becomes the top of our bind mount.
# top_rel is the relative path from top_path to the current working directory,
# and is where we'll set the working directory in the container... | python | {
"resource": ""
} |
q235612 | ScubaDive.__make_scubadir | train | def __make_scubadir(self):
'''Make temp directory where all ancillary files are bind-mounted
'''
self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')
self.__scubadir_contpath = '/.scuba'
self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath) | python | {
"resource": ""
} |
q235613 | ScubaDive.__setup_native_run | train | def __setup_native_run(self):
# These options are appended to mounted volume arguments
# NOTE: This tells Docker to re-label the directory for compatibility
# with SELinux. See `man docker-run` for more information.
self.vol_opts = ['z']
# Pass variables to scubainit
se... | python | {
"resource": ""
} |
q235614 | ScubaDive.open_scubadir_file | train | def open_scubadir_file(self, name, mode):
'''Opens a file in the 'scubadir'
This file will automatically be bind-mounted into the container,
at a path given by the 'container_path' property on the returned file object.
'''
path = os.path.join(self.__scubadir_hostpath, name)
... | python | {
"resource": ""
} |
q235615 | ScubaDive.copy_scubadir_file | train | def copy_scubadir_file(self, name, source):
'''Copies source into the scubadir
Returns the container-path of the copied file
'''
dest = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(dest)
shutil.copy2(source, dest)
return os.path.join(se... | python | {
"resource": ""
} |
q235616 | format_cmdline | train | def format_cmdline(args, maxwidth=80):
'''Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
'''
# Leave room for the space and backslash at the end of each line
maxwidth -= 2
def lines():
... | python | {
"resource": ""
} |
q235617 | parse_env_var | train | def parse_env_var(s):
"""Parse an environment variable string
Returns a key-value tuple
Apply the same logic as `docker run -e`:
"If the operator names an environment variable without specifying a value,
then the current value of the named variable is propagated into the
container's environmen... | python | {
"resource": ""
} |
q235618 | __wrap_docker_exec | train | def __wrap_docker_exec(func):
'''Wrap a function to raise DockerExecuteError on ENOENT'''
def call(*args, **kwargs):
try:
return func(*args, **kwargs)
except OSError as e:
if e.errno == errno.ENOENT:
raise DockerExecuteError('Failed to execute docker. Is i... | python | {
"resource": ""
} |
q235619 | docker_inspect | train | def docker_inspect(image):
'''Inspects a docker image
Returns: Parsed JSON data
'''
args = ['docker', 'inspect', '--type', 'image', image]
p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stder... | python | {
"resource": ""
} |
q235620 | docker_pull | train | def docker_pull(image):
'''Pulls an image'''
args = ['docker', 'pull', image]
# If this fails, the default docker stdout/stderr looks good to the user.
ret = call(args)
if ret != 0:
raise DockerError('Failed to pull image "{}"'.format(image)) | python | {
"resource": ""
} |
q235621 | get_image_command | train | def get_image_command(image):
'''Gets the default command for an image'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Cmd']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke)) | python | {
"resource": ""
} |
q235622 | get_image_entrypoint | train | def get_image_entrypoint(image):
'''Gets the image entrypoint'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Entrypoint']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke)) | python | {
"resource": ""
} |
q235623 | make_vol_opt | train | def make_vol_opt(hostdir, contdir, options=None):
'''Generate a docker volume option'''
vol = '--volume={}:{}'.format(hostdir, contdir)
if options != None:
if isinstance(options, str):
options = (options,)
vol += ':' + ','.join(options)
return vol | python | {
"resource": ""
} |
q235624 | find_config | train | def find_config():
'''Search up the diretcory hierarchy for .scuba.yml
Returns: path, rel on success, or None if not found
path The absolute path of the directory where .scuba.yml was found
rel The relative path from the directory where .scuba.yml was found
to the current... | python | {
"resource": ""
} |
q235625 | _process_script_node | train | def _process_script_node(node, name):
'''Process a script-type node
This handles nodes that follow the *Common script schema*,
as outlined in doc/yaml-reference.md.
'''
if isinstance(node, basestring):
# The script is just the text itself
return [node]
if isinstance(node, dict... | python | {
"resource": ""
} |
q235626 | ScubaConfig.process_command | train | def process_command(self, command):
'''Processes a user command using aliases
Arguments:
command A user command list (e.g. argv)
Returns: A ScubaContext object with the following attributes:
script: a list of command line strings
image: the docker image ... | python | {
"resource": ""
} |
q235627 | IP2Location.open | train | def open(self, filename):
''' Opens a database file '''
# Ensure old file is closed before opening a new one
self.close()
self._f = open(filename, 'rb')
self._dbtype = struct.unpack('B', self._f.read(1))[0]
self._dbcolumn = struct.unpack('B', self._f.read(1))[0]
... | python | {
"resource": ""
} |
q235628 | IP2Location._parse_addr | train | def _parse_addr(self, addr):
''' Parses address and returns IP version. Raises exception on invalid argument '''
ipv = 0
try:
socket.inet_pton(socket.AF_INET6, addr)
# Convert ::FFFF:x.y.z.y to IPv4
if addr.lower().startswith('::ffff:'):
try:
... | python | {
"resource": ""
} |
q235629 | Client.rates_for_location | train | def rates_for_location(self, postal_code, location_deets=None):
"""Shows the sales tax rates for a given location."""
request = self._get("rates/" + postal_code, location_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235630 | Client.tax_for_order | train | def tax_for_order(self, order_deets):
"""Shows the sales tax that should be collected for a given order."""
request = self._post('taxes', order_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235631 | Client.list_orders | train | def list_orders(self, params=None):
"""Lists existing order transactions."""
request = self._get('transactions/orders', params)
return self.responder(request) | python | {
"resource": ""
} |
q235632 | Client.show_order | train | def show_order(self, order_id):
"""Shows an existing order transaction."""
request = self._get('transactions/orders/' + str(order_id))
return self.responder(request) | python | {
"resource": ""
} |
q235633 | Client.create_order | train | def create_order(self, order_deets):
"""Creates a new order transaction."""
request = self._post('transactions/orders', order_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235634 | Client.update_order | train | def update_order(self, order_id, order_deets):
"""Updates an existing order transaction."""
request = self._put("transactions/orders/" + str(order_id), order_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235635 | Client.delete_order | train | def delete_order(self, order_id):
"""Deletes an existing order transaction."""
request = self._delete("transactions/orders/" + str(order_id))
return self.responder(request) | python | {
"resource": ""
} |
q235636 | Client.list_refunds | train | def list_refunds(self, params=None):
"""Lists existing refund transactions."""
request = self._get('transactions/refunds', params)
return self.responder(request) | python | {
"resource": ""
} |
q235637 | Client.show_refund | train | def show_refund(self, refund_id):
"""Shows an existing refund transaction."""
request = self._get('transactions/refunds/' + str(refund_id))
return self.responder(request) | python | {
"resource": ""
} |
q235638 | Client.create_refund | train | def create_refund(self, refund_deets):
"""Creates a new refund transaction."""
request = self._post('transactions/refunds', refund_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235639 | Client.update_refund | train | def update_refund(self, refund_id, refund_deets):
"""Updates an existing refund transaction."""
request = self._put('transactions/refunds/' + str(refund_id), refund_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235640 | Client.delete_refund | train | def delete_refund(self, refund_id):
"""Deletes an existing refund transaction."""
request = self._delete('transactions/refunds/' + str(refund_id))
return self.responder(request) | python | {
"resource": ""
} |
q235641 | Client.list_customers | train | def list_customers(self, params=None):
"""Lists existing customers."""
request = self._get('customers', params)
return self.responder(request) | python | {
"resource": ""
} |
q235642 | Client.show_customer | train | def show_customer(self, customer_id):
"""Shows an existing customer."""
request = self._get('customers/' + str(customer_id))
return self.responder(request) | python | {
"resource": ""
} |
q235643 | Client.create_customer | train | def create_customer(self, customer_deets):
"""Creates a new customer."""
request = self._post('customers', customer_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235644 | Client.update_customer | train | def update_customer(self, customer_id, customer_deets):
"""Updates an existing customer."""
request = self._put("customers/" + str(customer_id), customer_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235645 | Client.delete_customer | train | def delete_customer(self, customer_id):
"""Deletes an existing customer."""
request = self._delete("customers/" + str(customer_id))
return self.responder(request) | python | {
"resource": ""
} |
q235646 | Client.validate_address | train | def validate_address(self, address_deets):
"""Validates a customer address and returns back a collection of address matches."""
request = self._post('addresses/validate', address_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235647 | Client.validate | train | def validate(self, vat_deets):
"""Validates an existing VAT identification number against VIES."""
request = self._get('validation', vat_deets)
return self.responder(request) | python | {
"resource": ""
} |
q235648 | choose_plural | train | def choose_plural(amount, variants):
"""
Choose proper form for plural.
Value is a amount, parameters are forms of noun.
Forms are variants for 1, 2, 5 nouns. It may be tuple
of elements, or string where variants separates each other
by comma.
Examples::
{{ some_int|choose_plural:"... | python | {
"resource": ""
} |
q235649 | in_words | train | def in_words(amount, gender=None):
"""
In-words representation of amount.
Parameter is a gender: MALE, FEMALE or NEUTER
Examples::
{{ some_int|in_words }}
{{ some_other_int|in_words:FEMALE }}
"""
try:
res = numeral.in_words(amount, getattr(numeral, str(gender), None))
... | python | {
"resource": ""
} |
q235650 | sum_string | train | def sum_string(amount, gender, items):
"""
in_words and choose_plural in a one flask
Makes in-words representation of value with
choosing correct form of noun.
First parameter is an amount of objects. Second is a
gender (MALE, FEMALE, NEUTER). Third is a variants
of forms for object name.
... | python | {
"resource": ""
} |
q235651 | rl_cleanspaces | train | def rl_cleanspaces(x):
"""
Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations
"""
patterns = (
# arguments for re.sub: pattern and repl
# удаляем пробел перед знаками препинания
(r' +([\.,?!\)]+)', r'\1'),
# добавляем пробел после знака п... | python | {
"resource": ""
} |
q235652 | rl_quotes | train | def rl_quotes(x):
"""
Replace quotes by typographic quotes
"""
patterns = (
# открывающие кавычки ставятся обычно вплотную к слову слева
# а закрывающие -- вплотную справа
# открывающие русские кавычки-ёлочки
(re.compile(r'((?:^|\s))(")((?u))', re.UNICODE), u'\\1\xab... | python | {
"resource": ""
} |
q235653 | distance_of_time | train | def distance_of_time(from_time, accuracy=1):
"""
Display distance of time from current time.
Parameter is an accuracy level (deafult is 1).
Value must be numeral (i.e. time.time() result) or
datetime.datetime (i.e. datetime.datetime.now()
result).
Examples::
{{ some_time|distance_o... | python | {
"resource": ""
} |
q235654 | ru_strftime | train | def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False):
"""
Russian strftime, formats date with given format.
Value is a date (supports datetime.date and datetime.datetime),
parameter is a format (string). For explainings about format,
see documentation for original strfti... | python | {
"resource": ""
} |
q235655 | ru_strftime | train | def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False,
inflected_day=False, preposition=False):
"""
Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@t... | python | {
"resource": ""
} |
q235656 | _get_float_remainder | train | def _get_float_remainder(fvalue, signs=9):
"""
Get remainder of float, i.e. 2.05 -> '05'
@param fvalue: input value
@type fvalue: C{integer types}, C{float} or C{Decimal}
@param signs: maximum number of signs
@type signs: C{integer types}
@return: remainder
@rtype: C{str}
@raise ... | python | {
"resource": ""
} |
q235657 | choose_plural | train | def choose_plural(amount, variants):
"""
Choose proper case depending on amount
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode... | python | {
"resource": ""
} |
q235658 | get_plural | train | def get_plural(amount, variants, absence=None):
"""
Get proper case with value
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}... | python | {
"resource": ""
} |
q235659 | in_words | train | def in_words(amount, gender=None):
"""
Numeral in words
@param amount: numeral
@type amount: C{integer types}, C{float} or C{Decimal}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@return: in-words reprsentation of numeral
@rtype: C{unicode}
raise ValueError... | python | {
"resource": ""
} |
q235660 | _sum_string_fn | train | def _sum_string_fn(into, tmp_val, gender, items=None):
"""
Make in-words representation of single order
@param into: in-words representation of lower orders
@type into: C{unicode}
@param tmp_val: temporary value without lower orders
@type tmp_val: C{integer types}
@param gender: gender (M... | python | {
"resource": ""
} |
q235661 | check_length | train | def check_length(value, length):
"""
Checks length of value
@param value: value to check
@type value: C{str}
@param length: length checking for
@type length: C{int}
@return: None when check successful
@raise ValueError: check failed
"""
_length = len(value)
if _length != ... | python | {
"resource": ""
} |
q235662 | check_positive | train | def check_positive(value, strict=False):
"""
Checks if variable is positive
@param value: value to check
@type value: C{integer types}, C{float} or C{Decimal}
@return: None when check successful
@raise ValueError: check failed
"""
if not strict and value < 0:
raise ValueError(... | python | {
"resource": ""
} |
q235663 | detranslify | train | def detranslify(text):
"""Detranslify russian text"""
try:
res = translit.detranslify(text)
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': text}
return res | python | {
"resource": ""
} |
q235664 | apply | train | def apply(diff, recs, strict=True):
"""
Transform the records with the patch. May fail if the records do not
match those expected in the patch.
"""
index_columns = diff['_index']
indexed = records.index(copy.deepcopy(list(recs)), index_columns)
_add_records(indexed, diff['added'], index_colu... | python | {
"resource": ""
} |
q235665 | load | train | def load(istream, strict=True):
"Deserialize a patch object."
try:
diff = json.load(istream)
if strict:
jsonschema.validate(diff, SCHEMA)
except ValueError:
raise InvalidPatchError('patch is not valid JSON')
except jsonschema.exceptions.ValidationError as e:
... | python | {
"resource": ""
} |
q235666 | save | train | def save(diff, stream=sys.stdout, compact=False):
"Serialize a patch object."
flags = {'sort_keys': True}
if not compact:
flags['indent'] = 2
json.dump(diff, stream, **flags) | python | {
"resource": ""
} |
q235667 | create | train | def create(from_records, to_records, index_columns, ignore_columns=None):
"""
Diff two sets of records, using the index columns as the primary key for
both datasets.
"""
from_indexed = records.index(from_records, index_columns)
to_indexed = records.index(to_records, index_columns)
if ignore... | python | {
"resource": ""
} |
q235668 | _compare_rows | train | def _compare_rows(from_recs, to_recs, keys):
"Return the set of keys which have changed."
return set(
k for k in keys
if sorted(from_recs[k].items()) != sorted(to_recs[k].items())
) | python | {
"resource": ""
} |
q235669 | record_diff | train | def record_diff(lhs, rhs):
"Diff an individual row."
delta = {}
for k in set(lhs).union(rhs):
from_ = lhs[k]
to_ = rhs[k]
if from_ != to_:
delta[k] = {'from': from_, 'to': to_}
return delta | python | {
"resource": ""
} |
q235670 | filter_significance | train | def filter_significance(diff, significance):
"""
Prune any changes in the patch which are due to numeric changes less than this level of
significance.
"""
changed = diff['changed']
# remove individual field changes that are significant
reduced = [{'key': delta['key'],
'field... | python | {
"resource": ""
} |
q235671 | _is_significant | train | def _is_significant(change, significance):
"""
Return True if a change is genuinely significant given our tolerance.
"""
try:
a = float(change['from'])
b = float(change['to'])
except ValueError:
return True
return abs(a - b) > 10 ** (-significance) | python | {
"resource": ""
} |
q235672 | diff_files | train | def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None):
"""
Diff two CSV files, returning the patch which transforms one into the
other.
"""
with open(from_file) as from_stream:
with open(to_file) as to_stream:
from_records = records.load(from_stream, se... | python | {
"resource": ""
} |
q235673 | patch_file | train | def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO,
strict: bool = True, sep: str = ','):
"""
Apply the patch to the source CSV file, and save the result to the target
file.
"""
diff = patch.load(patch_stream)
from_records = records.load(fromcsv_str... | python | {
"resource": ""
} |
q235674 | patch_records | train | def patch_records(diff, from_records, strict=True):
"""
Apply the patch to the sequence of records, returning the transformed
records.
"""
return patch.apply(diff, from_records, strict=strict) | python | {
"resource": ""
} |
q235675 | _nice_fieldnames | train | def _nice_fieldnames(all_columns, index_columns):
"Indexes on the left, other fields in alphabetical order on the right."
non_index_columns = set(all_columns).difference(index_columns)
return index_columns + sorted(non_index_columns) | python | {
"resource": ""
} |
q235676 | csvdiff_cmd | train | def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None,
sep=',', quiet=False, ignore_columns=None, significance=None):
"""
Compare two csv files to see what rows differ between them. The files
are each expected to have a header row, and for each row to be uniquely
ident... | python | {
"resource": ""
} |
q235677 | _diff_and_summarize | train | def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout,
sep=',', ignored_columns=None, significance=None):
"""
Print a summary of the difference between the two files.
"""
from_records = list(records.load(from_csv, sep=sep))
to_records = records.load(to_cs... | python | {
"resource": ""
} |
q235678 | csvpatch_cmd | train | def csvpatch_cmd(input_csv, input=None, output=None, strict=True):
"""
Apply the changes from a csvdiff patch to an existing CSV file.
"""
patch_stream = (sys.stdin
if input is None
else open(input))
tocsv_stream = (sys.stdout
if output is ... | python | {
"resource": ""
} |
q235679 | sort | train | def sort(records: Sequence[Record]) -> List[Record]:
"Sort records into a canonical order, suitable for comparison."
return sorted(records, key=_record_key) | python | {
"resource": ""
} |
q235680 | _record_key | train | def _record_key(record: Record) -> List[Tuple[Column, str]]:
"An orderable representation of this record."
return sorted(record.items()) | python | {
"resource": ""
} |
q235681 | getargspecs | train | def getargspecs(func):
"""Bridges inspect.getargspec and inspect.getfullargspec.
Automatically selects the proper one depending of current Python version.
Automatically bypasses wrappers from typechecked- and override-decorators.
"""
if func is None:
raise TypeError('None is not a Python fun... | python | {
"resource": ""
} |
q235682 | get_required_kwonly_args | train | def get_required_kwonly_args(argspecs):
"""Determines whether given argspecs implies required keywords-only args
and returns them as a list. Returns empty list if no such args exist.
"""
try:
kwonly = argspecs.kwonlyargs
if argspecs.kwonlydefaults is None:
return kwonly
... | python | {
"resource": ""
} |
q235683 | getargnames | train | def getargnames(argspecs, with_unbox=False):
"""Resembles list of arg-names as would be seen in a function signature, including
var-args, var-keywords and keyword-only args.
"""
# todo: We can maybe make use of inspect.formatargspec
args = argspecs.args
vargs = argspecs.varargs
try:
... | python | {
"resource": ""
} |
q235684 | get_class_that_defined_method | train | def get_class_that_defined_method(meth):
"""Determines the class owning the given method.
"""
if is_classmethod(meth):
return meth.__self__
if hasattr(meth, 'im_class'):
return meth.im_class
elif hasattr(meth, '__qualname__'):
# Python 3
try:
cls_names = m... | python | {
"resource": ""
} |
q235685 | is_classmethod | train | def is_classmethod(meth):
"""Detects if the given callable is a classmethod.
"""
if inspect.ismethoddescriptor(meth):
return isinstance(meth, classmethod)
if not inspect.ismethod(meth):
return False
if not inspect.isclass(meth.__self__):
return False
if not hasattr(meth._... | python | {
"resource": ""
} |
q235686 | get_current_args | train | def get_current_args(caller_level = 0, func = None, argNames = None):
"""Determines the args of current function call.
Use caller_level > 0 to get args of even earlier function calls in current stack.
"""
if argNames is None:
argNames = getargnames(getargspecs(func))
if func is None:
... | python | {
"resource": ""
} |
q235687 | getmodule | train | def getmodule(code):
"""More robust variant of inspect.getmodule.
E.g. has less issues on Jython.
"""
try:
md = inspect.getmodule(code, code.co_filename)
except AttributeError:
return inspect.getmodule(code)
if md is None:
# Jython-specific:
# This is currently ju... | python | {
"resource": ""
} |
q235688 | _calc_traceback_limit | train | def _calc_traceback_limit(tb):
"""Calculates limit-parameter to strip away pytypes' internals when used
with API from traceback module.
"""
limit = 1
tb2 = tb
while not tb2.tb_next is None:
try:
maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2]
... | python | {
"resource": ""
} |
q235689 | _pytypes_excepthook | train | def _pytypes_excepthook(exctype, value, tb):
""""An excepthook suitable for use as sys.excepthook, that strips away
the part of the traceback belonging to pytypes' internals.
Can be switched on and off via pytypes.clean_traceback
or pytypes.set_clean_traceback.
The latter automatically installs this... | python | {
"resource": ""
} |
q235690 | get_generator_type | train | def get_generator_type(genr):
"""Obtains PEP 484 style type of a generator object, i.e. returns a
typing.Generator object.
"""
if genr in _checked_generator_types:
return _checked_generator_types[genr]
if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals:
return genr... | python | {
"resource": ""
} |
q235691 | get_Generic_parameters | train | def get_Generic_parameters(tp, generic_supertype):
"""tp must be a subclass of generic_supertype.
Retrieves the type values from tp that correspond to parameters
defined by generic_supertype.
E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent
to get_Mapping_key_value(tp) except for the e... | python | {
"resource": ""
} |
q235692 | get_Tuple_params | train | def get_Tuple_params(tpl):
"""Python version independent function to obtain the parameters
of a typing.Tuple object.
Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
"""
try:
return tpl.__tuple_params__
except... | python | {
"resource": ""
} |
q235693 | is_Tuple_ellipsis | train | def is_Tuple_ellipsis(tpl):
"""Python version independent function to check if a typing.Tuple object
contains an ellipsis."""
try:
return tpl.__tuple_use_ellipsis__
except AttributeError:
try:
if tpl.__args__ is None:
return False
# Python 3.6
... | python | {
"resource": ""
} |
q235694 | is_Union | train | def is_Union(tp):
"""Python version independent check if a type is typing.Union.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
"""
if tp is Union:
return True
try:
# Python 3.6
return tp.__origin__ is Union
except AttributeError:
try:
return isin... | python | {
"resource": ""
} |
q235695 | is_builtin_type | train | def is_builtin_type(tp):
"""Checks if the given type is a builtin one.
"""
return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__) | python | {
"resource": ""
} |
q235696 | get_types | train | def get_types(func):
"""Works like get_type_hints, but returns types as a sequence rather than a
dictionary. Types are returned in declaration order of the corresponding arguments.
"""
return _get_types(func, util.is_classmethod(func), util.is_method(func)) | python | {
"resource": ""
} |
q235697 | get_member_types | train | def get_member_types(obj, member_name, prop_getter = False):
"""Still experimental, incomplete and hardly tested.
Works like get_types, but is also applicable to descriptors.
"""
cls = obj.__class__
member = getattr(cls, member_name)
slf = not (isinstance(member, staticmethod) or isinstance(memb... | python | {
"resource": ""
} |
q235698 | _get_types | train | def _get_types(func, clsm, slf, clss = None, prop_getter = False,
unspecified_type = Any, infer_defaults = None):
"""Helper for get_types and get_member_types.
"""
func0 = util._actualfunc(func, prop_getter)
# check consistency regarding special case with 'self'-keyword
if not slf:
... | python | {
"resource": ""
} |
q235699 | _get_type_hints | train | def _get_type_hints(func, args = None, res = None, infer_defaults = None):
"""Helper for get_type_hints.
"""
if args is None or res is None:
args2, res2 = _get_types(func, util.is_classmethod(func),
util.is_method(func), unspecified_type = type(NotImplemented),
infer_... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.