repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1 value | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|
wavefrontHQ/python-client | wavefront_api_client/api/webhook_api.py | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/webhook_api.py#L416-L437 | def update_webhook(self, id, **kwargs): # noqa: E501
"""Update a specific webhook # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_webhook(id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str id: (required)
:param Notificant body: Example Body: <pre>{ \"description\": \"WebHook Description\", \"template\": \"POST Body -- Mustache syntax\", \"title\": \"WebHook Title\", \"triggers\": [ \"ALERT_OPENED\" ], \"recipient\": \"http://example.com\", \"customHttpHeaders\": {}, \"contentType\": \"text/plain\" }</pre>
:return: ResponseContainerNotificant
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.update_webhook_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.update_webhook_with_http_info(id, **kwargs) # noqa: E501
return data | [
"def",
"update_webhook",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"update_webhoo... | Update a specific webhook # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_webhook(id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str id: (required)
:param Notificant body: Example Body: <pre>{ \"description\": \"WebHook Description\", \"template\": \"POST Body -- Mustache syntax\", \"title\": \"WebHook Title\", \"triggers\": [ \"ALERT_OPENED\" ], \"recipient\": \"http://example.com\", \"customHttpHeaders\": {}, \"contentType\": \"text/plain\" }</pre>
:return: ResponseContainerNotificant
If the method is called asynchronously,
returns the request thread. | [
"Update",
"a",
"specific",
"webhook",
"#",
"noqa",
":",
"E501"
] | python | train |
saltstack/salt | salt/modules/aptpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L892-L933 | def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs) | [
"def",
"remove",
"(",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_uninstall",
"(",
"action",
"=",
"'remove'",
",",
"name",
"=",
"name",
",",
"pkgs",
"=",
"pkgs",
",",
"*",
"*",
"kwargs",
")"
] | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]' | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"run",
"(",
"1",
")",
"_",
"is",
"now",
"used",
"to",
"i... | python | train |
vmirly/pyclust | pyclust/_bisect_kmeans.py | https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_bisect_kmeans.py#L110-L157 | def _bisect_kmeans(X, n_clusters, n_trials, max_iter, tol):
""" Apply Bisecting Kmeans clustering
to reach n_clusters number of clusters
"""
membs = np.empty(shape=X.shape[0], dtype=int)
centers = dict() #np.empty(shape=(n_clusters,X.shape[1]), dtype=float)
sse_arr = dict() #-1.0*np.ones(shape=n_clusters, dtype=float)
## data structure to store cluster hierarchies
tree = treelib.Tree()
tree = _add_tree_node(tree, 0, ilev=0, X=X)
km = _kmeans.KMeans(n_clusters=2, n_trials=n_trials, max_iter=max_iter, tol=tol)
for i in range(1,n_clusters):
sel_clust_id,sel_memb_ids = _select_cluster_2_split(membs, tree)
X_sub = X[sel_memb_ids,:]
km.fit(X_sub)
#print("Bisecting Step %d :"%i, sel_clust_id, km.sse_arr_, km.centers_)
## Updating the clusters & properties
#sse_arr[[sel_clust_id,i]] = km.sse_arr_
#centers[[sel_clust_id,i]] = km.centers_
tree = _add_tree_node(tree, 2*i-1, i, \
size=np.sum(km.labels_ == 0), center=km.centers_[0], \
sse=km.sse_arr_[0], parent= sel_clust_id)
tree = _add_tree_node(tree, 2*i, i, \
size=np.sum(km.labels_ == 1), center=km.centers_[1], \
sse=km.sse_arr_[1], parent= sel_clust_id)
pred_labels = km.labels_
pred_labels[np.where(pred_labels == 1)[0]] = 2*i
pred_labels[np.where(pred_labels == 0)[0]] = 2*i - 1
#if sel_clust_id == 1:
# pred_labels[np.where(pred_labels == 0)[0]] = sel_clust_id
# pred_labels[np.where(pred_labels == 1)[0]] = i
#else:
# pred_labels[np.where(pred_labels == 1)[0]] = i
# pred_labels[np.where(pred_labels == 0)[0]] = sel_clust_id
membs[sel_memb_ids] = pred_labels
for n in tree.leaves():
label = n.data['label']
centers[label] = n.data['center']
sse_arr[label] = n.data['sse']
return(centers, membs, sse_arr, tree) | [
"def",
"_bisect_kmeans",
"(",
"X",
",",
"n_clusters",
",",
"n_trials",
",",
"max_iter",
",",
"tol",
")",
":",
"membs",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"int",
")",
"centers",
"=",
"d... | Apply Bisecting Kmeans clustering
to reach n_clusters number of clusters | [
"Apply",
"Bisecting",
"Kmeans",
"clustering",
"to",
"reach",
"n_clusters",
"number",
"of",
"clusters"
] | python | train |
log2timeline/plaso | plaso/parsers/manager.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/manager.py#L320-L351 | def GetParserObjects(cls, parser_filter_expression=None):
"""Retrieves the parser objects.
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Returns:
dict[str, BaseParser]: parsers per name.
"""
includes, excludes = cls._GetParserFilters(parser_filter_expression)
parser_objects = {}
for parser_name, parser_class in iter(cls._parser_classes.items()):
# If there are no includes all parsers are included by default.
if not includes and parser_name in excludes:
continue
if includes and parser_name not in includes:
continue
parser_object = parser_class()
if parser_class.SupportsPlugins():
plugin_includes = None
if parser_name in includes:
plugin_includes = includes[parser_name]
parser_object.EnablePlugins(plugin_includes)
parser_objects[parser_name] = parser_object
return parser_objects | [
"def",
"GetParserObjects",
"(",
"cls",
",",
"parser_filter_expression",
"=",
"None",
")",
":",
"includes",
",",
"excludes",
"=",
"cls",
".",
"_GetParserFilters",
"(",
"parser_filter_expression",
")",
"parser_objects",
"=",
"{",
"}",
"for",
"parser_name",
",",
"p... | Retrieves the parser objects.
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Returns:
dict[str, BaseParser]: parsers per name. | [
"Retrieves",
"the",
"parser",
"objects",
"."
] | python | train |
projectshift/shift-boiler | boiler/user/user_service.py | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L314-L352 | def default_token_user_loader(self, token):
"""
Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherwise throws an exception.
:param token: str, token string
:return: boiler.user.models.User
"""
try:
data = self.decode_token(token)
except jwt.exceptions.DecodeError as e:
raise x.JwtDecodeError(str(e))
except jwt.ExpiredSignatureError as e:
raise x.JwtExpired(str(e))
user = self.get(data['user_id'])
if not user:
msg = 'No user with such id [{}]'
raise x.JwtNoUser(msg.format(data['user_id']))
if user.is_locked():
msg = 'This account is locked'
raise x.AccountLocked(msg, locked_until=user.locked_until)
if self.require_confirmation and not user.email_confirmed:
msg = 'Please confirm your email address [{}]'
raise x.EmailNotConfirmed(
msg.format(user.email_secure),
email=user.email
)
# test token matches the one on file
if not token == user._token:
raise x.JwtTokenMismatch('The token does not match our records')
# return on success
return user | [
"def",
"default_token_user_loader",
"(",
"self",
",",
"token",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"decode_token",
"(",
"token",
")",
"except",
"jwt",
".",
"exceptions",
".",
"DecodeError",
"as",
"e",
":",
"raise",
"x",
".",
"JwtDecodeError",
... | Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherwise throws an exception.
:param token: str, token string
:return: boiler.user.models.User | [
"Default",
"token",
"user",
"loader",
"Accepts",
"a",
"token",
"and",
"decodes",
"it",
"checking",
"signature",
"and",
"expiration",
".",
"Then",
"loads",
"user",
"by",
"id",
"from",
"the",
"token",
"to",
"see",
"if",
"account",
"is",
"not",
"locked",
".",... | python | train |
joelfrederico/SciSalt | scisalt/PWFA/match.py | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/match.py#L53-L57 | def sigma(self):
"""
Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}`
"""
return _np.power(2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.plasma.n_p * _np.power(_spc.elementary_charge, 2)) , 0.25) * _np.sqrt(self.emit) | [
"def",
"sigma",
"(",
"self",
")",
":",
"return",
"_np",
".",
"power",
"(",
"2",
"*",
"_sltr",
".",
"GeV2joule",
"(",
"self",
".",
"E",
")",
"*",
"_spc",
".",
"epsilon_0",
"/",
"(",
"self",
".",
"plasma",
".",
"n_p",
"*",
"_np",
".",
"power",
"(... | Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}` | [
"Spot",
"size",
"of",
"matched",
"beam",
":",
"math",
":",
"\\\\",
"left",
"(",
"\\\\",
"frac",
"{",
"2",
"E",
"\\\\",
"varepsilon_0",
"}",
"{",
"n_p",
"e^2",
"}",
"\\\\",
"right",
")",
"^",
"{",
"1",
"/",
"4",
"}",
"\\\\",
"sqrt",
"{",
"\\\\",
... | python | valid |
UDST/orca | orca/server/server.py | https://github.com/UDST/orca/blob/07b34aeef13cc87c966b2e30cbe7e76cc9d3622c/orca/server/server.py#L334-L340 | def column_csv(table_name, col_name):
"""
Return a column as CSV using Pandas' default CSV output.
"""
csv = orca.get_table(table_name).get_column(col_name).to_csv(path=None)
return csv, 200, {'Content-Type': 'text/csv'} | [
"def",
"column_csv",
"(",
"table_name",
",",
"col_name",
")",
":",
"csv",
"=",
"orca",
".",
"get_table",
"(",
"table_name",
")",
".",
"get_column",
"(",
"col_name",
")",
".",
"to_csv",
"(",
"path",
"=",
"None",
")",
"return",
"csv",
",",
"200",
",",
... | Return a column as CSV using Pandas' default CSV output. | [
"Return",
"a",
"column",
"as",
"CSV",
"using",
"Pandas",
"default",
"CSV",
"output",
"."
] | python | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_oven.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L279-L289 | def _macaroon_id_ops(ops):
'''Return operations suitable for serializing as part of a MacaroonId.
It assumes that ops has been canonicalized and that there's at least
one operation.
'''
id_ops = []
for entity, entity_ops in itertools.groupby(ops, lambda x: x.entity):
actions = map(lambda x: x.action, entity_ops)
id_ops.append(id_pb2.Op(entity=entity, actions=actions))
return id_ops | [
"def",
"_macaroon_id_ops",
"(",
"ops",
")",
":",
"id_ops",
"=",
"[",
"]",
"for",
"entity",
",",
"entity_ops",
"in",
"itertools",
".",
"groupby",
"(",
"ops",
",",
"lambda",
"x",
":",
"x",
".",
"entity",
")",
":",
"actions",
"=",
"map",
"(",
"lambda",
... | Return operations suitable for serializing as part of a MacaroonId.
It assumes that ops has been canonicalized and that there's at least
one operation. | [
"Return",
"operations",
"suitable",
"for",
"serializing",
"as",
"part",
"of",
"a",
"MacaroonId",
"."
] | python | train |
bitcraze/crazyflie-lib-python | cflib/drivers/crazyradio.py | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L210-L213 | def set_arc(self, arc):
""" Set the ACK retry count for radio communication """
_send_vendor_setup(self.handle, SET_RADIO_ARC, arc, 0, ())
self.arc = arc | [
"def",
"set_arc",
"(",
"self",
",",
"arc",
")",
":",
"_send_vendor_setup",
"(",
"self",
".",
"handle",
",",
"SET_RADIO_ARC",
",",
"arc",
",",
"0",
",",
"(",
")",
")",
"self",
".",
"arc",
"=",
"arc"
] | Set the ACK retry count for radio communication | [
"Set",
"the",
"ACK",
"retry",
"count",
"for",
"radio",
"communication"
] | python | train |
labeneator/flask-cavage | flask_cavage.py | https://github.com/labeneator/flask-cavage/blob/7144841eaf289b469ba77507e19d9012284272d4/flask_cavage.py#L187-L197 | def replay_checker(self, callback):
"""
Decorate a method that receives the request headers and returns a bool
indicating whether we should proceed with the request. This can be used
to protect against replay attacks. For example, this method could check
the request date header value is within a delta value of the server time.
"""
if not callback or not callable(callback):
raise Exception("Please pass in a callable that protects against replays")
self.replay_checker_callback = callback
return callback | [
"def",
"replay_checker",
"(",
"self",
",",
"callback",
")",
":",
"if",
"not",
"callback",
"or",
"not",
"callable",
"(",
"callback",
")",
":",
"raise",
"Exception",
"(",
"\"Please pass in a callable that protects against replays\"",
")",
"self",
".",
"replay_checker_... | Decorate a method that receives the request headers and returns a bool
indicating whether we should proceed with the request. This can be used
to protect against replay attacks. For example, this method could check
the request date header value is within a delta value of the server time. | [
"Decorate",
"a",
"method",
"that",
"receives",
"the",
"request",
"headers",
"and",
"returns",
"a",
"bool",
"indicating",
"whether",
"we",
"should",
"proceed",
"with",
"the",
"request",
".",
"This",
"can",
"be",
"used",
"to",
"protect",
"against",
"replay",
"... | python | train |
textbook/atmdb | atmdb/core.py | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L65-L85 | def calculate_timeout(http_date):
"""Extract request timeout from e.g. ``Retry-After`` header.
Notes:
Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can
be either an integer number of seconds or an HTTP date. This
function can handle either.
Arguments:
http_date (:py:class:`str`): The date to parse.
Returns:
:py:class:`int`: The timeout, in seconds.
"""
try:
return int(http_date)
except ValueError:
date_after = parse(http_date)
utc_now = datetime.now(tz=timezone.utc)
return int((date_after - utc_now).total_seconds()) | [
"def",
"calculate_timeout",
"(",
"http_date",
")",
":",
"try",
":",
"return",
"int",
"(",
"http_date",
")",
"except",
"ValueError",
":",
"date_after",
"=",
"parse",
"(",
"http_date",
")",
"utc_now",
"=",
"datetime",
".",
"now",
"(",
"tz",
"=",
"timezone",
... | Extract request timeout from e.g. ``Retry-After`` header.
Notes:
Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can
be either an integer number of seconds or an HTTP date. This
function can handle either.
Arguments:
http_date (:py:class:`str`): The date to parse.
Returns:
:py:class:`int`: The timeout, in seconds. | [
"Extract",
"request",
"timeout",
"from",
"e",
".",
"g",
".",
"Retry",
"-",
"After",
"header",
"."
] | python | train |
rosenbrockc/fortpy | fortpy/parsers/module.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/parsers/module.py#L177-L196 | def _process_publics(self, contents):
"""Extracts a list of public members, types and executables that were declared using
the public keyword instead of a decoration."""
matches = self.RE_PUBLIC.finditer(contents)
result = {}
start = 0
for public in matches:
methods = public.group("methods")
#We need to keep track of where the public declarations start so that the unit
#testing framework can insert public statements for those procedures being tested
#who are not marked as public
if start == 0:
start = public.start("methods")
for item in re.split(r"[\s&\n,]+", methods.strip()):
if item.lower() in ["interface", "type", "use"]:
#We have obviously reached the end of the actual public
#declaration in this regex match.
break
self._dict_increment(result, item.lower())
return (result, start) | [
"def",
"_process_publics",
"(",
"self",
",",
"contents",
")",
":",
"matches",
"=",
"self",
".",
"RE_PUBLIC",
".",
"finditer",
"(",
"contents",
")",
"result",
"=",
"{",
"}",
"start",
"=",
"0",
"for",
"public",
"in",
"matches",
":",
"methods",
"=",
"publ... | Extracts a list of public members, types and executables that were declared using
the public keyword instead of a decoration. | [
"Extracts",
"a",
"list",
"of",
"public",
"members",
"types",
"and",
"executables",
"that",
"were",
"declared",
"using",
"the",
"public",
"keyword",
"instead",
"of",
"a",
"decoration",
"."
] | python | train |
jcrist/skein | skein/core.py | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L440-L477 | def stop_global_driver(force=False):
"""Stops the global driver if running.
No-op if no global driver is running.
Parameters
----------
force : bool, optional
By default skein will check that the process associated with the
driver PID is actually a skein driver. Setting ``force`` to
``True`` will kill the process in all cases.
"""
address, pid = _read_driver()
if address is None:
return
if not force:
# Attempt to connect first, errors on failure
try:
Client(address=address)
except ConnectionError:
if pid_exists(pid):
# PID exists, but we can't connect, reraise
raise
# PID doesn't exist, continue cleanup as normal
try:
os.kill(pid, signal.SIGTERM)
except OSError as exc:
# If we're forcing a kill, ignore EPERM as well, as we're not sure
# if the process is a driver.
ignore = (errno.ESRCH, errno.EPERM) if force else (errno.ESRCH,)
if exc.errno not in ignore: # pragma: no cover
raise
try:
os.remove(os.path.join(properties.config_dir, 'driver'))
except OSError: # pragma: no cover
pass | [
"def",
"stop_global_driver",
"(",
"force",
"=",
"False",
")",
":",
"address",
",",
"pid",
"=",
"_read_driver",
"(",
")",
"if",
"address",
"is",
"None",
":",
"return",
"if",
"not",
"force",
":",
"# Attempt to connect first, errors on failure",
"try",
":",
"Clie... | Stops the global driver if running.
No-op if no global driver is running.
Parameters
----------
force : bool, optional
By default skein will check that the process associated with the
driver PID is actually a skein driver. Setting ``force`` to
``True`` will kill the process in all cases. | [
"Stops",
"the",
"global",
"driver",
"if",
"running",
"."
] | python | train |
google/grr | grr/server/grr_response_server/databases/mem_flows.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_flows.py#L610-L618 | def _RegisterFlowProcessingHandler(self, handler):
"""Registers a handler to receive flow processing messages."""
self.flow_handler_stop = False
self.flow_handler_thread = threading.Thread(
name="flow_processing_handler",
target=self._HandleFlowProcessingRequestLoop,
args=(handler,))
self.flow_handler_thread.daemon = True
self.flow_handler_thread.start() | [
"def",
"_RegisterFlowProcessingHandler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"flow_handler_stop",
"=",
"False",
"self",
".",
"flow_handler_thread",
"=",
"threading",
".",
"Thread",
"(",
"name",
"=",
"\"flow_processing_handler\"",
",",
"target",
"="... | Registers a handler to receive flow processing messages. | [
"Registers",
"a",
"handler",
"to",
"receive",
"flow",
"processing",
"messages",
"."
] | python | train |
hyperledger/sawtooth-core | cli/sawtooth_cli/network_command/compare.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/cli/sawtooth_cli/network_command/compare.py#L462-L474 | def print_cliques(cliques, next_cliques, node_id_map):
"""Print a '*' on each branch with its block id and the ids of the nodes
that have the block."""
n_cliques = len(cliques)
format_str = '{:<' + str(n_cliques * 2) + '} {} {}'
branches = ['|'] * len(cliques)
for i, clique in enumerate(cliques):
block_id, nodes = clique
print(format_str.format(
' '.join(branches[:i] + ['*'] + branches[i + 1:]),
block_id[:8], format_siblings(nodes, node_id_map)))
if block_id not in next_cliques:
branches[i] = ' ' | [
"def",
"print_cliques",
"(",
"cliques",
",",
"next_cliques",
",",
"node_id_map",
")",
":",
"n_cliques",
"=",
"len",
"(",
"cliques",
")",
"format_str",
"=",
"'{:<'",
"+",
"str",
"(",
"n_cliques",
"*",
"2",
")",
"+",
"'} {} {}'",
"branches",
"=",
"[",
"'|... | Print a '*' on each branch with its block id and the ids of the nodes
that have the block. | [
"Print",
"a",
"*",
"on",
"each",
"branch",
"with",
"its",
"block",
"id",
"and",
"the",
"ids",
"of",
"the",
"nodes",
"that",
"have",
"the",
"block",
"."
] | python | train |
Esri/ArcREST | src/arcrest/manageorg/_portals.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_portals.py#L50-L57 | def regions(self):
"""gets the regions value"""
url = "%s/regions" % self.root
params = {"f": "json"}
return self._get(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | [
"def",
"regions",
"(",
"self",
")",
":",
"url",
"=",
"\"%s/regions\"",
"%",
"self",
".",
"root",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_u... | gets the regions value | [
"gets",
"the",
"regions",
"value"
] | python | train |
raphaelvallat/pingouin | pingouin/parametric.py | https://github.com/raphaelvallat/pingouin/blob/58b19fa4fffbfe09d58b456e3926a148249e4d9b/pingouin/parametric.py#L1082-L1235 | def welch_anova(dv=None, between=None, data=None, export_filename=None):
"""One-way Welch ANOVA.
Parameters
----------
dv : string
Name of column containing the dependant variable.
between : string
Name of column containing the between factor.
data : pandas DataFrame
DataFrame. Note that this function can also directly be used as a
Pandas method, in which case this argument is no longer needed.
export_filename : string
Filename (without extension) for the output file.
If None, do not export the table.
By default, the file will be created in the current python console
directory. To change that, specify the filename with full path.
Returns
-------
aov : DataFrame
ANOVA summary ::
'Source' : Factor names
'SS' : Sums of squares
'DF' : Degrees of freedom
'MS' : Mean squares
'F' : F-values
'p-unc' : uncorrected p-values
'np2' : Partial eta-square effect sizes
See Also
--------
anova : One-way ANOVA
rm_anova : One-way and two-way repeated measures ANOVA
mixed_anova : Two way mixed ANOVA
kruskal : Non-parametric one-way ANOVA
Notes
-----
The classic ANOVA is very powerful when the groups are normally distributed
and have equal variances. However, when the groups have unequal variances,
it is best to use the Welch ANOVA that better controls for
type I error (Liu 2015). The homogeneity of variances can be measured with
the `homoscedasticity` function. The two other assumptions of
normality and independance remain.
The main idea of Welch ANOVA is to use a weight :math:`w_i` to reduce
the effect of unequal variances. This weight is calculated using the sample
size :math:`n_i` and variance :math:`s_i^2` of each group
:math:`i=1,...,r`:
.. math:: w_i = \\frac{n_i}{s_i^2}
Using these weights, the adjusted grand mean of the data is:
.. math::
\\overline{Y}_{welch} = \\frac{\\sum_{i=1}^r w_i\\overline{Y}_i}
{\\sum w}
where :math:`\\overline{Y}_i` is the mean of the :math:`i` group.
The treatment sums of squares is defined as:
.. math::
SS_{treatment} = \\sum_{i=1}^r w_i
(\\overline{Y}_i - \\overline{Y}_{welch})^2
We then need to calculate a term lambda:
.. math::
\\Lambda = \\frac{3\\sum_{i=1}^r(\\frac{1}{n_i-1})
(1 - \\frac{w_i}{\\sum w})^2}{r^2 - 1}
from which the F-value can be calculated:
.. math::
F_{welch} = \\frac{SS_{treatment} / (r-1)}
{1 + \\frac{2\\Lambda(r-2)}{3}}
and the p-value approximated using a F-distribution with
:math:`(r-1, 1 / \\Lambda)` degrees of freedom.
When the groups are balanced and have equal variances, the optimal post-hoc
test is the Tukey-HSD test (`pairwise_tukey`). If the groups have unequal
variances, the Games-Howell test is more adequate.
Results have been tested against R.
References
----------
.. [1] Liu, Hangcheng. "Comparing Welch's ANOVA, a Kruskal-Wallis test and
traditional ANOVA in case of Heterogeneity of Variance." (2015).
.. [2] Welch, Bernard Lewis. "On the comparison of several mean values:
an alternative approach." Biometrika 38.3/4 (1951): 330-336.
Examples
--------
1. One-way Welch ANOVA on the pain threshold dataset.
>>> from pingouin import welch_anova, read_dataset
>>> df = read_dataset('anova')
>>> aov = welch_anova(dv='Pain threshold', between='Hair color',
... data=df, export_filename='pain_anova.csv')
>>> aov
Source ddof1 ddof2 F p-unc
0 Hair color 3 8.33 5.89 0.018813
"""
# Check data
_check_dataframe(dv=dv, between=between, data=data, effects='between')
# Reset index (avoid duplicate axis error)
data = data.reset_index(drop=True)
# Number of groups
r = data[between].nunique()
ddof1 = r - 1
# Compute weights and ajusted means
grp = data.groupby(between)[dv]
weights = grp.count() / grp.var()
adj_grandmean = (weights * grp.mean()).sum() / weights.sum()
# Treatment sum of squares
ss_tr = np.sum(weights * np.square(grp.mean() - adj_grandmean))
ms_tr = ss_tr / ddof1
# Calculate lambda, F-value and p-value
lamb = (3 * np.sum((1 / (grp.count() - 1)) *
(1 - (weights / weights.sum()))**2)) / (r**2 - 1)
fval = ms_tr / (1 + (2 * lamb * (r - 2)) / 3)
pval = f.sf(fval, ddof1, 1 / lamb)
# Create output dataframe
aov = pd.DataFrame({'Source': between,
'ddof1': ddof1,
'ddof2': 1 / lamb,
'F': fval,
'p-unc': pval,
}, index=[0])
col_order = ['Source', 'ddof1', 'ddof2', 'F', 'p-unc']
aov = aov.reindex(columns=col_order)
aov[['F', 'ddof2']] = aov[['F', 'ddof2']].round(3)
# Export to .csv
if export_filename is not None:
_export_table(aov, export_filename)
return aov | [
"def",
"welch_anova",
"(",
"dv",
"=",
"None",
",",
"between",
"=",
"None",
",",
"data",
"=",
"None",
",",
"export_filename",
"=",
"None",
")",
":",
"# Check data",
"_check_dataframe",
"(",
"dv",
"=",
"dv",
",",
"between",
"=",
"between",
",",
"data",
"... | One-way Welch ANOVA.
Parameters
----------
dv : string
Name of column containing the dependant variable.
between : string
Name of column containing the between factor.
data : pandas DataFrame
DataFrame. Note that this function can also directly be used as a
Pandas method, in which case this argument is no longer needed.
export_filename : string
Filename (without extension) for the output file.
If None, do not export the table.
By default, the file will be created in the current python console
directory. To change that, specify the filename with full path.
Returns
-------
aov : DataFrame
ANOVA summary ::
'Source' : Factor names
'SS' : Sums of squares
'DF' : Degrees of freedom
'MS' : Mean squares
'F' : F-values
'p-unc' : uncorrected p-values
'np2' : Partial eta-square effect sizes
See Also
--------
anova : One-way ANOVA
rm_anova : One-way and two-way repeated measures ANOVA
mixed_anova : Two way mixed ANOVA
kruskal : Non-parametric one-way ANOVA
Notes
-----
The classic ANOVA is very powerful when the groups are normally distributed
and have equal variances. However, when the groups have unequal variances,
it is best to use the Welch ANOVA that better controls for
type I error (Liu 2015). The homogeneity of variances can be measured with
the `homoscedasticity` function. The two other assumptions of
normality and independance remain.
The main idea of Welch ANOVA is to use a weight :math:`w_i` to reduce
the effect of unequal variances. This weight is calculated using the sample
size :math:`n_i` and variance :math:`s_i^2` of each group
:math:`i=1,...,r`:
.. math:: w_i = \\frac{n_i}{s_i^2}
Using these weights, the adjusted grand mean of the data is:
.. math::
\\overline{Y}_{welch} = \\frac{\\sum_{i=1}^r w_i\\overline{Y}_i}
{\\sum w}
where :math:`\\overline{Y}_i` is the mean of the :math:`i` group.
The treatment sums of squares is defined as:
.. math::
SS_{treatment} = \\sum_{i=1}^r w_i
(\\overline{Y}_i - \\overline{Y}_{welch})^2
We then need to calculate a term lambda:
.. math::
\\Lambda = \\frac{3\\sum_{i=1}^r(\\frac{1}{n_i-1})
(1 - \\frac{w_i}{\\sum w})^2}{r^2 - 1}
from which the F-value can be calculated:
.. math::
F_{welch} = \\frac{SS_{treatment} / (r-1)}
{1 + \\frac{2\\Lambda(r-2)}{3}}
and the p-value approximated using a F-distribution with
:math:`(r-1, 1 / \\Lambda)` degrees of freedom.
When the groups are balanced and have equal variances, the optimal post-hoc
test is the Tukey-HSD test (`pairwise_tukey`). If the groups have unequal
variances, the Games-Howell test is more adequate.
Results have been tested against R.
References
----------
.. [1] Liu, Hangcheng. "Comparing Welch's ANOVA, a Kruskal-Wallis test and
traditional ANOVA in case of Heterogeneity of Variance." (2015).
.. [2] Welch, Bernard Lewis. "On the comparison of several mean values:
an alternative approach." Biometrika 38.3/4 (1951): 330-336.
Examples
--------
1. One-way Welch ANOVA on the pain threshold dataset.
>>> from pingouin import welch_anova, read_dataset
>>> df = read_dataset('anova')
>>> aov = welch_anova(dv='Pain threshold', between='Hair color',
... data=df, export_filename='pain_anova.csv')
>>> aov
Source ddof1 ddof2 F p-unc
0 Hair color 3 8.33 5.89 0.018813 | [
"One",
"-",
"way",
"Welch",
"ANOVA",
"."
] | python | train |
neherlab/treetime | treetime/utils.py | https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/utils.py#L117-L126 | def min_interp(interp_object):
"""
Find the global minimum of a function represented as an interpolation object.
"""
try:
return interp_object.x[interp_object(interp_object.x).argmin()]
except Exception as e:
s = "Cannot find minimum of the interpolation object" + str(interp_object.x) + \
"Minimal x: " + str(interp_object.x.min()) + "Maximal x: " + str(interp_object.x.max())
raise e | [
"def",
"min_interp",
"(",
"interp_object",
")",
":",
"try",
":",
"return",
"interp_object",
".",
"x",
"[",
"interp_object",
"(",
"interp_object",
".",
"x",
")",
".",
"argmin",
"(",
")",
"]",
"except",
"Exception",
"as",
"e",
":",
"s",
"=",
"\"Cannot find... | Find the global minimum of a function represented as an interpolation object. | [
"Find",
"the",
"global",
"minimum",
"of",
"a",
"function",
"represented",
"as",
"an",
"interpolation",
"object",
"."
] | python | test |
playpauseandstop/rororo | rororo/settings.py | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/settings.py#L26-L34 | def from_env(key: str, default: T = None) -> Union[str, Optional[T]]:
"""Shortcut for safely reading environment variable.
:param key: Environment var key.
:param default:
Return default value if environment var not found by given key. By
default: ``None``
"""
return os.getenv(key, default) | [
"def",
"from_env",
"(",
"key",
":",
"str",
",",
"default",
":",
"T",
"=",
"None",
")",
"->",
"Union",
"[",
"str",
",",
"Optional",
"[",
"T",
"]",
"]",
":",
"return",
"os",
".",
"getenv",
"(",
"key",
",",
"default",
")"
] | Shortcut for safely reading environment variable.
:param key: Environment var key.
:param default:
Return default value if environment var not found by given key. By
default: ``None`` | [
"Shortcut",
"for",
"safely",
"reading",
"environment",
"variable",
"."
] | python | train |
ph4r05/monero-serialize | monero_serialize/xmrobj.py | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrobj.py#L316-L349 | async def load_field(obj, elem_type, params=None, elem=None):
"""
Loads a field from the reader, based on the field type specification. Demultiplexer.
:param obj:
:param elem_type:
:param params:
:param elem:
:return:
"""
if issubclass(elem_type, x.UVarintType) or issubclass(elem_type, x.IntType) or isinstance(obj, (int, bool)):
return set_elem(elem, obj)
elif issubclass(elem_type, x.BlobType):
fvalue = await load_blob(obj, elem_type)
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.UnicodeType) or isinstance(elem, str):
return set_elem(elem, obj)
elif issubclass(elem_type, x.VariantType):
fvalue = await load_variant(obj, elem=get_elem(elem), elem_type=elem_type, params=params)
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.ContainerType): # container ~ simple list
fvalue = await load_container(obj, elem_type, params=params, container=get_elem(elem))
return set_elem(elem, fvalue)
elif issubclass(elem_type, x.MessageType):
fvalue = await load_message(obj, msg_type=elem_type, msg=get_elem(elem))
return set_elem(elem, fvalue)
else:
raise TypeError | [
"async",
"def",
"load_field",
"(",
"obj",
",",
"elem_type",
",",
"params",
"=",
"None",
",",
"elem",
"=",
"None",
")",
":",
"if",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
"UVarintType",
")",
"or",
"issubclass",
"(",
"elem_type",
",",
"x",
".",
... | Loads a field from the reader, based on the field type specification. Demultiplexer.
:param obj:
:param elem_type:
:param params:
:param elem:
:return: | [
"Loads",
"a",
"field",
"from",
"the",
"reader",
"based",
"on",
"the",
"field",
"type",
"specification",
".",
"Demultiplexer",
"."
] | python | train |
halcy/Mastodon.py | mastodon/Mastodon.py | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1928-L1936 | def account_unpin(self, id):
"""
Unpin / un-endorse a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/unpin'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"account_unpin",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}/unpin'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'... | Unpin / un-endorse a user.
Returns a `relationship dict`_ containing the updated relationship to the user. | [
"Unpin",
"/",
"un",
"-",
"endorse",
"a",
"user",
"."
] | python | train |
ssalentin/plip | plip/modules/detection.py | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/detection.py#L52-L72 | def hydrophobic_interactions(atom_set_a, atom_set_b):
"""Detection of hydrophobic pliprofiler between atom_set_a (binding site) and atom_set_b (ligand).
Definition: All pairs of qualified carbon atoms within a distance of HYDROPH_DIST_MAX
"""
data = namedtuple('hydroph_interaction', 'bsatom bsatom_orig_idx ligatom ligatom_orig_idx '
'distance restype resnr reschain restype_l, resnr_l, reschain_l')
pairings = []
for a, b in itertools.product(atom_set_a, atom_set_b):
if a.orig_idx == b.orig_idx:
continue
e = euclidean3d(a.atom.coords, b.atom.coords)
if not config.MIN_DIST < e < config.HYDROPH_DIST_MAX:
continue
restype, resnr, reschain = whichrestype(a.atom), whichresnumber(a.atom), whichchain(a.atom)
restype_l, resnr_l, reschain_l = whichrestype(b.orig_atom), whichresnumber(b.orig_atom), whichchain(b.orig_atom)
contact = data(bsatom=a.atom, bsatom_orig_idx=a.orig_idx, ligatom=b.atom, ligatom_orig_idx=b.orig_idx,
distance=e, restype=restype, resnr=resnr,
reschain=reschain, restype_l=restype_l,
resnr_l=resnr_l, reschain_l=reschain_l)
pairings.append(contact)
return filter_contacts(pairings) | [
"def",
"hydrophobic_interactions",
"(",
"atom_set_a",
",",
"atom_set_b",
")",
":",
"data",
"=",
"namedtuple",
"(",
"'hydroph_interaction'",
",",
"'bsatom bsatom_orig_idx ligatom ligatom_orig_idx '",
"'distance restype resnr reschain restype_l, resnr_l, reschain_l'",
")",
"pairings"... | Detection of hydrophobic pliprofiler between atom_set_a (binding site) and atom_set_b (ligand).
Definition: All pairs of qualified carbon atoms within a distance of HYDROPH_DIST_MAX | [
"Detection",
"of",
"hydrophobic",
"pliprofiler",
"between",
"atom_set_a",
"(",
"binding",
"site",
")",
"and",
"atom_set_b",
"(",
"ligand",
")",
".",
"Definition",
":",
"All",
"pairs",
"of",
"qualified",
"carbon",
"atoms",
"within",
"a",
"distance",
"of",
"HYDR... | python | train |
ceph/ceph-deploy | ceph_deploy/util/net.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/net.py#L271-L333 | def _interfaces_ifconfig(out):
"""
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr)
"""
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')
pip = re.compile(r'.*?(?:inet addr:|inet )(.*?)\s')
pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)')
pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))')
pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+)).*')
pupdown = re.compile('UP')
pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)')
groups = re.compile('\r?\n(?=\\S)').split(out)
for group in groups:
data = dict()
iface = ''
updown = False
for line in group.splitlines():
miface = piface.match(line)
mmac = pmac.match(line)
mip = pip.match(line)
mip6 = pip6.match(line)
mupdown = pupdown.search(line)
if miface:
iface = miface.group(1)
if mmac:
data['hwaddr'] = mmac.group(1)
if mip:
if 'inet' not in data:
data['inet'] = list()
addr_obj = dict()
addr_obj['address'] = mip.group(1)
mmask = pmask.match(line)
if mmask:
if mmask.group(1):
mmask = _number_of_set_bits_to_ipv4_netmask(
int(mmask.group(1), 16))
else:
mmask = mmask.group(2)
addr_obj['netmask'] = mmask
mbcast = pbcast.match(line)
if mbcast:
addr_obj['broadcast'] = mbcast.group(1)
data['inet'].append(addr_obj)
if mupdown:
updown = True
if mip6:
if 'inet6' not in data:
data['inet6'] = list()
addr_obj = dict()
addr_obj['address'] = mip6.group(1) or mip6.group(2)
mmask6 = pmask6.match(line)
if mmask6:
addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2)
data['inet6'].append(addr_obj)
data['up'] = updown
ret[iface] = data
del data
return ret | [
"def",
"_interfaces_ifconfig",
"(",
"out",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"piface",
"=",
"re",
".",
"compile",
"(",
"r'^([^\\s:]+)'",
")",
"pmac",
"=",
"re",
".",
"compile",
"(",
"'.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)'",
")",
"pip",
"="... | Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr) | [
"Uses",
"ifconfig",
"to",
"return",
"a",
"dictionary",
"of",
"interfaces",
"with",
"various",
"information",
"about",
"each",
"(",
"up",
"/",
"down",
"state",
"ip",
"address",
"netmask",
"and",
"hwaddr",
")"
] | python | train |
Nekroze/partpy | examples/contacts.py | https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/examples/contacts.py#L106-L137 | def parse_email(self):
"""Email address parsing is done in several stages.
First the name of the email use is determined.
Then it looks for a '@' as a delimiter between the name and the site.
Lastly the email site is matched.
Each part's string is stored, combined and returned.
"""
email = []
# Match from current char until a non lower cased alpha
name = self.match_string_pattern(spat.alphal)
if not name:
raise PartpyError(self, 'Expected a valid name')
email.append(name) # Store the name
self.eat_string(name) # Eat the name
nextchar = self.get_char()
if not nextchar == '@':
raise PartpyError(self, 'Expecting @, found: ' + nextchar)
email.append(nextchar)
self.eat_length(1) # Eat the '@' symbol
# Use string pattern matching to match all lower cased alphas or '.'s.
site = self.match_string_pattern(spat.alphal + '.')
if not site:
raise PartpyError(self, 'Expecting a site, found: ' + site)
email.append(site)
self.eat_string(site) # Eat the site
return ''.join(email) | [
"def",
"parse_email",
"(",
"self",
")",
":",
"email",
"=",
"[",
"]",
"# Match from current char until a non lower cased alpha",
"name",
"=",
"self",
".",
"match_string_pattern",
"(",
"spat",
".",
"alphal",
")",
"if",
"not",
"name",
":",
"raise",
"PartpyError",
"... | Email address parsing is done in several stages.
First the name of the email use is determined.
Then it looks for a '@' as a delimiter between the name and the site.
Lastly the email site is matched.
Each part's string is stored, combined and returned. | [
"Email",
"address",
"parsing",
"is",
"done",
"in",
"several",
"stages",
".",
"First",
"the",
"name",
"of",
"the",
"email",
"use",
"is",
"determined",
".",
"Then",
"it",
"looks",
"for",
"a",
"@",
"as",
"a",
"delimiter",
"between",
"the",
"name",
"and",
... | python | train |
mitsei/dlkit | dlkit/json_/assessment_authoring/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment_authoring/sessions.py#L1295-L1313 | def get_assessment_parts_by_banks(self, bank_ids):
"""Gets the list of assessment part corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.authoring.AssessmentPartList) - list of
assessment parts
raise: NullArgument - ``bank_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resources_by_bins
assessment_part_list = []
for bank_id in bank_ids:
assessment_part_list += list(
self.get_assessment_parts_by_bank(bank_id))
return objects.AssessmentPartList(assessment_part_list) | [
"def",
"get_assessment_parts_by_banks",
"(",
"self",
",",
"bank_ids",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_resources_by_bins",
"assessment_part_list",
"=",
"[",
"]",
"for",
"bank_id",
"in",
"bank_ids",
":",
"assessment_part_list",... | Gets the list of assessment part corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.authoring.AssessmentPartList) - list of
assessment parts
raise: NullArgument - ``bank_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"list",
"of",
"assessment",
"part",
"corresponding",
"to",
"a",
"list",
"of",
"Banks",
"."
] | python | train |
hyperledger-archives/indy-client | sovrin_client/client/wallet/wallet.py | https://github.com/hyperledger-archives/indy-client/blob/b5633dd7767b4aaf08f622181f3937a104b290fb/sovrin_client/client/wallet/wallet.py#L291-L300 | def requestAttribute(self, attrib: Attribute, sender):
"""
Used to get a raw attribute from Sovrin
:param attrib: attribute to add
:return: number of pending txns
"""
self._attributes[attrib.key()] = attrib
req = attrib.getRequest(sender)
if req:
return self.prepReq(req, key=attrib.key()) | [
"def",
"requestAttribute",
"(",
"self",
",",
"attrib",
":",
"Attribute",
",",
"sender",
")",
":",
"self",
".",
"_attributes",
"[",
"attrib",
".",
"key",
"(",
")",
"]",
"=",
"attrib",
"req",
"=",
"attrib",
".",
"getRequest",
"(",
"sender",
")",
"if",
... | Used to get a raw attribute from Sovrin
:param attrib: attribute to add
:return: number of pending txns | [
"Used",
"to",
"get",
"a",
"raw",
"attribute",
"from",
"Sovrin",
":",
"param",
"attrib",
":",
"attribute",
"to",
"add",
":",
"return",
":",
"number",
"of",
"pending",
"txns"
] | python | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/server.py | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L271-L277 | def PublicIPs(self):
"""Returns PublicIPs object associated with the server.
"""
if not self.public_ips: self.public_ips = clc.v2.PublicIPs(server=self,public_ips_lst=self.ip_addresses,session=self.session)
return(self.public_ips) | [
"def",
"PublicIPs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"public_ips",
":",
"self",
".",
"public_ips",
"=",
"clc",
".",
"v2",
".",
"PublicIPs",
"(",
"server",
"=",
"self",
",",
"public_ips_lst",
"=",
"self",
".",
"ip_addresses",
",",
"sessi... | Returns PublicIPs object associated with the server. | [
"Returns",
"PublicIPs",
"object",
"associated",
"with",
"the",
"server",
"."
] | python | train |
chaoss/grimoirelab-manuscripts | manuscripts2/elasticsearch.py | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts2/elasticsearch.py#L493-L533 | def get_timeseries(self, child_agg_count=0, dataframe=False):
"""
Get time series data for the specified fields and period of analysis
:param child_agg_count: the child aggregation count to be used
default = 0
:param dataframe: if dataframe=True, return a pandas.DataFrame object
:returns: dictionary containing "date", "value" and "unixtime" keys
with lists as values containing data from each bucket in the
aggregation
"""
res = self.fetch_aggregation_results()
ts = {"date": [], "value": [], "unixtime": []}
if 'buckets' not in res['aggregations'][str(self.parent_agg_counter - 1)]:
raise RuntimeError("Aggregation results have no buckets in time series results.")
for bucket in res['aggregations'][str(self.parent_agg_counter - 1)]['buckets']:
ts['date'].append(parser.parse(bucket['key_as_string']).date())
if str(child_agg_count) in bucket:
# We have a subaggregation with the value
# If it is percentiles we get the median
if 'values' in bucket[str(child_agg_count)]:
val = bucket[str(child_agg_count)]['values']['50.0']
if val == 'NaN':
# ES returns NaN. Convert to None for matplotlib graph
val = None
ts['value'].append(val)
else:
ts['value'].append(bucket[str(child_agg_count)]['value'])
else:
ts['value'].append(bucket['doc_count'])
# unixtime comes in ms from ElasticSearch
ts['unixtime'].append(bucket['key'] / 1000)
if dataframe:
df = pd.DataFrame.from_records(ts, index="date")
return df.fillna(0)
return ts | [
"def",
"get_timeseries",
"(",
"self",
",",
"child_agg_count",
"=",
"0",
",",
"dataframe",
"=",
"False",
")",
":",
"res",
"=",
"self",
".",
"fetch_aggregation_results",
"(",
")",
"ts",
"=",
"{",
"\"date\"",
":",
"[",
"]",
",",
"\"value\"",
":",
"[",
"]"... | Get time series data for the specified fields and period of analysis
:param child_agg_count: the child aggregation count to be used
default = 0
:param dataframe: if dataframe=True, return a pandas.DataFrame object
:returns: dictionary containing "date", "value" and "unixtime" keys
with lists as values containing data from each bucket in the
aggregation | [
"Get",
"time",
"series",
"data",
"for",
"the",
"specified",
"fields",
"and",
"period",
"of",
"analysis"
] | python | train |
six8/corona-cipr | src/cipr/commands/cfg.py | https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/cfg.py#L73-L84 | def add_package(self, package):
"""
Add a package to this project
"""
self._data.setdefault('packages', {})
self._data['packages'][package.name] = package.source
for package in package.deploy_packages:
self.add_package(package)
self._save() | [
"def",
"add_package",
"(",
"self",
",",
"package",
")",
":",
"self",
".",
"_data",
".",
"setdefault",
"(",
"'packages'",
",",
"{",
"}",
")",
"self",
".",
"_data",
"[",
"'packages'",
"]",
"[",
"package",
".",
"name",
"]",
"=",
"package",
".",
"source"... | Add a package to this project | [
"Add",
"a",
"package",
"to",
"this",
"project"
] | python | train |
sepandhaghighi/pycm | setup.py | https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/setup.py#L15-L33 | def read_description():
"""Read README.md and CHANGELOG.md."""
try:
with open("README.md") as r:
description = "\n"
description += r.read()
with open("CHANGELOG.md") as c:
description += "\n"
description += c.read()
return description
except Exception:
return '''
PyCM is a multi-class confusion matrix library written in Python that
supports both input data vectors and direct matrix, and a proper tool for
post-classification model evaluation that supports most classes and overall
statistics parameters.
PyCM is the swiss-army knife of confusion matrices, targeted mainly at
data scientists that need a broad array of metrics for predictive models
and an accurate evaluation of large variety of classifiers.''' | [
"def",
"read_description",
"(",
")",
":",
"try",
":",
"with",
"open",
"(",
"\"README.md\"",
")",
"as",
"r",
":",
"description",
"=",
"\"\\n\"",
"description",
"+=",
"r",
".",
"read",
"(",
")",
"with",
"open",
"(",
"\"CHANGELOG.md\"",
")",
"as",
"c",
":... | Read README.md and CHANGELOG.md. | [
"Read",
"README",
".",
"md",
"and",
"CHANGELOG",
".",
"md",
"."
] | python | train |
Clinical-Genomics/scout | scout/adapter/mongo/matchmaker.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/matchmaker.py#L10-L50 | def case_mme_update(self, case_obj, user_obj, mme_subm_obj):
"""Updates a case after a submission to MatchMaker Exchange
Args:
case_obj(dict): a scout case object
user_obj(dict): a scout user object
mme_subm_obj(dict): contains MME submission params and server response
Returns:
updated_case(dict): the updated scout case
"""
created = None
patient_ids = []
updated = datetime.now()
if 'mme_submission' in case_obj and case_obj['mme_submission']:
created = case_obj['mme_submission']['created_at']
else:
created = updated
patients = [ resp['patient'] for resp in mme_subm_obj.get('server_responses')]
subm_obj = {
'created_at' : created,
'updated_at' : updated,
'patients' : patients, # list of submitted patient data
'subm_user' : user_obj['_id'], # submitting user
'sex' : mme_subm_obj['sex'],
'features' : mme_subm_obj['features'],
'disorders' : mme_subm_obj['disorders'],
'genes_only' : mme_subm_obj['genes_only']
}
case_obj['mme_submission'] = subm_obj
updated_case = self.update_case(case_obj)
# create events for subjects add in MatchMaker for this case
institute_obj = self.institute(case_obj['owner'])
for individual in case_obj['individuals']:
if individual['phenotype'] == 2: # affected
# create event for patient
self.create_event(institute=institute_obj, case=case_obj, user=user_obj,
link='', category='case', verb='mme_add', subject=individual['display_name'],
level='specific')
return updated_case | [
"def",
"case_mme_update",
"(",
"self",
",",
"case_obj",
",",
"user_obj",
",",
"mme_subm_obj",
")",
":",
"created",
"=",
"None",
"patient_ids",
"=",
"[",
"]",
"updated",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"'mme_submission'",
"in",
"case_obj",
"and... | Updates a case after a submission to MatchMaker Exchange
Args:
case_obj(dict): a scout case object
user_obj(dict): a scout user object
mme_subm_obj(dict): contains MME submission params and server response
Returns:
updated_case(dict): the updated scout case | [
"Updates",
"a",
"case",
"after",
"a",
"submission",
"to",
"MatchMaker",
"Exchange",
"Args",
":",
"case_obj",
"(",
"dict",
")",
":",
"a",
"scout",
"case",
"object",
"user_obj",
"(",
"dict",
")",
":",
"a",
"scout",
"user",
"object",
"mme_subm_obj",
"(",
"d... | python | test |
oanda/v20-python | src/v20/order.py | https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/order.py#L4732-L4747 | def trailing_stop_loss(self, accountID, **kwargs):
"""
Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request
"""
return self.create(
accountID,
order=TrailingStopLossOrderRequest(**kwargs)
) | [
"def",
"trailing_stop_loss",
"(",
"self",
",",
"accountID",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"create",
"(",
"accountID",
",",
"order",
"=",
"TrailingStopLossOrderRequest",
"(",
"*",
"*",
"kwargs",
")",
")"
] | Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request | [
"Shortcut",
"to",
"create",
"a",
"Trailing",
"Stop",
"Loss",
"Order",
"in",
"an",
"Account"
] | python | train |
andreafioraldi/angrdbg | angrdbg/page_7.py | https://github.com/andreafioraldi/angrdbg/blob/939b20fb9b341aee695d2db12142b1eddc5b555a/angrdbg/page_7.py#L868-L873 | def memory_objects_for_hash(self, n):
"""
Returns a set of :class:`SimMemoryObjects` that contain expressions that contain a variable with the hash
`h`.
"""
return set([self[i] for i in self.addrs_for_hash(n)]) | [
"def",
"memory_objects_for_hash",
"(",
"self",
",",
"n",
")",
":",
"return",
"set",
"(",
"[",
"self",
"[",
"i",
"]",
"for",
"i",
"in",
"self",
".",
"addrs_for_hash",
"(",
"n",
")",
"]",
")"
] | Returns a set of :class:`SimMemoryObjects` that contain expressions that contain a variable with the hash
`h`. | [
"Returns",
"a",
"set",
"of",
":",
"class",
":",
"SimMemoryObjects",
"that",
"contain",
"expressions",
"that",
"contain",
"a",
"variable",
"with",
"the",
"hash",
"h",
"."
] | python | train |
idlesign/uwsgiconf | uwsgiconf/config.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/config.py#L393-L415 | def env(self, key, value=None, unset=False, asap=False):
"""Processes (sets/unsets) environment variable.
If is not given in `set` mode value will be taken from current env.
:param str|unicode key:
:param value:
:param bool unset: Whether to unset this variable.
:param bool asap: If True env variable will be set as soon as possible.
"""
if unset:
self._set('unenv', key, multi=True)
else:
if value is None:
value = os.environ.get(key)
self._set('%senv' % ('i' if asap else ''), '%s=%s' % (key, value), multi=True)
return self | [
"def",
"env",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
",",
"unset",
"=",
"False",
",",
"asap",
"=",
"False",
")",
":",
"if",
"unset",
":",
"self",
".",
"_set",
"(",
"'unenv'",
",",
"key",
",",
"multi",
"=",
"True",
")",
"else",
":",... | Processes (sets/unsets) environment variable.
If is not given in `set` mode value will be taken from current env.
:param str|unicode key:
:param value:
:param bool unset: Whether to unset this variable.
:param bool asap: If True env variable will be set as soon as possible. | [
"Processes",
"(",
"sets",
"/",
"unsets",
")",
"environment",
"variable",
"."
] | python | train |
clld/clldutils | src/clldutils/misc.py | https://github.com/clld/clldutils/blob/7b8587ef5b56a2fc6cafaff90bc5004355c2b13f/src/clldutils/misc.py#L75-L85 | def dict_merged(d, _filter=None, **kw):
"""Update dictionary d with the items passed as kw if the value passes _filter."""
def f(s):
if _filter:
return _filter(s)
return s is not None
d = d or {}
for k, v in iteritems(kw):
if f(v):
d[k] = v
return d | [
"def",
"dict_merged",
"(",
"d",
",",
"_filter",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"def",
"f",
"(",
"s",
")",
":",
"if",
"_filter",
":",
"return",
"_filter",
"(",
"s",
")",
"return",
"s",
"is",
"not",
"None",
"d",
"=",
"d",
"or",
"{"... | Update dictionary d with the items passed as kw if the value passes _filter. | [
"Update",
"dictionary",
"d",
"with",
"the",
"items",
"passed",
"as",
"kw",
"if",
"the",
"value",
"passes",
"_filter",
"."
] | python | train |
TracyWebTech/django-revproxy | revproxy/views.py | https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/views.py#L140-L143 | def get_encoded_query_params(self):
"""Return encoded query params to be used in proxied request"""
get_data = encode_items(self.request.GET.lists())
return urlencode(get_data) | [
"def",
"get_encoded_query_params",
"(",
"self",
")",
":",
"get_data",
"=",
"encode_items",
"(",
"self",
".",
"request",
".",
"GET",
".",
"lists",
"(",
")",
")",
"return",
"urlencode",
"(",
"get_data",
")"
] | Return encoded query params to be used in proxied request | [
"Return",
"encoded",
"query",
"params",
"to",
"be",
"used",
"in",
"proxied",
"request"
] | python | train |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/monitoring.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/monitoring.py#L283-L288 | def _to_micros(dur):
"""Convert duration 'dur' to microseconds."""
if hasattr(dur, 'total_seconds'):
return int(dur.total_seconds() * 10e5)
# Python 2.6
return dur.microseconds + (dur.seconds + dur.days * 24 * 3600) * 1000000 | [
"def",
"_to_micros",
"(",
"dur",
")",
":",
"if",
"hasattr",
"(",
"dur",
",",
"'total_seconds'",
")",
":",
"return",
"int",
"(",
"dur",
".",
"total_seconds",
"(",
")",
"*",
"10e5",
")",
"# Python 2.6",
"return",
"dur",
".",
"microseconds",
"+",
"(",
"du... | Convert duration 'dur' to microseconds. | [
"Convert",
"duration",
"dur",
"to",
"microseconds",
"."
] | python | train |
ktdreyer/txkoji | txkoji/estimates.py | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/estimates.py#L84-L103 | def average_last_builds(connection, package, limit=5):
"""
Find the average duration time for the last couple of builds.
:param connection: txkoji.Connection
:param package: package name
:returns: deferred that when fired returns a datetime.timedelta object, or
None if there were no previous builds for this package.
"""
# TODO: take branches (targets, or tags, etc) into account when estimating
# a package's build time.
state = build_states.COMPLETE
opts = {'limit': limit, 'order': '-completion_time'}
builds = yield connection.listBuilds(package, state=state, queryOpts=opts)
if not builds:
defer.returnValue(None)
durations = [build.duration for build in builds]
average = sum(durations, timedelta()) / len(durations)
# print('average duration for %s is %s' % (package, average))
defer.returnValue(average) | [
"def",
"average_last_builds",
"(",
"connection",
",",
"package",
",",
"limit",
"=",
"5",
")",
":",
"# TODO: take branches (targets, or tags, etc) into account when estimating",
"# a package's build time.",
"state",
"=",
"build_states",
".",
"COMPLETE",
"opts",
"=",
"{",
"... | Find the average duration time for the last couple of builds.
:param connection: txkoji.Connection
:param package: package name
:returns: deferred that when fired returns a datetime.timedelta object, or
None if there were no previous builds for this package. | [
"Find",
"the",
"average",
"duration",
"time",
"for",
"the",
"last",
"couple",
"of",
"builds",
"."
] | python | train |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L436-L441 | def set_ttl(self):
"""Parses summary and set value"""
try:
self.ttl = self.soup.find('ttl').string
except AttributeError:
self.ttl = None | [
"def",
"set_ttl",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"ttl",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'ttl'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"ttl",
"=",
"None"
] | Parses summary and set value | [
"Parses",
"summary",
"and",
"set",
"value"
] | python | train |
aio-libs/aioftp | aioftp/client.py | https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/client.py#L365-L388 | def parse_ls_date(self, s, *, now=None):
"""
Parsing dates from the ls unix utility. For example,
"Nov 18 1958" and "Nov 18 12:29".
:param s: ls date
:type s: :py:class:`str`
:rtype: :py:class:`str`
"""
with setlocale("C"):
try:
if now is None:
now = datetime.datetime.now()
d = datetime.datetime.strptime(s, "%b %d %H:%M")
d = d.replace(year=now.year)
diff = (now - d).total_seconds()
if diff > HALF_OF_YEAR_IN_SECONDS:
d = d.replace(year=now.year + 1)
elif diff < -HALF_OF_YEAR_IN_SECONDS:
d = d.replace(year=now.year - 1)
except ValueError:
d = datetime.datetime.strptime(s, "%b %d %Y")
return self.format_date_time(d) | [
"def",
"parse_ls_date",
"(",
"self",
",",
"s",
",",
"*",
",",
"now",
"=",
"None",
")",
":",
"with",
"setlocale",
"(",
"\"C\"",
")",
":",
"try",
":",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
... | Parsing dates from the ls unix utility. For example,
"Nov 18 1958" and "Nov 18 12:29".
:param s: ls date
:type s: :py:class:`str`
:rtype: :py:class:`str` | [
"Parsing",
"dates",
"from",
"the",
"ls",
"unix",
"utility",
".",
"For",
"example",
"Nov",
"18",
"1958",
"and",
"Nov",
"18",
"12",
":",
"29",
"."
] | python | valid |
napalm-automation/napalm-logs | napalm_logs/listener/udp.py | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/udp.py#L64-L74 | def receive(self):
'''
Return the message received and the address.
'''
try:
msg, addr = self.skt.recvfrom(self.buffer_size)
except socket.error as error:
log.error('Received listener socket error: %s', error, exc_info=True)
raise ListenerException(error)
log.debug('[%s] Received %s from %s', msg, addr, time.time())
return msg, addr[0] | [
"def",
"receive",
"(",
"self",
")",
":",
"try",
":",
"msg",
",",
"addr",
"=",
"self",
".",
"skt",
".",
"recvfrom",
"(",
"self",
".",
"buffer_size",
")",
"except",
"socket",
".",
"error",
"as",
"error",
":",
"log",
".",
"error",
"(",
"'Received listen... | Return the message received and the address. | [
"Return",
"the",
"message",
"received",
"and",
"the",
"address",
"."
] | python | train |
ChristianTremblay/BAC0 | BAC0/core/devices/Device.py | https://github.com/ChristianTremblay/BAC0/blob/8d95b065ea068524a08f5b0c34322ebeeba95d06/BAC0/core/devices/Device.py#L677-L727 | def connect(self, *, db=None):
"""
Attempt to connect to device. If unable, attempt to connect to a controller database
(so the user can use previously saved data).
"""
if not self.properties.network:
self.new_state(DeviceFromDB)
else:
try:
name = self.properties.network.read(
"{} device {} objectName".format(
self.properties.address, self.properties.device_id
)
)
segmentation = self.properties.network.read(
"{} device {} segmentationSupported".format(
self.properties.address, self.properties.device_id
)
)
if not self.segmentation_supported or segmentation not in (
"segmentedTransmit",
"segmentedBoth",
):
segmentation_supported = False
self._log.debug("Segmentation not supported")
else:
segmentation_supported = True
if name:
if segmentation_supported:
self.new_state(RPMDeviceConnected)
else:
self.new_state(RPDeviceConnected)
except SegmentationNotSupported:
self.segmentation_supported = False
self._log.warning(
"Segmentation not supported.... expect slow responses."
)
self.new_state(RPDeviceConnected)
except (NoResponseFromController, AttributeError) as error:
if self.properties.db_name:
self.new_state(DeviceFromDB)
else:
self._log.warning(
"Offline: provide database name to load stored data."
)
self._log.warning("Ex. controller.connect(db = 'backup')") | [
"def",
"connect",
"(",
"self",
",",
"*",
",",
"db",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"properties",
".",
"network",
":",
"self",
".",
"new_state",
"(",
"DeviceFromDB",
")",
"else",
":",
"try",
":",
"name",
"=",
"self",
".",
"properti... | Attempt to connect to device. If unable, attempt to connect to a controller database
(so the user can use previously saved data). | [
"Attempt",
"to",
"connect",
"to",
"device",
".",
"If",
"unable",
"attempt",
"to",
"connect",
"to",
"a",
"controller",
"database",
"(",
"so",
"the",
"user",
"can",
"use",
"previously",
"saved",
"data",
")",
"."
] | python | train |
fbcotter/py3nvml | py3nvml/py3nvml.py | https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L1351-L1400 | def nvmlUnitGetHandleByIndex(index):
r"""
/**
* Acquire the handle for a particular unit, based on its index.
*
* For S-class products.
*
* Valid indices are derived from the \a unitCount returned by \ref nvmlUnitGetCount().
* For example, if \a unitCount is 2 the valid indices are 0 and 1, corresponding to UNIT 0 and UNIT 1.
*
* The order in which NVML enumerates units has no guarantees of consistency between reboots.
*
* @param index The index of the target unit, >= 0 and < \a unitCount
* @param unit Reference in which to return the unit handle
*
* @return
* - \ref NVML_SUCCESS if \a unit has been set
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a index is invalid or \a unit is NULL
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*/
nvmlReturn_t DECLDIR nvmlUnitGetHandleByIndex
"""
"""
/**
* Acquire the handle for a particular unit, based on its index.
*
* For S-class products.
*
* Valid indices are derived from the \a unitCount returned by \ref nvmlUnitGetCount().
* For example, if \a unitCount is 2 the valid indices are 0 and 1, corresponding to UNIT 0 and UNIT 1.
*
* The order in which NVML enumerates units has no guarantees of consistency between reboots.
*
* @param index The index of the target unit, >= 0 and < \a unitCount
* @param unit Reference in which to return the unit handle
*
* @return
* - \ref NVML_SUCCESS if \a unit has been set
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a index is invalid or \a unit is NULL
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*/
"""
c_index = c_uint(index)
unit = c_nvmlUnit_t()
fn = _nvmlGetFunctionPointer("nvmlUnitGetHandleByIndex")
ret = fn(c_index, byref(unit))
_nvmlCheckReturn(ret)
return bytes_to_str(unit) | [
"def",
"nvmlUnitGetHandleByIndex",
"(",
"index",
")",
":",
"\"\"\"\n/**\n * Acquire the handle for a particular unit, based on its index.\n *\n * For S-class products.\n *\n * Valid indices are derived from the \\a unitCount returned by \\ref nvmlUnitGetCount().\n * For example, if \\a unitCount is 2 ... | r"""
/**
* Acquire the handle for a particular unit, based on its index.
*
* For S-class products.
*
* Valid indices are derived from the \a unitCount returned by \ref nvmlUnitGetCount().
* For example, if \a unitCount is 2 the valid indices are 0 and 1, corresponding to UNIT 0 and UNIT 1.
*
* The order in which NVML enumerates units has no guarantees of consistency between reboots.
*
* @param index The index of the target unit, >= 0 and < \a unitCount
* @param unit Reference in which to return the unit handle
*
* @return
* - \ref NVML_SUCCESS if \a unit has been set
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a index is invalid or \a unit is NULL
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*/
nvmlReturn_t DECLDIR nvmlUnitGetHandleByIndex | [
"r",
"/",
"**",
"*",
"Acquire",
"the",
"handle",
"for",
"a",
"particular",
"unit",
"based",
"on",
"its",
"index",
".",
"*",
"*",
"For",
"S",
"-",
"class",
"products",
".",
"*",
"*",
"Valid",
"indices",
"are",
"derived",
"from",
"the",
"\\",
"a",
"u... | python | train |
michael-lazar/rtv | rtv/packages/praw/objects.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/objects.py#L1268-L1278 | def get_flair_choices(self, *args, **kwargs):
"""Return available link flair choices and current flair.
Convenience function for
:meth:`~.AuthenticatedReddit.get_flair_choices` populating both the
`subreddit` and `link` parameters.
:returns: The json response from the server.
"""
return self.subreddit.get_flair_choices(self.fullname, *args, **kwargs) | [
"def",
"get_flair_choices",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"subreddit",
".",
"get_flair_choices",
"(",
"self",
".",
"fullname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Return available link flair choices and current flair.
Convenience function for
:meth:`~.AuthenticatedReddit.get_flair_choices` populating both the
`subreddit` and `link` parameters.
:returns: The json response from the server. | [
"Return",
"available",
"link",
"flair",
"choices",
"and",
"current",
"flair",
"."
] | python | train |
mozilla-iot/webthing-python | webthing/server.py | https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/server.py#L363-L397 | def put(self, thing_id='0', property_name=None):
"""
Handle a PUT request.
thing_id -- ID of the thing this request is for
property_name -- the name of the property from the URL path
"""
thing = self.get_thing(thing_id)
if thing is None:
self.set_status(404)
return
try:
args = json.loads(self.request.body.decode())
except ValueError:
self.set_status(400)
return
if property_name not in args:
self.set_status(400)
return
if thing.has_property(property_name):
try:
thing.set_property(property_name, args[property_name])
except PropertyError:
self.set_status(400)
return
self.set_header('Content-Type', 'application/json')
self.write(json.dumps({
property_name: thing.get_property(property_name),
}))
else:
self.set_status(404) | [
"def",
"put",
"(",
"self",
",",
"thing_id",
"=",
"'0'",
",",
"property_name",
"=",
"None",
")",
":",
"thing",
"=",
"self",
".",
"get_thing",
"(",
"thing_id",
")",
"if",
"thing",
"is",
"None",
":",
"self",
".",
"set_status",
"(",
"404",
")",
"return",... | Handle a PUT request.
thing_id -- ID of the thing this request is for
property_name -- the name of the property from the URL path | [
"Handle",
"a",
"PUT",
"request",
"."
] | python | test |
sorgerlab/indra | indra/sources/geneways/find_full_text_sentence.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/find_full_text_sentence.py#L33-L49 | def get_sentences(self, root_element, block_tags):
"""Returns a list of plain-text sentences by iterating through
XML tags except for those listed in block_tags."""
sentences = []
for element in root_element:
if not self.any_ends_with(block_tags, element.tag):
# tag not in block_tags
if element.text is not None and not re.match('^\s*$',
element.text):
sentences.extend(self.sentence_tokenize(element.text))
sentences.extend(self.get_sentences(element, block_tags))
f = open('sentence_debug.txt', 'w')
for s in sentences:
f.write(s.lower() + '\n')
f.close()
return sentences | [
"def",
"get_sentences",
"(",
"self",
",",
"root_element",
",",
"block_tags",
")",
":",
"sentences",
"=",
"[",
"]",
"for",
"element",
"in",
"root_element",
":",
"if",
"not",
"self",
".",
"any_ends_with",
"(",
"block_tags",
",",
"element",
".",
"tag",
")",
... | Returns a list of plain-text sentences by iterating through
XML tags except for those listed in block_tags. | [
"Returns",
"a",
"list",
"of",
"plain",
"-",
"text",
"sentences",
"by",
"iterating",
"through",
"XML",
"tags",
"except",
"for",
"those",
"listed",
"in",
"block_tags",
"."
] | python | train |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/isogeo_sdk.py | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/isogeo_sdk.py#L559-L590 | def licenses(
self, token: dict = None, owner_id: str = None, prot: str = "https"
) -> dict:
"""Get information about licenses owned by a specific workgroup.
:param str token: API auth token
:param str owner_id: workgroup UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
"""
# handling request parameters
payload = {"gid": owner_id}
# search request
licenses_url = "{}://v1.{}.isogeo.com/groups/{}/licenses".format(
prot, self.api_url, owner_id
)
licenses_req = self.get(
licenses_url,
headers=self.header,
params=payload,
proxies=self.proxies,
verify=self.ssl,
)
# checking response
req_check = checker.check_api_response(licenses_req)
if isinstance(req_check, tuple):
return req_check
# end of method
return licenses_req.json() | [
"def",
"licenses",
"(",
"self",
",",
"token",
":",
"dict",
"=",
"None",
",",
"owner_id",
":",
"str",
"=",
"None",
",",
"prot",
":",
"str",
"=",
"\"https\"",
")",
"->",
"dict",
":",
"# handling request parameters",
"payload",
"=",
"{",
"\"gid\"",
":",
"... | Get information about licenses owned by a specific workgroup.
:param str token: API auth token
:param str owner_id: workgroup UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | [
"Get",
"information",
"about",
"licenses",
"owned",
"by",
"a",
"specific",
"workgroup",
"."
] | python | train |
titusjan/argos | argos/widgets/mainwindow.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L778-L783 | def activateAndRaise(self):
""" Activates and raises the window.
"""
logger.debug("Activate and raising window: {}".format(self.windowNumber))
self.activateWindow()
self.raise_() | [
"def",
"activateAndRaise",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Activate and raising window: {}\"",
".",
"format",
"(",
"self",
".",
"windowNumber",
")",
")",
"self",
".",
"activateWindow",
"(",
")",
"self",
".",
"raise_",
"(",
")"
] | Activates and raises the window. | [
"Activates",
"and",
"raises",
"the",
"window",
"."
] | python | train |
django-danceschool/django-danceschool | danceschool/core/classreg.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L440-L492 | def get_context_data(self,**kwargs):
''' Pass the initial kwargs, then update with the needed registration info. '''
context_data = super(RegistrationSummaryView,self).get_context_data(**kwargs)
regSession = self.request.session[REG_VALIDATION_STR]
reg_id = regSession["temp_reg_id"]
reg = TemporaryRegistration.objects.get(id=reg_id)
discount_codes = regSession.get('discount_codes',None)
discount_amount = regSession.get('total_discount_amount',0)
voucher_names = regSession.get('voucher_names',[])
total_voucher_amount = regSession.get('total_voucher_amount',0)
addons = regSession.get('addons',[])
if reg.priceWithDiscount == 0:
# Create a new Invoice if one does not already exist.
new_invoice = Invoice.get_or_create_from_registration(reg,status=Invoice.PaymentStatus.paid)
new_invoice.processPayment(0,0,forceFinalize=True)
isFree = True
else:
isFree = False
context_data.update({
'registration': reg,
"totalPrice": reg.totalPrice,
'subtotal': reg.priceWithDiscount,
'taxes': reg.addTaxes,
"netPrice": reg.priceWithDiscountAndTaxes,
"addonItems": addons,
"discount_codes": discount_codes,
"discount_code_amount": discount_amount,
"voucher_names": voucher_names,
"total_voucher_amount": total_voucher_amount,
"total_discount_amount": discount_amount + total_voucher_amount,
"currencyCode": getConstant('general__currencyCode'),
'payAtDoor': reg.payAtDoor,
'is_free': isFree,
})
if self.request.user:
door_permission = self.request.user.has_perm('core.accept_door_payments')
invoice_permission = self.request.user.has_perm('core.send_invoices')
if door_permission or invoice_permission:
context_data['form'] = DoorAmountForm(
user=self.request.user,
doorPortion=door_permission,
invoicePortion=invoice_permission,
payerEmail=reg.email,
discountAmount=max(reg.totalPrice - reg.priceWithDiscount,0),
)
return context_data | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context_data",
"=",
"super",
"(",
"RegistrationSummaryView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"regSession",
"=",
"self",
".",
"request",
"."... | Pass the initial kwargs, then update with the needed registration info. | [
"Pass",
"the",
"initial",
"kwargs",
"then",
"update",
"with",
"the",
"needed",
"registration",
"info",
"."
] | python | train |
pylp/pylp | pylp/cli/logger.py | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/cli/logger.py#L63-L67 | def log(*texts, sep = ""):
"""Log a text."""
text = sep.join(texts)
count = text.count("\n")
just_log("\n" * count, *get_time(), text.replace("\n", ""), sep=sep) | [
"def",
"log",
"(",
"*",
"texts",
",",
"sep",
"=",
"\"\"",
")",
":",
"text",
"=",
"sep",
".",
"join",
"(",
"texts",
")",
"count",
"=",
"text",
".",
"count",
"(",
"\"\\n\"",
")",
"just_log",
"(",
"\"\\n\"",
"*",
"count",
",",
"*",
"get_time",
"(",
... | Log a text. | [
"Log",
"a",
"text",
"."
] | python | train |
odlgroup/odl | odl/set/sets.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/set/sets.py#L471-L476 | def contains_all(self, other):
"""Return ``True`` if ``other`` is a sequence of integers."""
dtype = getattr(other, 'dtype', None)
if dtype is None:
dtype = np.result_type(*other)
return is_int_dtype(dtype) | [
"def",
"contains_all",
"(",
"self",
",",
"other",
")",
":",
"dtype",
"=",
"getattr",
"(",
"other",
",",
"'dtype'",
",",
"None",
")",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"np",
".",
"result_type",
"(",
"*",
"other",
")",
"return",
"is_int_d... | Return ``True`` if ``other`` is a sequence of integers. | [
"Return",
"True",
"if",
"other",
"is",
"a",
"sequence",
"of",
"integers",
"."
] | python | train |
celiao/tmdbsimple | tmdbsimple/account.py | https://github.com/celiao/tmdbsimple/blob/ff17893110c99771d6398a62c35d36dd9735f4b9/tmdbsimple/account.py#L43-L58 | def info(self, **kwargs):
"""
Get the basic information for an account.
Call this method first, before calling other Account methods.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('info')
kwargs.update({'session_id': self.session_id})
response = self._GET(path, kwargs)
self.id = response['id']
self._set_attrs_to_values(response)
return response | [
"def",
"info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"'info'",
")",
"kwargs",
".",
"update",
"(",
"{",
"'session_id'",
":",
"self",
".",
"session_id",
"}",
")",
"response",
"=",
"self",
".",
"_G... | Get the basic information for an account.
Call this method first, before calling other Account methods.
Returns:
A dict respresentation of the JSON returned from the API. | [
"Get",
"the",
"basic",
"information",
"for",
"an",
"account",
"."
] | python | test |
happyleavesaoc/python-limitlessled | limitlessled/group/white.py | https://github.com/happyleavesaoc/python-limitlessled/blob/70307c2bf8c91430a99579d2ad18b228ec7a8488/limitlessled/group/white.py#L79-L96 | def transition(self, duration, brightness=None, temperature=None):
""" Transition wrapper.
Short-circuit transition if necessary.
:param duration: Duration of transition.
:param brightness: Transition to this brightness.
:param temperature: Transition to this temperature.
"""
# Transition immediately if duration is zero.
if duration == 0:
if brightness is not None:
self.brightness = brightness
if temperature is not None:
self.temperature = temperature
return
if brightness != self.brightness or temperature != self.temperature:
self._transition(duration, brightness, temperature) | [
"def",
"transition",
"(",
"self",
",",
"duration",
",",
"brightness",
"=",
"None",
",",
"temperature",
"=",
"None",
")",
":",
"# Transition immediately if duration is zero.",
"if",
"duration",
"==",
"0",
":",
"if",
"brightness",
"is",
"not",
"None",
":",
"self... | Transition wrapper.
Short-circuit transition if necessary.
:param duration: Duration of transition.
:param brightness: Transition to this brightness.
:param temperature: Transition to this temperature. | [
"Transition",
"wrapper",
"."
] | python | train |
kislyuk/aegea | aegea/packages/github3/orgs.py | https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/orgs.py#L500-L506 | def publicize_member(self, login):
"""Make ``login``'s membership in this organization public.
:returns: bool
"""
url = self._build_url('public_members', login, base_url=self._api)
return self._boolean(self._put(url), 204, 404) | [
"def",
"publicize_member",
"(",
"self",
",",
"login",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'public_members'",
",",
"login",
",",
"base_url",
"=",
"self",
".",
"_api",
")",
"return",
"self",
".",
"_boolean",
"(",
"self",
".",
"_put",
"... | Make ``login``'s membership in this organization public.
:returns: bool | [
"Make",
"login",
"s",
"membership",
"in",
"this",
"organization",
"public",
"."
] | python | train |
OpenKMIP/PyKMIP | kmip/core/attributes.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/attributes.py#L921-L940 | def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Digest object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
"""
tstream = BytearrayStream()
self.hashing_algorithm.write(tstream, kmip_version=kmip_version)
self.digest_value.write(tstream, kmip_version=kmip_version)
self.key_format_type.write(tstream, kmip_version=kmip_version)
self.length = tstream.length()
super(Digest, self).write(ostream, kmip_version=kmip_version)
ostream.write(tstream.buffer) | [
"def",
"write",
"(",
"self",
",",
"ostream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"tstream",
"=",
"BytearrayStream",
"(",
")",
"self",
".",
"hashing_algorithm",
".",
"write",
"(",
"tstream",
",",
"kmip_version",
... | Write the data encoding the Digest object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0. | [
"Write",
"the",
"data",
"encoding",
"the",
"Digest",
"object",
"to",
"a",
"stream",
"."
] | python | test |
shoebot/shoebot | lib/graph/event.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/event.py#L61-L105 | def update(self):
""" Interacts with the graph by clicking or dragging nodes.
Hovering a node fires the callback function events.hover().
Clicking a node fires the callback function events.click().
"""
if self.mousedown:
# When not pressing or dragging, check each node.
if not self.pressed and not self.dragged:
for n in self.graph.nodes:
if self.mouse in n:
self.pressed = n
break
# If a node is pressed, check if a drag is started.
elif self.pressed and not self.mouse in self.pressed:
self.dragged = self.pressed
self.pressed = None
# Drag the node (right now only for springgraphs).
elif self.dragged and self.graph.layout.type == "spring":
self.drag(self.dragged)
self.graph.layout.i = min(100, max(2, self.graph.layout.n-100))
# Mouse is clicked on a node, fire callback.
elif self.pressed and self.mouse in self.pressed:
self.clicked = self.pressed
self.pressed = None
self.graph.layout.i = 2
self.click(self.clicked)
# Mouse up.
else:
self.hovered = None
self.pressed = None
self.dragged = None
# Hovering over a node?
for n in self.graph.nodes:
if self.mouse in n:
self.hovered = n
self.hover(n)
break | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"mousedown",
":",
"# When not pressing or dragging, check each node.",
"if",
"not",
"self",
".",
"pressed",
"and",
"not",
"self",
".",
"dragged",
":",
"for",
"n",
"in",
"self",
".",
"graph",
".",
"... | Interacts with the graph by clicking or dragging nodes.
Hovering a node fires the callback function events.hover().
Clicking a node fires the callback function events.click(). | [
"Interacts",
"with",
"the",
"graph",
"by",
"clicking",
"or",
"dragging",
"nodes",
".",
"Hovering",
"a",
"node",
"fires",
"the",
"callback",
"function",
"events",
".",
"hover",
"()",
".",
"Clicking",
"a",
"node",
"fires",
"the",
"callback",
"function",
"event... | python | valid |
ioos/compliance-checker | compliance_checker/base.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/base.py#L208-L219 | def std_check_in(dataset, name, allowed_vals):
"""
Returns 0 if attr not present, 1 if present but not in correct value, 2 if good
"""
if not hasattr(dataset, name):
return 0
ret_val = 1
if getattr(dataset, name) in allowed_vals:
ret_val += 1
return ret_val | [
"def",
"std_check_in",
"(",
"dataset",
",",
"name",
",",
"allowed_vals",
")",
":",
"if",
"not",
"hasattr",
"(",
"dataset",
",",
"name",
")",
":",
"return",
"0",
"ret_val",
"=",
"1",
"if",
"getattr",
"(",
"dataset",
",",
"name",
")",
"in",
"allowed_vals... | Returns 0 if attr not present, 1 if present but not in correct value, 2 if good | [
"Returns",
"0",
"if",
"attr",
"not",
"present",
"1",
"if",
"present",
"but",
"not",
"in",
"correct",
"value",
"2",
"if",
"good"
] | python | train |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/manip.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/manip.py#L53-L121 | def prune_shell(shell, use_copy=True):
"""
Removes exact duplicates of primitives, and condenses duplicate exponents
into general contractions
Also removes primitives if all coefficients are zero
"""
new_exponents = []
new_coefficients = []
exponents = shell['exponents']
nprim = len(exponents)
# transpose of the coefficient matrix
coeff_t = list(map(list, zip(*shell['coefficients'])))
# Group by exponents
ex_groups = []
for i in range(nprim):
for ex in ex_groups:
if float(exponents[i]) == float(ex[0]):
ex[1].append(coeff_t[i])
break
else:
ex_groups.append((exponents[i], [coeff_t[i]]))
# Now collapse within groups
for ex in ex_groups:
if len(ex[1]) == 1:
# only add if there is a nonzero contraction coefficient
if not all([float(x) == 0.0 for x in ex[1][0]]):
new_exponents.append(ex[0])
new_coefficients.append(ex[1][0])
continue
# ex[1] contains rows of coefficients. The length of ex[1]
# is the number of times the exponent is duplicated. Columns represent general contractions.
# We want to find the non-zero coefficient in each column, if it exists
# The result is a single row with a length representing the number
# of general contractions
new_coeff_row = []
# so take yet another transpose.
ex_coeff = list(map(list, zip(*ex[1])))
for g in ex_coeff:
nonzero = [x for x in g if float(x) != 0.0]
if len(nonzero) > 1:
raise RuntimeError("Exponent {} is duplicated within a contraction".format(ex[0]))
if len(nonzero) == 0:
new_coeff_row.append(g[0])
else:
new_coeff_row.append(nonzero[0])
# only add if there is a nonzero contraction coefficient anywhere for this exponent
if not all([float(x) == 0.0 for x in new_coeff_row]):
new_exponents.append(ex[0])
new_coefficients.append(new_coeff_row)
# take the transpose again, putting the general contraction
# as the slowest index
new_coefficients = list(map(list, zip(*new_coefficients)))
shell['exponents'] = new_exponents
shell['coefficients'] = new_coefficients
return shell | [
"def",
"prune_shell",
"(",
"shell",
",",
"use_copy",
"=",
"True",
")",
":",
"new_exponents",
"=",
"[",
"]",
"new_coefficients",
"=",
"[",
"]",
"exponents",
"=",
"shell",
"[",
"'exponents'",
"]",
"nprim",
"=",
"len",
"(",
"exponents",
")",
"# transpose of t... | Removes exact duplicates of primitives, and condenses duplicate exponents
into general contractions
Also removes primitives if all coefficients are zero | [
"Removes",
"exact",
"duplicates",
"of",
"primitives",
"and",
"condenses",
"duplicate",
"exponents",
"into",
"general",
"contractions"
] | python | train |
Kozea/cairocffi | cairocffi/surfaces.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L1153-L1167 | def set_eps(self, eps):
"""
If :obj:`eps` is True,
the PostScript surface will output Encapsulated PostScript.
This method should only be called
before any drawing operations have been performed on the current page.
The simplest way to do this is to call this method
immediately after creating the surface.
An Encapsulated PostScript file should never contain
more than one page.
"""
cairo.cairo_ps_surface_set_eps(self._pointer, bool(eps))
self._check_status() | [
"def",
"set_eps",
"(",
"self",
",",
"eps",
")",
":",
"cairo",
".",
"cairo_ps_surface_set_eps",
"(",
"self",
".",
"_pointer",
",",
"bool",
"(",
"eps",
")",
")",
"self",
".",
"_check_status",
"(",
")"
] | If :obj:`eps` is True,
the PostScript surface will output Encapsulated PostScript.
This method should only be called
before any drawing operations have been performed on the current page.
The simplest way to do this is to call this method
immediately after creating the surface.
An Encapsulated PostScript file should never contain
more than one page. | [
"If",
":",
"obj",
":",
"eps",
"is",
"True",
"the",
"PostScript",
"surface",
"will",
"output",
"Encapsulated",
"PostScript",
"."
] | python | train |
suds-community/suds | tools/suds_devel/egg.py | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/egg.py#L144-L175 | def _detect_eggs_in_folder(folder):
"""
Detect egg distributions located in the given folder.
Only direct folder content is considered and subfolders are not searched
recursively.
"""
eggs = {}
for x in os.listdir(folder):
zip = x.endswith(_zip_ext)
if zip:
root = x[:-len(_zip_ext)]
egg = _Egg.NONE
elif x.endswith(_egg_ext):
root = x[:-len(_egg_ext)]
if os.path.isdir(os.path.join(folder, x)):
egg = _Egg.FOLDER
else:
egg = _Egg.FILE
else:
continue
try:
info = eggs[root]
except KeyError:
eggs[root] = _Egg(os.path.join(folder, root), egg, zip)
else:
if egg is not _Egg.NONE:
info.set_egg(egg)
if zip:
info.set_zip()
return eggs.values() | [
"def",
"_detect_eggs_in_folder",
"(",
"folder",
")",
":",
"eggs",
"=",
"{",
"}",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"folder",
")",
":",
"zip",
"=",
"x",
".",
"endswith",
"(",
"_zip_ext",
")",
"if",
"zip",
":",
"root",
"=",
"x",
"[",
":"... | Detect egg distributions located in the given folder.
Only direct folder content is considered and subfolders are not searched
recursively. | [
"Detect",
"egg",
"distributions",
"located",
"in",
"the",
"given",
"folder",
".",
"Only",
"direct",
"folder",
"content",
"is",
"considered",
"and",
"subfolders",
"are",
"not",
"searched",
"recursively",
"."
] | python | train |
camsci/meteor-pi | src/pythonModules/meteorpi_db/meteorpi_db/__init__.py | https://github.com/camsci/meteor-pi/blob/7b01527650bd1b2b76d6f364e8122e25b8812c8d/src/pythonModules/meteorpi_db/meteorpi_db/__init__.py#L962-L1011 | def create_or_update_user(self, user_id, password, roles):
"""
Create a new user record, or update an existing one
:param user_id:
user ID to update or create
:param password:
new password, or None to leave unchanged
:param roles:
new roles, or None to leave unchanged
:return:
the action taken, one of "none", "update", "create"
:raises:
ValueError if there is no existing user and either password or roles is None
"""
action = "update"
self.con.execute('SELECT 1 FROM archive_users WHERE userId = %s;', (user_id,))
results = self.con.fetchall()
if len(results) == 0:
if password is None:
raise ValueError("Must specify an initial password when creating a new user!")
action = "create"
self.con.execute('INSERT INTO archive_users (userId, pwHash) VALUES (%s,%s)',
(user_id, passlib.hash.bcrypt.encrypt(password)))
if password is None and roles is None:
action = "none"
if password is not None:
self.con.execute('UPDATE archive_users SET pwHash = %s WHERE userId = %s',
(passlib.hash.bcrypt.encrypt(password), user_id))
if roles is not None:
# Clear out existing roles, and delete any unused roles
self.con.execute("DELETE r FROM archive_user_roles AS r WHERE "
"(SELECT u.userId FROM archive_users AS u WHERE r.userId=u.uid)=%s;", (user_id,))
self.con.execute("DELETE r FROM archive_roles AS r WHERE r.uid NOT IN "
"(SELECT roleId FROM archive_user_roles);")
for role in roles:
self.con.execute("SELECT uid FROM archive_roles WHERE name=%s;", (role,))
results = self.con.fetchall()
if len(results) < 1:
self.con.execute("INSERT INTO archive_roles (name) VALUES (%s);", (role,))
self.con.execute("SELECT uid FROM archive_roles WHERE name=%s;", (role,))
results = self.con.fetchall()
self.con.execute('INSERT INTO archive_user_roles (userId, roleId) VALUES '
'((SELECT u.uid FROM archive_users u WHERE u.userId=%s),'
'%s)', (user_id, results[0]['uid']))
return action | [
"def",
"create_or_update_user",
"(",
"self",
",",
"user_id",
",",
"password",
",",
"roles",
")",
":",
"action",
"=",
"\"update\"",
"self",
".",
"con",
".",
"execute",
"(",
"'SELECT 1 FROM archive_users WHERE userId = %s;'",
",",
"(",
"user_id",
",",
")",
")",
... | Create a new user record, or update an existing one
:param user_id:
user ID to update or create
:param password:
new password, or None to leave unchanged
:param roles:
new roles, or None to leave unchanged
:return:
the action taken, one of "none", "update", "create"
:raises:
ValueError if there is no existing user and either password or roles is None | [
"Create",
"a",
"new",
"user",
"record",
"or",
"update",
"an",
"existing",
"one"
] | python | train |
OSLL/jabba | jabba/file_index.py | https://github.com/OSLL/jabba/blob/71c1d008ab497020fba6ffa12a600721eb3f5ef7/jabba/file_index.py#L182-L196 | def include_raw_constructor(self, loader, node):
"""
Called when PyYaml encounters '!include-raw'
"""
path = convert_path(node.value)
with open(path, 'r') as f:
config = f.read()
config = self.inject_include_info(path, config, include_type='include-raw')
self.add_file(path, config)
return config | [
"def",
"include_raw_constructor",
"(",
"self",
",",
"loader",
",",
"node",
")",
":",
"path",
"=",
"convert_path",
"(",
"node",
".",
"value",
")",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"config",
"=",
"f",
".",
"read",
"(",
")... | Called when PyYaml encounters '!include-raw' | [
"Called",
"when",
"PyYaml",
"encounters",
"!include",
"-",
"raw"
] | python | train |
wavycloud/pyboto3 | pyboto3/snowball.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/snowball.py#L1077-L1184 | def update_job(JobId=None, RoleARN=None, Notification=None, Resources=None, AddressId=None, ShippingOption=None, Description=None, SnowballCapacityPreference=None, ForwardingAddressId=None):
"""
While a job's JobState value is New , you can update some of the information associated with a job. Once the job changes to a different job state, usually within 60 minutes of the job being created, this action is no longer available.
See also: AWS API Documentation
Examples
This action allows you to update certain parameters for a job. Once the job changes to a different job state, usually within 60 minutes of the job being created, this action is no longer available.
Expected Output:
:example: response = client.update_job(
JobId='string',
RoleARN='string',
Notification={
'SnsTopicARN': 'string',
'JobStatesToNotify': [
'New'|'PreparingAppliance'|'PreparingShipment'|'InTransitToCustomer'|'WithCustomer'|'InTransitToAWS'|'WithAWS'|'InProgress'|'Complete'|'Cancelled'|'Listing'|'Pending',
],
'NotifyAll': True|False
},
Resources={
'S3Resources': [
{
'BucketArn': 'string',
'KeyRange': {
'BeginMarker': 'string',
'EndMarker': 'string'
}
},
],
'LambdaResources': [
{
'LambdaArn': 'string',
'EventTriggers': [
{
'EventResourceARN': 'string'
},
]
},
]
},
AddressId='string',
ShippingOption='SECOND_DAY'|'NEXT_DAY'|'EXPRESS'|'STANDARD',
Description='string',
SnowballCapacityPreference='T50'|'T80'|'T100'|'NoPreference',
ForwardingAddressId='string'
)
:type JobId: string
:param JobId: [REQUIRED]
The job ID of the job that you want to update, for example JID123e4567-e89b-12d3-a456-426655440000 .
:type RoleARN: string
:param RoleARN: The new role Amazon Resource Name (ARN) that you want to associate with this job. To create a role ARN, use the CreateRole AWS Identity and Access Management (IAM) API action.
:type Notification: dict
:param Notification: The new or updated Notification object.
SnsTopicARN (string) --The new SNS TopicArn that you want to associate with this job. You can create Amazon Resource Names (ARNs) for topics by using the CreateTopic Amazon SNS API action.
You can subscribe email addresses to an Amazon SNS topic through the AWS Management Console, or by using the Subscribe AWS Simple Notification Service (SNS) API action.
JobStatesToNotify (list) --The list of job states that will trigger a notification for this job.
(string) --
NotifyAll (boolean) --Any change in job state will trigger a notification for this job.
:type Resources: dict
:param Resources: The updated S3Resource object (for a single Amazon S3 bucket or key range), or the updated JobResource object (for multiple buckets or key ranges).
S3Resources (list) --An array of S3Resource objects.
(dict) --Each S3Resource object represents an Amazon S3 bucket that your transferred data will be exported from or imported into. For export jobs, this object can have an optional KeyRange value. The length of the range is defined at job creation, and has either an inclusive BeginMarker , an inclusive EndMarker , or both. Ranges are UTF-8 binary sorted.
BucketArn (string) --The Amazon Resource Name (ARN) of an Amazon S3 bucket.
KeyRange (dict) --For export jobs, you can provide an optional KeyRange within a specific Amazon S3 bucket. The length of the range is defined at job creation, and has either an inclusive BeginMarker , an inclusive EndMarker , or both. Ranges are UTF-8 binary sorted.
BeginMarker (string) --The key that starts an optional key range for an export job. Ranges are inclusive and UTF-8 binary sorted.
EndMarker (string) --The key that ends an optional key range for an export job. Ranges are inclusive and UTF-8 binary sorted.
LambdaResources (list) --The Python-language Lambda functions for this job.
(dict) --Identifies
LambdaArn (string) --An Amazon Resource Name (ARN) that represents an AWS Lambda function to be triggered by PUT object actions on the associated local Amazon S3 resource.
EventTriggers (list) --The array of ARNs for S3Resource objects to trigger the LambdaResource objects associated with this job.
(dict) --The container for the EventTriggerDefinition$EventResourceARN .
EventResourceARN (string) --The Amazon Resource Name (ARN) for any local Amazon S3 resource that is an AWS Lambda function's event trigger associated with this job.
:type AddressId: string
:param AddressId: The ID of the updated Address object.
:type ShippingOption: string
:param ShippingOption: The updated shipping option value of this job's ShippingDetails object.
:type Description: string
:param Description: The updated description of this job's JobMetadata object.
:type SnowballCapacityPreference: string
:param SnowballCapacityPreference: The updated SnowballCapacityPreference of this job's JobMetadata object. The 50 TB Snowballs are only available in the US regions.
:type ForwardingAddressId: string
:param ForwardingAddressId: The updated ID for the forwarding address for a job. This field is not supported in most regions.
:rtype: dict
:return: {}
:returns:
(dict) --
"""
pass | [
"def",
"update_job",
"(",
"JobId",
"=",
"None",
",",
"RoleARN",
"=",
"None",
",",
"Notification",
"=",
"None",
",",
"Resources",
"=",
"None",
",",
"AddressId",
"=",
"None",
",",
"ShippingOption",
"=",
"None",
",",
"Description",
"=",
"None",
",",
"Snowba... | While a job's JobState value is New , you can update some of the information associated with a job. Once the job changes to a different job state, usually within 60 minutes of the job being created, this action is no longer available.
See also: AWS API Documentation
Examples
This action allows you to update certain parameters for a job. Once the job changes to a different job state, usually within 60 minutes of the job being created, this action is no longer available.
Expected Output:
:example: response = client.update_job(
JobId='string',
RoleARN='string',
Notification={
'SnsTopicARN': 'string',
'JobStatesToNotify': [
'New'|'PreparingAppliance'|'PreparingShipment'|'InTransitToCustomer'|'WithCustomer'|'InTransitToAWS'|'WithAWS'|'InProgress'|'Complete'|'Cancelled'|'Listing'|'Pending',
],
'NotifyAll': True|False
},
Resources={
'S3Resources': [
{
'BucketArn': 'string',
'KeyRange': {
'BeginMarker': 'string',
'EndMarker': 'string'
}
},
],
'LambdaResources': [
{
'LambdaArn': 'string',
'EventTriggers': [
{
'EventResourceARN': 'string'
},
]
},
]
},
AddressId='string',
ShippingOption='SECOND_DAY'|'NEXT_DAY'|'EXPRESS'|'STANDARD',
Description='string',
SnowballCapacityPreference='T50'|'T80'|'T100'|'NoPreference',
ForwardingAddressId='string'
)
:type JobId: string
:param JobId: [REQUIRED]
The job ID of the job that you want to update, for example JID123e4567-e89b-12d3-a456-426655440000 .
:type RoleARN: string
:param RoleARN: The new role Amazon Resource Name (ARN) that you want to associate with this job. To create a role ARN, use the CreateRole AWS Identity and Access Management (IAM) API action.
:type Notification: dict
:param Notification: The new or updated Notification object.
SnsTopicARN (string) --The new SNS TopicArn that you want to associate with this job. You can create Amazon Resource Names (ARNs) for topics by using the CreateTopic Amazon SNS API action.
You can subscribe email addresses to an Amazon SNS topic through the AWS Management Console, or by using the Subscribe AWS Simple Notification Service (SNS) API action.
JobStatesToNotify (list) --The list of job states that will trigger a notification for this job.
(string) --
NotifyAll (boolean) --Any change in job state will trigger a notification for this job.
:type Resources: dict
:param Resources: The updated S3Resource object (for a single Amazon S3 bucket or key range), or the updated JobResource object (for multiple buckets or key ranges).
S3Resources (list) --An array of S3Resource objects.
(dict) --Each S3Resource object represents an Amazon S3 bucket that your transferred data will be exported from or imported into. For export jobs, this object can have an optional KeyRange value. The length of the range is defined at job creation, and has either an inclusive BeginMarker , an inclusive EndMarker , or both. Ranges are UTF-8 binary sorted.
BucketArn (string) --The Amazon Resource Name (ARN) of an Amazon S3 bucket.
KeyRange (dict) --For export jobs, you can provide an optional KeyRange within a specific Amazon S3 bucket. The length of the range is defined at job creation, and has either an inclusive BeginMarker , an inclusive EndMarker , or both. Ranges are UTF-8 binary sorted.
BeginMarker (string) --The key that starts an optional key range for an export job. Ranges are inclusive and UTF-8 binary sorted.
EndMarker (string) --The key that ends an optional key range for an export job. Ranges are inclusive and UTF-8 binary sorted.
LambdaResources (list) --The Python-language Lambda functions for this job.
(dict) --Identifies
LambdaArn (string) --An Amazon Resource Name (ARN) that represents an AWS Lambda function to be triggered by PUT object actions on the associated local Amazon S3 resource.
EventTriggers (list) --The array of ARNs for S3Resource objects to trigger the LambdaResource objects associated with this job.
(dict) --The container for the EventTriggerDefinition$EventResourceARN .
EventResourceARN (string) --The Amazon Resource Name (ARN) for any local Amazon S3 resource that is an AWS Lambda function's event trigger associated with this job.
:type AddressId: string
:param AddressId: The ID of the updated Address object.
:type ShippingOption: string
:param ShippingOption: The updated shipping option value of this job's ShippingDetails object.
:type Description: string
:param Description: The updated description of this job's JobMetadata object.
:type SnowballCapacityPreference: string
:param SnowballCapacityPreference: The updated SnowballCapacityPreference of this job's JobMetadata object. The 50 TB Snowballs are only available in the US regions.
:type ForwardingAddressId: string
:param ForwardingAddressId: The updated ID for the forwarding address for a job. This field is not supported in most regions.
:rtype: dict
:return: {}
:returns:
(dict) -- | [
"While",
"a",
"job",
"s",
"JobState",
"value",
"is",
"New",
"you",
"can",
"update",
"some",
"of",
"the",
"information",
"associated",
"with",
"a",
"job",
".",
"Once",
"the",
"job",
"changes",
"to",
"a",
"different",
"job",
"state",
"usually",
"within",
"... | python | train |
saltstack/salt | salt/states/azurearm_network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L2254-L2314 | def route_table_absent(name, resource_group, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a route table does not exist in the resource group.
:param name:
Name of the route table.
:param resource_group:
The resource group assigned to the route table.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
rt_tbl = __salt__['azurearm_network.route_table_get'](
name,
resource_group,
azurearm_log_level='info',
**connection_auth
)
if 'error' in rt_tbl:
ret['result'] = True
ret['comment'] = 'Route table {0} was not found.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Route table {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': rt_tbl,
'new': {},
}
return ret
deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Route table {0} has been deleted.'.format(name)
ret['changes'] = {
'old': rt_tbl,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete route table {0}!'.format(name)
return ret | [
"def",
"route_table_absent",
"(",
"name",
",",
"resource_group",
",",
"connection_auth",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"i... | .. versionadded:: 2019.2.0
Ensure a route table does not exist in the resource group.
:param name:
Name of the route table.
:param resource_group:
The resource group assigned to the route table.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API. | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsHandle_Edit.py | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsHandle_Edit.py#L424-L433 | def _Start_refresh_timer(self):
""" Internal method to support auto-refresh functionality. """
if self._refreshPeriod > 60:
interval = self._refreshPeriod - 60
else:
interval = 60
self._refreshTimer = Timer(self._refreshPeriod, self.Refresh)
# TODO:handle exit and logout active connections. revert from daemon then
self._refreshTimer.setDaemon(True)
self._refreshTimer.start() | [
"def",
"_Start_refresh_timer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_refreshPeriod",
">",
"60",
":",
"interval",
"=",
"self",
".",
"_refreshPeriod",
"-",
"60",
"else",
":",
"interval",
"=",
"60",
"self",
".",
"_refreshTimer",
"=",
"Timer",
"(",
"se... | Internal method to support auto-refresh functionality. | [
"Internal",
"method",
"to",
"support",
"auto",
"-",
"refresh",
"functionality",
"."
] | python | train |
vatlab/SoS | src/sos/task_engines.py | https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/task_engines.py#L651-L702 | def _submit_task_with_template(self, task_ids):
'''Submit tasks by interpolating a shell script defined in job_template'''
runtime = self.config
runtime.update({
'workdir': os.getcwd(),
'cur_dir': os.getcwd(), # for backward compatibility
'verbosity': env.verbosity,
'sig_mode': env.config.get('sig_mode', 'default'),
'run_mode': env.config.get('run_mode', 'run'),
'home_dir': os.path.expanduser('~')
})
if '_runtime' in env.sos_dict:
runtime.update({
x: env.sos_dict['_runtime'][x]
for x in ('nodes', 'cores', 'workdir', 'mem', 'walltime')
if x in env.sos_dict['_runtime']
})
if 'nodes' not in runtime:
runtime['nodes'] = 1
if 'cores' not in runtime:
runtime['cores'] = 1
# let us first prepare a task file
job_text = ''
for task_id in task_ids:
runtime['task'] = task_id
try:
job_text += cfg_interpolate(self.job_template, runtime)
job_text += '\n'
except Exception as e:
raise ValueError(
f'Failed to generate job file for task {task_id}: {e}')
filename = task_ids[0] + ('.sh' if len(task_ids) == 1 else
f'-{task_ids[-1]}.sh')
# now we need to write a job file
job_file = os.path.join(
os.path.expanduser('~'), '.sos', 'tasks', filename)
# do not translate newline under windows because the script will be executed
# under linux/mac
with open(job_file, 'w', newline='') as job:
job.write(job_text)
# then copy the job file to remote host if necessary
self.agent.send_task_file(job_file)
try:
cmd = f'bash ~/.sos/tasks/{filename}'
self.agent.run_command(cmd, wait_for_task=self.wait_for_task)
except Exception as e:
raise RuntimeError(f'Failed to submit task {task_ids}: {e}')
return True | [
"def",
"_submit_task_with_template",
"(",
"self",
",",
"task_ids",
")",
":",
"runtime",
"=",
"self",
".",
"config",
"runtime",
".",
"update",
"(",
"{",
"'workdir'",
":",
"os",
".",
"getcwd",
"(",
")",
",",
"'cur_dir'",
":",
"os",
".",
"getcwd",
"(",
")... | Submit tasks by interpolating a shell script defined in job_template | [
"Submit",
"tasks",
"by",
"interpolating",
"a",
"shell",
"script",
"defined",
"in",
"job_template"
] | python | train |
tanghaibao/goatools | goatools/grouper/sorter_nts.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_nts.py#L71-L86 | def get_sorted_nts_omit_section(self, hdrgo_prt, hdrgo_sort):
"""Return a flat list of sections (wo/section names) with GO terms grouped and sorted."""
nts_flat = []
# print("SSSS SorterNts:get_sorted_nts_omit_section(hdrgo_prt={}, hdrgo_sort={})".format(
# hdrgo_prt, hdrgo_sort))
hdrgos_seen = set()
hdrgos_actual = self.sortgos.grprobj.get_hdrgos()
for _, section_hdrgos_all in self.sections:
#section_hdrgos_act = set(section_hdrgos_all).intersection(hdrgos_actual)
section_hdrgos_act = [h for h in section_hdrgos_all if h in hdrgos_actual]
hdrgos_seen |= set(section_hdrgos_act)
self.sortgos.get_sorted_hdrgo2usrgos(
section_hdrgos_act, nts_flat, hdrgo_prt, hdrgo_sort)
remaining_hdrgos = set(self.sortgos.grprobj.get_hdrgos()).difference(hdrgos_seen)
self.sortgos.get_sorted_hdrgo2usrgos(remaining_hdrgos, nts_flat, hdrgo_prt, hdrgo_sort)
return nts_flat | [
"def",
"get_sorted_nts_omit_section",
"(",
"self",
",",
"hdrgo_prt",
",",
"hdrgo_sort",
")",
":",
"nts_flat",
"=",
"[",
"]",
"# print(\"SSSS SorterNts:get_sorted_nts_omit_section(hdrgo_prt={}, hdrgo_sort={})\".format(",
"# hdrgo_prt, hdrgo_sort))",
"hdrgos_seen",
"=",
"set",
... | Return a flat list of sections (wo/section names) with GO terms grouped and sorted. | [
"Return",
"a",
"flat",
"list",
"of",
"sections",
"(",
"wo",
"/",
"section",
"names",
")",
"with",
"GO",
"terms",
"grouped",
"and",
"sorted",
"."
] | python | train |
buildinspace/peru | peru/main.py | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/main.py#L334-L344 | def force_utf8_in_ascii_mode_hack():
'''In systems without a UTF8 locale configured, Python will default to
ASCII mode for stdout and stderr. This causes our fancy display to fail
with encoding errors. In particular, you run into this if you try to run
peru inside of Docker. This is a hack to force emitting UTF8 in that case.
Hopefully it doesn't break anything important.'''
if sys.stdout.encoding == 'ANSI_X3.4-1968':
sys.stdout = open(
sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
sys.stderr = open(
sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1) | [
"def",
"force_utf8_in_ascii_mode_hack",
"(",
")",
":",
"if",
"sys",
".",
"stdout",
".",
"encoding",
"==",
"'ANSI_X3.4-1968'",
":",
"sys",
".",
"stdout",
"=",
"open",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
",",
"mode",
"=",
"'w'",
",",
"enc... | In systems without a UTF8 locale configured, Python will default to
ASCII mode for stdout and stderr. This causes our fancy display to fail
with encoding errors. In particular, you run into this if you try to run
peru inside of Docker. This is a hack to force emitting UTF8 in that case.
Hopefully it doesn't break anything important. | [
"In",
"systems",
"without",
"a",
"UTF8",
"locale",
"configured",
"Python",
"will",
"default",
"to",
"ASCII",
"mode",
"for",
"stdout",
"and",
"stderr",
".",
"This",
"causes",
"our",
"fancy",
"display",
"to",
"fail",
"with",
"encoding",
"errors",
".",
"In",
... | python | train |
shoebot/shoebot | shoebot/grammar/drawbot.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L311-L319 | def textpath(self, txt, x, y, width=None, height=1000000, enableRendering=False, **kwargs):
'''
Draws an outlined path of the input text
'''
txt = self.Text(txt, x, y, width, height, **kwargs)
path = txt.path
if draw:
path.draw()
return path | [
"def",
"textpath",
"(",
"self",
",",
"txt",
",",
"x",
",",
"y",
",",
"width",
"=",
"None",
",",
"height",
"=",
"1000000",
",",
"enableRendering",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"txt",
"=",
"self",
".",
"Text",
"(",
"txt",
",",
... | Draws an outlined path of the input text | [
"Draws",
"an",
"outlined",
"path",
"of",
"the",
"input",
"text"
] | python | valid |
rootpy/rootpy | rootpy/plotting/views.py | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/views.py#L307-L316 | def Get(self, path):
''' Get the (modified) object from path '''
self.getting = path
try:
obj = self.dir.Get(path)
return self.apply_view(obj)
except DoesNotExist as dne:
#print dir(dne)
raise DoesNotExist(
str(dne) + "[{0}]".format(self.__class__.__name__)) | [
"def",
"Get",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"getting",
"=",
"path",
"try",
":",
"obj",
"=",
"self",
".",
"dir",
".",
"Get",
"(",
"path",
")",
"return",
"self",
".",
"apply_view",
"(",
"obj",
")",
"except",
"DoesNotExist",
"as",
... | Get the (modified) object from path | [
"Get",
"the",
"(",
"modified",
")",
"object",
"from",
"path"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_image_transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L435-L449 | def mtf_image_transformer_single():
"""Small single parameters."""
hparams = mtf_image_transformer_tiny()
hparams.mesh_shape = ""
hparams.layout = ""
hparams.hidden_size = 32
hparams.filter_size = 32
hparams.batch_size = 1
hparams.num_encoder_layers = 1
hparams.num_decoder_layers = 1
hparams.num_heads = 2
hparams.attention_key_size = 32
hparams.attention_value_size = 32
hparams.block_length = 16
return hparams | [
"def",
"mtf_image_transformer_single",
"(",
")",
":",
"hparams",
"=",
"mtf_image_transformer_tiny",
"(",
")",
"hparams",
".",
"mesh_shape",
"=",
"\"\"",
"hparams",
".",
"layout",
"=",
"\"\"",
"hparams",
".",
"hidden_size",
"=",
"32",
"hparams",
".",
"filter_size... | Small single parameters. | [
"Small",
"single",
"parameters",
"."
] | python | train |
PyGithub/PyGithub | github/AuthenticatedUser.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/AuthenticatedUser.py#L509-L527 | def create_key(self, title, key):
"""
:calls: `POST /user/keys <http://developer.github.com/v3/users/keys>`_
:param title: string
:param key: string
:rtype: :class:`github.UserKey.UserKey`
"""
assert isinstance(title, (str, unicode)), title
assert isinstance(key, (str, unicode)), key
post_parameters = {
"title": title,
"key": key,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
"/user/keys",
input=post_parameters
)
return github.UserKey.UserKey(self._requester, headers, data, completed=True) | [
"def",
"create_key",
"(",
"self",
",",
"title",
",",
"key",
")",
":",
"assert",
"isinstance",
"(",
"title",
",",
"(",
"str",
",",
"unicode",
")",
")",
",",
"title",
"assert",
"isinstance",
"(",
"key",
",",
"(",
"str",
",",
"unicode",
")",
")",
",",... | :calls: `POST /user/keys <http://developer.github.com/v3/users/keys>`_
:param title: string
:param key: string
:rtype: :class:`github.UserKey.UserKey` | [
":",
"calls",
":",
"POST",
"/",
"user",
"/",
"keys",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"users",
"/",
"keys",
">",
"_",
":",
"param",
"title",
":",
"string",
":",
"param",
"key",
":",
"string",
":",
"rtype... | python | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L962-L971 | def make_html_patterns():
"""Strongly inspired from idlelib.ColorDelegator.make_pat """
tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
keywords = any("keyword", [r" [\w:-]*?(?==)"])
string = any("string", [r'".*?"'])
comment = any("comment", [r"<!--.*?-->"])
multiline_comment_start = any("multiline_comment_start", [r"<!--"])
multiline_comment_end = any("multiline_comment_end", [r"-->"])
return "|".join([comment, multiline_comment_start,
multiline_comment_end, tags, keywords, string]) | [
"def",
"make_html_patterns",
"(",
")",
":",
"tags",
"=",
"any",
"(",
"\"builtin\"",
",",
"[",
"r\"<\"",
",",
"r\"[\\?/]?>\"",
",",
"r\"(?<=<).*?(?=[ >])\"",
"]",
")",
"keywords",
"=",
"any",
"(",
"\"keyword\"",
",",
"[",
"r\" [\\w:-]*?(?==)\"",
"]",
")",
"st... | Strongly inspired from idlelib.ColorDelegator.make_pat | [
"Strongly",
"inspired",
"from",
"idlelib",
".",
"ColorDelegator",
".",
"make_pat"
] | python | train |
alex-kostirin/pyatomac | atomac/ldtpd/combo_box.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/combo_box.py#L241-L258 | def hidelist(self, window_name, object_name):
"""
Hide combo box list / menu
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type object_name: string
@return: 1 on success.
@rtype: integer
"""
object_handle = self._get_object_handle(window_name, object_name)
object_handle.activate()
object_handle.sendKey(AXKeyCodeConstants.ESCAPE)
return 1 | [
"def",
"hidelist",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"object_handle",
"=",
"self",
".",
"_get_object_handle",
"(",
"window_name",
",",
"object_name",
")",
"object_handle",
".",
"activate",
"(",
")",
"object_handle",
".",
"sendKey",
... | Hide combo box list / menu
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type object_name: string
@return: 1 on success.
@rtype: integer | [
"Hide",
"combo",
"box",
"list",
"/",
"menu",
"@param",
"window_name",
":",
"Window",
"name",
"to",
"type",
"in",
"either",
"full",
"name",
"LDTP",
"s",
"name",
"convention",
"or",
"a",
"Unix",
"glob",
".",
"@type",
"window_name",
":",
"string",
"@param",
... | python | valid |
justquick/django-activity-stream | actstream/managers.py | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L33-L39 | def target(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the target.
Keyword arguments will be passed to Action.objects.filter
"""
check(obj)
return obj.target_actions.public(**kwargs) | [
"def",
"target",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"check",
"(",
"obj",
")",
"return",
"obj",
".",
"target_actions",
".",
"public",
"(",
"*",
"*",
"kwargs",
")"
] | Stream of most recent actions where obj is the target.
Keyword arguments will be passed to Action.objects.filter | [
"Stream",
"of",
"most",
"recent",
"actions",
"where",
"obj",
"is",
"the",
"target",
".",
"Keyword",
"arguments",
"will",
"be",
"passed",
"to",
"Action",
".",
"objects",
".",
"filter"
] | python | train |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L705-L710 | def _subtotals(self):
"""Composed tuple storing actual sequence of _Subtotal objects."""
return tuple(
_Subtotal(subtotal_dict, self.valid_elements)
for subtotal_dict in self._iter_valid_subtotal_dicts()
) | [
"def",
"_subtotals",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"_Subtotal",
"(",
"subtotal_dict",
",",
"self",
".",
"valid_elements",
")",
"for",
"subtotal_dict",
"in",
"self",
".",
"_iter_valid_subtotal_dicts",
"(",
")",
")"
] | Composed tuple storing actual sequence of _Subtotal objects. | [
"Composed",
"tuple",
"storing",
"actual",
"sequence",
"of",
"_Subtotal",
"objects",
"."
] | python | train |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L439-L448 | def bounds_to_space(bounds):
"""
Takes as input a list of tuples with bounds, and create a dictionary to be processed by the class Design_space. This function
us used to keep the compatibility with previous versions of GPyOpt in which only bounded continuous optimization was possible
(and the optimization domain passed as a list of tuples).
"""
space = []
for k in range(len(bounds)):
space += [{'name': 'var_'+str(k+1), 'type': 'continuous', 'domain':bounds[k], 'dimensionality':1}]
return space | [
"def",
"bounds_to_space",
"(",
"bounds",
")",
":",
"space",
"=",
"[",
"]",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"bounds",
")",
")",
":",
"space",
"+=",
"[",
"{",
"'name'",
":",
"'var_'",
"+",
"str",
"(",
"k",
"+",
"1",
")",
",",
"'type'"... | Takes as input a list of tuples with bounds, and create a dictionary to be processed by the class Design_space. This function
us used to keep the compatibility with previous versions of GPyOpt in which only bounded continuous optimization was possible
(and the optimization domain passed as a list of tuples). | [
"Takes",
"as",
"input",
"a",
"list",
"of",
"tuples",
"with",
"bounds",
"and",
"create",
"a",
"dictionary",
"to",
"be",
"processed",
"by",
"the",
"class",
"Design_space",
".",
"This",
"function",
"us",
"used",
"to",
"keep",
"the",
"compatibility",
"with",
"... | python | train |
potash/drain | drain/model.py | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/model.py#L164-L180 | def y_score(estimator, X):
"""
Score examples from a new matrix X
Args:
estimator: an sklearn estimator object
X: design matrix with the same features that the estimator was trained on
Returns: a vector of scores of the same length as X
Note that estimator.predict_proba is preferred but when unavailable
(e.g. SVM without probability calibration) decision_function is used.
"""
try:
y = estimator.predict_proba(X)
return y[:, 1]
except(AttributeError):
return estimator.decision_function(X) | [
"def",
"y_score",
"(",
"estimator",
",",
"X",
")",
":",
"try",
":",
"y",
"=",
"estimator",
".",
"predict_proba",
"(",
"X",
")",
"return",
"y",
"[",
":",
",",
"1",
"]",
"except",
"(",
"AttributeError",
")",
":",
"return",
"estimator",
".",
"decision_f... | Score examples from a new matrix X
Args:
estimator: an sklearn estimator object
X: design matrix with the same features that the estimator was trained on
Returns: a vector of scores of the same length as X
Note that estimator.predict_proba is preferred but when unavailable
(e.g. SVM without probability calibration) decision_function is used. | [
"Score",
"examples",
"from",
"a",
"new",
"matrix",
"X",
"Args",
":",
"estimator",
":",
"an",
"sklearn",
"estimator",
"object",
"X",
":",
"design",
"matrix",
"with",
"the",
"same",
"features",
"that",
"the",
"estimator",
"was",
"trained",
"on"
] | python | train |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L61-L74 | def set_main_style(widget):
"""Load the main.qss and apply it to the application
:param widget: The widget to apply the stylesheet to.
Can also be a QApplication. ``setStylesheet`` is called on the widget.
:type widget: :class:`QtGui.QWidget`
:returns: None
:rtype: None
:raises: None
"""
load_all_resources()
with open(MAIN_STYLESHEET, 'r') as qss:
sheet = qss.read()
widget.setStyleSheet(sheet) | [
"def",
"set_main_style",
"(",
"widget",
")",
":",
"load_all_resources",
"(",
")",
"with",
"open",
"(",
"MAIN_STYLESHEET",
",",
"'r'",
")",
"as",
"qss",
":",
"sheet",
"=",
"qss",
".",
"read",
"(",
")",
"widget",
".",
"setStyleSheet",
"(",
"sheet",
")"
] | Load the main.qss and apply it to the application
:param widget: The widget to apply the stylesheet to.
Can also be a QApplication. ``setStylesheet`` is called on the widget.
:type widget: :class:`QtGui.QWidget`
:returns: None
:rtype: None
:raises: None | [
"Load",
"the",
"main",
".",
"qss",
"and",
"apply",
"it",
"to",
"the",
"application"
] | python | train |
pandas-dev/pandas | pandas/core/indexes/base.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3086-L3142 | def reindex(self, target, method=None, level=None, limit=None,
tolerance=None):
"""
Create index with target's values (move/add/delete values
as necessary).
Parameters
----------
target : an iterable
Returns
-------
new_index : pd.Index
Resulting index.
indexer : np.ndarray or None
Indices of output values in original index.
"""
# GH6552: preserve names when reindexing to non-named target
# (i.e. neither Index nor Series).
preserve_names = not hasattr(target, 'name')
# GH7774: preserve dtype/tz if target is empty and not an Index.
target = _ensure_has_len(target) # target may be an iterator
if not isinstance(target, Index) and len(target) == 0:
attrs = self._get_attributes_dict()
attrs.pop('freq', None) # don't preserve freq
values = self._data[:0] # appropriately-dtyped empty array
target = self._simple_new(values, dtype=self.dtype, **attrs)
else:
target = ensure_index(target)
if level is not None:
if method is not None:
raise TypeError('Fill method not supported if level passed')
_, indexer, _ = self._join_level(target, level, how='right',
return_indexers=True)
else:
if self.equals(target):
indexer = None
else:
if self.is_unique:
indexer = self.get_indexer(target, method=method,
limit=limit,
tolerance=tolerance)
else:
if method is not None or limit is not None:
raise ValueError("cannot reindex a non-unique index "
"with a method or limit")
indexer, missing = self.get_indexer_non_unique(target)
if preserve_names and target.nlevels == 1 and target.name != self.name:
target = target.copy()
target.name = self.name
return target, indexer | [
"def",
"reindex",
"(",
"self",
",",
"target",
",",
"method",
"=",
"None",
",",
"level",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"tolerance",
"=",
"None",
")",
":",
"# GH6552: preserve names when reindexing to non-named target",
"# (i.e. neither Index nor Series... | Create index with target's values (move/add/delete values
as necessary).
Parameters
----------
target : an iterable
Returns
-------
new_index : pd.Index
Resulting index.
indexer : np.ndarray or None
Indices of output values in original index. | [
"Create",
"index",
"with",
"target",
"s",
"values",
"(",
"move",
"/",
"add",
"/",
"delete",
"values",
"as",
"necessary",
")",
"."
] | python | train |
JarryShaw/PyPCAPKit | src/utilities/validations.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L226-L236 | def pkt_check(*args, func=None):
"""Check if arguments are valid packets."""
func = func or inspect.stack()[2][3]
for var in args:
dict_check(var, func=func)
dict_check(var.get('frame'), func=func)
enum_check(var.get('protocol'), func=func)
real_check(var.get('timestamp'), func=func)
ip_check(var.get('src'), var.get('dst'), func=func)
bool_check(var.get('syn'), var.get('fin'), func=func)
int_check(var.get('srcport'), var.get('dstport'), var.get('index'), func=func) | [
"def",
"pkt_check",
"(",
"*",
"args",
",",
"func",
"=",
"None",
")",
":",
"func",
"=",
"func",
"or",
"inspect",
".",
"stack",
"(",
")",
"[",
"2",
"]",
"[",
"3",
"]",
"for",
"var",
"in",
"args",
":",
"dict_check",
"(",
"var",
",",
"func",
"=",
... | Check if arguments are valid packets. | [
"Check",
"if",
"arguments",
"are",
"valid",
"packets",
"."
] | python | train |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L658-L719 | def _parse_uri(uri_as_string):
"""
Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
* s3://my_key:my_secret@my_bucket/my_key
* s3://my_key:my_secret@my_server:my_port@my_bucket/my_key
* hdfs:///path/file
* hdfs://path/file
* webhdfs://host:port/path/file
* ./local/path/file
* ~/local/path/file
* local/path/file
* ./local/path/file.gz
* file:///home/user/file
* file:///home/user/file.bz2
* [ssh|scp|sftp]://username@host//path/file
* [ssh|scp|sftp]://username@host/path/file
"""
if os.name == 'nt':
# urlsplit doesn't work on Windows -- it parses the drive as the scheme...
if '://' not in uri_as_string:
# no protocol given => assume a local file
uri_as_string = 'file://' + uri_as_string
parsed_uri = _my_urlsplit(uri_as_string)
if parsed_uri.scheme == "hdfs":
return _parse_uri_hdfs(parsed_uri)
elif parsed_uri.scheme == "webhdfs":
return _parse_uri_webhdfs(parsed_uri)
elif parsed_uri.scheme in smart_open_s3.SUPPORTED_SCHEMES:
return _parse_uri_s3x(parsed_uri)
elif parsed_uri.scheme == 'file':
return _parse_uri_file(parsed_uri.netloc + parsed_uri.path)
elif parsed_uri.scheme in ('', None):
return _parse_uri_file(uri_as_string)
elif parsed_uri.scheme.startswith('http'):
return Uri(scheme=parsed_uri.scheme, uri_path=uri_as_string)
elif parsed_uri.scheme in smart_open_ssh.SCHEMES:
return _parse_uri_ssh(parsed_uri)
else:
raise NotImplementedError(
"unknown URI scheme %r in %r" % (parsed_uri.scheme, uri_as_string)
) | [
"def",
"_parse_uri",
"(",
"uri_as_string",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# urlsplit doesn't work on Windows -- it parses the drive as the scheme...",
"if",
"'://'",
"not",
"in",
"uri_as_string",
":",
"# no protocol given => assume a local file",
"ur... | Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
* s3://my_key:my_secret@my_bucket/my_key
* s3://my_key:my_secret@my_server:my_port@my_bucket/my_key
* hdfs:///path/file
* hdfs://path/file
* webhdfs://host:port/path/file
* ./local/path/file
* ~/local/path/file
* local/path/file
* ./local/path/file.gz
* file:///home/user/file
* file:///home/user/file.bz2
* [ssh|scp|sftp]://username@host//path/file
* [ssh|scp|sftp]://username@host/path/file | [
"Parse",
"the",
"given",
"URI",
"from",
"a",
"string",
"."
] | python | train |
tanghaibao/goatools | goatools/wr_tbl_class.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl_class.py#L49-L53 | def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx):
"""Merge all columns and place text string in widened cell."""
hdridxval = len(self.hdrs) - 1
worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt)
return row_idx + 1 | [
"def",
"wr_row_mergeall",
"(",
"self",
",",
"worksheet",
",",
"txtstr",
",",
"fmt",
",",
"row_idx",
")",
":",
"hdridxval",
"=",
"len",
"(",
"self",
".",
"hdrs",
")",
"-",
"1",
"worksheet",
".",
"merge_range",
"(",
"row_idx",
",",
"0",
",",
"row_idx",
... | Merge all columns and place text string in widened cell. | [
"Merge",
"all",
"columns",
"and",
"place",
"text",
"string",
"in",
"widened",
"cell",
"."
] | python | train |
jxtech/wechatpy | wechatpy/client/api/tag.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/tag.py#L126-L142 | def get_tag_users(self, tag_id, first_user_id=None):
"""
获取标签下粉丝列表
:param tag_id: 标签 ID
:param first_user_id: 可选。第一个拉取的 OPENID,不填默认从头开始拉取
:return: 返回的 JSON 数据包
"""
data = {
'tagid': tag_id,
}
if first_user_id:
data['next_openid'] = first_user_id
return self._post(
'user/tag/get',
data=data
) | [
"def",
"get_tag_users",
"(",
"self",
",",
"tag_id",
",",
"first_user_id",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'tagid'",
":",
"tag_id",
",",
"}",
"if",
"first_user_id",
":",
"data",
"[",
"'next_openid'",
"]",
"=",
"first_user_id",
"return",
"self",
... | 获取标签下粉丝列表
:param tag_id: 标签 ID
:param first_user_id: 可选。第一个拉取的 OPENID,不填默认从头开始拉取
:return: 返回的 JSON 数据包 | [
"获取标签下粉丝列表"
] | python | train |
peri-source/peri | peri/states.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L599-L603 | def model_to_data(self, sigma=0.0):
""" Switch out the data for the model's recreation of the data. """
im = self.model.copy()
im += sigma*np.random.randn(*im.shape)
self.set_image(util.NullImage(image=im)) | [
"def",
"model_to_data",
"(",
"self",
",",
"sigma",
"=",
"0.0",
")",
":",
"im",
"=",
"self",
".",
"model",
".",
"copy",
"(",
")",
"im",
"+=",
"sigma",
"*",
"np",
".",
"random",
".",
"randn",
"(",
"*",
"im",
".",
"shape",
")",
"self",
".",
"set_i... | Switch out the data for the model's recreation of the data. | [
"Switch",
"out",
"the",
"data",
"for",
"the",
"model",
"s",
"recreation",
"of",
"the",
"data",
"."
] | python | valid |
cloudera/cm_api | python/src/cm_api/endpoints/services.py | https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1176-L1188 | def disable_oozie_ha(self, active_name):
"""
Disable high availability for Oozie
@param active_name: Name of the Oozie Server that will be active after
High Availability is disabled.
@return: Reference to the submitted command.
@since: API v6
"""
args = dict(
activeName = active_name
)
return self._cmd('oozieDisableHa', data=args, api_version=6) | [
"def",
"disable_oozie_ha",
"(",
"self",
",",
"active_name",
")",
":",
"args",
"=",
"dict",
"(",
"activeName",
"=",
"active_name",
")",
"return",
"self",
".",
"_cmd",
"(",
"'oozieDisableHa'",
",",
"data",
"=",
"args",
",",
"api_version",
"=",
"6",
")"
] | Disable high availability for Oozie
@param active_name: Name of the Oozie Server that will be active after
High Availability is disabled.
@return: Reference to the submitted command.
@since: API v6 | [
"Disable",
"high",
"availability",
"for",
"Oozie"
] | python | train |
adewes/blitzdb | blitzdb/backends/sql/relations.py | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/sql/relations.py#L123-L132 | def remove(self,obj):
"""
Remove an object from the relation
"""
relationship_table = self.params['relationship_table']
with self.obj.backend.transaction(implicit = True):
condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk,
relationship_table.c[self.params['pk_field_name']] == self.obj.pk)
self.obj.backend.connection.execute(delete(relationship_table).where(condition))
self._queryset = None | [
"def",
"remove",
"(",
"self",
",",
"obj",
")",
":",
"relationship_table",
"=",
"self",
".",
"params",
"[",
"'relationship_table'",
"]",
"with",
"self",
".",
"obj",
".",
"backend",
".",
"transaction",
"(",
"implicit",
"=",
"True",
")",
":",
"condition",
"... | Remove an object from the relation | [
"Remove",
"an",
"object",
"from",
"the",
"relation"
] | python | train |
thieman/dagobah | dagobah/backend/mongo.py | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/backend/mongo.py#L96-L107 | def delete_dagobah(self, dagobah_id):
""" Deletes the Dagobah and all child Jobs from the database.
Related run logs are deleted as well.
"""
rec = self.dagobah_coll.find_one({'_id': dagobah_id})
for job in rec.get('jobs', []):
if 'job_id' in job:
self.delete_job(job['job_id'])
self.log_coll.remove({'parent_id': dagobah_id})
self.dagobah_coll.remove({'_id': dagobah_id}) | [
"def",
"delete_dagobah",
"(",
"self",
",",
"dagobah_id",
")",
":",
"rec",
"=",
"self",
".",
"dagobah_coll",
".",
"find_one",
"(",
"{",
"'_id'",
":",
"dagobah_id",
"}",
")",
"for",
"job",
"in",
"rec",
".",
"get",
"(",
"'jobs'",
",",
"[",
"]",
")",
"... | Deletes the Dagobah and all child Jobs from the database.
Related run logs are deleted as well. | [
"Deletes",
"the",
"Dagobah",
"and",
"all",
"child",
"Jobs",
"from",
"the",
"database",
"."
] | python | train |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L174-L198 | def repl_init(self, config):
"""create replica set by config
return True if replica set created successfuly, else False"""
self.update_server_map(config)
# init_server - server which can init replica set
init_server = [member['host'] for member in config['members']
if not (member.get('arbiterOnly', False)
or member.get('priority', 1) == 0)][0]
servers = [member['host'] for member in config['members']]
if not self.wait_while_reachable(servers):
logger.error("all servers must be reachable")
self.cleanup()
return False
try:
result = self.connection(init_server).admin.command("replSetInitiate", config)
logger.debug("replica init result: {result}".format(**locals()))
except pymongo.errors.PyMongoError:
raise
if int(result.get('ok', 0)) == 1:
# Wait while members come up
return self.waiting_member_state()
else:
self.cleanup()
return False | [
"def",
"repl_init",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"update_server_map",
"(",
"config",
")",
"# init_server - server which can init replica set",
"init_server",
"=",
"[",
"member",
"[",
"'host'",
"]",
"for",
"member",
"in",
"config",
"[",
"'me... | create replica set by config
return True if replica set created successfuly, else False | [
"create",
"replica",
"set",
"by",
"config",
"return",
"True",
"if",
"replica",
"set",
"created",
"successfuly",
"else",
"False"
] | python | train |
softlayer/softlayer-python | SoftLayer/CLI/file/replication/failover.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/failover.py#L17-L30 | def cli(env, volume_id, replicant_id, immediate):
"""Failover a file volume to the given replicant volume."""
file_storage_manager = SoftLayer.FileStorageManager(env.client)
success = file_storage_manager.failover_to_replicant(
volume_id,
replicant_id,
immediate
)
if success:
click.echo("Failover to replicant is now in progress.")
else:
click.echo("Failover operation could not be initiated.") | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"replicant_id",
",",
"immediate",
")",
":",
"file_storage_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"success",
"=",
"file_storage_manager",
".",
"failover_to_replicant",
... | Failover a file volume to the given replicant volume. | [
"Failover",
"a",
"file",
"volume",
"to",
"the",
"given",
"replicant",
"volume",
"."
] | python | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L470-L528 | def buckets(bucket=None, account=None, matched=False, kdenied=False,
errors=False, dbpath=None, size=None, denied=False,
format=None, incomplete=False, oversize=False, region=(),
not_region=(), inventory=None, output=None, config=None, sort=None,
tagprefix=None, not_bucket=None):
"""Report on stats by bucket"""
d = db.db(dbpath)
if tagprefix and not config:
raise ValueError(
"account tag value inclusion requires account config file")
if config and tagprefix:
with open(config) as fh:
data = json.load(fh).get('accounts')
account_data = {}
for a in data:
for t in a['tags']:
if t.startswith(tagprefix):
account_data[a['name']] = t[len(tagprefix):]
buckets = []
for b in sorted(d.buckets(account),
key=operator.attrgetter('bucket_id')):
if bucket and b.name not in bucket:
continue
if not_bucket and b.name in not_bucket:
continue
if matched and not b.matched:
continue
if kdenied and not b.keys_denied:
continue
if errors and not b.error_count:
continue
if size and b.size < size:
continue
if inventory and not b.using_inventory:
continue
if denied and not b.denied:
continue
if oversize and b.scanned <= b.size:
continue
if incomplete and b.percent_scanned >= incomplete:
continue
if region and b.region not in region:
continue
if not_region and b.region in not_region:
continue
if tagprefix:
setattr(b, tagprefix[:-1], account_data[b.account])
buckets.append(b)
if sort:
key = operator.attrgetter(sort)
buckets = list(reversed(sorted(buckets, key=key)))
formatter = format == 'csv' and format_csv or format_plain
keys = tagprefix and (tagprefix[:-1],) or ()
formatter(buckets, output, keys=keys) | [
"def",
"buckets",
"(",
"bucket",
"=",
"None",
",",
"account",
"=",
"None",
",",
"matched",
"=",
"False",
",",
"kdenied",
"=",
"False",
",",
"errors",
"=",
"False",
",",
"dbpath",
"=",
"None",
",",
"size",
"=",
"None",
",",
"denied",
"=",
"False",
"... | Report on stats by bucket | [
"Report",
"on",
"stats",
"by",
"bucket"
] | python | train |
h2oai/h2o-3 | h2o-py/h2o/grid/grid_search.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/grid/grid_search.py#L147-L151 | def join(self):
"""Wait until grid finishes computing."""
self._future = False
self._job.poll()
self._job = None | [
"def",
"join",
"(",
"self",
")",
":",
"self",
".",
"_future",
"=",
"False",
"self",
".",
"_job",
".",
"poll",
"(",
")",
"self",
".",
"_job",
"=",
"None"
] | Wait until grid finishes computing. | [
"Wait",
"until",
"grid",
"finishes",
"computing",
"."
] | python | test |
astropy/photutils | photutils/segmentation/properties.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L904-L928 | def background_at_centroid(self):
"""
The value of the ``background`` at the position of the source
centroid.
The background value at fractional position values are
determined using bilinear interpolation.
"""
from scipy.ndimage import map_coordinates
if self._background is not None:
# centroid can still be NaN if all data values are <= 0
if (self._is_completely_masked or
np.any(~np.isfinite(self.centroid))):
return np.nan * self._background_unit # unit for table
else:
value = map_coordinates(self._background,
[[self.ycentroid.value],
[self.xcentroid.value]], order=1,
mode='nearest')[0]
return value * self._background_unit
else:
return None | [
"def",
"background_at_centroid",
"(",
"self",
")",
":",
"from",
"scipy",
".",
"ndimage",
"import",
"map_coordinates",
"if",
"self",
".",
"_background",
"is",
"not",
"None",
":",
"# centroid can still be NaN if all data values are <= 0",
"if",
"(",
"self",
".",
"_is_... | The value of the ``background`` at the position of the source
centroid.
The background value at fractional position values are
determined using bilinear interpolation. | [
"The",
"value",
"of",
"the",
"background",
"at",
"the",
"position",
"of",
"the",
"source",
"centroid",
"."
] | python | train |
limodou/uliweb | uliweb/utils/generic.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L299-L303 | def get_value_for_datastore(self, model_instance):
"""Get key of reference rather than reference itself."""
table_id = getattr(model_instance, self.table_fieldname, None)
object_id = getattr(model_instance, self.object_fieldname, None)
return table_id, object_id | [
"def",
"get_value_for_datastore",
"(",
"self",
",",
"model_instance",
")",
":",
"table_id",
"=",
"getattr",
"(",
"model_instance",
",",
"self",
".",
"table_fieldname",
",",
"None",
")",
"object_id",
"=",
"getattr",
"(",
"model_instance",
",",
"self",
".",
"obj... | Get key of reference rather than reference itself. | [
"Get",
"key",
"of",
"reference",
"rather",
"than",
"reference",
"itself",
"."
] | python | train |
trevisanj/f311 | f311/hapi.py | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/hapi.py#L2390-L2409 | def getColumns(TableName,ParameterNames):
"""
INPUT PARAMETERS:
TableName: source table name (required)
ParameterNames: list of column names to get (required)
OUTPUT PARAMETERS:
ListColumnData: tuple of lists of values from specified column
---
DESCRIPTION:
Returns columns with a names in ParameterNames from
table TableName. Columns are returned as a tuple of lists.
---
EXAMPLE OF USAGE:
p1,p2,p3 = getColumns('sampletab',('p1','p2','p3'))
---
"""
Columns = []
for par_name in ParameterNames:
Columns.append(LOCAL_TABLE_CACHE[TableName]['data'][par_name])
return Columns | [
"def",
"getColumns",
"(",
"TableName",
",",
"ParameterNames",
")",
":",
"Columns",
"=",
"[",
"]",
"for",
"par_name",
"in",
"ParameterNames",
":",
"Columns",
".",
"append",
"(",
"LOCAL_TABLE_CACHE",
"[",
"TableName",
"]",
"[",
"'data'",
"]",
"[",
"par_name",
... | INPUT PARAMETERS:
TableName: source table name (required)
ParameterNames: list of column names to get (required)
OUTPUT PARAMETERS:
ListColumnData: tuple of lists of values from specified column
---
DESCRIPTION:
Returns columns with a names in ParameterNames from
table TableName. Columns are returned as a tuple of lists.
---
EXAMPLE OF USAGE:
p1,p2,p3 = getColumns('sampletab',('p1','p2','p3'))
--- | [
"INPUT",
"PARAMETERS",
":",
"TableName",
":",
"source",
"table",
"name",
"(",
"required",
")",
"ParameterNames",
":",
"list",
"of",
"column",
"names",
"to",
"get",
"(",
"required",
")",
"OUTPUT",
"PARAMETERS",
":",
"ListColumnData",
":",
"tuple",
"of",
"list... | python | train |
VJftw/invoke-tools | idflow/utils.py | https://github.com/VJftw/invoke-tools/blob/9584a1f8a402118310b6f2a495062f388fc8dc3a/idflow/utils.py#L37-L48 | def get_version():
"""
Returns the current code version
"""
try:
return check_output(
"git describe --tags".split(" ")
).decode('utf-8').strip()
except CalledProcessError:
return check_output(
"git rev-parse --short HEAD".split(" ")
).decode('utf-8').strip() | [
"def",
"get_version",
"(",
")",
":",
"try",
":",
"return",
"check_output",
"(",
"\"git describe --tags\"",
".",
"split",
"(",
"\" \"",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
"except",
"CalledProcessError",
":",
"return",
"che... | Returns the current code version | [
"Returns",
"the",
"current",
"code",
"version"
] | python | train |
singnet/snet-cli | snet_cli/mpe_service_command.py | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_service_command.py#L73-L80 | def metadata_update_endpoints(self):
""" Metadata: Remove all endpoints from the group and add new ones """
metadata = load_mpe_service_metadata(self.args.metadata_file)
group_name = metadata.get_group_name_nonetrick(self.args.group_name)
metadata.remove_all_endpoints_for_group(group_name)
for endpoint in self.args.endpoints:
metadata.add_endpoint(group_name, endpoint)
metadata.save_pretty(self.args.metadata_file) | [
"def",
"metadata_update_endpoints",
"(",
"self",
")",
":",
"metadata",
"=",
"load_mpe_service_metadata",
"(",
"self",
".",
"args",
".",
"metadata_file",
")",
"group_name",
"=",
"metadata",
".",
"get_group_name_nonetrick",
"(",
"self",
".",
"args",
".",
"group_name... | Metadata: Remove all endpoints from the group and add new ones | [
"Metadata",
":",
"Remove",
"all",
"endpoints",
"from",
"the",
"group",
"and",
"add",
"new",
"ones"
] | python | train |
pyhys/minimalmodbus | minimalmodbus.py | https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L358-L392 | def read_float(self, registeraddress, functioncode=3, numberOfRegisters=2):
"""Read a floating point number from the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave. The
encoding is according to the standard IEEE 754.
There are differences in the byte order used by different manufacturers. A floating
point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this
implementation the data will be sent as ``'\\x3f\\x80'`` and ``'\\x00\\x00'``
to two consecutetive registers . Make sure to test that it makes sense for your instrument.
It is pretty straight-forward to change this code if some other byte order is
required by anyone (see support section).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 3 or 4.
* numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
====================================== ================= =========== =================
Type of floating point number in slave Size Registers Range
====================================== ================= =========== =================
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308
====================================== ================= =========== =================
Returns:
The numerical value (float).
Raises:
ValueError, TypeError, IOError
"""
_checkFunctioncode(functioncode, [3, 4])
_checkInt(numberOfRegisters, minvalue=2, maxvalue=4, description='number of registers')
return self._genericCommand(functioncode, registeraddress, numberOfRegisters=numberOfRegisters, payloadformat='float') | [
"def",
"read_float",
"(",
"self",
",",
"registeraddress",
",",
"functioncode",
"=",
"3",
",",
"numberOfRegisters",
"=",
"2",
")",
":",
"_checkFunctioncode",
"(",
"functioncode",
",",
"[",
"3",
",",
"4",
"]",
")",
"_checkInt",
"(",
"numberOfRegisters",
",",
... | Read a floating point number from the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave. The
encoding is according to the standard IEEE 754.
There are differences in the byte order used by different manufacturers. A floating
point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this
implementation the data will be sent as ``'\\x3f\\x80'`` and ``'\\x00\\x00'``
to two consecutetive registers . Make sure to test that it makes sense for your instrument.
It is pretty straight-forward to change this code if some other byte order is
required by anyone (see support section).
Args:
* registeraddress (int): The slave register start address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 3 or 4.
* numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
====================================== ================= =========== =================
Type of floating point number in slave Size Registers Range
====================================== ================= =========== =================
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308
====================================== ================= =========== =================
Returns:
The numerical value (float).
Raises:
ValueError, TypeError, IOError | [
"Read",
"a",
"floating",
"point",
"number",
"from",
"the",
"slave",
"."
] | python | train |
Miachol/pycnf | pycnf/configtype.py | https://github.com/Miachol/pycnf/blob/8fc0f25b0d6f9f3a79dbd30027fcb22c981afa4b/pycnf/configtype.py#L29-L41 | def is_ini_file(filename, show_warnings = False):
"""Check configuration file type is INI
Return a boolean indicating wheather the file is INI format or not
"""
try:
config_dict = load_config(filename, file_type = "ini")
if config_dict == {}:
is_ini = False
else:
is_ini = True
except:
is_ini = False
return(is_ini) | [
"def",
"is_ini_file",
"(",
"filename",
",",
"show_warnings",
"=",
"False",
")",
":",
"try",
":",
"config_dict",
"=",
"load_config",
"(",
"filename",
",",
"file_type",
"=",
"\"ini\"",
")",
"if",
"config_dict",
"==",
"{",
"}",
":",
"is_ini",
"=",
"False",
... | Check configuration file type is INI
Return a boolean indicating wheather the file is INI format or not | [
"Check",
"configuration",
"file",
"type",
"is",
"INI",
"Return",
"a",
"boolean",
"indicating",
"wheather",
"the",
"file",
"is",
"INI",
"format",
"or",
"not"
] | python | train |
saltstack/salt | salt/modules/inspectlib/query.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/query.py#L86-L97 | def _get_cpu(self):
'''
Get available CPU information.
'''
# CPU data in grains is OK-ish, but lscpu is still better in this case
out = __salt__['cmd.run_all']("lscpu")
salt.utils.fsutils._verify_run(out)
data = dict()
for descr, value in [elm.split(":", 1) for elm in out['stdout'].split(os.linesep)]:
data[descr.strip()] = value.strip()
return data | [
"def",
"_get_cpu",
"(",
"self",
")",
":",
"# CPU data in grains is OK-ish, but lscpu is still better in this case",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"lscpu\"",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_verify_run",
"(",
"out",
")",
... | Get available CPU information. | [
"Get",
"available",
"CPU",
"information",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.