nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
datalad/datalad | d8c8383d878a207bb586415314219a60c345f732 | datalad/runner/gitrunner.py | python | GitRunnerBase.get_git_environ_adjusted | (env=None) | return git_env | Replaces GIT_DIR and GIT_WORK_TREE with absolute paths if relative path and defined | Replaces GIT_DIR and GIT_WORK_TREE with absolute paths if relative path and defined | [
"Replaces",
"GIT_DIR",
"and",
"GIT_WORK_TREE",
"with",
"absolute",
"paths",
"if",
"relative",
"path",
"and",
"defined"
] | def get_git_environ_adjusted(env=None):
"""
Replaces GIT_DIR and GIT_WORK_TREE with absolute paths if relative path and defined
"""
# if env set copy else get os environment
git_env = env.copy() if env else os.environ.copy()
if GitRunnerBase._GIT_PATH:
git_env['PATH'] = op.pathsep.join([GitRunnerBase._GIT_PATH, git_env['PATH']]) \
if 'PATH' in git_env \
else GitRunnerBase._GIT_PATH
for varstring in ['GIT_DIR', 'GIT_WORK_TREE']:
var = git_env.get(varstring)
if var: # if env variable set
if not op.isabs(var): # and it's a relative path
git_env[varstring] = op.abspath(var) # to absolute path
lgr.log(9, "Updated %s to %s", varstring, git_env[varstring])
if 'GIT_SSH_COMMAND' not in git_env:
git_env['GIT_SSH_COMMAND'] = GIT_SSH_COMMAND
git_env['GIT_SSH_VARIANT'] = 'ssh'
git_env['GIT_ANNEX_USE_GIT_SSH'] = '1'
# We are parsing error messages and hints. For those to work more
# reliably we are doomed to sacrifice i18n effort of git, and enforce
# consistent language of the messages
git_env['LC_MESSAGES'] = 'C'
# But since LC_ALL takes precedence, over LC_MESSAGES, we cannot
# "leak" that one inside, and are doomed to pop it
git_env.pop('LC_ALL', None)
return git_env | [
"def",
"get_git_environ_adjusted",
"(",
"env",
"=",
"None",
")",
":",
"# if env set copy else get os environment",
"git_env",
"=",
"env",
".",
"copy",
"(",
")",
"if",
"env",
"else",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"GitRunnerBase",
".",
"_G... | https://github.com/datalad/datalad/blob/d8c8383d878a207bb586415314219a60c345f732/datalad/runner/gitrunner.py#L84-L115 | |
Tramac/awesome-semantic-segmentation-pytorch | 5843f75215dadc5d734155a238b425a753a665d9 | core/models/segbase.py | python | SegBaseModel.evaluate | (self, x) | return self.forward(x)[0] | evaluating network with inputs and targets | evaluating network with inputs and targets | [
"evaluating",
"network",
"with",
"inputs",
"and",
"targets"
] | def evaluate(self, x):
"""evaluating network with inputs and targets"""
return self.forward(x)[0] | [
"def",
"evaluate",
"(",
"self",
",",
"x",
")",
":",
"return",
"self",
".",
"forward",
"(",
"x",
")",
"[",
"0",
"]"
] | https://github.com/Tramac/awesome-semantic-segmentation-pytorch/blob/5843f75215dadc5d734155a238b425a753a665d9/core/models/segbase.py#L52-L54 | |
deepmind/bsuite | f305972cf05042f6ce23d638477ea9b33918ba17 | bsuite/logging/sqlite_logging.py | python | Logger.__init__ | (self,
db_path: str,
experiment_name: str,
setting_index: int,
connection: Optional[sqlite3.Connection] = None,
skip_name_validation: bool = False) | Initializes a new SQLite logger.
Args:
db_path: Path to the database file. The logger will create the file on the
first write if it does not exist.
experiment_name: The name of the bsuite experiment, e.g. 'deep_sea'.
setting_index: The index of the corresponding environment setting as
defined in each experiment's sweep.py file. For an example `bsuite_id`
"deep_sea/7", `experiment_name` will be "deep_sea" and `setting_index`
will be 7.
connection: Optional connection, for testing purposes. If supplied,
`db_path` will be ignored.
skip_name_validation: Optionally, disable validation of `experiment_name`. | Initializes a new SQLite logger. | [
"Initializes",
"a",
"new",
"SQLite",
"logger",
"."
] | def __init__(self,
db_path: str,
experiment_name: str,
setting_index: int,
connection: Optional[sqlite3.Connection] = None,
skip_name_validation: bool = False):
"""Initializes a new SQLite logger.
Args:
db_path: Path to the database file. The logger will create the file on the
first write if it does not exist.
experiment_name: The name of the bsuite experiment, e.g. 'deep_sea'.
setting_index: The index of the corresponding environment setting as
defined in each experiment's sweep.py file. For an example `bsuite_id`
"deep_sea/7", `experiment_name` will be "deep_sea" and `setting_index`
will be 7.
connection: Optional connection, for testing purposes. If supplied,
`db_path` will be ignored.
skip_name_validation: Optionally, disable validation of `experiment_name`.
"""
if not skip_name_validation:
_validate_experiment_name(experiment_name)
if connection is None:
self._connection = sqlite3.connect(db_path, timeout=20.0)
else:
self._connection = connection
self._experiment_name = experiment_name
self._setting_index = setting_index
self._sure_that_table_exists = False
self._insert_statement = None
self._db_path = db_path
self._keys = None | [
"def",
"__init__",
"(",
"self",
",",
"db_path",
":",
"str",
",",
"experiment_name",
":",
"str",
",",
"setting_index",
":",
"int",
",",
"connection",
":",
"Optional",
"[",
"sqlite3",
".",
"Connection",
"]",
"=",
"None",
",",
"skip_name_validation",
":",
"bo... | https://github.com/deepmind/bsuite/blob/f305972cf05042f6ce23d638477ea9b33918ba17/bsuite/logging/sqlite_logging.py#L54-L86 | ||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | apps/impala/gen-py/hive_metastore/ThriftHiveMetastore.py | python | Client.get_table_objects_by_name | (self, dbname, tbl_names) | return self.recv_get_table_objects_by_name() | Parameters:
- dbname
- tbl_names | Parameters:
- dbname
- tbl_names | [
"Parameters",
":",
"-",
"dbname",
"-",
"tbl_names"
] | def get_table_objects_by_name(self, dbname, tbl_names):
"""
Parameters:
- dbname
- tbl_names
"""
self.send_get_table_objects_by_name(dbname, tbl_names)
return self.recv_get_table_objects_by_name() | [
"def",
"get_table_objects_by_name",
"(",
"self",
",",
"dbname",
",",
"tbl_names",
")",
":",
"self",
".",
"send_get_table_objects_by_name",
"(",
"dbname",
",",
"tbl_names",
")",
"return",
"self",
".",
"recv_get_table_objects_by_name",
"(",
")"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/apps/impala/gen-py/hive_metastore/ThriftHiveMetastore.py#L2098-L2106 | |
WerWolv/EdiZon_CheatsConfigsAndScripts | d16d36c7509c01dca770f402babd83ff2e9ae6e7 | Scripts/lib/python3.5/heapq.py | python | merge | (*iterables, key=None, reverse=False) | Merge multiple sorted inputs into a single sorted output.
Similar to sorted(itertools.chain(*iterables)) but returns a generator,
does not pull the data into memory all at once, and assumes that each of
the input streams is already sorted (smallest to largest).
>>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
[0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
If *key* is not None, applies a key function to each element to determine
its sort order.
>>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))
['dog', 'cat', 'fish', 'horse', 'kangaroo'] | Merge multiple sorted inputs into a single sorted output. | [
"Merge",
"multiple",
"sorted",
"inputs",
"into",
"a",
"single",
"sorted",
"output",
"."
] | def merge(*iterables, key=None, reverse=False):
'''Merge multiple sorted inputs into a single sorted output.
Similar to sorted(itertools.chain(*iterables)) but returns a generator,
does not pull the data into memory all at once, and assumes that each of
the input streams is already sorted (smallest to largest).
>>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
[0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
If *key* is not None, applies a key function to each element to determine
its sort order.
>>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))
['dog', 'cat', 'fish', 'horse', 'kangaroo']
'''
h = []
h_append = h.append
if reverse:
_heapify = _heapify_max
_heappop = _heappop_max
_heapreplace = _heapreplace_max
direction = -1
else:
_heapify = heapify
_heappop = heappop
_heapreplace = heapreplace
direction = 1
if key is None:
for order, it in enumerate(map(iter, iterables)):
try:
next = it.__next__
h_append([next(), order * direction, next])
except StopIteration:
pass
_heapify(h)
while len(h) > 1:
try:
while True:
value, order, next = s = h[0]
yield value
s[0] = next() # raises StopIteration when exhausted
_heapreplace(h, s) # restore heap condition
except StopIteration:
_heappop(h) # remove empty iterator
if h:
# fast case when only a single iterator remains
value, order, next = h[0]
yield value
yield from next.__self__
return
for order, it in enumerate(map(iter, iterables)):
try:
next = it.__next__
value = next()
h_append([key(value), order * direction, value, next])
except StopIteration:
pass
_heapify(h)
while len(h) > 1:
try:
while True:
key_value, order, value, next = s = h[0]
yield value
value = next()
s[0] = key(value)
s[2] = value
_heapreplace(h, s)
except StopIteration:
_heappop(h)
if h:
key_value, order, value, next = h[0]
yield value
yield from next.__self__ | [
"def",
"merge",
"(",
"*",
"iterables",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"h",
"=",
"[",
"]",
"h_append",
"=",
"h",
".",
"append",
"if",
"reverse",
":",
"_heapify",
"=",
"_heapify_max",
"_heappop",
"=",
"_heappop_max",
"... | https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/heapq.py#L314-L392 | ||
openai/kubernetes-ec2-autoscaler | 1d4d1314e9ee2cb2ae0e17b8b8d8d7845fe8b168 | autoscaler/azure.py | python | AzureVirtualScaleSet.terminate_instances | (self, vm_ids) | return AllCompletedFuture(futures) | [] | def terminate_instances(self, vm_ids):
vm_ids = list(vm_ids)
instances = {}
for vm_id in vm_ids:
scale_set_name, instance = self.vm_id_to_instance[vm_id]
# Update our cached copy of the Scale Set
self.scale_sets[scale_set_name].capacity -= 1
instances.setdefault(scale_set_name, []).append(instance)
logger.info('Terminated instances %s', vm_ids)
futures = []
for scale_set_name, scale_set_instances in instances.items():
futures.append(self.client.terminate_scale_set_instances(self.scale_sets[scale_set_name], scale_set_instances))
return AllCompletedFuture(futures) | [
"def",
"terminate_instances",
"(",
"self",
",",
"vm_ids",
")",
":",
"vm_ids",
"=",
"list",
"(",
"vm_ids",
")",
"instances",
"=",
"{",
"}",
"for",
"vm_id",
"in",
"vm_ids",
":",
"scale_set_name",
",",
"instance",
"=",
"self",
".",
"vm_id_to_instance",
"[",
... | https://github.com/openai/kubernetes-ec2-autoscaler/blob/1d4d1314e9ee2cb2ae0e17b8b8d8d7845fe8b168/autoscaler/azure.py#L217-L230 | |||
miyosuda/unreal | 31d4886149412fa248f6efa490ab65bd2f425cde | model/model.py | python | UnrealModel._get2d_deconv_output_size | (self,
input_height, input_width,
filter_height, filter_width,
stride, padding_type) | return out_height, out_width | [] | def _get2d_deconv_output_size(self,
input_height, input_width,
filter_height, filter_width,
stride, padding_type):
if padding_type == 'VALID':
out_height = (input_height - 1) * stride + filter_height
out_width = (input_width - 1) * stride + filter_width
elif padding_type == 'SAME':
out_height = input_height * stride
out_width = input_width * stride
return out_height, out_width | [
"def",
"_get2d_deconv_output_size",
"(",
"self",
",",
"input_height",
",",
"input_width",
",",
"filter_height",
",",
"filter_width",
",",
"stride",
",",
"padding_type",
")",
":",
"if",
"padding_type",
"==",
"'VALID'",
":",
"out_height",
"=",
"(",
"input_height",
... | https://github.com/miyosuda/unreal/blob/31d4886149412fa248f6efa490ab65bd2f425cde/model/model.py#L471-L483 | |||
pytorch/ignite | e452884afa36b63447b9029c4773f6f59cf41340 | ignite/handlers/lr_finder.py | python | FastaiLRFinder.attach | (
self,
trainer: Engine,
to_save: Mapping,
output_transform: Callable = lambda output: output,
num_iter: Optional[int] = None,
start_lr: Optional[float] = None,
end_lr: float = 10.0,
step_mode: str = "exp",
smooth_f: float = 0.05,
diverge_th: float = 5.0,
) | Attaches lr_finder to a given trainer. It also resets model and optimizer at the end of the run.
Args:
trainer: lr_finder is attached to this trainer. Please, keep in mind that all attached handlers
will be executed.
to_save: dictionary with optimizer and other objects that needs to be restored after running
the LR finder. For example, ``to_save={'optimizer': optimizer, 'model': model}``.
It should contain "optimizer" key for the optimizer.
Also all objects should implement ``state_dict`` and ``load_state_dict`` methods.
output_transform: function that transforms the trainer's ``state.output`` after each
iteration. It must return the loss of that iteration.
num_iter: number of iterations for lr schedule between base lr and end_lr. Default, it will
run for ``trainer.state.epoch_length * trainer.state.max_epochs``.
start_lr: lower bound for lr search. Default, Learning Rate specified with the optimizer.
end_lr: upper bound for lr search. Default, 10.0.
step_mode: "exp" or "linear", which way should the lr be increased from ``start_lr``
to ``end_lr``. Default, "exp".
smooth_f: loss smoothing factor in range ``[0, 1)``. Default, 0.05
diverge_th: Used for stopping the search when ``current loss > diverge_th * best_loss``.
Default, 5.0.
Returns:
trainer_with_lr_finder (trainer used for finding the lr)
Examples:
.. code-block:: python
to_save = {"model": model, "optimizer": optimizer}
with lr_finder.attach(trainer, to_save=to_save) as trainer_with_lr_finder:
trainer_with_lr_finder.run(dataloader)
Note:
lr_finder cannot be attached to more than one trainer at a time. | Attaches lr_finder to a given trainer. It also resets model and optimizer at the end of the run. | [
"Attaches",
"lr_finder",
"to",
"a",
"given",
"trainer",
".",
"It",
"also",
"resets",
"model",
"and",
"optimizer",
"at",
"the",
"end",
"of",
"the",
"run",
"."
] | def attach(
self,
trainer: Engine,
to_save: Mapping,
output_transform: Callable = lambda output: output,
num_iter: Optional[int] = None,
start_lr: Optional[float] = None,
end_lr: float = 10.0,
step_mode: str = "exp",
smooth_f: float = 0.05,
diverge_th: float = 5.0,
) -> Any:
"""Attaches lr_finder to a given trainer. It also resets model and optimizer at the end of the run.
Args:
trainer: lr_finder is attached to this trainer. Please, keep in mind that all attached handlers
will be executed.
to_save: dictionary with optimizer and other objects that needs to be restored after running
the LR finder. For example, ``to_save={'optimizer': optimizer, 'model': model}``.
It should contain "optimizer" key for the optimizer.
Also all objects should implement ``state_dict`` and ``load_state_dict`` methods.
output_transform: function that transforms the trainer's ``state.output`` after each
iteration. It must return the loss of that iteration.
num_iter: number of iterations for lr schedule between base lr and end_lr. Default, it will
run for ``trainer.state.epoch_length * trainer.state.max_epochs``.
start_lr: lower bound for lr search. Default, Learning Rate specified with the optimizer.
end_lr: upper bound for lr search. Default, 10.0.
step_mode: "exp" or "linear", which way should the lr be increased from ``start_lr``
to ``end_lr``. Default, "exp".
smooth_f: loss smoothing factor in range ``[0, 1)``. Default, 0.05
diverge_th: Used for stopping the search when ``current loss > diverge_th * best_loss``.
Default, 5.0.
Returns:
trainer_with_lr_finder (trainer used for finding the lr)
Examples:
.. code-block:: python
to_save = {"model": model, "optimizer": optimizer}
with lr_finder.attach(trainer, to_save=to_save) as trainer_with_lr_finder:
trainer_with_lr_finder.run(dataloader)
Note:
lr_finder cannot be attached to more than one trainer at a time.
"""
if not isinstance(to_save, Mapping):
raise TypeError(f"Argument to_save should be a mapping, but given {type(to_save)}")
Checkpoint._check_objects(to_save, "state_dict")
Checkpoint._check_objects(to_save, "load_state_dict")
if "optimizer" not in to_save:
raise ValueError("Mapping to_save should contain 'optimizer' key")
if not isinstance(to_save["optimizer"], torch.optim.Optimizer):
raise TypeError(
f"Object to_save['optimizer'] should be torch optimizer, but given {type(to_save['optimizer'])}"
)
if smooth_f < 0 or smooth_f >= 1:
raise ValueError("smooth_f is outside the range [0, 1]")
if diverge_th < 1:
raise ValueError("diverge_th should be larger than 1")
if step_mode not in ["exp", "linear"]:
raise ValueError(f"step_mode should be 'exp' or 'linear', but given {step_mode}")
if num_iter is not None:
if not isinstance(num_iter, int):
raise TypeError(f"if provided, num_iter should be an integer, but give {num_iter}")
if num_iter <= 0:
raise ValueError(f"if provided, num_iter should be positive, but give {num_iter}")
if isinstance(start_lr, (float, int)) and start_lr >= end_lr:
raise ValueError(f"start_lr must be less than end_lr, start_lr={start_lr} vs end_lr={end_lr}")
# store to_save
with tempfile.TemporaryDirectory() as tmpdirname:
obj = {k: o.state_dict() for k, o in to_save.items()}
# add trainer
obj["trainer"] = trainer.state_dict()
cache_filepath = Path(tmpdirname) / "ignite_lr_finder_cache.pt"
torch.save(obj, cache_filepath.as_posix())
optimizer = to_save["optimizer"]
# Attach handlers
if not trainer.has_event_handler(self._run):
trainer.add_event_handler(
Events.STARTED,
self._run,
optimizer,
output_transform,
num_iter,
start_lr,
end_lr,
step_mode,
smooth_f,
diverge_th,
)
if not trainer.has_event_handler(self._warning):
trainer.add_event_handler(Events.COMPLETED, self._warning)
if not trainer.has_event_handler(self._reset):
trainer.add_event_handler(Events.COMPLETED, self._reset)
yield trainer
self._detach(trainer)
# restore to_save and reset trainer's state
obj = torch.load(cache_filepath.as_posix())
trainer.load_state_dict(obj["trainer"])
for k, o in obj.items():
if k in to_save:
to_save[k].load_state_dict(o) | [
"def",
"attach",
"(",
"self",
",",
"trainer",
":",
"Engine",
",",
"to_save",
":",
"Mapping",
",",
"output_transform",
":",
"Callable",
"=",
"lambda",
"output",
":",
"output",
",",
"num_iter",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"start_lr"... | https://github.com/pytorch/ignite/blob/e452884afa36b63447b9029c4773f6f59cf41340/ignite/handlers/lr_finder.py#L364-L473 | ||
Azure/azure-linux-extensions | a42ef718c746abab2b3c6a21da87b29e76364558 | Common/libpsutil/py2.7-glibc-2.12+/psutil/_pswindows.py | python | users | () | return retlist | Return currently connected users as a list of namedtuples. | Return currently connected users as a list of namedtuples. | [
"Return",
"currently",
"connected",
"users",
"as",
"a",
"list",
"of",
"namedtuples",
"."
] | def users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = cext.users()
for item in rawlist:
user, hostname, tstamp = item
nt = _common.suser(user, None, hostname, tstamp)
retlist.append(nt)
return retlist | [
"def",
"users",
"(",
")",
":",
"retlist",
"=",
"[",
"]",
"rawlist",
"=",
"cext",
".",
"users",
"(",
")",
"for",
"item",
"in",
"rawlist",
":",
"user",
",",
"hostname",
",",
"tstamp",
"=",
"item",
"nt",
"=",
"_common",
".",
"suser",
"(",
"user",
",... | https://github.com/Azure/azure-linux-extensions/blob/a42ef718c746abab2b3c6a21da87b29e76364558/Common/libpsutil/py2.7-glibc-2.12+/psutil/_pswindows.py#L182-L190 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/sympy/utilities/iterables.py | python | _iproduct2 | (iterable1, iterable2) | Cartesian product of two possibly infinite iterables | Cartesian product of two possibly infinite iterables | [
"Cartesian",
"product",
"of",
"two",
"possibly",
"infinite",
"iterables"
] | def _iproduct2(iterable1, iterable2):
'''Cartesian product of two possibly infinite iterables'''
it1 = iter(iterable1)
it2 = iter(iterable2)
elems1 = []
elems2 = []
sentinel = object()
def append(it, elems):
e = next(it, sentinel)
if e is not sentinel:
elems.append(e)
n = 0
append(it1, elems1)
append(it2, elems2)
while n <= len(elems1) + len(elems2):
for m in range(n-len(elems1)+1, len(elems2)):
yield (elems1[n-m], elems2[m])
n += 1
append(it1, elems1)
append(it2, elems2) | [
"def",
"_iproduct2",
"(",
"iterable1",
",",
"iterable2",
")",
":",
"it1",
"=",
"iter",
"(",
"iterable1",
")",
"it2",
"=",
"iter",
"(",
"iterable2",
")",
"elems1",
"=",
"[",
"]",
"elems2",
"=",
"[",
"]",
"sentinel",
"=",
"object",
"(",
")",
"def",
"... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/utilities/iterables.py#L199-L223 | ||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | external/Scripting Engine/Xenotix Python Scripting Engine/Lib/codecs.py | python | IncrementalEncoder.getstate | (self) | return 0 | Return the current state of the encoder. | Return the current state of the encoder. | [
"Return",
"the",
"current",
"state",
"of",
"the",
"encoder",
"."
] | def getstate(self):
"""
Return the current state of the encoder.
"""
return 0 | [
"def",
"getstate",
"(",
"self",
")",
":",
"return",
"0"
] | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/codecs.py#L184-L188 | |
trakt/Plex-Trakt-Scrobbler | aeb0bfbe62fad4b06c164f1b95581da7f35dce0b | Trakttv.bundle/Contents/Libraries/Shared/elftools/construct/macros.py | python | EmbeddedBitStruct | (*subcons) | return Bitwise(Embedded(Struct(None, *subcons))) | an embedded BitStruct. no name is necessary.
* subcons - the subcons that make up this structure | an embedded BitStruct. no name is necessary.
* subcons - the subcons that make up this structure | [
"an",
"embedded",
"BitStruct",
".",
"no",
"name",
"is",
"necessary",
".",
"*",
"subcons",
"-",
"the",
"subcons",
"that",
"make",
"up",
"this",
"structure"
] | def EmbeddedBitStruct(*subcons):
"""an embedded BitStruct. no name is necessary.
* subcons - the subcons that make up this structure
"""
return Bitwise(Embedded(Struct(None, *subcons))) | [
"def",
"EmbeddedBitStruct",
"(",
"*",
"subcons",
")",
":",
"return",
"Bitwise",
"(",
"Embedded",
"(",
"Struct",
"(",
"None",
",",
"*",
"subcons",
")",
")",
")"
] | https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Shared/elftools/construct/macros.py#L459-L463 | |
jython/jython3 | def4f8ec47cb7a9c799ea4c745f12badf92c5769 | Lib/decimal.py | python | Context.max_mag | (self, a, b) | return a.max_mag(b, context=self) | Compares the values numerically with their sign ignored.
>>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
Decimal('7')
>>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
Decimal('-10')
>>> ExtendedContext.max_mag(1, -2)
Decimal('-2')
>>> ExtendedContext.max_mag(Decimal(1), -2)
Decimal('-2')
>>> ExtendedContext.max_mag(1, Decimal(-2))
Decimal('-2') | Compares the values numerically with their sign ignored. | [
"Compares",
"the",
"values",
"numerically",
"with",
"their",
"sign",
"ignored",
"."
] | def max_mag(self, a, b):
"""Compares the values numerically with their sign ignored.
>>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
Decimal('7')
>>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
Decimal('-10')
>>> ExtendedContext.max_mag(1, -2)
Decimal('-2')
>>> ExtendedContext.max_mag(Decimal(1), -2)
Decimal('-2')
>>> ExtendedContext.max_mag(1, Decimal(-2))
Decimal('-2')
"""
a = _convert_other(a, raiseit=True)
return a.max_mag(b, context=self) | [
"def",
"max_mag",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"max_mag",
"(",
"b",
",",
"context",
"=",
"self",
")"
] | https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/Lib/decimal.py#L4679-L4694 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/datetime.py | python | tzinfo.__reduce__ | (self) | [] | def __reduce__(self):
getinitargs = getattr(self, "__getinitargs__", None)
if getinitargs:
args = getinitargs()
else:
args = ()
getstate = getattr(self, "__getstate__", None)
if getstate:
state = getstate()
else:
state = getattr(self, "__dict__", None) or None
if state is None:
return (self.__class__, args)
else:
return (self.__class__, args, state) | [
"def",
"__reduce__",
"(",
"self",
")",
":",
"getinitargs",
"=",
"getattr",
"(",
"self",
",",
"\"__getinitargs__\"",
",",
"None",
")",
"if",
"getinitargs",
":",
"args",
"=",
"getinitargs",
"(",
")",
"else",
":",
"args",
"=",
"(",
")",
"getstate",
"=",
"... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/datetime.py#L986-L1000 | ||||
hydroshare/hydroshare | 7ba563b55412f283047fb3ef6da367d41dec58c6 | hs_tools_resource/models.py | python | ToolResource.get_supported_upload_file_types | (cls) | return () | [] | def get_supported_upload_file_types(cls):
# no file types are supported
return () | [
"def",
"get_supported_upload_file_types",
"(",
"cls",
")",
":",
"# no file types are supported",
"return",
"(",
")"
] | https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_tools_resource/models.py#L40-L42 | |||
kindredresearch/SenseAct | e7acbeb7918d0069ea82f0bab09ecb99807fdc9b | senseact/rtrl_base_env.py | python | RTRLBaseEnv._act_singlethread | (self, action) | Processes actions in single thread mode.
Args:
action: A numpy array containing action. | Processes actions in single thread mode. | [
"Processes",
"actions",
"in",
"single",
"thread",
"mode",
"."
] | def _act_singlethread(self, action):
"""Processes actions in single thread mode.
Args:
action: A numpy array containing action.
"""
self._write_action(action)
self._action_to_actuator_() | [
"def",
"_act_singlethread",
"(",
"self",
",",
"action",
")",
":",
"self",
".",
"_write_action",
"(",
"action",
")",
"self",
".",
"_action_to_actuator_",
"(",
")"
] | https://github.com/kindredresearch/SenseAct/blob/e7acbeb7918d0069ea82f0bab09ecb99807fdc9b/senseact/rtrl_base_env.py#L423-L430 | ||
exodrifter/unity-python | bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d | Lib/mailbox.py | python | _mboxMMDFMessage._explain_to | (self, message) | Copy mbox- or MMDF-specific state to message insofar as possible. | Copy mbox- or MMDF-specific state to message insofar as possible. | [
"Copy",
"mbox",
"-",
"or",
"MMDF",
"-",
"specific",
"state",
"to",
"message",
"insofar",
"as",
"possible",
"."
] | def _explain_to(self, message):
"""Copy mbox- or MMDF-specific state to message insofar as possible."""
if isinstance(message, MaildirMessage):
flags = set(self.get_flags())
if 'O' in flags:
message.set_subdir('cur')
if 'F' in flags:
message.add_flag('F')
if 'A' in flags:
message.add_flag('R')
if 'R' in flags:
message.add_flag('S')
if 'D' in flags:
message.add_flag('T')
del message['status']
del message['x-status']
maybe_date = ' '.join(self.get_from().split()[-5:])
try:
message.set_date(calendar.timegm(time.strptime(maybe_date,
'%a %b %d %H:%M:%S %Y')))
except (ValueError, OverflowError):
pass
elif isinstance(message, _mboxMMDFMessage):
message.set_flags(self.get_flags())
message.set_from(self.get_from())
elif isinstance(message, MHMessage):
flags = set(self.get_flags())
if 'R' not in flags:
message.add_sequence('unseen')
if 'A' in flags:
message.add_sequence('replied')
if 'F' in flags:
message.add_sequence('flagged')
del message['status']
del message['x-status']
elif isinstance(message, BabylMessage):
flags = set(self.get_flags())
if 'R' not in flags:
message.add_label('unseen')
if 'D' in flags:
message.add_label('deleted')
if 'A' in flags:
message.add_label('answered')
del message['status']
del message['x-status']
elif isinstance(message, Message):
pass
else:
raise TypeError('Cannot convert to specified type: %s' %
type(message)) | [
"def",
"_explain_to",
"(",
"self",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"MaildirMessage",
")",
":",
"flags",
"=",
"set",
"(",
"self",
".",
"get_flags",
"(",
")",
")",
"if",
"'O'",
"in",
"flags",
":",
"message",
".",
"set... | https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/mailbox.py#L1647-L1696 | ||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/pytz-2012j-py2.7.egg/pytz/tzinfo.py | python | DstTzInfo.localize | (self, dt, is_dst=False) | return sorting_keys[first_key] | Convert naive time to local time.
This method should be used to construct localtimes, rather
than passing a tzinfo argument to a datetime constructor.
is_dst is used to determine the correct timezone in the ambigous
period at the end of daylight savings time.
>>> from pytz import timezone
>>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
>>> amdam = timezone('Europe/Amsterdam')
>>> dt = datetime(2004, 10, 31, 2, 0, 0)
>>> loc_dt1 = amdam.localize(dt, is_dst=True)
>>> loc_dt2 = amdam.localize(dt, is_dst=False)
>>> loc_dt1.strftime(fmt)
'2004-10-31 02:00:00 CEST (+0200)'
>>> loc_dt2.strftime(fmt)
'2004-10-31 02:00:00 CET (+0100)'
>>> str(loc_dt2 - loc_dt1)
'1:00:00'
Use is_dst=None to raise an AmbiguousTimeError for ambiguous
times at the end of daylight savings
>>> try:
... loc_dt1 = amdam.localize(dt, is_dst=None)
... except AmbiguousTimeError:
... print('Ambiguous')
Ambiguous
is_dst defaults to False
>>> amdam.localize(dt) == amdam.localize(dt, False)
True
is_dst is also used to determine the correct timezone in the
wallclock times jumped over at the start of daylight savings time.
>>> pacific = timezone('US/Pacific')
>>> dt = datetime(2008, 3, 9, 2, 0, 0)
>>> ploc_dt1 = pacific.localize(dt, is_dst=True)
>>> ploc_dt2 = pacific.localize(dt, is_dst=False)
>>> ploc_dt1.strftime(fmt)
'2008-03-09 02:00:00 PDT (-0700)'
>>> ploc_dt2.strftime(fmt)
'2008-03-09 02:00:00 PST (-0800)'
>>> str(ploc_dt2 - ploc_dt1)
'1:00:00'
Use is_dst=None to raise a NonExistentTimeError for these skipped
times.
>>> try:
... loc_dt1 = pacific.localize(dt, is_dst=None)
... except NonExistentTimeError:
... print('Non-existent')
Non-existent | Convert naive time to local time. | [
"Convert",
"naive",
"time",
"to",
"local",
"time",
"."
] | def localize(self, dt, is_dst=False):
'''Convert naive time to local time.
This method should be used to construct localtimes, rather
than passing a tzinfo argument to a datetime constructor.
is_dst is used to determine the correct timezone in the ambigous
period at the end of daylight savings time.
>>> from pytz import timezone
>>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
>>> amdam = timezone('Europe/Amsterdam')
>>> dt = datetime(2004, 10, 31, 2, 0, 0)
>>> loc_dt1 = amdam.localize(dt, is_dst=True)
>>> loc_dt2 = amdam.localize(dt, is_dst=False)
>>> loc_dt1.strftime(fmt)
'2004-10-31 02:00:00 CEST (+0200)'
>>> loc_dt2.strftime(fmt)
'2004-10-31 02:00:00 CET (+0100)'
>>> str(loc_dt2 - loc_dt1)
'1:00:00'
Use is_dst=None to raise an AmbiguousTimeError for ambiguous
times at the end of daylight savings
>>> try:
... loc_dt1 = amdam.localize(dt, is_dst=None)
... except AmbiguousTimeError:
... print('Ambiguous')
Ambiguous
is_dst defaults to False
>>> amdam.localize(dt) == amdam.localize(dt, False)
True
is_dst is also used to determine the correct timezone in the
wallclock times jumped over at the start of daylight savings time.
>>> pacific = timezone('US/Pacific')
>>> dt = datetime(2008, 3, 9, 2, 0, 0)
>>> ploc_dt1 = pacific.localize(dt, is_dst=True)
>>> ploc_dt2 = pacific.localize(dt, is_dst=False)
>>> ploc_dt1.strftime(fmt)
'2008-03-09 02:00:00 PDT (-0700)'
>>> ploc_dt2.strftime(fmt)
'2008-03-09 02:00:00 PST (-0800)'
>>> str(ploc_dt2 - ploc_dt1)
'1:00:00'
Use is_dst=None to raise a NonExistentTimeError for these skipped
times.
>>> try:
... loc_dt1 = pacific.localize(dt, is_dst=None)
... except NonExistentTimeError:
... print('Non-existent')
Non-existent
'''
if dt.tzinfo is not None:
raise ValueError('Not naive datetime (tzinfo is already set)')
# Find the two best possibilities.
possible_loc_dt = set()
for delta in [timedelta(days=-1), timedelta(days=1)]:
loc_dt = dt + delta
idx = max(0, bisect_right(
self._utc_transition_times, loc_dt) - 1)
inf = self._transition_info[idx]
tzinfo = self._tzinfos[inf]
loc_dt = tzinfo.normalize(dt.replace(tzinfo=tzinfo))
if loc_dt.replace(tzinfo=None) == dt:
possible_loc_dt.add(loc_dt)
if len(possible_loc_dt) == 1:
return possible_loc_dt.pop()
# If there are no possibly correct timezones, we are attempting
# to convert a time that never happened - the time period jumped
# during the start-of-DST transition period.
if len(possible_loc_dt) == 0:
# If we refuse to guess, raise an exception.
if is_dst is None:
raise NonExistentTimeError(dt)
# If we are forcing the pre-DST side of the DST transition, we
# obtain the correct timezone by winding the clock forward a few
# hours.
elif is_dst:
return self.localize(
dt + timedelta(hours=6), is_dst=True) - timedelta(hours=6)
# If we are forcing the post-DST side of the DST transition, we
# obtain the correct timezone by winding the clock back.
else:
return self.localize(
dt - timedelta(hours=6), is_dst=False) + timedelta(hours=6)
# If we get this far, we have multiple possible timezones - this
# is an ambiguous case occuring during the end-of-DST transition.
# If told to be strict, raise an exception since we have an
# ambiguous case
if is_dst is None:
raise AmbiguousTimeError(dt)
# Filter out the possiblilities that don't match the requested
# is_dst
filtered_possible_loc_dt = [
p for p in possible_loc_dt
if bool(p.tzinfo._dst) == is_dst
]
# Hopefully we only have one possibility left. Return it.
if len(filtered_possible_loc_dt) == 1:
return filtered_possible_loc_dt[0]
if len(filtered_possible_loc_dt) == 0:
filtered_possible_loc_dt = list(possible_loc_dt)
# If we get this far, we have in a wierd timezone transition
# where the clocks have been wound back but is_dst is the same
# in both (eg. Europe/Warsaw 1915 when they switched to CET).
# At this point, we just have to guess unless we allow more
# hints to be passed in (such as the UTC offset or abbreviation),
# but that is just getting silly.
#
# Choose the earliest (by UTC) applicable timezone.
sorting_keys = {}
for local_dt in filtered_possible_loc_dt:
key = local_dt.replace(tzinfo=None) - local_dt.tzinfo._utcoffset
sorting_keys[key] = local_dt
first_key = sorted(sorting_keys)[0]
return sorting_keys[first_key] | [
"def",
"localize",
"(",
"self",
",",
"dt",
",",
"is_dst",
"=",
"False",
")",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Not naive datetime (tzinfo is already set)'",
")",
"# Find the two best possibilities.",
"possible_... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/pytz-2012j-py2.7.egg/pytz/tzinfo.py#L244-L378 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/combinatorics/subsets.py | python | Subset.prev_lexicographic | (self) | return Subset(ret_set, super_set) | Generates the previous lexicographically ordered subset.
Examples
========
>>> from sympy.combinatorics.subsets import Subset
>>> a = Subset([], ['a','b','c','d'])
>>> a.prev_lexicographic().subset
['d']
>>> a = Subset(['c','d'], ['a','b','c','d'])
>>> a.prev_lexicographic().subset
['c']
See Also
========
next_lexicographic | Generates the previous lexicographically ordered subset. | [
"Generates",
"the",
"previous",
"lexicographically",
"ordered",
"subset",
"."
] | def prev_lexicographic(self):
"""
Generates the previous lexicographically ordered subset.
Examples
========
>>> from sympy.combinatorics.subsets import Subset
>>> a = Subset([], ['a','b','c','d'])
>>> a.prev_lexicographic().subset
['d']
>>> a = Subset(['c','d'], ['a','b','c','d'])
>>> a.prev_lexicographic().subset
['c']
See Also
========
next_lexicographic
"""
i = self.superset_size - 1
indices = Subset.subset_indices(self.subset, self.superset)
while i not in indices and i >= 0:
i = i - 1
if i - 1 in indices or i == 0:
indices.remove(i)
else:
if i >= 0:
indices.remove(i)
indices.append(i - 1)
indices.append(self.superset_size - 1)
ret_set = []
super_set = self.superset
for i in indices:
ret_set.append(super_set[i])
return Subset(ret_set, super_set) | [
"def",
"prev_lexicographic",
"(",
"self",
")",
":",
"i",
"=",
"self",
".",
"superset_size",
"-",
"1",
"indices",
"=",
"Subset",
".",
"subset_indices",
"(",
"self",
".",
"subset",
",",
"self",
".",
"superset",
")",
"while",
"i",
"not",
"in",
"indices",
... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/combinatorics/subsets.py#L177-L214 | |
SmirkCao/Lihang | ad8dc2b82df421ed6be88a77921d941a75f69055 | CH05/decision_tree.py | python | cal_condition_ent | (x, y) | return ent | calculate condition ent(y|x)
:param x: feature
:param y: class
:return: ent(y|x) | calculate condition ent(y|x)
:param x: feature
:param y: class
:return: ent(y|x) | [
"calculate",
"condition",
"ent",
"(",
"y|x",
")",
":",
"param",
"x",
":",
"feature",
":",
"param",
"y",
":",
"class",
":",
"return",
":",
"ent",
"(",
"y|x",
")"
] | def cal_condition_ent(x, y):
"""
calculate condition ent(y|x)
:param x: feature
:param y: class
:return: ent(y|x)
"""
ent = 0
x_values = set(x)
for x_value in x_values:
sub_y = y[x == x_value]
tmp_ent = cal_ent(sub_y)
p = sub_y.shape[0]/y.shape[0]
ent += p*tmp_ent
return ent | [
"def",
"cal_condition_ent",
"(",
"x",
",",
"y",
")",
":",
"ent",
"=",
"0",
"x_values",
"=",
"set",
"(",
"x",
")",
"for",
"x_value",
"in",
"x_values",
":",
"sub_y",
"=",
"y",
"[",
"x",
"==",
"x_value",
"]",
"tmp_ent",
"=",
"cal_ent",
"(",
"sub_y",
... | https://github.com/SmirkCao/Lihang/blob/ad8dc2b82df421ed6be88a77921d941a75f69055/CH05/decision_tree.py#L211-L225 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/combinatorics/coset_table.py | python | CosetTable.modified_merge | (self, k, lamda, w, q) | r"""
Parameters
==========
'k', 'lamda' -- the two class representatives to be merged.
q -- queue of length l of elements to be deleted from `\Omega` *.
w -- Word in (YUY^-1)
See Also
========
merge | r"""
Parameters
========== | [
"r",
"Parameters",
"=========="
] | def modified_merge(self, k, lamda, w, q):
r"""
Parameters
==========
'k', 'lamda' -- the two class representatives to be merged.
q -- queue of length l of elements to be deleted from `\Omega` *.
w -- Word in (YUY^-1)
See Also
========
merge
"""
self.merge(k, lamda, q, w=w, modified=True) | [
"def",
"modified_merge",
"(",
"self",
",",
"k",
",",
"lamda",
",",
"w",
",",
"q",
")",
":",
"self",
".",
"merge",
"(",
"k",
",",
"lamda",
",",
"q",
",",
"w",
"=",
"w",
",",
"modified",
"=",
"True",
")"
] | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/combinatorics/coset_table.py#L914-L928 | ||
paulwinex/pw_MultiScriptEditor | e447e99f87cb07e238baf693b7e124e50efdbc51 | multi_script_editor/jedi/evaluate/compiled/__init__.py | python | _a_generator | (foo) | Used to have an object to return for generators. | Used to have an object to return for generators. | [
"Used",
"to",
"have",
"an",
"object",
"to",
"return",
"for",
"generators",
"."
] | def _a_generator(foo):
"""Used to have an object to return for generators."""
yield 42
yield foo | [
"def",
"_a_generator",
"(",
"foo",
")",
":",
"yield",
"42",
"yield",
"foo"
] | https://github.com/paulwinex/pw_MultiScriptEditor/blob/e447e99f87cb07e238baf693b7e124e50efdbc51/multi_script_editor/jedi/evaluate/compiled/__init__.py#L372-L375 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/patched/notpip/_vendor/distlib/util.py | python | parse_requirement | (req) | return Container(name=distname, extras=extras, constraints=versions,
marker=mark_expr, url=uri, requirement=rs) | Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement. | Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement. | [
"Parse",
"a",
"requirement",
"passed",
"in",
"as",
"a",
"string",
".",
"Return",
"a",
"Container",
"whose",
"attributes",
"contain",
"the",
"various",
"parts",
"of",
"the",
"requirement",
"."
] | def parse_requirement(req):
"""
Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement.
"""
remaining = req.strip()
if not remaining or remaining.startswith('#'):
return None
m = IDENTIFIER.match(remaining)
if not m:
raise SyntaxError('name expected: %s' % remaining)
distname = m.groups()[0]
remaining = remaining[m.end():]
extras = mark_expr = versions = uri = None
if remaining and remaining[0] == '[':
i = remaining.find(']', 1)
if i < 0:
raise SyntaxError('unterminated extra: %s' % remaining)
s = remaining[1:i]
remaining = remaining[i + 1:].lstrip()
extras = []
while s:
m = IDENTIFIER.match(s)
if not m:
raise SyntaxError('malformed extra: %s' % s)
extras.append(m.groups()[0])
s = s[m.end():]
if not s:
break
if s[0] != ',':
raise SyntaxError('comma expected in extras: %s' % s)
s = s[1:].lstrip()
if not extras:
extras = None
if remaining:
if remaining[0] == '@':
# it's a URI
remaining = remaining[1:].lstrip()
m = NON_SPACE.match(remaining)
if not m:
raise SyntaxError('invalid URI: %s' % remaining)
uri = m.groups()[0]
t = urlparse(uri)
# there are issues with Python and URL parsing, so this test
# is a bit crude. See bpo-20271, bpo-23505. Python doesn't
# always parse invalid URLs correctly - it should raise
# exceptions for malformed URLs
if not (t.scheme and t.netloc):
raise SyntaxError('Invalid URL: %s' % uri)
remaining = remaining[m.end():].lstrip()
else:
def get_versions(ver_remaining):
"""
Return a list of operator, version tuples if any are
specified, else None.
"""
m = COMPARE_OP.match(ver_remaining)
versions = None
if m:
versions = []
while True:
op = m.groups()[0]
ver_remaining = ver_remaining[m.end():]
m = VERSION_IDENTIFIER.match(ver_remaining)
if not m:
raise SyntaxError('invalid version: %s' % ver_remaining)
v = m.groups()[0]
versions.append((op, v))
ver_remaining = ver_remaining[m.end():]
if not ver_remaining or ver_remaining[0] != ',':
break
ver_remaining = ver_remaining[1:].lstrip()
m = COMPARE_OP.match(ver_remaining)
if not m:
raise SyntaxError('invalid constraint: %s' % ver_remaining)
if not versions:
versions = None
return versions, ver_remaining
if remaining[0] != '(':
versions, remaining = get_versions(remaining)
else:
i = remaining.find(')', 1)
if i < 0:
raise SyntaxError('unterminated parenthesis: %s' % remaining)
s = remaining[1:i]
remaining = remaining[i + 1:].lstrip()
# As a special diversion from PEP 508, allow a version number
# a.b.c in parentheses as a synonym for ~= a.b.c (because this
# is allowed in earlier PEPs)
if COMPARE_OP.match(s):
versions, _ = get_versions(s)
else:
m = VERSION_IDENTIFIER.match(s)
if not m:
raise SyntaxError('invalid constraint: %s' % s)
v = m.groups()[0]
s = s[m.end():].lstrip()
if s:
raise SyntaxError('invalid constraint: %s' % s)
versions = [('~=', v)]
if remaining:
if remaining[0] != ';':
raise SyntaxError('invalid requirement: %s' % remaining)
remaining = remaining[1:].lstrip()
mark_expr, remaining = parse_marker(remaining)
if remaining and remaining[0] != '#':
raise SyntaxError('unexpected trailing data: %s' % remaining)
if not versions:
rs = distname
else:
rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))
return Container(name=distname, extras=extras, constraints=versions,
marker=mark_expr, url=uri, requirement=rs) | [
"def",
"parse_requirement",
"(",
"req",
")",
":",
"remaining",
"=",
"req",
".",
"strip",
"(",
")",
"if",
"not",
"remaining",
"or",
"remaining",
".",
"startswith",
"(",
"'#'",
")",
":",
"return",
"None",
"m",
"=",
"IDENTIFIER",
".",
"match",
"(",
"remai... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/distlib/util.py#L145-L263 | |
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/packaging/specifiers.py | python | BaseSpecifier.prereleases | (self, value: bool) | Sets whether or not pre-releases as a whole are allowed by this
specifier. | Sets whether or not pre-releases as a whole are allowed by this
specifier. | [
"Sets",
"whether",
"or",
"not",
"pre",
"-",
"releases",
"as",
"a",
"whole",
"are",
"allowed",
"by",
"this",
"specifier",
"."
] | def prereleases(self, value: bool) -> None:
"""
Sets whether or not pre-releases as a whole are allowed by this
specifier.
""" | [
"def",
"prereleases",
"(",
"self",
",",
"value",
":",
"bool",
")",
"->",
"None",
":"
] | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/packaging/specifiers.py#L75-L79 | ||
boto/boto | b2a6f08122b2f1b89888d2848e730893595cd001 | boto/vpc/__init__.py | python | VPCConnection.create_subnet | (self, vpc_id, cidr_block, availability_zone=None,
dry_run=False) | return self.get_object('CreateSubnet', params, Subnet) | Create a new Subnet
:type vpc_id: str
:param vpc_id: The ID of the VPC where you want to create the subnet.
:type cidr_block: str
:param cidr_block: The CIDR block you want the subnet to cover.
:type availability_zone: str
:param availability_zone: The AZ you want the subnet in
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: The newly created Subnet
:return: A :class:`boto.vpc.customergateway.Subnet` object | Create a new Subnet | [
"Create",
"a",
"new",
"Subnet"
] | def create_subnet(self, vpc_id, cidr_block, availability_zone=None,
dry_run=False):
"""
Create a new Subnet
:type vpc_id: str
:param vpc_id: The ID of the VPC where you want to create the subnet.
:type cidr_block: str
:param cidr_block: The CIDR block you want the subnet to cover.
:type availability_zone: str
:param availability_zone: The AZ you want the subnet in
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: The newly created Subnet
:return: A :class:`boto.vpc.customergateway.Subnet` object
"""
params = {'VpcId': vpc_id,
'CidrBlock': cidr_block}
if availability_zone:
params['AvailabilityZone'] = availability_zone
if dry_run:
params['DryRun'] = 'true'
return self.get_object('CreateSubnet', params, Subnet) | [
"def",
"create_subnet",
"(",
"self",
",",
"vpc_id",
",",
"cidr_block",
",",
"availability_zone",
"=",
"None",
",",
"dry_run",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'VpcId'",
":",
"vpc_id",
",",
"'CidrBlock'",
":",
"cidr_block",
"}",
"if",
"availabil... | https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/vpc/__init__.py#L1154-L1180 | |
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/reportlab/pdfbase/pdfdoc.py | python | NoEncryption.encode | (self, t) | return t | encode a string, stream, text | encode a string, stream, text | [
"encode",
"a",
"string",
"stream",
"text"
] | def encode(self, t):
"encode a string, stream, text"
return t | [
"def",
"encode",
"(",
"self",
",",
"t",
")",
":",
"return",
"t"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/reportlab/pdfbase/pdfdoc.py#L101-L103 | |
oracle/oci-python-sdk | 3c1604e4e212008fb6718e2f68cdb5ef71fd5793 | src/oci/identity/identity_client.py | python | IdentityClient.bulk_delete_resources | (self, compartment_id, bulk_delete_resources_details, **kwargs) | Deletes multiple resources in the compartment. All resources must be in the same compartment. You must have the appropriate
permissions to delete the resources in the request. This API can only be invoked from the tenancy's
`home region`__. This operation creates a
:class:`WorkRequest`. Use the :func:`get_work_request`
API to monitor the status of the bulk action.
__ https://docs.cloud.oracle.com/Content/Identity/Tasks/managingregions.htm#Home
:param str compartment_id: (required)
The OCID of the compartment.
:param oci.identity.models.BulkDeleteResourcesDetails bulk_delete_resources_details: (required)
Request object for bulk delete resources in a compartment.
:param str opc_request_id: (optional)
Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
particular request, please provide the request ID.
:param str opc_retry_token: (optional)
A token that uniquely identifies a request so it can be retried in case of a timeout or
server error without risk of executing that same action again. Retry tokens expire after 24
hours, but can be invalidated before then due to conflicting operations (e.g., if a resource
has been deleted and purged from the system, then a retry of the original creation request
may be rejected).
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:return: A :class:`~oci.response.Response` object with data of type None
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/identity/bulk_delete_resources.py.html>`__ to see an example of how to use bulk_delete_resources API. | Deletes multiple resources in the compartment. All resources must be in the same compartment. You must have the appropriate
permissions to delete the resources in the request. This API can only be invoked from the tenancy's
`home region`__. This operation creates a
:class:`WorkRequest`. Use the :func:`get_work_request`
API to monitor the status of the bulk action. | [
"Deletes",
"multiple",
"resources",
"in",
"the",
"compartment",
".",
"All",
"resources",
"must",
"be",
"in",
"the",
"same",
"compartment",
".",
"You",
"must",
"have",
"the",
"appropriate",
"permissions",
"to",
"delete",
"the",
"resources",
"in",
"the",
"reques... | def bulk_delete_resources(self, compartment_id, bulk_delete_resources_details, **kwargs):
"""
Deletes multiple resources in the compartment. All resources must be in the same compartment. You must have the appropriate
permissions to delete the resources in the request. This API can only be invoked from the tenancy's
`home region`__. This operation creates a
:class:`WorkRequest`. Use the :func:`get_work_request`
API to monitor the status of the bulk action.
__ https://docs.cloud.oracle.com/Content/Identity/Tasks/managingregions.htm#Home
:param str compartment_id: (required)
The OCID of the compartment.
:param oci.identity.models.BulkDeleteResourcesDetails bulk_delete_resources_details: (required)
Request object for bulk delete resources in a compartment.
:param str opc_request_id: (optional)
Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
particular request, please provide the request ID.
:param str opc_retry_token: (optional)
A token that uniquely identifies a request so it can be retried in case of a timeout or
server error without risk of executing that same action again. Retry tokens expire after 24
hours, but can be invalidated before then due to conflicting operations (e.g., if a resource
has been deleted and purged from the system, then a retry of the original creation request
may be rejected).
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:return: A :class:`~oci.response.Response` object with data of type None
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/identity/bulk_delete_resources.py.html>`__ to see an example of how to use bulk_delete_resources API.
"""
resource_path = "/compartments/{compartmentId}/actions/bulkDeleteResources"
method = "POST"
# Don't accept unknown kwargs
expected_kwargs = [
"retry_strategy",
"opc_request_id",
"opc_retry_token"
]
extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"bulk_delete_resources got unknown kwargs: {!r}".format(extra_kwargs))
path_params = {
"compartmentId": compartment_id
}
path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing}
for (k, v) in six.iteritems(path_params):
if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0):
raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k))
header_params = {
"accept": "application/json",
"content-type": "application/json",
"opc-request-id": kwargs.get("opc_request_id", missing),
"opc-retry-token": kwargs.get("opc_retry_token", missing)
}
header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None}
retry_strategy = self.base_client.get_preferred_retry_strategy(
operation_retry_strategy=kwargs.get('retry_strategy'),
client_retry_strategy=self.retry_strategy
)
if retry_strategy:
if not isinstance(retry_strategy, retry.NoneRetryStrategy):
self.base_client.add_opc_retry_token_if_needed(header_params)
self.base_client.add_opc_client_retries_header(header_params)
retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback)
return retry_strategy.make_retrying_call(
self.base_client.call_api,
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params,
body=bulk_delete_resources_details)
else:
return self.base_client.call_api(
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params,
body=bulk_delete_resources_details) | [
"def",
"bulk_delete_resources",
"(",
"self",
",",
"compartment_id",
",",
"bulk_delete_resources_details",
",",
"*",
"*",
"kwargs",
")",
":",
"resource_path",
"=",
"\"/compartments/{compartmentId}/actions/bulkDeleteResources\"",
"method",
"=",
"\"POST\"",
"# Don't accept unkno... | https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/identity/identity_client.py#L474-L571 | ||
missionpinball/mpf | 8e6b74cff4ba06d2fec9445742559c1068b88582 | mpf/core/config_player.py | python | ConfigPlayer.get_full_config | (self, value) | return self.machine.config_validator.validate_config(
self.config_file_section, value, base_spec='config_player_common') | Return full config. | Return full config. | [
"Return",
"full",
"config",
"."
] | def get_full_config(self, value):
"""Return full config."""
return self.machine.config_validator.validate_config(
self.config_file_section, value, base_spec='config_player_common') | [
"def",
"get_full_config",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"machine",
".",
"config_validator",
".",
"validate_config",
"(",
"self",
".",
"config_file_section",
",",
"value",
",",
"base_spec",
"=",
"'config_player_common'",
")"
] | https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/core/config_player.py#L214-L217 | |
scrtlabs/catalyst | 2e8029780f2381da7a0729f7b52505e5db5f535b | catalyst/data/data_portal.py | python | DataPortal.get_current_future_chain | (self, continuous_future, dt) | return self.asset_finder.retrieve_all(chain) | Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification.
Returns
-------
future_chain : list[Future]
A list of active futures, where the first index is the current
contract specified by the continuous future definition, the second
is the next upcoming contract and so on. | Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification. | [
"Retrieves",
"the",
"future",
"chain",
"for",
"the",
"contract",
"at",
"the",
"given",
"dt",
"according",
"the",
"continuous_future",
"specification",
"."
] | def get_current_future_chain(self, continuous_future, dt):
"""
Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification.
Returns
-------
future_chain : list[Future]
A list of active futures, where the first index is the current
contract specified by the continuous future definition, the second
is the next upcoming contract and so on.
"""
rf = self._roll_finders[continuous_future.roll_style]
session = self.trading_calendar.minute_to_session_label(dt)
contract_center = rf.get_contract_center(
continuous_future.root_symbol, session,
continuous_future.offset)
oc = self.asset_finder.get_ordered_contracts(
continuous_future.root_symbol)
chain = oc.active_chain(contract_center, session.value)
return self.asset_finder.retrieve_all(chain) | [
"def",
"get_current_future_chain",
"(",
"self",
",",
"continuous_future",
",",
"dt",
")",
":",
"rf",
"=",
"self",
".",
"_roll_finders",
"[",
"continuous_future",
".",
"roll_style",
"]",
"session",
"=",
"self",
".",
"trading_calendar",
".",
"minute_to_session_label... | https://github.com/scrtlabs/catalyst/blob/2e8029780f2381da7a0729f7b52505e5db5f535b/catalyst/data/data_portal.py#L1398-L1419 | |
PyTorchLightning/lightning-bolts | 22e494e546e7fe322d6b4cf36258819c7ba58e02 | pl_bolts/models/rl/common/gym_wrappers.py | python | MaxAndSkipEnv.reset | (self) | return obs | Clear past frame buffer and init.
to first obs. from inner env. | Clear past frame buffer and init. | [
"Clear",
"past",
"frame",
"buffer",
"and",
"init",
"."
] | def reset(self):
"""Clear past frame buffer and init.
to first obs. from inner env.
"""
self._obs_buffer.clear()
obs = self.env.reset()
self._obs_buffer.append(obs)
return obs | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_obs_buffer",
".",
"clear",
"(",
")",
"obs",
"=",
"self",
".",
"env",
".",
"reset",
"(",
")",
"self",
".",
"_obs_buffer",
".",
"append",
"(",
"obs",
")",
"return",
"obs"
] | https://github.com/PyTorchLightning/lightning-bolts/blob/22e494e546e7fe322d6b4cf36258819c7ba58e02/pl_bolts/models/rl/common/gym_wrappers.py#L97-L105 | |
django-nonrel/djangotoolbox | 7e2c47e2ab5ee98d0c0f47c5ccce08e75feda48a | djangotoolbox/db/base.py | python | NonrelDatabaseOperations._value_for_db_key | (self, value, field_kind) | Converts value to be used as a key to an acceptable type.
On default we do no encoding, only allowing key values directly
acceptable by the database for its key type (if any).
The conversion has to be reversible given the field type,
encoding should preserve comparisons.
Use this to expand the set of fields that can be used as
primary keys, return value suitable for a key rather than
a key itself. | Converts value to be used as a key to an acceptable type.
On default we do no encoding, only allowing key values directly
acceptable by the database for its key type (if any). | [
"Converts",
"value",
"to",
"be",
"used",
"as",
"a",
"key",
"to",
"an",
"acceptable",
"type",
".",
"On",
"default",
"we",
"do",
"no",
"encoding",
"only",
"allowing",
"key",
"values",
"directly",
"acceptable",
"by",
"the",
"database",
"for",
"its",
"key",
... | def _value_for_db_key(self, value, field_kind):
"""
Converts value to be used as a key to an acceptable type.
On default we do no encoding, only allowing key values directly
acceptable by the database for its key type (if any).
The conversion has to be reversible given the field type,
encoding should preserve comparisons.
Use this to expand the set of fields that can be used as
primary keys, return value suitable for a key rather than
a key itself.
"""
raise DatabaseError(
"%s may not be used as primary key field." % field_kind) | [
"def",
"_value_for_db_key",
"(",
"self",
",",
"value",
",",
"field_kind",
")",
":",
"raise",
"DatabaseError",
"(",
"\"%s may not be used as primary key field.\"",
"%",
"field_kind",
")"
] | https://github.com/django-nonrel/djangotoolbox/blob/7e2c47e2ab5ee98d0c0f47c5ccce08e75feda48a/djangotoolbox/db/base.py#L622-L636 | ||
matplotlib/matplotlib | 8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322 | lib/matplotlib/spines.py | python | Spine.set_patch_arc | (self, center, radius, theta1, theta2) | Set the spine to be arc-like. | Set the spine to be arc-like. | [
"Set",
"the",
"spine",
"to",
"be",
"arc",
"-",
"like",
"."
] | def set_patch_arc(self, center, radius, theta1, theta2):
"""Set the spine to be arc-like."""
self._patch_type = 'arc'
self._center = center
self._width = radius * 2
self._height = radius * 2
self._theta1 = theta1
self._theta2 = theta2
self._path = mpath.Path.arc(theta1, theta2)
# arc drawn on axes transform
self.set_transform(self.axes.transAxes)
self.stale = True | [
"def",
"set_patch_arc",
"(",
"self",
",",
"center",
",",
"radius",
",",
"theta1",
",",
"theta2",
")",
":",
"self",
".",
"_patch_type",
"=",
"'arc'",
"self",
".",
"_center",
"=",
"center",
"self",
".",
"_width",
"=",
"radius",
"*",
"2",
"self",
".",
"... | https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/spines.py#L87-L98 | ||
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/pip/pip/_vendor/distlib/wheel.py | python | Wheel.tags | (self) | [] | def tags(self):
for pyver in self.pyver:
for abi in self.abi:
for arch in self.arch:
yield pyver, abi, arch | [
"def",
"tags",
"(",
"self",
")",
":",
"for",
"pyver",
"in",
"self",
".",
"pyver",
":",
"for",
"abi",
"in",
"self",
".",
"abi",
":",
"for",
"arch",
"in",
"self",
".",
"arch",
":",
"yield",
"pyver",
",",
"abi",
",",
"arch"
] | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/distlib/wheel.py#L209-L213 | ||||
argoai/argoverse-api | 575c222e7d7fa0c56bdc9dc20f71464c4bea2e6d | argoverse/utils/frustum_clipping.py | python | form_top_clipping_plane | (fx: float, img_height: int) | return top_plane | r"""Form the top clipping plane for a camera view frustum.
In the camera coordinate frame, y is down the imager, x is across the imager,
and z is along the optical axis. The focal length is the distance to the center
of the image plane. We know that a similar triangle is formed as follows::
(x,y,z) (x,y,z)
\\=================//
\\ //
(-w/h,-h/2,fx) (w/h,-h/2,fx)
o-------------o
|\\ //| IMAGE PLANE
| \\ // | IMAGE PLANE
o--\\-----//--o
\\ //
\\ //
O PINHOLE
Normal must point into the frustum. The plane moves -h/2 in y-axis for every
+fx in z-axis, so normal will have negative inverse slope components. The
x-axis component is zero since constant in x.
The "d" in "ax + by + cz = d" is zero because plane goes through origin.
Args:
fx: Horizontal focal length in pixels
img_height: Image height in pixels
Returns:
top_plane: Array of shape (4,) for ax + by + cz = d | r"""Form the top clipping plane for a camera view frustum. | [
"r",
"Form",
"the",
"top",
"clipping",
"plane",
"for",
"a",
"camera",
"view",
"frustum",
"."
] | def form_top_clipping_plane(fx: float, img_height: int) -> np.ndarray:
r"""Form the top clipping plane for a camera view frustum.
In the camera coordinate frame, y is down the imager, x is across the imager,
and z is along the optical axis. The focal length is the distance to the center
of the image plane. We know that a similar triangle is formed as follows::
(x,y,z) (x,y,z)
\\=================//
\\ //
(-w/h,-h/2,fx) (w/h,-h/2,fx)
o-------------o
|\\ //| IMAGE PLANE
| \\ // | IMAGE PLANE
o--\\-----//--o
\\ //
\\ //
O PINHOLE
Normal must point into the frustum. The plane moves -h/2 in y-axis for every
+fx in z-axis, so normal will have negative inverse slope components. The
x-axis component is zero since constant in x.
The "d" in "ax + by + cz = d" is zero because plane goes through origin.
Args:
fx: Horizontal focal length in pixels
img_height: Image height in pixels
Returns:
top_plane: Array of shape (4,) for ax + by + cz = d
"""
top_plane = np.array([0.0, fx, img_height / 2.0, 0.0])
top_plane /= np.linalg.norm(top_plane)
return top_plane | [
"def",
"form_top_clipping_plane",
"(",
"fx",
":",
"float",
",",
"img_height",
":",
"int",
")",
"->",
"np",
".",
"ndarray",
":",
"top_plane",
"=",
"np",
".",
"array",
"(",
"[",
"0.0",
",",
"fx",
",",
"img_height",
"/",
"2.0",
",",
"0.0",
"]",
")",
"... | https://github.com/argoai/argoverse-api/blob/575c222e7d7fa0c56bdc9dc20f71464c4bea2e6d/argoverse/utils/frustum_clipping.py#L110-L143 | |
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | lib-python/2.7/distutils/util.py | python | byte_compile | (py_files,
optimize=0, force=0,
prefix=None, base_dir=None,
verbose=1, dry_run=0,
direct=None) | Byte-compile a collection of Python source files to either .pyc
or .pyo files in the same directory. 'py_files' is a list of files
to compile; any files that don't end in ".py" are silently skipped.
'optimize' must be one of the following:
0 - don't optimize (generate .pyc)
1 - normal optimization (like "python -O")
2 - extra optimization (like "python -OO")
If 'force' is true, all files are recompiled regardless of
timestamps.
The source filename encoded in each bytecode file defaults to the
filenames listed in 'py_files'; you can modify these with 'prefix' and
'basedir'. 'prefix' is a string that will be stripped off of each
source filename, and 'base_dir' is a directory name that will be
prepended (after 'prefix' is stripped). You can supply either or both
(or neither) of 'prefix' and 'base_dir', as you wish.
If 'dry_run' is true, doesn't actually do anything that would
affect the filesystem.
Byte-compilation is either done directly in this interpreter process
with the standard py_compile module, or indirectly by writing a
temporary script and executing it. Normally, you should let
'byte_compile()' figure out to use direct compilation or not (see
the source for details). The 'direct' flag is used by the script
generated in indirect mode; unless you know what you're doing, leave
it set to None. | Byte-compile a collection of Python source files to either .pyc
or .pyo files in the same directory. 'py_files' is a list of files
to compile; any files that don't end in ".py" are silently skipped.
'optimize' must be one of the following:
0 - don't optimize (generate .pyc)
1 - normal optimization (like "python -O")
2 - extra optimization (like "python -OO")
If 'force' is true, all files are recompiled regardless of
timestamps. | [
"Byte",
"-",
"compile",
"a",
"collection",
"of",
"Python",
"source",
"files",
"to",
"either",
".",
"pyc",
"or",
".",
"pyo",
"files",
"in",
"the",
"same",
"directory",
".",
"py_files",
"is",
"a",
"list",
"of",
"files",
"to",
"compile",
";",
"any",
"file... | def byte_compile (py_files,
optimize=0, force=0,
prefix=None, base_dir=None,
verbose=1, dry_run=0,
direct=None):
"""Byte-compile a collection of Python source files to either .pyc
or .pyo files in the same directory. 'py_files' is a list of files
to compile; any files that don't end in ".py" are silently skipped.
'optimize' must be one of the following:
0 - don't optimize (generate .pyc)
1 - normal optimization (like "python -O")
2 - extra optimization (like "python -OO")
If 'force' is true, all files are recompiled regardless of
timestamps.
The source filename encoded in each bytecode file defaults to the
filenames listed in 'py_files'; you can modify these with 'prefix' and
'basedir'. 'prefix' is a string that will be stripped off of each
source filename, and 'base_dir' is a directory name that will be
prepended (after 'prefix' is stripped). You can supply either or both
(or neither) of 'prefix' and 'base_dir', as you wish.
If 'dry_run' is true, doesn't actually do anything that would
affect the filesystem.
Byte-compilation is either done directly in this interpreter process
with the standard py_compile module, or indirectly by writing a
temporary script and executing it. Normally, you should let
'byte_compile()' figure out to use direct compilation or not (see
the source for details). The 'direct' flag is used by the script
generated in indirect mode; unless you know what you're doing, leave
it set to None.
"""
# nothing is done if sys.dont_write_bytecode is True
if sys.dont_write_bytecode:
raise DistutilsByteCompileError('byte-compiling is disabled.')
# First, if the caller didn't force us into direct or indirect mode,
# figure out which mode we should be in. We take a conservative
# approach: choose direct mode *only* if the current interpreter is
# in debug mode and optimize is 0. If we're not in debug mode (-O
# or -OO), we don't know which level of optimization this
# interpreter is running with, so we can't do direct
# byte-compilation and be certain that it's the right thing. Thus,
# always compile indirectly if the current interpreter is in either
# optimize mode, or if either optimization level was requested by
# the caller.
if direct is None:
direct = (__debug__ and optimize == 0)
# "Indirect" byte-compilation: write a temporary script and then
# run it with the appropriate flags.
if not direct:
try:
from tempfile import mkstemp
(script_fd, script_name) = mkstemp(".py")
except ImportError:
from tempfile import mktemp
(script_fd, script_name) = None, mktemp(".py")
log.info("writing byte-compilation script '%s'", script_name)
if not dry_run:
if script_fd is not None:
script = os.fdopen(script_fd, "w")
else:
script = open(script_name, "w")
script.write("""\
from distutils.util import byte_compile
files = [
""")
# XXX would be nice to write absolute filenames, just for
# safety's sake (script should be more robust in the face of
# chdir'ing before running it). But this requires abspath'ing
# 'prefix' as well, and that breaks the hack in build_lib's
# 'byte_compile()' method that carefully tacks on a trailing
# slash (os.sep really) to make sure the prefix here is "just
# right". This whole prefix business is rather delicate -- the
# problem is that it's really a directory, but I'm treating it
# as a dumb string, so trailing slashes and so forth matter.
#py_files = map(os.path.abspath, py_files)
#if prefix:
# prefix = os.path.abspath(prefix)
script.write(string.join(map(repr, py_files), ",\n") + "]\n")
script.write("""
byte_compile(files, optimize=%r, force=%r,
prefix=%r, base_dir=%r,
verbose=%r, dry_run=0,
direct=1)
""" % (optimize, force, prefix, base_dir, verbose))
script.close()
cmd = [sys.executable, script_name]
if optimize == 1:
cmd.insert(1, "-O")
elif optimize == 2:
cmd.insert(1, "-OO")
spawn(cmd, dry_run=dry_run)
execute(os.remove, (script_name,), "removing %s" % script_name,
dry_run=dry_run)
# "Direct" byte-compilation: use the py_compile module to compile
# right here, right now. Note that the script generated in indirect
# mode simply calls 'byte_compile()' in direct mode, a weird sort of
# cross-process recursion. Hey, it works!
else:
from py_compile import compile
for file in py_files:
if file[-3:] != ".py":
# This lets us be lazy and not filter filenames in
# the "install_lib" command.
continue
# Terminology from the py_compile module:
# cfile - byte-compiled file
# dfile - purported source filename (same as 'file' by default)
cfile = file + (__debug__ and "c" or "o")
dfile = file
if prefix:
if file[:len(prefix)] != prefix:
raise ValueError, \
("invalid prefix: filename %r doesn't start with %r"
% (file, prefix))
dfile = dfile[len(prefix):]
if base_dir:
dfile = os.path.join(base_dir, dfile)
cfile_base = os.path.basename(cfile)
if direct:
if force or newer(file, cfile):
log.info("byte-compiling %s to %s", file, cfile_base)
if not dry_run:
compile(file, cfile, dfile)
else:
log.debug("skipping byte-compilation of %s to %s",
file, cfile_base) | [
"def",
"byte_compile",
"(",
"py_files",
",",
"optimize",
"=",
"0",
",",
"force",
"=",
"0",
",",
"prefix",
"=",
"None",
",",
"base_dir",
"=",
"None",
",",
"verbose",
"=",
"1",
",",
"dry_run",
"=",
"0",
",",
"direct",
"=",
"None",
")",
":",
"# nothin... | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/distutils/util.py#L336-L475 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/interactive/ipythonprinting.py | python | load_ipython_extension | (ip) | Load the extension in IPython. | Load the extension in IPython. | [
"Load",
"the",
"extension",
"in",
"IPython",
"."
] | def load_ipython_extension(ip):
"""Load the extension in IPython."""
# Since Python filters deprecation warnings by default,
# we add a filter to make sure this message will be shown.
warnings.simplefilter("once", SymPyDeprecationWarning)
SymPyDeprecationWarning(
feature="using %load_ext sympy.interactive.ipythonprinting",
useinstead="from sympy import init_printing ; init_printing()",
deprecated_since_version="0.7.3",
issue=7013
).warn()
init_printing(ip=ip) | [
"def",
"load_ipython_extension",
"(",
"ip",
")",
":",
"# Since Python filters deprecation warnings by default,",
"# we add a filter to make sure this message will be shown.",
"warnings",
".",
"simplefilter",
"(",
"\"once\"",
",",
"SymPyDeprecationWarning",
")",
"SymPyDeprecationWarni... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/interactive/ipythonprinting.py#L40-L51 | ||
bitcoin-core/HWI | 6871946c2176f2f9777b6ac8f0614d96d99bfa0e | hwilib/descriptor.py | python | _parse_descriptor | (desc: str, ctx: '_ParseDescriptorContext') | :meta private:
Parse a descriptor given the context level we are in.
Used recursively to parse subdescriptors
:param desc: The descriptor string to parse
:param ctx: The :class:`_ParseDescriptorContext` indicating the level we are in
:return: The parsed descriptor
:raises: ValueError: if the descriptor is malformed | :meta private: | [
":",
"meta",
"private",
":"
] | def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext') -> 'Descriptor':
"""
:meta private:
Parse a descriptor given the context level we are in.
Used recursively to parse subdescriptors
:param desc: The descriptor string to parse
:param ctx: The :class:`_ParseDescriptorContext` indicating the level we are in
:return: The parsed descriptor
:raises: ValueError: if the descriptor is malformed
"""
func, expr = _get_func_expr(desc)
if func == "pk":
pubkey, expr = parse_pubkey(expr)
if expr:
raise ValueError("more than one pubkey in pk descriptor")
return PKDescriptor(pubkey)
if func == "pkh":
if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH or ctx == _ParseDescriptorContext.P2WSH):
raise ValueError("Can only have pkh at top level, in sh(), or in wsh()")
pubkey, expr = parse_pubkey(expr)
if expr:
raise ValueError("More than one pubkey in pkh descriptor")
return PKHDescriptor(pubkey)
if func == "sortedmulti" or func == "multi":
if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH or ctx == _ParseDescriptorContext.P2WSH):
raise ValueError("Can only have multi/sortedmulti at top level, in sh(), or in wsh()")
is_sorted = func == "sortedmulti"
comma_idx = expr.index(",")
thresh = int(expr[:comma_idx])
expr = expr[comma_idx + 1:]
pubkeys = []
while expr:
pubkey, expr = parse_pubkey(expr)
pubkeys.append(pubkey)
if len(pubkeys) == 0 or len(pubkeys) > 16:
raise ValueError("Cannot have {} keys in a multisig; must have between 1 and 16 keys, inclusive".format(len(pubkeys)))
elif thresh < 1:
raise ValueError("Multisig threshold cannot be {}, must be at least 1".format(thresh))
elif thresh > len(pubkeys):
raise ValueError("Multisig threshold cannot be larger than the number of keys; threshold is {} but only {} keys specified".format(thresh, len(pubkeys)))
if ctx == _ParseDescriptorContext.TOP and len(pubkeys) > 3:
raise ValueError("Cannot have {} pubkeys in bare multisig: only at most 3 pubkeys")
return MultisigDescriptor(pubkeys, thresh, is_sorted)
if func == "wpkh":
if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH):
raise ValueError("Can only have wpkh() at top level or inside sh()")
pubkey, expr = parse_pubkey(expr)
if expr:
raise ValueError("More than one pubkey in pkh descriptor")
return WPKHDescriptor(pubkey)
if func == "sh":
if ctx != _ParseDescriptorContext.TOP:
raise ValueError("Can only have sh() at top level")
subdesc = _parse_descriptor(expr, _ParseDescriptorContext.P2SH)
return SHDescriptor(subdesc)
if func == "wsh":
if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH):
raise ValueError("Can only have wsh() at top level or inside sh()")
subdesc = _parse_descriptor(expr, _ParseDescriptorContext.P2WSH)
return WSHDescriptor(subdesc)
if func == "tr":
if ctx != _ParseDescriptorContext.TOP:
raise ValueError("Can only have tr at top level")
internal_key, expr = parse_pubkey(expr)
subscripts = []
depths = []
if expr:
# Path from top of the tree to what we're currently processing.
# branches[i] == False: left branch in the i'th step from the top
# branches[i] == true: right branch
branches = []
while True:
# Process open braces
while True:
try:
expr = _get_const(expr, "{")
branches.append(False)
except ValueError:
break
if len(branches) > MAX_TAPROOT_NODES:
raise ValueError("tr() suports at most {MAX_TAPROOT_NODES} nesting levels")
# Process script expression
sarg, expr = _get_expr(expr)
subscripts.append(_parse_descriptor(sarg, _ParseDescriptorContext.P2TR))
depths.append(len(branches))
# Process closing braces
while len(branches) > 0 and branches[-1]:
expr = _get_const(expr, "}")
branches.pop()
# If we're at the end of a left branch, expect a comma
if len(branches) > 0 and not branches[-1]:
expr = _get_const(expr, ",")
branches[-1] = True
if len(branches) == 0:
break
return TRDescriptor(internal_key, subscripts, depths)
if ctx == _ParseDescriptorContext.P2SH:
raise ValueError("A function is needed within P2SH")
elif ctx == _ParseDescriptorContext.P2WSH:
raise ValueError("A function is needed within P2WSH")
raise ValueError("{} is not a valid descriptor function".format(func)) | [
"def",
"_parse_descriptor",
"(",
"desc",
":",
"str",
",",
"ctx",
":",
"'_ParseDescriptorContext'",
")",
"->",
"'Descriptor'",
":",
"func",
",",
"expr",
"=",
"_get_func_expr",
"(",
"desc",
")",
"if",
"func",
"==",
"\"pk\"",
":",
"pubkey",
",",
"expr",
"=",
... | https://github.com/bitcoin-core/HWI/blob/6871946c2176f2f9777b6ac8f0614d96d99bfa0e/hwilib/descriptor.py#L512-L615 | ||
ThilinaRajapakse/simpletransformers | 9323c0398baea0157044e080617b2c4be59de7a9 | simpletransformers/question_answering/qa_dataset_loading_script/qa_dataset_loading_script.py | python | QA._split_generators | (self, dl_manager) | return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"filepath": self.config.data_files},
),
] | Returns SplitGenerators. | Returns SplitGenerators. | [
"Returns",
"SplitGenerators",
"."
] | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"filepath": self.config.data_files},
),
] | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"return",
"[",
"datasets",
".",
"SplitGenerator",
"(",
"name",
"=",
"datasets",
".",
"Split",
".",
"TRAIN",
",",
"gen_kwargs",
"=",
"{",
"\"filepath\"",
":",
"self",
".",
"config",
".",
... | https://github.com/ThilinaRajapakse/simpletransformers/blob/9323c0398baea0157044e080617b2c4be59de7a9/simpletransformers/question_answering/qa_dataset_loading_script/qa_dataset_loading_script.py#L49-L57 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/modulefinder.py | python | ModuleFinder.find_all_submodules | (self, m) | return modules.keys() | [] | def find_all_submodules(self, m):
if not m.__path__:
return
modules = {}
# 'suffixes' used to be a list hardcoded to [".py", ".pyc", ".pyo"].
# But we must also collect Python extension modules - although
# we cannot separate normal dlls from Python extensions.
suffixes = []
for triple in imp.get_suffixes():
suffixes.append(triple[0])
for dir in m.__path__:
try:
names = os.listdir(dir)
except os.error:
self.msg(2, "can't list directory", dir)
continue
for name in names:
mod = None
for suff in suffixes:
n = len(suff)
if name[-n:] == suff:
mod = name[:-n]
break
if mod and mod != "__init__":
modules[mod] = mod
return modules.keys() | [
"def",
"find_all_submodules",
"(",
"self",
",",
"m",
")",
":",
"if",
"not",
"m",
".",
"__path__",
":",
"return",
"modules",
"=",
"{",
"}",
"# 'suffixes' used to be a list hardcoded to [\".py\", \".pyc\", \".pyo\"].",
"# But we must also collect Python extension modules - alth... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/modulefinder.py#L244-L269 | |||
KaihuaTang/VQA2.0-Recent-Approachs-2018.pytorch | 1a4aa392a510a6fb7e1037ca90d06c2eb0dd6cd9 | preprocess-vocab.py | python | extract_vocab | (iterable, top_k=None, start=0) | return vocab | Turns an iterable of list of tokens into a vocabulary.
These tokens could be single answers or word tokens in questions. | Turns an iterable of list of tokens into a vocabulary.
These tokens could be single answers or word tokens in questions. | [
"Turns",
"an",
"iterable",
"of",
"list",
"of",
"tokens",
"into",
"a",
"vocabulary",
".",
"These",
"tokens",
"could",
"be",
"single",
"answers",
"or",
"word",
"tokens",
"in",
"questions",
"."
] | def extract_vocab(iterable, top_k=None, start=0):
""" Turns an iterable of list of tokens into a vocabulary.
These tokens could be single answers or word tokens in questions.
"""
all_tokens = itertools.chain.from_iterable(iterable)
counter = Counter(all_tokens)
if top_k:
most_common = counter.most_common(top_k)
most_common = (t for t, c in most_common)
else:
most_common = counter.keys()
# descending in count, then lexicographical order
tokens = sorted(most_common, key=lambda x: (counter[x], x), reverse=True)
vocab = {t: i for i, t in enumerate(tokens, start=start)}
return vocab | [
"def",
"extract_vocab",
"(",
"iterable",
",",
"top_k",
"=",
"None",
",",
"start",
"=",
"0",
")",
":",
"all_tokens",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"iterable",
")",
"counter",
"=",
"Counter",
"(",
"all_tokens",
")",
"if",
"top_... | https://github.com/KaihuaTang/VQA2.0-Recent-Approachs-2018.pytorch/blob/1a4aa392a510a6fb7e1037ca90d06c2eb0dd6cd9/preprocess-vocab.py#L11-L25 | |
frappe/frappe | b64cab6867dfd860f10ccaf41a4ec04bc890b583 | frappe/database/database.py | python | Database.get_description | (self) | return self._cursor.description | Returns result metadata. | Returns result metadata. | [
"Returns",
"result",
"metadata",
"."
] | def get_description(self):
"""Returns result metadata."""
return self._cursor.description | [
"def",
"get_description",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cursor",
".",
"description"
] | https://github.com/frappe/frappe/blob/b64cab6867dfd860f10ccaf41a4ec04bc890b583/frappe/database/database.py#L322-L324 | |
bbrodriges/pholcidae | 71c83571ad3ab7c60d44b912bd17dcbdd3903a10 | pholcidae2/__init__.py | python | SyncStorage.is_parsed | (self, value) | return value in self._set | Checks if value has been already parsed | Checks if value has been already parsed | [
"Checks",
"if",
"value",
"has",
"been",
"already",
"parsed"
] | def is_parsed(self, value):
"""
Checks if value has been already parsed
"""
return value in self._set | [
"def",
"is_parsed",
"(",
"self",
",",
"value",
")",
":",
"return",
"value",
"in",
"self",
".",
"_set"
] | https://github.com/bbrodriges/pholcidae/blob/71c83571ad3ab7c60d44b912bd17dcbdd3903a10/pholcidae2/__init__.py#L480-L486 | |
Pyomo/pyomo | dbd4faee151084f343b893cc2b0c04cf2b76fd92 | pyomo/core/base/componentuid.py | python | ComponentUID.__le__ | (self, other) | return self < other or self == other | Return True if this CUID <= the 'other' CUID | Return True if this CUID <= the 'other' CUID | [
"Return",
"True",
"if",
"this",
"CUID",
"<",
"=",
"the",
"other",
"CUID"
] | def __le__(self, other):
"Return True if this CUID <= the 'other' CUID"
return self < other or self == other | [
"def",
"__le__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
"<",
"other",
"or",
"self",
"==",
"other"
] | https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/core/base/componentuid.py#L186-L188 | |
ales-tsurko/cells | 4cf7e395cd433762bea70cdc863a346f3a6fe1d0 | packaging/macos/python/lib/python3.7/tkinter/__init__.py | python | Scrollbar.identify | (self, x, y) | return self.tk.call(self._w, 'identify', x, y) | Return the element under position X,Y as one of
"arrow1","slider","arrow2" or "". | Return the element under position X,Y as one of
"arrow1","slider","arrow2" or "". | [
"Return",
"the",
"element",
"under",
"position",
"X",
"Y",
"as",
"one",
"of",
"arrow1",
"slider",
"arrow2",
"or",
"."
] | def identify(self, x, y):
"""Return the element under position X,Y as one of
"arrow1","slider","arrow2" or ""."""
return self.tk.call(self._w, 'identify', x, y) | [
"def",
"identify",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'identify'",
",",
"x",
",",
"y",
")"
] | https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/tkinter/__init__.py#L3061-L3064 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/cpdp/v20190820/models.py | python | QueryAnchorContractInfoRequest.__init__ | (self) | r"""
:param BeginTime: 起始时间,格式为yyyy-MM-dd
:type BeginTime: str
:param EndTime: 起始时间,格式为yyyy-MM-dd
:type EndTime: str | r"""
:param BeginTime: 起始时间,格式为yyyy-MM-dd
:type BeginTime: str
:param EndTime: 起始时间,格式为yyyy-MM-dd
:type EndTime: str | [
"r",
":",
"param",
"BeginTime",
":",
"起始时间,格式为yyyy",
"-",
"MM",
"-",
"dd",
":",
"type",
"BeginTime",
":",
"str",
":",
"param",
"EndTime",
":",
"起始时间,格式为yyyy",
"-",
"MM",
"-",
"dd",
":",
"type",
"EndTime",
":",
"str"
] | def __init__(self):
r"""
:param BeginTime: 起始时间,格式为yyyy-MM-dd
:type BeginTime: str
:param EndTime: 起始时间,格式为yyyy-MM-dd
:type EndTime: str
"""
self.BeginTime = None
self.EndTime = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"BeginTime",
"=",
"None",
"self",
".",
"EndTime",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cpdp/v20190820/models.py#L9140-L9148 | ||
lpty/nlp_base | e82f5a317a335b382e106307c9f047850c6da6f4 | ner/src/corpus.py | python | Corpus.pos_perform | (cls, pos) | 去除词性携带的标签先验知识 | 去除词性携带的标签先验知识 | [
"去除词性携带的标签先验知识"
] | def pos_perform(cls, pos):
"""
去除词性携带的标签先验知识
"""
if pos in cls._maps.keys() and pos != u't':
return u'n'
else:
return pos | [
"def",
"pos_perform",
"(",
"cls",
",",
"pos",
")",
":",
"if",
"pos",
"in",
"cls",
".",
"_maps",
".",
"keys",
"(",
")",
"and",
"pos",
"!=",
"u't'",
":",
"return",
"u'n'",
"else",
":",
"return",
"pos"
] | https://github.com/lpty/nlp_base/blob/e82f5a317a335b382e106307c9f047850c6da6f4/ner/src/corpus.py#L132-L139 | ||
7sDream/zhihu-py3 | bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc | zhihu/answer.py | python | Answer.comment_num | (self) | return int(number) if number.isdigit() else 0 | :return: 答案下评论的数量
:rtype: int | :return: 答案下评论的数量
:rtype: int | [
":",
"return",
":",
"答案下评论的数量",
":",
"rtype",
":",
"int"
] | def comment_num(self):
"""
:return: 答案下评论的数量
:rtype: int
"""
comment = self.soup.select_one("div.answer-actions a.toggle-comment")
comment_num_string = comment.text
number = comment_num_string.split()[0]
return int(number) if number.isdigit() else 0 | [
"def",
"comment_num",
"(",
"self",
")",
":",
"comment",
"=",
"self",
".",
"soup",
".",
"select_one",
"(",
"\"div.answer-actions a.toggle-comment\"",
")",
"comment_num_string",
"=",
"comment",
".",
"text",
"number",
"=",
"comment_num_string",
".",
"split",
"(",
"... | https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/answer.py#L267-L275 | |
FateScript/CenterNet-better | 972dbf2882375d54ec0e06ada21f39baaa997f0c | dl_lib/checkpoint/c2_model_loading.py | python | align_and_update_state_dicts | (model_state_dict, ckpt_state_dict, c2_conversion=True) | Match names between the two state-dict, and update the values of model_state_dict in-place with
copies of the matched tensor in ckpt_state_dict.
If `c2_conversion==True`, `ckpt_state_dict` is assumed to be a Caffe2
model and will be renamed at first.
Strategy: suppose that the models that we will create will have prefixes appended
to each of its keys, for example due to an extra level of nesting that the original
pre-trained weights from ImageNet won't contain. For example, model.state_dict()
might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains
res2.conv1.weight. We thus want to match both parameters together.
For that, we look for each model weight, look among all loaded keys if there is one
that is a suffix of the current weight name, and use it if that's the case.
If multiple matches exist, take the one with longest size
of the corresponding name. For example, for the same model as before, the pretrained
weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case,
we want to match backbone[0].body.conv1.weight to conv1.weight, and
backbone[0].body.res2.conv1.weight to res2.conv1.weight. | Match names between the two state-dict, and update the values of model_state_dict in-place with
copies of the matched tensor in ckpt_state_dict.
If `c2_conversion==True`, `ckpt_state_dict` is assumed to be a Caffe2
model and will be renamed at first. | [
"Match",
"names",
"between",
"the",
"two",
"state",
"-",
"dict",
"and",
"update",
"the",
"values",
"of",
"model_state_dict",
"in",
"-",
"place",
"with",
"copies",
"of",
"the",
"matched",
"tensor",
"in",
"ckpt_state_dict",
".",
"If",
"c2_conversion",
"==",
"T... | def align_and_update_state_dicts(model_state_dict, ckpt_state_dict, c2_conversion=True):
"""
Match names between the two state-dict, and update the values of model_state_dict in-place with
copies of the matched tensor in ckpt_state_dict.
If `c2_conversion==True`, `ckpt_state_dict` is assumed to be a Caffe2
model and will be renamed at first.
Strategy: suppose that the models that we will create will have prefixes appended
to each of its keys, for example due to an extra level of nesting that the original
pre-trained weights from ImageNet won't contain. For example, model.state_dict()
might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains
res2.conv1.weight. We thus want to match both parameters together.
For that, we look for each model weight, look among all loaded keys if there is one
that is a suffix of the current weight name, and use it if that's the case.
If multiple matches exist, take the one with longest size
of the corresponding name. For example, for the same model as before, the pretrained
weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case,
we want to match backbone[0].body.conv1.weight to conv1.weight, and
backbone[0].body.res2.conv1.weight to res2.conv1.weight.
"""
model_keys = sorted(list(model_state_dict.keys()))
if c2_conversion:
ckpt_state_dict, original_keys = convert_c2_detectron_names(ckpt_state_dict)
# original_keys: the name in the original dict (before renaming)
else:
original_keys = {x: x for x in ckpt_state_dict.keys()}
ckpt_keys = sorted(list(ckpt_state_dict.keys()))
def match(a, b):
# Matched ckpt_key should be a complete (starts with '.') suffix.
# For example, roi_heads.mesh_head.whatever_conv1 does not match conv1,
# but matches whatever_conv1 or mesh_head.whatever_conv1.
return a == b or a.endswith("." + b)
# get a matrix of string matches, where each (i, j) entry correspond to the size of the
# ckpt_key string, if it matches
match_matrix = [len(j) if match(i, j) else 0 for i in model_keys for j in ckpt_keys]
match_matrix = torch.as_tensor(match_matrix).view(len(model_keys), len(ckpt_keys))
# use the matched one with longest size in case of multiple matches
max_match_size, idxs = match_matrix.max(1)
# remove indices that correspond to no-match
idxs[max_match_size == 0] = -1
# used for logging
max_len_model = max(len(key) for key in model_keys) if model_keys else 1
max_len_ckpt = max(len(key) for key in ckpt_keys) if ckpt_keys else 1
log_str_template = "{: <{}} loaded from {: <{}} of shape {}"
logger = logging.getLogger(__name__)
# matched_pairs (matched checkpoint key --> matched model key)
matched_keys = {}
for idx_model, idx_ckpt in enumerate(idxs.tolist()):
if idx_ckpt == -1:
continue
key_model = model_keys[idx_model]
key_ckpt = ckpt_keys[idx_ckpt]
value_ckpt = ckpt_state_dict[key_ckpt]
shape_in_model = model_state_dict[key_model].shape
if shape_in_model != value_ckpt.shape:
logger.warning(
"Shape of {} in checkpoint is {}, while shape of {} in model is {}.".format(
key_ckpt, value_ckpt.shape, key_model, shape_in_model
)
)
logger.warning(
"{} will not be loaded. Please double check and see if this is desired.".format(
key_ckpt
)
)
continue
model_state_dict[key_model] = value_ckpt.clone()
if key_ckpt in matched_keys: # already added to matched_keys
logger.error(
"Ambiguity found for {} in checkpoint!"
"It matches at least two keys in the model ({} and {}).".format(
key_ckpt, key_model, matched_keys[key_ckpt]
)
)
raise ValueError("Cannot match one checkpoint key to multiple keys in the model.")
matched_keys[key_ckpt] = key_model
logger.info(
log_str_template.format(
key_model,
max_len_model,
original_keys[key_ckpt],
max_len_ckpt,
tuple(shape_in_model),
)
)
matched_model_keys = matched_keys.values()
matched_ckpt_keys = matched_keys.keys()
# print warnings about unmatched keys on both side
unmatched_model_keys = [k for k in model_keys if k not in matched_model_keys]
if len(unmatched_model_keys):
logger.info(get_missing_parameters_message(unmatched_model_keys))
unmatched_ckpt_keys = [k for k in ckpt_keys if k not in matched_ckpt_keys]
if len(unmatched_ckpt_keys):
logger.info(
get_unexpected_parameters_message(original_keys[x] for x in unmatched_ckpt_keys)
) | [
"def",
"align_and_update_state_dicts",
"(",
"model_state_dict",
",",
"ckpt_state_dict",
",",
"c2_conversion",
"=",
"True",
")",
":",
"model_keys",
"=",
"sorted",
"(",
"list",
"(",
"model_state_dict",
".",
"keys",
"(",
")",
")",
")",
"if",
"c2_conversion",
":",
... | https://github.com/FateScript/CenterNet-better/blob/972dbf2882375d54ec0e06ada21f39baaa997f0c/dl_lib/checkpoint/c2_model_loading.py#L211-L313 | ||
landlab/landlab | a5dd80b8ebfd03d1ba87ef6c4368c409485f222c | landlab/components/species_evolution/zone_taxon.py | python | ZoneTaxon.zones | (self) | return self._zones | The zones of the taxon. | The zones of the taxon. | [
"The",
"zones",
"of",
"the",
"taxon",
"."
] | def zones(self):
"""The zones of the taxon."""
return self._zones | [
"def",
"zones",
"(",
"self",
")",
":",
"return",
"self",
".",
"_zones"
] | https://github.com/landlab/landlab/blob/a5dd80b8ebfd03d1ba87ef6c4368c409485f222c/landlab/components/species_evolution/zone_taxon.py#L136-L138 | |
etetoolkit/ete | 2b207357dc2a40ccad7bfd8f54964472c72e4726 | ete3/nexml/_nexml.py | python | RnaSeqs.exportLiteralChildren | (self, outfile, level, name_) | [] | def exportLiteralChildren(self, outfile, level, name_):
super(RnaSeqs, self).exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('meta=[\n')
level += 1
for meta_ in self.meta:
showIndent(outfile, level)
outfile.write('model_.Meta(\n')
meta_.exportLiteral(outfile, level, name_='Meta')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.format is not None:
showIndent(outfile, level)
outfile.write('format=model_.RNAFormat(\n')
self.format.exportLiteral(outfile, level, name_='format')
showIndent(outfile, level)
outfile.write('),\n')
if self.matrix is not None:
showIndent(outfile, level)
outfile.write('matrix=model_.RNASeqMatrix(\n')
self.matrix.exportLiteral(outfile, level, name_='matrix')
showIndent(outfile, level)
outfile.write('),\n') | [
"def",
"exportLiteralChildren",
"(",
"self",
",",
"outfile",
",",
"level",
",",
"name_",
")",
":",
"super",
"(",
"RnaSeqs",
",",
"self",
")",
".",
"exportLiteralChildren",
"(",
"outfile",
",",
"level",
",",
"name_",
")",
"showIndent",
"(",
"outfile",
",",
... | https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/nexml/_nexml.py#L14738-L14763 | ||||
lilydjwg/winterpy | 3864a463386202b9c9c6ce8ba902878e40f3084c | pylib/htmlutils.py | python | parse_document_from_requests | (response, session=None, *, encoding=None) | return doc | ``response``: requests ``Response`` object, or URL
``encoding``: override detected encoding | ``response``: requests ``Response`` object, or URL
``encoding``: override detected encoding | [
"response",
":",
"requests",
"Response",
"object",
"or",
"URL",
"encoding",
":",
"override",
"detected",
"encoding"
] | def parse_document_from_requests(response, session=None, *, encoding=None):
'''
``response``: requests ``Response`` object, or URL
``encoding``: override detected encoding
'''
if isinstance(response, str):
if session is None:
raise ValueError('URL given but no session')
r = session.get(response)
else:
r = response
if encoding:
r.encoding = encoding
# fromstring handles bytes well
# https://stackoverflow.com/a/15305248/296473
parser = html.HTMLParser(encoding=encoding or r.encoding)
doc = html.fromstring(r.content, base_url=r.url, parser=parser)
doc.make_links_absolute()
return doc | [
"def",
"parse_document_from_requests",
"(",
"response",
",",
"session",
"=",
"None",
",",
"*",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"response",
",",
"str",
")",
":",
"if",
"session",
"is",
"None",
":",
"raise",
"ValueError",
"... | https://github.com/lilydjwg/winterpy/blob/3864a463386202b9c9c6ce8ba902878e40f3084c/pylib/htmlutils.py#L58-L78 | |
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/telnetlib.py | python | Telnet.open | (self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT) | Connect to a host.
The optional second argument is the port number, which
defaults to the standard telnet port (23).
Don't try to reopen an already connected instance. | Connect to a host. | [
"Connect",
"to",
"a",
"host",
"."
] | def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
"""Connect to a host.
The optional second argument is the port number, which
defaults to the standard telnet port (23).
Don't try to reopen an already connected instance.
"""
self.eof = 0
if not port:
port = TELNET_PORT
self.host = host
self.port = port
self.timeout = timeout
self.sock = socket.create_connection((host, port), timeout) | [
"def",
"open",
"(",
"self",
",",
"host",
",",
"port",
"=",
"0",
",",
"timeout",
"=",
"socket",
".",
"_GLOBAL_DEFAULT_TIMEOUT",
")",
":",
"self",
".",
"eof",
"=",
"0",
"if",
"not",
"port",
":",
"port",
"=",
"TELNET_PORT",
"self",
".",
"host",
"=",
"... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/telnetlib.py#L220-L234 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/insteon/api/properties.py | python | _get_radio_button_properties | (device) | return props, schema | Return the values and schema to set KPL buttons as radio buttons. | Return the values and schema to set KPL buttons as radio buttons. | [
"Return",
"the",
"values",
"and",
"schema",
"to",
"set",
"KPL",
"buttons",
"as",
"radio",
"buttons",
"."
] | def _get_radio_button_properties(device):
"""Return the values and schema to set KPL buttons as radio buttons."""
rb_groups = _calc_radio_button_groups(device)
props = []
schema = {}
index = 0
remaining_buttons = []
buttons_in_groups = list(chain.from_iterable(rb_groups))
# Identify buttons not belonging to any group
for button in device.groups:
if button not in buttons_in_groups:
remaining_buttons.append(button)
for rb_group in rb_groups:
name = f"{RADIO_BUTTON_GROUP_PROP}{index}"
button_1 = rb_group[0]
button_str = f"_{button_1}" if button_1 != 1 else ""
on_mask = device.properties[f"{ON_MASK}{button_str}"]
off_mask = device.properties[f"{OFF_MASK}{button_str}"]
modified = on_mask.is_dirty or off_mask.is_dirty
props.append(
{
"name": name,
"modified": modified,
"value": rb_group,
}
)
options = {
button: device.groups[button].name
for button in chain.from_iterable([rb_group, remaining_buttons])
}
rb_schema = vol.Schema({vol.Optional(name): cv.multi_select(options)})
rb_schema_dict = voluptuous_serialize.convert(
rb_schema, custom_serializer=cv.custom_serializer
)
schema[name] = rb_schema_dict[0]
index += 1
if len(remaining_buttons) > 1:
name = f"{RADIO_BUTTON_GROUP_PROP}{index}"
props.append(
{
"name": name,
"modified": False,
"value": [],
}
)
options = {button: device.groups[button].name for button in remaining_buttons}
rb_schema = vol.Schema({vol.Optional(name): cv.multi_select(options)})
rb_schema_dict = voluptuous_serialize.convert(
rb_schema, custom_serializer=cv.custom_serializer
)
schema[name] = rb_schema_dict[0]
return props, schema | [
"def",
"_get_radio_button_properties",
"(",
"device",
")",
":",
"rb_groups",
"=",
"_calc_radio_button_groups",
"(",
"device",
")",
"props",
"=",
"[",
"]",
"schema",
"=",
"{",
"}",
"index",
"=",
"0",
"remaining_buttons",
"=",
"[",
"]",
"buttons_in_groups",
"=",... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/insteon/api/properties.py#L188-L251 | |
django-nonrel/django-nonrel | 4fbfe7344481a5eab8698f79207f09124310131b | django/utils/dictconfig.py | python | BaseConfigurator.as_tuple | (self, value) | return value | Utility function which converts lists to tuples. | Utility function which converts lists to tuples. | [
"Utility",
"function",
"which",
"converts",
"lists",
"to",
"tuples",
"."
] | def as_tuple(self, value):
"""Utility function which converts lists to tuples."""
if isinstance(value, list):
value = tuple(value)
return value | [
"def",
"as_tuple",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"tuple",
"(",
"value",
")",
"return",
"value"
] | https://github.com/django-nonrel/django-nonrel/blob/4fbfe7344481a5eab8698f79207f09124310131b/django/utils/dictconfig.py#L260-L264 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py | python | Standard_Suite_Events.move | (self, _object, _attributes={}, **_arguments) | move: Move object(s) to a new location.
Required argument: the object for the command
Keyword argument to: The new location for the object(s).
Keyword argument _attributes: AppleEvent attribute dictionary | move: Move object(s) to a new location.
Required argument: the object for the command
Keyword argument to: The new location for the object(s).
Keyword argument _attributes: AppleEvent attribute dictionary | [
"move",
":",
"Move",
"object",
"(",
"s",
")",
"to",
"a",
"new",
"location",
".",
"Required",
"argument",
":",
"the",
"object",
"for",
"the",
"command",
"Keyword",
"argument",
"to",
":",
"The",
"new",
"location",
"for",
"the",
"object",
"(",
"s",
")",
... | def move(self, _object, _attributes={}, **_arguments):
"""move: Move object(s) to a new location.
Required argument: the object for the command
Keyword argument to: The new location for the object(s).
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'core'
_subcode = 'move'
aetools.keysubst(_arguments, self._argmap_move)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"move",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'core'",
"_subcode",
"=",
"'move'",
"aetools",
".",
"keysubst",
"(",
"_arguments",
",",
"self",
".",
"_argmap_move",
")... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py#L193-L212 | ||
tensorflow/lingvo | ce10019243d954c3c3ebe739f7589b5eebfdf907 | lingvo/tasks/car/detection_3d_lib.py | python | RandomPadOrTrimTo | (tensor_list, num_points_out, seed=None) | return (data, padding_tensor) | Pads or Trims a list of Tensors on the major dimension.
Slices if there are more points, or pads if not enough.
In this implementation:
Padded points are random duplications of real points.
Sliced points are a random subset of the real points.
Args:
tensor_list: A list of tf.Tensor objects to pad or trim along first dim. All
tensors are expected to have the same first dimension.
num_points_out: An int for the requested number of points to trim/pad to.
seed: Random seed to use for random generators.
Returns:
A tuple of output_tensors and a padding indicator.
- output_tensors: A list of padded or trimmed versions of our tensor_list
input tensors, all with the same first dimension.
- padding: A tf.float32 tf.Tensor of shape [num_points_out] with 0 if the
point is real, 1 if it is padded. | Pads or Trims a list of Tensors on the major dimension. | [
"Pads",
"or",
"Trims",
"a",
"list",
"of",
"Tensors",
"on",
"the",
"major",
"dimension",
"."
] | def RandomPadOrTrimTo(tensor_list, num_points_out, seed=None):
"""Pads or Trims a list of Tensors on the major dimension.
Slices if there are more points, or pads if not enough.
In this implementation:
Padded points are random duplications of real points.
Sliced points are a random subset of the real points.
Args:
tensor_list: A list of tf.Tensor objects to pad or trim along first dim. All
tensors are expected to have the same first dimension.
num_points_out: An int for the requested number of points to trim/pad to.
seed: Random seed to use for random generators.
Returns:
A tuple of output_tensors and a padding indicator.
- output_tensors: A list of padded or trimmed versions of our tensor_list
input tensors, all with the same first dimension.
- padding: A tf.float32 tf.Tensor of shape [num_points_out] with 0 if the
point is real, 1 if it is padded.
"""
actual_num = tf.shape(tensor_list[0])[0]
point_idx = tf.range(num_points_out, dtype=tf.int32)
padding_tensor = tf.where(point_idx < actual_num,
tf.zeros([num_points_out], dtype=tf.float32),
tf.ones([num_points_out], dtype=tf.float32))
def _Slicing():
# Choose a random set of indices.
indices = tf.range(actual_num)
indices = tf.random.shuffle(indices, seed=seed)[:num_points_out]
return [tf.gather(t, indices, axis=0) for t in tensor_list]
def _Padding():
indices = tf.random.uniform([num_points_out - actual_num],
minval=0,
maxval=actual_num,
dtype=tf.int32,
seed=seed)
padded = []
for t in tensor_list:
padded.append(tf.concat([t, tf.gather(t, indices, axis=0)], axis=0))
return padded
def _PadZeros():
padded = []
for t in tensor_list:
shape = tf.concat([[num_points_out], tf.shape(t)[1:]], axis=0)
padded.append(tf.zeros(shape=shape, dtype=t.dtype))
return padded
data = tf.cond(
actual_num > num_points_out,
_Slicing, lambda: tf.cond(tf.equal(actual_num, 0), _PadZeros, _Padding))
return (data, padding_tensor) | [
"def",
"RandomPadOrTrimTo",
"(",
"tensor_list",
",",
"num_points_out",
",",
"seed",
"=",
"None",
")",
":",
"actual_num",
"=",
"tf",
".",
"shape",
"(",
"tensor_list",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"point_idx",
"=",
"tf",
".",
"range",
"(",
"num_poi... | https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/tasks/car/detection_3d_lib.py#L818-L874 | |
hydroshare/hydroshare | 7ba563b55412f283047fb3ef6da367d41dec58c6 | hs_core/hydroshare/utils.py | python | get_user_party_name | (user) | return party_name | [] | def get_user_party_name(user):
user_profile = get_profile(user)
if user.last_name and user.first_name:
if user_profile.middle_name:
party_name = '%s, %s %s' % (user.last_name, user.first_name,
user_profile.middle_name)
else:
party_name = '%s, %s' % (user.last_name, user.first_name)
elif user.last_name:
party_name = user.last_name
elif user.first_name:
party_name = user.first_name
elif user_profile.middle_name:
party_name = user_profile.middle_name
else:
party_name = ''
return party_name | [
"def",
"get_user_party_name",
"(",
"user",
")",
":",
"user_profile",
"=",
"get_profile",
"(",
"user",
")",
"if",
"user",
".",
"last_name",
"and",
"user",
".",
"first_name",
":",
"if",
"user_profile",
".",
"middle_name",
":",
"party_name",
"=",
"'%s, %s %s'",
... | https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_core/hydroshare/utils.py#L837-L853 | |||
cuthbertLab/music21 | bd30d4663e52955ed922c10fdf541419d8c67671 | music21/tree/verticality.py | python | Verticality.timeToNextEvent | (self) | return common.opFrac(nextOffset - self.offset) | Returns a float or Fraction of the quarterLength to the next
event (usually the next Verticality, but also to the end of the piece).
Returns None if there is no next event, such as when the verticality
is divorced from its tree. | Returns a float or Fraction of the quarterLength to the next
event (usually the next Verticality, but also to the end of the piece). | [
"Returns",
"a",
"float",
"or",
"Fraction",
"of",
"the",
"quarterLength",
"to",
"the",
"next",
"event",
"(",
"usually",
"the",
"next",
"Verticality",
"but",
"also",
"to",
"the",
"end",
"of",
"the",
"piece",
")",
"."
] | def timeToNextEvent(self) -> Optional[OffsetQL]:
'''
Returns a float or Fraction of the quarterLength to the next
event (usually the next Verticality, but also to the end of the piece).
Returns None if there is no next event, such as when the verticality
is divorced from its tree.
'''
nextOffset = self.nextStartOffset
if nextOffset is None:
if self.timespanTree is None:
return None
nextOffset = self.timespanTree.endTime
return common.opFrac(nextOffset - self.offset) | [
"def",
"timeToNextEvent",
"(",
"self",
")",
"->",
"Optional",
"[",
"OffsetQL",
"]",
":",
"nextOffset",
"=",
"self",
".",
"nextStartOffset",
"if",
"nextOffset",
"is",
"None",
":",
"if",
"self",
".",
"timespanTree",
"is",
"None",
":",
"return",
"None",
"next... | https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/tree/verticality.py#L536-L549 | |
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | calendarserver/tap/util.py | python | MemoryLimitService.__init__ | (self, processMonitor, intervalSeconds, limitBytes, residentOnly, reactor=None) | @param processMonitor: the DelayedStartupProcessMonitor
@param intervalSeconds: how often to check
@type intervalSeconds: C{int}
@param limitBytes: any monitored process over this limit is stopped
@type limitBytes: C{int}
@param residentOnly: whether only resident memory should be included
@type residentOnly: C{boolean}
@param reactor: for testing | [] | def __init__(self, processMonitor, intervalSeconds, limitBytes, residentOnly, reactor=None):
"""
@param processMonitor: the DelayedStartupProcessMonitor
@param intervalSeconds: how often to check
@type intervalSeconds: C{int}
@param limitBytes: any monitored process over this limit is stopped
@type limitBytes: C{int}
@param residentOnly: whether only resident memory should be included
@type residentOnly: C{boolean}
@param reactor: for testing
"""
self._processMonitor = processMonitor
self._seconds = intervalSeconds
self._bytes = limitBytes
self._residentOnly = residentOnly
self._delayedCall = None
if reactor is None:
from twisted.internet import reactor
self._reactor = reactor
# Unit tests can swap out _memoryForPID
self._memoryForPID = memoryForPID | [
"def",
"__init__",
"(",
"self",
",",
"processMonitor",
",",
"intervalSeconds",
",",
"limitBytes",
",",
"residentOnly",
",",
"reactor",
"=",
"None",
")",
":",
"self",
".",
"_processMonitor",
"=",
"processMonitor",
"self",
".",
"_seconds",
"=",
"intervalSeconds",
... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/calendarserver/tap/util.py#L925-L946 | |||
JoinMarket-Org/joinmarket-clientserver | 8b3d21f226185e31aa10e8e16cdfc719cea4a98e | jmclient/jmclient/podle.py | python | add_external_commitments | (ecs) | To allow external functions to add
PoDLE commitments that were calculated elsewhere. | To allow external functions to add
PoDLE commitments that were calculated elsewhere. | [
"To",
"allow",
"external",
"functions",
"to",
"add",
"PoDLE",
"commitments",
"that",
"were",
"calculated",
"elsewhere",
"."
] | def add_external_commitments(ecs):
"""To allow external functions to add
PoDLE commitments that were calculated elsewhere.
"""
update_commitments(external_to_add=ecs) | [
"def",
"add_external_commitments",
"(",
"ecs",
")",
":",
"update_commitments",
"(",
"external_to_add",
"=",
"ecs",
")"
] | https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/8b3d21f226185e31aa10e8e16cdfc719cea4a98e/jmclient/jmclient/podle.py#L372-L376 | ||
Toblerity/rtree | eb04ef8933418ab108a45b6576abea95d6cbcbdb | setup.py | python | InstallPlatlib.finalize_options | (self) | Copy the shared libraries into the wheel. Note that this
will *only* check in `rtree/lib` rather than anywhere on
the system so if you are building a wheel you *must* copy or
symlink the `.so`/`.dll`/`.dylib` files into `rtree/lib`. | Copy the shared libraries into the wheel. Note that this
will *only* check in `rtree/lib` rather than anywhere on
the system so if you are building a wheel you *must* copy or
symlink the `.so`/`.dll`/`.dylib` files into `rtree/lib`. | [
"Copy",
"the",
"shared",
"libraries",
"into",
"the",
"wheel",
".",
"Note",
"that",
"this",
"will",
"*",
"only",
"*",
"check",
"in",
"rtree",
"/",
"lib",
"rather",
"than",
"anywhere",
"on",
"the",
"system",
"so",
"if",
"you",
"are",
"building",
"a",
"wh... | def finalize_options(self):
"""
Copy the shared libraries into the wheel. Note that this
will *only* check in `rtree/lib` rather than anywhere on
the system so if you are building a wheel you *must* copy or
symlink the `.so`/`.dll`/`.dylib` files into `rtree/lib`.
"""
# use for checking extension types
from fnmatch import fnmatch
install.finalize_options(self)
if self.distribution.has_ext_modules():
self.install_lib = self.install_platlib
# now copy over libspatialindex
# get the location of the shared library on the filesystem
# where we're putting the shared library in the build directory
target_dir = os.path.join(self.build_lib, 'rtree', 'lib')
# where are we checking for shared libraries
source_dir = os.path.join(_cwd, 'rtree', 'lib')
# what patterns represent shared libraries
patterns = {'*.so',
'libspatialindex*dylib',
'*.dll'}
if not os.path.isdir(source_dir):
# no copying of binary parts to library
# this is so `pip install .` works even
# if `rtree/lib` isn't populated
return
for file_name in os.listdir(source_dir):
# make sure file name is lower case
check = file_name.lower()
# use filename pattern matching to see if it is
# a shared library format file
if not any(fnmatch(check, p) for p in patterns):
continue
# if the source isn't a file skip it
if not os.path.isfile(os.path.join(source_dir, file_name)):
continue
# make build directory if it doesn't exist yet
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
# copy the source file to the target directory
self.copy_file(
os.path.join(source_dir, file_name),
os.path.join(target_dir, file_name)) | [
"def",
"finalize_options",
"(",
"self",
")",
":",
"# use for checking extension types",
"from",
"fnmatch",
"import",
"fnmatch",
"install",
".",
"finalize_options",
"(",
"self",
")",
"if",
"self",
".",
"distribution",
".",
"has_ext_modules",
"(",
")",
":",
"self",
... | https://github.com/Toblerity/rtree/blob/eb04ef8933418ab108a45b6576abea95d6cbcbdb/setup.py#L38-L89 | ||
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-35/fabmetheus_utilities/geometry/geometry_utilities/evaluate.py | python | EvaluatorConcatenate.executePairOperation | (self, evaluators, evaluatorIndex, operationLevel) | Operate on two evaluators. | Operate on two evaluators. | [
"Operate",
"on",
"two",
"evaluators",
"."
] | def executePairOperation(self, evaluators, evaluatorIndex, operationLevel):
'Operate on two evaluators.'
if operationLevel != 80:
return
leftIndex = evaluatorIndex - 1
if leftIndex < 0:
del evaluators[evaluatorIndex]
return
rightIndex = evaluatorIndex + 1
if rightIndex >= len(evaluators):
del evaluators[ leftIndex : rightIndex ]
return
leftValue = evaluators[leftIndex].value
rightValue = evaluators[rightIndex].value
if leftValue.__class__ == rightValue.__class__ and (leftValue.__class__ == list or rightValue.__class__ == str):
evaluators[leftIndex].value = leftValue + rightValue
del evaluators[ evaluatorIndex : evaluatorIndex + 2 ]
return
if leftValue.__class__ == list and rightValue.__class__ == int:
if rightValue > 0:
originalList = leftValue[:]
for copyIndex in xrange( rightValue - 1 ):
leftValue += originalList
evaluators[leftIndex].value = leftValue
del evaluators[ evaluatorIndex : evaluatorIndex + 2 ]
return
if leftValue.__class__ == dict and rightValue.__class__ == dict:
leftValue.update(rightValue)
evaluators[leftIndex].value = leftValue
del evaluators[ evaluatorIndex : evaluatorIndex + 2 ]
return
del evaluators[ leftIndex : evaluatorIndex + 2 ] | [
"def",
"executePairOperation",
"(",
"self",
",",
"evaluators",
",",
"evaluatorIndex",
",",
"operationLevel",
")",
":",
"if",
"operationLevel",
"!=",
"80",
":",
"return",
"leftIndex",
"=",
"evaluatorIndex",
"-",
"1",
"if",
"leftIndex",
"<",
"0",
":",
"del",
"... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/geometry/geometry_utilities/evaluate.py#L1358-L1389 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/logic/inference.py | python | KB.__init__ | (self, sentence=None) | [] | def __init__(self, sentence=None):
self.clauses = []
if sentence:
self.tell(sentence) | [
"def",
"__init__",
"(",
"self",
",",
"sentence",
"=",
"None",
")",
":",
"self",
".",
"clauses",
"=",
"[",
"]",
"if",
"sentence",
":",
"self",
".",
"tell",
"(",
"sentence",
")"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/logic/inference.py#L169-L172 | ||||
bokeh/bokeh | a00e59da76beb7b9f83613533cfd3aced1df5f06 | bokeh/server/server.py | python | BaseServer.get_session | (self, app_path: str, session_id: ID) | return self._tornado.get_session(app_path, session_id) | Get an active a session by name application path and session ID.
Args:
app_path (str) :
The configured application path for the application to return
a session for.
session_id (str) :
The session ID of the session to retrieve.
Returns:
ServerSession | Get an active a session by name application path and session ID. | [
"Get",
"an",
"active",
"a",
"session",
"by",
"name",
"application",
"path",
"and",
"session",
"ID",
"."
] | def get_session(self, app_path: str, session_id: ID) -> ServerSession:
''' Get an active a session by name application path and session ID.
Args:
app_path (str) :
The configured application path for the application to return
a session for.
session_id (str) :
The session ID of the session to retrieve.
Returns:
ServerSession
'''
return self._tornado.get_session(app_path, session_id) | [
"def",
"get_session",
"(",
"self",
",",
"app_path",
":",
"str",
",",
"session_id",
":",
"ID",
")",
"->",
"ServerSession",
":",
"return",
"self",
".",
"_tornado",
".",
"get_session",
"(",
"app_path",
",",
"session_id",
")"
] | https://github.com/bokeh/bokeh/blob/a00e59da76beb7b9f83613533cfd3aced1df5f06/bokeh/server/server.py#L214-L229 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/lxml-3.3.6/src/lxml/html/diff.py | python | htmldiff | (old_html, new_html) | return fixup_ins_del_tags(result) | Do a diff of the old and new document. The documents are HTML
*fragments* (str/UTF8 or unicode), they are not complete documents
(i.e., no <html> tag).
Returns HTML with <ins> and <del> tags added around the
appropriate text.
Markup is generally ignored, with the markup from new_html
preserved, and possibly some markup from old_html (though it is
considered acceptable to lose some of the old markup). Only the
words in the HTML are diffed. The exception is <img> tags, which
are treated like words, and the href attribute of <a> tags, which
are noted inside the tag itself when there are changes. | Do a diff of the old and new document. The documents are HTML
*fragments* (str/UTF8 or unicode), they are not complete documents
(i.e., no <html> tag). | [
"Do",
"a",
"diff",
"of",
"the",
"old",
"and",
"new",
"document",
".",
"The",
"documents",
"are",
"HTML",
"*",
"fragments",
"*",
"(",
"str",
"/",
"UTF8",
"or",
"unicode",
")",
"they",
"are",
"not",
"complete",
"documents",
"(",
"i",
".",
"e",
".",
"... | def htmldiff(old_html, new_html):
## FIXME: this should take parsed documents too, and use their body
## or other content.
""" Do a diff of the old and new document. The documents are HTML
*fragments* (str/UTF8 or unicode), they are not complete documents
(i.e., no <html> tag).
Returns HTML with <ins> and <del> tags added around the
appropriate text.
Markup is generally ignored, with the markup from new_html
preserved, and possibly some markup from old_html (though it is
considered acceptable to lose some of the old markup). Only the
words in the HTML are diffed. The exception is <img> tags, which
are treated like words, and the href attribute of <a> tags, which
are noted inside the tag itself when there are changes.
"""
old_html_tokens = tokenize(old_html)
new_html_tokens = tokenize(new_html)
result = htmldiff_tokens(old_html_tokens, new_html_tokens)
result = ''.join(result).strip()
return fixup_ins_del_tags(result) | [
"def",
"htmldiff",
"(",
"old_html",
",",
"new_html",
")",
":",
"## FIXME: this should take parsed documents too, and use their body",
"## or other content.",
"old_html_tokens",
"=",
"tokenize",
"(",
"old_html",
")",
"new_html_tokens",
"=",
"tokenize",
"(",
"new_html",
")",
... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/lxml-3.3.6/src/lxml/html/diff.py#L154-L175 | |
xhochy/fletcher | 39ce11d71e4ac1e95725d46be21bb38f3ea04349 | benchmarks/text.py | python | TimeSuiteText.time_casefold | (self) | [] | def time_casefold(self):
self.df["str"].str.casefold() | [
"def",
"time_casefold",
"(",
"self",
")",
":",
"self",
".",
"df",
"[",
"\"str\"",
"]",
".",
"str",
".",
"casefold",
"(",
")"
] | https://github.com/xhochy/fletcher/blob/39ce11d71e4ac1e95725d46be21bb38f3ea04349/benchmarks/text.py#L99-L100 | ||||
pikpikcu/Pentest-Tools-Framework | cd6e6107764a809943dc4e073cde8149c1a2cd03 | modules/dirsearch/thirdparty/requests/utils.py | python | get_environ_proxies | (url) | Return a dict of environment proxies. | Return a dict of environment proxies. | [
"Return",
"a",
"dict",
"of",
"environment",
"proxies",
"."
] | def get_environ_proxies(url):
"""Return a dict of environment proxies."""
if should_bypass_proxies(url):
return {}
else:
return getproxies() | [
"def",
"get_environ_proxies",
"(",
"url",
")",
":",
"if",
"should_bypass_proxies",
"(",
"url",
")",
":",
"return",
"{",
"}",
"else",
":",
"return",
"getproxies",
"(",
")"
] | https://github.com/pikpikcu/Pentest-Tools-Framework/blob/cd6e6107764a809943dc4e073cde8149c1a2cd03/modules/dirsearch/thirdparty/requests/utils.py#L533-L538 | ||
rlpy/rlpy | af25d2011fff1d61cb7c5cc8992549808f0c6103 | rlpy/Representations/Representation.py | python | Representation.post_discover | (self, s, terminal, a, td_error, phi_s) | return 0 | Identifies and adds ("discovers") new features for this adaptive
representation AFTER having obtained the TD-Error.
For example, see :py:class:`~rlpy.Representations.iFDD.iFDD`.
In that class, a new feature is added based on regions of high TD-Error.
.. note::
For adaptive representations that do not require access to TD-Error
to determine which features to add next, you may
use :py:meth:`~rlpy.Representations.Representation.Representation.pre_discover`
instead.
:param s: The state
:param terminal: boolean, whether or not *s* is a terminal state.
:param a: The action
:param td_error: The temporal difference error at this transition.
:param phi_s: The feature vector evaluated at state *s*.
:return: The number of new features added to the representation | Identifies and adds ("discovers") new features for this adaptive
representation AFTER having obtained the TD-Error.
For example, see :py:class:`~rlpy.Representations.iFDD.iFDD`.
In that class, a new feature is added based on regions of high TD-Error. | [
"Identifies",
"and",
"adds",
"(",
"discovers",
")",
"new",
"features",
"for",
"this",
"adaptive",
"representation",
"AFTER",
"having",
"obtained",
"the",
"TD",
"-",
"Error",
".",
"For",
"example",
"see",
":",
"py",
":",
"class",
":",
"~rlpy",
".",
"Represe... | def post_discover(self, s, terminal, a, td_error, phi_s):
"""
Identifies and adds ("discovers") new features for this adaptive
representation AFTER having obtained the TD-Error.
For example, see :py:class:`~rlpy.Representations.iFDD.iFDD`.
In that class, a new feature is added based on regions of high TD-Error.
.. note::
For adaptive representations that do not require access to TD-Error
to determine which features to add next, you may
use :py:meth:`~rlpy.Representations.Representation.Representation.pre_discover`
instead.
:param s: The state
:param terminal: boolean, whether or not *s* is a terminal state.
:param a: The action
:param td_error: The temporal difference error at this transition.
:param phi_s: The feature vector evaluated at state *s*.
:return: The number of new features added to the representation
"""
return 0 | [
"def",
"post_discover",
"(",
"self",
",",
"s",
",",
"terminal",
",",
"a",
",",
"td_error",
",",
"phi_s",
")",
":",
"return",
"0"
] | https://github.com/rlpy/rlpy/blob/af25d2011fff1d61cb7c5cc8992549808f0c6103/rlpy/Representations/Representation.py#L398-L419 | |
yampelo/beagle | 8bb2b615fd5968e07af42d41a173d98541fc1e85 | beagle/transformers/fireeye_hx_transformer.py | python | FireEyeHXTransformer.make_file | (self, event: dict) | return (file_node, process, proc_file_node) | Converts a fileWriteEvent to two nodes, a file and the process manipulated the file.
Generates a process - (Wrote) -> File edge.
Parameters
----------
event : dict
The fileWriteEvent event.
Returns
-------
Optional[Tuple[File, Process, File]]
Returns a tuple contaning the File that this event is focused on, and the process
which manipulated the file. The process has a Wrote edge to the file. Also contains
the file that the process belongs to. | Converts a fileWriteEvent to two nodes, a file and the process manipulated the file.
Generates a process - (Wrote) -> File edge. | [
"Converts",
"a",
"fileWriteEvent",
"to",
"two",
"nodes",
"a",
"file",
"and",
"the",
"process",
"manipulated",
"the",
"file",
".",
"Generates",
"a",
"process",
"-",
"(",
"Wrote",
")",
"-",
">",
"File",
"edge",
"."
] | def make_file(self, event: dict) -> Optional[Tuple[File, Process, File]]:
"""Converts a fileWriteEvent to two nodes, a file and the process manipulated the file.
Generates a process - (Wrote) -> File edge.
Parameters
----------
event : dict
The fileWriteEvent event.
Returns
-------
Optional[Tuple[File, Process, File]]
Returns a tuple contaning the File that this event is focused on, and the process
which manipulated the file. The process has a Wrote edge to the file. Also contains
the file that the process belongs to.
"""
if "filePath" not in event:
return None
# Add the drive where possible.
if event.get("drive"):
file_path = f"{event['drive']}:\\{event['filePath']}"
else:
file_path = event["filePath"]
hashes: Dict[str, str] = {}
if event.get("md5"):
hashes = {"md5": event["md5"]}
# Create the file node.
file_node = File(file_path=file_path, file_name=event["fileName"], hashes=hashes)
# Set the extension
file_node.set_extension()
# Set the process node
process = Process(
process_id=int(event["pid"]),
process_image=event["process"],
process_image_path=event["processPath"],
user=event.get("username"),
)
# Add a wrote edge with the contents of the file write.
process.wrote[file_node].append(
timestamp=int(event["event_time"]), contents=event.get("textAtLowestOffset")
)
# Pull out the image of the process
proc_file_node = process.get_file_node()
# File - (File Of) -> Process
proc_file_node.file_of[process]
return (file_node, process, proc_file_node) | [
"def",
"make_file",
"(",
"self",
",",
"event",
":",
"dict",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"File",
",",
"Process",
",",
"File",
"]",
"]",
":",
"if",
"\"filePath\"",
"not",
"in",
"event",
":",
"return",
"None",
"# Add the drive where possible.",
... | https://github.com/yampelo/beagle/blob/8bb2b615fd5968e07af42d41a173d98541fc1e85/beagle/transformers/fireeye_hx_transformer.py#L142-L197 | |
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.py | python | Specifier._compare_compatible | (self, prospective, spec) | return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
prospective, prefix
) | [] | def _compare_compatible(self, prospective, spec):
# Compatible releases have an equivalent combination of >= and ==. That
# is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
# implement this in terms of the other specifiers instead of
# implementing it ourselves. The only thing we need to do is construct
# the other specifiers.
# We want everything but the last item in the version, but we want to
# ignore post and dev releases and we want to treat the pre-release as
# it's own separate segment.
prefix = ".".join(
list(
itertools.takewhile(
lambda x: (not x.startswith("post") and not x.startswith("dev")),
_version_split(spec),
)
)[:-1]
)
# Add the prefix notation to the end of our string
prefix += ".*"
return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
prospective, prefix
) | [
"def",
"_compare_compatible",
"(",
"self",
",",
"prospective",
",",
"spec",
")",
":",
"# Compatible releases have an equivalent combination of >= and ==. That",
"# is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to",
"# implement this in terms of the other specifiers instead of",
... | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.py#L375-L399 | |||
mpdavis/python-jose | cfbb868efffe05352546f064a47e6d90a53bbae0 | jose/jwe.py | python | _get_random_cek_bytes_for_enc | (enc) | return cek_bytes | Get the random cek bytes based on the encryptionn algorithm
Args:
enc (str): Encryption algorithm
Returns:
(bytes) random bytes for cek key | Get the random cek bytes based on the encryptionn algorithm | [
"Get",
"the",
"random",
"cek",
"bytes",
"based",
"on",
"the",
"encryptionn",
"algorithm"
] | def _get_random_cek_bytes_for_enc(enc):
"""
Get the random cek bytes based on the encryptionn algorithm
Args:
enc (str): Encryption algorithm
Returns:
(bytes) random bytes for cek key
"""
if enc == ALGORITHMS.A128GCM:
num_bits = 128
elif enc == ALGORITHMS.A192GCM:
num_bits = 192
elif enc in (ALGORITHMS.A128CBC_HS256, ALGORITHMS.A256GCM):
num_bits = 256
elif enc == ALGORITHMS.A192CBC_HS384:
num_bits = 384
elif enc == ALGORITHMS.A256CBC_HS512:
num_bits = 512
else:
raise NotImplementedError(f"{enc} not supported")
cek_bytes = get_random_bytes(num_bits // 8)
return cek_bytes | [
"def",
"_get_random_cek_bytes_for_enc",
"(",
"enc",
")",
":",
"if",
"enc",
"==",
"ALGORITHMS",
".",
"A128GCM",
":",
"num_bits",
"=",
"128",
"elif",
"enc",
"==",
"ALGORITHMS",
".",
"A192GCM",
":",
"num_bits",
"=",
"192",
"elif",
"enc",
"in",
"(",
"ALGORITHM... | https://github.com/mpdavis/python-jose/blob/cfbb868efffe05352546f064a47e6d90a53bbae0/jose/jwe.py#L531-L554 | |
log2timeline/dfvfs | 4ca7bf06b15cdc000297a7122a065f0ca71de544 | dfvfs/vfs/ext_file_entry.py | python | EXTFileEntry.GetEXTFileEntry | (self) | return self._fsext_file_entry | Retrieves the EXT file entry.
Returns:
pyfsext.file_entry: EXT file entry. | Retrieves the EXT file entry. | [
"Retrieves",
"the",
"EXT",
"file",
"entry",
"."
] | def GetEXTFileEntry(self):
"""Retrieves the EXT file entry.
Returns:
pyfsext.file_entry: EXT file entry.
"""
return self._fsext_file_entry | [
"def",
"GetEXTFileEntry",
"(",
"self",
")",
":",
"return",
"self",
".",
"_fsext_file_entry"
] | https://github.com/log2timeline/dfvfs/blob/4ca7bf06b15cdc000297a7122a065f0ca71de544/dfvfs/vfs/ext_file_entry.py#L273-L279 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/google/appengine/api/datastore_types.py | python | Key.kind | (self) | Returns this entity's kind, as a string. | Returns this entity's kind, as a string. | [
"Returns",
"this",
"entity",
"s",
"kind",
"as",
"a",
"string",
"."
] | def kind(self):
"""Returns this entity's kind, as a string."""
if self.__reference.path().element_size() > 0:
encoded = self.__reference.path().element_list()[-1].type()
return unicode(encoded.decode('utf-8'))
else:
return None | [
"def",
"kind",
"(",
"self",
")",
":",
"if",
"self",
".",
"__reference",
".",
"path",
"(",
")",
".",
"element_size",
"(",
")",
">",
"0",
":",
"encoded",
"=",
"self",
".",
"__reference",
".",
"path",
"(",
")",
".",
"element_list",
"(",
")",
"[",
"-... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/datastore_types.py#L541-L547 | ||
google/jax | bebe9845a873b3203f8050395255f173ba3bbb71 | jax/example_libraries/stax.py | python | GeneralConvTranspose | (dimension_numbers, out_chan, filter_shape,
strides=None, padding='VALID', W_init=None,
b_init=normal(1e-6)) | return init_fun, apply_fun | Layer construction function for a general transposed-convolution layer. | Layer construction function for a general transposed-convolution layer. | [
"Layer",
"construction",
"function",
"for",
"a",
"general",
"transposed",
"-",
"convolution",
"layer",
"."
] | def GeneralConvTranspose(dimension_numbers, out_chan, filter_shape,
strides=None, padding='VALID', W_init=None,
b_init=normal(1e-6)):
"""Layer construction function for a general transposed-convolution layer."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
one = (1,) * len(filter_shape)
strides = strides or one
W_init = W_init or glorot_normal(rhs_spec.index('I'), rhs_spec.index('O'))
def init_fun(rng, input_shape):
filter_shape_iter = iter(filter_shape)
kernel_shape = [out_chan if c == 'O' else
input_shape[lhs_spec.index('C')] if c == 'I' else
next(filter_shape_iter) for c in rhs_spec]
output_shape = lax.conv_transpose_shape_tuple(
input_shape, kernel_shape, strides, padding, dimension_numbers)
bias_shape = [out_chan if c == 'C' else 1 for c in out_spec]
k1, k2 = random.split(rng)
W, b = W_init(k1, kernel_shape), b_init(k2, bias_shape)
return output_shape, (W, b)
def apply_fun(params, inputs, **kwargs):
W, b = params
return lax.conv_transpose(inputs, W, strides, padding,
dimension_numbers=dimension_numbers) + b
return init_fun, apply_fun | [
"def",
"GeneralConvTranspose",
"(",
"dimension_numbers",
",",
"out_chan",
",",
"filter_shape",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'VALID'",
",",
"W_init",
"=",
"None",
",",
"b_init",
"=",
"normal",
"(",
"1e-6",
")",
")",
":",
"lhs_spec",
",... | https://github.com/google/jax/blob/bebe9845a873b3203f8050395255f173ba3bbb71/jax/example_libraries/stax.py#L87-L110 | |
sfepy/sfepy | 02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25 | sfepy/homogenization/coefs_base.py | python | MiniAppBase.process_options | (self) | Setup application-specific options.
Subclasses should implement this method as needed.
Returns
-------
app_options : Struct instance
The application options. | Setup application-specific options. | [
"Setup",
"application",
"-",
"specific",
"options",
"."
] | def process_options(self):
"""
Setup application-specific options.
Subclasses should implement this method as needed.
Returns
-------
app_options : Struct instance
The application options.
""" | [
"def",
"process_options",
"(",
"self",
")",
":"
] | https://github.com/sfepy/sfepy/blob/02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25/sfepy/homogenization/coefs_base.py#L44-L54 | ||
openrazer/openrazer | 1615f8516e8014bad7f78c781c91e6529679718f | daemon/openrazer_daemon/hardware/mouse.py | python | RazerAbyssus1800._suspend_device | (self) | Suspend the device
Get the current logo state, store it for later and then set the logo to off | Suspend the device | [
"Suspend",
"the",
"device"
] | def _suspend_device(self):
"""
Suspend the device
Get the current logo state, store it for later and then set the logo to off
"""
self.suspend_args.clear()
self.suspend_args['active'] = _da_get_logo_active(self)
# Todo make it context?
self.disable_notify = True
_da_set_logo_active(self, False)
self.disable_notify = False | [
"def",
"_suspend_device",
"(",
"self",
")",
":",
"self",
".",
"suspend_args",
".",
"clear",
"(",
")",
"self",
".",
"suspend_args",
"[",
"'active'",
"]",
"=",
"_da_get_logo_active",
"(",
"self",
")",
"# Todo make it context?",
"self",
".",
"disable_notify",
"="... | https://github.com/openrazer/openrazer/blob/1615f8516e8014bad7f78c781c91e6529679718f/daemon/openrazer_daemon/hardware/mouse.py#L1563-L1575 | ||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | lib-python/2.7/idlelib/configDialog.py | python | ConfigDialog.SaveNewTheme | (self, themeName, theme) | save a newly created theme.
themeName - string, the name of the new theme
theme - dictionary containing the new theme | save a newly created theme.
themeName - string, the name of the new theme
theme - dictionary containing the new theme | [
"save",
"a",
"newly",
"created",
"theme",
".",
"themeName",
"-",
"string",
"the",
"name",
"of",
"the",
"new",
"theme",
"theme",
"-",
"dictionary",
"containing",
"the",
"new",
"theme"
] | def SaveNewTheme(self, themeName, theme):
"""
save a newly created theme.
themeName - string, the name of the new theme
theme - dictionary containing the new theme
"""
if not idleConf.userCfg['highlight'].has_section(themeName):
idleConf.userCfg['highlight'].add_section(themeName)
for element in theme:
value = theme[element]
idleConf.userCfg['highlight'].SetOption(themeName, element, value) | [
"def",
"SaveNewTheme",
"(",
"self",
",",
"themeName",
",",
"theme",
")",
":",
"if",
"not",
"idleConf",
".",
"userCfg",
"[",
"'highlight'",
"]",
".",
"has_section",
"(",
"themeName",
")",
":",
"idleConf",
".",
"userCfg",
"[",
"'highlight'",
"]",
".",
"add... | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/idlelib/configDialog.py#L1140-L1150 | ||
conjure-up/conjure-up | d2bf8ab8e71ff01321d0e691a8d3e3833a047678 | conjureup/bundle.py | python | BundleApplicationFragment.constraints | (self, val) | [] | def constraints(self, val):
self._constraints = val | [
"def",
"constraints",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"_constraints",
"=",
"val"
] | https://github.com/conjure-up/conjure-up/blob/d2bf8ab8e71ff01321d0e691a8d3e3833a047678/conjureup/bundle.py#L36-L37 | ||||
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | plexpy/notifiers.py | python | OSX.validate | (self) | [] | def validate(self):
try:
self.objc = __import__("objc")
self.AppKit = __import__("AppKit")
return True
except:
return False | [
"def",
"validate",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"objc",
"=",
"__import__",
"(",
"\"objc\"",
")",
"self",
".",
"AppKit",
"=",
"__import__",
"(",
"\"AppKit\"",
")",
"return",
"True",
"except",
":",
"return",
"False"
] | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/plexpy/notifiers.py#L2494-L2500 | ||||
entropy1337/infernal-twin | 10995cd03312e39a48ade0f114ebb0ae3a711bb8 | Modules/build/pillow/PIL/OleFileIO.py | python | OleFileIO.getmtime | (self, filename) | return entry.getmtime() | Return modification time of a stream/storage.
:param filename: path of stream/storage in storage tree. (see openstream for
syntax)
:returns: None if modification time is null, a python datetime object
otherwise (UTC timezone)
new in version 0.26 | Return modification time of a stream/storage. | [
"Return",
"modification",
"time",
"of",
"a",
"stream",
"/",
"storage",
"."
] | def getmtime(self, filename):
"""
Return modification time of a stream/storage.
:param filename: path of stream/storage in storage tree. (see openstream for
syntax)
:returns: None if modification time is null, a python datetime object
otherwise (UTC timezone)
new in version 0.26
"""
sid = self._find(filename)
entry = self.direntries[sid]
return entry.getmtime() | [
"def",
"getmtime",
"(",
"self",
",",
"filename",
")",
":",
"sid",
"=",
"self",
".",
"_find",
"(",
"filename",
")",
"entry",
"=",
"self",
".",
"direntries",
"[",
"sid",
"]",
"return",
"entry",
".",
"getmtime",
"(",
")"
] | https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pillow/PIL/OleFileIO.py#L1963-L1976 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | check_server/check_scripts/8.py | python | check.admin_check | (self) | return False | [] | def admin_check(self):
data = 'eval(666)'
headers['Cookie'] = 'PHPSESSID=ujg0tpds1u9d23b969f2duj5c7;'
res = http('get',host,port,'/admin/tools/database?type=export',data,headers)
tmp = http('get',host,port,'/admin/login/loginout.html','',headers)
if 'qq3479015851_article_type' in res:
return True
if debug:
print "[fail!] admin_fail"
return False | [
"def",
"admin_check",
"(",
"self",
")",
":",
"data",
"=",
"'eval(666)'",
"headers",
"[",
"'Cookie'",
"]",
"=",
"'PHPSESSID=ujg0tpds1u9d23b969f2duj5c7;'",
"res",
"=",
"http",
"(",
"'get'",
",",
"host",
",",
"port",
",",
"'/admin/tools/database?type=export'",
",",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/check_server/check_scripts/8.py#L119-L128 | |||
joxeankoret/pyew | 8eb3e49a9bf57c0787fa79ecae0671129ef3f2e8 | plugins/ole2.py | python | ole2Explore | (pyew, doprint=True, args=None) | Get the OLE2 directory | Get the OLE2 directory | [
"Get",
"the",
"OLE2",
"directory"
] | def ole2Explore(pyew, doprint=True, args=None):
""" Get the OLE2 directory """
if not pyew.physical:
filename = tempfile.mkstemp("pyew")[1]
f = file(filename, "wb")
f.write(pyew.getBuffer())
f.close()
else:
filename = pyew.filename
ole = OleFileIO(filename, raise_defects=DEFECT_INCORRECT)
ole.dumpdirectory()
i = 0
for streamname in ole.listdir():
if streamname[-1][0] == "\005":
print streamname, ": properties"
props = ole.getproperties(streamname)
props = props.items()
props.sort()
for k, v in props:
#[PL]: avoid to display too large or binary values:
if isinstance(v, basestring):
if len(v) > 50:
v = v[:50]
# quick and dirty binary check:
for c in (1,2,3,4,5,6,7,11,12,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,31):
if chr(c) in v:
v = '(binary data)'
break
print " ", k, v
# Read all streams to check if there are errors:
print '\nChecking streams...'
for streamname in ole.listdir():
# print name using repr() to convert binary chars to \xNN:
print '-', repr('/'.join(streamname)),'-',
st_type = ole.get_type(streamname)
if st_type == STGTY_STREAM:
print 'size %d' % ole.get_size(streamname)
# just try to read stream in memory:
ole.openstream(streamname)
else:
print 'NOT a stream : type=%d' % st_type
print ''
#[PL] Test a few new methods:
root = ole.get_rootentry_name()
print 'Root entry name: "%s"' % root
if ole.exists('worddocument'):
print "This is a Word document."
print "type of stream 'WordDocument':", ole.get_type('worddocument')
print "size :", ole.get_size('worddocument')
if ole.exists('macros/vba'):
print "This document may contain VBA macros." | [
"def",
"ole2Explore",
"(",
"pyew",
",",
"doprint",
"=",
"True",
",",
"args",
"=",
"None",
")",
":",
"if",
"not",
"pyew",
".",
"physical",
":",
"filename",
"=",
"tempfile",
".",
"mkstemp",
"(",
"\"pyew\"",
")",
"[",
"1",
"]",
"f",
"=",
"file",
"(",
... | https://github.com/joxeankoret/pyew/blob/8eb3e49a9bf57c0787fa79ecae0671129ef3f2e8/plugins/ole2.py#L32-L87 | ||
google-research/language | 61fa7260ac7d690d11ef72ca863e45a37c0bdc80 | language/search_agents/t5/t5_agent_lib.py | python | query_to_prompt | (query: str, addition_terms: Sequence[Term],
subtraction_terms: Sequence[Term],
or_terms: Sequence[Term]) | return " ".join(r for r in res if r) | Produces a plaintext form of the current query with all modifiers.
This is not the form to be used with Lucence but part of the T5 input.
Args:
query: The original query.
addition_terms: Forced terms.
subtraction_terms: Prohibited terms.
or_terms: Optional terms.
Returns:
query_with_modifiers as a flat string representation. | Produces a plaintext form of the current query with all modifiers. | [
"Produces",
"a",
"plaintext",
"form",
"of",
"the",
"current",
"query",
"with",
"all",
"modifiers",
"."
] | def query_to_prompt(query: str, addition_terms: Sequence[Term],
subtraction_terms: Sequence[Term],
or_terms: Sequence[Term]) -> str:
"""Produces a plaintext form of the current query with all modifiers.
This is not the form to be used with Lucence but part of the T5 input.
Args:
query: The original query.
addition_terms: Forced terms.
subtraction_terms: Prohibited terms.
or_terms: Optional terms.
Returns:
query_with_modifiers as a flat string representation.
"""
res = []
if query.strip():
res = [f"Query: '{query}'."]
def has_terms(terms):
for operator in terms:
if operator.term:
return True
return False
# The or-terms are all joined together with commas.
if has_terms(or_terms):
res.append("Should contain: " + ", ".join(
f"'{operator.term}'" for operator in or_terms if operator.term) + ".")
if has_terms(addition_terms):
res.append(" ".join(
f"{operator.field.capitalize()} must contain: '{operator.term}'."
for operator in addition_terms
if operator.term))
if has_terms(subtraction_terms):
res.append(" ".join(
f"{operator.field.capitalize()} cannot contain: '{operator.term}'."
for operator in subtraction_terms
if operator.term))
return " ".join(r for r in res if r) | [
"def",
"query_to_prompt",
"(",
"query",
":",
"str",
",",
"addition_terms",
":",
"Sequence",
"[",
"Term",
"]",
",",
"subtraction_terms",
":",
"Sequence",
"[",
"Term",
"]",
",",
"or_terms",
":",
"Sequence",
"[",
"Term",
"]",
")",
"->",
"str",
":",
"res",
... | https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/search_agents/t5/t5_agent_lib.py#L121-L164 | |
fonttools/fonttools | 892322aaff6a89bea5927379ec06bc0da3dfb7df | Lib/fontTools/feaLib/ast.py | python | MarkClassDefinition.glyphSet | (self) | return self.glyphs.glyphSet() | The glyphs in this class as a tuple of :class:`GlyphName` objects. | The glyphs in this class as a tuple of :class:`GlyphName` objects. | [
"The",
"glyphs",
"in",
"this",
"class",
"as",
"a",
"tuple",
"of",
":",
"class",
":",
"GlyphName",
"objects",
"."
] | def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return self.glyphs.glyphSet() | [
"def",
"glyphSet",
"(",
"self",
")",
":",
"return",
"self",
".",
"glyphs",
".",
"glyphSet",
"(",
")"
] | https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/feaLib/ast.py#L585-L587 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | opy/callgraph.py | python | Class.__init__ | (self, cls, mod_name, mod_path) | [] | def __init__(self, cls, mod_name, mod_path):
self.cls = cls
self.mod_name = mod_name
self.mod_path = mod_path
self.methods = [] | [
"def",
"__init__",
"(",
"self",
",",
"cls",
",",
"mod_name",
",",
"mod_path",
")",
":",
"self",
".",
"cls",
"=",
"cls",
"self",
".",
"mod_name",
"=",
"mod_name",
"self",
".",
"mod_path",
"=",
"mod_path",
"self",
".",
"methods",
"=",
"[",
"]"
] | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/opy/callgraph.py#L294-L298 | ||||
exodrifter/unity-python | bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d | Lib/lib2to3/patcomp.py | python | PatternCompiler.__init__ | (self, grammar_file=None) | Initializer.
Takes an optional alternative filename for the pattern grammar. | Initializer. | [
"Initializer",
"."
] | def __init__(self, grammar_file=None):
"""Initializer.
Takes an optional alternative filename for the pattern grammar.
"""
if grammar_file is None:
self.grammar = pygram.pattern_grammar
self.syms = pygram.pattern_symbols
else:
self.grammar = driver.load_grammar(grammar_file)
self.syms = pygram.Symbols(self.grammar)
self.pygrammar = pygram.python_grammar
self.pysyms = pygram.python_symbols
self.driver = driver.Driver(self.grammar, convert=pattern_convert) | [
"def",
"__init__",
"(",
"self",
",",
"grammar_file",
"=",
"None",
")",
":",
"if",
"grammar_file",
"is",
"None",
":",
"self",
".",
"grammar",
"=",
"pygram",
".",
"pattern_grammar",
"self",
".",
"syms",
"=",
"pygram",
".",
"pattern_symbols",
"else",
":",
"... | https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/lib2to3/patcomp.py#L40-L53 | ||
ilius/pyglossary | d599b3beda3ae17642af5debd83bb991148e6425 | pyglossary/xdxf_transform.py | python | xdxf_to_html_transformer | () | return transform | [] | def xdxf_to_html_transformer():
from lxml import etree
from lxml.etree import tostring
from os.path import join
try:
from lxml import etree as ET
except ModuleNotFoundError as e:
e.msg += f", run `{core.pip} install lxml` to install"
raise e
with open(join(rootDir, "pyglossary", "xdxf.xsl"), "r") as f:
xslt_txt = f.read()
xslt = ET.XML(xslt_txt)
_transform = ET.XSLT(xslt)
def transform(input_text: str) -> str:
doc = etree.parse(StringIO(f"<ar>{input_text}</ar>"))
result_tree = _transform(doc)
text = tostring(result_tree, encoding="utf-8").decode("utf-8")
text = text.replace("<br/> ", "<br/>")
return text
return transform | [
"def",
"xdxf_to_html_transformer",
"(",
")",
":",
"from",
"lxml",
"import",
"etree",
"from",
"lxml",
".",
"etree",
"import",
"tostring",
"from",
"os",
".",
"path",
"import",
"join",
"try",
":",
"from",
"lxml",
"import",
"etree",
"as",
"ET",
"except",
"Modu... | https://github.com/ilius/pyglossary/blob/d599b3beda3ae17642af5debd83bb991148e6425/pyglossary/xdxf_transform.py#L10-L33 | |||
vivisect/vivisect | 37b0b655d8dedfcf322e86b0f144b096e48d547e | cobra/cluster.py | python | ClusterWork.done | (self) | This is called back on the server once a work unit
is complete and returned. | This is called back on the server once a work unit
is complete and returned. | [
"This",
"is",
"called",
"back",
"on",
"the",
"server",
"once",
"a",
"work",
"unit",
"is",
"complete",
"and",
"returned",
"."
] | def done(self):
"""
This is called back on the server once a work unit
is complete and returned.
"""
pass | [
"def",
"done",
"(",
"self",
")",
":",
"pass"
] | https://github.com/vivisect/vivisect/blob/37b0b655d8dedfcf322e86b0f144b096e48d547e/cobra/cluster.py#L83-L88 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/multiprocessing/pool.py | python | Pool.imap_unordered | (self, func, iterable, chunksize=1) | Like `imap()` method but ordering of results is arbitrary. | Like `imap()` method but ordering of results is arbitrary. | [
"Like",
"imap",
"()",
"method",
"but",
"ordering",
"of",
"results",
"is",
"arbitrary",
"."
] | def imap_unordered(self, func, iterable, chunksize=1):
'''
Like `imap()` method but ordering of results is arbitrary.
'''
if self._state != RUN:
raise ValueError("Pool not running")
if chunksize == 1:
result = IMapUnorderedIterator(self._cache)
self._taskqueue.put(
(
self._guarded_task_generation(result._job, func, iterable),
result._set_length
))
return result
else:
if chunksize < 1:
raise ValueError(
"Chunksize must be 1+, not {0!r}".format(chunksize))
task_batches = Pool._get_tasks(func, iterable, chunksize)
result = IMapUnorderedIterator(self._cache)
self._taskqueue.put(
(
self._guarded_task_generation(result._job,
mapstar,
task_batches),
result._set_length
))
return (item for chunk in result for item in chunk) | [
"def",
"imap_unordered",
"(",
"self",
",",
"func",
",",
"iterable",
",",
"chunksize",
"=",
"1",
")",
":",
"if",
"self",
".",
"_state",
"!=",
"RUN",
":",
"raise",
"ValueError",
"(",
"\"Pool not running\"",
")",
"if",
"chunksize",
"==",
"1",
":",
"result",... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/multiprocessing/pool.py#L349-L376 | ||
hyunwoongko/kochat | b23308bdac63e58c347906c3bd45d3c14302a6c4 | kochat/proc/utils/metrics.py | python | Metrics.evaluate | (self, label: Tensor, predict: Tensor, mode: str) | return {'accuracy': accuracy_score(label, predict),
'precision': precision_score(label, predict, average='macro'),
'recall': recall_score(label, predict, average='macro'),
'f1_score': f1_score(label, predict, average='macro')} | 여러가지 메트릭에 의한 결과를 반환합니다.
:param label: 라벨
:param predict: 예측
:param mode: train or test
:return: 정확도 | 여러가지 메트릭에 의한 결과를 반환합니다. | [
"여러가지",
"메트릭에",
"의한",
"결과를",
"반환합니다",
"."
] | def evaluate(self, label: Tensor, predict: Tensor, mode: str) -> dict:
"""
여러가지 메트릭에 의한 결과를 반환합니다.
:param label: 라벨
:param predict: 예측
:param mode: train or test
:return: 정확도
"""
if not isinstance(label, np.ndarray):
label = label.detach().cpu().numpy()
if not isinstance(predict, np.ndarray):
predict = predict.detach().cpu().numpy()
if mode == 'train':
self.train_label = label
self.train_predict = predict
elif mode == 'test':
self.test_label = label
self.test_predict = predict
elif mode == 'ood':
self.ood_label = label
self.ood_predict = predict
else:
raise Exception("mode는 train과 test만 가능합니다.")
return {'accuracy': accuracy_score(label, predict),
'precision': precision_score(label, predict, average='macro'),
'recall': recall_score(label, predict, average='macro'),
'f1_score': f1_score(label, predict, average='macro')} | [
"def",
"evaluate",
"(",
"self",
",",
"label",
":",
"Tensor",
",",
"predict",
":",
"Tensor",
",",
"mode",
":",
"str",
")",
"->",
"dict",
":",
"if",
"not",
"isinstance",
"(",
"label",
",",
"np",
".",
"ndarray",
")",
":",
"label",
"=",
"label",
".",
... | https://github.com/hyunwoongko/kochat/blob/b23308bdac63e58c347906c3bd45d3c14302a6c4/kochat/proc/utils/metrics.py#L24-L57 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/dynamics/arithmetic_dynamics/wehlerK3.py | python | WehlerK3Surface_ring.canonical_height_minus | (self, P, N, badprimes=None, prec=100) | return h | r"""
Evaluates the canonical height minus function of Call-Silverman
for ``P`` with ``N`` terms of the series of the local heights.
Must be over `\ZZ` or `\QQ`.
ALGORITHM:
Sum over the lambda minus heights (local heights) in a convergent series,
for more detail see section 7 of [CS1996]_.
INPUT:
- ``P`` -- a surface point
- ``N`` -- positive integer (number of terms of the series to use)
- ``badprimes`` -- (optional) list of integer primes (where the surface is degenerate)
- ``prec`` -- (default: 100) float point or p-adic precision
OUTPUT: A real number
EXAMPLES::
sage: set_verbose(None)
sage: R.<x0,x1,x2,y0,y1,y2> = PolynomialRing(QQ, 6)
sage: L = (-y0 - y1)*x0 + (-y0*x1 - y2*x2)
sage: Q = (-y2*y0 - y1^2)*x0^2 + ((-y0^2 - y2*y0 + (-y2*y1 - y2^2))*x1\
+ (-y0^2 - y2*y1)*x2)*x0 + ((-y0^2 - y2*y0 - y2^2)*x1^2 + (-y2*y0 - y1^2)*x2*x1\
+ (-y0^2 + (-y1 - y2)*y0)*x2^2)
sage: X = WehlerK3Surface([L, Q])
sage: P = X([1, 0, -1, 1, -1, 0]) #order 16
sage: X.canonical_height_minus(P, 5) # long time
0.00000000000000000000000000000
Call-Silverman example::
sage: set_verbose(None)
sage: PP.<x0,x1,x2,y0,y1,y2> = ProductProjectiveSpaces([2, 2], QQ)
sage: Z = x0^2*y0^2 + 3*x0*x1*y0^2 + x1^2*y0^2 + 4*x0^2*y0*y1 +\
3*x0*x1*y0*y1 - 2*x2^2*y0*y1 - x0^2*y1^2 + 2*x1^2*y1^2 - x0*x2*y1^2 - \
4*x1*x2*y1^2 + 5*x0*x2*y0*y2 - 4*x1*x2*y0*y2 + 7*x0^2*y1*y2 + 4*x1^2*y1*y2 + \
x0*x1*y2^2 + 3*x2^2*y2^2
sage: Y = x0*y0 + x1*y1 + x2*y2
sage: X = WehlerK3Surface([Z, Y])
sage: P = X([0, 1, 0, 0, 0, 1])
sage: X.canonical_height_minus(P, 4) # long time
0.55073705369676788175590206734 | r"""
Evaluates the canonical height minus function of Call-Silverman
for ``P`` with ``N`` terms of the series of the local heights. | [
"r",
"Evaluates",
"the",
"canonical",
"height",
"minus",
"function",
"of",
"Call",
"-",
"Silverman",
"for",
"P",
"with",
"N",
"terms",
"of",
"the",
"series",
"of",
"the",
"local",
"heights",
"."
] | def canonical_height_minus(self, P, N, badprimes=None, prec=100):
r"""
Evaluates the canonical height minus function of Call-Silverman
for ``P`` with ``N`` terms of the series of the local heights.
Must be over `\ZZ` or `\QQ`.
ALGORITHM:
Sum over the lambda minus heights (local heights) in a convergent series,
for more detail see section 7 of [CS1996]_.
INPUT:
- ``P`` -- a surface point
- ``N`` -- positive integer (number of terms of the series to use)
- ``badprimes`` -- (optional) list of integer primes (where the surface is degenerate)
- ``prec`` -- (default: 100) float point or p-adic precision
OUTPUT: A real number
EXAMPLES::
sage: set_verbose(None)
sage: R.<x0,x1,x2,y0,y1,y2> = PolynomialRing(QQ, 6)
sage: L = (-y0 - y1)*x0 + (-y0*x1 - y2*x2)
sage: Q = (-y2*y0 - y1^2)*x0^2 + ((-y0^2 - y2*y0 + (-y2*y1 - y2^2))*x1\
+ (-y0^2 - y2*y1)*x2)*x0 + ((-y0^2 - y2*y0 - y2^2)*x1^2 + (-y2*y0 - y1^2)*x2*x1\
+ (-y0^2 + (-y1 - y2)*y0)*x2^2)
sage: X = WehlerK3Surface([L, Q])
sage: P = X([1, 0, -1, 1, -1, 0]) #order 16
sage: X.canonical_height_minus(P, 5) # long time
0.00000000000000000000000000000
Call-Silverman example::
sage: set_verbose(None)
sage: PP.<x0,x1,x2,y0,y1,y2> = ProductProjectiveSpaces([2, 2], QQ)
sage: Z = x0^2*y0^2 + 3*x0*x1*y0^2 + x1^2*y0^2 + 4*x0^2*y0*y1 +\
3*x0*x1*y0*y1 - 2*x2^2*y0*y1 - x0^2*y1^2 + 2*x1^2*y1^2 - x0*x2*y1^2 - \
4*x1*x2*y1^2 + 5*x0*x2*y0*y2 - 4*x1*x2*y0*y2 + 7*x0^2*y1*y2 + 4*x1^2*y1*y2 + \
x0*x1*y2^2 + 3*x2^2*y2^2
sage: Y = x0*y0 + x1*y1 + x2*y2
sage: X = WehlerK3Surface([Z, Y])
sage: P = X([0, 1, 0, 0, 0, 1])
sage: X.canonical_height_minus(P, 4) # long time
0.55073705369676788175590206734
"""
if badprimes is None:
badprimes = self.degenerate_primes()
m = 2
while P[0][m] == 0:
m = m - 1
n = 2
while P[1][n] == 0:
n = n-1
h = self.lambda_minus(P, 0, N, m, n, prec)
for p in badprimes:
h += self.lambda_minus(P, p, N, m, n, prec)
return h | [
"def",
"canonical_height_minus",
"(",
"self",
",",
"P",
",",
"N",
",",
"badprimes",
"=",
"None",
",",
"prec",
"=",
"100",
")",
":",
"if",
"badprimes",
"is",
"None",
":",
"badprimes",
"=",
"self",
".",
"degenerate_primes",
"(",
")",
"m",
"=",
"2",
"wh... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/dynamics/arithmetic_dynamics/wehlerK3.py#L1850-L1912 | |
jliljebl/flowblade | 995313a509b80e99eb1ad550d945bdda5995093b | flowblade-trunk/Flowblade/containeractions.py | python | MLTXMLContainerActions._launch_render | (self, clip, range_in, range_out, clip_start_offset) | [] | def _launch_render(self, clip, range_in, range_out, clip_start_offset):
self.create_data_dirs_if_needed()
self.render_range_in = range_in
self.render_range_out = range_out
self.clip_start_offset = clip_start_offset
mltxmlheadless.clear_flag_files(self.get_container_program_id())
# We need data to be available for render process,
# create video_render_data object with default values if not available.
if self.container_data.render_data == None:
self.container_data.render_data = toolsencoding.create_container_clip_default_render_data_object(current_sequence().profile)
mltxmlheadless.set_render_data(self.get_container_program_id(), self.container_data.render_data)
job_msg = self.get_job_queue_message()
job_msg.text = _("Render Starting...")
job_msg.status = jobs.RENDERING
jobs.update_job_queue(job_msg)
args = ("session_id:" + self.get_container_program_id(),
"clip_path:" + str(self.container_data.unrendered_media),
"range_in:" + str(range_in),
"range_out:"+ str(range_out),
"profile_desc:" + PROJECT().profile.description().replace(" ", "_"),
"xml_file_path:" + str(self.container_data.unrendered_media))
# Create command list and launch process.
command_list = [sys.executable]
command_list.append(respaths.LAUNCH_DIR + "flowblademltxmlheadless")
for arg in args:
command_list.append(arg)
subprocess.Popen(command_list) | [
"def",
"_launch_render",
"(",
"self",
",",
"clip",
",",
"range_in",
",",
"range_out",
",",
"clip_start_offset",
")",
":",
"self",
".",
"create_data_dirs_if_needed",
"(",
")",
"self",
".",
"render_range_in",
"=",
"range_in",
"self",
".",
"render_range_out",
"=",
... | https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/containeractions.py#L839-L872 | ||||
openstack/octavia | 27e5b27d31c695ba72fb6750de2bdafd76e0d7d9 | octavia/common/validate.py | python | header_value_string | (value, what=None) | return True | Raises an error if the value string contains invalid characters. | Raises an error if the value string contains invalid characters. | [
"Raises",
"an",
"error",
"if",
"the",
"value",
"string",
"contains",
"invalid",
"characters",
"."
] | def header_value_string(value, what=None):
"""Raises an error if the value string contains invalid characters."""
p = re.compile(constants.HTTP_HEADER_VALUE_REGEX)
q = re.compile(constants.HTTP_QUOTED_HEADER_VALUE_REGEX)
if not p.match(value) and not q.match(value):
raise exceptions.InvalidString(what=what)
return True | [
"def",
"header_value_string",
"(",
"value",
",",
"what",
"=",
"None",
")",
":",
"p",
"=",
"re",
".",
"compile",
"(",
"constants",
".",
"HTTP_HEADER_VALUE_REGEX",
")",
"q",
"=",
"re",
".",
"compile",
"(",
"constants",
".",
"HTTP_QUOTED_HEADER_VALUE_REGEX",
")... | https://github.com/openstack/octavia/blob/27e5b27d31c695ba72fb6750de2bdafd76e0d7d9/octavia/common/validate.py#L87-L93 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/email/_header_value_parser.py | python | AddressList.addresses | (self) | return [x for x in self if x.token_type=='address'] | [] | def addresses(self):
return [x for x in self if x.token_type=='address'] | [
"def",
"addresses",
"(",
"self",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"self",
"if",
"x",
".",
"token_type",
"==",
"'address'",
"]"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/email/_header_value_parser.py#L294-L295 | |||
googlefonts/fontbakery | cb8196c3a636b63654f8370636cb3f438b60d5b1 | Lib/fontbakery/profiles/googlefonts.py | python | com_google_fonts_check_cjk_vertical_metrics | (ttFont) | Check font follows the Google Fonts CJK vertical metric schema | Check font follows the Google Fonts CJK vertical metric schema | [
"Check",
"font",
"follows",
"the",
"Google",
"Fonts",
"CJK",
"vertical",
"metric",
"schema"
] | def com_google_fonts_check_cjk_vertical_metrics(ttFont):
"""Check font follows the Google Fonts CJK vertical metric schema"""
from .shared_conditions import is_cjk_font, typo_metrics_enabled
filename = os.path.basename(ttFont.reader.file.name)
# Check necessary tables are present.
missing_tables = False
required = ["OS/2", "hhea", "head"]
for key in required:
if key not in ttFont:
missing_tables = True
yield FAIL,\
Message(f'lacks-{key}',
f"{filename} lacks a '{key}' table.")
if missing_tables:
return
font_upm = ttFont['head'].unitsPerEm
font_metrics = {
'OS/2.sTypoAscender': ttFont['OS/2'].sTypoAscender,
'OS/2.sTypoDescender': ttFont['OS/2'].sTypoDescender,
'OS/2.sTypoLineGap': ttFont['OS/2'].sTypoLineGap,
'hhea.ascent': ttFont['hhea'].ascent,
'hhea.descent': ttFont['hhea'].descent,
'hhea.lineGap': ttFont['hhea'].lineGap,
'OS/2.usWinAscent': ttFont['OS/2'].usWinAscent,
'OS/2.usWinDescent': ttFont['OS/2'].usWinDescent
}
expected_metrics = {
'OS/2.sTypoAscender': font_upm * 0.88,
'OS/2.sTypoDescender': font_upm * -0.12,
'OS/2.sTypoLineGap': 0,
'hhea.lineGap': 0,
}
failed = False
warn = False
# Check fsSelection bit 7 is not enabled
if typo_metrics_enabled(ttFont):
failed = True
yield FAIL,\
Message('bad-fselection-bit7',
'OS/2 fsSelection bit 7 must be disabled')
# Check typo metrics and hhea lineGap match our expected values
for k in expected_metrics:
if font_metrics[k] != expected_metrics[k]:
failed = True
yield FAIL,\
Message(f'bad-{k}',
f'{k} is "{font_metrics[k]}" it should be {expected_metrics[k]}')
# Check hhea and win values match
if font_metrics['hhea.ascent'] != font_metrics['OS/2.usWinAscent']:
failed = True
yield FAIL,\
Message('ascent-mismatch',
'hhea.ascent must match OS/2.usWinAscent')
if abs(font_metrics['hhea.descent']) != font_metrics['OS/2.usWinDescent']:
failed = True
yield FAIL,\
Message('descent-mismatch',
'hhea.descent must match absolute value of OS/2.usWinDescent')
# Check the sum of the hhea metrics is between 1.1-1.5x of the font's upm
hhea_sum = (font_metrics['hhea.ascent'] +
abs(font_metrics['hhea.descent']) +
font_metrics['hhea.lineGap']) / font_upm
if not failed and not 1.1 < hhea_sum <= 1.5:
warn = True
yield WARN,\
Message('bad-hhea-range',
f"We recommend the absolute sum of the hhea metrics should be"
f" between 1.1-1.4x of the font's upm. This font has {hhea_sum}x")
if not failed and not warn:
yield PASS, 'Vertical metrics are good' | [
"def",
"com_google_fonts_check_cjk_vertical_metrics",
"(",
"ttFont",
")",
":",
"from",
".",
"shared_conditions",
"import",
"is_cjk_font",
",",
"typo_metrics_enabled",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"ttFont",
".",
"reader",
".",
"file",
"... | https://github.com/googlefonts/fontbakery/blob/cb8196c3a636b63654f8370636cb3f438b60d5b1/Lib/fontbakery/profiles/googlefonts.py#L4738-L4817 | ||
PokemonGoF/PokemonGo-Bot-Desktop | 4bfa94f0183406c6a86f93645eff7abd3ad4ced8 | build/pywin/Lib/bisect.py | python | bisect_left | (a, x, lo=0, hi=None) | return lo | Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x. So if x already appears in the list, a.insert(x) will
insert just before the leftmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched. | Return the index where to insert item x in list a, assuming a is sorted. | [
"Return",
"the",
"index",
"where",
"to",
"insert",
"item",
"x",
"in",
"list",
"a",
"assuming",
"a",
"is",
"sorted",
"."
] | def bisect_left(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x. So if x already appears in the list, a.insert(x) will
insert just before the leftmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x: lo = mid+1
else: hi = mid
return lo | [
"def",
"bisect_left",
"(",
"a",
",",
"x",
",",
"lo",
"=",
"0",
",",
"hi",
"=",
"None",
")",
":",
"if",
"lo",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'lo must be non-negative'",
")",
"if",
"hi",
"is",
"None",
":",
"hi",
"=",
"len",
"(",
"a",
... | https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/bisect.py#L67-L86 | |
Nuitka/Nuitka | 39262276993757fa4e299f497654065600453fc9 | nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/rpcgen.py | python | generate | (env) | Add RPCGEN Builders and construction variables for an Environment. | Add RPCGEN Builders and construction variables for an Environment. | [
"Add",
"RPCGEN",
"Builders",
"and",
"construction",
"variables",
"for",
"an",
"Environment",
"."
] | def generate(env):
"Add RPCGEN Builders and construction variables for an Environment."
client = Builder(action=rpcgen_client, suffix='_clnt.c', src_suffix='.x')
header = Builder(action=rpcgen_header, suffix='.h', src_suffix='.x')
service = Builder(action=rpcgen_service, suffix='_svc.c', src_suffix='.x')
xdr = Builder(action=rpcgen_xdr, suffix='_xdr.c', src_suffix='.x')
env.Append(BUILDERS={'RPCGenClient' : client,
'RPCGenHeader' : header,
'RPCGenService' : service,
'RPCGenXDR' : xdr})
env['RPCGEN'] = 'rpcgen'
env['RPCGENFLAGS'] = SCons.Util.CLVar('')
env['RPCGENCLIENTFLAGS'] = SCons.Util.CLVar('')
env['RPCGENHEADERFLAGS'] = SCons.Util.CLVar('')
env['RPCGENSERVICEFLAGS'] = SCons.Util.CLVar('')
env['RPCGENXDRFLAGS'] = SCons.Util.CLVar('') | [
"def",
"generate",
"(",
"env",
")",
":",
"client",
"=",
"Builder",
"(",
"action",
"=",
"rpcgen_client",
",",
"suffix",
"=",
"'_clnt.c'",
",",
"src_suffix",
"=",
"'.x'",
")",
"header",
"=",
"Builder",
"(",
"action",
"=",
"rpcgen_header",
",",
"suffix",
"=... | https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/rpcgen.py#L45-L61 | ||
eyounx/ZOOpt | 49c750daf842639ee6407848a867091689571810 | zoopt/algos/opt_algorithms/racos/sracos.py | python | SRacosTune.__init__ | (self, dimension, parameter) | return | Initialization.
:param dimension: instance of Dimension2 class
:param parameter: instance of Parameter class | Initialization. | [
"Initialization",
"."
] | def __init__(self, dimension, parameter):
"""
Initialization.
:param dimension: instance of Dimension2 class
:param parameter: instance of Parameter class
"""
RacosCommon.__init__(self)
self.clear()
objective = Objective(None, dimension)
self.set_objective(objective)
self.set_parameters(parameter)
self.init_num = 0
self.complete_num = 0
self.semaphore = 1 # control init
self.ub = self._parameter.get_uncertain_bits()
if self.ub is None:
self.ub = self.choose_ub(self.get_objective())
return | [
"def",
"__init__",
"(",
"self",
",",
"dimension",
",",
"parameter",
")",
":",
"RacosCommon",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"clear",
"(",
")",
"objective",
"=",
"Objective",
"(",
"None",
",",
"dimension",
")",
"self",
".",
"set_objective... | https://github.com/eyounx/ZOOpt/blob/49c750daf842639ee6407848a867091689571810/zoopt/algos/opt_algorithms/racos/sracos.py#L227-L247 | |
deepgully/me | f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0 | libs/sqlalchemy/pool.py | python | Pool._return_conn | (self, record) | Given a _ConnectionRecord, return it to the :class:`.Pool`.
This method is called when an instrumented DBAPI connection
has its ``close()`` method called. | Given a _ConnectionRecord, return it to the :class:`.Pool`. | [
"Given",
"a",
"_ConnectionRecord",
"return",
"it",
"to",
"the",
":",
"class",
":",
".",
"Pool",
"."
] | def _return_conn(self, record):
"""Given a _ConnectionRecord, return it to the :class:`.Pool`.
This method is called when an instrumented DBAPI connection
has its ``close()`` method called.
"""
if self._use_threadlocal:
try:
del self._threadconns.current
except AttributeError:
pass
self._do_return_conn(record) | [
"def",
"_return_conn",
"(",
"self",
",",
"record",
")",
":",
"if",
"self",
".",
"_use_threadlocal",
":",
"try",
":",
"del",
"self",
".",
"_threadconns",
".",
"current",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_do_return_conn",
"(",
"record",
... | https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/sqlalchemy/pool.py#L344-L356 | ||
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/pandas/core/dtypes/concat.py | python | _get_series_result_type | (result) | return appropriate class of Series concat
input is either dict or array-like | return appropriate class of Series concat
input is either dict or array-like | [
"return",
"appropriate",
"class",
"of",
"Series",
"concat",
"input",
"is",
"either",
"dict",
"or",
"array",
"-",
"like"
] | def _get_series_result_type(result):
"""
return appropriate class of Series concat
input is either dict or array-like
"""
if isinstance(result, dict):
# concat Series with axis 1
if all(is_sparse(c) for c in compat.itervalues(result)):
from pandas.core.sparse.api import SparseDataFrame
return SparseDataFrame
else:
from pandas.core.frame import DataFrame
return DataFrame
elif is_sparse(result):
# concat Series with axis 1
from pandas.core.sparse.api import SparseSeries
return SparseSeries
else:
from pandas.core.series import Series
return Series | [
"def",
"_get_series_result_type",
"(",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"dict",
")",
":",
"# concat Series with axis 1",
"if",
"all",
"(",
"is_sparse",
"(",
"c",
")",
"for",
"c",
"in",
"compat",
".",
"itervalues",
"(",
"result",
... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/dtypes/concat.py#L64-L84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.