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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
addisonlynch/iexfinance | 64ee3afe0f3e456e5a0a8120dd7c8c87b28964dd | iexfinance/stocks/base.py | python | Stock.get_key_stats | (self, **kwargs) | return self._get_endpoint("stats", params=kwargs) | Reference: https://iexcloud.io/docs/api/#key-stats
Parameters
----------
stat: str, optional
Case sensitive string matching the name of a single key
to return one value.Ex: If you only want the next earnings
date, you would use `nextEarningsDate`. | Reference: https://iexcloud.io/docs/api/#key-stats | [
"Reference",
":",
"https",
":",
"//",
"iexcloud",
".",
"io",
"/",
"docs",
"/",
"api",
"/",
"#key",
"-",
"stats"
] | def get_key_stats(self, **kwargs):
"""
Reference: https://iexcloud.io/docs/api/#key-stats
Parameters
----------
stat: str, optional
Case sensitive string matching the name of a single key
to return one value.Ex: If you only want the next earnings
date, you would use `nextEarningsDate`.
"""
return self._get_endpoint("stats", params=kwargs) | [
"def",
"get_key_stats",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_get_endpoint",
"(",
"\"stats\"",
",",
"params",
"=",
"kwargs",
")"
] | https://github.com/addisonlynch/iexfinance/blob/64ee3afe0f3e456e5a0a8120dd7c8c87b28964dd/iexfinance/stocks/base.py#L763-L774 | |
RJT1990/pyflux | 297f2afc2095acd97c12e827dd500e8ea5da0c0f | pyflux/inference/bbvi.py | python | BBVI.current_parameters | (self) | return np.array(current) | Obtains an array with the current parameters | Obtains an array with the current parameters | [
"Obtains",
"an",
"array",
"with",
"the",
"current",
"parameters"
] | def current_parameters(self):
"""
Obtains an array with the current parameters
"""
current = []
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
current.append(self.q[core_param].vi_return_param(approx_param))
return np.array(current) | [
"def",
"current_parameters",
"(",
"self",
")",
":",
"current",
"=",
"[",
"]",
"for",
"core_param",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"for",
"approx_param",
"in",
"range",
"(",
"self",
".",
"q",
"[",
"core_param",
"]",
... | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L71-L79 | |
HazyResearch/metal | b54631e9b94a3dcf55f6043c53ec181e12f29eb1 | metal/analysis.py | python | lf_coverages | (L) | return np.ravel((L != 0).sum(axis=0)) / L.shape[0] | Return the **fraction of data points that each LF labels.**
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate | Return the **fraction of data points that each LF labels.**
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate | [
"Return",
"the",
"**",
"fraction",
"of",
"data",
"points",
"that",
"each",
"LF",
"labels",
".",
"**",
"Args",
":",
"L",
":",
"an",
"n",
"x",
"m",
"scipy",
".",
"sparse",
"matrix",
"where",
"L_",
"{",
"i",
"j",
"}",
"is",
"the",
"label",
"given",
... | def lf_coverages(L):
"""Return the **fraction of data points that each LF labels.**
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
"""
return np.ravel((L != 0).sum(axis=0)) / L.shape[0] | [
"def",
"lf_coverages",
"(",
"L",
")",
":",
"return",
"np",
".",
"ravel",
"(",
"(",
"L",
"!=",
"0",
")",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
")",
"/",
"L",
".",
"shape",
"[",
"0",
"]"
] | https://github.com/HazyResearch/metal/blob/b54631e9b94a3dcf55f6043c53ec181e12f29eb1/metal/analysis.py#L71-L77 | |
xiadingZ/video-caption.pytorch | 0597647c9f1f756202ba7ff9898ad0a26847480f | misc/utils.py | python | RewardCriterion.forward | (self, input, seq, reward) | return output | [] | def forward(self, input, seq, reward):
input = input.contiguous().view(-1)
reward = reward.contiguous().view(-1)
mask = (seq > 0).float()
mask = torch.cat([mask.new(mask.size(0), 1).fill_(1).cuda(),
mask[:, :-1]], 1).contiguous().view(-1)
output = - input * reward * mask
output = torch.sum(output) / torch.sum(mask)
return output | [
"def",
"forward",
"(",
"self",
",",
"input",
",",
"seq",
",",
"reward",
")",
":",
"input",
"=",
"input",
".",
"contiguous",
"(",
")",
".",
"view",
"(",
"-",
"1",
")",
"reward",
"=",
"reward",
".",
"contiguous",
"(",
")",
".",
"view",
"(",
"-",
... | https://github.com/xiadingZ/video-caption.pytorch/blob/0597647c9f1f756202ba7ff9898ad0a26847480f/misc/utils.py#L30-L39 | |||
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/_version.py | python | render_pep440_pre | (pieces) | return rendered | TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE | TAG[.post.devDISTANCE] -- No -dirty. | [
"TAG",
"[",
".",
"post",
".",
"devDISTANCE",
"]",
"--",
"No",
"-",
"dirty",
"."
] | def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exception #1
rendered = "0.post.dev%d" % pieces["distance"]
return rendered | [
"def",
"render_pep440_pre",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
":",
"rendered",
"+=",
"\".post.dev%d\"",
"%",
"pieces",
... | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/_version.py#L364-L377 | |
ParallelSSH/parallel-ssh | 9c9b67825019b221927343a18a3c00001ae92aa2 | pssh/clients/native/single.py | python | SSHClient.spawn_send_keepalive | (self) | return spawn(self._send_keepalive) | Spawns a new greenlet that sends keep alive messages every
self.keepalive_seconds | Spawns a new greenlet that sends keep alive messages every
self.keepalive_seconds | [
"Spawns",
"a",
"new",
"greenlet",
"that",
"sends",
"keep",
"alive",
"messages",
"every",
"self",
".",
"keepalive_seconds"
] | def spawn_send_keepalive(self):
"""Spawns a new greenlet that sends keep alive messages every
self.keepalive_seconds"""
return spawn(self._send_keepalive) | [
"def",
"spawn_send_keepalive",
"(",
"self",
")",
":",
"return",
"spawn",
"(",
"self",
".",
"_send_keepalive",
")"
] | https://github.com/ParallelSSH/parallel-ssh/blob/9c9b67825019b221927343a18a3c00001ae92aa2/pssh/clients/native/single.py#L203-L206 | |
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/django/contrib/admin/views/main.py | python | ChangeList.get_filters | (self, request) | [] | def get_filters(self, request):
lookup_params = self.get_filters_params()
use_distinct = False
for key, value in lookup_params.items():
if not self.model_admin.lookup_allowed(key, value):
raise DisallowedModelAdminLookup("Filtering by %s not allowed" % key)
filter_specs = []
if self.list_filter:
for list_filter in self.list_filter:
if callable(list_filter):
# This is simply a custom list filter class.
spec = list_filter(request, lookup_params, self.model, self.model_admin)
else:
field_path = None
if isinstance(list_filter, (tuple, list)):
# This is a custom FieldListFilter class for a given field.
field, field_list_filter_class = list_filter
else:
# This is simply a field name, so use the default
# FieldListFilter class that has been registered for
# the type of the given field.
field, field_list_filter_class = list_filter, FieldListFilter.create
if not isinstance(field, models.Field):
field_path = field
field = get_fields_from_path(self.model, field_path)[-1]
lookup_params_count = len(lookup_params)
spec = field_list_filter_class(
field, request, lookup_params,
self.model, self.model_admin, field_path=field_path
)
# field_list_filter_class removes any lookup_params it
# processes. If that happened, check if distinct() is
# needed to remove duplicate results.
if lookup_params_count > len(lookup_params):
use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, field_path)
if spec and spec.has_output():
filter_specs.append(spec)
# At this point, all the parameters used by the various ListFilters
# have been removed from lookup_params, which now only contains other
# parameters passed via the query string. We now loop through the
# remaining parameters both to ensure that all the parameters are valid
# fields and to determine if at least one of them needs distinct(). If
# the lookup parameters aren't real fields, then bail out.
try:
for key, value in lookup_params.items():
lookup_params[key] = prepare_lookup_value(key, value)
use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, key)
return filter_specs, bool(filter_specs), lookup_params, use_distinct
except FieldDoesNotExist as e:
six.reraise(IncorrectLookupParameters, IncorrectLookupParameters(e), sys.exc_info()[2]) | [
"def",
"get_filters",
"(",
"self",
",",
"request",
")",
":",
"lookup_params",
"=",
"self",
".",
"get_filters_params",
"(",
")",
"use_distinct",
"=",
"False",
"for",
"key",
",",
"value",
"in",
"lookup_params",
".",
"items",
"(",
")",
":",
"if",
"not",
"se... | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/admin/views/main.py#L101-L154 | ||||
nltk/nltk | 3f74ac55681667d7ef78b664557487145f51eb02 | nltk/sem/linearlogic.py | python | BindingDict.__add__ | (self, other) | :param other: ``BindingDict`` The dict with which to combine self
:return: ``BindingDict`` A new dict containing all the elements of both parameters
:raise VariableBindingException: If the parameter dictionaries are not consistent with each other | :param other: ``BindingDict`` The dict with which to combine self
:return: ``BindingDict`` A new dict containing all the elements of both parameters
:raise VariableBindingException: If the parameter dictionaries are not consistent with each other | [
":",
"param",
"other",
":",
"BindingDict",
"The",
"dict",
"with",
"which",
"to",
"combine",
"self",
":",
"return",
":",
"BindingDict",
"A",
"new",
"dict",
"containing",
"all",
"the",
"elements",
"of",
"both",
"parameters",
":",
"raise",
"VariableBindingExcepti... | def __add__(self, other):
"""
:param other: ``BindingDict`` The dict with which to combine self
:return: ``BindingDict`` A new dict containing all the elements of both parameters
:raise VariableBindingException: If the parameter dictionaries are not consistent with each other
"""
try:
combined = BindingDict()
for v in self.d:
combined[v] = self.d[v]
for v in other.d:
combined[v] = other.d[v]
return combined
except VariableBindingException as e:
raise VariableBindingException(
"Attempting to add two contradicting"
" VariableBindingsLists: %s, %s" % (self, other)
) from e | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"try",
":",
"combined",
"=",
"BindingDict",
"(",
")",
"for",
"v",
"in",
"self",
".",
"d",
":",
"combined",
"[",
"v",
"]",
"=",
"self",
".",
"d",
"[",
"v",
"]",
"for",
"v",
"in",
"other",
... | https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/sem/linearlogic.py#L421-L438 | ||
PaddlePaddle/X2Paddle | b492545f61446af69e5d5d6288bc3a43a9a3931e | x2paddle/op_mapper/pytorch2paddle/aten.py | python | aten_frobenius_norm | (mapper, graph, node) | return current_inputs, current_outputs | 构造计算范数的PaddleLayer。
TorchScript示例:
%25 = aten::frobenius_norm(%input, %58, %24)
参数含义:
%25 (Tensor): 取范数后的结果。
%input (Tensor): 输入。
%58 (int): 使用范数计算的轴。
%24 (bool): 是否在输出的Tensor中保留和输入一样的维度。 | 构造计算范数的PaddleLayer。
TorchScript示例:
%25 = aten::frobenius_norm(%input, %58, %24)
参数含义:
%25 (Tensor): 取范数后的结果。
%input (Tensor): 输入。
%58 (int): 使用范数计算的轴。
%24 (bool): 是否在输出的Tensor中保留和输入一样的维度。 | [
"构造计算范数的PaddleLayer。",
"TorchScript示例",
":",
"%25",
"=",
"aten",
"::",
"frobenius_norm",
"(",
"%input",
"%58",
"%24",
")",
"参数含义",
":",
"%25",
"(",
"Tensor",
")",
":",
"取范数后的结果。",
"%input",
"(",
"Tensor",
")",
":",
"输入。",
"%58",
"(",
"int",
")",
":",
"... | def aten_frobenius_norm(mapper, graph, node):
""" 构造计算范数的PaddleLayer。
TorchScript示例:
%25 = aten::frobenius_norm(%input, %58, %24)
参数含义:
%25 (Tensor): 取范数后的结果。
%input (Tensor): 输入。
%58 (int): 使用范数计算的轴。
%24 (bool): 是否在输出的Tensor中保留和输入一样的维度。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_outputs_name(node)[0]
layer_outputs = [output_name]
layer_inputs = {}
layer_attrs = {}
inputs_name, inputs_node = mapper._get_inputs_name(node)
# 获取当前节点输出的list
current_outputs = [output_name]
# 处理输入0,即%input
mapper._check_input(graph, inputs_node[0], inputs_name[0], current_outputs,
scope_name)
layer_inputs["x"] = inputs_name[0]
current_inputs = list(layer_inputs.values())
layer_attrs["p"] = 2
# 处理输入1,即%58
if inputs_name[1] in mapper.attrs:
layer_attrs["axis"] = mapper.attrs[inputs_name[1]]
else:
mapper._check_input(graph, inputs_node[1], inputs_name[1],
current_outputs, scope_name)
layer_inputs["axis"] = inputs_name[1]
current_inputs.append(inputs_name[1])
# 处理输入2,即%24
if inputs_name[1] in mapper.attrs:
layer_attrs["keepdim"] = mapper.attrs[inputs_name[2]]
else:
mapper._check_input(graph, inputs_node[2], inputs_name[2],
current_outputs, scope_name)
layer_inputs["keepdim"] = inputs_name[2]
current_inputs.append(inputs_name[2])
graph.add_layer(
"paddle.norm",
inputs=layer_inputs,
outputs=layer_outputs,
scope_name=scope_name,
**layer_attrs)
return current_inputs, current_outputs | [
"def",
"aten_frobenius_norm",
"(",
"mapper",
",",
"graph",
",",
"node",
")",
":",
"scope_name",
"=",
"mapper",
".",
"normalize_scope_name",
"(",
"node",
")",
"output_name",
"=",
"mapper",
".",
"_get_outputs_name",
"(",
"node",
")",
"[",
"0",
"]",
"layer_outp... | https://github.com/PaddlePaddle/X2Paddle/blob/b492545f61446af69e5d5d6288bc3a43a9a3931e/x2paddle/op_mapper/pytorch2paddle/aten.py#L3741-L3788 | |
NiaOrg/NiaPy | 08f24ffc79fe324bc9c66ee7186ef98633026005 | niapy/algorithms/basic/de.py | python | MultiStrategyDifferentialEvolution.set_parameters | (self, strategies=(cross_rand1, cross_best1, cross_curr2best1, cross_rand2), **kwargs) | r"""Set the arguments of the algorithm.
Args:
strategies (Optional[Iterable[Callable[[numpy.ndarray[Individual], int, Individual, float, float, numpy.random.Generator], numpy.ndarray[Individual]]]]):
List of mutation strategies.
See Also:
* :func:`niapy.algorithms.basic.DifferentialEvolution.set_parameters` | r"""Set the arguments of the algorithm. | [
"r",
"Set",
"the",
"arguments",
"of",
"the",
"algorithm",
"."
] | def set_parameters(self, strategies=(cross_rand1, cross_best1, cross_curr2best1, cross_rand2), **kwargs):
r"""Set the arguments of the algorithm.
Args:
strategies (Optional[Iterable[Callable[[numpy.ndarray[Individual], int, Individual, float, float, numpy.random.Generator], numpy.ndarray[Individual]]]]):
List of mutation strategies.
See Also:
* :func:`niapy.algorithms.basic.DifferentialEvolution.set_parameters`
"""
super().set_parameters(strategy=multi_mutations, **kwargs)
self.strategies = strategies | [
"def",
"set_parameters",
"(",
"self",
",",
"strategies",
"=",
"(",
"cross_rand1",
",",
"cross_best1",
",",
"cross_curr2best1",
",",
"cross_rand2",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"set_parameters",
"(",
"strategy",
"=",
"mult... | https://github.com/NiaOrg/NiaPy/blob/08f24ffc79fe324bc9c66ee7186ef98633026005/niapy/algorithms/basic/de.py#L890-L902 | ||
mpi4py/mpi4py | 8a5e5adf8f41e4e7cc134a8f2574aeb95a7e8dac | src/mpi4py/futures/aplus.py | python | catch | (future, on_failure=None) | return then(future, None, on_failure) | Close equivalent to ``then(future, None, on_failure)``.
Args:
future: Input future instance.
on_failure (optional): Function to be called when the input future is
rejected. If `on_failure` is ``None``, the output future will be
resolved with ``None`` thus ignoring the exception. | Close equivalent to ``then(future, None, on_failure)``. | [
"Close",
"equivalent",
"to",
"then",
"(",
"future",
"None",
"on_failure",
")",
"."
] | def catch(future, on_failure=None):
"""Close equivalent to ``then(future, None, on_failure)``.
Args:
future: Input future instance.
on_failure (optional): Function to be called when the input future is
rejected. If `on_failure` is ``None``, the output future will be
resolved with ``None`` thus ignoring the exception.
"""
if on_failure is None:
return then(future, None, lambda exc: None)
return then(future, None, on_failure) | [
"def",
"catch",
"(",
"future",
",",
"on_failure",
"=",
"None",
")",
":",
"if",
"on_failure",
"is",
"None",
":",
"return",
"then",
"(",
"future",
",",
"None",
",",
"lambda",
"exc",
":",
"None",
")",
"return",
"then",
"(",
"future",
",",
"None",
",",
... | https://github.com/mpi4py/mpi4py/blob/8a5e5adf8f41e4e7cc134a8f2574aeb95a7e8dac/src/mpi4py/futures/aplus.py#L65-L77 | |
google/pybadges | 1f4de8796e7e0c19723054bccd41c6665e10e0a2 | pybadges/precalculate_text.py | python | generate_supported_characters | (deja_vu_sans_path: str) | Generate the characters support by the font at the given path. | Generate the characters support by the font at the given path. | [
"Generate",
"the",
"characters",
"support",
"by",
"the",
"font",
"at",
"the",
"given",
"path",
"."
] | def generate_supported_characters(deja_vu_sans_path: str) -> Iterable[str]:
"""Generate the characters support by the font at the given path."""
font = ttLib.TTFont(deja_vu_sans_path)
for cmap in font['cmap'].tables:
if cmap.isUnicode():
for code in cmap.cmap:
yield chr(code) | [
"def",
"generate_supported_characters",
"(",
"deja_vu_sans_path",
":",
"str",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"font",
"=",
"ttLib",
".",
"TTFont",
"(",
"deja_vu_sans_path",
")",
"for",
"cmap",
"in",
"font",
"[",
"'cmap'",
"]",
".",
"tables",
"... | https://github.com/google/pybadges/blob/1f4de8796e7e0c19723054bccd41c6665e10e0a2/pybadges/precalculate_text.py#L56-L62 | ||
brendano/tweetmotif | 1b0b1e3a941745cd5a26eba01f554688b7c4b27e | everything_else/djfrontend/django-1.0.2/utils/_decimal.py | python | Decimal.__long__ | (self) | return long(self.__int__()) | Converts to a long.
Equivalent to long(int(self)) | Converts to a long. | [
"Converts",
"to",
"a",
"long",
"."
] | def __long__(self):
"""Converts to a long.
Equivalent to long(int(self))
"""
return long(self.__int__()) | [
"def",
"__long__",
"(",
"self",
")",
":",
"return",
"long",
"(",
"self",
".",
"__int__",
"(",
")",
")"
] | https://github.com/brendano/tweetmotif/blob/1b0b1e3a941745cd5a26eba01f554688b7c4b27e/everything_else/djfrontend/django-1.0.2/utils/_decimal.py#L1466-L1471 | |
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v7/services/services/currency_constant_service/client.py | python | CurrencyConstantServiceClientMeta.get_transport_class | (
cls, label: str = None,
) | return next(iter(cls._transport_registry.values())) | Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use. | Return an appropriate transport class. | [
"Return",
"an",
"appropriate",
"transport",
"class",
"."
] | def get_transport_class(
cls, label: str = None,
) -> Type[CurrencyConstantServiceTransport]:
"""Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
if label:
return cls._transport_registry[label]
# No transport is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values())) | [
"def",
"get_transport_class",
"(",
"cls",
",",
"label",
":",
"str",
"=",
"None",
",",
")",
"->",
"Type",
"[",
"CurrencyConstantServiceTransport",
"]",
":",
"# If a specific transport is requested, return that one.",
"if",
"label",
":",
"return",
"cls",
".",
"_transp... | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/currency_constant_service/client.py#L54-L72 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/codegen/ast.py | python | _mk_Tuple | (args) | return Tuple(*args) | Create a SymPy Tuple object from an iterable, converting Python strings to
AST strings.
Parameters
==========
args: iterable
Arguments to :class:`sympy.Tuple`.
Returns
=======
sympy.Tuple | Create a SymPy Tuple object from an iterable, converting Python strings to
AST strings. | [
"Create",
"a",
"SymPy",
"Tuple",
"object",
"from",
"an",
"iterable",
"converting",
"Python",
"strings",
"to",
"AST",
"strings",
"."
] | def _mk_Tuple(args):
"""
Create a SymPy Tuple object from an iterable, converting Python strings to
AST strings.
Parameters
==========
args: iterable
Arguments to :class:`sympy.Tuple`.
Returns
=======
sympy.Tuple
"""
args = [String(arg) if isinstance(arg, str) else arg for arg in args]
return Tuple(*args) | [
"def",
"_mk_Tuple",
"(",
"args",
")",
":",
"args",
"=",
"[",
"String",
"(",
"arg",
")",
"if",
"isinstance",
"(",
"arg",
",",
"str",
")",
"else",
"arg",
"for",
"arg",
"in",
"args",
"]",
"return",
"Tuple",
"(",
"*",
"args",
")"
] | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/codegen/ast.py#L143-L160 | |
wwqgtxx/wwqLyParse | 33136508e52821babd9294fdecffbdf02d73a6fc | wwqLyParse/lib/python-3.7.2-embed-amd64/pyquery/pyquery.py | python | PyQuery._filter_only | (self, selector, elements, reverse=False, unique=False) | return self._copy(results, parent=self) | Filters the selection set only, as opposed to also including
descendants. | Filters the selection set only, as opposed to also including
descendants. | [
"Filters",
"the",
"selection",
"set",
"only",
"as",
"opposed",
"to",
"also",
"including",
"descendants",
"."
] | def _filter_only(self, selector, elements, reverse=False, unique=False):
"""Filters the selection set only, as opposed to also including
descendants.
"""
if selector is None:
results = elements
else:
xpath = self._css_to_xpath(selector, 'self::')
results = []
for tag in elements:
results.extend(tag.xpath(xpath, namespaces=self.namespaces))
if reverse:
results.reverse()
if unique:
result_list = results
results = []
for item in result_list:
if item not in results:
results.append(item)
return self._copy(results, parent=self) | [
"def",
"_filter_only",
"(",
"self",
",",
"selector",
",",
"elements",
",",
"reverse",
"=",
"False",
",",
"unique",
"=",
"False",
")",
":",
"if",
"selector",
"is",
"None",
":",
"results",
"=",
"elements",
"else",
":",
"xpath",
"=",
"self",
".",
"_css_to... | https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/python-3.7.2-embed-amd64/pyquery/pyquery.py#L442-L461 | |
exercism/python | f79d44ef6c9cf68d8c76cb94017a590f04391635 | exercises/practice/trinary/.meta/example.py | python | trinary | (string) | return reduce(lambda idx, edx: idx * 3 + int(edx), string, 0) | [] | def trinary(string):
if set(string) - set('012'):
return 0
return reduce(lambda idx, edx: idx * 3 + int(edx), string, 0) | [
"def",
"trinary",
"(",
"string",
")",
":",
"if",
"set",
"(",
"string",
")",
"-",
"set",
"(",
"'012'",
")",
":",
"return",
"0",
"return",
"reduce",
"(",
"lambda",
"idx",
",",
"edx",
":",
"idx",
"*",
"3",
"+",
"int",
"(",
"edx",
")",
",",
"string... | https://github.com/exercism/python/blob/f79d44ef6c9cf68d8c76cb94017a590f04391635/exercises/practice/trinary/.meta/example.py#L4-L7 | |||
mylar3/mylar3 | fce4771c5b627f8de6868dd4ab6bc53f7b22d303 | lib/configobj.py | python | ConfigObj._write_line | (self, indent_string, entry, this_entry, comment) | return '%s%s%s%s%s' % (indent_string,
self._decode_element(self._quote(entry, multiline=False)),
self._a_to_u(' = '),
val,
self._decode_element(comment)) | Write an individual line, for the write method | Write an individual line, for the write method | [
"Write",
"an",
"individual",
"line",
"for",
"the",
"write",
"method"
] | def _write_line(self, indent_string, entry, this_entry, comment):
"""Write an individual line, for the write method"""
# NOTE: the calls to self._quote here handles non-StringType values.
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
val = repr(this_entry)
return '%s%s%s%s%s' % (indent_string,
self._decode_element(self._quote(entry, multiline=False)),
self._a_to_u(' = '),
val,
self._decode_element(comment)) | [
"def",
"_write_line",
"(",
"self",
",",
"indent_string",
",",
"entry",
",",
"this_entry",
",",
"comment",
")",
":",
"# NOTE: the calls to self._quote here handles non-StringType values.",
"if",
"not",
"self",
".",
"unrepr",
":",
"val",
"=",
"self",
".",
"_decode_ele... | https://github.com/mylar3/mylar3/blob/fce4771c5b627f8de6868dd4ab6bc53f7b22d303/lib/configobj.py#L1971-L1982 | |
OpenMined/PySyft | f181ca02d307d57bfff9477610358df1a12e3ac9 | packages/syft/src/syft/core/tensor/tensor.py | python | TensorPointer.__sub__ | (
self, other: Union[TensorPointer, MPCTensor, int, float, np.ndarray]
) | return TensorPointer._apply_op(self, other, "sub") | Apply the "sub" operation between "self" and "other"
Args:
y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.
Returns:
Union[TensorPointer,MPCTensor] : Result of the operation. | Apply the "sub" operation between "self" and "other" | [
"Apply",
"the",
"sub",
"operation",
"between",
"self",
"and",
"other"
] | def __sub__(
self, other: Union[TensorPointer, MPCTensor, int, float, np.ndarray]
) -> Union[TensorPointer, MPCTensor]:
"""Apply the "sub" operation between "self" and "other"
Args:
y (Union[TensorPointer,MPCTensor,int,float,np.ndarray]) : second operand.
Returns:
Union[TensorPointer,MPCTensor] : Result of the operation.
"""
return TensorPointer._apply_op(self, other, "sub") | [
"def",
"__sub__",
"(",
"self",
",",
"other",
":",
"Union",
"[",
"TensorPointer",
",",
"MPCTensor",
",",
"int",
",",
"float",
",",
"np",
".",
"ndarray",
"]",
")",
"->",
"Union",
"[",
"TensorPointer",
",",
"MPCTensor",
"]",
":",
"return",
"TensorPointer",
... | https://github.com/OpenMined/PySyft/blob/f181ca02d307d57bfff9477610358df1a12e3ac9/packages/syft/src/syft/core/tensor/tensor.py#L203-L214 | |
CvvT/dumpDex | 92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1 | python/idaapi.py | python | regval_t.__eq__ | (self, *args) | return _idaapi.regval_t___eq__(self, *args) | __eq__(self, r) -> bool | __eq__(self, r) -> bool | [
"__eq__",
"(",
"self",
"r",
")",
"-",
">",
"bool"
] | def __eq__(self, *args):
"""
__eq__(self, r) -> bool
"""
return _idaapi.regval_t___eq__(self, *args) | [
"def",
"__eq__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"regval_t___eq__",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L3248-L3252 | |
nerdvegas/rez | d392c65bf63b4bca8106f938cec49144ba54e770 | src/rez/vendor/six/six.py | python | remove_move | (name) | Remove item from six.moves. | Remove item from six.moves. | [
"Remove",
"item",
"from",
"six",
".",
"moves",
"."
] | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | [
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
... | https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/vendor/six/six.py#L497-L505 | ||
scottslowe/learning-tools | 5a2abe30e269055d89f6ff4210f0f9f52d632680 | ansible/kubeadm-etcd-template/inventory/ec2.py | python | Ec2Inventory.get_auth_error_message | (self) | return '\n'.join(errors) | create an informative error message if there is an issue authenticating | create an informative error message if there is an issue authenticating | [
"create",
"an",
"informative",
"error",
"message",
"if",
"there",
"is",
"an",
"issue",
"authenticating"
] | def get_auth_error_message(self):
''' create an informative error message if there is an issue authenticating'''
errors = ["Authentication error retrieving ec2 inventory."]
if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]:
errors.append(' - No AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment vars found')
else:
errors.append(' - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment vars found but may not be correct')
boto_paths = ['/etc/boto.cfg', '~/.boto', '~/.aws/credentials']
boto_config_found = list(p for p in boto_paths if os.path.isfile(os.path.expanduser(p)))
if len(boto_config_found) > 0:
errors.append(" - Boto configs found at '%s', but the credentials contained may not be correct" % ', '.join(boto_config_found))
else:
errors.append(" - No Boto config found at any expected location '%s'" % ', '.join(boto_paths))
return '\n'.join(errors) | [
"def",
"get_auth_error_message",
"(",
"self",
")",
":",
"errors",
"=",
"[",
"\"Authentication error retrieving ec2 inventory.\"",
"]",
"if",
"None",
"in",
"[",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_ACCESS_KEY_ID'",
")",
",",
"os",
".",
"environ",
".",
"... | https://github.com/scottslowe/learning-tools/blob/5a2abe30e269055d89f6ff4210f0f9f52d632680/ansible/kubeadm-etcd-template/inventory/ec2.py#L775-L790 | |
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/models/v1_endpoints.py | python | V1Endpoints.kind | (self) | return self._kind | Gets the kind of this V1Endpoints.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
:return: The kind of this V1Endpoints.
:rtype: str | Gets the kind of this V1Endpoints.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds | [
"Gets",
"the",
"kind",
"of",
"this",
"V1Endpoints",
".",
"Kind",
"is",
"a",
"string",
"value",
"representing",
"the",
"REST",
"resource",
"this",
"object",
"represents",
".",
"Servers",
"may",
"infer",
"this",
"from",
"the",
"endpoint",
"the",
"client",
"sub... | def kind(self):
"""
Gets the kind of this V1Endpoints.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
:return: The kind of this V1Endpoints.
:rtype: str
"""
return self._kind | [
"def",
"kind",
"(",
"self",
")",
":",
"return",
"self",
".",
"_kind"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_endpoints.py#L76-L84 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-0.96/django/utils/translation/trans_real.py | python | gettext | (message) | return _default.gettext(message) | This function will be patched into the builtins module to provide the _
helper function. It will use the current thread as a discriminator to find
the translation object to use. If no current translation is activated, the
message will be run through the default translation object. | This function will be patched into the builtins module to provide the _
helper function. It will use the current thread as a discriminator to find
the translation object to use. If no current translation is activated, the
message will be run through the default translation object. | [
"This",
"function",
"will",
"be",
"patched",
"into",
"the",
"builtins",
"module",
"to",
"provide",
"the",
"_",
"helper",
"function",
".",
"It",
"will",
"use",
"the",
"current",
"thread",
"as",
"a",
"discriminator",
"to",
"find",
"the",
"translation",
"object... | def gettext(message):
"""
This function will be patched into the builtins module to provide the _
helper function. It will use the current thread as a discriminator to find
the translation object to use. If no current translation is activated, the
message will be run through the default translation object.
"""
global _default, _active
t = _active.get(currentThread(), None)
if t is not None:
return t.gettext(message)
if _default is None:
from django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
return _default.gettext(message) | [
"def",
"gettext",
"(",
"message",
")",
":",
"global",
"_default",
",",
"_active",
"t",
"=",
"_active",
".",
"get",
"(",
"currentThread",
"(",
")",
",",
"None",
")",
"if",
"t",
"is",
"not",
"None",
":",
"return",
"t",
".",
"gettext",
"(",
"message",
... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-0.96/django/utils/translation/trans_real.py#L255-L269 | |
skylander86/lambda-text-extractor | 6da52d077a2fc571e38bfe29c33ae68f6443cd5a | lib-linux_x64/docx/oxml/table.py | python | CT_Tc._remove_trailing_empty_p | (self) | Remove the last content element from this cell if it is an empty
``<w:p>`` element. | Remove the last content element from this cell if it is an empty
``<w:p>`` element. | [
"Remove",
"the",
"last",
"content",
"element",
"from",
"this",
"cell",
"if",
"it",
"is",
"an",
"empty",
"<w",
":",
"p",
">",
"element",
"."
] | def _remove_trailing_empty_p(self):
"""
Remove the last content element from this cell if it is an empty
``<w:p>`` element.
"""
block_items = list(self.iter_block_items())
last_content_elm = block_items[-1]
if last_content_elm.tag != qn('w:p'):
return
p = last_content_elm
if len(p.r_lst) > 0:
return
self.remove(p) | [
"def",
"_remove_trailing_empty_p",
"(",
"self",
")",
":",
"block_items",
"=",
"list",
"(",
"self",
".",
"iter_block_items",
"(",
")",
")",
"last_content_elm",
"=",
"block_items",
"[",
"-",
"1",
"]",
"if",
"last_content_elm",
".",
"tag",
"!=",
"qn",
"(",
"'... | https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/docx/oxml/table.py#L565-L577 | ||
rushter/MLAlgorithms | 3c8e16b8de3baf131395ae57edd479e59566a7c6 | mla/linear_models.py | python | BasicRegression._predict | (self, X=None) | return X.dot(self.theta) | [] | def _predict(self, X=None):
X = self._add_intercept(X)
return X.dot(self.theta) | [
"def",
"_predict",
"(",
"self",
",",
"X",
"=",
"None",
")",
":",
"X",
"=",
"self",
".",
"_add_intercept",
"(",
"X",
")",
"return",
"X",
".",
"dot",
"(",
"self",
".",
"theta",
")"
] | https://github.com/rushter/MLAlgorithms/blob/3c8e16b8de3baf131395ae57edd479e59566a7c6/mla/linear_models.py#L85-L87 | |||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/rfc822.py | python | Message.getheader | (self, name, default=None) | return self.dict.get(name.lower(), default) | Get the header value for a name.
This is the normal interface: it returns a stripped version of the
header value for a given header name, or None if it doesn't exist.
This uses the dictionary version which finds the *last* such header. | Get the header value for a name. | [
"Get",
"the",
"header",
"value",
"for",
"a",
"name",
"."
] | def getheader(self, name, default=None):
"""Get the header value for a name.
This is the normal interface: it returns a stripped version of the
header value for a given header name, or None if it doesn't exist.
This uses the dictionary version which finds the *last* such header.
"""
return self.dict.get(name.lower(), default) | [
"def",
"getheader",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"dict",
".",
"get",
"(",
"name",
".",
"lower",
"(",
")",
",",
"default",
")"
] | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/rfc822.py#L285-L292 | |
realthunder/FreeCAD_assembly3 | 8e8977cb444c8e3cde715e9f63d6f5b361c3e13f | freecad/asm3/deps/six.py | python | _add_doc | (func, doc) | Add documentation to a function. | Add documentation to a function. | [
"Add",
"documentation",
"to",
"a",
"function",
"."
] | def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc | [
"def",
"_add_doc",
"(",
"func",
",",
"doc",
")",
":",
"func",
".",
"__doc__",
"=",
"doc"
] | https://github.com/realthunder/FreeCAD_assembly3/blob/8e8977cb444c8e3cde715e9f63d6f5b361c3e13f/freecad/asm3/deps/six.py#L75-L77 | ||
nerdvegas/rez | d392c65bf63b4bca8106f938cec49144ba54e770 | src/rez/vendor/distlib/_backport/tarfile.py | python | TarFile.makefile | (self, tarinfo, targetpath) | Make a file called targetpath. | Make a file called targetpath. | [
"Make",
"a",
"file",
"called",
"targetpath",
"."
] | def makefile(self, tarinfo, targetpath):
"""Make a file called targetpath.
"""
source = self.fileobj
source.seek(tarinfo.offset_data)
target = bltn_open(targetpath, "wb")
if tarinfo.sparse is not None:
for offset, size in tarinfo.sparse:
target.seek(offset)
copyfileobj(source, target, size)
else:
copyfileobj(source, target, tarinfo.size)
target.seek(tarinfo.size)
target.truncate()
target.close() | [
"def",
"makefile",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"source",
"=",
"self",
".",
"fileobj",
"source",
".",
"seek",
"(",
"tarinfo",
".",
"offset_data",
")",
"target",
"=",
"bltn_open",
"(",
"targetpath",
",",
"\"wb\"",
")",
"if",
... | https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/vendor/distlib/_backport/tarfile.py#L2296-L2310 | ||
tensorflow/tfx | b4a6b83269815ed12ba9df9e9154c7376fef2ea0 | tfx/orchestration/launcher/kubernetes_component_launcher.py | python | KubernetesComponentLauncher._run_executor | (self, execution_id: int,
input_dict: Dict[str, List[types.Artifact]],
output_dict: Dict[str, List[types.Artifact]],
exec_properties: Dict[str, Any]) | Execute underlying component implementation.
Runs executor container in a Kubernetes Pod and wait until it goes into
`Succeeded` or `Failed` state.
Args:
execution_id: The ID of the execution.
input_dict: Input dict from input key to a list of Artifacts. These are
often outputs of another component in the pipeline and passed to the
component by the orchestration system.
output_dict: Output dict from output key to a list of Artifacts. These are
often consumed by a dependent component.
exec_properties: A dict of execution properties. These are inputs to
pipeline with primitive types (int, string, float) and fully
materialized when a pipeline is constructed. No dependency to other
component or later injection from orchestration systems is necessary or
possible on these values.
Raises:
RuntimeError: when the pod is in `Failed` state or unexpected failure from
Kubernetes API. | Execute underlying component implementation. | [
"Execute",
"underlying",
"component",
"implementation",
"."
] | def _run_executor(self, execution_id: int,
input_dict: Dict[str, List[types.Artifact]],
output_dict: Dict[str, List[types.Artifact]],
exec_properties: Dict[str, Any]) -> None:
"""Execute underlying component implementation.
Runs executor container in a Kubernetes Pod and wait until it goes into
`Succeeded` or `Failed` state.
Args:
execution_id: The ID of the execution.
input_dict: Input dict from input key to a list of Artifacts. These are
often outputs of another component in the pipeline and passed to the
component by the orchestration system.
output_dict: Output dict from output key to a list of Artifacts. These are
often consumed by a dependent component.
exec_properties: A dict of execution properties. These are inputs to
pipeline with primitive types (int, string, float) and fully
materialized when a pipeline is constructed. No dependency to other
component or later injection from orchestration systems is necessary or
possible on these values.
Raises:
RuntimeError: when the pod is in `Failed` state or unexpected failure from
Kubernetes API.
"""
container_spec = cast(executor_spec.ExecutorContainerSpec,
self._component_executor_spec)
# Replace container spec with jinja2 template.
container_spec = container_common.resolve_container_template(
container_spec, input_dict, output_dict, exec_properties)
pod_name = self._build_pod_name(execution_id)
# TODO(hongyes): replace the default value from component config.
try:
namespace = kube_utils.get_kfp_namespace()
except RuntimeError:
namespace = 'kubeflow'
pod_manifest = self._build_pod_manifest(pod_name, container_spec)
core_api = kube_utils.make_core_v1_api()
if kube_utils.is_inside_kfp():
launcher_pod = kube_utils.get_current_kfp_pod(core_api)
pod_manifest['spec']['serviceAccount'] = launcher_pod.spec.service_account
pod_manifest['spec'][
'serviceAccountName'] = launcher_pod.spec.service_account_name
pod_manifest['metadata'][
'ownerReferences'] = container_common.to_swagger_dict(
launcher_pod.metadata.owner_references)
else:
pod_manifest['spec']['serviceAccount'] = kube_utils.TFX_SERVICE_ACCOUNT
pod_manifest['spec'][
'serviceAccountName'] = kube_utils.TFX_SERVICE_ACCOUNT
logging.info('Looking for pod "%s:%s".', namespace, pod_name)
resp = kube_utils.get_pod(core_api, pod_name, namespace)
if not resp:
logging.info('Pod "%s:%s" does not exist. Creating it...',
namespace, pod_name)
logging.info('Pod manifest: %s', pod_manifest)
try:
resp = core_api.create_namespaced_pod(
namespace=namespace, body=pod_manifest)
except client.rest.ApiException as e:
raise RuntimeError(
'Failed to created container executor pod!\nReason: %s\nBody: %s' %
(e.reason, e.body))
# Wait up to 300 seconds for the pod to move from pending to another status.
logging.info('Waiting for pod "%s:%s" to start.', namespace, pod_name)
kube_utils.wait_pod(
core_api,
pod_name,
namespace,
exit_condition_lambda=kube_utils.pod_is_not_pending,
condition_description='non-pending status',
timeout_sec=300)
logging.info('Start log streaming for pod "%s:%s".', namespace, pod_name)
try:
logs = core_api.read_namespaced_pod_log(
name=pod_name,
namespace=namespace,
container=kube_utils.ARGO_MAIN_CONTAINER_NAME,
follow=True,
_preload_content=False).stream()
except client.rest.ApiException as e:
raise RuntimeError(
'Failed to stream the logs from the pod!\nReason: %s\nBody: %s' %
(e.reason, e.body))
for log in logs:
logging.info(log.decode().rstrip('\n'))
# Wait indefinitely for the pod to complete.
resp = kube_utils.wait_pod(
core_api,
pod_name,
namespace,
exit_condition_lambda=kube_utils.pod_is_done,
condition_description='done state')
if resp.status.phase == kube_utils.PodPhase.FAILED.value:
raise RuntimeError('Pod "%s:%s" failed with status "%s".' %
(namespace, pod_name, resp.status))
logging.info('Pod "%s:%s" is done.', namespace, pod_name) | [
"def",
"_run_executor",
"(",
"self",
",",
"execution_id",
":",
"int",
",",
"input_dict",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"types",
".",
"Artifact",
"]",
"]",
",",
"output_dict",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"types",
".",
"Arti... | https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/orchestration/launcher/kubernetes_component_launcher.py#L52-L161 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/cfinite_sequence.py | python | CFiniteSequence._sub_ | (self, other) | return CFiniteSequence(self.ogf() - other.numerator() / other.denominator()) | Subtraction of C-finite sequences.
TESTS::
sage: C.<x> = CFiniteSequences(QQ)
sage: r = C(1/(1-2*x))
sage: r[0:5] # a(n) = 2^n
[1, 2, 4, 8, 16]
sage: s = C.from_recurrence([1],[1])
sage: (r - s)[0:5] # a(n) = 2^n + 1
[0, 1, 3, 7, 15] | Subtraction of C-finite sequences. | [
"Subtraction",
"of",
"C",
"-",
"finite",
"sequences",
"."
] | def _sub_(self, other):
"""
Subtraction of C-finite sequences.
TESTS::
sage: C.<x> = CFiniteSequences(QQ)
sage: r = C(1/(1-2*x))
sage: r[0:5] # a(n) = 2^n
[1, 2, 4, 8, 16]
sage: s = C.from_recurrence([1],[1])
sage: (r - s)[0:5] # a(n) = 2^n + 1
[0, 1, 3, 7, 15]
"""
return CFiniteSequence(self.ogf() - other.numerator() / other.denominator()) | [
"def",
"_sub_",
"(",
"self",
",",
"other",
")",
":",
"return",
"CFiniteSequence",
"(",
"self",
".",
"ogf",
"(",
")",
"-",
"other",
".",
"numerator",
"(",
")",
"/",
"other",
".",
"denominator",
"(",
")",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/cfinite_sequence.py#L462-L476 | |
Amulet-Team/Amulet-Map-Editor | e99619ba6aab855173b9f7c203455944ab97f89a | amulet_map_editor/_version.py | python | git_versions_from_keywords | (keywords, tag_prefix, verbose) | return {
"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
"date": None,
} | Get version information from git keywords. | Get version information from git keywords. | [
"Get",
"version",
"information",
"from",
"git",
"keywords",
"."
] | def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
# datestamp. However we prefer "%ci" (which expands to an "ISO-8601
# -like" string, which we must then edit to make compliant), because
# it's been around since git-1.5.3, and it's too difficult to
# discover which version we're using, or to work around using an
# older one.
date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)])
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
# expansion behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r"\d", r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix) :]
if verbose:
print("picking %s" % r)
return {
"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": None,
"date": date,
}
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {
"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
"date": None,
} | [
"def",
"git_versions_from_keywords",
"(",
"keywords",
",",
"tag_prefix",
",",
"verbose",
")",
":",
"if",
"not",
"keywords",
":",
"raise",
"NotThisMethod",
"(",
"\"no keywords at all, weird\"",
")",
"date",
"=",
"keywords",
".",
"get",
"(",
"\"date\"",
")",
"if",... | https://github.com/Amulet-Team/Amulet-Map-Editor/blob/e99619ba6aab855173b9f7c203455944ab97f89a/amulet_map_editor/_version.py#L171-L229 | |
RasaHQ/rasa | 54823b68c1297849ba7ae841a4246193cd1223a1 | rasa/shared/core/training_data/structures.py | python | StoryGraph.__hash__ | (self) | return int(self.fingerprint(), 16) | Return hash for the story step.
Returns:
Hash of the story step. | Return hash for the story step. | [
"Return",
"hash",
"for",
"the",
"story",
"step",
"."
] | def __hash__(self) -> int:
"""Return hash for the story step.
Returns:
Hash of the story step.
"""
return int(self.fingerprint(), 16) | [
"def",
"__hash__",
"(",
"self",
")",
"->",
"int",
":",
"return",
"int",
"(",
"self",
".",
"fingerprint",
"(",
")",
",",
"16",
")"
] | https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/shared/core/training_data/structures.py#L440-L446 | |
Azure/azure-devops-cli-extension | 11334cd55806bef0b99c3bee5a438eed71e44037 | azure-devops/azext_devops/devops_sdk/released/work/work_client.py | python | WorkClient.update_team_days_off | (self, days_off_patch, team_context, iteration_id) | return self._deserialize('TeamSettingsDaysOff', response) | UpdateTeamDaysOff.
Set a team's days off for an iteration
:param :class:`<TeamSettingsDaysOffPatch> <azure.devops.v5_1.work.models.TeamSettingsDaysOffPatch>` days_off_patch: Team's days off patch containting a list of start and end dates
:param :class:`<TeamContext> <azure.devops.v5_1.work.models.TeamContext>` team_context: The team context for the operation
:param str iteration_id: ID of the iteration
:rtype: :class:`<TeamSettingsDaysOff> <azure.devops.v5_1.work.models.TeamSettingsDaysOff>` | UpdateTeamDaysOff.
Set a team's days off for an iteration
:param :class:`<TeamSettingsDaysOffPatch> <azure.devops.v5_1.work.models.TeamSettingsDaysOffPatch>` days_off_patch: Team's days off patch containting a list of start and end dates
:param :class:`<TeamContext> <azure.devops.v5_1.work.models.TeamContext>` team_context: The team context for the operation
:param str iteration_id: ID of the iteration
:rtype: :class:`<TeamSettingsDaysOff> <azure.devops.v5_1.work.models.TeamSettingsDaysOff>` | [
"UpdateTeamDaysOff",
".",
"Set",
"a",
"team",
"s",
"days",
"off",
"for",
"an",
"iteration",
":",
"param",
":",
"class",
":",
"<TeamSettingsDaysOffPatch",
">",
"<azure",
".",
"devops",
".",
"v5_1",
".",
"work",
".",
"models",
".",
"TeamSettingsDaysOffPatch",
... | def update_team_days_off(self, days_off_patch, team_context, iteration_id):
"""UpdateTeamDaysOff.
Set a team's days off for an iteration
:param :class:`<TeamSettingsDaysOffPatch> <azure.devops.v5_1.work.models.TeamSettingsDaysOffPatch>` days_off_patch: Team's days off patch containting a list of start and end dates
:param :class:`<TeamContext> <azure.devops.v5_1.work.models.TeamContext>` team_context: The team context for the operation
:param str iteration_id: ID of the iteration
:rtype: :class:`<TeamSettingsDaysOff> <azure.devops.v5_1.work.models.TeamSettingsDaysOff>`
"""
project = None
team = None
if team_context is not None:
if team_context.project_id:
project = team_context.project_id
else:
project = team_context.project
if team_context.team_id:
team = team_context.team_id
else:
team = team_context.team
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'string')
if team is not None:
route_values['team'] = self._serialize.url('team', team, 'string')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'str')
content = self._serialize.body(days_off_patch, 'TeamSettingsDaysOffPatch')
response = self._send(http_method='PATCH',
location_id='2d4faa2e-9150-4cbf-a47a-932b1b4a0773',
version='5.1',
route_values=route_values,
content=content)
return self._deserialize('TeamSettingsDaysOff', response) | [
"def",
"update_team_days_off",
"(",
"self",
",",
"days_off_patch",
",",
"team_context",
",",
"iteration_id",
")",
":",
"project",
"=",
"None",
"team",
"=",
"None",
"if",
"team_context",
"is",
"not",
"None",
":",
"if",
"team_context",
".",
"project_id",
":",
... | https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/released/work/work_client.py#L973-L1006 | |
Logan1x/Python-Scripts | e611dae0c86af21aad2bf11100bcc0448aa16fd0 | bin/memedensity.py | python | _execute_script | (email, password, count) | return driver_img_list | [] | def _execute_script(email, password, count):
print("\nLoading..\nCheck out today's xkcd comic till then : %s \n\n" % (_xkcd()))
driver = webdriver.PhantomJS()
driver.get('https://www.facebook.com')
email_ID = driver.find_element_by_id('email')
pass_ID = driver.find_element_by_id('pass')
email_ID.send_keys(email)
pass_ID.send_keys(password)
pass_ID.send_keys(Keys.ENTER)
sleep(5)
for i in range(0, count):
driver.execute_script(
"window.scrollBy(0, document.body.scrollHeight);")
sleep(1)
sleep(5)
driver_tags = driver.execute_script(
'return document.getElementsByClassName("scaledImageFitWidth img")')
driver_img_list = {
'src': [x.get_attribute('src') for x in driver_tags],
'alt': [x.get_attribute('alt') for x in driver_tags],
}
driver.quit()
return driver_img_list | [
"def",
"_execute_script",
"(",
"email",
",",
"password",
",",
"count",
")",
":",
"print",
"(",
"\"\\nLoading..\\nCheck out today's xkcd comic till then : %s \\n\\n\"",
"%",
"(",
"_xkcd",
"(",
")",
")",
")",
"driver",
"=",
"webdriver",
".",
"PhantomJS",
"(",
")",
... | https://github.com/Logan1x/Python-Scripts/blob/e611dae0c86af21aad2bf11100bcc0448aa16fd0/bin/memedensity.py#L49-L81 | |||
vpelletier/python-libusb1 | 86ad8ab73f7442874de71c1f9f824724d21da92b | usb1/__init__.py | python | hasCapability | (capability) | return libusb1.libusb_has_capability(capability) | Tests feature presence.
capability should be one of:
CAP_HAS_CAPABILITY
CAP_HAS_HOTPLUG
CAP_HAS_HID_ACCESS
CAP_SUPPORTS_DETACH_KERNEL_DRIVER
Calls loadLibrary. | Tests feature presence. | [
"Tests",
"feature",
"presence",
"."
] | def hasCapability(capability):
"""
Tests feature presence.
capability should be one of:
CAP_HAS_CAPABILITY
CAP_HAS_HOTPLUG
CAP_HAS_HID_ACCESS
CAP_SUPPORTS_DETACH_KERNEL_DRIVER
Calls loadLibrary.
"""
loadLibrary()
return libusb1.libusb_has_capability(capability) | [
"def",
"hasCapability",
"(",
"capability",
")",
":",
"loadLibrary",
"(",
")",
"return",
"libusb1",
".",
"libusb_has_capability",
"(",
"capability",
")"
] | https://github.com/vpelletier/python-libusb1/blob/86ad8ab73f7442874de71c1f9f824724d21da92b/usb1/__init__.py#L2677-L2690 | |
kozec/syncthing-gtk | 01eeeb9ed485232e145bf39d90142832e1c9751e | syncthing_gtk/app.py | python | App.parse_local_options | (self, is_option) | Test for expected options using specified method | Test for expected options using specified method | [
"Test",
"for",
"expected",
"options",
"using",
"specified",
"method"
] | def parse_local_options(self, is_option):
""" Test for expected options using specified method """
set_logging_level(is_option("verbose"), is_option("debug") )
if is_option("header"): self.use_headerbar = False
if is_option("window"): self.hide_window = False
if is_option("minimized"): self.hide_window = True
if is_option("dump"): self.dump_daemon_output = True
if is_option("no-status-icon"): self.show_status_icon = False
if is_option("wizard"):
self.exit_after_wizard = True
self.show_wizard()
elif is_option("about"):
from syncthing_gtk.aboutdialog import AboutDialog
ad = AboutDialog(self, self.gladepath, self.iconpath)
ad.run([])
sys.exit(0) | [
"def",
"parse_local_options",
"(",
"self",
",",
"is_option",
")",
":",
"set_logging_level",
"(",
"is_option",
"(",
"\"verbose\"",
")",
",",
"is_option",
"(",
"\"debug\"",
")",
")",
"if",
"is_option",
"(",
"\"header\"",
")",
":",
"self",
".",
"use_headerbar",
... | https://github.com/kozec/syncthing-gtk/blob/01eeeb9ed485232e145bf39d90142832e1c9751e/syncthing_gtk/app.py#L175-L190 | ||
realpython/book2-exercises | cde325eac8e6d8cff2316601c2e5b36bb46af7d0 | web2py/venv/lib/python2.7/site-packages/pip/index.py | python | PackageFinder._get_pages | (self, locations, project_name) | Yields (page, page_url) from the given locations, skipping
locations that have errors. | Yields (page, page_url) from the given locations, skipping
locations that have errors. | [
"Yields",
"(",
"page",
"page_url",
")",
"from",
"the",
"given",
"locations",
"skipping",
"locations",
"that",
"have",
"errors",
"."
] | def _get_pages(self, locations, project_name):
"""
Yields (page, page_url) from the given locations, skipping
locations that have errors.
"""
seen = set()
for location in locations:
if location in seen:
continue
seen.add(location)
page = self._get_page(location)
if page is None:
continue
yield page | [
"def",
"_get_pages",
"(",
"self",
",",
"locations",
",",
"project_name",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"location",
"in",
"locations",
":",
"if",
"location",
"in",
"seen",
":",
"continue",
"seen",
".",
"add",
"(",
"location",
")",
"page... | https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/site-packages/pip/index.py#L557-L572 | ||
hzlzh/AlfredWorkflow.com | 7055f14f6922c80ea5943839eb0caff11ae57255 | Sources/Workflows/ONE「一个」/workflow/workflow.py | python | Settings._load | (self) | Load cached settings from JSON file `self._filepath` | Load cached settings from JSON file `self._filepath` | [
"Load",
"cached",
"settings",
"from",
"JSON",
"file",
"self",
".",
"_filepath"
] | def _load(self):
"""Load cached settings from JSON file `self._filepath`"""
self._nosave = True
d = {}
with open(self._filepath, 'rb') as file_obj:
for key, value in json.load(file_obj, encoding='utf-8').items():
d[key] = value
self.update(d)
self._original = deepcopy(d)
self._nosave = False | [
"def",
"_load",
"(",
"self",
")",
":",
"self",
".",
"_nosave",
"=",
"True",
"d",
"=",
"{",
"}",
"with",
"open",
"(",
"self",
".",
"_filepath",
",",
"'rb'",
")",
"as",
"file_obj",
":",
"for",
"key",
",",
"value",
"in",
"json",
".",
"load",
"(",
... | https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/ONE「一个」/workflow/workflow.py#L980-L990 | ||
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/GmailSingleUser/Integrations/GmailSingleUser/GmailSingleUser.py | python | Client.template_params | (self, paramsStr) | Translate the template params if they exist from the context | Translate the template params if they exist from the context | [
"Translate",
"the",
"template",
"params",
"if",
"they",
"exist",
"from",
"the",
"context"
] | def template_params(self, paramsStr):
"""
Translate the template params if they exist from the context
"""
actualParams = {}
if paramsStr:
try:
params = json.loads(paramsStr)
except ValueError as e:
return_error('Unable to parse templateParams: {}'.format(str(e)))
# Build a simple key/value
for p in params:
if params[p].get('value'):
actualParams[p] = params[p]['value']
elif params[p].get('key'):
actualParams[p] = demisto.dt(demisto.context(), params[p]['key'])
return actualParams
else:
return None | [
"def",
"template_params",
"(",
"self",
",",
"paramsStr",
")",
":",
"actualParams",
"=",
"{",
"}",
"if",
"paramsStr",
":",
"try",
":",
"params",
"=",
"json",
".",
"loads",
"(",
"paramsStr",
")",
"except",
"ValueError",
"as",
"e",
":",
"return_error",
"(",... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/GmailSingleUser/Integrations/GmailSingleUser/GmailSingleUser.py#L591-L614 | ||
007gzs/dingtalk-sdk | 7979da2e259fdbc571728cae2425a04dbc65850a | dingtalk/client/api/taobao.py | python | TbTanx.taobao_tanx_qualification_add | (
self,
member_id,
token,
sign_time,
qualifications=None
) | return self._top_request(
"taobao.tanx.qualification.add",
{
"member_id": member_id,
"token": token,
"sign_time": sign_time,
"qualifications": qualifications
}
) | 提交资质接口
dsp客户提交客户资质和行业资质
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=24264
:param member_id: dsp用户memberId
:param token: dsp验证的token
:param sign_time: 签名时间,1970年到现在的秒
:param qualifications: dsp客户新增资质dto | 提交资质接口
dsp客户提交客户资质和行业资质
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=24264 | [
"提交资质接口",
"dsp客户提交客户资质和行业资质",
"文档地址:https",
":",
"//",
"open",
"-",
"doc",
".",
"dingtalk",
".",
"com",
"/",
"docs",
"/",
"api",
".",
"htm?apiId",
"=",
"24264"
] | def taobao_tanx_qualification_add(
self,
member_id,
token,
sign_time,
qualifications=None
):
"""
提交资质接口
dsp客户提交客户资质和行业资质
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=24264
:param member_id: dsp用户memberId
:param token: dsp验证的token
:param sign_time: 签名时间,1970年到现在的秒
:param qualifications: dsp客户新增资质dto
"""
return self._top_request(
"taobao.tanx.qualification.add",
{
"member_id": member_id,
"token": token,
"sign_time": sign_time,
"qualifications": qualifications
}
) | [
"def",
"taobao_tanx_qualification_add",
"(",
"self",
",",
"member_id",
",",
"token",
",",
"sign_time",
",",
"qualifications",
"=",
"None",
")",
":",
"return",
"self",
".",
"_top_request",
"(",
"\"taobao.tanx.qualification.add\"",
",",
"{",
"\"member_id\"",
":",
"m... | https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L40453-L40478 | |
datamachine/twx.botapi | 4807da2082704876c0de4826b347a6347d84372d | twx/botapi/botapi.py | python | get_chat_members_count | (chat_id, **kwargs) | return TelegramBotRPCRequest('getChatMembersCount', params=params, on_result=lambda result: result, **kwargs) | Use this method to get the number of members in a chat.
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
:param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest`
:type chat_id: int or str
:returns: Returns count on success.
:rtype: int | Use this method to get the number of members in a chat. | [
"Use",
"this",
"method",
"to",
"get",
"the",
"number",
"of",
"members",
"in",
"a",
"chat",
"."
] | def get_chat_members_count(chat_id, **kwargs):
"""
Use this method to get the number of members in a chat.
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
:param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest`
:type chat_id: int or str
:returns: Returns count on success.
:rtype: int
"""
# required args
params = dict(
chat_id=chat_id,
)
return TelegramBotRPCRequest('getChatMembersCount', params=params, on_result=lambda result: result, **kwargs) | [
"def",
"get_chat_members_count",
"(",
"chat_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# required args",
"params",
"=",
"dict",
"(",
"chat_id",
"=",
"chat_id",
",",
")",
"return",
"TelegramBotRPCRequest",
"(",
"'getChatMembersCount'",
",",
"params",
"=",
"params",... | https://github.com/datamachine/twx.botapi/blob/4807da2082704876c0de4826b347a6347d84372d/twx/botapi/botapi.py#L3559-L3577 | |
IFGHou/wapiti | 91242a8ad293a8ee54ab6e62732ff4b9d770772c | wapitiCore/report/jsonreportgenerator.py | python | JSONReportGenerator.generateReport | (self, filename) | Generate a JSON report of the vulnerabilities and anomalies which have
been previously logged with the log* methods. | Generate a JSON report of the vulnerabilities and anomalies which have
been previously logged with the log* methods. | [
"Generate",
"a",
"JSON",
"report",
"of",
"the",
"vulnerabilities",
"and",
"anomalies",
"which",
"have",
"been",
"previously",
"logged",
"with",
"the",
"log",
"*",
"methods",
"."
] | def generateReport(self, filename):
"""
Generate a JSON report of the vulnerabilities and anomalies which have
been previously logged with the log* methods.
"""
report_dict = {"classifications": self.__flawTypes,
"vulnerabilities": self.__vulns,
"anomalies": self.__anomalies,
"infos": self.__infos
}
f = open(filename, "w")
try:
json.dump(report_dict, f, indent=2)
finally:
f.close() | [
"def",
"generateReport",
"(",
"self",
",",
"filename",
")",
":",
"report_dict",
"=",
"{",
"\"classifications\"",
":",
"self",
".",
"__flawTypes",
",",
"\"vulnerabilities\"",
":",
"self",
".",
"__vulns",
",",
"\"anomalies\"",
":",
"self",
".",
"__anomalies",
",... | https://github.com/IFGHou/wapiti/blob/91242a8ad293a8ee54ab6e62732ff4b9d770772c/wapitiCore/report/jsonreportgenerator.py#L53-L67 | ||
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-35/fabmetheus_utilities/geometry/geometry_utilities/evaluate.py | python | ModuleXMLElement.processElse | ( self, xmlElement) | Process the else statement. | Process the else statement. | [
"Process",
"the",
"else",
"statement",
"."
] | def processElse( self, xmlElement):
"Process the else statement."
if self.elseElement != None:
self.pluginModule.processElse( self.elseElement) | [
"def",
"processElse",
"(",
"self",
",",
"xmlElement",
")",
":",
"if",
"self",
".",
"elseElement",
"!=",
"None",
":",
"self",
".",
"pluginModule",
".",
"processElse",
"(",
"self",
".",
"elseElement",
")"
] | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/geometry/geometry_utilities/evaluate.py#L1809-L1812 | ||
caronc/apprise | e5945e0be1b7051ab4890bf78949058304f2d641 | apprise/plugins/NotifyTwitter.py | python | NotifyTwitter._whoami | (self, lazy=True) | return results | Looks details of current authenticated user | Looks details of current authenticated user | [
"Looks",
"details",
"of",
"current",
"authenticated",
"user"
] | def _whoami(self, lazy=True):
"""
Looks details of current authenticated user
"""
# Prepare a whoami key; this is to prevent conflict with other
# NotifyTwitter declarations that may or may not use a different
# set of authentication keys
whoami_key = '{}{}{}{}'.format(
self.ckey, self.csecret, self.akey, self.asecret)
if lazy and hasattr(NotifyTwitter, '_whoami_cache') \
and whoami_key in getattr(NotifyTwitter, '_whoami_cache'):
# Use cached response
return getattr(NotifyTwitter, '_whoami_cache')[whoami_key]
# Contains a mapping of screen_name to id
results = {}
# Send Twitter DM
postokay, response = self._fetch(
self.twitter_whoami,
method='GET',
json=False,
)
if postokay:
try:
results[response['screen_name']] = response['id']
if lazy:
# Cache our response for future references
if not hasattr(NotifyTwitter, '_whoami_cache'):
setattr(
NotifyTwitter, '_whoami_cache',
{whoami_key: results})
else:
getattr(NotifyTwitter, '_whoami_cache')\
.update({whoami_key: results})
# Update our user cache as well
if not hasattr(NotifyTwitter, '_user_cache'):
setattr(NotifyTwitter, '_user_cache', results)
else:
getattr(NotifyTwitter, '_user_cache').update(results)
except (TypeError, KeyError):
pass
return results | [
"def",
"_whoami",
"(",
"self",
",",
"lazy",
"=",
"True",
")",
":",
"# Prepare a whoami key; this is to prevent conflict with other",
"# NotifyTwitter declarations that may or may not use a different",
"# set of authentication keys",
"whoami_key",
"=",
"'{}{}{}{}'",
".",
"format",
... | https://github.com/caronc/apprise/blob/e5945e0be1b7051ab4890bf78949058304f2d641/apprise/plugins/NotifyTwitter.py#L342-L392 | |
khalim19/gimp-plugin-export-layers | b37255f2957ad322f4d332689052351cdea6e563 | export_layers/pygimplib/_lib/future/libfuturize/fixer_util.py | python | touch_import_top | (package, name_to_import, node) | Works like `does_tree_import` but adds an import statement at the
top if it was not imported (but below any __future__ imports) and below any
comments such as shebang lines).
Based on lib2to3.fixer_util.touch_import()
Calling this multiple times adds the imports in reverse order.
Also adds "standard_library.install_aliases()" after "from future import
standard_library". This should probably be factored into another function. | Works like `does_tree_import` but adds an import statement at the
top if it was not imported (but below any __future__ imports) and below any
comments such as shebang lines). | [
"Works",
"like",
"does_tree_import",
"but",
"adds",
"an",
"import",
"statement",
"at",
"the",
"top",
"if",
"it",
"was",
"not",
"imported",
"(",
"but",
"below",
"any",
"__future__",
"imports",
")",
"and",
"below",
"any",
"comments",
"such",
"as",
"shebang",
... | def touch_import_top(package, name_to_import, node):
"""Works like `does_tree_import` but adds an import statement at the
top if it was not imported (but below any __future__ imports) and below any
comments such as shebang lines).
Based on lib2to3.fixer_util.touch_import()
Calling this multiple times adds the imports in reverse order.
Also adds "standard_library.install_aliases()" after "from future import
standard_library". This should probably be factored into another function.
"""
root = find_root(node)
if does_tree_import(package, name_to_import, root):
return
# Ideally, we would look for whether futurize --all-imports has been run,
# as indicated by the presence of ``from builtins import (ascii, ...,
# zip)`` -- and, if it has, we wouldn't import the name again.
# Look for __future__ imports and insert below them
found = False
for name in ['absolute_import', 'division', 'print_function',
'unicode_literals']:
if does_tree_import('__future__', name, root):
found = True
break
if found:
# At least one __future__ import. We want to loop until we've seen them
# all.
start, end = None, None
for idx, node in enumerate(root.children):
if check_future_import(node):
start = idx
# Start looping
idx2 = start
while node:
node = node.next_sibling
idx2 += 1
if not check_future_import(node):
end = idx2
break
break
assert start is not None
assert end is not None
insert_pos = end
else:
# No __future__ imports.
# We look for a docstring and insert the new node below that. If no docstring
# exists, just insert the node at the top.
for idx, node in enumerate(root.children):
if node.type != syms.simple_stmt:
break
if not is_docstring(node):
# This is the usual case.
break
insert_pos = idx
if package is None:
import_ = Node(syms.import_name, [
Leaf(token.NAME, u"import"),
Leaf(token.NAME, name_to_import, prefix=u" ")
])
else:
import_ = FromImport(package, [Leaf(token.NAME, name_to_import, prefix=u" ")])
if name_to_import == u'standard_library':
# Add:
# standard_library.install_aliases()
# after:
# from future import standard_library
install_hooks = Node(syms.simple_stmt,
[Node(syms.power,
[Leaf(token.NAME, u'standard_library'),
Node(syms.trailer, [Leaf(token.DOT, u'.'),
Leaf(token.NAME, u'install_aliases')]),
Node(syms.trailer, [Leaf(token.LPAR, u'('),
Leaf(token.RPAR, u')')])
])
]
)
children_hooks = [install_hooks, Newline()]
else:
children_hooks = []
# FromImport(package, [Leaf(token.NAME, name_to_import, prefix=u" ")])
children_import = [import_, Newline()]
old_prefix = root.children[insert_pos].prefix
root.children[insert_pos].prefix = u''
root.insert_child(insert_pos, Node(syms.simple_stmt, children_import, prefix=old_prefix))
if len(children_hooks) > 0:
root.insert_child(insert_pos + 1, Node(syms.simple_stmt, children_hooks)) | [
"def",
"touch_import_top",
"(",
"package",
",",
"name_to_import",
",",
"node",
")",
":",
"root",
"=",
"find_root",
"(",
"node",
")",
"if",
"does_tree_import",
"(",
"package",
",",
"name_to_import",
",",
"root",
")",
":",
"return",
"# Ideally, we would look for w... | https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/_lib/future/libfuturize/fixer_util.py#L333-L426 | ||
wwqgtxx/wwqLyParse | 33136508e52821babd9294fdecffbdf02d73a6fc | wwqLyParse/lib/flask_lib/jinja2/compiler.py | python | CodeGenerator.visit_Extends | (self, node, frame) | Calls the extender. | Calls the extender. | [
"Calls",
"the",
"extender",
"."
] | def visit_Extends(self, node, frame):
"""Calls the extender."""
if not frame.toplevel:
self.fail('cannot use extend from a non top-level scope',
node.lineno)
# if the number of extends statements in general is zero so
# far, we don't have to add a check if something extended
# the template before this one.
if self.extends_so_far > 0:
# if we have a known extends we just add a template runtime
# error into the generated code. We could catch that at compile
# time too, but i welcome it not to confuse users by throwing the
# same error at different times just "because we can".
if not self.has_known_extends:
self.writeline('if parent_template is not None:')
self.indent()
self.writeline('raise TemplateRuntimeError(%r)' %
'extended multiple times')
# if we have a known extends already we don't need that code here
# as we know that the template execution will end here.
if self.has_known_extends:
raise CompilerExit()
else:
self.outdent()
self.writeline('parent_template = environment.get_template(', node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
self.writeline('for name, parent_block in parent_template.'
'blocks.%s():' % dict_item_iter)
self.indent()
self.writeline('context.blocks.setdefault(name, []).'
'append(parent_block)')
self.outdent()
# if this extends statement was in the root level we can take
# advantage of that information and simplify the generated code
# in the top level from this point onwards
if frame.rootlevel:
self.has_known_extends = True
# and now we have one more
self.extends_so_far += 1 | [
"def",
"visit_Extends",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"if",
"not",
"frame",
".",
"toplevel",
":",
"self",
".",
"fail",
"(",
"'cannot use extend from a non top-level scope'",
",",
"node",
".",
"lineno",
")",
"# if the number of extends statement... | https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/flask_lib/jinja2/compiler.py#L843-L888 | ||
ArduPilot/pymavlink | 9d6ea618e8d0622bee95fa902b6251882e225afb | mavutil.py | python | mavfile.param_fetch_one | (self, name) | initiate fetch of one parameter | initiate fetch of one parameter | [
"initiate",
"fetch",
"of",
"one",
"parameter"
] | def param_fetch_one(self, name):
'''initiate fetch of one parameter'''
try:
idx = int(name)
self.mav.param_request_read_send(self.target_system, self.target_component, b"", idx)
except Exception:
if sys.version_info.major >= 3 and not isinstance(name, bytes):
name = bytes(name,'ascii')
self.mav.param_request_read_send(self.target_system, self.target_component, name, -1) | [
"def",
"param_fetch_one",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"idx",
"=",
"int",
"(",
"name",
")",
"self",
".",
"mav",
".",
"param_request_read_send",
"(",
"self",
".",
"target_system",
",",
"self",
".",
"target_component",
",",
"b\"\"",
",",... | https://github.com/ArduPilot/pymavlink/blob/9d6ea618e8d0622bee95fa902b6251882e225afb/mavutil.py#L530-L538 | ||
home-assistant-libs/pychromecast | d7acb9f5ae2c0daa797d78da1a1e8090b4181d21 | pychromecast/controllers/media.py | python | MediaStatusListener.new_media_status | (self, status: MediaStatus) | Updated media status. | Updated media status. | [
"Updated",
"media",
"status",
"."
] | def new_media_status(self, status: MediaStatus):
"""Updated media status.""" | [
"def",
"new_media_status",
"(",
"self",
",",
"status",
":",
"MediaStatus",
")",
":"
] | https://github.com/home-assistant-libs/pychromecast/blob/d7acb9f5ae2c0daa797d78da1a1e8090b4181d21/pychromecast/controllers/media.py#L317-L318 | ||
HKUST-KnowComp/DeepGraphCNNforTexts | bf0bb5441ecea58c5556a9969064bec074325c7a | TextCNN/p7_TextCNN_model.py | python | TextCNN.__init__ | (self, filter_sizes,num_filters,num_classes, learning_rate, batch_size, decay_steps, decay_rate,sequence_length,vocab_size,embed_size,
is_training,initializer=tf.random_normal_initializer(stddev=0.1),multi_label_flag=False,clip_gradients=5.0,decay_rate_big=0.50) | init all hyperparameter here | init all hyperparameter here | [
"init",
"all",
"hyperparameter",
"here"
] | def __init__(self, filter_sizes,num_filters,num_classes, learning_rate, batch_size, decay_steps, decay_rate,sequence_length,vocab_size,embed_size,
is_training,initializer=tf.random_normal_initializer(stddev=0.1),multi_label_flag=False,clip_gradients=5.0,decay_rate_big=0.50):
"""init all hyperparameter here"""
# set hyperparamter
self.num_classes = num_classes
self.batch_size = batch_size
self.sequence_length=sequence_length
self.vocab_size=vocab_size
self.embed_size=embed_size
self.is_training=is_training
self.learning_rate = tf.Variable(learning_rate, trainable=False, name="learning_rate")#ADD learning_rate
self.learning_rate_decay_half_op = tf.assign(self.learning_rate, self.learning_rate * decay_rate_big)
self.filter_sizes=filter_sizes # it is a list of int. e.g. [3,4,5]
self.num_filters=num_filters
self.initializer=initializer
self.num_filters_total=self.num_filters * len(filter_sizes) #how many filters totally.
self.multi_label_flag=multi_label_flag
self.clip_gradients = clip_gradients
# add placeholder (X,label)
self.input_x = tf.placeholder(tf.int32, [None, self.sequence_length], name="input_x") # X
#self.input_y = tf.placeholder(tf.int32, [None,],name="input_y") # y:[None,num_classes]
self.input_y_multilabel = tf.placeholder(tf.float32,[None,self.num_classes], name="input_y_multilabel") # y:[None,num_classes]. this is for multi-label classification only.
self.dropout_keep_prob=tf.placeholder(tf.float32,name="dropout_keep_prob")
self.iter = tf.placeholder(tf.int32) #training iteration
self.tst=tf.placeholder(tf.bool)
self.global_step = tf.Variable(0, trainable=False, name="Global_Step")
self.epoch_step=tf.Variable(0,trainable=False,name="Epoch_Step")
self.epoch_increment=tf.assign(self.epoch_step,tf.add(self.epoch_step,tf.constant(1)))
self.b1 = tf.Variable(tf.ones([self.num_filters]) / 10)
self.b2 = tf.Variable(tf.ones([self.num_filters]) / 10)
self.decay_steps, self.decay_rate = decay_steps, decay_rate
self.instantiate_weights()
self.logits = self.inference() #[None, self.label_size]. main computation graph is here.
self.possibility=tf.nn.sigmoid(self.logits)
if not is_training:
return
if multi_label_flag:print("going to use multi label loss.");self.loss_val = self.loss_multilabel()
else:print("going to use single label loss.");self.loss_val = self.loss()
self.train_op = self.train()
if not self.multi_label_flag:
self.predictions = tf.argmax(self.logits, 1, name="predictions") # shape:[None,]
print("self.predictions:", self.predictions)
correct_prediction = tf.equal(tf.cast(self.predictions,tf.int32), self.input_y) #tf.argmax(self.logits, 1)-->[batch_size]
self.accuracy =tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name="Accuracy") | [
"def",
"__init__",
"(",
"self",
",",
"filter_sizes",
",",
"num_filters",
",",
"num_classes",
",",
"learning_rate",
",",
"batch_size",
",",
"decay_steps",
",",
"decay_rate",
",",
"sequence_length",
",",
"vocab_size",
",",
"embed_size",
",",
"is_training",
",",
"i... | https://github.com/HKUST-KnowComp/DeepGraphCNNforTexts/blob/bf0bb5441ecea58c5556a9969064bec074325c7a/TextCNN/p7_TextCNN_model.py#L8-L54 | ||
rowliny/DiffHelper | ab3a96f58f9579d0023aed9ebd785f4edf26f8af | Tool/SitePackages/nltk/sem/linearlogic.py | python | BindingDict.__add__ | (self, other) | :param other: ``BindingDict`` The dict with which to combine self
:return: ``BindingDict`` A new dict containing all the elements of both parameters
:raise VariableBindingException: If the parameter dictionaries are not consistent with each other | :param other: ``BindingDict`` The dict with which to combine self
:return: ``BindingDict`` A new dict containing all the elements of both parameters
:raise VariableBindingException: If the parameter dictionaries are not consistent with each other | [
":",
"param",
"other",
":",
"BindingDict",
"The",
"dict",
"with",
"which",
"to",
"combine",
"self",
":",
"return",
":",
"BindingDict",
"A",
"new",
"dict",
"containing",
"all",
"the",
"elements",
"of",
"both",
"parameters",
":",
"raise",
"VariableBindingExcepti... | def __add__(self, other):
"""
:param other: ``BindingDict`` The dict with which to combine self
:return: ``BindingDict`` A new dict containing all the elements of both parameters
:raise VariableBindingException: If the parameter dictionaries are not consistent with each other
"""
try:
combined = BindingDict()
for v in self.d:
combined[v] = self.d[v]
for v in other.d:
combined[v] = other.d[v]
return combined
except VariableBindingException as e:
raise VariableBindingException(
"Attempting to add two contradicting"
" VariableBindingsLists: %s, %s" % (self, other)
) from e | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"try",
":",
"combined",
"=",
"BindingDict",
"(",
")",
"for",
"v",
"in",
"self",
".",
"d",
":",
"combined",
"[",
"v",
"]",
"=",
"self",
".",
"d",
"[",
"v",
"]",
"for",
"v",
"in",
"other",
... | https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/sem/linearlogic.py#L421-L438 | ||
polyaxon/polyaxon | e28d82051c2b61a84d06ce4d2388a40fc8565469 | src/core/polyaxon/client/run.py | python | RunClient.start | (self) | Sets the current run to `running` status.
<blockquote class="info">
N.B. If you are executing a managed run, you don't need to call this method manually.
This method is only useful for manual runs outside of Polyaxon.
</blockquote> | Sets the current run to `running` status. | [
"Sets",
"the",
"current",
"run",
"to",
"running",
"status",
"."
] | def start(self):
"""Sets the current run to `running` status.
<blockquote class="info">
N.B. If you are executing a managed run, you don't need to call this method manually.
This method is only useful for manual runs outside of Polyaxon.
</blockquote>
"""
self.log_status(polyaxon_sdk.V1Statuses.RUNNING, message="Operation is running") | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"log_status",
"(",
"polyaxon_sdk",
".",
"V1Statuses",
".",
"RUNNING",
",",
"message",
"=",
"\"Operation is running\"",
")"
] | https://github.com/polyaxon/polyaxon/blob/e28d82051c2b61a84d06ce4d2388a40fc8565469/src/core/polyaxon/client/run.py#L1310-L1318 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_clusterrole.py | python | Rule.attribute_restrictions | (self) | return self.__attribute_restrictions | property for attribute_restrictions | property for attribute_restrictions | [
"property",
"for",
"attribute_restrictions"
] | def attribute_restrictions(self):
'''property for attribute_restrictions'''
return self.__attribute_restrictions | [
"def",
"attribute_restrictions",
"(",
"self",
")",
":",
"return",
"self",
".",
"__attribute_restrictions"
] | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_clusterrole.py#L1527-L1529 | |
Blizzard/heroprotocol | 3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c | heroprotocol/versions/protocol71449.py | python | decode_replay_header | (contents) | return decoder.instance(replay_header_typeid) | Decodes and return the replay header from the contents byte string. | Decodes and return the replay header from the contents byte string. | [
"Decodes",
"and",
"return",
"the",
"replay",
"header",
"from",
"the",
"contents",
"byte",
"string",
"."
] | def decode_replay_header(contents):
"""Decodes and return the replay header from the contents byte string."""
decoder = VersionedDecoder(contents, typeinfos)
return decoder.instance(replay_header_typeid) | [
"def",
"decode_replay_header",
"(",
"contents",
")",
":",
"decoder",
"=",
"VersionedDecoder",
"(",
"contents",
",",
"typeinfos",
")",
"return",
"decoder",
".",
"instance",
"(",
"replay_header_typeid",
")"
] | https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol71449.py#L434-L437 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/_pydecimal.py | python | Context._shallow_copy | (self) | return nc | Returns a shallow copy from self. | Returns a shallow copy from self. | [
"Returns",
"a",
"shallow",
"copy",
"from",
"self",
"."
] | def _shallow_copy(self):
"""Returns a shallow copy from self."""
nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
self.capitals, self.clamp, self.flags, self.traps,
self._ignored_flags)
return nc | [
"def",
"_shallow_copy",
"(",
"self",
")",
":",
"nc",
"=",
"Context",
"(",
"self",
".",
"prec",
",",
"self",
".",
"rounding",
",",
"self",
".",
"Emin",
",",
"self",
".",
"Emax",
",",
"self",
".",
"capitals",
",",
"self",
".",
"clamp",
",",
"self",
... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/_pydecimal.py#L4008-L4013 | |
qiucheng025/zao- | 3a5edf3607b3a523f95746bc69b688090c76d89a | lib/gui/display_page.py | python | DisplayPage.add_options_info | (self) | Add the info bar | Add the info bar | [
"Add",
"the",
"info",
"bar"
] | def add_options_info(self):
""" Add the info bar """
logger.debug("Adding options info")
lblinfo = ttk.Label(self.optsframe,
textvariable=self.vars["info"],
anchor=tk.W,
width=70)
lblinfo.pack(side=tk.LEFT, padx=5, pady=5, anchor=tk.W) | [
"def",
"add_options_info",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Adding options info\"",
")",
"lblinfo",
"=",
"ttk",
".",
"Label",
"(",
"self",
".",
"optsframe",
",",
"textvariable",
"=",
"self",
".",
"vars",
"[",
"\"info\"",
"]",
",",
"... | https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/lib/gui/display_page.py#L65-L72 | ||
univ-of-utah-marriott-library-apple/firmware_password_manager | 198694a650acd3fa61b85d25dd61e83782bb25d5 | firmware_password_manager.py | python | FWPM_Object.hash_current_state | (self) | This should not be blank. | This should not be blank. | [
"This",
"should",
"not",
"be",
"blank",
"."
] | def hash_current_state(self):
"""
This should not be blank.
"""
if self.logger:
self.logger.info("%s: activated" % inspect.stack()[0][3])
existing_keyfile_hash = None
if self.logger:
self.logger.info("Checking existing hash.")
try:
existing_keyfile_hash_raw = subprocess.check_output(["/usr/sbin/nvram", "-p"]).decode('utf-8')
existing_keyfile_hash_raw = existing_keyfile_hash_raw.split('\n')
for item in existing_keyfile_hash_raw:
if "fwpw-hash" in item:
existing_keyfile_hash = item
else:
self.current_fwpm_hash = None
self.current_fwpm_hash = existing_keyfile_hash.split("\t")[1]
if self.args.testmode:
print("Existing hash: %s" % self.current_fwpm_hash)
except:
pass | [
"def",
"hash_current_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"%s: activated\"",
"%",
"inspect",
".",
"stack",
"(",
")",
"[",
"0",
"]",
"[",
"3",
"]",
")",
"existing_keyfile_hash",
"=",... | https://github.com/univ-of-utah-marriott-library-apple/firmware_password_manager/blob/198694a650acd3fa61b85d25dd61e83782bb25d5/firmware_password_manager.py#L251-L277 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py | python | MapperOption._generate_cache_key | (self, path) | return None | Used by the baked loader to see if this option can be cached.
A given MapperOption that returns a cache key must return a key
that uniquely identifies the complete state of this option, which
will match any other MapperOption that itself retains the identical
state. This includes path options, flags, etc.
If the MapperOption does not apply to the given path and would
not affect query results on such a path, it should return None.
if the MapperOption **does** apply to the give path, however cannot
produce a safe cache key, it should return False; this will cancel
caching of the result. An unsafe cache key is one that includes
an ad-hoc user object, typically an AliasedClass object. As these
are usually created per-query, they don't work as cache keys. | Used by the baked loader to see if this option can be cached. | [
"Used",
"by",
"the",
"baked",
"loader",
"to",
"see",
"if",
"this",
"option",
"can",
"be",
"cached",
"."
] | def _generate_cache_key(self, path):
"""Used by the baked loader to see if this option can be cached.
A given MapperOption that returns a cache key must return a key
that uniquely identifies the complete state of this option, which
will match any other MapperOption that itself retains the identical
state. This includes path options, flags, etc.
If the MapperOption does not apply to the given path and would
not affect query results on such a path, it should return None.
if the MapperOption **does** apply to the give path, however cannot
produce a safe cache key, it should return False; this will cancel
caching of the result. An unsafe cache key is one that includes
an ad-hoc user object, typically an AliasedClass object. As these
are usually created per-query, they don't work as cache keys.
"""
return None | [
"def",
"_generate_cache_key",
"(",
"self",
",",
"path",
")",
":",
"return",
"None"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py#L599-L619 | |
alonsovidales/facebook-programming-challenges | 8b61b09651889d81ed8cac9e8a2b98415897055f | secret-decoder/secret_decoder.py | python | SecretDecoder.resolve | (self) | return '\n'.join(decrypted) | This method launches the recursive serach of the correct combination and returns as string the text
decoded if possible, with the necessary format given by the specifications
@return str The text decoded and formatted | This method launches the recursive serach of the correct combination and returns as string the text
decoded if possible, with the necessary format given by the specifications | [
"This",
"method",
"launches",
"the",
"recursive",
"serach",
"of",
"the",
"correct",
"combination",
"and",
"returns",
"as",
"string",
"the",
"text",
"decoded",
"if",
"possible",
"with",
"the",
"necessary",
"format",
"given",
"by",
"the",
"specifications"
] | def resolve(self):
"""
This method launches the recursive serach of the correct combination and returns as string the text
decoded if possible, with the necessary format given by the specifications
@return str The text decoded and formatted
"""
decrypted = []
for line in self.__linesEncoded:
decrypted.append(self.__checkByDepp(line))
return '\n'.join(decrypted) | [
"def",
"resolve",
"(",
"self",
")",
":",
"decrypted",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"__linesEncoded",
":",
"decrypted",
".",
"append",
"(",
"self",
".",
"__checkByDepp",
"(",
"line",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"... | https://github.com/alonsovidales/facebook-programming-challenges/blob/8b61b09651889d81ed8cac9e8a2b98415897055f/secret-decoder/secret_decoder.py#L78-L89 | |
postgres/pgadmin4 | 374c5e952fa594d749fadf1f88076c1cba8c5f64 | web/pgadmin/browser/server_groups/servers/databases/schemas/tables/__init__.py | python | TableView.get_inherits | (self, gid, sid, did, scid, tid=None) | Returns:
This function will return list of tables available for inheritance
while creating new table | Returns:
This function will return list of tables available for inheritance
while creating new table | [
"Returns",
":",
"This",
"function",
"will",
"return",
"list",
"of",
"tables",
"available",
"for",
"inheritance",
"while",
"creating",
"new",
"table"
] | def get_inherits(self, gid, sid, did, scid, tid=None):
"""
Returns:
This function will return list of tables available for inheritance
while creating new table
"""
try:
res = []
SQL = render_template(
"/".join([self.table_template_path, 'get_inherits.sql']),
show_system_objects=self.blueprint.show_system_objects,
tid=tid,
scid=scid,
server_type=self.manager.server_type
)
status, rset = self.conn.execute_2darray(SQL)
if not status:
return internal_server_error(errormsg=res)
for row in rset['rows']:
res.append(
{'label': row['inherits'], 'value': row['inherits'],
'tid': row['oid']
}
)
return make_json_response(
data=res,
status=200
)
except Exception as e:
return internal_server_error(errormsg=str(e)) | [
"def",
"get_inherits",
"(",
"self",
",",
"gid",
",",
"sid",
",",
"did",
",",
"scid",
",",
"tid",
"=",
"None",
")",
":",
"try",
":",
"res",
"=",
"[",
"]",
"SQL",
"=",
"render_template",
"(",
"\"/\"",
".",
"join",
"(",
"[",
"self",
".",
"table_temp... | https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/__init__.py#L753-L783 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/Pillow-6.0.0-py3.7-macosx-10.9-x86_64.egg/PIL/ImageCms.py | python | getProfileCopyright | (profile) | (pyCMS) Gets the copyright for the given profile.
If profile isn't a valid CmsProfile object or filename to a profile,
a PyCMSError is raised.
If an error occurs while trying to obtain the copyright tag, a PyCMSError
is raised
Use this function to obtain the information stored in the profile's
copyright tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError: | (pyCMS) Gets the copyright for the given profile. | [
"(",
"pyCMS",
")",
"Gets",
"the",
"copyright",
"for",
"the",
"given",
"profile",
"."
] | def getProfileCopyright(profile):
"""
(pyCMS) Gets the copyright for the given profile.
If profile isn't a valid CmsProfile object or filename to a profile,
a PyCMSError is raised.
If an error occurs while trying to obtain the copyright tag, a PyCMSError
is raised
Use this function to obtain the information stored in the profile's
copyright tag.
:param profile: EITHER a valid CmsProfile object, OR a string of the
filename of an ICC profile.
:returns: A string containing the internal profile information stored in
an ICC tag.
:exception PyCMSError:
"""
try:
# add an extra newline to preserve pyCMS compatibility
if not isinstance(profile, ImageCmsProfile):
profile = ImageCmsProfile(profile)
return (profile.profile.copyright or "") + "\n"
except (AttributeError, IOError, TypeError, ValueError) as v:
raise PyCMSError(v) | [
"def",
"getProfileCopyright",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/Pillow-6.0.0-py3.7-macosx-10.9-x86_64.egg/PIL/ImageCms.py#L742-L767 | ||
mahmoud/boltons | 270e974975984f662f998c8f6eb0ebebd964de82 | boltons/mboxutils.py | python | mbox_readonlydir.flush | (self) | Write any pending changes to disk. This is called on mailbox
close and is usually not called explicitly.
.. note::
This deletes messages via truncation. Interruptions may
corrupt your mailbox. | Write any pending changes to disk. This is called on mailbox
close and is usually not called explicitly. | [
"Write",
"any",
"pending",
"changes",
"to",
"disk",
".",
"This",
"is",
"called",
"on",
"mailbox",
"close",
"and",
"is",
"usually",
"not",
"called",
"explicitly",
"."
] | def flush(self):
"""Write any pending changes to disk. This is called on mailbox
close and is usually not called explicitly.
.. note::
This deletes messages via truncation. Interruptions may
corrupt your mailbox.
"""
# Appending and basic assertions are the same as in mailbox.mbox.flush.
if not self._pending:
if self._pending_sync:
# Messages have only been added, so syncing the file
# is enough.
mailbox._sync_flush(self._file)
self._pending_sync = False
return
# In order to be writing anything out at all, self._toc must
# already have been generated (and presumably has been modified
# by adding or deleting an item).
assert self._toc is not None
# Check length of self._file; if it's changed, some other process
# has modified the mailbox since we scanned it.
self._file.seek(0, 2)
cur_len = self._file.tell()
if cur_len != self._file_length:
raise mailbox.ExternalClashError('Size of mailbox file changed '
'(expected %i, found %i)' %
(self._file_length, cur_len))
self._file.seek(0)
# Truncation logic begins here. Mostly the same except we
# can use tempfile because we're not doing rename(2).
with tempfile.TemporaryFile() as new_file:
new_toc = {}
self._pre_mailbox_hook(new_file)
for key in sorted(self._toc.keys()):
start, stop = self._toc[key]
self._file.seek(start)
self._pre_message_hook(new_file)
new_start = new_file.tell()
while True:
buffer = self._file.read(min(4096,
stop - self._file.tell()))
if buffer == '':
break
new_file.write(buffer)
new_toc[key] = (new_start, new_file.tell())
self._post_message_hook(new_file)
self._file_length = new_file.tell()
self._file.seek(0)
new_file.seek(0)
# Copy back our messages
if self._file_length <= self.maxmem:
self._file.write(new_file.read())
else:
while True:
buffer = new_file.read(4096)
if not buffer:
break
self._file.write(buffer)
# Delete the rest.
self._file.truncate()
# Same wrap up.
self._toc = new_toc
self._pending = False
self._pending_sync = False
if self._locked:
mailbox._lock_file(self._file, dotlock=False) | [
"def",
"flush",
"(",
"self",
")",
":",
"# Appending and basic assertions are the same as in mailbox.mbox.flush.",
"if",
"not",
"self",
".",
"_pending",
":",
"if",
"self",
".",
"_pending_sync",
":",
"# Messages have only been added, so syncing the file",
"# is enough.",
"mailb... | https://github.com/mahmoud/boltons/blob/270e974975984f662f998c8f6eb0ebebd964de82/boltons/mboxutils.py#L76-L152 | ||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py | python | _sample_without_replacement | (distribution, num_samples) | return indices | Categorical sampling without replacement is currently not implemented. The gumbel-max trick will do for now - see
https://github.com/tensorflow/tensorflow/issues/9260 for more info | Categorical sampling without replacement is currently not implemented. The gumbel-max trick will do for now - see
https://github.com/tensorflow/tensorflow/issues/9260 for more info | [
"Categorical",
"sampling",
"without",
"replacement",
"is",
"currently",
"not",
"implemented",
".",
"The",
"gumbel",
"-",
"max",
"trick",
"will",
"do",
"for",
"now",
"-",
"see",
"https",
":",
"//",
"github",
".",
"com",
"/",
"tensorflow",
"/",
"tensorflow",
... | def _sample_without_replacement(distribution, num_samples):
"""
Categorical sampling without replacement is currently not implemented. The gumbel-max trick will do for now - see
https://github.com/tensorflow/tensorflow/issues/9260 for more info
"""
z = -tf.math.log(tf.random.uniform(shape_list(distribution), 0, 1))
_, indices = tf.nn.top_k(distribution + z, num_samples)
return indices | [
"def",
"_sample_without_replacement",
"(",
"distribution",
",",
"num_samples",
")",
":",
"z",
"=",
"-",
"tf",
".",
"math",
".",
"log",
"(",
"tf",
".",
"random",
".",
"uniform",
"(",
"shape_list",
"(",
"distribution",
")",
",",
"0",
",",
"1",
")",
")",
... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py#L174-L181 | |
radlab/sparrow | afb8efadeb88524f1394d1abe4ea66c6fd2ac744 | deploy/third_party/boto-2.1.1/boto/storage_uri.py | python | BucketStorageUri.names_singleton | (self) | return self.object_name | Returns True if this URI names an object (vs. a bucket). | Returns True if this URI names an object (vs. a bucket). | [
"Returns",
"True",
"if",
"this",
"URI",
"names",
"an",
"object",
"(",
"vs",
".",
"a",
"bucket",
")",
"."
] | def names_singleton(self):
"""Returns True if this URI names an object (vs. a bucket).
"""
return self.object_name | [
"def",
"names_singleton",
"(",
"self",
")",
":",
"return",
"self",
".",
"object_name"
] | https://github.com/radlab/sparrow/blob/afb8efadeb88524f1394d1abe4ea66c6fd2ac744/deploy/third_party/boto-2.1.1/boto/storage_uri.py#L310-L313 | |
google/deepvariant | 9cf1c7b0e2342d013180aa153cba3c9331c9aef7 | third_party/nucleus/util/variant_utils.py | python | _non_excluded_alts | (alts, exclude_alleles=None) | return [a for a in alts if a not in exclude_alleles] | Exclude any alts listed, by default: '<*>', '.', and '<NON_REF>'.
These alleles are sometimes listed in ALT column but they shouldn't be
analyzed and usually indicate reference blocks in formats like gVCF.
E.g. 'A'->'<*>' is NOT an insertion, and 'A'->'.' is NOT a SNP.
Args:
alts: a list of strings representing the alternate alleles.
exclude_alleles: list(str). The alleles in this list will be ignored.
Returns:
alts alleles except those in exclude_alleles, by default excluding the GVCF
'<*>' allele, the '<NON_REF>' symbolic allele, and '.' missing field by
default. | Exclude any alts listed, by default: '<*>', '.', and '<NON_REF>'. | [
"Exclude",
"any",
"alts",
"listed",
"by",
"default",
":",
"<",
"*",
">",
".",
"and",
"<NON_REF",
">",
"."
] | def _non_excluded_alts(alts, exclude_alleles=None):
"""Exclude any alts listed, by default: '<*>', '.', and '<NON_REF>'.
These alleles are sometimes listed in ALT column but they shouldn't be
analyzed and usually indicate reference blocks in formats like gVCF.
E.g. 'A'->'<*>' is NOT an insertion, and 'A'->'.' is NOT a SNP.
Args:
alts: a list of strings representing the alternate alleles.
exclude_alleles: list(str). The alleles in this list will be ignored.
Returns:
alts alleles except those in exclude_alleles, by default excluding the GVCF
'<*>' allele, the '<NON_REF>' symbolic allele, and '.' missing field by
default.
"""
if exclude_alleles is None:
exclude_alleles = [
vcf_constants.GVCF_ALT_ALLELE, vcf_constants.SYMBOLIC_ALT_ALLELE,
vcf_constants.MISSING_FIELD
]
return [a for a in alts if a not in exclude_alleles] | [
"def",
"_non_excluded_alts",
"(",
"alts",
",",
"exclude_alleles",
"=",
"None",
")",
":",
"if",
"exclude_alleles",
"is",
"None",
":",
"exclude_alleles",
"=",
"[",
"vcf_constants",
".",
"GVCF_ALT_ALLELE",
",",
"vcf_constants",
".",
"SYMBOLIC_ALT_ALLELE",
",",
"vcf_c... | https://github.com/google/deepvariant/blob/9cf1c7b0e2342d013180aa153cba3c9331c9aef7/third_party/nucleus/util/variant_utils.py#L192-L214 | |
selfteaching/selfteaching-python-camp | 9982ee964b984595e7d664b07c389cddaf158f1e | 19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/pyparsing.py | python | ParseBaseException.markInputline | ( self, markerString = ">!<" ) | return line_str.strip() | Extracts the exception line from the input string, and marks
the location of the exception with a special symbol. | Extracts the exception line from the input string, and marks
the location of the exception with a special symbol. | [
"Extracts",
"the",
"exception",
"line",
"from",
"the",
"input",
"string",
"and",
"marks",
"the",
"location",
"of",
"the",
"exception",
"with",
"a",
"special",
"symbol",
"."
] | def markInputline( self, markerString = ">!<" ):
"""Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join((line_str[:line_column],
markerString, line_str[line_column:]))
return line_str.strip() | [
"def",
"markInputline",
"(",
"self",
",",
"markerString",
"=",
"\">!<\"",
")",
":",
"line_str",
"=",
"self",
".",
"line",
"line_column",
"=",
"self",
".",
"column",
"-",
"1",
"if",
"markerString",
":",
"line_str",
"=",
"\"\"",
".",
"join",
"(",
"(",
"l... | https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/pyparsing.py#L279-L288 | |
python/cpython | e13cdca0f5224ec4e23bdd04bb3120506964bc8b | Lib/ntpath.py | python | basename | (p) | return split(p)[1] | Returns the final component of a pathname | Returns the final component of a pathname | [
"Returns",
"the",
"final",
"component",
"of",
"a",
"pathname"
] | def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1] | [
"def",
"basename",
"(",
"p",
")",
":",
"return",
"split",
"(",
"p",
")",
"[",
"1",
"]"
] | https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/ntpath.py#L214-L216 | |
dask/dask | c2b962fec1ba45440fe928869dc64cfe9cc36506 | dask/array/wrap.py | python | wrap_func_shape_as_first_arg | (func, *args, **kwargs) | return Array(graph, name, chunks, dtype=dtype, meta=kwargs.get("meta", None)) | Transform np creation function into blocked version | Transform np creation function into blocked version | [
"Transform",
"np",
"creation",
"function",
"into",
"blocked",
"version"
] | def wrap_func_shape_as_first_arg(func, *args, **kwargs):
"""
Transform np creation function into blocked version
"""
if "shape" not in kwargs:
shape, args = args[0], args[1:]
else:
shape = kwargs.pop("shape")
if isinstance(shape, Array):
raise TypeError(
"Dask array input not supported. "
"Please use tuple, list, or a 1D numpy array instead."
)
parsed = _parse_wrap_args(func, args, kwargs, shape)
shape = parsed["shape"]
dtype = parsed["dtype"]
chunks = parsed["chunks"]
name = parsed["name"]
kwargs = parsed["kwargs"]
func = partial(func, dtype=dtype, **kwargs)
graph = BlockwiseCreateArray(
name,
func,
shape,
chunks,
)
return Array(graph, name, chunks, dtype=dtype, meta=kwargs.get("meta", None)) | [
"def",
"wrap_func_shape_as_first_arg",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"shape\"",
"not",
"in",
"kwargs",
":",
"shape",
",",
"args",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
":",
"]",
"else",
":",
... | https://github.com/dask/dask/blob/c2b962fec1ba45440fe928869dc64cfe9cc36506/dask/array/wrap.py#L44-L73 | |
criteo-research/CausE | 957e55665409ff1c788252977035b38180f60e09 | src/Data/dataset_loading.py | python | load_movielens10M | (dataset_location) | return userid, productid, rating | Load the movielens dataset from disk | Load the movielens dataset from disk | [
"Load",
"the",
"movielens",
"dataset",
"from",
"disk"
] | def load_movielens10M(dataset_location):
"""Load the movielens dataset from disk"""
split_characters = "::"
userid = []
productid = []
rating = []
with open(dataset_location, "r") as dataset_file:
for line in dataset_file:
f = line.rstrip('\r\n').split(split_characters)
userid.append(int(f[0]))
productid.append(int(f[1]))
rating.append(float(f[2]))
# Make the sequence being at zero and contain no missing IDs
_, userid = np.unique(np.asarray(userid), return_inverse=1)
_, productid = np.unique(np.asarray(productid), return_inverse=1)
print("Dataset loaded")
return userid, productid, rating | [
"def",
"load_movielens10M",
"(",
"dataset_location",
")",
":",
"split_characters",
"=",
"\"::\"",
"userid",
"=",
"[",
"]",
"productid",
"=",
"[",
"]",
"rating",
"=",
"[",
"]",
"with",
"open",
"(",
"dataset_location",
",",
"\"r\"",
")",
"as",
"dataset_file",
... | https://github.com/criteo-research/CausE/blob/957e55665409ff1c788252977035b38180f60e09/src/Data/dataset_loading.py#L30-L51 | |
toddlerya/NebulaSolarDash | 286ff86f0ad3550c1c92323d45e24f01c5c6fcd5 | lib/bottle.py | python | StplParser.get_syntax | (self) | return self._syntax | Tokens as a space separated string (default: <% %> % {{ }}) | Tokens as a space separated string (default: <% %> % {{ }}) | [
"Tokens",
"as",
"a",
"space",
"separated",
"string",
"(",
"default",
":",
"<%",
"%",
">",
"%",
"{{",
"}}",
")"
] | def get_syntax(self):
""" Tokens as a space separated string (default: <% %> % {{ }}) """
return self._syntax | [
"def",
"get_syntax",
"(",
"self",
")",
":",
"return",
"self",
".",
"_syntax"
] | https://github.com/toddlerya/NebulaSolarDash/blob/286ff86f0ad3550c1c92323d45e24f01c5c6fcd5/lib/bottle.py#L3834-L3836 | |
aws/chalice | de872630a9097b6657274dae9417522cf7aa8efd | chalice/utils.py | python | OSUtils.normalized_filename | (self, path) | return os.path.normpath(os.path.splitdrive(path)[1]) | Normalize a path into a filename.
This will normalize a file and remove any 'drive' component
from the path on OSes that support drive specifications. | Normalize a path into a filename. | [
"Normalize",
"a",
"path",
"into",
"a",
"filename",
"."
] | def normalized_filename(self, path):
# type: (str) -> str
"""Normalize a path into a filename.
This will normalize a file and remove any 'drive' component
from the path on OSes that support drive specifications.
"""
return os.path.normpath(os.path.splitdrive(path)[1]) | [
"def",
"normalized_filename",
"(",
"self",
",",
"path",
")",
":",
"# type: (str) -> str",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"splitdrive",
"(",
"path",
")",
"[",
"1",
"]",
")"
] | https://github.com/aws/chalice/blob/de872630a9097b6657274dae9417522cf7aa8efd/chalice/utils.py#L313-L321 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/finite_rings/finite_field_givaro.py | python | FiniteField_givaro.log_to_int | (self, n) | return self._cache.log_to_int(n) | r"""
Given an integer `n` this method returns ``i`` where ``i``
satisfies `g^n = i` where `g` is the generator of ``self``; the
result is interpreted as an integer.
INPUT:
- ``n`` -- log representation of a finite field element
OUTPUT:
integer representation of a finite field element.
EXAMPLES::
sage: k = GF(2**8, 'a')
sage: k.log_to_int(4)
16
sage: k.log_to_int(20)
180 | r"""
Given an integer `n` this method returns ``i`` where ``i``
satisfies `g^n = i` where `g` is the generator of ``self``; the
result is interpreted as an integer. | [
"r",
"Given",
"an",
"integer",
"n",
"this",
"method",
"returns",
"i",
"where",
"i",
"satisfies",
"g^n",
"=",
"i",
"where",
"g",
"is",
"the",
"generator",
"of",
"self",
";",
"the",
"result",
"is",
"interpreted",
"as",
"an",
"integer",
"."
] | def log_to_int(self, n):
r"""
Given an integer `n` this method returns ``i`` where ``i``
satisfies `g^n = i` where `g` is the generator of ``self``; the
result is interpreted as an integer.
INPUT:
- ``n`` -- log representation of a finite field element
OUTPUT:
integer representation of a finite field element.
EXAMPLES::
sage: k = GF(2**8, 'a')
sage: k.log_to_int(4)
16
sage: k.log_to_int(20)
180
"""
return self._cache.log_to_int(n) | [
"def",
"log_to_int",
"(",
"self",
",",
"n",
")",
":",
"return",
"self",
".",
"_cache",
".",
"log_to_int",
"(",
"n",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/finite_rings/finite_field_givaro.py#L432-L454 | |
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/physics/secondquant.py | python | FockState.__new__ | (cls, occupations) | return obj | occupations is a list with two possible meanings:
- For bosons it is a list of occupation numbers.
Element i is the number of particles in state i.
- For fermions it is a list of occupied orbits.
Element 0 is the state that was occupied first, element i
is the i'th occupied state. | occupations is a list with two possible meanings: | [
"occupations",
"is",
"a",
"list",
"with",
"two",
"possible",
"meanings",
":"
] | def __new__(cls, occupations):
"""
occupations is a list with two possible meanings:
- For bosons it is a list of occupation numbers.
Element i is the number of particles in state i.
- For fermions it is a list of occupied orbits.
Element 0 is the state that was occupied first, element i
is the i'th occupied state.
"""
occupations = list(map(sympify, occupations))
obj = Basic.__new__(cls, Tuple(*occupations))
return obj | [
"def",
"__new__",
"(",
"cls",
",",
"occupations",
")",
":",
"occupations",
"=",
"list",
"(",
"map",
"(",
"sympify",
",",
"occupations",
")",
")",
"obj",
"=",
"Basic",
".",
"__new__",
"(",
"cls",
",",
"Tuple",
"(",
"*",
"occupations",
")",
")",
"retur... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/physics/secondquant.py#L913-L926 | |
cackharot/suds-py3 | 1d92cc6297efee31bfd94b50b99c431505d7de21 | suds/mx/literal.py | python | Typed.skip | (self, content) | return False | Get whether to skip this I{content}.
Should be skipped when the content is optional
and either the value=None or the value is an empty list.
@param content: The content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
@rtype: bool | Get whether to skip this I{content}.
Should be skipped when the content is optional
and either the value=None or the value is an empty list. | [
"Get",
"whether",
"to",
"skip",
"this",
"I",
"{",
"content",
"}",
".",
"Should",
"be",
"skipped",
"when",
"the",
"content",
"is",
"optional",
"and",
"either",
"the",
"value",
"=",
"None",
"or",
"the",
"value",
"is",
"an",
"empty",
"list",
"."
] | def skip(self, content):
"""
Get whether to skip this I{content}.
Should be skipped when the content is optional
and either the value=None or the value is an empty list.
@param content: The content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
@rtype: bool
"""
if self.optional(content):
v = content.value
if v is None:
return True
if isinstance(v, (list, tuple)) and len(v) == 0:
return True
return False | [
"def",
"skip",
"(",
"self",
",",
"content",
")",
":",
"if",
"self",
".",
"optional",
"(",
"content",
")",
":",
"v",
"=",
"content",
".",
"value",
"if",
"v",
"is",
"None",
":",
"return",
"True",
"if",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",... | https://github.com/cackharot/suds-py3/blob/1d92cc6297efee31bfd94b50b99c431505d7de21/suds/mx/literal.py#L200-L216 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/physics/quantum/qubit.py | python | Qubit._represent_ZGate | (self, basis, **options) | Represent this qubits in the computational basis (ZGate). | Represent this qubits in the computational basis (ZGate). | [
"Represent",
"this",
"qubits",
"in",
"the",
"computational",
"basis",
"(",
"ZGate",
")",
"."
] | def _represent_ZGate(self, basis, **options):
"""Represent this qubits in the computational basis (ZGate).
"""
_format = options.get('format', 'sympy')
n = 1
definite_state = 0
for it in reversed(self.qubit_values):
definite_state += n*it
n = n*2
result = [0]*(2**self.dimension)
result[int(definite_state)] = 1
if _format == 'sympy':
return Matrix(result)
elif _format == 'numpy':
import numpy as np
return np.matrix(result, dtype='complex').transpose()
elif _format == 'scipy.sparse':
from scipy import sparse
return sparse.csr_matrix(result, dtype='complex').transpose() | [
"def",
"_represent_ZGate",
"(",
"self",
",",
"basis",
",",
"*",
"*",
"options",
")",
":",
"_format",
"=",
"options",
".",
"get",
"(",
"'format'",
",",
"'sympy'",
")",
"n",
"=",
"1",
"definite_state",
"=",
"0",
"for",
"it",
"in",
"reversed",
"(",
"sel... | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/physics/quantum/qubit.py#L197-L215 | ||
exaile/exaile | a7b58996c5c15b3aa7b9975ac13ee8f784ef4689 | xlgui/widgets/dialogs.py | python | FileOperationDialog.on_selection_changed | (self, selection) | When the user selects an extension the filename
that is entered will have its extension changed
to the selected extension | When the user selects an extension the filename
that is entered will have its extension changed
to the selected extension | [
"When",
"the",
"user",
"selects",
"an",
"extension",
"the",
"filename",
"that",
"is",
"entered",
"will",
"have",
"its",
"extension",
"changed",
"to",
"the",
"selected",
"extension"
] | def on_selection_changed(self, selection):
"""
When the user selects an extension the filename
that is entered will have its extension changed
to the selected extension
"""
model, iter = selection.get_selected()
(extension,) = model.get(iter, 1)
filename = ""
if self.get_filename():
filename = os.path.basename(self.get_filename())
filename, old_extension = os.path.splitext(filename)
filename += '.' + extension
else:
filename = '*.' + extension
self.set_current_name(filename) | [
"def",
"on_selection_changed",
"(",
"self",
",",
"selection",
")",
":",
"model",
",",
"iter",
"=",
"selection",
".",
"get_selected",
"(",
")",
"(",
"extension",
",",
")",
"=",
"model",
".",
"get",
"(",
"iter",
",",
"1",
")",
"filename",
"=",
"\"\"",
... | https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xlgui/widgets/dialogs.py#L650-L665 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/assumptions/handlers/sets.py | python | AskIrrationalHandler.Basic | (expr, assumptions) | [] | def Basic(expr, assumptions):
_real = ask(Q.real(expr), assumptions)
if _real:
_rational = ask(Q.rational(expr), assumptions)
if _rational is None:
return None
return not _rational
else:
return _real | [
"def",
"Basic",
"(",
"expr",
",",
"assumptions",
")",
":",
"_real",
"=",
"ask",
"(",
"Q",
".",
"real",
"(",
"expr",
")",
",",
"assumptions",
")",
"if",
"_real",
":",
"_rational",
"=",
"ask",
"(",
"Q",
".",
"rational",
"(",
"expr",
")",
",",
"assu... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/assumptions/handlers/sets.py#L161-L169 | ||||
napalm-automation/napalm-logs | 573beee426f5f2bbbc988e432ee6b5c80457fffa | napalm_logs/base.py | python | NapalmLogs.__init__ | (
self,
address='0.0.0.0',
port=514,
listener='udp',
publisher='zmq',
publish_address='0.0.0.0',
publish_port=49017,
auth_address='0.0.0.0',
auth_port=49018,
metrics_enabled=False,
metrics_address='0.0.0.0',
metrics_port='9215',
metrics_dir='/tmp/napalm_logs_metrics',
certificate=None,
keyfile=None,
disable_security=False,
config_path=None,
config_dict=None,
extension_config_path=None,
extension_config_dict=None,
log_level='warning',
log_format='%(asctime)s,%(msecs)03.0f [%(name)-17s][%(levelname)-8s] %(message)s',
device_blacklist=[],
device_whitelist=[],
hwm=None,
device_worker_processes=1,
serializer='msgpack',
buffer=None,
opts=None,
) | Init the napalm-logs engine.
:param address: The address to bind the syslog client. Default: 0.0.0.0.
:param port: Listen port. Default: 514.
:param listener: Listen type. Default: udp.
:param publish_address: The address to bing when publishing the OC
objects. Default: 0.0.0.0.
:param publish_port: Publish port. Default: 49017. | Init the napalm-logs engine. | [
"Init",
"the",
"napalm",
"-",
"logs",
"engine",
"."
] | def __init__(
self,
address='0.0.0.0',
port=514,
listener='udp',
publisher='zmq',
publish_address='0.0.0.0',
publish_port=49017,
auth_address='0.0.0.0',
auth_port=49018,
metrics_enabled=False,
metrics_address='0.0.0.0',
metrics_port='9215',
metrics_dir='/tmp/napalm_logs_metrics',
certificate=None,
keyfile=None,
disable_security=False,
config_path=None,
config_dict=None,
extension_config_path=None,
extension_config_dict=None,
log_level='warning',
log_format='%(asctime)s,%(msecs)03.0f [%(name)-17s][%(levelname)-8s] %(message)s',
device_blacklist=[],
device_whitelist=[],
hwm=None,
device_worker_processes=1,
serializer='msgpack',
buffer=None,
opts=None,
):
'''
Init the napalm-logs engine.
:param address: The address to bind the syslog client. Default: 0.0.0.0.
:param port: Listen port. Default: 514.
:param listener: Listen type. Default: udp.
:param publish_address: The address to bing when publishing the OC
objects. Default: 0.0.0.0.
:param publish_port: Publish port. Default: 49017.
'''
self.opts = opts if opts else {}
sentry_dsn = self.opts.get('sentry_dsn') or os.getenv('SENTRY_DSN')
if sentry_dsn:
if HAS_SENTRY:
sentry_sdk.init(
sentry_dsn,
**self.opts.get('sentry_opts', {'traces_sample_rate': 1.0})
)
else:
log.warning(
'Sentry DSN provided, but the sentry_sdk library is not installed'
)
self.address = address
self.port = port
self.listener = listener
self.publisher = publisher
self.publish_address = publish_address
self.publish_port = publish_port
self.auth_address = auth_address
self.auth_port = auth_port
self.metrics_enabled = metrics_enabled
self.metrics_address = metrics_address
self.metrics_port = metrics_port
self.metrics_dir = metrics_dir
self.certificate = certificate
self.keyfile = keyfile
self.disable_security = disable_security
self.config_path = config_path
self.config_dict = config_dict
self.extension_config_path = extension_config_path
self.extension_config_dict = extension_config_dict
self.log_level = log_level
self.log_format = log_format
self.device_whitelist = device_whitelist
self.device_blacklist = device_blacklist
self.serializer = serializer
self.device_worker_processes = device_worker_processes
self.hwm = hwm
self._buffer_cfg = buffer
self._buffer = None
# Setup the environment
self._setup_log()
self._build_config()
self._verify_config()
self._post_preparation()
# Start the Prometheus metrics server
self._setup_metrics()
self._setup_buffer()
# Private vars
self.__priv_key = None
self.__signing_key = None
self._processes = []
self.up = True | [
"def",
"__init__",
"(",
"self",
",",
"address",
"=",
"'0.0.0.0'",
",",
"port",
"=",
"514",
",",
"listener",
"=",
"'udp'",
",",
"publisher",
"=",
"'zmq'",
",",
"publish_address",
"=",
"'0.0.0.0'",
",",
"publish_port",
"=",
"49017",
",",
"auth_address",
"=",... | https://github.com/napalm-automation/napalm-logs/blob/573beee426f5f2bbbc988e432ee6b5c80457fffa/napalm_logs/base.py#L52-L145 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/py/_path/common.py | python | PathBase.visit | (self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False) | yields all paths below the current one
fil is a filter (glob pattern or callable), if not matching the
path will not be yielded, defaulting to None (everything is
returned)
rec is a filter (glob pattern or callable) that controls whether
a node is descended, defaulting to None
ignore is an Exception class that is ignoredwhen calling dirlist()
on any of the paths (by default, all exceptions are reported)
bf if True will cause a breadthfirst search instead of the
default depthfirst. Default: False
sort if True will sort entries within each directory level. | yields all paths below the current one | [
"yields",
"all",
"paths",
"below",
"the",
"current",
"one"
] | def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False):
""" yields all paths below the current one
fil is a filter (glob pattern or callable), if not matching the
path will not be yielded, defaulting to None (everything is
returned)
rec is a filter (glob pattern or callable) that controls whether
a node is descended, defaulting to None
ignore is an Exception class that is ignoredwhen calling dirlist()
on any of the paths (by default, all exceptions are reported)
bf if True will cause a breadthfirst search instead of the
default depthfirst. Default: False
sort if True will sort entries within each directory level.
"""
for x in Visitor(fil, rec, ignore, bf, sort).gen(self):
yield x | [
"def",
"visit",
"(",
"self",
",",
"fil",
"=",
"None",
",",
"rec",
"=",
"None",
",",
"ignore",
"=",
"NeverRaised",
",",
"bf",
"=",
"False",
",",
"sort",
"=",
"False",
")",
":",
"for",
"x",
"in",
"Visitor",
"(",
"fil",
",",
"rec",
",",
"ignore",
... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/py/_path/common.py#L359-L378 | ||
AstroPrint/AstroBox | e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75 | src/ext/makerbot_driver/EEPROM/EepromReader.py | python | EepromReader.read_value_from_eeprom | (self, input_dict, offset) | return data | Given an input dict with type information, and an offset,
pulls that data from the eeprom and unpacks it. Reads value
type by type, so we dont run into any read-too-much-info
errors.
@param dict input_dict: Dictionary with information required
to read off the eeprom.
@param int offset: The offset we read from on the eeprom
@return list: The pieces of data we read off the eeprom | Given an input dict with type information, and an offset,
pulls that data from the eeprom and unpacks it. Reads value
type by type, so we dont run into any read-too-much-info
errors. | [
"Given",
"an",
"input",
"dict",
"with",
"type",
"information",
"and",
"an",
"offset",
"pulls",
"that",
"data",
"from",
"the",
"eeprom",
"and",
"unpacks",
"it",
".",
"Reads",
"value",
"type",
"by",
"type",
"so",
"we",
"dont",
"run",
"into",
"any",
"read",... | def read_value_from_eeprom(self, input_dict, offset):
"""
Given an input dict with type information, and an offset,
pulls that data from the eeprom and unpacks it. Reads value
type by type, so we dont run into any read-too-much-info
errors.
@param dict input_dict: Dictionary with information required
to read off the eeprom.
@param int offset: The offset we read from on the eeprom
@return list: The pieces of data we read off the eeprom
"""
if 'mult' in input_dict:
unpack_code = str(input_dict['type'] * int(input_dict['mult']))
else:
unpack_code = str(input_dict['type'])
data = []
for char in unpack_code:
size = struct.calcsize(char)
#Get the value to unpack
val = self.s3g.read_from_EEPROM(offset, size)
data.extend(self.unpack_value(val, char))
offset += size
return data | [
"def",
"read_value_from_eeprom",
"(",
"self",
",",
"input_dict",
",",
"offset",
")",
":",
"if",
"'mult'",
"in",
"input_dict",
":",
"unpack_code",
"=",
"str",
"(",
"input_dict",
"[",
"'type'",
"]",
"*",
"int",
"(",
"input_dict",
"[",
"'mult'",
"]",
")",
"... | https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/ext/makerbot_driver/EEPROM/EepromReader.py#L181-L204 | |
selfteaching/selfteaching-python-camp | 9982ee964b984595e7d664b07c389cddaf158f1e | 19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/distlib/_backport/tarfile.py | python | copyfileobj | (src, dst, length=None) | return | Copy length bytes from fileobj src to fileobj dst.
If length is None, copy the entire content. | Copy length bytes from fileobj src to fileobj dst.
If length is None, copy the entire content. | [
"Copy",
"length",
"bytes",
"from",
"fileobj",
"src",
"to",
"fileobj",
"dst",
".",
"If",
"length",
"is",
"None",
"copy",
"the",
"entire",
"content",
"."
] | def copyfileobj(src, dst, length=None):
"""Copy length bytes from fileobj src to fileobj dst.
If length is None, copy the entire content.
"""
if length == 0:
return
if length is None:
while True:
buf = src.read(16*1024)
if not buf:
break
dst.write(buf)
return
BUFSIZE = 16 * 1024
blocks, remainder = divmod(length, BUFSIZE)
for b in range(blocks):
buf = src.read(BUFSIZE)
if len(buf) < BUFSIZE:
raise IOError("end of file reached")
dst.write(buf)
if remainder != 0:
buf = src.read(remainder)
if len(buf) < remainder:
raise IOError("end of file reached")
dst.write(buf)
return | [
"def",
"copyfileobj",
"(",
"src",
",",
"dst",
",",
"length",
"=",
"None",
")",
":",
"if",
"length",
"==",
"0",
":",
"return",
"if",
"length",
"is",
"None",
":",
"while",
"True",
":",
"buf",
"=",
"src",
".",
"read",
"(",
"16",
"*",
"1024",
")",
... | https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/distlib/_backport/tarfile.py#L256-L283 | |
huanghoujing/person-reid-triplet-loss-baseline | a1c2bd20180cfaf225782717aeaaab461798abec | tri_loss/utils/visualization.py | python | save_im | (im, save_path) | im: shape [3, H, W] | im: shape [3, H, W] | [
"im",
":",
"shape",
"[",
"3",
"H",
"W",
"]"
] | def save_im(im, save_path):
"""im: shape [3, H, W]"""
may_make_dir(ospdn(save_path))
im = im.transpose(1, 2, 0)
Image.fromarray(im).save(save_path) | [
"def",
"save_im",
"(",
"im",
",",
"save_path",
")",
":",
"may_make_dir",
"(",
"ospdn",
"(",
"save_path",
")",
")",
"im",
"=",
"im",
".",
"transpose",
"(",
"1",
",",
"2",
",",
"0",
")",
"Image",
".",
"fromarray",
"(",
"im",
")",
".",
"save",
"(",
... | https://github.com/huanghoujing/person-reid-triplet-loss-baseline/blob/a1c2bd20180cfaf225782717aeaaab461798abec/tri_loss/utils/visualization.py#L105-L109 | ||
hyperledger/aries-cloudagent-python | 2f36776e99f6053ae92eed8123b5b1b2e891c02a | aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py | python | V20PresExRecord.__init__ | (
self,
*,
pres_ex_id: str = None,
connection_id: str = None,
thread_id: str = None,
initiator: str = None,
role: str = None,
state: str = None,
pres_proposal: Union[V20PresProposal, Mapping] = None, # aries message
pres_request: Union[V20PresRequest, Mapping] = None, # aries message
pres: Union[V20Pres, Mapping] = None, # aries message
verified: str = None,
auto_present: bool = False,
error_msg: str = None,
trace: bool = False, # backward compat: BaseRecord.FromStorage()
by_format: Mapping = None, # backward compat: BaseRecord.FromStorage()
**kwargs,
) | Initialize a new PresExRecord. | Initialize a new PresExRecord. | [
"Initialize",
"a",
"new",
"PresExRecord",
"."
] | def __init__(
self,
*,
pres_ex_id: str = None,
connection_id: str = None,
thread_id: str = None,
initiator: str = None,
role: str = None,
state: str = None,
pres_proposal: Union[V20PresProposal, Mapping] = None, # aries message
pres_request: Union[V20PresRequest, Mapping] = None, # aries message
pres: Union[V20Pres, Mapping] = None, # aries message
verified: str = None,
auto_present: bool = False,
error_msg: str = None,
trace: bool = False, # backward compat: BaseRecord.FromStorage()
by_format: Mapping = None, # backward compat: BaseRecord.FromStorage()
**kwargs,
):
"""Initialize a new PresExRecord."""
super().__init__(pres_ex_id, state, trace=trace, **kwargs)
self.connection_id = connection_id
self.thread_id = thread_id
self.initiator = initiator
self.role = role
self.state = state
self._pres_proposal = V20PresProposal.serde(pres_proposal)
self._pres_request = V20PresRequest.serde(pres_request)
self._pres = V20Pres.serde(pres)
self.verified = verified
self.auto_present = auto_present
self.error_msg = error_msg | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"pres_ex_id",
":",
"str",
"=",
"None",
",",
"connection_id",
":",
"str",
"=",
"None",
",",
"thread_id",
":",
"str",
"=",
"None",
",",
"initiator",
":",
"str",
"=",
"None",
",",
"role",
":",
"str",
"=",... | https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py#L52-L83 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/vistir/compat.py | python | to_native_string | (string) | return to_text(string) | [] | def to_native_string(string):
from .misc import to_text, to_bytes
if six.PY2:
return to_bytes(string)
return to_text(string) | [
"def",
"to_native_string",
"(",
"string",
")",
":",
"from",
".",
"misc",
"import",
"to_text",
",",
"to_bytes",
"if",
"six",
".",
"PY2",
":",
"return",
"to_bytes",
"(",
"string",
")",
"return",
"to_text",
"(",
"string",
")"
] | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/vistir/compat.py#L448-L453 | |||
HymanLiuTS/flaskTs | 286648286976e85d9b9a5873632331efcafe0b21 | flasky/lib/python2.7/site-packages/pkg_resources/__init__.py | python | safe_version | (version) | Convert an arbitrary string to a standard version string | Convert an arbitrary string to a standard version string | [
"Convert",
"an",
"arbitrary",
"string",
"to",
"a",
"standard",
"version",
"string"
] | def safe_version(version):
"""
Convert an arbitrary string to a standard version string
"""
try:
# normalize the version
return str(packaging.version.Version(version))
except packaging.version.InvalidVersion:
version = version.replace(' ', '.')
return re.sub('[^A-Za-z0-9.]+', '-', version) | [
"def",
"safe_version",
"(",
"version",
")",
":",
"try",
":",
"# normalize the version",
"return",
"str",
"(",
"packaging",
".",
"version",
".",
"Version",
"(",
"version",
")",
")",
"except",
"packaging",
".",
"version",
".",
"InvalidVersion",
":",
"version",
... | https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/pkg_resources/__init__.py#L1383-L1392 | ||
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/pyasn1/type/univ.py | python | BitString.asOctets | (self) | return integer.to_bytes(self._value, length=len(self)) | Get |ASN.1| value as a sequence of octets.
If |ASN.1| object length is not a multiple of 8, result
will be left-padded with zeros. | Get |ASN.1| value as a sequence of octets. | [
"Get",
"|ASN",
".",
"1|",
"value",
"as",
"a",
"sequence",
"of",
"octets",
"."
] | def asOctets(self):
"""Get |ASN.1| value as a sequence of octets.
If |ASN.1| object length is not a multiple of 8, result
will be left-padded with zeros.
"""
return integer.to_bytes(self._value, length=len(self)) | [
"def",
"asOctets",
"(",
"self",
")",
":",
"return",
"integer",
".",
"to_bytes",
"(",
"self",
".",
"_value",
",",
"length",
"=",
"len",
"(",
"self",
")",
")"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/pyasn1/type/univ.py#L620-L626 | |
biolab/orange2 | db40a9449cb45b507d63dcd5739b223f9cffb8e6 | Orange/OrangeWidgets/OWClustering.py | python | DendrogramWidget.set_highlighted_item | (self, item) | Set the currently highlighted item. | Set the currently highlighted item. | [
"Set",
"the",
"currently",
"highlighted",
"item",
"."
] | def set_highlighted_item(self, item):
""" Set the currently highlighted item.
"""
if self._highlighted_item == item:
return
if self._highlighted_item:
self._highlighted_item.set_highlight(False)
if item:
item.set_highlight(True)
self._highlighted_item = item | [
"def",
"set_highlighted_item",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"_highlighted_item",
"==",
"item",
":",
"return",
"if",
"self",
".",
"_highlighted_item",
":",
"self",
".",
"_highlighted_item",
".",
"set_highlight",
"(",
"False",
")",
"i... | https://github.com/biolab/orange2/blob/db40a9449cb45b507d63dcd5739b223f9cffb8e6/Orange/OrangeWidgets/OWClustering.py#L571-L581 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/tableau_tuple.py | python | StandardTableauTuples_shape.an_element | (self) | return self[c > 3 and 4 or (c > 1 and -1 or 0)] | r"""
Returns a particular element of the class.
EXAMPLES::
sage: StandardTableauTuples([[2],[2,1]]).an_element()
([[2, 4]], [[1, 3], [5]])
sage: StandardTableauTuples([[10],[],[]]).an_element()
([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [], []) | r"""
Returns a particular element of the class. | [
"r",
"Returns",
"a",
"particular",
"element",
"of",
"the",
"class",
"."
] | def an_element(self):
r"""
Returns a particular element of the class.
EXAMPLES::
sage: StandardTableauTuples([[2],[2,1]]).an_element()
([[2, 4]], [[1, 3], [5]])
sage: StandardTableauTuples([[10],[],[]]).an_element()
([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [], [])
"""
c = self.cardinality()
return self[c > 3 and 4 or (c > 1 and -1 or 0)] | [
"def",
"an_element",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"cardinality",
"(",
")",
"return",
"self",
"[",
"c",
">",
"3",
"and",
"4",
"or",
"(",
"c",
">",
"1",
"and",
"-",
"1",
"or",
"0",
")",
"]"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/tableau_tuple.py#L4974-L4986 | |
morganstanley/treadmill | f18267c665baf6def4374d21170198f63ff1cde4 | lib/python/treadmill/admin/_ldap.py | python | Allocation.dn | (self, ident=None) | Object dn. | Object dn. | [
"Object",
"dn",
"."
] | def dn(self, ident=None):
"""Object dn."""
if not ident:
return self.admin.dn(['ou=%s' % self.ou()])
else:
return self.admin.dn(_allocation_dn_parts(ident)) | [
"def",
"dn",
"(",
"self",
",",
"ident",
"=",
"None",
")",
":",
"if",
"not",
"ident",
":",
"return",
"self",
".",
"admin",
".",
"dn",
"(",
"[",
"'ou=%s'",
"%",
"self",
".",
"ou",
"(",
")",
"]",
")",
"else",
":",
"return",
"self",
".",
"admin",
... | https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/admin/_ldap.py#L1896-L1901 | ||
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/pip/pip/_internal/utils/misc.py | python | splitext | (path) | return base, ext | Like os.path.splitext, but take off .tar too | Like os.path.splitext, but take off .tar too | [
"Like",
"os",
".",
"path",
".",
"splitext",
"but",
"take",
"off",
".",
"tar",
"too"
] | def splitext(path):
# type: (str) -> Tuple[str, str]
"""Like os.path.splitext, but take off .tar too"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext | [
"def",
"splitext",
"(",
"path",
")",
":",
"# type: (str) -> Tuple[str, str]",
"base",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"path",
")",
"if",
"base",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.tar'",
")",
":",
"ext",
"=",
"base",
"... | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_internal/utils/misc.py#L337-L344 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/cam/v20190116/models.py | python | ListSAMLProvidersResponse.__init__ | (self) | r"""
:param TotalCount: SAML身份提供商总数
:type TotalCount: int
:param SAMLProviderSet: SAML身份提供商列表
:type SAMLProviderSet: list of SAMLProviderInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | r"""
:param TotalCount: SAML身份提供商总数
:type TotalCount: int
:param SAMLProviderSet: SAML身份提供商列表
:type SAMLProviderSet: list of SAMLProviderInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | [
"r",
":",
"param",
"TotalCount",
":",
"SAML身份提供商总数",
":",
"type",
"TotalCount",
":",
"int",
":",
"param",
"SAMLProviderSet",
":",
"SAML身份提供商列表",
":",
"type",
"SAMLProviderSet",
":",
"list",
"of",
"SAMLProviderInfo",
":",
"param",
"RequestId",
":",
"唯一请求",
"ID,... | def __init__(self):
r"""
:param TotalCount: SAML身份提供商总数
:type TotalCount: int
:param SAMLProviderSet: SAML身份提供商列表
:type SAMLProviderSet: list of SAMLProviderInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.SAMLProviderSet = None
self.RequestId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"TotalCount",
"=",
"None",
"self",
".",
"SAMLProviderSet",
"=",
"None",
"self",
".",
"RequestId",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cam/v20190116/models.py#L3597-L3608 | ||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | lib-python/2.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
'''
assert self._state == RUN
if chunksize == 1:
result = IMapUnorderedIterator(self._cache)
self._taskqueue.put((((result._job, i, func, (x,), {})
for i, x in enumerate(iterable)), result._set_length))
return result
else:
assert chunksize > 1
task_batches = Pool._get_tasks(func, iterable, chunksize)
result = IMapUnorderedIterator(self._cache)
self._taskqueue.put((((result._job, i, mapstar, (x,), {})
for i, x in enumerate(task_batches)), result._set_length))
return (item for chunk in result for item in chunk) | [
"def",
"imap_unordered",
"(",
"self",
",",
"func",
",",
"iterable",
",",
"chunksize",
"=",
"1",
")",
":",
"assert",
"self",
".",
"_state",
"==",
"RUN",
"if",
"chunksize",
"==",
"1",
":",
"result",
"=",
"IMapUnorderedIterator",
"(",
"self",
".",
"_cache",... | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/multiprocessing/pool.py#L271-L287 | ||
ray-project/ray | 703c1610348615dcb8c2d141a0c46675084660f5 | rllib/agents/mbmpo/mbmpo.py | python | MBMPOTrainer.validate_env | (env: EnvType, env_context: EnvContext) | Validates the local_worker's env object (after creation).
Args:
env: The env object to check (for worker=0 only).
env_context: The env context used for the instantiation of
the local worker's env (worker=0).
Raises:
ValueError: In case something is wrong with the config. | Validates the local_worker's env object (after creation). | [
"Validates",
"the",
"local_worker",
"s",
"env",
"object",
"(",
"after",
"creation",
")",
"."
] | def validate_env(env: EnvType, env_context: EnvContext) -> None:
"""Validates the local_worker's env object (after creation).
Args:
env: The env object to check (for worker=0 only).
env_context: The env context used for the instantiation of
the local worker's env (worker=0).
Raises:
ValueError: In case something is wrong with the config.
"""
if not hasattr(env, "reward") or not callable(env.reward):
raise ValueError(
f"Env {env} doest not have a `reward()` method, needed for "
"MB-MPO! This `reward()` method should return ") | [
"def",
"validate_env",
"(",
"env",
":",
"EnvType",
",",
"env_context",
":",
"EnvContext",
")",
"->",
"None",
":",
"if",
"not",
"hasattr",
"(",
"env",
",",
"\"reward\"",
")",
"or",
"not",
"callable",
"(",
"env",
".",
"reward",
")",
":",
"raise",
"ValueE... | https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/rllib/agents/mbmpo/mbmpo.py#L452-L466 | ||
10XGenomics/cellranger | a83c753ce641db6409a59ad817328354fbe7187e | tenkit/lib/python/tenkit/samplesheet.py | python | _overwrite_cell | (row, idx, val, fill='') | return row | Either:
-- overwrite the cell at row[idx] if it exists
-- pad the row until you can append the idx col, and then write it | Either:
-- overwrite the cell at row[idx] if it exists
-- pad the row until you can append the idx col, and then write it | [
"Either",
":",
"--",
"overwrite",
"the",
"cell",
"at",
"row",
"[",
"idx",
"]",
"if",
"it",
"exists",
"--",
"pad",
"the",
"row",
"until",
"you",
"can",
"append",
"the",
"idx",
"col",
"and",
"then",
"write",
"it"
] | def _overwrite_cell(row, idx, val, fill=''):
"""
Either:
-- overwrite the cell at row[idx] if it exists
-- pad the row until you can append the idx col, and then write it
"""
while len(row) <= idx:
row.append(fill)
row[idx] = val
return row | [
"def",
"_overwrite_cell",
"(",
"row",
",",
"idx",
",",
"val",
",",
"fill",
"=",
"''",
")",
":",
"while",
"len",
"(",
"row",
")",
"<=",
"idx",
":",
"row",
".",
"append",
"(",
"fill",
")",
"row",
"[",
"idx",
"]",
"=",
"val",
"return",
"row"
] | https://github.com/10XGenomics/cellranger/blob/a83c753ce641db6409a59ad817328354fbe7187e/tenkit/lib/python/tenkit/samplesheet.py#L460-L469 | |
pwndbg/pwndbg | 136b3b6a80d94f494dcb00a614af1c24ca706700 | pwndbg/commands/windbg.py | python | bd | (which = '*') | Disable the breakpoint with the specified index. | Disable the breakpoint with the specified index. | [
"Disable",
"the",
"breakpoint",
"with",
"the",
"specified",
"index",
"."
] | def bd(which = '*'):
"""
Disable the breakpoint with the specified index.
"""
if which == '*':
gdb.execute('disable breakpoints')
else:
gdb.execute('disable breakpoints %s' % which) | [
"def",
"bd",
"(",
"which",
"=",
"'*'",
")",
":",
"if",
"which",
"==",
"'*'",
":",
"gdb",
".",
"execute",
"(",
"'disable breakpoints'",
")",
"else",
":",
"gdb",
".",
"execute",
"(",
"'disable breakpoints %s'",
"%",
"which",
")"
] | https://github.com/pwndbg/pwndbg/blob/136b3b6a80d94f494dcb00a614af1c24ca706700/pwndbg/commands/windbg.py#L313-L320 | ||
frescobaldi/frescobaldi | 301cc977fc4ba7caa3df9e4bf905212ad5d06912 | frescobaldi_app/sidebar/__init__.py | python | ViewSpaceSideBarManager.lineNumbersVisible | (self) | return self._line_numbers | Returns whether line numbers are shown. | Returns whether line numbers are shown. | [
"Returns",
"whether",
"line",
"numbers",
"are",
"shown",
"."
] | def lineNumbersVisible(self):
"""Returns whether line numbers are shown."""
return self._line_numbers | [
"def",
"lineNumbersVisible",
"(",
"self",
")",
":",
"return",
"self",
".",
"_line_numbers"
] | https://github.com/frescobaldi/frescobaldi/blob/301cc977fc4ba7caa3df9e4bf905212ad5d06912/frescobaldi_app/sidebar/__init__.py#L168-L170 | |
microsoft/botbuilder-python | 3d410365461dc434df59bdfeaa2f16d28d9df868 | libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py | python | ChoicePrompt.__init__ | (
self,
dialog_id: str,
validator: Callable[[PromptValidatorContext], bool] = None,
default_locale: str = None,
choice_defaults: Dict[str, ChoiceFactoryOptions] = None,
) | :param dialog_id: Unique ID of the dialog within its parent `DialogSet`.
:param validator: (Optional) validator that will be called each time the user responds to the prompt.
If the validator replies with a message no additional retry prompt will be sent.
:param default_locale: (Optional) locale to use if `dc.context.activity.locale` not specified.
Defaults to a value of `en-us`.
:param choice_defaults: (Optional) Overrides the dictionary of
Bot Framework SDK-supported _default_choice_options.
As type Dict[str, ChoiceFactoryOptions], the key is a string of the locale, such as "en-us".
* Must be passed in to each ConfirmPrompt that needs the custom choice defaults. | :param dialog_id: Unique ID of the dialog within its parent `DialogSet`.
:param validator: (Optional) validator that will be called each time the user responds to the prompt.
If the validator replies with a message no additional retry prompt will be sent.
:param default_locale: (Optional) locale to use if `dc.context.activity.locale` not specified.
Defaults to a value of `en-us`.
:param choice_defaults: (Optional) Overrides the dictionary of
Bot Framework SDK-supported _default_choice_options.
As type Dict[str, ChoiceFactoryOptions], the key is a string of the locale, such as "en-us".
* Must be passed in to each ConfirmPrompt that needs the custom choice defaults. | [
":",
"param",
"dialog_id",
":",
"Unique",
"ID",
"of",
"the",
"dialog",
"within",
"its",
"parent",
"DialogSet",
".",
":",
"param",
"validator",
":",
"(",
"Optional",
")",
"validator",
"that",
"will",
"be",
"called",
"each",
"time",
"the",
"user",
"responds"... | def __init__(
self,
dialog_id: str,
validator: Callable[[PromptValidatorContext], bool] = None,
default_locale: str = None,
choice_defaults: Dict[str, ChoiceFactoryOptions] = None,
):
"""
:param dialog_id: Unique ID of the dialog within its parent `DialogSet`.
:param validator: (Optional) validator that will be called each time the user responds to the prompt.
If the validator replies with a message no additional retry prompt will be sent.
:param default_locale: (Optional) locale to use if `dc.context.activity.locale` not specified.
Defaults to a value of `en-us`.
:param choice_defaults: (Optional) Overrides the dictionary of
Bot Framework SDK-supported _default_choice_options.
As type Dict[str, ChoiceFactoryOptions], the key is a string of the locale, such as "en-us".
* Must be passed in to each ConfirmPrompt that needs the custom choice defaults.
"""
super().__init__(dialog_id, validator)
self.style = ListStyle.auto
self.default_locale = default_locale
self.choice_options: ChoiceFactoryOptions = None
self.recognizer_options: FindChoicesOptions = None
if choice_defaults is not None:
self._default_choice_options = choice_defaults | [
"def",
"__init__",
"(",
"self",
",",
"dialog_id",
":",
"str",
",",
"validator",
":",
"Callable",
"[",
"[",
"PromptValidatorContext",
"]",
",",
"bool",
"]",
"=",
"None",
",",
"default_locale",
":",
"str",
"=",
"None",
",",
"choice_defaults",
":",
"Dict",
... | https://github.com/microsoft/botbuilder-python/blob/3d410365461dc434df59bdfeaa2f16d28d9df868/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py#L41-L67 | ||
flennerhag/mlens | 6cbc11354b5f9500a33d9cefb700a1bba9d3199a | mlens/parallel/learner.py | python | BaseNode.__fitted__ | (self) | return True | Fit status | Fit status | [
"Fit",
"status"
] | def __fitted__(self):
"""Fit status"""
if (not self._learner_ or not self._sublearners_ or
not self.indexer.__fitted__):
return False
# Check estimator param overlap
fitted = self._learner_ + self._sublearners_
fitted_params = fitted[0].estimator.get_params(deep=True)
model_estimator_params = self.estimator.get_params(deep=True)
# NOTE: Currently we just issue a warning if params don't overlap
check_params(fitted_params, model_estimator_params)
self._check_static_params()
# NOTE: This check would trigger a FitFailedError if param_check fails
# check_params(fitted_params, model_estimator_params):
# self.clear() # Release obsolete estimators
# return False
# Check that hyper-params hasn't changed
# if not self._check_static_params():
# return False
# return True
return True | [
"def",
"__fitted__",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"_learner_",
"or",
"not",
"self",
".",
"_sublearners_",
"or",
"not",
"self",
".",
"indexer",
".",
"__fitted__",
")",
":",
"return",
"False",
"# Check estimator param overlap",
"fitted... | https://github.com/flennerhag/mlens/blob/6cbc11354b5f9500a33d9cefb700a1bba9d3199a/mlens/parallel/learner.py#L736-L760 | |
kaaedit/kaa | e6a8819a5ecba04b7db8303bd5736b5a7c9b822d | kaa/cui/wnd.py | python | Window.activate | (self) | Activate wnd | Activate wnd | [
"Activate",
"wnd"
] | def activate(self):
"""Activate wnd"""
self.bring_top()
kaa.app.set_focus(self) | [
"def",
"activate",
"(",
"self",
")",
":",
"self",
".",
"bring_top",
"(",
")",
"kaa",
".",
"app",
".",
"set_focus",
"(",
"self",
")"
] | https://github.com/kaaedit/kaa/blob/e6a8819a5ecba04b7db8303bd5736b5a7c9b822d/kaa/cui/wnd.py#L174-L177 | ||
tomcatmanager/tomcatmanager | 41fa645d3cfef8ee83d98f401e653f174d59bfd4 | src/tomcatmanager/interactive_tomcat_manager.py | python | InteractiveTomcatManager.convert_to_boolean | (self, value: Any) | return self.BOOLEAN_VALUES[value.lower()] | Return a boolean value translating from other types if necessary. | Return a boolean value translating from other types if necessary. | [
"Return",
"a",
"boolean",
"value",
"translating",
"from",
"other",
"types",
"if",
"necessary",
"."
] | def convert_to_boolean(self, value: Any):
"""Return a boolean value translating from other types if necessary."""
if isinstance(value, bool) is True:
return value
if str(value).lower() not in self.BOOLEAN_VALUES:
if value is None or value == "":
raise ValueError("invalid syntax: must be true-ish or false-ish")
# we can't figure out what it is
raise ValueError(f"invalid syntax: not a boolean: '{value}'")
return self.BOOLEAN_VALUES[value.lower()] | [
"def",
"convert_to_boolean",
"(",
"self",
",",
"value",
":",
"Any",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
"is",
"True",
":",
"return",
"value",
"if",
"str",
"(",
"value",
")",
".",
"lower",
"(",
")",
"not",
"in",
"self",
"."... | https://github.com/tomcatmanager/tomcatmanager/blob/41fa645d3cfef8ee83d98f401e653f174d59bfd4/src/tomcatmanager/interactive_tomcat_manager.py#L737-L747 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.