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 |
|---|---|---|---|---|---|---|---|---|
CI-WATER/gsshapy | gsshapy/orm/rep.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/rep.py#L76-L87 | def _write(self, session, openFile, replaceParamFile):
"""
Replace Param File Write to File Method
"""
# Retrieve TargetParameter objects
targets = self.targetParameters
# Write lines
openFile.write('%s\n' % self.numParameters)
for target in targets:
... | [
"def",
"_write",
"(",
"self",
",",
"session",
",",
"openFile",
",",
"replaceParamFile",
")",
":",
"# Retrieve TargetParameter objects",
"targets",
"=",
"self",
".",
"targetParameters",
"# Write lines",
"openFile",
".",
"write",
"(",
"'%s\\n'",
"%",
"self",
".",
... | Replace Param File Write to File Method | [
"Replace",
"Param",
"File",
"Write",
"to",
"File",
"Method"
] | python | train |
PGower/PyCanvas | pycanvas/apis/users.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L876-L903 | def merge_user_into_another_user_destination_user_id(self, id, destination_user_id):
"""
Merge user into another user.
Merge a user into another user.
To merge users, the caller must have permissions to manage both users. This
should be considered irreversible. This will d... | [
"def",
"merge_user_into_another_user_destination_user_id",
"(",
"self",
",",
"id",
",",
"destination_user_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"id\"",
"... | Merge user into another user.
Merge a user into another user.
To merge users, the caller must have permissions to manage both users. This
should be considered irreversible. This will delete the user and move all
the data into the destination user.
When finding us... | [
"Merge",
"user",
"into",
"another",
"user",
".",
"Merge",
"a",
"user",
"into",
"another",
"user",
".",
"To",
"merge",
"users",
"the",
"caller",
"must",
"have",
"permissions",
"to",
"manage",
"both",
"users",
".",
"This",
"should",
"be",
"considered",
"irre... | python | train |
GeorgeArgyros/sfalearn | sfalearn/observationtableinit.py | https://github.com/GeorgeArgyros/sfalearn/blob/68a93f507e2fb7d89ca04bd8a8f0da2d6c680443/sfalearn/observationtableinit.py#L200-L287 | def _init_using_k_equivalence(self, given_graph, sfa=False):
"""
Args:
given_graph (DFA): The DFA states
sfa (boolean): A boolean for chosing SFA
Return:
list, list, list: sm_vector, smi_vector, em_vector initialization vectors
"""
graph = DFA(... | [
"def",
"_init_using_k_equivalence",
"(",
"self",
",",
"given_graph",
",",
"sfa",
"=",
"False",
")",
":",
"graph",
"=",
"DFA",
"(",
"self",
".",
"alphabet",
")",
"graph",
".",
"init_from_acceptor",
"(",
"given_graph",
")",
"graph",
".",
"fixminimized",
"(",
... | Args:
given_graph (DFA): The DFA states
sfa (boolean): A boolean for chosing SFA
Return:
list, list, list: sm_vector, smi_vector, em_vector initialization vectors | [
"Args",
":",
"given_graph",
"(",
"DFA",
")",
":",
"The",
"DFA",
"states",
"sfa",
"(",
"boolean",
")",
":",
"A",
"boolean",
"for",
"chosing",
"SFA",
"Return",
":",
"list",
"list",
"list",
":",
"sm_vector",
"smi_vector",
"em_vector",
"initialization",
"vecto... | python | train |
aodag/WebDispatch | webdispatch/uritemplate.py | https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/uritemplate.py#L120-L134 | def match(self, path_info: str) -> MatchResult:
""" parse path_info and detect urlvars of url pattern """
matched = self.regex.match(path_info)
if matched is None:
return None
matchlength = len(matched.group(0))
matchdict = matched.groupdict()
try:
... | [
"def",
"match",
"(",
"self",
",",
"path_info",
":",
"str",
")",
"->",
"MatchResult",
":",
"matched",
"=",
"self",
".",
"regex",
".",
"match",
"(",
"path_info",
")",
"if",
"matched",
"is",
"None",
":",
"return",
"None",
"matchlength",
"=",
"len",
"(",
... | parse path_info and detect urlvars of url pattern | [
"parse",
"path_info",
"and",
"detect",
"urlvars",
"of",
"url",
"pattern"
] | python | train |
winkidney/cmdtree | src/cmdtree/registry.py | https://github.com/winkidney/cmdtree/blob/8558be856f4c3044cf13d2d07a86b69877bb6491/src/cmdtree/registry.py#L19-L26 | def tree(self):
"""
:rtype: cmdtree.tree.CmdTree
"""
from cmdtree.tree import CmdTree
if self._tree is None:
self._tree = CmdTree()
return self._tree | [
"def",
"tree",
"(",
"self",
")",
":",
"from",
"cmdtree",
".",
"tree",
"import",
"CmdTree",
"if",
"self",
".",
"_tree",
"is",
"None",
":",
"self",
".",
"_tree",
"=",
"CmdTree",
"(",
")",
"return",
"self",
".",
"_tree"
] | :rtype: cmdtree.tree.CmdTree | [
":",
"rtype",
":",
"cmdtree",
".",
"tree",
".",
"CmdTree"
] | python | train |
Cognexa/cxflow | cxflow/hooks/save.py | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L175-L185 | def after_epoch(self, epoch_data: EpochData, **_) -> None:
"""
Save the model if the new value of the monitored variable is better than the best value so far.
:param epoch_data: epoch data to be processed
"""
new_value = self._get_value(epoch_data)
if self._is_value_bet... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
",",
"*",
"*",
"_",
")",
"->",
"None",
":",
"new_value",
"=",
"self",
".",
"_get_value",
"(",
"epoch_data",
")",
"if",
"self",
".",
"_is_value_better",
"(",
"new_value",
")",
":",
... | Save the model if the new value of the monitored variable is better than the best value so far.
:param epoch_data: epoch data to be processed | [
"Save",
"the",
"model",
"if",
"the",
"new",
"value",
"of",
"the",
"monitored",
"variable",
"is",
"better",
"than",
"the",
"best",
"value",
"so",
"far",
"."
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/classifier/svm_classifier.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/svm_classifier.py#L27-L226 | def create(dataset, target, features=None,
penalty=1.0, solver='auto',
feature_rescaling=True,
convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'],
lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'],
max_iterations = _DEFAULT_SOLVER_OPTIONS['max_iterations'],
... | [
"def",
"create",
"(",
"dataset",
",",
"target",
",",
"features",
"=",
"None",
",",
"penalty",
"=",
"1.0",
",",
"solver",
"=",
"'auto'",
",",
"feature_rescaling",
"=",
"True",
",",
"convergence_threshold",
"=",
"_DEFAULT_SOLVER_OPTIONS",
"[",
"'convergence_thresh... | Create a :class:`~turicreate.svm_classifier.SVMClassifier` to predict the class of a binary
target variable based on a model of which side of a hyperplane the example
falls on. In addition to standard numeric and categorical types, features
can also be extracted automatically from list- or dictionary-type S... | [
"Create",
"a",
":",
"class",
":",
"~turicreate",
".",
"svm_classifier",
".",
"SVMClassifier",
"to",
"predict",
"the",
"class",
"of",
"a",
"binary",
"target",
"variable",
"based",
"on",
"a",
"model",
"of",
"which",
"side",
"of",
"a",
"hyperplane",
"the",
"e... | python | train |
KelSolaar/Umbra | umbra/components/factory/components_manager_ui/components_manager_ui.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/components_manager_ui/components_manager_ui.py#L822-L858 | def activate_components_ui(self):
"""
Activates user selected Components.
:return: Method success.
:rtype: bool
:note: May require user interaction.
"""
selected_components = self.get_selected_components()
self.__engine.start_processing("Activating Com... | [
"def",
"activate_components_ui",
"(",
"self",
")",
":",
"selected_components",
"=",
"self",
".",
"get_selected_components",
"(",
")",
"self",
".",
"__engine",
".",
"start_processing",
"(",
"\"Activating Components ...\"",
",",
"len",
"(",
"selected_components",
")",
... | Activates user selected Components.
:return: Method success.
:rtype: bool
:note: May require user interaction. | [
"Activates",
"user",
"selected",
"Components",
"."
] | python | train |
python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L208-L234 | def _get_active_stats(self, app_stats):
"""
Process:
* active_scheduled_host_check_stats
* active_scheduled_service_check_stats
* active_ondemand_host_check_stats
* active_ondemand_service_check_stats
"""
stats = {}
app_keys = [
... | [
"def",
"_get_active_stats",
"(",
"self",
",",
"app_stats",
")",
":",
"stats",
"=",
"{",
"}",
"app_keys",
"=",
"[",
"\"active_scheduled_host_check_stats\"",
",",
"\"active_scheduled_service_check_stats\"",
",",
"\"active_ondemand_host_check_stats\"",
",",
"\"active_ondemand_... | Process:
* active_scheduled_host_check_stats
* active_scheduled_service_check_stats
* active_ondemand_host_check_stats
* active_ondemand_service_check_stats | [
"Process",
":",
"*",
"active_scheduled_host_check_stats",
"*",
"active_scheduled_service_check_stats",
"*",
"active_ondemand_host_check_stats",
"*",
"active_ondemand_service_check_stats"
] | python | train |
Yelp/threat_intel | threat_intel/util/http.py | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L220-L237 | def multi_post(self, urls, query_params=None, data=None, to_json=True, send_as_file=False):
"""Issue multiple POST requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
data - None, a ... | [
"def",
"multi_post",
"(",
"self",
",",
"urls",
",",
"query_params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"to_json",
"=",
"True",
",",
"send_as_file",
"=",
"False",
")",
":",
"return",
"self",
".",
"_multi_request",
"(",
"MultiRequest",
".",
"_VERB... | Issue multiple POST requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
data - None, a dict or string, or a list of dicts and strings representing the data body.
to_json - A bool... | [
"Issue",
"multiple",
"POST",
"requests",
"."
] | python | train |
sdispater/orator | orator/orm/relations/belongs_to_many.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L693-L703 | def _get_attach_id(self, key, value, attributes):
"""
Get the attach record ID and extra attributes.
"""
if isinstance(value, dict):
key = list(value.keys())[0]
attributes.update(value[key])
return [key, attributes]
return value, attributes | [
"def",
"_get_attach_id",
"(",
"self",
",",
"key",
",",
"value",
",",
"attributes",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"key",
"=",
"list",
"(",
"value",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"attributes",
".",
... | Get the attach record ID and extra attributes. | [
"Get",
"the",
"attach",
"record",
"ID",
"and",
"extra",
"attributes",
"."
] | python | train |
inveniosoftware/invenio-access | invenio_access/cli.py | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/cli.py#L108-L114 | def allow_user(user):
"""Allow a user identified by an email address."""
def processor(action, argument):
db.session.add(
ActionUsers.allow(action, argument=argument, user_id=user.id)
)
return processor | [
"def",
"allow_user",
"(",
"user",
")",
":",
"def",
"processor",
"(",
"action",
",",
"argument",
")",
":",
"db",
".",
"session",
".",
"add",
"(",
"ActionUsers",
".",
"allow",
"(",
"action",
",",
"argument",
"=",
"argument",
",",
"user_id",
"=",
"user",
... | Allow a user identified by an email address. | [
"Allow",
"a",
"user",
"identified",
"by",
"an",
"email",
"address",
"."
] | python | train |
Azure/azure-sdk-for-python | azure-servicebus/azure/servicebus/control_client/_serialization.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicebus/azure/servicebus/control_client/_serialization.py#L306-L346 | def _convert_etree_element_to_subscription(entry_element):
'''Converts entry element to subscription
The xml format for subscription:
<entry xmlns='http://www.w3.org/2005/Atom'>
<content type='application/xml'>
<SubscriptionDescription
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
... | [
"def",
"_convert_etree_element_to_subscription",
"(",
"entry_element",
")",
":",
"subscription",
"=",
"Subscription",
"(",
")",
"subscription_element",
"=",
"entry_element",
".",
"find",
"(",
"'./atom:content/sb:SubscriptionDescription'",
",",
"_etree_sb_feed_namespaces",
")"... | Converts entry element to subscription
The xml format for subscription:
<entry xmlns='http://www.w3.org/2005/Atom'>
<content type='application/xml'>
<SubscriptionDescription
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebu... | [
"Converts",
"entry",
"element",
"to",
"subscription"
] | python | test |
mikedh/trimesh | trimesh/integrate.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/integrate.py#L15-L90 | def symbolic_barycentric(function):
"""
Symbolically integrate a function(x,y,z) across a triangle or mesh.
Parameters
----------
function: string or sympy expression
x, y, z will be replaced with a barycentric representation
and the the function is integrated across the... | [
"def",
"symbolic_barycentric",
"(",
"function",
")",
":",
"class",
"evaluator",
":",
"def",
"__init__",
"(",
"self",
",",
"expr",
",",
"expr_args",
")",
":",
"self",
".",
"lambdified",
"=",
"sp",
".",
"lambdify",
"(",
"args",
"=",
"expr_args",
",",
"expr... | Symbolically integrate a function(x,y,z) across a triangle or mesh.
Parameters
----------
function: string or sympy expression
x, y, z will be replaced with a barycentric representation
and the the function is integrated across the triangle.
Returns
----------
evalu... | [
"Symbolically",
"integrate",
"a",
"function",
"(",
"x",
"y",
"z",
")",
"across",
"a",
"triangle",
"or",
"mesh",
"."
] | python | train |
saltstack/salt | salt/modules/napalm_mod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L253-L281 | def call(method, *args, **kwargs):
'''
Execute arbitrary methods from the NAPALM library.
To see the expected output, please consult the NAPALM documentation.
.. note::
This feature is not recommended to be used in production.
It should be used for testing only!
CLI Example:
... | [
"def",
"call",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"clean_kwargs",
"=",
"{",
"}",
"for",
"karg",
",",
"warg",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"# remove the __pub args",
"if",
"not",
"karg",
".",... | Execute arbitrary methods from the NAPALM library.
To see the expected output, please consult the NAPALM documentation.
.. note::
This feature is not recommended to be used in production.
It should be used for testing only!
CLI Example:
.. code-block:: bash
salt '*' napalm.c... | [
"Execute",
"arbitrary",
"methods",
"from",
"the",
"NAPALM",
"library",
".",
"To",
"see",
"the",
"expected",
"output",
"please",
"consult",
"the",
"NAPALM",
"documentation",
"."
] | python | train |
alefnula/tea | tea/utils/compress.py | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/compress.py#L158-L165 | def seven_zip(archive, items, self_extracting=False):
"""Create a 7z archive."""
if not isinstance(items, (list, tuple)):
items = [items]
if self_extracting:
return er(_get_sz(), "a", "-ssw", "-sfx", archive, *items)
else:
return er(_get_sz(), "a", "-ssw", archive, *items) | [
"def",
"seven_zip",
"(",
"archive",
",",
"items",
",",
"self_extracting",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"items",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"items",
"=",
"[",
"items",
"]",
"if",
"self_extracting",
":",
"... | Create a 7z archive. | [
"Create",
"a",
"7z",
"archive",
"."
] | python | train |
elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L703-L721 | def scan(self):
"""
Turn the search into a scan search and return a generator that will
iterate over all the documents matching the query.
Use ``params`` method to specify any additional arguments you with to
pass to the underlying ``scan`` helper from ``elasticsearch-py`` -
... | [
"def",
"scan",
"(",
"self",
")",
":",
"es",
"=",
"connections",
".",
"get_connection",
"(",
"self",
".",
"_using",
")",
"for",
"hit",
"in",
"scan",
"(",
"es",
",",
"query",
"=",
"self",
".",
"to_dict",
"(",
")",
",",
"index",
"=",
"self",
".",
"_... | Turn the search into a scan search and return a generator that will
iterate over all the documents matching the query.
Use ``params`` method to specify any additional arguments you with to
pass to the underlying ``scan`` helper from ``elasticsearch-py`` -
https://elasticsearch-py.readth... | [
"Turn",
"the",
"search",
"into",
"a",
"scan",
"search",
"and",
"return",
"a",
"generator",
"that",
"will",
"iterate",
"over",
"all",
"the",
"documents",
"matching",
"the",
"query",
"."
] | python | train |
mishbahr/django-connected | connected_accounts/views.py | https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L136-L140 | def handle_login_failure(self, provider, reason):
"""Message user and redirect on error."""
logger.error('Authenication Failure: {0}'.format(reason))
messages.error(self.request, 'Authenication Failed. Please try again')
return redirect(self.get_error_redirect(provider, reason)) | [
"def",
"handle_login_failure",
"(",
"self",
",",
"provider",
",",
"reason",
")",
":",
"logger",
".",
"error",
"(",
"'Authenication Failure: {0}'",
".",
"format",
"(",
"reason",
")",
")",
"messages",
".",
"error",
"(",
"self",
".",
"request",
",",
"'Authenica... | Message user and redirect on error. | [
"Message",
"user",
"and",
"redirect",
"on",
"error",
"."
] | python | train |
mikusjelly/apkutils | apkutils/apkfile.py | https://github.com/mikusjelly/apkutils/blob/2db1ed0cdb610dfc55bfd77266e9a91e4764bba4/apkutils/apkfile.py#L182-L196 | def is_zipfile(filename):
"""Quickly see if a file is a ZIP file by checking the magic number.
The filename argument may be a file or file-like object too.
"""
result = False
try:
if hasattr(filename, "read"):
result = _check_zipfile(fp=filename)
else:
with o... | [
"def",
"is_zipfile",
"(",
"filename",
")",
":",
"result",
"=",
"False",
"try",
":",
"if",
"hasattr",
"(",
"filename",
",",
"\"read\"",
")",
":",
"result",
"=",
"_check_zipfile",
"(",
"fp",
"=",
"filename",
")",
"else",
":",
"with",
"open",
"(",
"filena... | Quickly see if a file is a ZIP file by checking the magic number.
The filename argument may be a file or file-like object too. | [
"Quickly",
"see",
"if",
"a",
"file",
"is",
"a",
"ZIP",
"file",
"by",
"checking",
"the",
"magic",
"number",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/distlib/_backport/tarfile.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L810-L832 | def read(self, size=None):
"""Read at most size bytes from the file. If size is not
present or None, read all data until EOF is reached.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
buf = b""
if self.buffer:
if size is N... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed file\"",
")",
"buf",
"=",
"b\"\"",
"if",
"self",
".",
"buffer",
":",
"if",
"size",
"is",
"None",
":... | Read at most size bytes from the file. If size is not
present or None, read all data until EOF is reached. | [
"Read",
"at",
"most",
"size",
"bytes",
"from",
"the",
"file",
".",
"If",
"size",
"is",
"not",
"present",
"or",
"None",
"read",
"all",
"data",
"until",
"EOF",
"is",
"reached",
"."
] | python | train |
PythonSanSebastian/docstamp | docstamp/inkscape.py | https://github.com/PythonSanSebastian/docstamp/blob/b43808f2e15351b0b2f0b7eade9c7ef319c9e646/docstamp/inkscape.py#L98-L102 | def svg2png(svg_file_path, png_file_path, dpi=150, inkscape_binpath=None):
""" Transform SVG file to PNG file
"""
return inkscape_export(svg_file_path, png_file_path, export_flag="-e",
dpi=dpi, inkscape_binpath=inkscape_binpath) | [
"def",
"svg2png",
"(",
"svg_file_path",
",",
"png_file_path",
",",
"dpi",
"=",
"150",
",",
"inkscape_binpath",
"=",
"None",
")",
":",
"return",
"inkscape_export",
"(",
"svg_file_path",
",",
"png_file_path",
",",
"export_flag",
"=",
"\"-e\"",
",",
"dpi",
"=",
... | Transform SVG file to PNG file | [
"Transform",
"SVG",
"file",
"to",
"PNG",
"file"
] | python | test |
xym-tool/xym | xym/xym.py | https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L360-L373 | def strip_empty_lines_backward(self, model, max_lines_to_strip):
"""
Strips empty lines preceding the line that is currently being parsed. This
fucntion is called when the parser encounters a Footer.
:param model: lines that were added to the model up to this point
:param line_nu... | [
"def",
"strip_empty_lines_backward",
"(",
"self",
",",
"model",
",",
"max_lines_to_strip",
")",
":",
"for",
"l",
"in",
"range",
"(",
"0",
",",
"max_lines_to_strip",
")",
":",
"if",
"model",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"strip",
"(",
"' \\r\\... | Strips empty lines preceding the line that is currently being parsed. This
fucntion is called when the parser encounters a Footer.
:param model: lines that were added to the model up to this point
:param line_num: the number of teh line being parsed
:param max_lines_to_strip: max number ... | [
"Strips",
"empty",
"lines",
"preceding",
"the",
"line",
"that",
"is",
"currently",
"being",
"parsed",
".",
"This",
"fucntion",
"is",
"called",
"when",
"the",
"parser",
"encounters",
"a",
"Footer",
".",
":",
"param",
"model",
":",
"lines",
"that",
"were",
"... | python | train |
h2oai/h2o-3 | h2o-py/h2o/model/model_base.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/model_base.py#L840-L853 | def save_model_details(self, path="", force=False):
"""
Save Model Details of an H2O Model in JSON Format to disk.
:param model: The model object to save.
:param path: a path to save the model details at (hdfs, s3, local)
:param force: if True overwrite destination directory in ... | [
"def",
"save_model_details",
"(",
"self",
",",
"path",
"=",
"\"\"",
",",
"force",
"=",
"False",
")",
":",
"assert_is_type",
"(",
"path",
",",
"str",
")",
"assert_is_type",
"(",
"force",
",",
"bool",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"... | Save Model Details of an H2O Model in JSON Format to disk.
:param model: The model object to save.
:param path: a path to save the model details at (hdfs, s3, local)
:param force: if True overwrite destination directory in case it exists, or throw exception if set to False.
:returns st... | [
"Save",
"Model",
"Details",
"of",
"an",
"H2O",
"Model",
"in",
"JSON",
"Format",
"to",
"disk",
"."
] | python | test |
mixcloud/django-experiments | experiments/utils.py | https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/utils.py#L160-L177 | def visit(self):
"""Record that the user has visited the site for the purposes of retention tracking"""
for enrollment in self._get_all_enrollments():
if enrollment.experiment.is_displaying_alternatives():
# We have two different goals, VISIT_NOT_PRESENT_COUNT_GOAL and VISIT_... | [
"def",
"visit",
"(",
"self",
")",
":",
"for",
"enrollment",
"in",
"self",
".",
"_get_all_enrollments",
"(",
")",
":",
"if",
"enrollment",
".",
"experiment",
".",
"is_displaying_alternatives",
"(",
")",
":",
"# We have two different goals, VISIT_NOT_PRESENT_COUNT_GOAL ... | Record that the user has visited the site for the purposes of retention tracking | [
"Record",
"that",
"the",
"user",
"has",
"visited",
"the",
"site",
"for",
"the",
"purposes",
"of",
"retention",
"tracking"
] | python | train |
pyBookshelf/bookshelf | bookshelf/api_v1.py | https://github.com/pyBookshelf/bookshelf/blob/a6770678e735de95b194f6e6989223970db5f654/bookshelf/api_v1.py#L618-L670 | def _create_server_rackspace(region,
access_key_id,
secret_access_key,
disk_name,
disk_size,
ami,
key_pair,
instance_... | [
"def",
"_create_server_rackspace",
"(",
"region",
",",
"access_key_id",
",",
"secret_access_key",
",",
"disk_name",
",",
"disk_size",
",",
"ami",
",",
"key_pair",
",",
"instance_type",
",",
"username",
",",
"instance_name",
",",
"tags",
"=",
"{",
"}",
",",
"se... | Creates Rackspace Instance and saves it state in a local json file | [
"Creates",
"Rackspace",
"Instance",
"and",
"saves",
"it",
"state",
"in",
"a",
"local",
"json",
"file"
] | python | train |
bjmorgan/vasppy | vasppy/cell.py | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/cell.py#L137-L148 | def angles( self ):
"""
The cell angles (in degrees).
Args:
None
Returns:
(list(alpha,beta,gamma)): The cell angles.
"""
( a, b, c ) = [ row for row in self.matrix ]
return [ angle( b, c ), angle( a, c ), angle( a, b ) ] | [
"def",
"angles",
"(",
"self",
")",
":",
"(",
"a",
",",
"b",
",",
"c",
")",
"=",
"[",
"row",
"for",
"row",
"in",
"self",
".",
"matrix",
"]",
"return",
"[",
"angle",
"(",
"b",
",",
"c",
")",
",",
"angle",
"(",
"a",
",",
"c",
")",
",",
"angl... | The cell angles (in degrees).
Args:
None
Returns:
(list(alpha,beta,gamma)): The cell angles. | [
"The",
"cell",
"angles",
"(",
"in",
"degrees",
")",
"."
] | python | train |
harvard-nrg/yaxil | yaxil/bids/__init__.py | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L231-L251 | def convert(input, output):
'''
Run dcm2niix on input file
'''
dirname = os.path.dirname(output)
if not os.path.exists(dirname):
os.makedirs(dirname)
basename = os.path.basename(output)
basename = re.sub('.nii(.gz)?', '', basename)
dcm2niix = commons.which('dcm2niix')
cmd = [... | [
"def",
"convert",
"(",
"input",
",",
"output",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"... | Run dcm2niix on input file | [
"Run",
"dcm2niix",
"on",
"input",
"file"
] | python | train |
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/parser.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/parser.py#L168-L174 | def parse_set(self):
"""Parse an assign statement."""
lineno = next(self.stream).lineno
target = self.parse_assign_target()
self.stream.expect('assign')
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno) | [
"def",
"parse_set",
"(",
"self",
")",
":",
"lineno",
"=",
"next",
"(",
"self",
".",
"stream",
")",
".",
"lineno",
"target",
"=",
"self",
".",
"parse_assign_target",
"(",
")",
"self",
".",
"stream",
".",
"expect",
"(",
"'assign'",
")",
"expr",
"=",
"s... | Parse an assign statement. | [
"Parse",
"an",
"assign",
"statement",
"."
] | python | train |
LuminosoInsight/luminoso-api-client-python | luminoso_api/v4_upload.py | https://github.com/LuminosoInsight/luminoso-api-client-python/blob/3bedf2a454aee39214c11fbf556ead3eecc27881/luminoso_api/v4_upload.py#L19-L60 | def upload_stream(stream, server, account, projname, language=None,
username=None, password=None,
append=False, stage=False):
"""
Given a file-like object containing a JSON stream, upload it to
Luminoso with the given account name and project name.
"""
client = Lu... | [
"def",
"upload_stream",
"(",
"stream",
",",
"server",
",",
"account",
",",
"projname",
",",
"language",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"append",
"=",
"False",
",",
"stage",
"=",
"False",
")",
":",
"client"... | Given a file-like object containing a JSON stream, upload it to
Luminoso with the given account name and project name. | [
"Given",
"a",
"file",
"-",
"like",
"object",
"containing",
"a",
"JSON",
"stream",
"upload",
"it",
"to",
"Luminoso",
"with",
"the",
"given",
"account",
"name",
"and",
"project",
"name",
"."
] | python | test |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L988-L1012 | def update_source_model(sm_node, fname):
"""
:param sm_node: a sourceModel Node object containing sourceGroups
"""
i = 0
for group in sm_node:
if 'srcs_weights' in group.attrib:
raise InvalidFile('srcs_weights must be removed in %s' % fname)
if not group.tag.endswith('sou... | [
"def",
"update_source_model",
"(",
"sm_node",
",",
"fname",
")",
":",
"i",
"=",
"0",
"for",
"group",
"in",
"sm_node",
":",
"if",
"'srcs_weights'",
"in",
"group",
".",
"attrib",
":",
"raise",
"InvalidFile",
"(",
"'srcs_weights must be removed in %s'",
"%",
"fna... | :param sm_node: a sourceModel Node object containing sourceGroups | [
":",
"param",
"sm_node",
":",
"a",
"sourceModel",
"Node",
"object",
"containing",
"sourceGroups"
] | python | train |
lsst-sqre/documenteer | documenteer/stackdocs/build.py | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L228-L246 | def list_packages_in_eups_table(table_text):
"""List the names of packages that are required by an EUPS table file.
Parameters
----------
table_text : `str`
The text content of an EUPS table file.
Returns
-------
names : `list` [`str`]
List of package names that are require... | [
"def",
"list_packages_in_eups_table",
"(",
"table_text",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# This pattern matches required product names in EUPS table files.",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'setupRequired\\((?P<name>... | List the names of packages that are required by an EUPS table file.
Parameters
----------
table_text : `str`
The text content of an EUPS table file.
Returns
-------
names : `list` [`str`]
List of package names that are required byy the EUPS table file. | [
"List",
"the",
"names",
"of",
"packages",
"that",
"are",
"required",
"by",
"an",
"EUPS",
"table",
"file",
"."
] | python | train |
gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L151-L159 | def add_opt(self, opt, value=None):
""" Add a option
"""
if value is not None:
if not isinstance(value, File):
value = str(value)
self._options += [opt, value]
else:
self._options += [opt] | [
"def",
"add_opt",
"(",
"self",
",",
"opt",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"File",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"self",
".",
"_option... | Add a option | [
"Add",
"a",
"option"
] | python | train |
binux/pyspider | pyspider/libs/response.py | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L150-L163 | def etree(self):
"""Returns a lxml object of the response's content that can be selected by xpath"""
if not hasattr(self, '_elements'):
try:
parser = lxml.html.HTMLParser(encoding=self.encoding)
self._elements = lxml.html.fromstring(self.content, parser=parser... | [
"def",
"etree",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_elements'",
")",
":",
"try",
":",
"parser",
"=",
"lxml",
".",
"html",
".",
"HTMLParser",
"(",
"encoding",
"=",
"self",
".",
"encoding",
")",
"self",
".",
"_elements",... | Returns a lxml object of the response's content that can be selected by xpath | [
"Returns",
"a",
"lxml",
"object",
"of",
"the",
"response",
"s",
"content",
"that",
"can",
"be",
"selected",
"by",
"xpath"
] | python | train |
mapmyfitness/jtime | jtime/jira_ext.py | https://github.com/mapmyfitness/jtime/blob/402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd/jtime/jira_ext.py#L79-L88 | def get_datetime_issue_in_progress(self, issue):
"""
If the issue is in progress, gets that most recent time that the issue became 'In Progress'
"""
histories = issue.changelog.histories
for history in reversed(histories):
history_items = history.items
for... | [
"def",
"get_datetime_issue_in_progress",
"(",
"self",
",",
"issue",
")",
":",
"histories",
"=",
"issue",
".",
"changelog",
".",
"histories",
"for",
"history",
"in",
"reversed",
"(",
"histories",
")",
":",
"history_items",
"=",
"history",
".",
"items",
"for",
... | If the issue is in progress, gets that most recent time that the issue became 'In Progress' | [
"If",
"the",
"issue",
"is",
"in",
"progress",
"gets",
"that",
"most",
"recent",
"time",
"that",
"the",
"issue",
"became",
"In",
"Progress"
] | python | train |
SeattleTestbed/seash | pyreadline/modes/basemode.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/modes/basemode.py#L373-L376 | def backward_char_extend_selection(self, e): #
u"""Move back a character. """
self.l_buffer.backward_char_extend_selection(self.argument_reset)
self.finalize() | [
"def",
"backward_char_extend_selection",
"(",
"self",
",",
"e",
")",
":",
"#\r",
"self",
".",
"l_buffer",
".",
"backward_char_extend_selection",
"(",
"self",
".",
"argument_reset",
")",
"self",
".",
"finalize",
"(",
")"
] | u"""Move back a character. | [
"u",
"Move",
"back",
"a",
"character",
"."
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/clusterers.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L383-L439 | def main():
"""
Runs a clusterer from the command-line. Calls JVM start/stop automatically.
Use -h to see all options.
"""
parser = argparse.ArgumentParser(
description='Performs clustering from the command-line. Calls JVM start/stop automatically.')
parser.add_argument("-j", metavar="cl... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Performs clustering from the command-line. Calls JVM start/stop automatically.'",
")",
"parser",
".",
"add_argument",
"(",
"\"-j\"",
",",
"metavar",
"=",
"\"classp... | Runs a clusterer from the command-line. Calls JVM start/stop automatically.
Use -h to see all options. | [
"Runs",
"a",
"clusterer",
"from",
"the",
"command",
"-",
"line",
".",
"Calls",
"JVM",
"start",
"/",
"stop",
"automatically",
".",
"Use",
"-",
"h",
"to",
"see",
"all",
"options",
"."
] | python | train |
maas/python-libmaas | maas/client/viscera/machines.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L610-L622 | async def mark_broken(self, *, comment: str = None):
"""Mark broken.
:param comment: Reason machine is broken.
:type comment: `str`
"""
params = {
"system_id": self.system_id
}
if comment:
params["comment"] = comment
self._data = a... | [
"async",
"def",
"mark_broken",
"(",
"self",
",",
"*",
",",
"comment",
":",
"str",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"system_id\"",
":",
"self",
".",
"system_id",
"}",
"if",
"comment",
":",
"params",
"[",
"\"comment\"",
"]",
"=",
"comment",
... | Mark broken.
:param comment: Reason machine is broken.
:type comment: `str` | [
"Mark",
"broken",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/LensModel/numerical_profile_integrals.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/numerical_profile_integrals.py#L56-L71 | def mass_enclosed_2d(self, r, kwargs_profile):
"""
computes the mass enclosed the projected line-of-sight
:param r: radius (arcsec)
:param kwargs_profile: keyword argument list with lens model parameters
:return: projected mass enclosed radius r
"""
kwargs = copy.... | [
"def",
"mass_enclosed_2d",
"(",
"self",
",",
"r",
",",
"kwargs_profile",
")",
":",
"kwargs",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs_profile",
")",
"try",
":",
"del",
"kwargs",
"[",
"'center_x'",
"]",
"del",
"kwargs",
"[",
"'center_y'",
"]",
"except",
... | computes the mass enclosed the projected line-of-sight
:param r: radius (arcsec)
:param kwargs_profile: keyword argument list with lens model parameters
:return: projected mass enclosed radius r | [
"computes",
"the",
"mass",
"enclosed",
"the",
"projected",
"line",
"-",
"of",
"-",
"sight",
":",
"param",
"r",
":",
"radius",
"(",
"arcsec",
")",
":",
"param",
"kwargs_profile",
":",
"keyword",
"argument",
"list",
"with",
"lens",
"model",
"parameters",
":"... | python | train |
h2oai/h2o-3 | h2o-py/h2o/model/model_base.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/model_base.py#L321-L354 | def model_performance(self, test_data=None, train=False, valid=False, xval=False):
"""
Generate model metrics for this model on test_data.
:param H2OFrame test_data: Data set for which model metrics shall be computed against. All three of train,
valid and xval arguments are ignored ... | [
"def",
"model_performance",
"(",
"self",
",",
"test_data",
"=",
"None",
",",
"train",
"=",
"False",
",",
"valid",
"=",
"False",
",",
"xval",
"=",
"False",
")",
":",
"if",
"test_data",
"is",
"None",
":",
"if",
"not",
"train",
"and",
"not",
"valid",
"a... | Generate model metrics for this model on test_data.
:param H2OFrame test_data: Data set for which model metrics shall be computed against. All three of train,
valid and xval arguments are ignored if test_data is not None.
:param bool train: Report the training metrics for the model.
... | [
"Generate",
"model",
"metrics",
"for",
"this",
"model",
"on",
"test_data",
"."
] | python | test |
maweigert/gputools | gputools/fft/oclfft.py | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/oclfft.py#L13-L21 | def _convert_axes_to_absolute(dshape, axes):
"""axes = (-2,-1) does not work in reikna, so we have to convetr that"""
if axes is None:
return None
elif isinstance(axes, (tuple, list)):
return tuple(np.arange(len(dshape))[list(axes)])
else:
raise NotImplementedError("axes %s is o... | [
"def",
"_convert_axes_to_absolute",
"(",
"dshape",
",",
"axes",
")",
":",
"if",
"axes",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"axes",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"tuple",
"(",
"np",
".",
"arange",
... | axes = (-2,-1) does not work in reikna, so we have to convetr that | [
"axes",
"=",
"(",
"-",
"2",
"-",
"1",
")",
"does",
"not",
"work",
"in",
"reikna",
"so",
"we",
"have",
"to",
"convetr",
"that"
] | python | train |
TestInABox/stackInABox | stackinabox/services/service.py | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/services/service.py#L66-L92 | def set_subservice(self, obj):
"""Add a sub-service object.
:param obj: stackinabox.services.StackInABoxService instance
:raises: RouteAlreadyRegisteredError if the route is already registered
:returns: n/a
"""
# ensure there is not already a sub-service
if self.... | [
"def",
"set_subservice",
"(",
"self",
",",
"obj",
")",
":",
"# ensure there is not already a sub-service",
"if",
"self",
".",
"obj",
"is",
"not",
"None",
":",
"raise",
"RouteAlreadyRegisteredError",
"(",
"'Service Router ({0} - {1}): Route {2} already has a '",
"'sub-servic... | Add a sub-service object.
:param obj: stackinabox.services.StackInABoxService instance
:raises: RouteAlreadyRegisteredError if the route is already registered
:returns: n/a | [
"Add",
"a",
"sub",
"-",
"service",
"object",
"."
] | python | train |
elastic/elasticsearch-py | elasticsearch/client/xpack/ml.py | https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ml.py#L880-L903 | def update_model_snapshot(self, job_id, snapshot_id, body, params=None):
"""
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-update-snapshot.html>`_
:arg job_id: The ID of the job to fetch
:arg snapshot_id: The ID of the snapshot to update
:arg body: The mode... | [
"def",
"update_model_snapshot",
"(",
"self",
",",
"job_id",
",",
"snapshot_id",
",",
"body",
",",
"params",
"=",
"None",
")",
":",
"for",
"param",
"in",
"(",
"job_id",
",",
"snapshot_id",
",",
"body",
")",
":",
"if",
"param",
"in",
"SKIP_IN_PATH",
":",
... | `<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-update-snapshot.html>`_
:arg job_id: The ID of the job to fetch
:arg snapshot_id: The ID of the snapshot to update
:arg body: The model snapshot properties to update | [
"<http",
":",
"//",
"www",
".",
"elastic",
".",
"co",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"current",
"/",
"ml",
"-",
"update",
"-",
"snapshot",
".",
"html",
">",
"_"
] | python | train |
awslabs/sockeye | sockeye/image_captioning/encoder.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/image_captioning/encoder.py#L71-L90 | def get_image_cnn_encoder(config: ImageLoadedCnnEncoderConfig) -> 'Encoder':
"""
Creates a image encoder.
:param config: Configuration for image encoder.
:return: Encoder instance.
"""
encoders = list() # type: List[Encoder]
max_seq_len = config.encoded_seq_len
if not config.no_global... | [
"def",
"get_image_cnn_encoder",
"(",
"config",
":",
"ImageLoadedCnnEncoderConfig",
")",
"->",
"'Encoder'",
":",
"encoders",
"=",
"list",
"(",
")",
"# type: List[Encoder]",
"max_seq_len",
"=",
"config",
".",
"encoded_seq_len",
"if",
"not",
"config",
".",
"no_global_d... | Creates a image encoder.
:param config: Configuration for image encoder.
:return: Encoder instance. | [
"Creates",
"a",
"image",
"encoder",
"."
] | python | train |
MartinThoma/memtop | memtop/__init__.py | https://github.com/MartinThoma/memtop/blob/504d251f1951922db84883c2e660ba7e754d1546/memtop/__init__.py#L93-L115 | def graph_format(new_mem, old_mem, is_firstiteration=True):
"""Show changes graphically in memory consumption"""
if is_firstiteration:
output = " n/a "
elif new_mem - old_mem > 50000000:
output = " +++++"
elif new_mem - old_mem > 20000000:
output = " ++++ "
elif new_me... | [
"def",
"graph_format",
"(",
"new_mem",
",",
"old_mem",
",",
"is_firstiteration",
"=",
"True",
")",
":",
"if",
"is_firstiteration",
":",
"output",
"=",
"\" n/a \"",
"elif",
"new_mem",
"-",
"old_mem",
">",
"50000000",
":",
"output",
"=",
"\" +++++\"",
"elif... | Show changes graphically in memory consumption | [
"Show",
"changes",
"graphically",
"in",
"memory",
"consumption"
] | python | train |
facebook/codemod | codemod/terminal_helper.py | https://github.com/facebook/codemod/blob/78bb627792fc8a5253baa9cd9d8160533b16fd85/codemod/terminal_helper.py#L74-L83 | def _terminal_use_capability(capability_name):
"""
If the terminal supports the given capability, output it. Return whether
it was output.
"""
curses.setupterm()
capability = curses.tigetstr(capability_name)
if capability:
sys.stdout.write(_unicode(capability))
return bool(capab... | [
"def",
"_terminal_use_capability",
"(",
"capability_name",
")",
":",
"curses",
".",
"setupterm",
"(",
")",
"capability",
"=",
"curses",
".",
"tigetstr",
"(",
"capability_name",
")",
"if",
"capability",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"_unicode",
... | If the terminal supports the given capability, output it. Return whether
it was output. | [
"If",
"the",
"terminal",
"supports",
"the",
"given",
"capability",
"output",
"it",
".",
"Return",
"whether",
"it",
"was",
"output",
"."
] | python | train |
textbook/atmdb | atmdb/utils.py | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L77-L101 | async def _overlap(items, overlap_attr, client=None, get_method=None):
"""Generic overlap implementation.
Arguments:
item (:py:class:`collections.abc.Sequence`): The objects to
find overlaps for.
overlap_attr (:py:class:`str`): The attribute of the items to use
as input for the over... | [
"async",
"def",
"_overlap",
"(",
"items",
",",
"overlap_attr",
",",
"client",
"=",
"None",
",",
"get_method",
"=",
"None",
")",
":",
"overlap",
"=",
"set",
".",
"intersection",
"(",
"*",
"(",
"getattr",
"(",
"item",
",",
"overlap_attr",
")",
"for",
"it... | Generic overlap implementation.
Arguments:
item (:py:class:`collections.abc.Sequence`): The objects to
find overlaps for.
overlap_attr (:py:class:`str`): The attribute of the items to use
as input for the overlap.
client (:py:class:`~.TMDbClient`, optional): The TMDb client
... | [
"Generic",
"overlap",
"implementation",
"."
] | python | train |
onjin/ntv | ntv/web.py | https://github.com/onjin/ntv/blob/9baa9cfdff9eca0ebd12b6c456951345a269039f/ntv/web.py#L31-L60 | def result_to_dict(raw_result):
"""
Parse raw result from fetcher into readable dictionary
Args:
raw_result (dict) - raw data from `fetcher`
Returns:
dict - readable dictionary
"""
result = {}
for channel_index, channel in enumerate(raw_result):
channel_id, channe... | [
"def",
"result_to_dict",
"(",
"raw_result",
")",
":",
"result",
"=",
"{",
"}",
"for",
"channel_index",
",",
"channel",
"in",
"enumerate",
"(",
"raw_result",
")",
":",
"channel_id",
",",
"channel_name",
"=",
"channel",
"[",
"0",
"]",
",",
"channel",
"[",
... | Parse raw result from fetcher into readable dictionary
Args:
raw_result (dict) - raw data from `fetcher`
Returns:
dict - readable dictionary | [
"Parse",
"raw",
"result",
"from",
"fetcher",
"into",
"readable",
"dictionary"
] | python | train |
chaoss/grimoirelab-perceval-mozilla | perceval/backends/mozilla/crates.py | https://github.com/chaoss/grimoirelab-perceval-mozilla/blob/4514f8d3d609d3cb79d83c72d51fcc4b4a7daeb4/perceval/backends/mozilla/crates.py#L204-L211 | def __fetch_crate_owner_team(self, crate_id):
"""Get crate team owner"""
raw_owner_team = self.client.crate_attribute(crate_id, 'owner_team')
owner_team = json.loads(raw_owner_team)
return owner_team | [
"def",
"__fetch_crate_owner_team",
"(",
"self",
",",
"crate_id",
")",
":",
"raw_owner_team",
"=",
"self",
".",
"client",
".",
"crate_attribute",
"(",
"crate_id",
",",
"'owner_team'",
")",
"owner_team",
"=",
"json",
".",
"loads",
"(",
"raw_owner_team",
")",
"re... | Get crate team owner | [
"Get",
"crate",
"team",
"owner"
] | python | test |
src-d/modelforge | modelforge/meta.py | https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/meta.py#L24-L53 | def generate_new_meta(name: str, description: str, vendor: str, license: str) -> dict:
"""
Create the metadata tree for the given model name and the list of dependencies.
:param name: Name of the model.
:param description: Description of the model.
:param vendor: Name of the party which is responsi... | [
"def",
"generate_new_meta",
"(",
"name",
":",
"str",
",",
"description",
":",
"str",
",",
"vendor",
":",
"str",
",",
"license",
":",
"str",
")",
"->",
"dict",
":",
"check_license",
"(",
"license",
")",
"return",
"{",
"\"code\"",
":",
"None",
",",
"\"cr... | Create the metadata tree for the given model name and the list of dependencies.
:param name: Name of the model.
:param description: Description of the model.
:param vendor: Name of the party which is responsible for support of the model.
:param license: License identifier.
:return: dict with the me... | [
"Create",
"the",
"metadata",
"tree",
"for",
"the",
"given",
"model",
"name",
"and",
"the",
"list",
"of",
"dependencies",
"."
] | python | train |
gwastro/pycbc-glue | pycbc_glue/ligolw/array.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/array.py#L154-L162 | def get_array(xmldoc, name):
"""
Scan xmldoc for an array named name. Raises ValueError if not
exactly 1 such array is found.
"""
arrays = getArraysByName(xmldoc, name)
if len(arrays) != 1:
raise ValueError("document must contain exactly one %s array" % StripArrayName(name))
return arrays[0] | [
"def",
"get_array",
"(",
"xmldoc",
",",
"name",
")",
":",
"arrays",
"=",
"getArraysByName",
"(",
"xmldoc",
",",
"name",
")",
"if",
"len",
"(",
"arrays",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"document must contain exactly one %s array\"",
"%",
"... | Scan xmldoc for an array named name. Raises ValueError if not
exactly 1 such array is found. | [
"Scan",
"xmldoc",
"for",
"an",
"array",
"named",
"name",
".",
"Raises",
"ValueError",
"if",
"not",
"exactly",
"1",
"such",
"array",
"is",
"found",
"."
] | python | train |
saltstack/salt | salt/modules/nspawn.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L834-L859 | def list_all():
'''
Lists all nspawn containers
CLI Example:
.. code-block:: bash
salt myminion nspawn.list_all
'''
ret = []
if _sd_version() >= 219:
for line in _machinectl('list-images')['stdout'].splitlines():
try:
ret.append(line.split()[0])... | [
"def",
"list_all",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"_sd_version",
"(",
")",
">=",
"219",
":",
"for",
"line",
"in",
"_machinectl",
"(",
"'list-images'",
")",
"[",
"'stdout'",
"]",
".",
"splitlines",
"(",
")",
":",
"try",
":",
"ret",
".",
... | Lists all nspawn containers
CLI Example:
.. code-block:: bash
salt myminion nspawn.list_all | [
"Lists",
"all",
"nspawn",
"containers"
] | python | train |
KelSolaar/Umbra | umbra/preferences.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/preferences.py#L206-L223 | def set_key(self, section, key, value):
"""
Stores given key in settings file.
:param section: Current section to save the key into.
:type section: unicode
:param key: Current key to save.
:type key: unicode
:param value: Current key value to save.
:type ... | [
"def",
"set_key",
"(",
"self",
",",
"section",
",",
"key",
",",
"value",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Saving '{0}' in '{1}' section with value: '{2}' in settings file.\"",
".",
"format",
"(",
"key",
",",
"section",
",",
"foundations",
".",
"strings"... | Stores given key in settings file.
:param section: Current section to save the key into.
:type section: unicode
:param key: Current key to save.
:type key: unicode
:param value: Current key value to save.
:type value: object | [
"Stores",
"given",
"key",
"in",
"settings",
"file",
"."
] | python | train |
python-security/pyt | pyt/cfg/expr_visitor.py | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/expr_visitor.py#L247-L329 | def save_def_args_in_temp(
self,
call_args,
def_args,
line_number,
saved_function_call_index,
first_node
):
"""Save the arguments of the definition being called. Visit the arguments if they're calls.
Args:
call_args(list[ast.Name]): Of the... | [
"def",
"save_def_args_in_temp",
"(",
"self",
",",
"call_args",
",",
"def_args",
",",
"line_number",
",",
"saved_function_call_index",
",",
"first_node",
")",
":",
"args_mapping",
"=",
"dict",
"(",
")",
"last_return_value_of_nested_call",
"=",
"None",
"# Create e.g. te... | Save the arguments of the definition being called. Visit the arguments if they're calls.
Args:
call_args(list[ast.Name]): Of the call being made.
def_args(ast_helper.Arguments): Of the definition being called.
line_number(int): Of the call being made.
saved_funct... | [
"Save",
"the",
"arguments",
"of",
"the",
"definition",
"being",
"called",
".",
"Visit",
"the",
"arguments",
"if",
"they",
"re",
"calls",
"."
] | python | train |
askedrelic/libgreader | libgreader/googlereader.py | https://github.com/askedrelic/libgreader/blob/7b668ee291c2464ea172ef44393100c369efa970/libgreader/googlereader.py#L235-L251 | def subscribe(self, feedUrl):
"""
Adds a feed to the top-level subscription list
Ubscribing seems idempotent, you can subscribe multiple times
without error
returns True or throws HTTPError
"""
response = self.httpPost(
ReaderUrl.SUBSCRIPTION_EDIT_UR... | [
"def",
"subscribe",
"(",
"self",
",",
"feedUrl",
")",
":",
"response",
"=",
"self",
".",
"httpPost",
"(",
"ReaderUrl",
".",
"SUBSCRIPTION_EDIT_URL",
",",
"{",
"'ac'",
":",
"'subscribe'",
",",
"'s'",
":",
"feedUrl",
"}",
")",
"# FIXME - need better return API",... | Adds a feed to the top-level subscription list
Ubscribing seems idempotent, you can subscribe multiple times
without error
returns True or throws HTTPError | [
"Adds",
"a",
"feed",
"to",
"the",
"top",
"-",
"level",
"subscription",
"list"
] | python | train |
androguard/androguard | androguard/core/androconf.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/androconf.py#L339-L346 | def color_range(startcolor, goalcolor, steps):
"""
wrapper for interpolate_tuple that accepts colors as html ("#CCCCC" and such)
"""
start_tuple = make_color_tuple(startcolor)
goal_tuple = make_color_tuple(goalcolor)
return interpolate_tuple(start_tuple, goal_tuple, steps) | [
"def",
"color_range",
"(",
"startcolor",
",",
"goalcolor",
",",
"steps",
")",
":",
"start_tuple",
"=",
"make_color_tuple",
"(",
"startcolor",
")",
"goal_tuple",
"=",
"make_color_tuple",
"(",
"goalcolor",
")",
"return",
"interpolate_tuple",
"(",
"start_tuple",
",",... | wrapper for interpolate_tuple that accepts colors as html ("#CCCCC" and such) | [
"wrapper",
"for",
"interpolate_tuple",
"that",
"accepts",
"colors",
"as",
"html",
"(",
"#CCCCC",
"and",
"such",
")"
] | python | train |
doakey3/DashTable | dashtable/html2data/headers_present.py | https://github.com/doakey3/DashTable/blob/744cfb6a717fa75a8092c83ebcd49b2668023681/dashtable/html2data/headers_present.py#L1-L28 | def headers_present(html_string):
"""
Checks if the html table contains headers and returns True/False
Parameters
----------
html_string : str
Returns
-------
bool
"""
try:
from bs4 import BeautifulSoup
except ImportError:
print("ERROR: You must have Beautif... | [
"def",
"headers_present",
"(",
"html_string",
")",
":",
"try",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"except",
"ImportError",
":",
"print",
"(",
"\"ERROR: You must have BeautifulSoup to use html2data\"",
")",
"return",
"soup",
"=",
"BeautifulSoup",
"(",
"html... | Checks if the html table contains headers and returns True/False
Parameters
----------
html_string : str
Returns
-------
bool | [
"Checks",
"if",
"the",
"html",
"table",
"contains",
"headers",
"and",
"returns",
"True",
"/",
"False"
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/tunnel/pb/encoder.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/tunnel/pb/encoder.py#L42-L44 | def append_tag(self, field_number, wire_type):
"""Appends a tag containing field number and wire type information."""
self._stream.append_var_uint32(wire_format.pack_tag(field_number, wire_type)) | [
"def",
"append_tag",
"(",
"self",
",",
"field_number",
",",
"wire_type",
")",
":",
"self",
".",
"_stream",
".",
"append_var_uint32",
"(",
"wire_format",
".",
"pack_tag",
"(",
"field_number",
",",
"wire_type",
")",
")"
] | Appends a tag containing field number and wire type information. | [
"Appends",
"a",
"tag",
"containing",
"field",
"number",
"and",
"wire",
"type",
"information",
"."
] | python | train |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2647-L2658 | def addUnderlineAnnot(self, rect):
"""Underline content in a rectangle or quadrilateral."""
CheckParent(self)
val = _fitz.Page_addUnderlineAnnot(self, rect)
if not val: return
val.thisown = True
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = val
... | [
"def",
"addUnderlineAnnot",
"(",
"self",
",",
"rect",
")",
":",
"CheckParent",
"(",
"self",
")",
"val",
"=",
"_fitz",
".",
"Page_addUnderlineAnnot",
"(",
"self",
",",
"rect",
")",
"if",
"not",
"val",
":",
"return",
"val",
".",
"thisown",
"=",
"True",
"... | Underline content in a rectangle or quadrilateral. | [
"Underline",
"content",
"in",
"a",
"rectangle",
"or",
"quadrilateral",
"."
] | python | train |
saltstack/salt | salt/cli/salt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/salt.py#L364-L380 | def _output_ret(self, ret, out, retcode=0):
'''
Print the output from a single return to the terminal
'''
import salt.output
# Handle special case commands
if self.config['fun'] == 'sys.doc' and not isinstance(ret, Exception):
self._print_docs(ret)
els... | [
"def",
"_output_ret",
"(",
"self",
",",
"ret",
",",
"out",
",",
"retcode",
"=",
"0",
")",
":",
"import",
"salt",
".",
"output",
"# Handle special case commands",
"if",
"self",
".",
"config",
"[",
"'fun'",
"]",
"==",
"'sys.doc'",
"and",
"not",
"isinstance",... | Print the output from a single return to the terminal | [
"Print",
"the",
"output",
"from",
"a",
"single",
"return",
"to",
"the",
"terminal"
] | python | train |
bcbio/bcbio-nextgen | bcbio/variation/prioritize.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L189-L204 | def _do_prioritize(items):
"""Determine if we should perform prioritization.
Currently done on tumor-only input samples and feeding into PureCN
which needs the germline annotations.
"""
if not any("tumoronly-prioritization" in dd.get_tools_off(d) for d in items):
if vcfutils.get_paired_phen... | [
"def",
"_do_prioritize",
"(",
"items",
")",
":",
"if",
"not",
"any",
"(",
"\"tumoronly-prioritization\"",
"in",
"dd",
".",
"get_tools_off",
"(",
"d",
")",
"for",
"d",
"in",
"items",
")",
":",
"if",
"vcfutils",
".",
"get_paired_phenotype",
"(",
"items",
"["... | Determine if we should perform prioritization.
Currently done on tumor-only input samples and feeding into PureCN
which needs the germline annotations. | [
"Determine",
"if",
"we",
"should",
"perform",
"prioritization",
"."
] | python | train |
kubernetes-client/python | kubernetes/client/apis/core_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/core_v1_api.py#L11464-L11490 | def list_limit_range_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_limit_range_for_all_namespaces(asy... | [
"def",
"list_limit_range_for_all_namespaces",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"list_limit_range_for_all_... | list or watch objects of kind LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_limit_range_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool... | [
"list",
"or",
"watch",
"objects",
"of",
"kind",
"LimitRange",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"t... | python | train |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L523-L556 | def update_model(self, model, fields, retry=DEFAULT_RETRY):
"""[Beta] Change some fields of a model.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None``
in ``model``, it will be deleted.
If ``... | [
"def",
"update_model",
"(",
"self",
",",
"model",
",",
"fields",
",",
"retry",
"=",
"DEFAULT_RETRY",
")",
":",
"partial",
"=",
"model",
".",
"_build_resource",
"(",
"fields",
")",
"if",
"model",
".",
"etag",
":",
"headers",
"=",
"{",
"\"If-Match\"",
":",... | [Beta] Change some fields of a model.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None``
in ``model``, it will be deleted.
If ``model.etag`` is not ``None``, the update will only succeed if
t... | [
"[",
"Beta",
"]",
"Change",
"some",
"fields",
"of",
"a",
"model",
"."
] | python | train |
roamanalytics/mittens | mittens/np_mittens.py | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/np_mittens.py#L136-L154 | def _apply_updates(self, gradients):
"""Apply AdaGrad update to parameters.
Parameters
----------
gradients
Returns
-------
"""
if not hasattr(self, 'optimizers'):
self.optimizers = \
{obj: AdaGradOptimizer(self.learning_rate... | [
"def",
"_apply_updates",
"(",
"self",
",",
"gradients",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'optimizers'",
")",
":",
"self",
".",
"optimizers",
"=",
"{",
"obj",
":",
"AdaGradOptimizer",
"(",
"self",
".",
"learning_rate",
")",
"for",
"obj... | Apply AdaGrad update to parameters.
Parameters
----------
gradients
Returns
------- | [
"Apply",
"AdaGrad",
"update",
"to",
"parameters",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/ndarray/sparse.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L754-L784 | def copyto(self, other):
"""Copies the value of this array to another array.
If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape``
and ``self.shape`` should be the same. This function copies the value from
``self`` to ``other``.
If ``other`` is a co... | [
"def",
"copyto",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Context",
")",
":",
"return",
"super",
"(",
"RowSparseNDArray",
",",
"self",
")",
".",
"copyto",
"(",
"other",
")",
"elif",
"isinstance",
"(",
"other",
",",
... | Copies the value of this array to another array.
If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape``
and ``self.shape`` should be the same. This function copies the value from
``self`` to ``other``.
If ``other`` is a context, a new ``RowSparseNDArray`` wi... | [
"Copies",
"the",
"value",
"of",
"this",
"array",
"to",
"another",
"array",
"."
] | python | train |
glomex/gcdt | gcdt/kumo_start_stop.py | https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/kumo_start_stop.py#L169-L284 | def stop_stack(awsclient, stack_name, use_suspend=False):
"""Stop an existing stack on AWS cloud.
:param awsclient:
:param stack_name:
:param use_suspend: use suspend and resume on the autoscaling group
:return: exit_code
"""
exit_code = 0
# check for DisableStop
#disable_stop = co... | [
"def",
"stop_stack",
"(",
"awsclient",
",",
"stack_name",
",",
"use_suspend",
"=",
"False",
")",
":",
"exit_code",
"=",
"0",
"# check for DisableStop",
"#disable_stop = conf.get('deployment', {}).get('DisableStop', False)",
"#if disable_stop:",
"# log.warn('\\'DisableStop\\' i... | Stop an existing stack on AWS cloud.
:param awsclient:
:param stack_name:
:param use_suspend: use suspend and resume on the autoscaling group
:return: exit_code | [
"Stop",
"an",
"existing",
"stack",
"on",
"AWS",
"cloud",
"."
] | python | train |
eaton-lab/toytree | toytree/Coords.py | https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/Coords.py#L252-L287 | def reorient_coordinates(self):
"""
Returns a modified .verts array with new coordinates for nodes.
This does not need to modify .edges. The order of nodes, and therefore
of verts rows is still the same because it is still based on the tree
branching order (ladderized usually). ... | [
"def",
"reorient_coordinates",
"(",
"self",
")",
":",
"# if tree is empty then bail out",
"if",
"len",
"(",
"self",
".",
"ttree",
")",
"<",
"2",
":",
"return",
"# down is the default orientation",
"# down-facing tips align at y=0, first ladderized tip at x=0",
"if",
"self",... | Returns a modified .verts array with new coordinates for nodes.
This does not need to modify .edges. The order of nodes, and therefore
of verts rows is still the same because it is still based on the tree
branching order (ladderized usually). | [
"Returns",
"a",
"modified",
".",
"verts",
"array",
"with",
"new",
"coordinates",
"for",
"nodes",
".",
"This",
"does",
"not",
"need",
"to",
"modify",
".",
"edges",
".",
"The",
"order",
"of",
"nodes",
"and",
"therefore",
"of",
"verts",
"rows",
"is",
"still... | python | train |
lpantano/seqcluster | seqcluster/detect/description.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/detect/description.py#L25-L40 | def best_precursor(clus, loci):
"""
Select best precursor asuming size around 100 nt
"""
data_loci = sort_precursor(clus, loci)
current_size = data_loci[0][5]
best = 0
for item, locus in enumerate(data_loci):
if locus[3] - locus[2] > 70:
if locus[5] > current_size * 0.8:
... | [
"def",
"best_precursor",
"(",
"clus",
",",
"loci",
")",
":",
"data_loci",
"=",
"sort_precursor",
"(",
"clus",
",",
"loci",
")",
"current_size",
"=",
"data_loci",
"[",
"0",
"]",
"[",
"5",
"]",
"best",
"=",
"0",
"for",
"item",
",",
"locus",
"in",
"enum... | Select best precursor asuming size around 100 nt | [
"Select",
"best",
"precursor",
"asuming",
"size",
"around",
"100",
"nt"
] | python | train |
celery/django-celery | djcelery/managers.py | https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L115-L124 | def delete_expired(self, expires):
"""Delete all expired taskset results."""
meta = self.model._meta
with commit_on_success():
self.get_all_expired(expires).update(hidden=True)
cursor = self.connection_for_write().cursor()
cursor.execute(
'DELE... | [
"def",
"delete_expired",
"(",
"self",
",",
"expires",
")",
":",
"meta",
"=",
"self",
".",
"model",
".",
"_meta",
"with",
"commit_on_success",
"(",
")",
":",
"self",
".",
"get_all_expired",
"(",
"expires",
")",
".",
"update",
"(",
"hidden",
"=",
"True",
... | Delete all expired taskset results. | [
"Delete",
"all",
"expired",
"taskset",
"results",
"."
] | python | train |
GNS3/gns3-server | gns3server/compute/base_manager.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L495-L517 | def get_relative_image_path(self, path):
"""
Get a path relative to images directory path
or an abspath if the path is not located inside
image directory
:param path: file path
:return: file path
"""
if not path:
return ""
path = forc... | [
"def",
"get_relative_image_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"\"\"",
"path",
"=",
"force_unix_path",
"(",
"self",
".",
"get_abs_image_path",
"(",
"path",
")",
")",
"img_directory",
"=",
"self",
".",
"get_images_di... | Get a path relative to images directory path
or an abspath if the path is not located inside
image directory
:param path: file path
:return: file path | [
"Get",
"a",
"path",
"relative",
"to",
"images",
"directory",
"path",
"or",
"an",
"abspath",
"if",
"the",
"path",
"is",
"not",
"located",
"inside",
"image",
"directory"
] | python | train |
log2timeline/dftimewolf | dftimewolf/lib/processors/turbinia.py | https://github.com/log2timeline/dftimewolf/blob/45f898476a288d73c4256ae8e3836a2a4848c0d7/dftimewolf/lib/processors/turbinia.py#L94-L111 | def _print_task_data(self, task):
"""Pretty-prints task data.
Args:
task: Task dict generated by Turbinia.
"""
print(' {0:s} ({1:s})'.format(task['name'], task['id']))
paths = task.get('saved_paths', [])
if not paths:
return
for path in paths:
if path.endswith('worker-log.... | [
"def",
"_print_task_data",
"(",
"self",
",",
"task",
")",
":",
"print",
"(",
"' {0:s} ({1:s})'",
".",
"format",
"(",
"task",
"[",
"'name'",
"]",
",",
"task",
"[",
"'id'",
"]",
")",
")",
"paths",
"=",
"task",
".",
"get",
"(",
"'saved_paths'",
",",
"["... | Pretty-prints task data.
Args:
task: Task dict generated by Turbinia. | [
"Pretty",
"-",
"prints",
"task",
"data",
"."
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_battery.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_battery.py#L121-L131 | def mavlink_packet(self, m):
'''handle a mavlink packet'''
mtype = m.get_type()
if mtype == "SYS_STATUS":
self.battery_update(m)
if mtype == "BATTERY2":
self.battery2_voltage = m.voltage * 0.001
if mtype == "POWER_STATUS":
self.power_status_upd... | [
"def",
"mavlink_packet",
"(",
"self",
",",
"m",
")",
":",
"mtype",
"=",
"m",
".",
"get_type",
"(",
")",
"if",
"mtype",
"==",
"\"SYS_STATUS\"",
":",
"self",
".",
"battery_update",
"(",
"m",
")",
"if",
"mtype",
"==",
"\"BATTERY2\"",
":",
"self",
".",
"... | handle a mavlink packet | [
"handle",
"a",
"mavlink",
"packet"
] | python | train |
vstinner/perf | perf/_cpu_utils.py | https://github.com/vstinner/perf/blob/cf096c0c0c955d0aa1c893847fa6393ba4922ada/perf/_cpu_utils.py#L127-L147 | def get_isolated_cpus():
"""Get the list of isolated CPUs.
Return a sorted list of CPU identifiers, or return None if no CPU is
isolated.
"""
# The cpu/isolated sysfs was added in Linux 4.2
# (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49)
path = sysfs_path('devices/system/cpu/isolated')
... | [
"def",
"get_isolated_cpus",
"(",
")",
":",
"# The cpu/isolated sysfs was added in Linux 4.2",
"# (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49)",
"path",
"=",
"sysfs_path",
"(",
"'devices/system/cpu/isolated'",
")",
"isolated",
"=",
"read_first_line",
"(",
"path",
")",
"if",... | Get the list of isolated CPUs.
Return a sorted list of CPU identifiers, or return None if no CPU is
isolated. | [
"Get",
"the",
"list",
"of",
"isolated",
"CPUs",
"."
] | python | train |
django-danceschool/django-danceschool | danceschool/payments/square/tasks.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/square/tasks.py#L5-L17 | def updateSquareFees(paymentRecord):
'''
The Square Checkout API does not calculate fees immediately, so this task is
called to be asynchronously run 1 minute after the initial transaction, so that
any Invoice or ExpenseItem associated with this transaction also remains accurate.
'''
fee... | [
"def",
"updateSquareFees",
"(",
"paymentRecord",
")",
":",
"fees",
"=",
"paymentRecord",
".",
"netFees",
"invoice",
"=",
"paymentRecord",
".",
"invoice",
"invoice",
".",
"fees",
"=",
"fees",
"invoice",
".",
"save",
"(",
")",
"invoice",
".",
"allocateFees",
"... | The Square Checkout API does not calculate fees immediately, so this task is
called to be asynchronously run 1 minute after the initial transaction, so that
any Invoice or ExpenseItem associated with this transaction also remains accurate. | [
"The",
"Square",
"Checkout",
"API",
"does",
"not",
"calculate",
"fees",
"immediately",
"so",
"this",
"task",
"is",
"called",
"to",
"be",
"asynchronously",
"run",
"1",
"minute",
"after",
"the",
"initial",
"transaction",
"so",
"that",
"any",
"Invoice",
"or",
"... | python | train |
cggh/scikit-allel | allel/stats/hw.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/hw.py#L106-L157 | def inbreeding_coefficient(g, fill=np.nan):
"""Calculate the inbreeding coefficient for each variant.
Parameters
----------
g : array_like, int, shape (n_variants, n_samples, ploidy)
Genotype array.
fill : float, optional
Use this value for variants where the expected heterozygosit... | [
"def",
"inbreeding_coefficient",
"(",
"g",
",",
"fill",
"=",
"np",
".",
"nan",
")",
":",
"# check inputs",
"if",
"not",
"hasattr",
"(",
"g",
",",
"'count_het'",
")",
"or",
"not",
"hasattr",
"(",
"g",
",",
"'count_called'",
")",
":",
"g",
"=",
"Genotype... | Calculate the inbreeding coefficient for each variant.
Parameters
----------
g : array_like, int, shape (n_variants, n_samples, ploidy)
Genotype array.
fill : float, optional
Use this value for variants where the expected heterozygosity is
zero.
Returns
-------
f ... | [
"Calculate",
"the",
"inbreeding",
"coefficient",
"for",
"each",
"variant",
"."
] | python | train |
estnltk/estnltk | estnltk/text.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/text.py#L722-L727 | def tag_syntax_vislcg3(self):
""" Changes default syntactic parser to VISLCG3Parser, performs syntactic analysis,
and stores the results in the layer named LAYER_VISLCG3."""
if not self.__syntactic_parser or not isinstance(self.__syntactic_parser, VISLCG3Parser):
self.__syntactic... | [
"def",
"tag_syntax_vislcg3",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__syntactic_parser",
"or",
"not",
"isinstance",
"(",
"self",
".",
"__syntactic_parser",
",",
"VISLCG3Parser",
")",
":",
"self",
".",
"__syntactic_parser",
"=",
"VISLCG3Parser",
"(",
... | Changes default syntactic parser to VISLCG3Parser, performs syntactic analysis,
and stores the results in the layer named LAYER_VISLCG3. | [
"Changes",
"default",
"syntactic",
"parser",
"to",
"VISLCG3Parser",
"performs",
"syntactic",
"analysis",
"and",
"stores",
"the",
"results",
"in",
"the",
"layer",
"named",
"LAYER_VISLCG3",
"."
] | python | train |
hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1591-L1613 | def enum_value(self):
"""Return the value of an enum constant."""
if not hasattr(self, '_enum_value'):
assert self.kind == CursorKind.ENUM_CONSTANT_DECL
# Figure out the underlying type of the enum to know if it
# is a signed or unsigned quantity.
underlyi... | [
"def",
"enum_value",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_enum_value'",
")",
":",
"assert",
"self",
".",
"kind",
"==",
"CursorKind",
".",
"ENUM_CONSTANT_DECL",
"# Figure out the underlying type of the enum to know if it",
"# is a signed ... | Return the value of an enum constant. | [
"Return",
"the",
"value",
"of",
"an",
"enum",
"constant",
"."
] | python | train |
gccxml/pygccxml | pygccxml/declarations/algorithm.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/algorithm.py#L37-L60 | def does_match_exist(self, inst):
"""
Returns True if inst does match one of specified criteria.
:param inst: declaration instance
:type inst: :class:`declaration_t`
:rtype: bool
"""
answer = True
if self._decl_type is not None:
answer &= i... | [
"def",
"does_match_exist",
"(",
"self",
",",
"inst",
")",
":",
"answer",
"=",
"True",
"if",
"self",
".",
"_decl_type",
"is",
"not",
"None",
":",
"answer",
"&=",
"isinstance",
"(",
"inst",
",",
"self",
".",
"_decl_type",
")",
"if",
"self",
".",
"name",
... | Returns True if inst does match one of specified criteria.
:param inst: declaration instance
:type inst: :class:`declaration_t`
:rtype: bool | [
"Returns",
"True",
"if",
"inst",
"does",
"match",
"one",
"of",
"specified",
"criteria",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/vi/csiszar_divergence.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L121-L166 | def kl_reverse(logu, self_normalized=False, name=None):
"""The reverse Kullback-Leibler Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the KL-reverse Csiszar-function is:
```none
f(u) = -log(u) + (u - 1)
`... | [
"def",
"kl_reverse",
"(",
"logu",
",",
"self_normalized",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"kl_reverse\"",
",",
"[",
"logu",
"]",
")",
":",
"return",
"ama... | The reverse Kullback-Leibler Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the KL-reverse Csiszar-function is:
```none
f(u) = -log(u) + (u - 1)
```
When `self_normalized = False` the `(u - 1)` term is om... | [
"The",
"reverse",
"Kullback",
"-",
"Leibler",
"Csiszar",
"-",
"function",
"in",
"log",
"-",
"space",
"."
] | python | test |
RedHatInsights/insights-core | insights/parsers/__init__.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/__init__.py#L451-L528 | def keyword_search(rows, **kwargs):
"""
Takes a list of dictionaries and finds all the dictionaries where the
keys and values match those found in the keyword arguments.
Keys in the row data have ' ' and '-' replaced with '_', so they can
match the keyword argument parsing. For example, the keywor... | [
"def",
"keyword_search",
"(",
"rows",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"[",
"]",
"if",
"not",
"kwargs",
":",
"return",
"results",
"# Allows us to transform the key and do lookups like __contains and",
"# __startswith",
"matchers",
"=",
"{",
"'defau... | Takes a list of dictionaries and finds all the dictionaries where the
keys and values match those found in the keyword arguments.
Keys in the row data have ' ' and '-' replaced with '_', so they can
match the keyword argument parsing. For example, the keyword argument
'fix_up_path' will match a key na... | [
"Takes",
"a",
"list",
"of",
"dictionaries",
"and",
"finds",
"all",
"the",
"dictionaries",
"where",
"the",
"keys",
"and",
"values",
"match",
"those",
"found",
"in",
"the",
"keyword",
"arguments",
"."
] | python | train |
briandilley/ebs-deploy | ebs_deploy/__init__.py | https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L58-L66 | def parse_option_settings(option_settings):
"""
Parses option_settings as they are defined in the configuration file
"""
ret = []
for namespace, params in list(option_settings.items()):
for key, value in list(params.items()):
ret.append((namespace, key, value))
return ret | [
"def",
"parse_option_settings",
"(",
"option_settings",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"namespace",
",",
"params",
"in",
"list",
"(",
"option_settings",
".",
"items",
"(",
")",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"params",
... | Parses option_settings as they are defined in the configuration file | [
"Parses",
"option_settings",
"as",
"they",
"are",
"defined",
"in",
"the",
"configuration",
"file"
] | python | valid |
fabric/fabric | fabric/config.py | https://github.com/fabric/fabric/blob/e9939d68b734935f0c98d98817912ad7c698238f/fabric/config.py#L210-L253 | def global_defaults():
"""
Default configuration values and behavior toggles.
Fabric only extends this method in order to make minor adjustments and
additions to Invoke's `~invoke.config.Config.global_defaults`; see its
documentation for the base values, such as the config subtr... | [
"def",
"global_defaults",
"(",
")",
":",
"# TODO: hrm should the run-related things actually be derived from the",
"# runner_class? E.g. Local defines local stuff, Remote defines remote",
"# stuff? Doesn't help with the final config tree tho...",
"# TODO: as to that, this is a core problem, Fabric w... | Default configuration values and behavior toggles.
Fabric only extends this method in order to make minor adjustments and
additions to Invoke's `~invoke.config.Config.global_defaults`; see its
documentation for the base values, such as the config subtrees
controlling behavior of ``run``... | [
"Default",
"configuration",
"values",
"and",
"behavior",
"toggles",
"."
] | python | train |
explosion/spaCy | spacy/util.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L406-L427 | def expand_exc(excs, search, replace):
"""Find string in tokenizer exceptions, duplicate entry and replace string.
For example, to add additional versions with typographic apostrophes.
excs (dict): Tokenizer exceptions.
search (unicode): String to find and replace.
replace (unicode): Replacement.
... | [
"def",
"expand_exc",
"(",
"excs",
",",
"search",
",",
"replace",
")",
":",
"def",
"_fix_token",
"(",
"token",
",",
"search",
",",
"replace",
")",
":",
"fixed",
"=",
"dict",
"(",
"token",
")",
"fixed",
"[",
"ORTH",
"]",
"=",
"fixed",
"[",
"ORTH",
"]... | Find string in tokenizer exceptions, duplicate entry and replace string.
For example, to add additional versions with typographic apostrophes.
excs (dict): Tokenizer exceptions.
search (unicode): String to find and replace.
replace (unicode): Replacement.
RETURNS (dict): Combined tokenizer exceptio... | [
"Find",
"string",
"in",
"tokenizer",
"exceptions",
"duplicate",
"entry",
"and",
"replace",
"string",
".",
"For",
"example",
"to",
"add",
"additional",
"versions",
"with",
"typographic",
"apostrophes",
"."
] | python | train |
dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L221-L253 | def _load_embedding(self, pretrained_file_path, elem_delim,
encoding='utf8'):
"""Load embedding vectors from a pre-trained token embedding file.
Both text files and TokenEmbedding serialization files are supported.
elem_delim and encoding are ignored for non-text files.
... | [
"def",
"_load_embedding",
"(",
"self",
",",
"pretrained_file_path",
",",
"elem_delim",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"pretrained_file_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"pretrained_file_path",
")",
"if",
"not",
"os",
".",
"path"... | Load embedding vectors from a pre-trained token embedding file.
Both text files and TokenEmbedding serialization files are supported.
elem_delim and encoding are ignored for non-text files.
For every unknown token, if its representation `self.unknown_token` is encountered in the
pre-tr... | [
"Load",
"embedding",
"vectors",
"from",
"a",
"pre",
"-",
"trained",
"token",
"embedding",
"file",
"."
] | python | train |
stain/forgetSQL | lib/forgetSQL.py | https://github.com/stain/forgetSQL/blob/2e13f983020b121fd75a95fcafce3ea75573fb6b/lib/forgetSQL.py#L439-L449 | def delete(self):
"""Mark this object for deletion in the database.
The object will then be reset and ready for use
again with a new id.
"""
(sql, ) = self._prepareSQL("DELETE")
curs = self.cursor()
curs.execute(sql, self._getID())
curs.close()
se... | [
"def",
"delete",
"(",
"self",
")",
":",
"(",
"sql",
",",
")",
"=",
"self",
".",
"_prepareSQL",
"(",
"\"DELETE\"",
")",
"curs",
"=",
"self",
".",
"cursor",
"(",
")",
"curs",
".",
"execute",
"(",
"sql",
",",
"self",
".",
"_getID",
"(",
")",
")",
... | Mark this object for deletion in the database.
The object will then be reset and ready for use
again with a new id. | [
"Mark",
"this",
"object",
"for",
"deletion",
"in",
"the",
"database",
"."
] | python | train |
jobovy/galpy | galpy/potential/SoftenedNeedleBarPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/SoftenedNeedleBarPotential.py#L217-L242 | def _dens(self,R,z,phi=0.,t=0.):
"""
NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the densi... | [
"def",
"_dens",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"self",
".",
"_compute_xyz",
"(",
"R",
",",
"phi",
",",
"z",
",",
"t",
")",
"zc",
"=",
"numpy",
".",
"s... | NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the density
HISTORY:
2016-11-04 - Written -... | [
"NAME",
":",
"_dens",
"PURPOSE",
":",
"evaluate",
"the",
"density",
"for",
"this",
"potential",
"INPUT",
":",
"R",
"-",
"Galactocentric",
"cylindrical",
"radius",
"z",
"-",
"vertical",
"height",
"phi",
"-",
"azimuth",
"t",
"-",
"time",
"OUTPUT",
":",
"the"... | python | train |
Azure/msrest-for-python | msrest/serialization.py | https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/serialization.py#L634-L655 | def header(self, name, data, data_type, **kwargs):
"""Serialize data intended for a request header.
:param data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
:raises: TypeError if serialization fails.
:raises: ValueError if... | [
"def",
"header",
"(",
"self",
",",
"name",
",",
"data",
",",
"data_type",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"client_side_validation",
":",
"data",
"=",
"self",
".",
"validate",
"(",
"data",
",",
"name",
",",
"required",
"=",
"True... | Serialize data intended for a request header.
:param data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
:raises: TypeError if serialization fails.
:raises: ValueError if data is None | [
"Serialize",
"data",
"intended",
"for",
"a",
"request",
"header",
"."
] | python | train |
consbio/ncdjango | ncdjango/geoimage.py | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoimage.py#L121-L170 | def warp(self, target_bbox, target_size=None):
"""Returns a copy of this image warped to a target size and bounding box"""
# Determine target size based on pixels per unit of the source image and the target bounding box reprojected
# to the source projection.
if not target_size:
... | [
"def",
"warp",
"(",
"self",
",",
"target_bbox",
",",
"target_size",
"=",
"None",
")",
":",
"# Determine target size based on pixels per unit of the source image and the target bounding box reprojected",
"# to the source projection.",
"if",
"not",
"target_size",
":",
"px_per_unit"... | Returns a copy of this image warped to a target size and bounding box | [
"Returns",
"a",
"copy",
"of",
"this",
"image",
"warped",
"to",
"a",
"target",
"size",
"and",
"bounding",
"box"
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/util/config.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/config.py#L370-L379 | def _enable_profiling():
""" Start profiling and register callback to print stats when the program
exits.
"""
import cProfile
import atexit
global _profiler
_profiler = cProfile.Profile()
_profiler.enable()
atexit.register(_profile_atexit) | [
"def",
"_enable_profiling",
"(",
")",
":",
"import",
"cProfile",
"import",
"atexit",
"global",
"_profiler",
"_profiler",
"=",
"cProfile",
".",
"Profile",
"(",
")",
"_profiler",
".",
"enable",
"(",
")",
"atexit",
".",
"register",
"(",
"_profile_atexit",
")"
] | Start profiling and register callback to print stats when the program
exits. | [
"Start",
"profiling",
"and",
"register",
"callback",
"to",
"print",
"stats",
"when",
"the",
"program",
"exits",
"."
] | python | train |
numenta/htmresearch | projects/l2_pooling/single_column_sp.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/single_column_sp.py#L32-L42 | def createThreeObjects():
"""
Helper function that creates a set of three objects used for basic
experiments.
:return: (list(list(tuple)) List of lists of feature / location pairs.
"""
objectA = zip(range(10), range(10))
objectB = [(0, 0), (2, 2), (1, 1), (1, 4), (4, 2), (4, 1)]
objectC = [(0, 0), (... | [
"def",
"createThreeObjects",
"(",
")",
":",
"objectA",
"=",
"zip",
"(",
"range",
"(",
"10",
")",
",",
"range",
"(",
"10",
")",
")",
"objectB",
"=",
"[",
"(",
"0",
",",
"0",
")",
",",
"(",
"2",
",",
"2",
")",
",",
"(",
"1",
",",
"1",
")",
... | Helper function that creates a set of three objects used for basic
experiments.
:return: (list(list(tuple)) List of lists of feature / location pairs. | [
"Helper",
"function",
"that",
"creates",
"a",
"set",
"of",
"three",
"objects",
"used",
"for",
"basic",
"experiments",
"."
] | python | train |
vicalloy/lbutils | lbutils/widgets.py | https://github.com/vicalloy/lbutils/blob/66ae7e73bc939f073cdc1b91602a95e67caf4ba6/lbutils/widgets.py#L71-L75 | def render_hidden(name, value):
""" render as hidden widget """
if isinstance(value, list):
return MultipleHiddenInput().render(name, value)
return HiddenInput().render(name, value) | [
"def",
"render_hidden",
"(",
"name",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"MultipleHiddenInput",
"(",
")",
".",
"render",
"(",
"name",
",",
"value",
")",
"return",
"HiddenInput",
"(",
")",
".",
"ren... | render as hidden widget | [
"render",
"as",
"hidden",
"widget"
] | python | train |
Datary/scrapbag | scrapbag/csvs.py | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/csvs.py#L58-L85 | def populate_csv_headers(rows,
partial_headers,
column_headers_count=1):
"""
Populate csv rows headers when are empty, extending the superior or
upper headers.
"""
result = [''] * (len(rows) - column_headers_count)
for i_index in range(0, len(p... | [
"def",
"populate_csv_headers",
"(",
"rows",
",",
"partial_headers",
",",
"column_headers_count",
"=",
"1",
")",
":",
"result",
"=",
"[",
"''",
"]",
"*",
"(",
"len",
"(",
"rows",
")",
"-",
"column_headers_count",
")",
"for",
"i_index",
"in",
"range",
"(",
... | Populate csv rows headers when are empty, extending the superior or
upper headers. | [
"Populate",
"csv",
"rows",
"headers",
"when",
"are",
"empty",
"extending",
"the",
"superior",
"or",
"upper",
"headers",
"."
] | python | train |
psss/fmf | fmf/base.py | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L217-L276 | def grow(self, path):
"""
Grow the metadata tree for the given directory path
Note: For each path, grow() should be run only once. Growing the tree
from the same path multiple times with attribute adding using the "+"
sign leads to adding the value more than once!
"""
... | [
"def",
"grow",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"path",
"=",
"path",
".",
"rstrip",
"(",
"\"/\"",
")",
"log",
".",
"info",
"(",
"\"Walking through directory {0}\"",
".",
"format",
"(",
"os",
".",
"path",
... | Grow the metadata tree for the given directory path
Note: For each path, grow() should be run only once. Growing the tree
from the same path multiple times with attribute adding using the "+"
sign leads to adding the value more than once! | [
"Grow",
"the",
"metadata",
"tree",
"for",
"the",
"given",
"directory",
"path"
] | python | train |
DerwenAI/pytextrank | pytextrank/pytextrank.py | https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L678-L699 | def top_sentences (kernel, path):
"""
determine distance for each sentence
"""
key_sent = {}
i = 0
if isinstance(path, str):
path = json_iter(path)
for meta in path:
graf = meta["graf"]
tagged_sent = [WordNode._make(x) for x in graf]
text = " ".join([w.raw f... | [
"def",
"top_sentences",
"(",
"kernel",
",",
"path",
")",
":",
"key_sent",
"=",
"{",
"}",
"i",
"=",
"0",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"path",
"=",
"json_iter",
"(",
"path",
")",
"for",
"meta",
"in",
"path",
":",
"graf",
"... | determine distance for each sentence | [
"determine",
"distance",
"for",
"each",
"sentence"
] | python | valid |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L23483-L23564 | def merge_to(self, target):
"""Starts merging the contents of this medium and all intermediate
differencing media in the chain to the given target medium.
The target medium must be either a descendant of this medium or
its ancestor (otherwise this method will immediately return ... | [
"def",
"merge_to",
"(",
"self",
",",
"target",
")",
":",
"if",
"not",
"isinstance",
"(",
"target",
",",
"IMedium",
")",
":",
"raise",
"TypeError",
"(",
"\"target can only be an instance of type IMedium\"",
")",
"progress",
"=",
"self",
".",
"_call",
"(",
"\"me... | Starts merging the contents of this medium and all intermediate
differencing media in the chain to the given target medium.
The target medium must be either a descendant of this medium or
its ancestor (otherwise this method will immediately return a failure).
It follows that the... | [
"Starts",
"merging",
"the",
"contents",
"of",
"this",
"medium",
"and",
"all",
"intermediate",
"differencing",
"media",
"in",
"the",
"chain",
"to",
"the",
"given",
"target",
"medium",
".",
"The",
"target",
"medium",
"must",
"be",
"either",
"a",
"descendant",
... | python | train |
wavycloud/pyboto3 | pyboto3/opsworks.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/opsworks.py#L729-L937 | def create_layer(StackId=None, Type=None, Name=None, Shortname=None, Attributes=None, CloudWatchLogsConfiguration=None, CustomInstanceProfileArn=None, CustomJson=None, CustomSecurityGroupIds=None, Packages=None, VolumeConfigurations=None, EnableAutoHealing=None, AutoAssignElasticIps=None, AutoAssignPublicIps=None, Cust... | [
"def",
"create_layer",
"(",
"StackId",
"=",
"None",
",",
"Type",
"=",
"None",
",",
"Name",
"=",
"None",
",",
"Shortname",
"=",
"None",
",",
"Attributes",
"=",
"None",
",",
"CloudWatchLogsConfiguration",
"=",
"None",
",",
"CustomInstanceProfileArn",
"=",
"Non... | Creates a layer. For more information, see How to Create a Layer .
See also: AWS API Documentation
:example: response = client.create_layer(
StackId='string',
Type='aws-flow-ruby'|'ecs-cluster'|'java-app'|'lb'|'web'|'php-app'|'rails-app'|'nodejs-app'|'memcached'|'db-master'|'monitoring... | [
"Creates",
"a",
"layer",
".",
"For",
"more",
"information",
"see",
"How",
"to",
"Create",
"a",
"Layer",
".",
"See",
"also",
":",
"AWS",
"API",
"Documentation",
":",
"example",
":",
"response",
"=",
"client",
".",
"create_layer",
"(",
"StackId",
"=",
"str... | python | train |
google/pyringe | pyringe/payload/exec_socket.py | https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/payload/exec_socket.py#L24-L64 | def StartExecServer():
"""Opens a socket in /tmp, execs data from it and writes results back."""
sockdir = '/tmp/pyringe_%s' % os.getpid()
if not os.path.isdir(sockdir):
os.mkdir(sockdir)
socket_path = ('%s/%s.execsock' %
(sockdir, threading.current_thread().ident))
if os.path.exists(soc... | [
"def",
"StartExecServer",
"(",
")",
":",
"sockdir",
"=",
"'/tmp/pyringe_%s'",
"%",
"os",
".",
"getpid",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"sockdir",
")",
":",
"os",
".",
"mkdir",
"(",
"sockdir",
")",
"socket_path",
"=",
"("... | Opens a socket in /tmp, execs data from it and writes results back. | [
"Opens",
"a",
"socket",
"in",
"/",
"tmp",
"execs",
"data",
"from",
"it",
"and",
"writes",
"results",
"back",
"."
] | python | train |
wikimedia/ores | setup.py | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/setup.py#L20-L32 | def requirements(fname):
"""
Generator to parse requirements.txt file
Supports bits of extended pip format (git urls)
"""
with open(fname) as f:
for line in f:
match = re.search('#egg=(.*)$', line)
if match:
yield match.groups()[0]
else:
... | [
"def",
"requirements",
"(",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"match",
"=",
"re",
".",
"search",
"(",
"'#egg=(.*)$'",
",",
"line",
")",
"if",
"match",
":",
"yield",
"match",
".",
... | Generator to parse requirements.txt file
Supports bits of extended pip format (git urls) | [
"Generator",
"to",
"parse",
"requirements",
".",
"txt",
"file"
] | python | train |
mottosso/be | be/util.py | https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/util.py#L100-L115 | def dump(context=os.environ):
"""Dump current environment as a dictionary
Arguments:
context (dict, optional): Current context, defaults
to the current environment.
"""
output = {}
for key, value in context.iteritems():
if not key.startswith("BE_"):
continu... | [
"def",
"dump",
"(",
"context",
"=",
"os",
".",
"environ",
")",
":",
"output",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"context",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"key",
".",
"startswith",
"(",
"\"BE_\"",
")",
":",
"continue",
... | Dump current environment as a dictionary
Arguments:
context (dict, optional): Current context, defaults
to the current environment. | [
"Dump",
"current",
"environment",
"as",
"a",
"dictionary"
] | python | train |
guaix-ucm/numina | numina/dal/mockdal.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/dal/mockdal.py#L32-L34 | def search_prod_type_tags(self, ins, type, tags, pipeline):
'''Returns the first coincidence...'''
return StoredProduct(id=100, content='null.fits', tags={}) | [
"def",
"search_prod_type_tags",
"(",
"self",
",",
"ins",
",",
"type",
",",
"tags",
",",
"pipeline",
")",
":",
"return",
"StoredProduct",
"(",
"id",
"=",
"100",
",",
"content",
"=",
"'null.fits'",
",",
"tags",
"=",
"{",
"}",
")"
] | Returns the first coincidence... | [
"Returns",
"the",
"first",
"coincidence",
"..."
] | python | train |
note35/sinon | sinon/lib/spy.py | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/spy.py#L332-L344 | def threw(self, error_type=None):
"""
Determining whether the exception is thrown
Args:
error_type:
None: checking without specified exception
Specified Exception
Return: Boolean
"""
if not error_type:
return True if... | [
"def",
"threw",
"(",
"self",
",",
"error_type",
"=",
"None",
")",
":",
"if",
"not",
"error_type",
":",
"return",
"True",
"if",
"len",
"(",
"self",
".",
"exceptions",
")",
">",
"0",
"else",
"False",
"else",
":",
"return",
"uch",
".",
"obj_in_list",
"(... | Determining whether the exception is thrown
Args:
error_type:
None: checking without specified exception
Specified Exception
Return: Boolean | [
"Determining",
"whether",
"the",
"exception",
"is",
"thrown",
"Args",
":",
"error_type",
":",
"None",
":",
"checking",
"without",
"specified",
"exception",
"Specified",
"Exception",
"Return",
":",
"Boolean"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.