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 |
|---|---|---|---|---|---|---|---|---|
Yelp/detect-secrets | detect_secrets/plugins/common/initialize.py | https://github.com/Yelp/detect-secrets/blob/473923ea71f1ac2b5ea1eacc49b98f97967e3d05/detect_secrets/plugins/common/initialize.py#L195-L205 | def _get_mapping_from_secret_type_to_class_name():
"""Returns secret_type => plugin classname"""
mapping = {}
for key, value in globals().items():
try:
if issubclass(value, BasePlugin) and value != BasePlugin:
mapping[value.secret_type] = key
except TypeError:
... | [
"def",
"_get_mapping_from_secret_type_to_class_name",
"(",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"globals",
"(",
")",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"issubclass",
"(",
"value",
",",
"BasePlugin",
")",
"and"... | Returns secret_type => plugin classname | [
"Returns",
"secret_type",
"=",
">",
"plugin",
"classname"
] | python | train |
phoebe-project/phoebe2 | phoebe/backend/mesh_wd.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh_wd.py#L65-L92 | def project_onto_potential(r, pot_name, *args):
"""
TODO: add documentation
"""
pot = globals()[pot_name]
dpdx = globals()['d%sdx'%(pot_name)]
dpdy = globals()['d%sdy'%(pot_name)]
dpdz = globals()['d%sdz'%(pot_name)]
dpdr = globals()['d%sdr'%(pot_name)]
n_iter = 0
rmag, rmag0 ... | [
"def",
"project_onto_potential",
"(",
"r",
",",
"pot_name",
",",
"*",
"args",
")",
":",
"pot",
"=",
"globals",
"(",
")",
"[",
"pot_name",
"]",
"dpdx",
"=",
"globals",
"(",
")",
"[",
"'d%sdx'",
"%",
"(",
"pot_name",
")",
"]",
"dpdy",
"=",
"globals",
... | TODO: add documentation | [
"TODO",
":",
"add",
"documentation"
] | python | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/query.py | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/query.py#L1453-L1468 | def analyze(self):
"""Return a list giving the parameters required by a query."""
class MockBindings(dict):
def __contains__(self, key):
self[key] = None
return True
bindings = MockBindings()
used = {}
ancestor = self.ancestor
if isinstance(ancestor, ParameterizedThing):
... | [
"def",
"analyze",
"(",
"self",
")",
":",
"class",
"MockBindings",
"(",
"dict",
")",
":",
"def",
"__contains__",
"(",
"self",
",",
"key",
")",
":",
"self",
"[",
"key",
"]",
"=",
"None",
"return",
"True",
"bindings",
"=",
"MockBindings",
"(",
")",
"use... | Return a list giving the parameters required by a query. | [
"Return",
"a",
"list",
"giving",
"the",
"parameters",
"required",
"by",
"a",
"query",
"."
] | python | train |
obriencj/python-javatools | javatools/manifest.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L860-L874 | def multi_path_generator(pathnames):
"""
yields (name,chunkgen) for all of the files found under the list
of pathnames given. This is recursive, so directories will have
their contents emitted. chunkgen is a function that can called and
iterated over to obtain the contents of the file in multiple
... | [
"def",
"multi_path_generator",
"(",
"pathnames",
")",
":",
"for",
"pathname",
"in",
"pathnames",
":",
"if",
"isdir",
"(",
"pathname",
")",
":",
"for",
"entry",
"in",
"directory_generator",
"(",
"pathname",
")",
":",
"yield",
"entry",
"else",
":",
"yield",
... | yields (name,chunkgen) for all of the files found under the list
of pathnames given. This is recursive, so directories will have
their contents emitted. chunkgen is a function that can called and
iterated over to obtain the contents of the file in multiple
reads. | [
"yields",
"(",
"name",
"chunkgen",
")",
"for",
"all",
"of",
"the",
"files",
"found",
"under",
"the",
"list",
"of",
"pathnames",
"given",
".",
"This",
"is",
"recursive",
"so",
"directories",
"will",
"have",
"their",
"contents",
"emitted",
".",
"chunkgen",
"... | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1930-L1965 | def __add_loaded_module(self, event):
"""
Private method to automatically add new module objects from debug events.
@type event: L{Event}
@param event: Event object.
"""
lpBaseOfDll = event.get_module_base()
hFile = event.get_file_handle()
## if not... | [
"def",
"__add_loaded_module",
"(",
"self",
",",
"event",
")",
":",
"lpBaseOfDll",
"=",
"event",
".",
"get_module_base",
"(",
")",
"hFile",
"=",
"event",
".",
"get_file_handle",
"(",
")",
"## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan",
... | Private method to automatically add new module objects from debug events.
@type event: L{Event}
@param event: Event object. | [
"Private",
"method",
"to",
"automatically",
"add",
"new",
"module",
"objects",
"from",
"debug",
"events",
"."
] | python | train |
linnarsson-lab/loompy | loompy/loompy.py | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L784-L806 | def permute(self, ordering: np.ndarray, axis: int) -> None:
"""
Permute the dataset along the indicated axis.
Args:
ordering (list of int): The desired order along the axis
axis (int): The axis along which to permute
Returns:
Nothing.
"""
if self._file.__contains__("tiles"):
del self._fi... | [
"def",
"permute",
"(",
"self",
",",
"ordering",
":",
"np",
".",
"ndarray",
",",
"axis",
":",
"int",
")",
"->",
"None",
":",
"if",
"self",
".",
"_file",
".",
"__contains__",
"(",
"\"tiles\"",
")",
":",
"del",
"self",
".",
"_file",
"[",
"'tiles'",
"]... | Permute the dataset along the indicated axis.
Args:
ordering (list of int): The desired order along the axis
axis (int): The axis along which to permute
Returns:
Nothing. | [
"Permute",
"the",
"dataset",
"along",
"the",
"indicated",
"axis",
"."
] | python | train |
instaloader/instaloader | instaloader/instaloader.py | https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/instaloader.py#L694-L715 | def download_saved_posts(self, max_count: int = None, fast_update: bool = False,
post_filter: Optional[Callable[[Post], bool]] = None) -> None:
"""Download user's saved pictures.
:param max_count: Maximum count of pictures to download
:param fast_update: If true, ab... | [
"def",
"download_saved_posts",
"(",
"self",
",",
"max_count",
":",
"int",
"=",
"None",
",",
"fast_update",
":",
"bool",
"=",
"False",
",",
"post_filter",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"Post",
"]",
",",
"bool",
"]",
"]",
"=",
"None",
")",
... | Download user's saved pictures.
:param max_count: Maximum count of pictures to download
:param fast_update: If true, abort when first already-downloaded picture is encountered
:param post_filter: function(post), which returns True if given picture should be downloaded | [
"Download",
"user",
"s",
"saved",
"pictures",
"."
] | python | train |
proycon/pynlpl | pynlpl/statistics.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L91-L99 | def count(self, type, amount = 1):
"""Count a certain type. The counter will increase by the amount specified (defaults to one)"""
if self.dovalidation: type = self._validate(type)
if self._ranked: self._ranked = None
if type in self._count:
self._count[type] += amount
... | [
"def",
"count",
"(",
"self",
",",
"type",
",",
"amount",
"=",
"1",
")",
":",
"if",
"self",
".",
"dovalidation",
":",
"type",
"=",
"self",
".",
"_validate",
"(",
"type",
")",
"if",
"self",
".",
"_ranked",
":",
"self",
".",
"_ranked",
"=",
"None",
... | Count a certain type. The counter will increase by the amount specified (defaults to one) | [
"Count",
"a",
"certain",
"type",
".",
"The",
"counter",
"will",
"increase",
"by",
"the",
"amount",
"specified",
"(",
"defaults",
"to",
"one",
")"
] | python | train |
ray-project/ray | python/ray/tune/trial_runner.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L322-L334 | def add_trial(self, trial):
"""Adds a new trial to this TrialRunner.
Trials may be added at any time.
Args:
trial (Trial): Trial to queue.
"""
trial.set_verbose(self._verbose)
self._trials.append(trial)
with warn_if_slow("scheduler.on_trial_add"):
... | [
"def",
"add_trial",
"(",
"self",
",",
"trial",
")",
":",
"trial",
".",
"set_verbose",
"(",
"self",
".",
"_verbose",
")",
"self",
".",
"_trials",
".",
"append",
"(",
"trial",
")",
"with",
"warn_if_slow",
"(",
"\"scheduler.on_trial_add\"",
")",
":",
"self",
... | Adds a new trial to this TrialRunner.
Trials may be added at any time.
Args:
trial (Trial): Trial to queue. | [
"Adds",
"a",
"new",
"trial",
"to",
"this",
"TrialRunner",
"."
] | python | train |
pysal/giddy | giddy/ergodic.py | https://github.com/pysal/giddy/blob/13fae6c18933614be78e91a6b5060693bea33a04/giddy/ergodic.py#L62-L118 | def fmpt(P):
"""
Calculates the matrix of first mean passage times for an ergodic transition
probability matrix.
Parameters
----------
P : array
(k, k), an ergodic Markov transition probability matrix.
Returns
-------
M : array
(k, k), elements are the e... | [
"def",
"fmpt",
"(",
"P",
")",
":",
"P",
"=",
"np",
".",
"matrix",
"(",
"P",
")",
"k",
"=",
"P",
".",
"shape",
"[",
"0",
"]",
"A",
"=",
"np",
".",
"zeros_like",
"(",
"P",
")",
"ss",
"=",
"steady_state",
"(",
"P",
")",
".",
"reshape",
"(",
... | Calculates the matrix of first mean passage times for an ergodic transition
probability matrix.
Parameters
----------
P : array
(k, k), an ergodic Markov transition probability matrix.
Returns
-------
M : array
(k, k), elements are the expected value for the num... | [
"Calculates",
"the",
"matrix",
"of",
"first",
"mean",
"passage",
"times",
"for",
"an",
"ergodic",
"transition",
"probability",
"matrix",
"."
] | python | train |
HazyResearch/pdftotree | pdftotree/utils/pdf/node.py | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/node.py#L187-L206 | def _get_cols(row_content):
"""
Counting the number columns based on the content of this row
"""
cols = []
subcell_col = []
prev_bar = None
for _coord, item in row_content:
if isinstance(item, LTTextLine):
subcell_col.append(item)
else: # bar, add column content
... | [
"def",
"_get_cols",
"(",
"row_content",
")",
":",
"cols",
"=",
"[",
"]",
"subcell_col",
"=",
"[",
"]",
"prev_bar",
"=",
"None",
"for",
"_coord",
",",
"item",
"in",
"row_content",
":",
"if",
"isinstance",
"(",
"item",
",",
"LTTextLine",
")",
":",
"subce... | Counting the number columns based on the content of this row | [
"Counting",
"the",
"number",
"columns",
"based",
"on",
"the",
"content",
"of",
"this",
"row"
] | python | train |
thoughtworksarts/EmoPy | EmoPy/src/neuralnets.py | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/neuralnets.py#L94-L109 | def _get_base_model(self):
"""
:return: base model from Keras based on user-supplied model name
"""
if self.model_name == 'inception_v3':
return InceptionV3(weights='imagenet', include_top=False)
elif self.model_name == 'xception':
return Xception(weights=... | [
"def",
"_get_base_model",
"(",
"self",
")",
":",
"if",
"self",
".",
"model_name",
"==",
"'inception_v3'",
":",
"return",
"InceptionV3",
"(",
"weights",
"=",
"'imagenet'",
",",
"include_top",
"=",
"False",
")",
"elif",
"self",
".",
"model_name",
"==",
"'xcept... | :return: base model from Keras based on user-supplied model name | [
":",
"return",
":",
"base",
"model",
"from",
"Keras",
"based",
"on",
"user",
"-",
"supplied",
"model",
"name"
] | python | train |
apache/spark | python/pyspark/sql/streaming.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/streaming.py#L829-L878 | def trigger(self, processingTime=None, once=None, continuous=None):
"""Set the trigger for the stream query. If this is not set it will run the query as fast
as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``.
.. note:: Evolving.
:param processing... | [
"def",
"trigger",
"(",
"self",
",",
"processingTime",
"=",
"None",
",",
"once",
"=",
"None",
",",
"continuous",
"=",
"None",
")",
":",
"params",
"=",
"[",
"processingTime",
",",
"once",
",",
"continuous",
"]",
"if",
"params",
".",
"count",
"(",
"None",... | Set the trigger for the stream query. If this is not set it will run the query as fast
as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``.
.. note:: Evolving.
:param processingTime: a processing time interval as a string, e.g. '5 seconds', '1 minute'.
... | [
"Set",
"the",
"trigger",
"for",
"the",
"stream",
"query",
".",
"If",
"this",
"is",
"not",
"set",
"it",
"will",
"run",
"the",
"query",
"as",
"fast",
"as",
"possible",
"which",
"is",
"equivalent",
"to",
"setting",
"the",
"trigger",
"to",
"processingTime",
... | python | train |
Stewori/pytypes | pytypes/type_util.py | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L109-L122 | def get_generator_type(genr):
"""Obtains PEP 484 style type of a generator object, i.e. returns a
typing.Generator object.
"""
if genr in _checked_generator_types:
return _checked_generator_types[genr]
if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals:
return genr... | [
"def",
"get_generator_type",
"(",
"genr",
")",
":",
"if",
"genr",
"in",
"_checked_generator_types",
":",
"return",
"_checked_generator_types",
"[",
"genr",
"]",
"if",
"not",
"genr",
".",
"gi_frame",
"is",
"None",
"and",
"'gen_type'",
"in",
"genr",
".",
"gi_fra... | Obtains PEP 484 style type of a generator object, i.e. returns a
typing.Generator object. | [
"Obtains",
"PEP",
"484",
"style",
"type",
"of",
"a",
"generator",
"object",
"i",
".",
"e",
".",
"returns",
"a",
"typing",
".",
"Generator",
"object",
"."
] | python | train |
neovim/pynvim | pynvim/msgpack_rpc/session.py | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/session.py#L65-L103 | def request(self, method, *args, **kwargs):
"""Send a msgpack-rpc request and block until as response is received.
If the event loop is running, this method must have been called by a
request or notification handler running on a greenlet. In that case,
send the quest and yield to the pa... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"async_",
"=",
"check_async",
"(",
"kwargs",
".",
"pop",
"(",
"'async_'",
",",
"None",
")",
",",
"kwargs",
",",
"False",
")",
"if",
"async_",
":",
... | Send a msgpack-rpc request and block until as response is received.
If the event loop is running, this method must have been called by a
request or notification handler running on a greenlet. In that case,
send the quest and yield to the parent greenlet until a response is
available.
... | [
"Send",
"a",
"msgpack",
"-",
"rpc",
"request",
"and",
"block",
"until",
"as",
"response",
"is",
"received",
"."
] | python | train |
balloob/pychromecast | pychromecast/socket_client.py | https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/socket_client.py#L646-L659 | def _read_message(self):
""" Reads a message from the socket and converts it to a message. """
# first 4 bytes is Big-Endian payload length
payload_info = self._read_bytes_from_socket(4)
read_len = unpack(">I", payload_info)[0]
# now read the payload
payload = self._read... | [
"def",
"_read_message",
"(",
"self",
")",
":",
"# first 4 bytes is Big-Endian payload length",
"payload_info",
"=",
"self",
".",
"_read_bytes_from_socket",
"(",
"4",
")",
"read_len",
"=",
"unpack",
"(",
"\">I\"",
",",
"payload_info",
")",
"[",
"0",
"]",
"# now rea... | Reads a message from the socket and converts it to a message. | [
"Reads",
"a",
"message",
"from",
"the",
"socket",
"and",
"converts",
"it",
"to",
"a",
"message",
"."
] | python | train |
saltstack/salt | salt/states/module.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/module.py#L439-L496 | def _call_function(name, returner=None, **kwargs):
'''
Calls a function from the specified module.
:param name:
:param kwargs:
:return:
'''
argspec = salt.utils.args.get_function_argspec(__salt__[name])
# func_kw is initialized to a dictionary of keyword arguments the function to be ru... | [
"def",
"_call_function",
"(",
"name",
",",
"returner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"argspec",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"get_function_argspec",
"(",
"__salt__",
"[",
"name",
"]",
")",
"# func_kw is initialized to a dict... | Calls a function from the specified module.
:param name:
:param kwargs:
:return: | [
"Calls",
"a",
"function",
"from",
"the",
"specified",
"module",
"."
] | python | train |
zhelev/python-afsapi | afsapi/__init__.py | https://github.com/zhelev/python-afsapi/blob/bb1990cf1460ae42f2dde75f2291625ddac2c0e4/afsapi/__init__.py#L141-L147 | def handle_set(self, item, value):
"""Helper method for setting a value by using the fsapi API."""
doc = yield from self.call('SET/{}'.format(item), dict(value=value))
if doc is None:
return None
return doc.status == 'FS_OK' | [
"def",
"handle_set",
"(",
"self",
",",
"item",
",",
"value",
")",
":",
"doc",
"=",
"yield",
"from",
"self",
".",
"call",
"(",
"'SET/{}'",
".",
"format",
"(",
"item",
")",
",",
"dict",
"(",
"value",
"=",
"value",
")",
")",
"if",
"doc",
"is",
"None... | Helper method for setting a value by using the fsapi API. | [
"Helper",
"method",
"for",
"setting",
"a",
"value",
"by",
"using",
"the",
"fsapi",
"API",
"."
] | python | valid |
xflr6/gsheets | gsheets/api.py | https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/api.py#L92-L109 | def get(self, id_or_url, default=None):
"""Fetch and return the spreadsheet with the given id or url.
Args:
id_or_url (str): unique alphanumeric id or URL of the spreadsheet
Returns:
New SpreadSheet instance or given default if none is found
Raises:
V... | [
"def",
"get",
"(",
"self",
",",
"id_or_url",
",",
"default",
"=",
"None",
")",
":",
"if",
"'/'",
"in",
"id_or_url",
":",
"id",
"=",
"urls",
".",
"SheetUrl",
".",
"from_string",
"(",
"id_or_url",
")",
".",
"id",
"else",
":",
"id",
"=",
"id_or_url",
... | Fetch and return the spreadsheet with the given id or url.
Args:
id_or_url (str): unique alphanumeric id or URL of the spreadsheet
Returns:
New SpreadSheet instance or given default if none is found
Raises:
ValueError: if an URL is given from which no id coul... | [
"Fetch",
"and",
"return",
"the",
"spreadsheet",
"with",
"the",
"given",
"id",
"or",
"url",
"."
] | python | train |
projecthamster/hamster | src/hamster/lib/layout.py | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/layout.py#L474-L496 | def resize_children(self):
"""default container alignment is to pile stuff just up, respecting only
padding, margin and element's alignment properties"""
width = self.width - self.horizontal_padding
height = self.height - self.vertical_padding
for sprite, props in (get_props(spr... | [
"def",
"resize_children",
"(",
"self",
")",
":",
"width",
"=",
"self",
".",
"width",
"-",
"self",
".",
"horizontal_padding",
"height",
"=",
"self",
".",
"height",
"-",
"self",
".",
"vertical_padding",
"for",
"sprite",
",",
"props",
"in",
"(",
"get_props",
... | default container alignment is to pile stuff just up, respecting only
padding, margin and element's alignment properties | [
"default",
"container",
"alignment",
"is",
"to",
"pile",
"stuff",
"just",
"up",
"respecting",
"only",
"padding",
"margin",
"and",
"element",
"s",
"alignment",
"properties"
] | python | train |
Erotemic/utool | utool/util_gridsearch.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_gridsearch.py#L2033-L2117 | def interact_gridsearch_result_images(show_result_func, cfgdict_list,
cfglbl_list, cfgresult_list,
score_list=None, fnum=None, figtitle='',
unpack=False, max_plots=25, verbose=True,
... | [
"def",
"interact_gridsearch_result_images",
"(",
"show_result_func",
",",
"cfgdict_list",
",",
"cfglbl_list",
",",
"cfgresult_list",
",",
"score_list",
"=",
"None",
",",
"fnum",
"=",
"None",
",",
"figtitle",
"=",
"''",
",",
"unpack",
"=",
"False",
",",
"max_plot... | helper function for visualizing results of gridsearch | [
"helper",
"function",
"for",
"visualizing",
"results",
"of",
"gridsearch"
] | python | train |
bwohlberg/sporco | sporco/admm/pdcsc.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/pdcsc.py#L422-L432 | def block_sep1(self, Y):
r"""Separate variable into component corresponding to
:math:`\mathbf{y}_1` in :math:`\mathbf{y}\;\;`.
"""
# This method is overridden because we have to change the
# mechanism for combining the Y0 and Y1 blocks into a single
# array (see comment ... | [
"def",
"block_sep1",
"(",
"self",
",",
"Y",
")",
":",
"# This method is overridden because we have to change the",
"# mechanism for combining the Y0 and Y1 blocks into a single",
"# array (see comment in the __init__ method).",
"shp",
"=",
"Y",
".",
"shape",
"[",
"0",
":",
"sel... | r"""Separate variable into component corresponding to
:math:`\mathbf{y}_1` in :math:`\mathbf{y}\;\;`. | [
"r",
"Separate",
"variable",
"into",
"component",
"corresponding",
"to",
":",
"math",
":",
"\\",
"mathbf",
"{",
"y",
"}",
"_1",
"in",
":",
"math",
":",
"\\",
"mathbf",
"{",
"y",
"}",
"\\",
";",
"\\",
";",
"."
] | python | train |
twisted/epsilon | epsilon/hotfixes/timeoutmixin_calllater.py | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/hotfixes/timeoutmixin_calllater.py#L22-L41 | def setTimeout(self, period):
"""Change the timeout period
@type period: C{int} or C{NoneType}
@param period: The period, in seconds, to change the timeout to, or
C{None} to disable the timeout.
"""
prev = self.timeOut
self.timeOut = period
if self.__tim... | [
"def",
"setTimeout",
"(",
"self",
",",
"period",
")",
":",
"prev",
"=",
"self",
".",
"timeOut",
"self",
".",
"timeOut",
"=",
"period",
"if",
"self",
".",
"__timeoutCall",
"is",
"not",
"None",
":",
"if",
"period",
"is",
"None",
":",
"self",
".",
"__ti... | Change the timeout period
@type period: C{int} or C{NoneType}
@param period: The period, in seconds, to change the timeout to, or
C{None} to disable the timeout. | [
"Change",
"the",
"timeout",
"period"
] | python | train |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L5214-L5230 | def libvlc_audio_set_callbacks(mp, play, pause, resume, flush, drain, opaque):
'''Set callbacks and private data for decoded audio.
Use L{libvlc_audio_set_format}() or L{libvlc_audio_set_format_callbacks}()
to configure the decoded audio format.
@param mp: the media player.
@param play: callback to ... | [
"def",
"libvlc_audio_set_callbacks",
"(",
"mp",
",",
"play",
",",
"pause",
",",
"resume",
",",
"flush",
",",
"drain",
",",
"opaque",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_audio_set_callbacks'",
",",
"None",
")",
"or",
"_Cfunction",
"... | Set callbacks and private data for decoded audio.
Use L{libvlc_audio_set_format}() or L{libvlc_audio_set_format_callbacks}()
to configure the decoded audio format.
@param mp: the media player.
@param play: callback to play audio samples (must not be NULL).
@param pause: callback to pause playback (o... | [
"Set",
"callbacks",
"and",
"private",
"data",
"for",
"decoded",
"audio",
".",
"Use",
"L",
"{",
"libvlc_audio_set_format",
"}",
"()",
"or",
"L",
"{",
"libvlc_audio_set_format_callbacks",
"}",
"()",
"to",
"configure",
"the",
"decoded",
"audio",
"format",
"."
] | python | train |
absperf/python-req | req.py | https://github.com/absperf/python-req/blob/de878f08f4fb28fa140c80d5cbdb04518ef5e968/req.py#L83-L150 | def load(fp, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):
'''Load an object from the file pointer.
:param fp: A readable filehandle.
:param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types.
:param index_separator: The separator b... | [
"def",
"load",
"(",
"fp",
",",
"separator",
"=",
"DEFAULT",
",",
"index_separator",
"=",
"DEFAULT",
",",
"cls",
"=",
"dict",
",",
"list_cls",
"=",
"list",
")",
":",
"converter",
"=",
"None",
"output",
"=",
"cls",
"(",
")",
"arraykeys",
"=",
"set",
"(... | Load an object from the file pointer.
:param fp: A readable filehandle.
:param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types.
:param index_separator: The separator between key and index. Defaults to u'_' or b'_', depending on the types.
:param cls: A... | [
"Load",
"an",
"object",
"from",
"the",
"file",
"pointer",
"."
] | python | valid |
mitsei/dlkit | dlkit/records/osid/base_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/osid/base_records.py#L2383-L2389 | def clear_color_coordinate(self):
"""stub"""
if (self.get_color_coordinate_metadata().is_read_only() or
self.get_color_coordinate_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map['colorCoordinate'] = \
dict(self.get_color_coordi... | [
"def",
"clear_color_coordinate",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"get_color_coordinate_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
"or",
"self",
".",
"get_color_coordinate_metadata",
"(",
")",
".",
"is_required",
"(",
")",
")",
":",
"r... | stub | [
"stub"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L604-L609 | def is_beating(self):
"""Is the heartbeat running and responsive (and not paused)."""
if self.is_alive() and not self._pause and self._beating:
return True
else:
return False | [
"def",
"is_beating",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_alive",
"(",
")",
"and",
"not",
"self",
".",
"_pause",
"and",
"self",
".",
"_beating",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Is the heartbeat running and responsive (and not paused). | [
"Is",
"the",
"heartbeat",
"running",
"and",
"responsive",
"(",
"and",
"not",
"paused",
")",
"."
] | python | test |
CalebBell/ht | ht/conv_free_immersed.py | https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/conv_free_immersed.py#L521-L579 | def Nu_vertical_cylinder_Kreith_Eckert(Pr, Gr, turbulent=None):
r'''Calculates Nusselt number for natural convection around a vertical
isothermal cylinder according to the results of [1]_ correlated by
[2]_, also as presented in [3]_, [4]_, and [5]_.
.. math::
Nu_H = 0.555 Ra_H^{0.25},\; 10^{5... | [
"def",
"Nu_vertical_cylinder_Kreith_Eckert",
"(",
"Pr",
",",
"Gr",
",",
"turbulent",
"=",
"None",
")",
":",
"Ra",
"=",
"Pr",
"*",
"Gr",
"if",
"turbulent",
"or",
"(",
"Ra",
">",
"1E9",
"and",
"turbulent",
"is",
"None",
")",
":",
"return",
"0.021",
"*",
... | r'''Calculates Nusselt number for natural convection around a vertical
isothermal cylinder according to the results of [1]_ correlated by
[2]_, also as presented in [3]_, [4]_, and [5]_.
.. math::
Nu_H = 0.555 Ra_H^{0.25},\; 10^{5} < Ra < 10^{9}
Nu_H = 0.021 Ra_H^{0.4},\; 10^{9} < Ra < 10... | [
"r",
"Calculates",
"Nusselt",
"number",
"for",
"natural",
"convection",
"around",
"a",
"vertical",
"isothermal",
"cylinder",
"according",
"to",
"the",
"results",
"of",
"[",
"1",
"]",
"_",
"correlated",
"by",
"[",
"2",
"]",
"_",
"also",
"as",
"presented",
"... | python | train |
xu2243051/easyui-menu | easyui/mixins/view_mixins.py | https://github.com/xu2243051/easyui-menu/blob/4da0b50cf2d3ddb0f1ec7a4da65fd3c4339f8dfb/easyui/mixins/view_mixins.py#L65-L71 | def get_template_names(self):
"""
datagrid的默认模板
"""
names = super(EasyUIDeleteView, self).get_template_names()
names.append('easyui/confirm_delete.html')
return names | [
"def",
"get_template_names",
"(",
"self",
")",
":",
"names",
"=",
"super",
"(",
"EasyUIDeleteView",
",",
"self",
")",
".",
"get_template_names",
"(",
")",
"names",
".",
"append",
"(",
"'easyui/confirm_delete.html'",
")",
"return",
"names"
] | datagrid的默认模板 | [
"datagrid的默认模板"
] | python | valid |
log2timeline/dfvfs | dfvfs/vfs/encoded_stream_file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/encoded_stream_file_system.py#L72-L81 | def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
EncodedStreamFileEntry: a file entry or None if not available.
"""
path_spec = encoded_stream_path_spec.EncodedStreamPathSpec(
encoding_method=self._encoding_method,
parent=self._path_spec.parent)
return se... | [
"def",
"GetRootFileEntry",
"(",
"self",
")",
":",
"path_spec",
"=",
"encoded_stream_path_spec",
".",
"EncodedStreamPathSpec",
"(",
"encoding_method",
"=",
"self",
".",
"_encoding_method",
",",
"parent",
"=",
"self",
".",
"_path_spec",
".",
"parent",
")",
"return",... | Retrieves the root file entry.
Returns:
EncodedStreamFileEntry: a file entry or None if not available. | [
"Retrieves",
"the",
"root",
"file",
"entry",
"."
] | python | train |
eumis/pyviews | pyviews/core/common.py | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/common.py#L38-L40 | def add_cause(self, error: Exception):
'''Adds cause error to error message'''
self.add_info('Cause error', '{0} - {1}'.format(type(error).__name__, error)) | [
"def",
"add_cause",
"(",
"self",
",",
"error",
":",
"Exception",
")",
":",
"self",
".",
"add_info",
"(",
"'Cause error'",
",",
"'{0} - {1}'",
".",
"format",
"(",
"type",
"(",
"error",
")",
".",
"__name__",
",",
"error",
")",
")"
] | Adds cause error to error message | [
"Adds",
"cause",
"error",
"to",
"error",
"message"
] | python | train |
fhcrc/seqmagick | seqmagick/transform.py | https://github.com/fhcrc/seqmagick/blob/1642bb87ba5c171fbd307f9da0f8a0ee1d69d5ed/seqmagick/transform.py#L256-L267 | def multi_mask_sequences(records, slices):
"""
Replace characters sliced by slices with gap characters.
"""
for record in records:
record_indices = list(range(len(record)))
keep_indices = reduce(lambda i, s: i - frozenset(record_indices[s]),
slices, frozense... | [
"def",
"multi_mask_sequences",
"(",
"records",
",",
"slices",
")",
":",
"for",
"record",
"in",
"records",
":",
"record_indices",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"record",
")",
")",
")",
"keep_indices",
"=",
"reduce",
"(",
"lambda",
"i",
",",
... | Replace characters sliced by slices with gap characters. | [
"Replace",
"characters",
"sliced",
"by",
"slices",
"with",
"gap",
"characters",
"."
] | python | train |
apache/incubator-mxnet | example/ctc/lstm_ocr_train.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm_ocr_train.py#L58-L121 | def main():
"""Program entry point"""
args = parse_args()
if not any(args.loss == s for s in ['ctc', 'warpctc']):
raise ValueError("Invalid loss '{}' (must be 'ctc' or 'warpctc')".format(args.loss))
hp = Hyperparams()
# Start a multiprocessor captcha image generator
mp_captcha = MPDigi... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"if",
"not",
"any",
"(",
"args",
".",
"loss",
"==",
"s",
"for",
"s",
"in",
"[",
"'ctc'",
",",
"'warpctc'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid loss '{}' (must be 'ctc'... | Program entry point | [
"Program",
"entry",
"point"
] | python | train |
lsst-sqre/lsst-projectmeta-kit | lsstprojectmeta/git/timestamp.py | https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/git/timestamp.py#L88-L165 | def get_content_commit_date(extensions, acceptance_callback=None,
root_dir='.'):
"""Get the datetime for the most recent commit to a project that
affected certain types of content.
Parameters
----------
extensions : sequence of 'str'
Extensions of files to consid... | [
"def",
"get_content_commit_date",
"(",
"extensions",
",",
"acceptance_callback",
"=",
"None",
",",
"root_dir",
"=",
"'.'",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"def",
"_null_callback",
"(",
"_",
")",
":",
"return",
"Tru... | Get the datetime for the most recent commit to a project that
affected certain types of content.
Parameters
----------
extensions : sequence of 'str'
Extensions of files to consider in getting the most recent commit
date. For example, ``('rst', 'svg', 'png')`` are content extensions
... | [
"Get",
"the",
"datetime",
"for",
"the",
"most",
"recent",
"commit",
"to",
"a",
"project",
"that",
"affected",
"certain",
"types",
"of",
"content",
"."
] | python | valid |
CalebBell/thermo | thermo/volume.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L937-L1023 | def load_all_methods(self):
r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,
:obj:`all_methods` and obj:`all_methods_P` as a set of... | [
"def",
"load_all_methods",
"(",
"self",
")",
":",
"methods",
"=",
"[",
"]",
"methods_P",
"=",
"[",
"]",
"Tmins",
",",
"Tmaxs",
"=",
"[",
"]",
",",
"[",
"]",
"if",
"has_CoolProp",
"and",
"self",
".",
"CASRN",
"in",
"coolprop_dict",
":",
"methods",
"."... | r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,
:obj:`all_methods` and obj:`all_methods_P` as a set of methods for
which the data ... | [
"r",
"Method",
"which",
"picks",
"out",
"coefficients",
"for",
"the",
"specified",
"chemical",
"from",
"the",
"various",
"dictionaries",
"and",
"DataFrames",
"storing",
"it",
".",
"All",
"data",
"is",
"stored",
"as",
"attributes",
".",
"This",
"method",
"also"... | python | valid |
wesm/feather | cpp/build-support/cpplint.py | https://github.com/wesm/feather/blob/99267b30461c46b9e437f95e1d9338a92a854270/cpp/build-support/cpplint.py#L3776-L3809 | def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error):
"""Check for rvalue references.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance w... | [
"def",
"CheckRValueReference",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Find lines missing spaces around &&.",
"# TODO(unknown): currently we don't check for rvalue references",
"# with spaces surrounding the && to avoid fa... | Check for rvalue references.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested block... | [
"Check",
"for",
"rvalue",
"references",
"."
] | python | train |
wind-python/windpowerlib | windpowerlib/wake_losses.py | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/wake_losses.py#L59-L150 | def get_wind_efficiency_curve(curve_name='all'):
r"""
Reads wind efficiency curve(s) specified in `curve_name`.
Parameters
----------
curve_name : str or list
Specifies the curve. Use 'all' to get all curves in a MultiIndex
DataFrame or one of the curve names to retrieve a single cu... | [
"def",
"get_wind_efficiency_curve",
"(",
"curve_name",
"=",
"'all'",
")",
":",
"possible_curve_names",
"=",
"[",
"'dena_mean'",
",",
"'knorr_mean'",
",",
"'dena_extreme1'",
",",
"'dena_extreme2'",
",",
"'knorr_extreme1'",
",",
"'knorr_extreme2'",
",",
"'knorr_extreme3'"... | r"""
Reads wind efficiency curve(s) specified in `curve_name`.
Parameters
----------
curve_name : str or list
Specifies the curve. Use 'all' to get all curves in a MultiIndex
DataFrame or one of the curve names to retrieve a single curve.
Default: 'all'.
Returns
-------... | [
"r",
"Reads",
"wind",
"efficiency",
"curve",
"(",
"s",
")",
"specified",
"in",
"curve_name",
"."
] | python | train |
getpelican/pelican-plugins | events/events.py | https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/events/events.py#L159-L168 | def generate_events_list(generator):
"""Populate the event_list variable to be used in jinja templates"""
if not localized_events:
generator.context['events_list'] = sorted(events, reverse = True,
key=lambda ev: (ev.dtstart, ev.dtend))
else:
... | [
"def",
"generate_events_list",
"(",
"generator",
")",
":",
"if",
"not",
"localized_events",
":",
"generator",
".",
"context",
"[",
"'events_list'",
"]",
"=",
"sorted",
"(",
"events",
",",
"reverse",
"=",
"True",
",",
"key",
"=",
"lambda",
"ev",
":",
"(",
... | Populate the event_list variable to be used in jinja templates | [
"Populate",
"the",
"event_list",
"variable",
"to",
"be",
"used",
"in",
"jinja",
"templates"
] | python | train |
fastai/fastai | fastai/train.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L34-L43 | def to_fp16(learn:Learner, loss_scale:float=None, max_noskip:int=1000, dynamic:bool=True, clip:float=None,
flat_master:bool=False, max_scale:float=2**24)->Learner:
"Put `learn` in FP16 precision mode."
learn.to_fp32()
learn.model = model2half(learn.model)
learn.data.add_tfm(batch_to_half)
... | [
"def",
"to_fp16",
"(",
"learn",
":",
"Learner",
",",
"loss_scale",
":",
"float",
"=",
"None",
",",
"max_noskip",
":",
"int",
"=",
"1000",
",",
"dynamic",
":",
"bool",
"=",
"True",
",",
"clip",
":",
"float",
"=",
"None",
",",
"flat_master",
":",
"bool... | Put `learn` in FP16 precision mode. | [
"Put",
"learn",
"in",
"FP16",
"precision",
"mode",
"."
] | python | train |
alephdata/memorious | memorious/helpers/__init__.py | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/helpers/__init__.py#L33-L39 | def search_results_total(html, xpath, check, delimiter):
""" Get the total number of results from the DOM of a search index. """
for container in html.findall(xpath):
if check in container.findtext('.'):
text = container.findtext('.').split(delimiter)
total = int(text[-1].strip()... | [
"def",
"search_results_total",
"(",
"html",
",",
"xpath",
",",
"check",
",",
"delimiter",
")",
":",
"for",
"container",
"in",
"html",
".",
"findall",
"(",
"xpath",
")",
":",
"if",
"check",
"in",
"container",
".",
"findtext",
"(",
"'.'",
")",
":",
"text... | Get the total number of results from the DOM of a search index. | [
"Get",
"the",
"total",
"number",
"of",
"results",
"from",
"the",
"DOM",
"of",
"a",
"search",
"index",
"."
] | python | train |
pgxcentre/geneparse | geneparse/readers/impute2.py | https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L222-L239 | def _get_biallelic_variant(self, variant, info, _check_alleles=True):
"""Creates a bi-allelic variant."""
info = info.iloc[0, :]
assert not info.multiallelic
# Seeking and parsing the file
self._impute2_file.seek(info.seek)
genotypes = self._parse_impute2_line(self._impu... | [
"def",
"_get_biallelic_variant",
"(",
"self",
",",
"variant",
",",
"info",
",",
"_check_alleles",
"=",
"True",
")",
":",
"info",
"=",
"info",
".",
"iloc",
"[",
"0",
",",
":",
"]",
"assert",
"not",
"info",
".",
"multiallelic",
"# Seeking and parsing the file"... | Creates a bi-allelic variant. | [
"Creates",
"a",
"bi",
"-",
"allelic",
"variant",
"."
] | python | train |
GluuFederation/oxd-python | oxdpython/client.py | https://github.com/GluuFederation/oxd-python/blob/a0448cda03b4384bc50a8c20bd65eacd983bceb8/oxdpython/client.py#L115-L153 | def get_authorization_url(self, acr_values=None, prompt=None, scope=None,
custom_params=None):
"""Function to get the authorization url that can be opened in the
browser for the user to provide authorization and authentication
Parameters:
* **acr_values... | [
"def",
"get_authorization_url",
"(",
"self",
",",
"acr_values",
"=",
"None",
",",
"prompt",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"custom_params",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"oxd_id\"",
":",
"self",
".",
"oxd_id",
"}",
"if",
"s... | Function to get the authorization url that can be opened in the
browser for the user to provide authorization and authentication
Parameters:
* **acr_values (list, optional):** acr values in the order of priority
* **prompt (string, optional):** prompt=login is required if you wa... | [
"Function",
"to",
"get",
"the",
"authorization",
"url",
"that",
"can",
"be",
"opened",
"in",
"the",
"browser",
"for",
"the",
"user",
"to",
"provide",
"authorization",
"and",
"authentication"
] | python | train |
modin-project/modin | modin/backends/pandas/query_compiler.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/backends/pandas/query_compiler.py#L1564-L1601 | def mode(self, **kwargs):
"""Returns a new QueryCompiler with modes calculated for each label along given axis.
Returns:
A new QueryCompiler with modes calculated.
"""
axis = kwargs.get("axis", 0)
def mode_builder(df, **kwargs):
result = df.mode(**kwargs... | [
"def",
"mode",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"axis",
"=",
"kwargs",
".",
"get",
"(",
"\"axis\"",
",",
"0",
")",
"def",
"mode_builder",
"(",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"df",
".",
"mode",
"(",
"*",
... | Returns a new QueryCompiler with modes calculated for each label along given axis.
Returns:
A new QueryCompiler with modes calculated. | [
"Returns",
"a",
"new",
"QueryCompiler",
"with",
"modes",
"calculated",
"for",
"each",
"label",
"along",
"given",
"axis",
"."
] | python | train |
briancappello/flask-unchained | flask_unchained/bundles/security/extensions/security.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/extensions/security.py#L215-L226 | def _get_pwd_context(self, app: FlaskUnchained) -> CryptContext:
"""
Get the password hashing context.
"""
pw_hash = app.config.SECURITY_PASSWORD_HASH
schemes = app.config.SECURITY_PASSWORD_SCHEMES
if pw_hash not in schemes:
allowed = (', '.join(schemes[:-1]) ... | [
"def",
"_get_pwd_context",
"(",
"self",
",",
"app",
":",
"FlaskUnchained",
")",
"->",
"CryptContext",
":",
"pw_hash",
"=",
"app",
".",
"config",
".",
"SECURITY_PASSWORD_HASH",
"schemes",
"=",
"app",
".",
"config",
".",
"SECURITY_PASSWORD_SCHEMES",
"if",
"pw_hash... | Get the password hashing context. | [
"Get",
"the",
"password",
"hashing",
"context",
"."
] | python | train |
rsgalloway/grit | grit/server/handler.py | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/handler.py#L79-L84 | def handle_versions(repo, **kwargs):
""":return: repo.versions()"""
log.info('versions: %s %s' %(repo, kwargs))
if not hasattr(repo, 'versions'):
return []
return [v.serialize() for v in repo.versions(**kwargs)] | [
"def",
"handle_versions",
"(",
"repo",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"info",
"(",
"'versions: %s %s'",
"%",
"(",
"repo",
",",
"kwargs",
")",
")",
"if",
"not",
"hasattr",
"(",
"repo",
",",
"'versions'",
")",
":",
"return",
"[",
"]",
... | :return: repo.versions() | [
":",
"return",
":",
"repo",
".",
"versions",
"()"
] | python | train |
googledatalab/pydatalab | google/datalab/bigquery/commands/_bigquery.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L519-L545 | def _datasource_cell(args, cell_body):
"""Implements the BigQuery datasource cell magic for ipython notebooks.
The supported syntax is
%%bq datasource --name <var> --paths <url> [--format <CSV|JSON>]
<schema>
Args:
args: the optional arguments following '%%bq datasource'
cell_body: the datasource's ... | [
"def",
"_datasource_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"name",
"=",
"args",
"[",
"'name'",
"]",
"paths",
"=",
"args",
"[",
"'paths'",
"]",
"data_format",
"=",
"(",
"args",
"[",
"'format'",
"]",
"or",
"'CSV'",
")",
".",
"lower",
"(",
")",... | Implements the BigQuery datasource cell magic for ipython notebooks.
The supported syntax is
%%bq datasource --name <var> --paths <url> [--format <CSV|JSON>]
<schema>
Args:
args: the optional arguments following '%%bq datasource'
cell_body: the datasource's schema in json/yaml | [
"Implements",
"the",
"BigQuery",
"datasource",
"cell",
"magic",
"for",
"ipython",
"notebooks",
"."
] | python | train |
apache/spark | python/pyspark/sql/functions.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L1283-L1316 | def from_utc_timestamp(timestamp, tz):
"""
This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function
takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in UTC, and
renders that timestamp as a timestamp in the given time zone.
However, t... | [
"def",
"from_utc_timestamp",
"(",
"timestamp",
",",
"tz",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Deprecated in 3.0. See SPARK-25496\"",
",",
"DeprecationWarning",
")",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"if",
"isinstance",
"(",
"tz",
",",
... | This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function
takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in UTC, and
renders that timestamp as a timestamp in the given time zone.
However, timestamp in Spark represents number of microseconds... | [
"This",
"is",
"a",
"common",
"function",
"for",
"databases",
"supporting",
"TIMESTAMP",
"WITHOUT",
"TIMEZONE",
".",
"This",
"function",
"takes",
"a",
"timestamp",
"which",
"is",
"timezone",
"-",
"agnostic",
"and",
"interprets",
"it",
"as",
"a",
"timestamp",
"i... | python | train |
ellmetha/django-machina | machina/apps/forum/abstract_models.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L155-L173 | def save(self, *args, **kwargs):
""" Saves the forum instance. """
# It is vital to track the changes of the parent associated with a forum in order to
# maintain counters up-to-date and to trigger other operations such as permissions updates.
old_instance = None
if self.pk:
... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# It is vital to track the changes of the parent associated with a forum in order to",
"# maintain counters up-to-date and to trigger other operations such as permissions updates.",
"old_instance",
"=",... | Saves the forum instance. | [
"Saves",
"the",
"forum",
"instance",
"."
] | python | train |
howie6879/ruia | ruia/middleware.py | https://github.com/howie6879/ruia/blob/2dc5262fc9c3e902a8faa7d5fa2f046f9d9ee1fa/ruia/middleware.py#L19-L31 | def request(self, *args, **kwargs):
"""
Define a Decorate to be called before a request.
eg: @middleware.request
"""
middleware = args[0]
@wraps(middleware)
def register_middleware(*args, **kwargs):
self.request_middleware.append(middleware)
... | [
"def",
"request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"middleware",
"=",
"args",
"[",
"0",
"]",
"@",
"wraps",
"(",
"middleware",
")",
"def",
"register_middleware",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | Define a Decorate to be called before a request.
eg: @middleware.request | [
"Define",
"a",
"Decorate",
"to",
"be",
"called",
"before",
"a",
"request",
".",
"eg",
":"
] | python | test |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/detector/sampler.py | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/detector/sampler.py#L156-L195 | def iterate_cascade(self, cascade, image, threshold = None):
"""iterate_cascade(self, cascade, image, [threshold]) -> prediction, bounding_box
Iterates over the given image and computes the cascade of classifiers.
This function will compute the cascaded classification result for the given ``image`` using t... | [
"def",
"iterate_cascade",
"(",
"self",
",",
"cascade",
",",
"image",
",",
"threshold",
"=",
"None",
")",
":",
"for",
"scale",
",",
"scaled_image_shape",
"in",
"self",
".",
"scales",
"(",
"image",
")",
":",
"# prepare the feature extractor to extract features from ... | iterate_cascade(self, cascade, image, [threshold]) -> prediction, bounding_box
Iterates over the given image and computes the cascade of classifiers.
This function will compute the cascaded classification result for the given ``image`` using the given ``cascade``.
It yields a tuple of prediction value and ... | [
"iterate_cascade",
"(",
"self",
"cascade",
"image",
"[",
"threshold",
"]",
")",
"-",
">",
"prediction",
"bounding_box"
] | python | train |
vfilimonov/pydatastream | pydatastream/pydatastream.py | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L598-L646 | def get_epit_vintage_matrix(self, mnemonic, date_from='1951-01-01', date_to=None):
""" Construct the vintage matrix for a given economic series.
Requires subscription to Thomson Reuters Economic Point-in-Time (EPiT).
Vintage matrix represents a DataFrame where columns correspond to a
... | [
"def",
"get_epit_vintage_matrix",
"(",
"self",
",",
"mnemonic",
",",
"date_from",
"=",
"'1951-01-01'",
",",
"date_to",
"=",
"None",
")",
":",
"# Get first available date from the REL1 series",
"rel1",
"=",
"self",
".",
"fetch",
"(",
"mnemonic",
",",
"'REL1'",
",",... | Construct the vintage matrix for a given economic series.
Requires subscription to Thomson Reuters Economic Point-in-Time (EPiT).
Vintage matrix represents a DataFrame where columns correspond to a
particular period (quarter or month) for the reported statistic and
index... | [
"Construct",
"the",
"vintage",
"matrix",
"for",
"a",
"given",
"economic",
"series",
".",
"Requires",
"subscription",
"to",
"Thomson",
"Reuters",
"Economic",
"Point",
"-",
"in",
"-",
"Time",
"(",
"EPiT",
")",
"."
] | python | train |
mk-fg/feedjack | feedjack/models.py | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/models.py#L616-L622 | def update_handler(feeds):
'''Update all cross-referencing filters results for feeds and others, related to them.
Intended to be called from non-Feed update hooks (like new Post saving).'''
# Check if this call is a result of actions initiated from
# one of the hooks in a higher frame (resulting in recursion)... | [
"def",
"update_handler",
"(",
"feeds",
")",
":",
"# Check if this call is a result of actions initiated from",
"# one of the hooks in a higher frame (resulting in recursion).",
"if",
"Feed",
".",
"_filters_update_handler_lock",
":",
"return",
"return",
"Feed",
".",
"_filters_updat... | Update all cross-referencing filters results for feeds and others, related to them.
Intended to be called from non-Feed update hooks (like new Post saving). | [
"Update",
"all",
"cross",
"-",
"referencing",
"filters",
"results",
"for",
"feeds",
"and",
"others",
"related",
"to",
"them",
".",
"Intended",
"to",
"be",
"called",
"from",
"non",
"-",
"Feed",
"update",
"hooks",
"(",
"like",
"new",
"Post",
"saving",
")",
... | python | train |
stephenmcd/gnotty | gnotty/migrations/0003_joins_leaves.py | https://github.com/stephenmcd/gnotty/blob/bea3762dc9cbc3cb21a5ae7224091cf027273c40/gnotty/migrations/0003_joins_leaves.py#L9-L14 | def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
if not db.dry_run:
orm['gnotty.IRCMessage'].objects.filter(message="joins").update(join_or_leave=True)
orm['gnotty.IRCMessage... | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"# Note: Remember to use orm['appname.ModelName'] rather than \"from appname.models...\"",
"if",
"not",
"db",
".",
"dry_run",
":",
"orm",
"[",
"'gnotty.IRCMessage'",
"]",
".",
"objects",
".",
"filter",
"(",
"messag... | Write your forwards methods here. | [
"Write",
"your",
"forwards",
"methods",
"here",
"."
] | python | train |
dshean/pygeotools | pygeotools/lib/malib.py | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/malib.py#L1474-L1488 | def nanfill(a, f_a, *args, **kwargs):
"""Fill masked areas with np.nan
Wrapper for functions that can't handle ma (e.g. scipy.ndimage)
This will force filters to ignore nan, but causes adjacent pixels to be set to nan as well: http://projects.scipy.org/scipy/ticket/1155
"""
a = checkma(a)
... | [
"def",
"nanfill",
"(",
"a",
",",
"f_a",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"a",
"=",
"checkma",
"(",
"a",
")",
"ndv",
"=",
"a",
".",
"fill_value",
"#Note: The following fails for arrays that are not float (np.nan is float)",
"b",
"=",
"f_a"... | Fill masked areas with np.nan
Wrapper for functions that can't handle ma (e.g. scipy.ndimage)
This will force filters to ignore nan, but causes adjacent pixels to be set to nan as well: http://projects.scipy.org/scipy/ticket/1155 | [
"Fill",
"masked",
"areas",
"with",
"np",
".",
"nan"
] | python | train |
rwl/pylon | pylon/io/rst.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/rst.py#L312-L355 | def write_how_many(self, file):
""" Writes component numbers to a table.
"""
report = CaseReport(self.case)
# Map component labels to attribute names
components = [("Bus", "n_buses"), ("Generator", "n_generators"),
("Committed Generator", "n_online_generators"),
... | [
"def",
"write_how_many",
"(",
"self",
",",
"file",
")",
":",
"report",
"=",
"CaseReport",
"(",
"self",
".",
"case",
")",
"# Map component labels to attribute names",
"components",
"=",
"[",
"(",
"\"Bus\"",
",",
"\"n_buses\"",
")",
",",
"(",
"\"Generator\"",
",... | Writes component numbers to a table. | [
"Writes",
"component",
"numbers",
"to",
"a",
"table",
"."
] | python | train |
aestrivex/bctpy | bct/algorithms/distance.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/distance.py#L540-L644 | def efficiency_wei(Gw, local=False):
'''
The global efficiency is the average of inverse shortest path length,
and is inversely related to the characteristic path length.
The local efficiency is the global efficiency computed on the
neighborhood of the node, and is related to the clustering coeffic... | [
"def",
"efficiency_wei",
"(",
"Gw",
",",
"local",
"=",
"False",
")",
":",
"def",
"distance_inv_wei",
"(",
"G",
")",
":",
"n",
"=",
"len",
"(",
"G",
")",
"D",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
")",
"# distance matrix",
"D",
... | The global efficiency is the average of inverse shortest path length,
and is inversely related to the characteristic path length.
The local efficiency is the global efficiency computed on the
neighborhood of the node, and is related to the clustering coefficient.
Parameters
----------
W : NxN ... | [
"The",
"global",
"efficiency",
"is",
"the",
"average",
"of",
"inverse",
"shortest",
"path",
"length",
"and",
"is",
"inversely",
"related",
"to",
"the",
"characteristic",
"path",
"length",
"."
] | python | train |
eXamadeus/godaddypy | godaddypy/client.py | https://github.com/eXamadeus/godaddypy/blob/67820604ffe233a67ef9f6b3a59ab85b02653e57/godaddypy/client.py#L187-L203 | def replace_records(self, domain, records, record_type=None, name=None):
"""This will replace all records at the domain. Record type and record name can be provided to filter
which records to replace.
:param domain: the domain to replace records at
:param records: the records you will ... | [
"def",
"replace_records",
"(",
"self",
",",
"domain",
",",
"records",
",",
"record_type",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_build_record_url",
"(",
"domain",
",",
"name",
"=",
"name",
",",
"record_type",
"=",
"... | This will replace all records at the domain. Record type and record name can be provided to filter
which records to replace.
:param domain: the domain to replace records at
:param records: the records you will be saving
:param record_type: the type of records you want to replace (eg. o... | [
"This",
"will",
"replace",
"all",
"records",
"at",
"the",
"domain",
".",
"Record",
"type",
"and",
"record",
"name",
"can",
"be",
"provided",
"to",
"filter",
"which",
"records",
"to",
"replace",
"."
] | python | train |
sassoo/goldman | goldman/serializers/jsonapi_error.py | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/serializers/jsonapi_error.py#L74-L85 | def get_headers(self):
""" Return a HTTPStatus compliant headers attribute
FIX: duplicate headers will collide terribly!
"""
headers = {'Content-Type': goldman.JSON_MIMETYPE}
for error in self.errors:
if 'headers' in error:
headers.update(error['hea... | [
"def",
"get_headers",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"goldman",
".",
"JSON_MIMETYPE",
"}",
"for",
"error",
"in",
"self",
".",
"errors",
":",
"if",
"'headers'",
"in",
"error",
":",
"headers",
".",
"update",
"(",
"error"... | Return a HTTPStatus compliant headers attribute
FIX: duplicate headers will collide terribly! | [
"Return",
"a",
"HTTPStatus",
"compliant",
"headers",
"attribute"
] | python | train |
neherlab/treetime | treetime/gtr.py | https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L229-L369 | def standard(model, **kwargs):
"""
Create standard model of molecular evolution.
Parameters
----------
model : str
Model to create. See list of available models below
**kwargs:
Key word arguments to be passed to the model
**Available ... | [
"def",
"standard",
"(",
"model",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"nuc_models",
"import",
"JC69",
",",
"K80",
",",
"F81",
",",
"HKY85",
",",
"T92",
",",
"TN93",
"from",
".",
"aa_models",
"import",
"JTT92",
"if",
"model",
".",
"lower",
... | Create standard model of molecular evolution.
Parameters
----------
model : str
Model to create. See list of available models below
**kwargs:
Key word arguments to be passed to the model
**Available models**
- JC69:
Jukes-Cantor 1... | [
"Create",
"standard",
"model",
"of",
"molecular",
"evolution",
"."
] | python | test |
Blueqat/Blueqat | blueqat/pauli.py | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L707-L709 | def max_n(self):
"""Returns the maximum index of Pauli matrices in the Term."""
return max(term.max_n() for term in self.terms if term.ops) | [
"def",
"max_n",
"(",
"self",
")",
":",
"return",
"max",
"(",
"term",
".",
"max_n",
"(",
")",
"for",
"term",
"in",
"self",
".",
"terms",
"if",
"term",
".",
"ops",
")"
] | Returns the maximum index of Pauli matrices in the Term. | [
"Returns",
"the",
"maximum",
"index",
"of",
"Pauli",
"matrices",
"in",
"the",
"Term",
"."
] | python | train |
devopshq/artifactory | artifactory.py | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L662-L673 | def owner(self, pathobj):
"""
Returns file owner
This makes little sense for Artifactory, but to be consistent
with pathlib, we return modified_by instead, if available
"""
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.modified_by
... | [
"def",
"owner",
"(",
"self",
",",
"pathobj",
")",
":",
"stat",
"=",
"self",
".",
"stat",
"(",
"pathobj",
")",
"if",
"not",
"stat",
".",
"is_dir",
":",
"return",
"stat",
".",
"modified_by",
"else",
":",
"return",
"'nobody'"
] | Returns file owner
This makes little sense for Artifactory, but to be consistent
with pathlib, we return modified_by instead, if available | [
"Returns",
"file",
"owner",
"This",
"makes",
"little",
"sense",
"for",
"Artifactory",
"but",
"to",
"be",
"consistent",
"with",
"pathlib",
"we",
"return",
"modified_by",
"instead",
"if",
"available"
] | python | train |
jmcarp/robobrowser | robobrowser/browser.py | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L311-L323 | def follow_link(self, link, **kwargs):
"""Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send`
"""
try:
href = link['href']
except KeyError:
raise exceptions.RoboError('Link element must have "href" '
... | [
"def",
"follow_link",
"(",
"self",
",",
"link",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"href",
"=",
"link",
"[",
"'href'",
"]",
"except",
"KeyError",
":",
"raise",
"exceptions",
".",
"RoboError",
"(",
"'Link element must have \"href\" '",
"'attribute... | Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send` | [
"Click",
"a",
"link",
"."
] | python | train |
pgjones/quart | quart/blueprints.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L694-L711 | def register(
self,
app: 'Quart',
first_registration: bool,
*,
url_prefix: Optional[str]=None,
) -> None:
"""Register this blueprint on the app given."""
state = self.make_setup_state(app, first_registration, url_prefix=url_prefix)
... | [
"def",
"register",
"(",
"self",
",",
"app",
":",
"'Quart'",
",",
"first_registration",
":",
"bool",
",",
"*",
",",
"url_prefix",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"state",
"=",
"self",
".",
"make_setup_state",
... | Register this blueprint on the app given. | [
"Register",
"this",
"blueprint",
"on",
"the",
"app",
"given",
"."
] | python | train |
rsennrich/Bleualign | bleualign/gale_church.py | https://github.com/rsennrich/Bleualign/blob/1de181dcc3257d885a2b981f751c0220c0e8958f/bleualign/gale_church.py#L10-L27 | def erfcc(x):
"""Complementary error function."""
z = abs(x)
t = 1 / (1 + 0.5 * z)
r = t * math.exp(-z * z -
1.26551223 + t *
(1.00002368 + t *
(.37409196 + t *
(.09678418 + t *
(-.18628806 + t... | [
"def",
"erfcc",
"(",
"x",
")",
":",
"z",
"=",
"abs",
"(",
"x",
")",
"t",
"=",
"1",
"/",
"(",
"1",
"+",
"0.5",
"*",
"z",
")",
"r",
"=",
"t",
"*",
"math",
".",
"exp",
"(",
"-",
"z",
"*",
"z",
"-",
"1.26551223",
"+",
"t",
"*",
"(",
"1.00... | Complementary error function. | [
"Complementary",
"error",
"function",
"."
] | python | test |
aio-libs/aioredis | aioredis/sentinel/commands.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/sentinel/commands.py#L78-L81 | def master_address(self, name):
"""Returns a (host, port) pair for the given ``name``."""
fut = self.execute(b'get-master-addr-by-name', name, encoding='utf-8')
return wait_convert(fut, parse_address) | [
"def",
"master_address",
"(",
"self",
",",
"name",
")",
":",
"fut",
"=",
"self",
".",
"execute",
"(",
"b'get-master-addr-by-name'",
",",
"name",
",",
"encoding",
"=",
"'utf-8'",
")",
"return",
"wait_convert",
"(",
"fut",
",",
"parse_address",
")"
] | Returns a (host, port) pair for the given ``name``. | [
"Returns",
"a",
"(",
"host",
"port",
")",
"pair",
"for",
"the",
"given",
"name",
"."
] | python | train |
yjzhang/uncurl_python | uncurl/gap_score.py | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/gap_score.py#L7-L25 | def preproc_data(data, gene_subset=False, **kwargs):
"""
basic data preprocessing before running gap score
Assumes that data is a matrix of shape (genes, cells).
Returns a matrix of shape (cells, 8), using the first 8 SVD
components. Why 8? It's an arbitrary selection...
"""
import uncurl
... | [
"def",
"preproc_data",
"(",
"data",
",",
"gene_subset",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"uncurl",
"from",
"uncurl",
".",
"preprocessing",
"import",
"log1p",
",",
"cell_normalize",
"from",
"sklearn",
".",
"decomposition",
"import",
... | basic data preprocessing before running gap score
Assumes that data is a matrix of shape (genes, cells).
Returns a matrix of shape (cells, 8), using the first 8 SVD
components. Why 8? It's an arbitrary selection... | [
"basic",
"data",
"preprocessing",
"before",
"running",
"gap",
"score"
] | python | train |
xtuml/pyxtuml | xtuml/load.py | https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/load.py#L615-L620 | def p_create_rop_statement(self, p):
'''create_rop_statement : CREATE ROP REF_ID RELID FROM association_end TO association_end'''
args = [p[4]]
args.extend(p[6])
args.extend(p[8])
p[0] = CreateAssociationStmt(*args) | [
"def",
"p_create_rop_statement",
"(",
"self",
",",
"p",
")",
":",
"args",
"=",
"[",
"p",
"[",
"4",
"]",
"]",
"args",
".",
"extend",
"(",
"p",
"[",
"6",
"]",
")",
"args",
".",
"extend",
"(",
"p",
"[",
"8",
"]",
")",
"p",
"[",
"0",
"]",
"=",
... | create_rop_statement : CREATE ROP REF_ID RELID FROM association_end TO association_end | [
"create_rop_statement",
":",
"CREATE",
"ROP",
"REF_ID",
"RELID",
"FROM",
"association_end",
"TO",
"association_end"
] | python | test |
DmitryUlyanov/Multicore-TSNE | tsne-embedding.py | https://github.com/DmitryUlyanov/Multicore-TSNE/blob/62dedde52469f3a0aeb22fdd7bce2538f17f77ef/tsne-embedding.py#L9-L42 | def imscatter(images, positions):
'''
Creates a scatter plot, where each plot is shown by corresponding image
'''
positions = np.array(positions)
bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images])
tops = bottoms + np.array([im.shape[1] for im in images])
lefts =... | [
"def",
"imscatter",
"(",
"images",
",",
"positions",
")",
":",
"positions",
"=",
"np",
".",
"array",
"(",
"positions",
")",
"bottoms",
"=",
"positions",
"[",
":",
",",
"1",
"]",
"-",
"np",
".",
"array",
"(",
"[",
"im",
".",
"shape",
"[",
"1",
"]"... | Creates a scatter plot, where each plot is shown by corresponding image | [
"Creates",
"a",
"scatter",
"plot",
"where",
"each",
"plot",
"is",
"shown",
"by",
"corresponding",
"image"
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/find_dimension.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/find_dimension.py#L72-L121 | def find_clusters(struct, connected_list):
"""
Finds bonded clusters of atoms in the structure with periodic boundary conditions.
If there are atoms that are not bonded to anything, returns [0,1,0].(For faster computation time in FindDimension())
Args:
struct (Structure): Input structure
... | [
"def",
"find_clusters",
"(",
"struct",
",",
"connected_list",
")",
":",
"n_atoms",
"=",
"len",
"(",
"struct",
".",
"species",
")",
"if",
"len",
"(",
"np",
".",
"unique",
"(",
"connected_list",
")",
")",
"!=",
"n_atoms",
":",
"return",
"[",
"0",
",",
... | Finds bonded clusters of atoms in the structure with periodic boundary conditions.
If there are atoms that are not bonded to anything, returns [0,1,0].(For faster computation time in FindDimension())
Args:
struct (Structure): Input structure
connected_list: Must be made from the same structure ... | [
"Finds",
"bonded",
"clusters",
"of",
"atoms",
"in",
"the",
"structure",
"with",
"periodic",
"boundary",
"conditions",
".",
"If",
"there",
"are",
"atoms",
"that",
"are",
"not",
"bonded",
"to",
"anything",
"returns",
"[",
"0",
"1",
"0",
"]",
".",
"(",
"For... | python | train |
pydata/xarray | xarray/core/formatting.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/formatting.py#L122-L136 | def format_timedelta(t, timedelta_format=None):
"""Cast given object to a Timestamp and return a nicely formatted string"""
timedelta_str = str(pd.Timedelta(t))
try:
days_str, time_str = timedelta_str.split(' days ')
except ValueError:
# catch NaT and others that don't split nicely
... | [
"def",
"format_timedelta",
"(",
"t",
",",
"timedelta_format",
"=",
"None",
")",
":",
"timedelta_str",
"=",
"str",
"(",
"pd",
".",
"Timedelta",
"(",
"t",
")",
")",
"try",
":",
"days_str",
",",
"time_str",
"=",
"timedelta_str",
".",
"split",
"(",
"' days '... | Cast given object to a Timestamp and return a nicely formatted string | [
"Cast",
"given",
"object",
"to",
"a",
"Timestamp",
"and",
"return",
"a",
"nicely",
"formatted",
"string"
] | python | train |
profitbricks/profitbricks-sdk-python | profitbricks/client.py | https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1181-L1209 | def update_nic(self, datacenter_id, server_id,
nic_id, **kwargs):
"""
Updates a NIC with the parameters provided.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the serve... | [
"def",
"update_nic",
"(",
"self",
",",
"datacenter_id",
",",
"server_id",
",",
"nic_id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"}",
"for",
"attr",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"data",
"[",
"self",
".",
... | Updates a NIC with the parameters provided.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param nic_id: The unique ID of the NIC.
... | [
"Updates",
"a",
"NIC",
"with",
"the",
"parameters",
"provided",
"."
] | python | valid |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L765-L819 | def GetSyncMoConfig(ConfigDoc):
""" Internal support method for SyncManagedObject. """
moConfigMap = {}
configList = ConfigDoc.getElementsByTagName("mo")
for moConfigNode in configList:
classId = None
noun = None
version = None
actionVersion = None
action = None
ignoreReason = None
status ... | [
"def",
"GetSyncMoConfig",
"(",
"ConfigDoc",
")",
":",
"moConfigMap",
"=",
"{",
"}",
"configList",
"=",
"ConfigDoc",
".",
"getElementsByTagName",
"(",
"\"mo\"",
")",
"for",
"moConfigNode",
"in",
"configList",
":",
"classId",
"=",
"None",
"noun",
"=",
"None",
... | Internal support method for SyncManagedObject. | [
"Internal",
"support",
"method",
"for",
"SyncManagedObject",
"."
] | python | train |
saltstack/salt | salt/utils/iam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/iam.py#L56-L66 | def _convert_key_to_str(key):
'''
Stolen completely from boto.providers
'''
# IMPORTANT: on PY2, the secret key must be str and not unicode to work
# properly with hmac.new (see http://bugs.python.org/issue5285)
#
# pylint: disable=incompatible-py3-code,undefined-variable
return salt.uti... | [
"def",
"_convert_key_to_str",
"(",
"key",
")",
":",
"# IMPORTANT: on PY2, the secret key must be str and not unicode to work",
"# properly with hmac.new (see http://bugs.python.org/issue5285)",
"#",
"# pylint: disable=incompatible-py3-code,undefined-variable",
"return",
"salt",
".",
"utils... | Stolen completely from boto.providers | [
"Stolen",
"completely",
"from",
"boto",
".",
"providers"
] | python | train |
F5Networks/f5-common-python | f5/bigip/resource.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L137-L149 | def _missing_required_parameters(rqset, **kwargs):
"""Helper function to do operation on sets.
Checks for any missing required parameters.
Returns non-empty or empty list. With empty
list being False.
::returns list
"""
key_set = set(list(iterkeys(kwargs)))
required_minus_received = rq... | [
"def",
"_missing_required_parameters",
"(",
"rqset",
",",
"*",
"*",
"kwargs",
")",
":",
"key_set",
"=",
"set",
"(",
"list",
"(",
"iterkeys",
"(",
"kwargs",
")",
")",
")",
"required_minus_received",
"=",
"rqset",
"-",
"key_set",
"if",
"required_minus_received",... | Helper function to do operation on sets.
Checks for any missing required parameters.
Returns non-empty or empty list. With empty
list being False.
::returns list | [
"Helper",
"function",
"to",
"do",
"operation",
"on",
"sets",
"."
] | python | train |
uber/tchannel-python | tchannel/tornado/response.py | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/response.py#L109-L119 | def get_header(self):
"""Get the header value from the response.
:return: a future contains the deserialized value of header
"""
raw_header = yield get_arg(self, 1)
if not self.serializer:
raise tornado.gen.Return(raw_header)
else:
header = self.s... | [
"def",
"get_header",
"(",
"self",
")",
":",
"raw_header",
"=",
"yield",
"get_arg",
"(",
"self",
",",
"1",
")",
"if",
"not",
"self",
".",
"serializer",
":",
"raise",
"tornado",
".",
"gen",
".",
"Return",
"(",
"raw_header",
")",
"else",
":",
"header",
... | Get the header value from the response.
:return: a future contains the deserialized value of header | [
"Get",
"the",
"header",
"value",
"from",
"the",
"response",
"."
] | python | train |
mdsol/rwslib | rwslib/rws_requests/odm_adapter.py | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/rws_requests/odm_adapter.py#L121-L127 | def _querystring(self):
"""Additional keyword arguments"""
kw = {"studyoid": self.studyoid}
if self.location_oid is not None:
kw["locationoid"] = self.location_oid
return kw | [
"def",
"_querystring",
"(",
"self",
")",
":",
"kw",
"=",
"{",
"\"studyoid\"",
":",
"self",
".",
"studyoid",
"}",
"if",
"self",
".",
"location_oid",
"is",
"not",
"None",
":",
"kw",
"[",
"\"locationoid\"",
"]",
"=",
"self",
".",
"location_oid",
"return",
... | Additional keyword arguments | [
"Additional",
"keyword",
"arguments"
] | python | train |
aio-libs/aiohttp-debugtoolbar | aiohttp_debugtoolbar/tbtools/tbtools.py | https://github.com/aio-libs/aiohttp-debugtoolbar/blob/a1c3fb2b487bcaaf23eb71ee4c9c3cfc9cb94322/aiohttp_debugtoolbar/tbtools/tbtools.py#L198-L227 | def render_full(self, request, lodgeit_url=None):
"""Render the Full HTML page with the traceback info."""
static_path = request.app.router[STATIC_ROUTE_NAME].url_for(
filename='')
root_path = request.app.router[ROOT_ROUTE_NAME].url_for()
exc = escape(self.exception)
... | [
"def",
"render_full",
"(",
"self",
",",
"request",
",",
"lodgeit_url",
"=",
"None",
")",
":",
"static_path",
"=",
"request",
".",
"app",
".",
"router",
"[",
"STATIC_ROUTE_NAME",
"]",
".",
"url_for",
"(",
"filename",
"=",
"''",
")",
"root_path",
"=",
"req... | Render the Full HTML page with the traceback info. | [
"Render",
"the",
"Full",
"HTML",
"page",
"with",
"the",
"traceback",
"info",
"."
] | python | train |
Hypex/hyppy | hyppy/hapi.py | https://github.com/Hypex/hyppy/blob/a425619c2a102b0e598fd6cac8aa0f6b766f542d/hyppy/hapi.py#L17-L22 | def requires_api_auth(fn):
"""Decorator for HAPI methods that requires the instance to be authenticated with a HAPI token"""
def wrapper(self, *args, **kwargs):
self.auth_context = HAPI.auth_context_hapi
return fn(self, *args, **kwargs)
return wrapper | [
"def",
"requires_api_auth",
"(",
"fn",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"auth_context",
"=",
"HAPI",
".",
"auth_context_hapi",
"return",
"fn",
"(",
"self",
",",
"*",
"args",
",... | Decorator for HAPI methods that requires the instance to be authenticated with a HAPI token | [
"Decorator",
"for",
"HAPI",
"methods",
"that",
"requires",
"the",
"instance",
"to",
"be",
"authenticated",
"with",
"a",
"HAPI",
"token"
] | python | train |
mozilla/python-zeppelin | zeppelin/converters/markdown.py | https://github.com/mozilla/python-zeppelin/blob/76ce6b7608ef6cf7b807bd5d850a58ea6a59ef07/zeppelin/converters/markdown.py#L129-L135 | def build_output(self, fout):
"""Squash self.out into string.
Join every line in self.out with a new line and write the
result to the output file.
"""
fout.write('\n'.join([s for s in self.out])) | [
"def",
"build_output",
"(",
"self",
",",
"fout",
")",
":",
"fout",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"out",
"]",
")",
")"
] | Squash self.out into string.
Join every line in self.out with a new line and write the
result to the output file. | [
"Squash",
"self",
".",
"out",
"into",
"string",
"."
] | python | train |
guaix-ucm/pyemir | emirdrp/processing/bardetect.py | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/bardetect.py#L186-L211 | def _locate_bar_gen(icut, epos, transform1, transform2):
"""Generic function for the fine position of the CSU"""
epos_pix = coor_to_pix_1d(epos)
# transform ->
epos_pix_s = transform1(epos_pix)
icut2 = transform2(icut)
#
try:
res = position_half_h(icut2, epos_pix_s)
xint_... | [
"def",
"_locate_bar_gen",
"(",
"icut",
",",
"epos",
",",
"transform1",
",",
"transform2",
")",
":",
"epos_pix",
"=",
"coor_to_pix_1d",
"(",
"epos",
")",
"# transform ->",
"epos_pix_s",
"=",
"transform1",
"(",
"epos_pix",
")",
"icut2",
"=",
"transform2",
"(",
... | Generic function for the fine position of the CSU | [
"Generic",
"function",
"for",
"the",
"fine",
"position",
"of",
"the",
"CSU"
] | python | train |
agoragames/haigha | haigha/connections/rabbit_connection.py | https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/connections/rabbit_connection.py#L240-L266 | def consume(self, queue, consumer, consumer_tag='', no_local=False,
no_ack=True, exclusive=False, nowait=True, ticket=None,
cb=None, cancel_cb=None):
'''Start a queue consumer.
Accepts the following optional arg in addition to those of
`BasicClass.consume()`:
... | [
"def",
"consume",
"(",
"self",
",",
"queue",
",",
"consumer",
",",
"consumer_tag",
"=",
"''",
",",
"no_local",
"=",
"False",
",",
"no_ack",
"=",
"True",
",",
"exclusive",
"=",
"False",
",",
"nowait",
"=",
"True",
",",
"ticket",
"=",
"None",
",",
"cb"... | Start a queue consumer.
Accepts the following optional arg in addition to those of
`BasicClass.consume()`:
:param cancel_cb: a callable to be called when the broker cancels the
consumer; e.g., when the consumer's queue is deleted. See
www.rabbitmq.com/consumer-cancel.html.
... | [
"Start",
"a",
"queue",
"consumer",
"."
] | python | train |
deepmind/sonnet | sonnet/python/modules/gated_rnn.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L178-L207 | def get_possible_initializer_keys(cls, use_peepholes=False,
use_projection=False):
"""Returns the keys the dictionary of variable initializers may contain.
The set of all possible initializer keys are:
w_gates: weight for gates
b_gates: bias of gates
w_f_... | [
"def",
"get_possible_initializer_keys",
"(",
"cls",
",",
"use_peepholes",
"=",
"False",
",",
"use_projection",
"=",
"False",
")",
":",
"possible_keys",
"=",
"cls",
".",
"POSSIBLE_INITIALIZER_KEYS",
".",
"copy",
"(",
")",
"if",
"not",
"use_peepholes",
":",
"possi... | Returns the keys the dictionary of variable initializers may contain.
The set of all possible initializer keys are:
w_gates: weight for gates
b_gates: bias of gates
w_f_diag: weight for prev_cell -> forget gate peephole
w_i_diag: weight for prev_cell -> input gate peephole
w_o_diag:... | [
"Returns",
"the",
"keys",
"the",
"dictionary",
"of",
"variable",
"initializers",
"may",
"contain",
"."
] | python | train |
Tathorack/searchcolor | searchcolor/average.py | https://github.com/Tathorack/searchcolor/blob/f50b0a40e9da59fd994440f20e106730b9deb6bf/searchcolor/average.py#L123-L146 | def google_average(search_term, num_results, api_key, cse_id, **kwargs):
"""Does a Google image search to get the average color of the
top x results.
Arguments
search_term: str
tearm to search for
num_results: int
number of results to average
api_key: str
Google API key
... | [
"def",
"google_average",
"(",
"search_term",
",",
"num_results",
",",
"api_key",
",",
"cse_id",
",",
"*",
"*",
"kwargs",
")",
":",
"url_list",
"=",
"[",
"]",
"result",
"=",
"{",
"'name'",
":",
"search_term",
"}",
"GIS",
"=",
"GoogleImageSearch",
"(",
"ap... | Does a Google image search to get the average color of the
top x results.
Arguments
search_term: str
tearm to search for
num_results: int
number of results to average
api_key: str
Google API key
cse_id: str
Google CSE ID
max_threads: int
max number of ... | [
"Does",
"a",
"Google",
"image",
"search",
"to",
"get",
"the",
"average",
"color",
"of",
"the",
"top",
"x",
"results",
".",
"Arguments",
"search_term",
":",
"str",
"tearm",
"to",
"search",
"for",
"num_results",
":",
"int",
"number",
"of",
"results",
"to",
... | python | train |
timothydmorton/isochrones | isochrones/starmodel_old.py | https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L767-L841 | def triangle(self, params=None, query=None, extent=0.999,
**kwargs):
"""
Makes a nifty corner plot.
Uses :func:`triangle.corner`.
:param params: (optional)
Names of columns (from :attr:`StarModel.samples`)
to plot. If ``None``, then it will plo... | [
"def",
"triangle",
"(",
"self",
",",
"params",
"=",
"None",
",",
"query",
"=",
"None",
",",
"extent",
"=",
"0.999",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"triangle",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"'please run \"pip install triangle_plo... | Makes a nifty corner plot.
Uses :func:`triangle.corner`.
:param params: (optional)
Names of columns (from :attr:`StarModel.samples`)
to plot. If ``None``, then it will plot samples
of the parameters used in the MCMC fit-- that is,
mass, age, [Fe/H], and... | [
"Makes",
"a",
"nifty",
"corner",
"plot",
"."
] | python | train |
acutesoftware/AIKIF | aikif/index.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/index.py#L89-L97 | def format_op_row(ipFile, totLines, totWords, uniqueWords):
"""
Format the output row with stats
"""
txt = os.path.basename(ipFile).ljust(36) + ' '
txt += str(totLines).rjust(7) + ' '
txt += str(totWords).rjust(7) + ' '
txt += str(len(uniqueWords)).rjust(7) + ' '
return txt | [
"def",
"format_op_row",
"(",
"ipFile",
",",
"totLines",
",",
"totWords",
",",
"uniqueWords",
")",
":",
"txt",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"ipFile",
")",
".",
"ljust",
"(",
"36",
")",
"+",
"' '",
"txt",
"+=",
"str",
"(",
"totLines",
... | Format the output row with stats | [
"Format",
"the",
"output",
"row",
"with",
"stats"
] | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/gallery/gallery_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/gallery/gallery_client.py#L961-L981 | def share_extension_with_host(self, publisher_name, extension_name, host_type, host_name):
"""ShareExtensionWithHost.
[Preview API]
:param str publisher_name:
:param str extension_name:
:param str host_type:
:param str host_name:
"""
route_values = {}
... | [
"def",
"share_extension_with_host",
"(",
"self",
",",
"publisher_name",
",",
"extension_name",
",",
"host_type",
",",
"host_name",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"publisher_name",
"is",
"not",
"None",
":",
"route_values",
"[",
"'publisherName'",
... | ShareExtensionWithHost.
[Preview API]
:param str publisher_name:
:param str extension_name:
:param str host_type:
:param str host_name: | [
"ShareExtensionWithHost",
".",
"[",
"Preview",
"API",
"]",
":",
"param",
"str",
"publisher_name",
":",
":",
"param",
"str",
"extension_name",
":",
":",
"param",
"str",
"host_type",
":",
":",
"param",
"str",
"host_name",
":"
] | python | train |
idlesign/django-admirarchy | admirarchy/utils.py | https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L131-L139 | def get_results(self, request):
"""Gets query set results.
:param request:
:return:
"""
super(HierarchicalChangeList, self).get_results(request)
self._hierarchy.hook_get_results(self) | [
"def",
"get_results",
"(",
"self",
",",
"request",
")",
":",
"super",
"(",
"HierarchicalChangeList",
",",
"self",
")",
".",
"get_results",
"(",
"request",
")",
"self",
".",
"_hierarchy",
".",
"hook_get_results",
"(",
"self",
")"
] | Gets query set results.
:param request:
:return: | [
"Gets",
"query",
"set",
"results",
"."
] | python | train |
acorg/dark-matter | dark/fastq.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fastq.py#L26-L38 | def iter(self):
"""
Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class.
"""
for _file in self._files:
with asHandle(_file) as fp:
# Use FastqGeneralIterator because it provides access to
... | [
"def",
"iter",
"(",
"self",
")",
":",
"for",
"_file",
"in",
"self",
".",
"_files",
":",
"with",
"asHandle",
"(",
"_file",
")",
"as",
"fp",
":",
"# Use FastqGeneralIterator because it provides access to",
"# the unconverted quality string (i.e., it doesn't try to",
"# fi... | Iterate over the sequences in the files in self.files_, yielding each
as an instance of the desired read class. | [
"Iterate",
"over",
"the",
"sequences",
"in",
"the",
"files",
"in",
"self",
".",
"files_",
"yielding",
"each",
"as",
"an",
"instance",
"of",
"the",
"desired",
"read",
"class",
"."
] | python | train |
hellosign/hellosign-python-sdk | hellosign_sdk/utils/hsaccesstokenauth.py | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/hsaccesstokenauth.py#L53-L69 | def from_response(self, response_data):
''' Builds a new HSAccessTokenAuth straight from response data
Args:
response_data (dict): Response data to use
Returns:
A HSAccessTokenAuth objet
'''
return HSAccessTokenAuth(
response_data['access_t... | [
"def",
"from_response",
"(",
"self",
",",
"response_data",
")",
":",
"return",
"HSAccessTokenAuth",
"(",
"response_data",
"[",
"'access_token'",
"]",
",",
"response_data",
"[",
"'token_type'",
"]",
",",
"response_data",
"[",
"'refresh_token'",
"]",
",",
"response_... | Builds a new HSAccessTokenAuth straight from response data
Args:
response_data (dict): Response data to use
Returns:
A HSAccessTokenAuth objet | [
"Builds",
"a",
"new",
"HSAccessTokenAuth",
"straight",
"from",
"response",
"data"
] | python | train |
jstitch/MambuPy | MambuPy/rest/mambuactivity.py | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuactivity.py#L67-L90 | def convertDict2Attrs(self, *args, **kwargs):
"""The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Activity object for each one, initializing
them one at a time, and changing the attrs attribute (which jus... | [
"def",
"convertDict2Attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"n",
",",
"a",
"in",
"enumerate",
"(",
"self",
".",
"attrs",
")",
":",
"# ok ok, I'm modifying elements of a list while iterating it. BAD PRACTICE!",
"try",
":",... | The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Activity object for each one, initializing
them one at a time, and changing the attrs attribute (which just
holds a list of plain dictionaries) with a Mamb... | [
"The",
"trick",
"for",
"iterable",
"Mambu",
"Objects",
"comes",
"here",
":"
] | python | train |
has2k1/plotnine | plotnine/facets/facet.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet.py#L654-L697 | def eval_facet_vars(data, vars, env):
"""
Evaluate facet variables
Parameters
----------
data : DataFrame
Factet dataframe
vars : list
Facet variables
env : environment
Plot environment
Returns
-------
facet_vals : DataFrame
Facet values that cor... | [
"def",
"eval_facet_vars",
"(",
"data",
",",
"vars",
",",
"env",
")",
":",
"# To allow expressions in facet formula",
"def",
"I",
"(",
"value",
")",
":",
"return",
"value",
"env",
"=",
"env",
".",
"with_outer_namespace",
"(",
"{",
"'I'",
":",
"I",
"}",
")",... | Evaluate facet variables
Parameters
----------
data : DataFrame
Factet dataframe
vars : list
Facet variables
env : environment
Plot environment
Returns
-------
facet_vals : DataFrame
Facet values that correspond to the specified
variables. | [
"Evaluate",
"facet",
"variables"
] | python | train |
scopus-api/scopus | scopus/utils/get_encoded_text.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/utils/get_encoded_text.py#L15-L33 | def get_encoded_text(container, xpath):
"""Return text for element at xpath in the container xml if it is there.
Parameters
----------
container : xml.etree.ElementTree.Element
The element to be searched in.
xpath : str
The path to be looked for.
Returns
-------
result... | [
"def",
"get_encoded_text",
"(",
"container",
",",
"xpath",
")",
":",
"try",
":",
"return",
"\"\"",
".",
"join",
"(",
"container",
".",
"find",
"(",
"xpath",
",",
"ns",
")",
".",
"itertext",
"(",
")",
")",
"except",
"AttributeError",
":",
"return",
"Non... | Return text for element at xpath in the container xml if it is there.
Parameters
----------
container : xml.etree.ElementTree.Element
The element to be searched in.
xpath : str
The path to be looked for.
Returns
-------
result : str | [
"Return",
"text",
"for",
"element",
"at",
"xpath",
"in",
"the",
"container",
"xml",
"if",
"it",
"is",
"there",
"."
] | python | train |
jay-johnson/network-pipeline | network_pipeline/create_layer_2_socket.py | https://github.com/jay-johnson/network-pipeline/blob/4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa/network_pipeline/create_layer_2_socket.py#L9-L22 | def create_layer_2_socket():
"""create_layer_2_socket"""
# create a socket for recording layer 2, 3 and 4 frames
s = None
try:
log.info("Creating l234 socket")
s = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW,
socket.ntohs(0x0003))
... | [
"def",
"create_layer_2_socket",
"(",
")",
":",
"# create a socket for recording layer 2, 3 and 4 frames",
"s",
"=",
"None",
"try",
":",
"log",
".",
"info",
"(",
"\"Creating l234 socket\"",
")",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_PACKET",
",... | create_layer_2_socket | [
"create_layer_2_socket"
] | python | train |
peeringdb/django-peeringdb | django_peeringdb/client_adaptor/backend.py | https://github.com/peeringdb/django-peeringdb/blob/2a32aae8a7e1c11ab6e5a873bb19619c641098c8/django_peeringdb/client_adaptor/backend.py#L157-L171 | def detect_missing_relations(self, obj, exc):
"""
Parse error messages and collect the missing-relationship errors
as a dict of Resource -> {id set}
"""
missing = defaultdict(set)
for name, err in exc.error_dict.items():
# check if it was a relationship that d... | [
"def",
"detect_missing_relations",
"(",
"self",
",",
"obj",
",",
"exc",
")",
":",
"missing",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"name",
",",
"err",
"in",
"exc",
".",
"error_dict",
".",
"items",
"(",
")",
":",
"# check if it was a relationship that d... | Parse error messages and collect the missing-relationship errors
as a dict of Resource -> {id set} | [
"Parse",
"error",
"messages",
"and",
"collect",
"the",
"missing",
"-",
"relationship",
"errors",
"as",
"a",
"dict",
"of",
"Resource",
"-",
">",
"{",
"id",
"set",
"}"
] | python | train |
Alignak-monitoring/alignak | alignak/util.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1145-L1162 | def filter_service_by_servicegroup_name(group):
"""Filter for service
Filter on group
:param group: group to filter
:type group: str
:return: Filter
:rtype: bool
"""
def inner_filter(items):
"""Inner filter for service. Accept if group in service.servicegroups"""
servic... | [
"def",
"filter_service_by_servicegroup_name",
"(",
"group",
")",
":",
"def",
"inner_filter",
"(",
"items",
")",
":",
"\"\"\"Inner filter for service. Accept if group in service.servicegroups\"\"\"",
"service",
"=",
"items",
"[",
"\"service\"",
"]",
"if",
"service",
"is",
... | Filter for service
Filter on group
:param group: group to filter
:type group: str
:return: Filter
:rtype: bool | [
"Filter",
"for",
"service",
"Filter",
"on",
"group"
] | python | train |
xolox/python-qpass | qpass/__init__.py | https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L219-L224 | def entries(self):
"""A list of :class:`PasswordEntry` objects."""
passwords = []
for store in self.stores:
passwords.extend(store.entries)
return natsort(passwords, key=lambda e: e.name) | [
"def",
"entries",
"(",
"self",
")",
":",
"passwords",
"=",
"[",
"]",
"for",
"store",
"in",
"self",
".",
"stores",
":",
"passwords",
".",
"extend",
"(",
"store",
".",
"entries",
")",
"return",
"natsort",
"(",
"passwords",
",",
"key",
"=",
"lambda",
"e... | A list of :class:`PasswordEntry` objects. | [
"A",
"list",
"of",
":",
"class",
":",
"PasswordEntry",
"objects",
"."
] | python | train |
nitely/kua | kua/routes.py | https://github.com/nitely/kua/blob/6ffc9d0426e87a34cf8c3f8e7aedac6d35e59cb6/kua/routes.py#L213-L231 | def _deconstruct_url(self, url: str) -> List[str]:
"""
Split a regular URL into parts
:param url: A normalized URL
:return: Parts of the URL
:raises kua.routes.RouteError: \
If the depth of the URL exceeds\
the max depth of the deepest\
registered pattern... | [
"def",
"_deconstruct_url",
"(",
"self",
",",
"url",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"parts",
"=",
"url",
".",
"split",
"(",
"'/'",
",",
"self",
".",
"_max_depth",
"+",
"1",
")",
"if",
"depth_of",
"(",
"parts",
")",
">",
"self... | Split a regular URL into parts
:param url: A normalized URL
:return: Parts of the URL
:raises kua.routes.RouteError: \
If the depth of the URL exceeds\
the max depth of the deepest\
registered pattern
:private: | [
"Split",
"a",
"regular",
"URL",
"into",
"parts"
] | python | train |
milesrichardson/ParsePy | parse_rest/datatypes.py | https://github.com/milesrichardson/ParsePy/blob/7c52d8a5dc63bb7c3b0b8c0c09d032b4bc7299ea/parse_rest/datatypes.py#L598-L610 | def increment(self, key, amount=1):
"""
Increment one value in the object. Note that this happens immediately:
it does not wait for save() to be called
"""
payload = {
key: {
'__op': 'Increment',
'amount': amount
}
... | [
"def",
"increment",
"(",
"self",
",",
"key",
",",
"amount",
"=",
"1",
")",
":",
"payload",
"=",
"{",
"key",
":",
"{",
"'__op'",
":",
"'Increment'",
",",
"'amount'",
":",
"amount",
"}",
"}",
"self",
".",
"__class__",
".",
"PUT",
"(",
"self",
".",
... | Increment one value in the object. Note that this happens immediately:
it does not wait for save() to be called | [
"Increment",
"one",
"value",
"in",
"the",
"object",
".",
"Note",
"that",
"this",
"happens",
"immediately",
":",
"it",
"does",
"not",
"wait",
"for",
"save",
"()",
"to",
"be",
"called"
] | python | train |
tonybaloney/wily | wily/__main__.py | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/__main__.py#L299-L313 | def clean(ctx, yes):
"""Clear the .wily/ folder."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
if not yes:
p = input("Are you sure you want to delete wily cache? [y/N]")
if p.lower() != "y":
exit(0)
from wily.cache import clean
... | [
"def",
"clean",
"(",
"ctx",
",",
"yes",
")",
":",
"config",
"=",
"ctx",
".",
"obj",
"[",
"\"CONFIG\"",
"]",
"if",
"not",
"exists",
"(",
"config",
")",
":",
"handle_no_cache",
"(",
"ctx",
")",
"if",
"not",
"yes",
":",
"p",
"=",
"input",
"(",
"\"Ar... | Clear the .wily/ folder. | [
"Clear",
"the",
".",
"wily",
"/",
"folder",
"."
] | python | train |
davisd50/sparc.db | sparc/db/splunk/search.py | https://github.com/davisd50/sparc.db/blob/12dfcb51f7bdc4fbe9c8ec3b5af65059c1f66392/sparc/db/splunk/search.py#L25-L37 | def saved_searches_factory_helper(splunk_connection_info):
"""Return a valid splunklib.client.SavedSearches object
kwargs:
- see splunklib.client.connect()
"""
if not ISplunkConnectionInfo.providedBy(splunk_connection_info):
DoesNotImplement('argument did not provide expected interf... | [
"def",
"saved_searches_factory_helper",
"(",
"splunk_connection_info",
")",
":",
"if",
"not",
"ISplunkConnectionInfo",
".",
"providedBy",
"(",
"splunk_connection_info",
")",
":",
"DoesNotImplement",
"(",
"'argument did not provide expected interface'",
")",
"service",
"=",
... | Return a valid splunklib.client.SavedSearches object
kwargs:
- see splunklib.client.connect() | [
"Return",
"a",
"valid",
"splunklib",
".",
"client",
".",
"SavedSearches",
"object",
"kwargs",
":",
"-",
"see",
"splunklib",
".",
"client",
".",
"connect",
"()"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.