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 |
|---|---|---|---|---|---|---|---|---|
manns/pyspread | pyspread/src/interfaces/pys.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/interfaces/pys.py#L213-L233 | def _pys2attributes(self, line):
"""Updates attributes in code_array"""
splitline = self._split_tidy(line)
selection_data = map(ast.literal_eval, splitline[:5])
selection = Selection(*selection_data)
tab = int(splitline[5])
attrs = {}
for col, ele in enumerate... | [
"def",
"_pys2attributes",
"(",
"self",
",",
"line",
")",
":",
"splitline",
"=",
"self",
".",
"_split_tidy",
"(",
"line",
")",
"selection_data",
"=",
"map",
"(",
"ast",
".",
"literal_eval",
",",
"splitline",
"[",
":",
"5",
"]",
")",
"selection",
"=",
"S... | Updates attributes in code_array | [
"Updates",
"attributes",
"in",
"code_array"
] | python | train |
biosustain/optlang | optlang/interface.py | https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L149-L158 | def clone(cls, variable, **kwargs):
"""
Make a copy of another variable. The variable being copied can be of the same type or belong to
a different solver interface.
Example
----------
>>> var_copy = Variable.clone(old_var)
"""
return cls(variable.name, l... | [
"def",
"clone",
"(",
"cls",
",",
"variable",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"variable",
".",
"name",
",",
"lb",
"=",
"variable",
".",
"lb",
",",
"ub",
"=",
"variable",
".",
"ub",
",",
"type",
"=",
"variable",
".",
"type"... | Make a copy of another variable. The variable being copied can be of the same type or belong to
a different solver interface.
Example
----------
>>> var_copy = Variable.clone(old_var) | [
"Make",
"a",
"copy",
"of",
"another",
"variable",
".",
"The",
"variable",
"being",
"copied",
"can",
"be",
"of",
"the",
"same",
"type",
"or",
"belong",
"to",
"a",
"different",
"solver",
"interface",
"."
] | python | train |
bioasp/caspo | caspo/visualize.py | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L197-L242 | def behaviors_distribution(df, filepath=None):
"""
Plots the distribution of logical networks across input-output behaviors.
Optionally, input-output behaviors can be grouped by MSE.
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `networks` and optionally `mse`
... | [
"def",
"behaviors_distribution",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"cols",
"=",
"[",
"\"networks\"",
",",
"\"index\"",
"]",
"rcols",
"=",
"[",
"\"Logical networks\"",
",",
"\"Input-Output behaviors\"",
"]",
"sort_cols",
"=",
"[",
"\"networks\"",... | Plots the distribution of logical networks across input-output behaviors.
Optionally, input-output behaviors can be grouped by MSE.
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `networks` and optionally `mse`
filepath: str
Absolute path to a folder where to ... | [
"Plots",
"the",
"distribution",
"of",
"logical",
"networks",
"across",
"input",
"-",
"output",
"behaviors",
".",
"Optionally",
"input",
"-",
"output",
"behaviors",
"can",
"be",
"grouped",
"by",
"MSE",
"."
] | python | train |
boto/s3transfer | s3transfer/upload.py | https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/upload.py#L697-L724 | def _main(self, client, fileobj, bucket, key, upload_id, part_number,
extra_args):
"""
:param client: The client to use when calling PutObject
:param fileobj: The file to upload.
:param bucket: The name of the bucket to upload to
:param key: The name of the key to u... | [
"def",
"_main",
"(",
"self",
",",
"client",
",",
"fileobj",
",",
"bucket",
",",
"key",
",",
"upload_id",
",",
"part_number",
",",
"extra_args",
")",
":",
"with",
"fileobj",
"as",
"body",
":",
"response",
"=",
"client",
".",
"upload_part",
"(",
"Bucket",
... | :param client: The client to use when calling PutObject
:param fileobj: The file to upload.
:param bucket: The name of the bucket to upload to
:param key: The name of the key to upload to
:param upload_id: The id of the upload
:param part_number: The number representing the part ... | [
":",
"param",
"client",
":",
"The",
"client",
"to",
"use",
"when",
"calling",
"PutObject",
":",
"param",
"fileobj",
":",
"The",
"file",
"to",
"upload",
".",
":",
"param",
"bucket",
":",
"The",
"name",
"of",
"the",
"bucket",
"to",
"upload",
"to",
":",
... | python | test |
gpagliuca/pyfas | build/lib/pyfas/tab.py | https://github.com/gpagliuca/pyfas/blob/5daa1199bd124d315d02bef0ad3888a8f58355b2/build/lib/pyfas/tab.py#L32-L42 | def _tab_type(self):
"""
Private method to define the tab type
"""
with open(self.abspath) as fobj:
contents = fobj.readlines()
for line in contents:
if 'COMPONENTS' in line:
return 'keyword'
else:
... | [
"def",
"_tab_type",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"abspath",
")",
"as",
"fobj",
":",
"contents",
"=",
"fobj",
".",
"readlines",
"(",
")",
"for",
"line",
"in",
"contents",
":",
"if",
"'COMPONENTS'",
"in",
"line",
":",
"retur... | Private method to define the tab type | [
"Private",
"method",
"to",
"define",
"the",
"tab",
"type"
] | python | train |
cloudnull/cloudlib | cloudlib/shell.py | https://github.com/cloudnull/cloudlib/blob/5038111ce02521caa2558117e3bae9e1e806d315/cloudlib/shell.py#L167-L216 | def md5_checker(self, md5sum, local_file=None, file_object=None):
"""Return True if the local file and the provided `md5sum` are equal.
If the processed file and the provided md5sum do not match an exception
is raised indicating the failure.
:param md5sum: ``str``
:param local_... | [
"def",
"md5_checker",
"(",
"self",
",",
"md5sum",
",",
"local_file",
"=",
"None",
",",
"file_object",
"=",
"None",
")",
":",
"def",
"calc_hash",
"(",
")",
":",
"\"\"\"Read the hash.\n\n :return data_hash.read():\n \"\"\"",
"return",
"file_object",
... | Return True if the local file and the provided `md5sum` are equal.
If the processed file and the provided md5sum do not match an exception
is raised indicating the failure.
:param md5sum: ``str``
:param local_file: ``str``
:param file_object: ``BytesIO``
:return: ``bol`... | [
"Return",
"True",
"if",
"the",
"local",
"file",
"and",
"the",
"provided",
"md5sum",
"are",
"equal",
"."
] | python | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/hhea.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/hhea.py#L50-L95 | def com_google_fonts_check_monospace_max_advancewidth(ttFont, glyph_metrics_stats):
"""Monospace font has hhea.advanceWidthMax equal to each glyph's
advanceWidth?"""
from fontbakery.utils import pretty_print_list
seems_monospaced = glyph_metrics_stats["seems_monospaced"]
if not seems_monospaced:
yield SK... | [
"def",
"com_google_fonts_check_monospace_max_advancewidth",
"(",
"ttFont",
",",
"glyph_metrics_stats",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"pretty_print_list",
"seems_monospaced",
"=",
"glyph_metrics_stats",
"[",
"\"seems_monospaced\"",
"]",
"if",
"not",... | Monospace font has hhea.advanceWidthMax equal to each glyph's
advanceWidth? | [
"Monospace",
"font",
"has",
"hhea",
".",
"advanceWidthMax",
"equal",
"to",
"each",
"glyph",
"s",
"advanceWidth?"
] | python | train |
googleapis/oauth2client | oauth2client/contrib/dictionary_storage.py | https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/dictionary_storage.py#L53-L61 | def locked_put(self, credentials):
"""Save the credentials to the dictionary.
Args:
credentials: A :class:`oauth2client.client.OAuth2Credentials`
instance.
"""
serialized = credentials.to_json()
self._dictionary[self._key] = serialized | [
"def",
"locked_put",
"(",
"self",
",",
"credentials",
")",
":",
"serialized",
"=",
"credentials",
".",
"to_json",
"(",
")",
"self",
".",
"_dictionary",
"[",
"self",
".",
"_key",
"]",
"=",
"serialized"
] | Save the credentials to the dictionary.
Args:
credentials: A :class:`oauth2client.client.OAuth2Credentials`
instance. | [
"Save",
"the",
"credentials",
"to",
"the",
"dictionary",
"."
] | python | valid |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shcoeffsgrid.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L1020-L1127 | def rotate(self, alpha, beta, gamma, degrees=True, convention='y',
body=False, dj_matrix=None):
"""
Rotate either the coordinate system used to express the spherical
harmonic coefficients or the physical body, and return a new class
instance.
Usage
-----
... | [
"def",
"rotate",
"(",
"self",
",",
"alpha",
",",
"beta",
",",
"gamma",
",",
"degrees",
"=",
"True",
",",
"convention",
"=",
"'y'",
",",
"body",
"=",
"False",
",",
"dj_matrix",
"=",
"None",
")",
":",
"if",
"type",
"(",
"convention",
")",
"!=",
"str"... | Rotate either the coordinate system used to express the spherical
harmonic coefficients or the physical body, and return a new class
instance.
Usage
-----
x_rotated = x.rotate(alpha, beta, gamma, [degrees, convention,
body, dj_matrix])
Retur... | [
"Rotate",
"either",
"the",
"coordinate",
"system",
"used",
"to",
"express",
"the",
"spherical",
"harmonic",
"coefficients",
"or",
"the",
"physical",
"body",
"and",
"return",
"a",
"new",
"class",
"instance",
"."
] | python | train |
olitheolix/qtmacs | qtmacs/extensions/qtmacsscintilla_widget.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_widget.py#L654-L680 | def isSelectionPositionValid(self, selPos: tuple):
"""
Return **True** if the start- and end position denote valid
positions within the document.
|Args|
* ``selPos`` (**tuple**): tuple with four integers.
|Returns|
**bool**: **True** if the positions are valid... | [
"def",
"isSelectionPositionValid",
"(",
"self",
",",
"selPos",
":",
"tuple",
")",
":",
"if",
"selPos",
"is",
"None",
":",
"return",
"False",
"if",
"len",
"(",
"selPos",
")",
"!=",
"4",
":",
"return",
"False",
"check1",
"=",
"self",
".",
"isPositionValid"... | Return **True** if the start- and end position denote valid
positions within the document.
|Args|
* ``selPos`` (**tuple**): tuple with four integers.
|Returns|
**bool**: **True** if the positions are valid; **False** otherwise.
|Raises|
* **None** | [
"Return",
"**",
"True",
"**",
"if",
"the",
"start",
"-",
"and",
"end",
"position",
"denote",
"valid",
"positions",
"within",
"the",
"document",
"."
] | python | train |
noxdafox/clipspy | clips/agenda.py | https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L370-L375 | def delete(self):
"""Remove the activation from the agenda."""
if lib.EnvDeleteActivation(self._env, self._act) != 1:
raise CLIPSError(self._env)
self._env = None | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"lib",
".",
"EnvDeleteActivation",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_act",
")",
"!=",
"1",
":",
"raise",
"CLIPSError",
"(",
"self",
".",
"_env",
")",
"self",
".",
"_env",
"=",
"None"
] | Remove the activation from the agenda. | [
"Remove",
"the",
"activation",
"from",
"the",
"agenda",
"."
] | python | train |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/session.py | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/session.py#L111-L134 | def start_login_server(self, ):
"""Start a server that will get a request from a user logging in.
This uses the Implicit Grant Flow of OAuth2. The user is asked
to login to twitch and grant PyTwitcher authorization.
Once the user agrees, he is redirected to an url.
This server w... | [
"def",
"start_login_server",
"(",
"self",
",",
")",
":",
"self",
".",
"login_server",
"=",
"oauth",
".",
"LoginServer",
"(",
"session",
"=",
"self",
")",
"target",
"=",
"self",
".",
"login_server",
".",
"serve_forever",
"self",
".",
"login_thread",
"=",
"t... | Start a server that will get a request from a user logging in.
This uses the Implicit Grant Flow of OAuth2. The user is asked
to login to twitch and grant PyTwitcher authorization.
Once the user agrees, he is redirected to an url.
This server will respond to that url and get the oauth t... | [
"Start",
"a",
"server",
"that",
"will",
"get",
"a",
"request",
"from",
"a",
"user",
"logging",
"in",
"."
] | python | train |
Guake/guake | guake/prefs.py | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1028-L1035 | def _load_hooks_settings(self):
"""load hooks settings"""
log.debug("executing _load_hooks_settings")
hook_show_widget = self.get_widget("hook_show")
hook_show_setting = self.settings.hooks.get_string("show")
if hook_show_widget is not None:
if hook_show_setting is no... | [
"def",
"_load_hooks_settings",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"executing _load_hooks_settings\"",
")",
"hook_show_widget",
"=",
"self",
".",
"get_widget",
"(",
"\"hook_show\"",
")",
"hook_show_setting",
"=",
"self",
".",
"settings",
".",
"hooks... | load hooks settings | [
"load",
"hooks",
"settings"
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/snmp_server/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/snmp_server/__init__.py#L219-L240 | def _set_v3host(self, v, load=False):
"""
Setter method for v3host, mapped from YANG variable /snmp_server/v3host (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_v3host is considered as a private
method. Backends looking to populate this variable should
do... | [
"def",
"_set_v3host",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for v3host, mapped from YANG variable /snmp_server/v3host (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_v3host is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_v3host() directly. | [
"Setter",
"method",
"for",
"v3host",
"mapped",
"from",
"YANG",
"variable",
"/",
"snmp_server",
"/",
"v3host",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
... | python | train |
project-rig/rig | rig/routing_table/minimise.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/minimise.py#L135-L139 | def _identity(table, target_length):
"""Identity minimisation function."""
if target_length is None or len(table) < target_length:
return table
raise MinimisationFailedError(target_length, len(table)) | [
"def",
"_identity",
"(",
"table",
",",
"target_length",
")",
":",
"if",
"target_length",
"is",
"None",
"or",
"len",
"(",
"table",
")",
"<",
"target_length",
":",
"return",
"table",
"raise",
"MinimisationFailedError",
"(",
"target_length",
",",
"len",
"(",
"t... | Identity minimisation function. | [
"Identity",
"minimisation",
"function",
"."
] | python | train |
kubernetes-client/python | kubernetes/client/apis/admissionregistration_v1beta1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/admissionregistration_v1beta1_api.py#L375-L401 | def delete_collection_validating_webhook_configuration(self, **kwargs):
"""
delete collection of ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collec... | [
"def",
"delete_collection_validating_webhook_configuration",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"delete_col... | delete collection of ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_validating_webhook_configuration(async_req=True)
>>> result = thread.get()
... | [
"delete",
"collection",
"of",
"ValidatingWebhookConfiguration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"threa... | python | train |
bcbio/bcbio-nextgen | bcbio/structural/pindel.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/pindel.py#L97-L109 | def _create_tmp_input(input_bams, names, tmp_path, config):
"""Create input file for pindel. tab file: bam file, insert size, name
:param input_bams: (list) bam files
:param names: (list) names of samples
:param tmp_path: (str) temporal dir
:param config: (dict) information from yaml file(itmes[0]['... | [
"def",
"_create_tmp_input",
"(",
"input_bams",
",",
"names",
",",
"tmp_path",
",",
"config",
")",
":",
"tmp_input",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_path",
",",
"\"pindel.txt\"",
")",
"with",
"open",
"(",
"tmp_input",
",",
"'w'",
")",
"as",... | Create input file for pindel. tab file: bam file, insert size, name
:param input_bams: (list) bam files
:param names: (list) names of samples
:param tmp_path: (str) temporal dir
:param config: (dict) information from yaml file(itmes[0]['config'])
:returns: (str) input file for pindel | [
"Create",
"input",
"file",
"for",
"pindel",
".",
"tab",
"file",
":",
"bam",
"file",
"insert",
"size",
"name",
":",
"param",
"input_bams",
":",
"(",
"list",
")",
"bam",
"files",
":",
"param",
"names",
":",
"(",
"list",
")",
"names",
"of",
"samples",
"... | python | train |
tyiannak/pyAudioAnalysis | pyAudioAnalysis/audioSegmentation.py | https://github.com/tyiannak/pyAudioAnalysis/blob/e3da991e7247492deba50648a4c7c0f41e684af4/pyAudioAnalysis/audioSegmentation.py#L278-L330 | def trainHMM_computeStatistics(features, labels):
'''
This function computes the statistics used to train an HMM joint segmentation-classification model
using a sequence of sequential features and respective labels
ARGUMENTS:
- features: a numpy matrix of feature vectors (numOfDimensions x n_wi... | [
"def",
"trainHMM_computeStatistics",
"(",
"features",
",",
"labels",
")",
":",
"u_labels",
"=",
"numpy",
".",
"unique",
"(",
"labels",
")",
"n_comps",
"=",
"len",
"(",
"u_labels",
")",
"n_feats",
"=",
"features",
".",
"shape",
"[",
"0",
"]",
"if",
"featu... | This function computes the statistics used to train an HMM joint segmentation-classification model
using a sequence of sequential features and respective labels
ARGUMENTS:
- features: a numpy matrix of feature vectors (numOfDimensions x n_wins)
- labels: a numpy array of class indices (n_wins x... | [
"This",
"function",
"computes",
"the",
"statistics",
"used",
"to",
"train",
"an",
"HMM",
"joint",
"segmentation",
"-",
"classification",
"model",
"using",
"a",
"sequence",
"of",
"sequential",
"features",
"and",
"respective",
"labels"
] | python | train |
saltstack/salt | salt/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L207-L214 | def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req | [
"def",
"trim_req",
"(",
"req",
")",
":",
"reqfirst",
"=",
"next",
"(",
"iter",
"(",
"req",
")",
")",
"if",
"'.'",
"in",
"reqfirst",
":",
"return",
"{",
"reqfirst",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
":",
"req",
"[",
"reqfirst",
"]",
... | Trim any function off of a requisite | [
"Trim",
"any",
"function",
"off",
"of",
"a",
"requisite"
] | python | train |
evhub/coconut | coconut/constants.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/constants.py#L33-L35 | def fixpath(path):
"""Uniformly format a path."""
return os.path.normpath(os.path.realpath(os.path.expanduser(path))) | [
"def",
"fixpath",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
")",
")"
] | Uniformly format a path. | [
"Uniformly",
"format",
"a",
"path",
"."
] | python | train |
boronine/discipline | discipline/models.py | https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L262-L332 | def __get_is_revertible(self):
"""Return a boolean representing whether this Action is revertible
or not"""
# If it was already reverted
if self.reverted:
return False
errors = []
inst = self.timemachine
if inst.fields != inst.presently.fiel... | [
"def",
"__get_is_revertible",
"(",
"self",
")",
":",
"# If it was already reverted",
"if",
"self",
".",
"reverted",
":",
"return",
"False",
"errors",
"=",
"[",
"]",
"inst",
"=",
"self",
".",
"timemachine",
"if",
"inst",
".",
"fields",
"!=",
"inst",
".",
"p... | Return a boolean representing whether this Action is revertible
or not | [
"Return",
"a",
"boolean",
"representing",
"whether",
"this",
"Action",
"is",
"revertible",
"or",
"not"
] | python | train |
pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/ef09f28b858b7ffcd2627ce6a4dc618183a6bc8a/ffn/core.py#L557-L582 | def plot_histogram(self, freq=None, figsize=(15, 5), title=None,
bins=20, **kwargs):
"""
Plots a histogram of returns given a return frequency.
Args:
* freq (str): Data frequency used for display purposes.
This will dictate the type of returns
... | [
"def",
"plot_histogram",
"(",
"self",
",",
"freq",
"=",
"None",
",",
"figsize",
"=",
"(",
"15",
",",
"5",
")",
",",
"title",
"=",
"None",
",",
"bins",
"=",
"20",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"title",
"is",
"None",
":",
"title",
"=",... | Plots a histogram of returns given a return frequency.
Args:
* freq (str): Data frequency used for display purposes.
This will dictate the type of returns
(daily returns, monthly, ...)
Refer to pandas docs for valid period strings.
* figsi... | [
"Plots",
"a",
"histogram",
"of",
"returns",
"given",
"a",
"return",
"frequency",
"."
] | python | train |
ttinies/sc2common | sc2common/containers.py | https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/containers.py#L86-L93 | def gameValue(self):
"""identify the correpsonding internal SC2 game value for self.type's value"""
allowed = type(self).ALLOWED_TYPES
try:
if isinstance(allowed, dict): # if ALLOWED_TYPES is not a dict, there is no-internal game value mapping defined
return allowed.g... | [
"def",
"gameValue",
"(",
"self",
")",
":",
"allowed",
"=",
"type",
"(",
"self",
")",
".",
"ALLOWED_TYPES",
"try",
":",
"if",
"isinstance",
"(",
"allowed",
",",
"dict",
")",
":",
"# if ALLOWED_TYPES is not a dict, there is no-internal game value mapping defined",
"re... | identify the correpsonding internal SC2 game value for self.type's value | [
"identify",
"the",
"correpsonding",
"internal",
"SC2",
"game",
"value",
"for",
"self",
".",
"type",
"s",
"value"
] | python | train |
xiyouMc/ncmbot | ncmbot/core.py | https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L361-L374 | def user_record(uid, type=0):
"""获取用户的播放列表,必须登录
:param uid: 用户的ID,可通过登录或者其他接口获取
:param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData
"""
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_RECORD'
r.data = {'type': type, 'uid': uid, "csrf_token": ""}
r.send()... | [
"def",
"user_record",
"(",
"uid",
",",
"type",
"=",
"0",
")",
":",
"if",
"uid",
"is",
"None",
":",
"raise",
"ParamsError",
"(",
")",
"r",
"=",
"NCloudBot",
"(",
")",
"r",
".",
"method",
"=",
"'USER_RECORD'",
"r",
".",
"data",
"=",
"{",
"'type'",
... | 获取用户的播放列表,必须登录
:param uid: 用户的ID,可通过登录或者其他接口获取
:param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData | [
"获取用户的播放列表",
"必须登录"
] | python | train |
vlukes/dicom2fem | dicom2fem/mesh.py | https://github.com/vlukes/dicom2fem/blob/3056c977ca7119e01984d3aa0c4448a1c6c2430f/dicom2fem/mesh.py#L153-L185 | def get_min_vertex_distance( coor, guess ):
"""Can miss the minimum, but is enough for our purposes."""
# Sort by x.
ix = nm.argsort( coor[:,0] )
scoor = coor[ix]
mvd = 1e16
# Get mvd in chunks potentially smaller than guess.
n_coor = coor.shape[0]
print n_coor
i0 = i1 = 0... | [
"def",
"get_min_vertex_distance",
"(",
"coor",
",",
"guess",
")",
":",
"# Sort by x.",
"ix",
"=",
"nm",
".",
"argsort",
"(",
"coor",
"[",
":",
",",
"0",
"]",
")",
"scoor",
"=",
"coor",
"[",
"ix",
"]",
"mvd",
"=",
"1e16",
"# Get mvd in chunks potentially ... | Can miss the minimum, but is enough for our purposes. | [
"Can",
"miss",
"the",
"minimum",
"but",
"is",
"enough",
"for",
"our",
"purposes",
"."
] | python | train |
ArchiveTeam/wpull | wpull/processor/rule.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/rule.py#L280-L293 | def handle_no_document(self, item_session: ItemSession) -> Actions:
'''Callback for successful responses containing no useful document.
Returns:
A value from :class:`.hook.Actions`.
'''
self._waiter.reset()
action = self.handle_response(item_session)
if act... | [
"def",
"handle_no_document",
"(",
"self",
",",
"item_session",
":",
"ItemSession",
")",
"->",
"Actions",
":",
"self",
".",
"_waiter",
".",
"reset",
"(",
")",
"action",
"=",
"self",
".",
"handle_response",
"(",
"item_session",
")",
"if",
"action",
"==",
"Ac... | Callback for successful responses containing no useful document.
Returns:
A value from :class:`.hook.Actions`. | [
"Callback",
"for",
"successful",
"responses",
"containing",
"no",
"useful",
"document",
"."
] | python | train |
thomasdelaet/python-velbus | velbus/parser.py | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/parser.py#L95-L102 | def extract_packet(self):
"""
Extract packet from buffer
"""
packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
(self.buffer[3] & 0x0F)
packet = self.buffer[0:packet_size]
return packet | [
"def",
"extract_packet",
"(",
"self",
")",
":",
"packet_size",
"=",
"velbus",
".",
"MINIMUM_MESSAGE_SIZE",
"+",
"(",
"self",
".",
"buffer",
"[",
"3",
"]",
"&",
"0x0F",
")",
"packet",
"=",
"self",
".",
"buffer",
"[",
"0",
":",
"packet_size",
"]",
"retur... | Extract packet from buffer | [
"Extract",
"packet",
"from",
"buffer"
] | python | train |
tchellomello/raincloudy | raincloudy/faucet.py | https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L347-L386 | def preupdate(self, force_refresh=True):
"""Return a dict with all current options prior submitting request."""
ddata = MANUAL_OP_DATA.copy()
# force update to make sure status is accurate
if force_refresh:
self.update()
# select current controller and faucet
... | [
"def",
"preupdate",
"(",
"self",
",",
"force_refresh",
"=",
"True",
")",
":",
"ddata",
"=",
"MANUAL_OP_DATA",
".",
"copy",
"(",
")",
"# force update to make sure status is accurate",
"if",
"force_refresh",
":",
"self",
".",
"update",
"(",
")",
"# select current co... | Return a dict with all current options prior submitting request. | [
"Return",
"a",
"dict",
"with",
"all",
"current",
"options",
"prior",
"submitting",
"request",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/mystats.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/mystats.py#L6-L13 | def up_threshold(x, s, p):
"""function to decide if similarity is
below cutoff"""
if 1.0 * x/s >= p:
return True
elif stat.binom_test(x, s, p) > 0.01:
return True
return False | [
"def",
"up_threshold",
"(",
"x",
",",
"s",
",",
"p",
")",
":",
"if",
"1.0",
"*",
"x",
"/",
"s",
">=",
"p",
":",
"return",
"True",
"elif",
"stat",
".",
"binom_test",
"(",
"x",
",",
"s",
",",
"p",
")",
">",
"0.01",
":",
"return",
"True",
"retur... | function to decide if similarity is
below cutoff | [
"function",
"to",
"decide",
"if",
"similarity",
"is",
"below",
"cutoff"
] | python | train |
kislyuk/argcomplete | argcomplete/shellintegration.py | https://github.com/kislyuk/argcomplete/blob/f9eb0a2354d9e6153f687c463df98c16251d97ed/argcomplete/shellintegration.py#L46-L71 | def shellcode(executables, use_defaults=True, shell='bash', complete_arguments=None):
'''
Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_default... | [
"def",
"shellcode",
"(",
"executables",
",",
"use_defaults",
"=",
"True",
",",
"shell",
"=",
"'bash'",
",",
"complete_arguments",
"=",
"None",
")",
":",
"if",
"complete_arguments",
"is",
"None",
":",
"complete_options",
"=",
"'-o nospace -o default'",
"if",
"use... | Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.
:param ... | [
"Provide",
"the",
"shell",
"code",
"required",
"to",
"register",
"a",
"python",
"executable",
"for",
"use",
"with",
"the",
"argcomplete",
"module",
"."
] | python | train |
wummel/linkchecker | linkcheck/htmlutil/formsearch.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/htmlutil/formsearch.py#L61-L78 | def start_element(self, tag, attrs):
"""Does nothing, override in a subclass."""
if tag == u'form':
if u'action' in attrs:
url = attrs['action']
self.form = Form(url)
elif tag == u'input':
if self.form:
if 'name' in attrs:
... | [
"def",
"start_element",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"if",
"tag",
"==",
"u'form'",
":",
"if",
"u'action'",
"in",
"attrs",
":",
"url",
"=",
"attrs",
"[",
"'action'",
"]",
"self",
".",
"form",
"=",
"Form",
"(",
"url",
")",
"elif",... | Does nothing, override in a subclass. | [
"Does",
"nothing",
"override",
"in",
"a",
"subclass",
"."
] | python | train |
CalebBell/fluids | fluids/fittings.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/fittings.py#L2394-L2576 | def diffuser_conical(Di1, Di2, l=None, angle=None, fd=None, Re=None,
roughness=0.0, method='Rennels'):
r'''Returns the loss coefficient for any conical pipe diffuser.
This calculation has four methods available.
The 'Rennels' [1]_ formulas are as follows (three different formulas a... | [
"def",
"diffuser_conical",
"(",
"Di1",
",",
"Di2",
",",
"l",
"=",
"None",
",",
"angle",
"=",
"None",
",",
"fd",
"=",
"None",
",",
"Re",
"=",
"None",
",",
"roughness",
"=",
"0.0",
",",
"method",
"=",
"'Rennels'",
")",
":",
"beta",
"=",
"Di1",
"/",... | r'''Returns the loss coefficient for any conical pipe diffuser.
This calculation has four methods available.
The 'Rennels' [1]_ formulas are as follows (three different formulas are
used, depending on the angle and the ratio of diameters):
For 0 to 20 degrees, all aspect ratios:
.. math::
... | [
"r",
"Returns",
"the",
"loss",
"coefficient",
"for",
"any",
"conical",
"pipe",
"diffuser",
".",
"This",
"calculation",
"has",
"four",
"methods",
"available",
".",
"The",
"Rennels",
"[",
"1",
"]",
"_",
"formulas",
"are",
"as",
"follows",
"(",
"three",
"diff... | python | train |
fermiPy/fermipy | fermipy/gtutils.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtutils.py#L208-L248 | def create_spectrum_from_dict(spectrum_type, spectral_pars, fn=None):
"""Create a Function object from a parameter dictionary.
Parameters
----------
spectrum_type : str
String identifying the spectrum type (e.g. PowerLaw).
spectral_pars : dict
Dictionary of spectral parameters.
... | [
"def",
"create_spectrum_from_dict",
"(",
"spectrum_type",
",",
"spectral_pars",
",",
"fn",
"=",
"None",
")",
":",
"if",
"fn",
"is",
"None",
":",
"fn",
"=",
"pyLike",
".",
"SourceFactory_funcFactory",
"(",
")",
".",
"create",
"(",
"str",
"(",
"spectrum_type",... | Create a Function object from a parameter dictionary.
Parameters
----------
spectrum_type : str
String identifying the spectrum type (e.g. PowerLaw).
spectral_pars : dict
Dictionary of spectral parameters. | [
"Create",
"a",
"Function",
"object",
"from",
"a",
"parameter",
"dictionary",
"."
] | python | train |
numenta/nupic | src/nupic/swarming/hypersearch/permutation_helpers.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/permutation_helpers.py#L238-L277 | def pushAwayFrom(self, otherPositions, rng):
"""See comments in base class."""
# If min and max are the same, nothing to do
if self.max == self.min:
return
# How many potential other positions to evaluate?
numPositions = len(otherPositions) * 4
if numPositions == 0:
return
# As... | [
"def",
"pushAwayFrom",
"(",
"self",
",",
"otherPositions",
",",
"rng",
")",
":",
"# If min and max are the same, nothing to do",
"if",
"self",
".",
"max",
"==",
"self",
".",
"min",
":",
"return",
"# How many potential other positions to evaluate?",
"numPositions",
"=",
... | See comments in base class. | [
"See",
"comments",
"in",
"base",
"class",
"."
] | python | valid |
PSU-OIT-ARC/django-local-settings | local_settings/strategy.py | https://github.com/PSU-OIT-ARC/django-local-settings/blob/758810fbd9411c2046a187afcac6532155cac694/local_settings/strategy.py#L122-L152 | def read_file(self, file_name, section=None):
"""Read settings from specified ``section`` of config file."""
file_name, section = self.parse_file_name_and_section(file_name, section)
if not os.path.isfile(file_name):
raise SettingsFileNotFoundError(file_name)
parser = self.ma... | [
"def",
"read_file",
"(",
"self",
",",
"file_name",
",",
"section",
"=",
"None",
")",
":",
"file_name",
",",
"section",
"=",
"self",
".",
"parse_file_name_and_section",
"(",
"file_name",
",",
"section",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
... | Read settings from specified ``section`` of config file. | [
"Read",
"settings",
"from",
"specified",
"section",
"of",
"config",
"file",
"."
] | python | train |
cjdrake/pyeda | pyeda/boolalg/bdd.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L524-L535 | def _iter_all_paths(start, end, rand=False, path=tuple()):
"""Iterate through all paths from start to end."""
path = path + (start, )
if start is end:
yield path
else:
nodes = [start.lo, start.hi]
if rand: # pragma: no cover
random.shuffle(nodes)
for node in n... | [
"def",
"_iter_all_paths",
"(",
"start",
",",
"end",
",",
"rand",
"=",
"False",
",",
"path",
"=",
"tuple",
"(",
")",
")",
":",
"path",
"=",
"path",
"+",
"(",
"start",
",",
")",
"if",
"start",
"is",
"end",
":",
"yield",
"path",
"else",
":",
"nodes"... | Iterate through all paths from start to end. | [
"Iterate",
"through",
"all",
"paths",
"from",
"start",
"to",
"end",
"."
] | python | train |
dnephin/PyStaticConfiguration | staticconf/validation.py | https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/validation.py#L123-L129 | def build_list_type_validator(item_validator):
"""Return a function which validates that the value is a list of items
which are validated using item_validator.
"""
def validate_list_of_type(value):
return [item_validator(item) for item in validate_list(value)]
return validate_list_of_type | [
"def",
"build_list_type_validator",
"(",
"item_validator",
")",
":",
"def",
"validate_list_of_type",
"(",
"value",
")",
":",
"return",
"[",
"item_validator",
"(",
"item",
")",
"for",
"item",
"in",
"validate_list",
"(",
"value",
")",
"]",
"return",
"validate_list... | Return a function which validates that the value is a list of items
which are validated using item_validator. | [
"Return",
"a",
"function",
"which",
"validates",
"that",
"the",
"value",
"is",
"a",
"list",
"of",
"items",
"which",
"are",
"validated",
"using",
"item_validator",
"."
] | python | train |
Komnomnomnom/swigibpy | swigibpy.py | https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1462-L1464 | def placeOrder(self, id, contract, order):
"""placeOrder(EClientSocketBase self, OrderId id, Contract contract, Order order)"""
return _swigibpy.EClientSocketBase_placeOrder(self, id, contract, order) | [
"def",
"placeOrder",
"(",
"self",
",",
"id",
",",
"contract",
",",
"order",
")",
":",
"return",
"_swigibpy",
".",
"EClientSocketBase_placeOrder",
"(",
"self",
",",
"id",
",",
"contract",
",",
"order",
")"
] | placeOrder(EClientSocketBase self, OrderId id, Contract contract, Order order) | [
"placeOrder",
"(",
"EClientSocketBase",
"self",
"OrderId",
"id",
"Contract",
"contract",
"Order",
"order",
")"
] | python | train |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2419-L2425 | def detachAcceptMsOriginating():
"""DETACH ACCEPT Section 9.4.6.2"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x6) # 00000110
c = ForceToStandbyAndSpareHalfOctets()
packet = a / b / c
return packet | [
"def",
"detachAcceptMsOriginating",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x6",
")",
"# 00000110",
"c",
"=",
"ForceToStandbyAndSpareHalfOctets",
"(",
")",
"packet",
"=",
"a",
"/",
"b",... | DETACH ACCEPT Section 9.4.6.2 | [
"DETACH",
"ACCEPT",
"Section",
"9",
".",
"4",
".",
"6",
".",
"2"
] | python | train |
dpgaspar/Flask-AppBuilder | flask_appbuilder/views.py | https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/views.py#L627-L641 | def action_post(self):
"""
Action method to handle multiple records selected from a list view
"""
name = request.form["action"]
pks = request.form.getlist("rowid")
if self.appbuilder.sm.has_access(name, self.__class__.__name__):
action = self.actions.get(n... | [
"def",
"action_post",
"(",
"self",
")",
":",
"name",
"=",
"request",
".",
"form",
"[",
"\"action\"",
"]",
"pks",
"=",
"request",
".",
"form",
".",
"getlist",
"(",
"\"rowid\"",
")",
"if",
"self",
".",
"appbuilder",
".",
"sm",
".",
"has_access",
"(",
"... | Action method to handle multiple records selected from a list view | [
"Action",
"method",
"to",
"handle",
"multiple",
"records",
"selected",
"from",
"a",
"list",
"view"
] | python | train |
guma44/GEOparse | GEOparse/GEOparse.py | https://github.com/guma44/GEOparse/blob/7ee8d5b8678d780382a6bf884afa69d2033f5ca0/GEOparse/GEOparse.py#L342-L392 | def parse_GSM(filepath, entry_name=None):
"""Parse GSM entry from SOFT file.
Args:
filepath (:obj:`str` or :obj:`Iterable`): Path to file with 1 GSM entry
or list of lines representing GSM from GSE file.
entry_name (:obj:`str`, optional): Name of the entry. By default it is
... | [
"def",
"parse_GSM",
"(",
"filepath",
",",
"entry_name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"filepath",
",",
"str",
")",
":",
"with",
"utils",
".",
"smart_open",
"(",
"filepath",
")",
"as",
"f",
":",
"soft",
"=",
"[",
"]",
"has_table",
"=... | Parse GSM entry from SOFT file.
Args:
filepath (:obj:`str` or :obj:`Iterable`): Path to file with 1 GSM entry
or list of lines representing GSM from GSE file.
entry_name (:obj:`str`, optional): Name of the entry. By default it is
inferred from the data.
Returns:
... | [
"Parse",
"GSM",
"entry",
"from",
"SOFT",
"file",
"."
] | python | train |
OnroerendErfgoed/crabpy_pyramid | crabpy_pyramid/utils.py | https://github.com/OnroerendErfgoed/crabpy_pyramid/blob/b727ea55838d71575db96e987b536a0bac9f6a7a/crabpy_pyramid/utils.py#L39-L69 | def range_return(request, items):
"""
Determine what range of objects to return.
Will check fot both `Range` and `X-Range` headers in the request and
set both `Content-Range` and 'X-Content-Range' headers.
:rtype: list
"""
if ('Range' in request.headers):
range = parse_range_header... | [
"def",
"range_return",
"(",
"request",
",",
"items",
")",
":",
"if",
"(",
"'Range'",
"in",
"request",
".",
"headers",
")",
":",
"range",
"=",
"parse_range_header",
"(",
"request",
".",
"headers",
"[",
"'Range'",
"]",
")",
"elif",
"'X-Range'",
"in",
"requ... | Determine what range of objects to return.
Will check fot both `Range` and `X-Range` headers in the request and
set both `Content-Range` and 'X-Content-Range' headers.
:rtype: list | [
"Determine",
"what",
"range",
"of",
"objects",
"to",
"return",
"."
] | python | train |
patrickayoup/md2remark | md2remark/main.py | https://github.com/patrickayoup/md2remark/blob/04e66462046cd123c5b1810454d949c3a05bc057/md2remark/main.py#L8-L26 | def compile_markdown_file(source_file):
'''Compiles a single markdown file to a remark.js slideshow.'''
template = pkg_resources.resource_string('md2remark.resources.templates', 'slideshow.mustache')
renderer = pystache.Renderer(search_dirs='./templates')
f = open(source_file, 'r')
slideshow_md = f.read()
... | [
"def",
"compile_markdown_file",
"(",
"source_file",
")",
":",
"template",
"=",
"pkg_resources",
".",
"resource_string",
"(",
"'md2remark.resources.templates'",
",",
"'slideshow.mustache'",
")",
"renderer",
"=",
"pystache",
".",
"Renderer",
"(",
"search_dirs",
"=",
"'.... | Compiles a single markdown file to a remark.js slideshow. | [
"Compiles",
"a",
"single",
"markdown",
"file",
"to",
"a",
"remark",
".",
"js",
"slideshow",
"."
] | python | train |
atztogo/phonopy | phonopy/api_phonopy.py | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L709-L746 | def get_frequencies_with_eigenvectors(self, q):
"""Calculate phonon frequencies and eigenvectors at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,)
Returns
-------
(frequencies, eigenvectors)
frequencie... | [
"def",
"get_frequencies_with_eigenvectors",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"_set_dynamical_matrix",
"(",
")",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"Runti... | Calculate phonon frequencies and eigenvectors at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,)
Returns
-------
(frequencies, eigenvectors)
frequencies: ndarray
Phonon frequencies
shape... | [
"Calculate",
"phonon",
"frequencies",
"and",
"eigenvectors",
"at",
"a",
"given",
"q",
"-",
"point"
] | python | train |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L1076-L1099 | def _ip_int_from_string(self, ip_str):
"""Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address.
... | [
"def",
"_ip_int_from_string",
"(",
"self",
",",
"ip_str",
")",
":",
"octets",
"=",
"ip_str",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"octets",
")",
"!=",
"4",
":",
"raise",
"AddressValueError",
"(",
"ip_str",
")",
"packed_ip",
"=",
"0",
"for",... | Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address. | [
"Turn",
"the",
"given",
"IP",
"string",
"into",
"an",
"integer",
"for",
"comparison",
"."
] | python | train |
stevearc/dql | dql/output.py | https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L147-L171 | def format_field(self, field):
""" Format a single Dynamo value """
if field is None:
return "NULL"
elif isinstance(field, TypeError):
return "TypeError"
elif isinstance(field, Decimal):
if field % 1 == 0:
return str(int(field))
... | [
"def",
"format_field",
"(",
"self",
",",
"field",
")",
":",
"if",
"field",
"is",
"None",
":",
"return",
"\"NULL\"",
"elif",
"isinstance",
"(",
"field",
",",
"TypeError",
")",
":",
"return",
"\"TypeError\"",
"elif",
"isinstance",
"(",
"field",
",",
"Decimal... | Format a single Dynamo value | [
"Format",
"a",
"single",
"Dynamo",
"value"
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/scoped_variable_list.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/scoped_variable_list.py#L137-L148 | def on_add(self, widget, data=None):
"""Create a new scoped variable with default values"""
if isinstance(self.model, ContainerStateModel):
try:
scoped_var_ids = gui_helper_state_machine.add_scoped_variable_to_selected_states(selected_states=[self.model])
if s... | [
"def",
"on_add",
"(",
"self",
",",
"widget",
",",
"data",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
",",
"ContainerStateModel",
")",
":",
"try",
":",
"scoped_var_ids",
"=",
"gui_helper_state_machine",
".",
"add_scoped_variable_to_se... | Create a new scoped variable with default values | [
"Create",
"a",
"new",
"scoped",
"variable",
"with",
"default",
"values"
] | python | train |
ktdreyer/txkoji | txkoji/cache.py | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/cache.py#L63-L72 | def filename(self, type_, id_):
"""
cache filename to read for this type/id.
:param type_: str, "user" or "tag"
:param id_: int, eg. 123456
:returns: str
"""
profile = self.connection.profile
return os.path.join(self.directory, profile, type_, str(id_)) | [
"def",
"filename",
"(",
"self",
",",
"type_",
",",
"id_",
")",
":",
"profile",
"=",
"self",
".",
"connection",
".",
"profile",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"profile",
",",
"type_",
",",
"str",
"(",
"... | cache filename to read for this type/id.
:param type_: str, "user" or "tag"
:param id_: int, eg. 123456
:returns: str | [
"cache",
"filename",
"to",
"read",
"for",
"this",
"type",
"/",
"id",
"."
] | python | train |
saltstack/salt | salt/modules/keystone.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L1192-L1247 | def user_role_add(user_id=None, user=None, tenant_id=None,
tenant=None, role_id=None, role=None, profile=None,
project_id=None, project_name=None, **connection_args):
'''
Add role for user in tenant (keystone user-role-add)
CLI Examples:
.. code-block:: bash
... | [
"def",
"user_role_add",
"(",
"user_id",
"=",
"None",
",",
"user",
"=",
"None",
",",
"tenant_id",
"=",
"None",
",",
"tenant",
"=",
"None",
",",
"role_id",
"=",
"None",
",",
"role",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"project_id",
"=",
"Non... | Add role for user in tenant (keystone user-role-add)
CLI Examples:
.. code-block:: bash
salt '*' keystone.user_role_add \
user_id=298ce377245c4ec9b70e1c639c89e654 \
tenant_id=7167a092ece84bae8cead4bf9d15bb3b \
role_id=ce377245c4ec9b70e1c639c89e8cead4
salt '*' keystone.user_role_add user=admin... | [
"Add",
"role",
"for",
"user",
"in",
"tenant",
"(",
"keystone",
"user",
"-",
"role",
"-",
"add",
")"
] | python | train |
alpacahq/pylivetrader | pylivetrader/assets/finder.py | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/assets/finder.py#L57-L95 | def retrieve_all(self, sids, default_none=False):
"""
Retrieve all assets in `sids`.
Parameters
----------
sids : iterable of string
Assets to retrieve.
default_none : bool
If True, return None for failed lookups.
If False, raise `Sids... | [
"def",
"retrieve_all",
"(",
"self",
",",
"sids",
",",
"default_none",
"=",
"False",
")",
":",
"failures",
"=",
"set",
"(",
")",
"hits",
"=",
"{",
"}",
"for",
"sid",
"in",
"sids",
":",
"try",
":",
"hits",
"[",
"sid",
"]",
"=",
"self",
".",
"_asset... | Retrieve all assets in `sids`.
Parameters
----------
sids : iterable of string
Assets to retrieve.
default_none : bool
If True, return None for failed lookups.
If False, raise `SidsNotFound`.
Returns
-------
assets : list[Asse... | [
"Retrieve",
"all",
"assets",
"in",
"sids",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/Util/util.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Util/util.py#L369-L410 | def neighborSelect(a, x, y):
"""
finds (local) minima in a 2d grid
:param a: 1d array of displacements from the source positions
:type a: numpy array with length numPix**2 in float
:returns: array of indices of local minima, values of those minima
:raises: AttributeError, KeyError
"""
... | [
"def",
"neighborSelect",
"(",
"a",
",",
"x",
",",
"y",
")",
":",
"dim",
"=",
"int",
"(",
"np",
".",
"sqrt",
"(",
"len",
"(",
"a",
")",
")",
")",
"values",
"=",
"[",
"]",
"x_mins",
"=",
"[",
"]",
"y_mins",
"=",
"[",
"]",
"for",
"i",
"in",
... | finds (local) minima in a 2d grid
:param a: 1d array of displacements from the source positions
:type a: numpy array with length numPix**2 in float
:returns: array of indices of local minima, values of those minima
:raises: AttributeError, KeyError | [
"finds",
"(",
"local",
")",
"minima",
"in",
"a",
"2d",
"grid"
] | python | train |
jbittel/django-mama-cas | mama_cas/cas.py | https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/cas.py#L82-L91 | def get_attributes(user, service):
"""
Return a dictionary of user attributes from the set of configured
callback functions.
"""
attributes = {}
for path in get_callbacks(service):
callback = import_string(path)
attributes.update(callback(user, service))
return attributes | [
"def",
"get_attributes",
"(",
"user",
",",
"service",
")",
":",
"attributes",
"=",
"{",
"}",
"for",
"path",
"in",
"get_callbacks",
"(",
"service",
")",
":",
"callback",
"=",
"import_string",
"(",
"path",
")",
"attributes",
".",
"update",
"(",
"callback",
... | Return a dictionary of user attributes from the set of configured
callback functions. | [
"Return",
"a",
"dictionary",
"of",
"user",
"attributes",
"from",
"the",
"set",
"of",
"configured",
"callback",
"functions",
"."
] | python | train |
tkf/python-epc | epc/handler.py | https://github.com/tkf/python-epc/blob/f3673ae5c35f20a0f71546ab34c28e3dde3595c1/epc/handler.py#L397-L413 | def call_sync(self, name, args, timeout=None):
"""
Blocking version of :meth:`call`.
:type name: str
:arg name: Remote function name to call.
:type args: list
:arg args: Arguments passed to the remote function.
:type timeout: int or None
:ar... | [
"def",
"call_sync",
"(",
"self",
",",
"name",
",",
"args",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_blocking_request",
"(",
"self",
".",
"call",
",",
"timeout",
",",
"name",
",",
"args",
")"
] | Blocking version of :meth:`call`.
:type name: str
:arg name: Remote function name to call.
:type args: list
:arg args: Arguments passed to the remote function.
:type timeout: int or None
:arg timeout: Timeout in second. None means no timeout.
If ... | [
"Blocking",
"version",
"of",
":",
"meth",
":",
"call",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py#L36-L46 | def BGPSessionState_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
BGPSessionState = ET.SubElement(config, "BGPSessionState", xmlns="http://brocade.com/ns/brocade-notification-stream")
originator_switch_info = ET... | [
"def",
"BGPSessionState_originator_switch_info_switchIpV4Address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"BGPSessionState",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"BGPSessionState\... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3813-L3831 | def chdir(self, target_directory):
"""Change current working directory to target directory.
Args:
target_directory: The path to new current working directory.
Raises:
OSError: if user lacks permission to enter the argument directory
or if the target is n... | [
"def",
"chdir",
"(",
"self",
",",
"target_directory",
")",
":",
"target_directory",
"=",
"self",
".",
"filesystem",
".",
"resolve_path",
"(",
"target_directory",
",",
"allow_fd",
"=",
"True",
")",
"self",
".",
"filesystem",
".",
"confirmdir",
"(",
"target_dire... | Change current working directory to target directory.
Args:
target_directory: The path to new current working directory.
Raises:
OSError: if user lacks permission to enter the argument directory
or if the target is not a directory. | [
"Change",
"current",
"working",
"directory",
"to",
"target",
"directory",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1824-L1832 | def setShowGrid( self, state ):
"""
Sets whether or not this delegate should draw its grid lines.
:param state | <bool>
"""
delegate = self.itemDelegate()
if ( isinstance(delegate, XTreeWidgetDelegate) ):
delegate.setShowGrid(state) | [
"def",
"setShowGrid",
"(",
"self",
",",
"state",
")",
":",
"delegate",
"=",
"self",
".",
"itemDelegate",
"(",
")",
"if",
"(",
"isinstance",
"(",
"delegate",
",",
"XTreeWidgetDelegate",
")",
")",
":",
"delegate",
".",
"setShowGrid",
"(",
"state",
")"
] | Sets whether or not this delegate should draw its grid lines.
:param state | <bool> | [
"Sets",
"whether",
"or",
"not",
"this",
"delegate",
"should",
"draw",
"its",
"grid",
"lines",
".",
":",
"param",
"state",
"|",
"<bool",
">"
] | python | train |
tgbugs/pyontutils | ttlser/ttlser/serializers.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ttlser/ttlser/serializers.py#L818-L823 | def serialize(self, *args, **kwargs):
""" Modified to allow additional labels to be passed in. """
if 'labels' in kwargs:
# populate labels from outside the local graph
self._labels.update(kwargs['labels'])
super(HtmlTurtleSerializer, self).serialize(*args, **kwargs) | [
"def",
"serialize",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'labels'",
"in",
"kwargs",
":",
"# populate labels from outside the local graph",
"self",
".",
"_labels",
".",
"update",
"(",
"kwargs",
"[",
"'labels'",
"]",
")",
... | Modified to allow additional labels to be passed in. | [
"Modified",
"to",
"allow",
"additional",
"labels",
"to",
"be",
"passed",
"in",
"."
] | python | train |
dereneaton/ipyrad | ipyrad/analysis/tetrad.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L1063-L1174 | def _inference(self, start, lbview, quiet=False):
"""
Inference sends slices of jobs to the parallel engines for computing
and collects the results into the output hdf5 array as they finish.
"""
## an iterator to distribute sampled quartets in chunks
gen = xrange(self.... | [
"def",
"_inference",
"(",
"self",
",",
"start",
",",
"lbview",
",",
"quiet",
"=",
"False",
")",
":",
"## an iterator to distribute sampled quartets in chunks",
"gen",
"=",
"xrange",
"(",
"self",
".",
"checkpoint",
".",
"arr",
",",
"self",
".",
"params",
".",
... | Inference sends slices of jobs to the parallel engines for computing
and collects the results into the output hdf5 array as they finish. | [
"Inference",
"sends",
"slices",
"of",
"jobs",
"to",
"the",
"parallel",
"engines",
"for",
"computing",
"and",
"collects",
"the",
"results",
"into",
"the",
"output",
"hdf5",
"array",
"as",
"they",
"finish",
"."
] | python | valid |
bcbio/bcbio-nextgen | bcbio/variation/vcfutils.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfutils.py#L513-L528 | def sort_by_ref(vcf_file, data):
"""Sort a VCF file by genome reference and position, adding contig information.
"""
out_file = "%s-prep.vcf.gz" % utils.splitext_plus(vcf_file)[0]
if not utils.file_uptodate(out_file, vcf_file):
with file_transaction(data, out_file) as tx_out_file:
he... | [
"def",
"sort_by_ref",
"(",
"vcf_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-prep.vcf.gz\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"vcf_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"vcf_file",
")",... | Sort a VCF file by genome reference and position, adding contig information. | [
"Sort",
"a",
"VCF",
"file",
"by",
"genome",
"reference",
"and",
"position",
"adding",
"contig",
"information",
"."
] | python | train |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L176-L198 | def __generate_method(name):
"""
Wraps the DataFrame's original method by name to return the derived class instance.
"""
try:
func = getattr(DataFrame, name)
except AttributeError as e:
# PySpark version is too old
def func(self, *args, **kwarg... | [
"def",
"__generate_method",
"(",
"name",
")",
":",
"try",
":",
"func",
"=",
"getattr",
"(",
"DataFrame",
",",
"name",
")",
"except",
"AttributeError",
"as",
"e",
":",
"# PySpark version is too old",
"def",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
... | Wraps the DataFrame's original method by name to return the derived class instance. | [
"Wraps",
"the",
"DataFrame",
"s",
"original",
"method",
"by",
"name",
"to",
"return",
"the",
"derived",
"class",
"instance",
"."
] | python | train |
mitsei/dlkit | dlkit/handcar/learning/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/objects.py#L754-L773 | def set_assessments(self, assessment_ids=None):
"""Sets the assessments.
arg: assessmentIds (osid.id.Id): the assessment Ids
raise: INVALID_ARGUMENT - assessmentIds is invalid
raise: NullArgument - assessmentIds is null
raise: NoAccess - metadata.is_read_only() is true
... | [
"def",
"set_assessments",
"(",
"self",
",",
"assessment_ids",
"=",
"None",
")",
":",
"if",
"assessment_ids",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"metadata",
"=",
"Metadata",
"(",
"*",
"*",
"settings",
".",
"METADATA",
"[",
"'assessment_ids'... | Sets the assessments.
arg: assessmentIds (osid.id.Id): the assessment Ids
raise: INVALID_ARGUMENT - assessmentIds is invalid
raise: NullArgument - assessmentIds is null
raise: NoAccess - metadata.is_read_only() is true
compliance: mandatory - This method must be implemente... | [
"Sets",
"the",
"assessments",
"."
] | python | train |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/widgets/reftrackwidget.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/reftrackwidget.py#L164-L181 | def set_maintext(self, index):
"""Set the maintext_lb to display text information about the given reftrack
:param index: the index
:type index: :class:`QtGui.QModelIndex`
:returns: None
:rtype: None
:raises: None
"""
dr = QtCore.Qt.DisplayRole
tex... | [
"def",
"set_maintext",
"(",
"self",
",",
"index",
")",
":",
"dr",
"=",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"text",
"=",
"\"\"",
"model",
"=",
"index",
".",
"model",
"(",
")",
"for",
"i",
"in",
"(",
"1",
",",
"2",
",",
"3",
",",
"5",
",",
... | Set the maintext_lb to display text information about the given reftrack
:param index: the index
:type index: :class:`QtGui.QModelIndex`
:returns: None
:rtype: None
:raises: None | [
"Set",
"the",
"maintext_lb",
"to",
"display",
"text",
"information",
"about",
"the",
"given",
"reftrack"
] | python | train |
onnx/onnxmltools | onnxutils/onnxconverter_common/shape_calculator.py | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/shape_calculator.py#L17-L60 | def calculate_linear_classifier_output_shapes(operator):
'''
This operator maps an input feature vector into a scalar label if the number of outputs is one. If two outputs
appear in this operator's output list, we should further generate a map storing all classes' probabilities.
Allowed input/output pa... | [
"def",
"calculate_linear_classifier_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"1",
",",
"output_count_range",
"=",
"[",
"1",
",",
"2",
"]",
")",
"check_input_and_output_types",
"(",
"op... | This operator maps an input feature vector into a scalar label if the number of outputs is one. If two outputs
appear in this operator's output list, we should further generate a map storing all classes' probabilities.
Allowed input/output patterns are
1. [N, C] ---> [N, 1], A sequence of map
Note... | [
"This",
"operator",
"maps",
"an",
"input",
"feature",
"vector",
"into",
"a",
"scalar",
"label",
"if",
"the",
"number",
"of",
"outputs",
"is",
"one",
".",
"If",
"two",
"outputs",
"appear",
"in",
"this",
"operator",
"s",
"output",
"list",
"we",
"should",
"... | python | train |
StagPython/StagPy | stagpy/stagyydata.py | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L626-L637 | def binfiles_set(self, isnap):
"""Set of existing binary files at a given snap.
Args:
isnap (int): snapshot index.
Returns:
set of pathlib.Path: the set of output files available for this
snapshot number.
"""
possible_files = set(self.filename... | [
"def",
"binfiles_set",
"(",
"self",
",",
"isnap",
")",
":",
"possible_files",
"=",
"set",
"(",
"self",
".",
"filename",
"(",
"fstem",
",",
"isnap",
",",
"force_legacy",
"=",
"True",
")",
"for",
"fstem",
"in",
"phyvars",
".",
"FIELD_FILES",
")",
"return",... | Set of existing binary files at a given snap.
Args:
isnap (int): snapshot index.
Returns:
set of pathlib.Path: the set of output files available for this
snapshot number. | [
"Set",
"of",
"existing",
"binary",
"files",
"at",
"a",
"given",
"snap",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py#L4191-L4204 | def get_stp_mst_detail_output_cist_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
... | [
"def",
"get_stp_mst_detail_output_cist_port_designated_port_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_mst_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_stp_mst_detail\"",
")",
"conf... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
geographika/mappyfile | mappyfile/pprint.py | https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L247-L264 | def format_repeated_pair_list(self, key, root_list, level):
"""
Process (possibly) repeated lists of pairs e.g. POINTs blocks
"""
lines = []
def depth(L):
return isinstance(L, (tuple, list)) and max(map(depth, L)) + 1
if depth(root_list) == 2:
#... | [
"def",
"format_repeated_pair_list",
"(",
"self",
",",
"key",
",",
"root_list",
",",
"level",
")",
":",
"lines",
"=",
"[",
"]",
"def",
"depth",
"(",
"L",
")",
":",
"return",
"isinstance",
"(",
"L",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"m... | Process (possibly) repeated lists of pairs e.g. POINTs blocks | [
"Process",
"(",
"possibly",
")",
"repeated",
"lists",
"of",
"pairs",
"e",
".",
"g",
".",
"POINTs",
"blocks"
] | python | train |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L7371-L7449 | def clip_upper(self, threshold, axis=None, inplace=False):
"""
Trim values above a given threshold.
.. deprecated:: 0.24.0
Use clip(upper=threshold) instead.
Elements above the `threshold` will be changed to match the
`threshold` value(s). Threshold can be a single ... | [
"def",
"clip_upper",
"(",
"self",
",",
"threshold",
",",
"axis",
"=",
"None",
",",
"inplace",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"'clip_upper(threshold) is deprecated, '",
"'use clip(upper=threshold) instead'",
",",
"FutureWarning",
",",
"stacklev... | Trim values above a given threshold.
.. deprecated:: 0.24.0
Use clip(upper=threshold) instead.
Elements above the `threshold` will be changed to match the
`threshold` value(s). Threshold can be a single value or an array,
in the latter case it performs the truncation elemen... | [
"Trim",
"values",
"above",
"a",
"given",
"threshold",
"."
] | python | train |
tcalmant/python-javaobj | javaobj/core.py | https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1140-L1157 | def _convert_char_to_type(self, type_char):
"""
Ensures a read character is a typecode.
:param type_char: Read typecode
:return: The typecode as a string (using chr)
:raise RuntimeError: Unknown typecode
"""
typecode = type_char
if type(type_char) is int:... | [
"def",
"_convert_char_to_type",
"(",
"self",
",",
"type_char",
")",
":",
"typecode",
"=",
"type_char",
"if",
"type",
"(",
"type_char",
")",
"is",
"int",
":",
"typecode",
"=",
"chr",
"(",
"type_char",
")",
"if",
"typecode",
"in",
"self",
".",
"TYPECODES_LIS... | Ensures a read character is a typecode.
:param type_char: Read typecode
:return: The typecode as a string (using chr)
:raise RuntimeError: Unknown typecode | [
"Ensures",
"a",
"read",
"character",
"is",
"a",
"typecode",
"."
] | python | train |
jupyter/jupyter-drive | jupyterdrive/mixednbmanager.py | https://github.com/jupyter/jupyter-drive/blob/545813377cb901235e8ea81f83b0ac7755dbd7a9/jupyterdrive/mixednbmanager.py#L186-L208 | def path_dispatch_rename(rename_like_method):
"""
decorator for rename-like function, that need dispatch on 2 arguments
"""
def _wrapper_method(self, old_path, new_path):
old_path, _old_path, old_sentinel = _split_path(old_path);
new_path, _new_path, new_sentine... | [
"def",
"path_dispatch_rename",
"(",
"rename_like_method",
")",
":",
"def",
"_wrapper_method",
"(",
"self",
",",
"old_path",
",",
"new_path",
")",
":",
"old_path",
",",
"_old_path",
",",
"old_sentinel",
"=",
"_split_path",
"(",
"old_path",
")",
"new_path",
",",
... | decorator for rename-like function, that need dispatch on 2 arguments | [
"decorator",
"for",
"rename",
"-",
"like",
"function",
"that",
"need",
"dispatch",
"on",
"2",
"arguments"
] | python | train |
henrysher/kotocore | kotocore/utils/import_utils.py | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/utils/import_utils.py#L6-L38 | def import_class(import_path):
"""
Imports a class dynamically from a full import path.
"""
if not '.' in import_path:
raise IncorrectImportPath(
"Invalid Python-style import path provided: {0}.".format(
import_path
)
)
path_bits = import_path... | [
"def",
"import_class",
"(",
"import_path",
")",
":",
"if",
"not",
"'.'",
"in",
"import_path",
":",
"raise",
"IncorrectImportPath",
"(",
"\"Invalid Python-style import path provided: {0}.\"",
".",
"format",
"(",
"import_path",
")",
")",
"path_bits",
"=",
"import_path",... | Imports a class dynamically from a full import path. | [
"Imports",
"a",
"class",
"dynamically",
"from",
"a",
"full",
"import",
"path",
"."
] | python | train |
annoviko/pyclustering | pyclustering/cluster/hsyncnet.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/hsyncnet.py#L168-L182 | def __calculate_radius(self, number_neighbors, radius):
"""!
@brief Calculate new connectivity radius.
@param[in] number_neighbors (uint): Average amount of neighbors that should be connected by new radius.
@param[in] radius (double): Current connectivity radius.
... | [
"def",
"__calculate_radius",
"(",
"self",
",",
"number_neighbors",
",",
"radius",
")",
":",
"if",
"(",
"number_neighbors",
">=",
"len",
"(",
"self",
".",
"_osc_loc",
")",
")",
":",
"return",
"radius",
"*",
"self",
".",
"__increase_persent",
"+",
"radius",
... | !
@brief Calculate new connectivity radius.
@param[in] number_neighbors (uint): Average amount of neighbors that should be connected by new radius.
@param[in] radius (double): Current connectivity radius.
@return New connectivity radius. | [
"!"
] | python | valid |
bspaans/python-mingus | mingus/core/chords.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L494-L503 | def dominant_flat_five(note):
"""Build a dominant flat five chord on note.
Example:
>>> dominant_flat_five('C')
['C', 'E', 'Gb', 'Bb']
"""
res = dominant_seventh(note)
res[2] = notes.diminish(res[2])
return res | [
"def",
"dominant_flat_five",
"(",
"note",
")",
":",
"res",
"=",
"dominant_seventh",
"(",
"note",
")",
"res",
"[",
"2",
"]",
"=",
"notes",
".",
"diminish",
"(",
"res",
"[",
"2",
"]",
")",
"return",
"res"
] | Build a dominant flat five chord on note.
Example:
>>> dominant_flat_five('C')
['C', 'E', 'Gb', 'Bb'] | [
"Build",
"a",
"dominant",
"flat",
"five",
"chord",
"on",
"note",
"."
] | python | train |
jsvine/spectra | spectra/grapefruit.py | https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1313-L1337 | def NewFromXyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF):
'''Create a new instance based on the specifed CIE-XYZ values.
Parameters:
:x:
The Red component value [0...1]
:y:
The Green component value [0...1]
:z:
The Blue component value [0...1]
:alpha:
The c... | [
"def",
"NewFromXyz",
"(",
"x",
",",
"y",
",",
"z",
",",
"alpha",
"=",
"1.0",
",",
"wref",
"=",
"_DEFAULT_WREF",
")",
":",
"return",
"Color",
"(",
"Color",
".",
"XyzToRgb",
"(",
"x",
",",
"y",
",",
"z",
")",
",",
"'rgb'",
",",
"alpha",
",",
"wre... | Create a new instance based on the specifed CIE-XYZ values.
Parameters:
:x:
The Red component value [0...1]
:y:
The Green component value [0...1]
:z:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
... | [
"Create",
"a",
"new",
"instance",
"based",
"on",
"the",
"specifed",
"CIE",
"-",
"XYZ",
"values",
"."
] | python | train |
pyokagan/pyglreg | glreg.py | https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L794-L814 | def import_type(dest, src, name, api=None, filter_symbol=None):
"""Import Type `name` and its dependencies from Registry `src`
to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of type to import
:param str api: Prefer to im... | [
"def",
"import_type",
"(",
"dest",
",",
"src",
",",
"name",
",",
"api",
"=",
"None",
",",
"filter_symbol",
"=",
"None",
")",
":",
"if",
"not",
"filter_symbol",
":",
"filter_symbol",
"=",
"_default_filter_symbol",
"type",
"=",
"src",
".",
"get_type",
"(",
... | Import Type `name` and its dependencies from Registry `src`
to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of type to import
:param str api: Prefer to import Types with api Name `api`, or None to
import T... | [
"Import",
"Type",
"name",
"and",
"its",
"dependencies",
"from",
"Registry",
"src",
"to",
"Registry",
"dest",
"."
] | python | train |
DataDog/integrations-core | datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py#L664-L696 | def _submit_gauges_from_histogram(
self, name, metric, send_histograms_buckets=True, custom_tags=None, hostname=None
):
"""
Extracts metrics from a prometheus histogram and sends them as gauges
"""
if custom_tags is None:
custom_tags = []
# histograms do n... | [
"def",
"_submit_gauges_from_histogram",
"(",
"self",
",",
"name",
",",
"metric",
",",
"send_histograms_buckets",
"=",
"True",
",",
"custom_tags",
"=",
"None",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"custom_tags",
"is",
"None",
":",
"custom_tags",
"=",
... | Extracts metrics from a prometheus histogram and sends them as gauges | [
"Extracts",
"metrics",
"from",
"a",
"prometheus",
"histogram",
"and",
"sends",
"them",
"as",
"gauges"
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/hardware/profile/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/hardware/profile/__init__.py#L135-L156 | def _set_route_table(self, v, load=False):
"""
Setter method for route_table, mapped from YANG variable /hardware/profile/route_table (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_route_table is considered as a private
method. Backends looking to popula... | [
"def",
"_set_route_table",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"ba... | Setter method for route_table, mapped from YANG variable /hardware/profile/route_table (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_route_table is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._... | [
"Setter",
"method",
"for",
"route_table",
"mapped",
"from",
"YANG",
"variable",
"/",
"hardware",
"/",
"profile",
"/",
"route_table",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
... | python | train |
rbccps-iisc/ideam-python-sdk | ideam/entity.py | https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L221-L234 | def subscribe(self, devices_to_bind=[]):
""" This function allows an entity to subscribe for data from the devices specified in the bind operation. It
creates a thread with an event loop to manager the tasks created in start_subscribe_worker.
Args:
devices_to_bind (list): an array o... | [
"def",
"subscribe",
"(",
"self",
",",
"devices_to_bind",
"=",
"[",
"]",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"self",
".",
... | This function allows an entity to subscribe for data from the devices specified in the bind operation. It
creates a thread with an event loop to manager the tasks created in start_subscribe_worker.
Args:
devices_to_bind (list): an array of devices to listen to | [
"This",
"function",
"allows",
"an",
"entity",
"to",
"subscribe",
"for",
"data",
"from",
"the",
"devices",
"specified",
"in",
"the",
"bind",
"operation",
".",
"It",
"creates",
"a",
"thread",
"with",
"an",
"event",
"loop",
"to",
"manager",
"the",
"tasks",
"c... | python | train |
telminov/sw-django-utils | djutils/views/helpers.py | https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/views/helpers.py#L53-L100 | def prepare_sort_params(params, request, sort_key='sort', revers_sort=None, except_params=None):
"""
Prepare sort params. Add revers '-' if need.
Params:
params - list of sort parameters
request
sort_key
revers_sort - list or set with keys that need re... | [
"def",
"prepare_sort_params",
"(",
"params",
",",
"request",
",",
"sort_key",
"=",
"'sort'",
",",
"revers_sort",
"=",
"None",
",",
"except_params",
"=",
"None",
")",
":",
"current_param",
",",
"current_reversed",
"=",
"sort_key_process",
"(",
"request",
",",
"... | Prepare sort params. Add revers '-' if need.
Params:
params - list of sort parameters
request
sort_key
revers_sort - list or set with keys that need reverse default sort direction
except_params - GET-params that will be ignored
Example:
... | [
"Prepare",
"sort",
"params",
".",
"Add",
"revers",
"-",
"if",
"need",
".",
"Params",
":",
"params",
"-",
"list",
"of",
"sort",
"parameters",
"request",
"sort_key",
"revers_sort",
"-",
"list",
"or",
"set",
"with",
"keys",
"that",
"need",
"reverse",
"default... | python | train |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L4481-L4562 | def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs):
'''
Return the optimal 'custom' CPU baseline config for VM's on this minion
.. versionadded:: 2016.3.0
:param full: Return all CPU features rather than the ones on top of the closest CPU model
:param migratable: Exclude CPU f... | [
"def",
"cpu_baseline",
"(",
"full",
"=",
"False",
",",
"migratable",
"=",
"False",
",",
"out",
"=",
"'libvirt'",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__get_conn",
"(",
"*",
"*",
"kwargs",
")",
"caps",
"=",
"ElementTree",
".",
"fromstring",
... | Return the optimal 'custom' CPU baseline config for VM's on this minion
.. versionadded:: 2016.3.0
:param full: Return all CPU features rather than the ones on top of the closest CPU model
:param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+)
:param out: 'libvirt' (default) for... | [
"Return",
"the",
"optimal",
"custom",
"CPU",
"baseline",
"config",
"for",
"VM",
"s",
"on",
"this",
"minion"
] | python | train |
dmwm/DBS | Server/Python/src/dbs/web/DBSReaderModel.py | https://github.com/dmwm/DBS/blob/9619bafce3783b3e77f0415f8f9a258e33dd1e6f/Server/Python/src/dbs/web/DBSReaderModel.py#L251-L274 | def listPrimaryDsTypes(self, primary_ds_type="", dataset=""):
"""
API to list primary dataset types
:param primary_ds_type: List that primary dataset type (Optional)
:type primary_ds_type: str
:param dataset: List the primary dataset type for that dataset (Optional)
:typ... | [
"def",
"listPrimaryDsTypes",
"(",
"self",
",",
"primary_ds_type",
"=",
"\"\"",
",",
"dataset",
"=",
"\"\"",
")",
":",
"if",
"primary_ds_type",
":",
"primary_ds_type",
"=",
"primary_ds_type",
".",
"replace",
"(",
"\"*\"",
",",
"\"%\"",
")",
"if",
"dataset",
"... | API to list primary dataset types
:param primary_ds_type: List that primary dataset type (Optional)
:type primary_ds_type: str
:param dataset: List the primary dataset type for that dataset (Optional)
:type dataset: str
:returns: List of dictionaries containing the following key... | [
"API",
"to",
"list",
"primary",
"dataset",
"types"
] | python | train |
saltstack/salt | salt/modules/ipmi.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipmi.py#L280-L329 | def get_channel_access(channel=14, read_mode='non_volatile', **kwargs):
'''
:param kwargs:api_host='127.0.0.1' api_user='admin' api_pass='example' api_port=623
:param channel: number [1:7]
:param read_mode:
- non_volatile = get non-volatile Channel Access
- volatile = get present... | [
"def",
"get_channel_access",
"(",
"channel",
"=",
"14",
",",
"read_mode",
"=",
"'non_volatile'",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"_IpmiCommand",
"(",
"*",
"*",
"kwargs",
")",
"as",
"s",
":",
"return",
"s",
".",
"get_channel_access",
"(",
"chan... | :param kwargs:api_host='127.0.0.1' api_user='admin' api_pass='example' api_port=623
:param channel: number [1:7]
:param read_mode:
- non_volatile = get non-volatile Channel Access
- volatile = get present volatile (active) setting of Channel Access
:param kwargs:
- api_host=... | [
":",
"param",
"kwargs",
":",
"api_host",
"=",
"127",
".",
"0",
".",
"0",
".",
"1",
"api_user",
"=",
"admin",
"api_pass",
"=",
"example",
"api_port",
"=",
"623"
] | python | train |
aws/sagemaker-containers | src/sagemaker_containers/_transformer.py | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_transformer.py#L159-L177 | def transform(self): # type: () -> _worker.Response
"""Take a request with input data, deserialize it, make a prediction, and return a
serialized response.
Returns:
sagemaker_containers.beta.framework.worker.Response: a Flask response object with
the following args:... | [
"def",
"transform",
"(",
"self",
")",
":",
"# type: () -> _worker.Response",
"request",
"=",
"_worker",
".",
"Request",
"(",
")",
"result",
"=",
"self",
".",
"_transform_fn",
"(",
"self",
".",
"_model",
",",
"request",
".",
"content",
",",
"request",
".",
... | Take a request with input data, deserialize it, make a prediction, and return a
serialized response.
Returns:
sagemaker_containers.beta.framework.worker.Response: a Flask response object with
the following args:
* response: the serialized data to return
... | [
"Take",
"a",
"request",
"with",
"input",
"data",
"deserialize",
"it",
"make",
"a",
"prediction",
"and",
"return",
"a",
"serialized",
"response",
"."
] | python | train |
radjkarl/imgProcessor | imgProcessor/camera/flatField/postProcessing.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/flatField/postProcessing.py#L16-L74 | def postProcessing(arr, method='KW replace + Gauss', mask=None):
'''
Post process measured flat field [arr].
Depending on the measurement, different
post processing [method]s are beneficial.
The available methods are presented in
---
K.Bedrich, M.Bokalic et al.:
... | [
"def",
"postProcessing",
"(",
"arr",
",",
"method",
"=",
"'KW replace + Gauss'",
",",
"mask",
"=",
"None",
")",
":",
"assert",
"method",
"in",
"ppMETHODS",
",",
"'post processing method (%s) must be one of %s'",
"%",
"(",
"method",
",",
"ppMETHODS",
")",
"if",
"... | Post process measured flat field [arr].
Depending on the measurement, different
post processing [method]s are beneficial.
The available methods are presented in
---
K.Bedrich, M.Bokalic et al.:
ELECTROLUMINESCENCE IMAGING OF PV DEVICES:
ADVANCED FLAT FIELD CALI... | [
"Post",
"process",
"measured",
"flat",
"field",
"[",
"arr",
"]",
".",
"Depending",
"on",
"the",
"measurement",
"different",
"post",
"processing",
"[",
"method",
"]",
"s",
"are",
"beneficial",
".",
"The",
"available",
"methods",
"are",
"presented",
"in",
"---... | python | train |
danielfrg/datasciencebox | datasciencebox/salt/_modules/conda.py | https://github.com/danielfrg/datasciencebox/blob/6b7aa642c6616a46547035fcb815acc1de605a6f/datasciencebox/salt/_modules/conda.py#L15-L27 | def conda_prefix(user=None):
"""
Get the conda prefix for a particular user (~/anaconda)
If user is None it defaults to /opt/anaconda
"""
if user == 'root':
return __salt__['grains.get']('conda:prefix', default='/opt/anaconda')
else:
if user is None:
user = __salt__['... | [
"def",
"conda_prefix",
"(",
"user",
"=",
"None",
")",
":",
"if",
"user",
"==",
"'root'",
":",
"return",
"__salt__",
"[",
"'grains.get'",
"]",
"(",
"'conda:prefix'",
",",
"default",
"=",
"'/opt/anaconda'",
")",
"else",
":",
"if",
"user",
"is",
"None",
":"... | Get the conda prefix for a particular user (~/anaconda)
If user is None it defaults to /opt/anaconda | [
"Get",
"the",
"conda",
"prefix",
"for",
"a",
"particular",
"user",
"(",
"~",
"/",
"anaconda",
")",
"If",
"user",
"is",
"None",
"it",
"defaults",
"to",
"/",
"opt",
"/",
"anaconda"
] | python | train |
IdentityPython/oidcendpoint | src/oidcendpoint/session.py | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L92-L106 | def dict_match(a, b):
"""
Check if all attribute/value pairs in a also appears in b
:param a: A dictionary
:param b: A dictionary
:return: True/False
"""
res = []
for k, v in a.items():
try:
res.append(b[k] == v)
except KeyError:
pass
return a... | [
"def",
"dict_match",
"(",
"a",
",",
"b",
")",
":",
"res",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"a",
".",
"items",
"(",
")",
":",
"try",
":",
"res",
".",
"append",
"(",
"b",
"[",
"k",
"]",
"==",
"v",
")",
"except",
"KeyError",
":",
"... | Check if all attribute/value pairs in a also appears in b
:param a: A dictionary
:param b: A dictionary
:return: True/False | [
"Check",
"if",
"all",
"attribute",
"/",
"value",
"pairs",
"in",
"a",
"also",
"appears",
"in",
"b"
] | python | train |
Crypto-toolbox/bitex | bitex/api/WSS/bitfinex.py | https://github.com/Crypto-toolbox/bitex/blob/56d46ea3db6de5219a72dad9b052fbabc921232f/bitex/api/WSS/bitfinex.py#L468-L482 | def _raise_error(self, *args, **kwargs):
"""
Raises the proper exception for passed error code. These must then be
handled by the layer calling _raise_error()
"""
log.debug("_raise_error(): %s" % kwargs)
try:
error_code = str(kwargs['code'])
except Key... | [
"def",
"_raise_error",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"\"_raise_error(): %s\"",
"%",
"kwargs",
")",
"try",
":",
"error_code",
"=",
"str",
"(",
"kwargs",
"[",
"'code'",
"]",
")",
"except",
"... | Raises the proper exception for passed error code. These must then be
handled by the layer calling _raise_error() | [
"Raises",
"the",
"proper",
"exception",
"for",
"passed",
"error",
"code",
".",
"These",
"must",
"then",
"be",
"handled",
"by",
"the",
"layer",
"calling",
"_raise_error",
"()"
] | python | train |
hanguokai/youku | youku/youku_playlists.py | https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_playlists.py#L33-L43 | def find_playlists_by_ids(self, playlist_ids):
"""doc: http://open.youku.com/docs/doc?id=67
"""
url = 'https://openapi.youku.com/v2/playlists/show_batch.json'
params = {
'client_id': self.client_id,
'playlist_ids': playlist_ids
}
r = requests.get(u... | [
"def",
"find_playlists_by_ids",
"(",
"self",
",",
"playlist_ids",
")",
":",
"url",
"=",
"'https://openapi.youku.com/v2/playlists/show_batch.json'",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'playlist_ids'",
":",
"playlist_ids",
"}",
"r",
... | doc: http://open.youku.com/docs/doc?id=67 | [
"doc",
":",
"http",
":",
"//",
"open",
".",
"youku",
".",
"com",
"/",
"docs",
"/",
"doc?id",
"=",
"67"
] | python | train |
osrg/ryu | ryu/lib/ovs/bridge.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/ovs/bridge.py#L376-L396 | def add_bond(self, name, ifaces, bond_mode=None, lacp=None):
"""
Creates a bonded port.
:param name: Port name to be created
:param ifaces: List of interfaces containing at least 2 interfaces
:param bond_mode: Bonding mode (active-backup, balance-tcp
or... | [
"def",
"add_bond",
"(",
"self",
",",
"name",
",",
"ifaces",
",",
"bond_mode",
"=",
"None",
",",
"lacp",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"ifaces",
")",
">=",
"2",
"options",
"=",
"''",
"if",
"bond_mode",
":",
"options",
"+=",
"'bond_mode=... | Creates a bonded port.
:param name: Port name to be created
:param ifaces: List of interfaces containing at least 2 interfaces
:param bond_mode: Bonding mode (active-backup, balance-tcp
or balance-slb)
:param lacp: LACP mode (active, passive or off) | [
"Creates",
"a",
"bonded",
"port",
"."
] | python | train |
blazelibs/blazeutils | blazeutils/spreadsheets.py | https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/spreadsheets.py#L212-L223 | def get_font(self, values):
"""
'height' 10pt = 200, 8pt = 160
"""
font_key = values
f = self.FONT_FACTORY.get(font_key, None)
if f is None:
f = xlwt.Font()
for attr, value in values:
f.__setattr__(attr, value)
self.FONT... | [
"def",
"get_font",
"(",
"self",
",",
"values",
")",
":",
"font_key",
"=",
"values",
"f",
"=",
"self",
".",
"FONT_FACTORY",
".",
"get",
"(",
"font_key",
",",
"None",
")",
"if",
"f",
"is",
"None",
":",
"f",
"=",
"xlwt",
".",
"Font",
"(",
")",
"for"... | 'height' 10pt = 200, 8pt = 160 | [
"height",
"10pt",
"=",
"200",
"8pt",
"=",
"160"
] | python | train |
santoshphilip/eppy | eppy/hvacbuilder.py | https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/hvacbuilder.py#L990-L1003 | def replacebranch1(idf, loop, branchname, listofcomponents_tuples, fluid=None,
debugsave=False):
"""do I even use this ? .... yup! I do"""
if fluid is None:
fluid = ''
listofcomponents_tuples = _clean_listofcomponents_tuples(listofcomponents_tuples)
branch = idf.getobject('BRA... | [
"def",
"replacebranch1",
"(",
"idf",
",",
"loop",
",",
"branchname",
",",
"listofcomponents_tuples",
",",
"fluid",
"=",
"None",
",",
"debugsave",
"=",
"False",
")",
":",
"if",
"fluid",
"is",
"None",
":",
"fluid",
"=",
"''",
"listofcomponents_tuples",
"=",
... | do I even use this ? .... yup! I do | [
"do",
"I",
"even",
"use",
"this",
"?",
"....",
"yup!",
"I",
"do"
] | python | train |
Alignak-monitoring/alignak | alignak/dependencynode.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L657-L691 | def find_object(self, pattern, hosts, services):
"""Find object from pattern
:param pattern: text to search (host1,service1)
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, u... | [
"def",
"find_object",
"(",
"self",
",",
"pattern",
",",
"hosts",
",",
"services",
")",
":",
"obj",
"=",
"None",
"error",
"=",
"None",
"is_service",
"=",
"False",
"# h_name, service_desc are , separated",
"elts",
"=",
"pattern",
".",
"split",
"(",
"','",
")",... | Find object from pattern
:param pattern: text to search (host1,service1)
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: align... | [
"Find",
"object",
"from",
"pattern"
] | python | train |
klen/muffin-rest | muffin_rest/handlers.py | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/handlers.py#L279-L294 | def make_pagination_headers(request, limit, curpage, total, links=False):
"""Return Link Hypermedia Header."""
lastpage = math.ceil(total / limit) - 1
headers = {'X-Total-Count': str(total), 'X-Limit': str(limit),
'X-Page-Last': str(lastpage), 'X-Page': str(curpage)}
if links:
bas... | [
"def",
"make_pagination_headers",
"(",
"request",
",",
"limit",
",",
"curpage",
",",
"total",
",",
"links",
"=",
"False",
")",
":",
"lastpage",
"=",
"math",
".",
"ceil",
"(",
"total",
"/",
"limit",
")",
"-",
"1",
"headers",
"=",
"{",
"'X-Total-Count'",
... | Return Link Hypermedia Header. | [
"Return",
"Link",
"Hypermedia",
"Header",
"."
] | python | train |
deepmind/pysc2 | pysc2/lib/sc_process.py | https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/sc_process.py#L195-L206 | def _shutdown_proc(p, timeout):
"""Wait for a proc to shut down, then terminate or kill it after `timeout`."""
freq = 10 # how often to check per second
for _ in range(1 + timeout * freq):
ret = p.poll()
if ret is not None:
logging.info("Shutdown gracefully.")
return ret
time.sleep(1 / fr... | [
"def",
"_shutdown_proc",
"(",
"p",
",",
"timeout",
")",
":",
"freq",
"=",
"10",
"# how often to check per second",
"for",
"_",
"in",
"range",
"(",
"1",
"+",
"timeout",
"*",
"freq",
")",
":",
"ret",
"=",
"p",
".",
"poll",
"(",
")",
"if",
"ret",
"is",
... | Wait for a proc to shut down, then terminate or kill it after `timeout`. | [
"Wait",
"for",
"a",
"proc",
"to",
"shut",
"down",
"then",
"terminate",
"or",
"kill",
"it",
"after",
"timeout",
"."
] | python | train |
eventbrite/eventbrite-sdk-python | eventbrite/access_methods.py | https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/access_methods.py#L291-L298 | def get_event_public_discounts(self, id, **data):
"""
GET /events/:id/public_discounts/
Returns a :ref:`paginated <pagination>` response with a key of ``discounts``, containing a list of public :format:`discounts <discount>` available on this event.
Note that public discounts and discoun... | [
"def",
"get_event_public_discounts",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"/events/{0}/public_discounts/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | GET /events/:id/public_discounts/
Returns a :ref:`paginated <pagination>` response with a key of ``discounts``, containing a list of public :format:`discounts <discount>` available on this event.
Note that public discounts and discounts have exactly the same form and structure; they're just namespaced s... | [
"GET",
"/",
"events",
"/",
":",
"id",
"/",
"public_discounts",
"/",
"Returns",
"a",
":",
"ref",
":",
"paginated",
"<pagination",
">",
"response",
"with",
"a",
"key",
"of",
"discounts",
"containing",
"a",
"list",
"of",
"public",
":",
"format",
":",
"disco... | python | train |
mikhaildubov/AST-text-analysis | east/asts/easa.py | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/asts/easa.py#L38-L55 | def traverse_depth_first_pre_order(self, callback):
"""Visits the internal "nodes" of the enhanced suffix array in depth-first pre-order.
Based on Abouelhoda et al. (2004).
"""
n = len(self.suftab)
root = [0, 0, n - 1, ""] # <l, i, j, char>
def _traverse_top_down(inter... | [
"def",
"traverse_depth_first_pre_order",
"(",
"self",
",",
"callback",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"suftab",
")",
"root",
"=",
"[",
"0",
",",
"0",
",",
"n",
"-",
"1",
",",
"\"\"",
"]",
"# <l, i, j, char>",
"def",
"_traverse_top_down",
... | Visits the internal "nodes" of the enhanced suffix array in depth-first pre-order.
Based on Abouelhoda et al. (2004). | [
"Visits",
"the",
"internal",
"nodes",
"of",
"the",
"enhanced",
"suffix",
"array",
"in",
"depth",
"-",
"first",
"pre",
"-",
"order",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L941-L955 | def _averageFromList(self, param):
""" Averages out values passed as a comma-separated
list, disregarding the zero-valued entries.
"""
_result = 0.0
_count = 0
for _param in param.split(','):
if _param != '' and float(_param) != 0.0:
_resu... | [
"def",
"_averageFromList",
"(",
"self",
",",
"param",
")",
":",
"_result",
"=",
"0.0",
"_count",
"=",
"0",
"for",
"_param",
"in",
"param",
".",
"split",
"(",
"','",
")",
":",
"if",
"_param",
"!=",
"''",
"and",
"float",
"(",
"_param",
")",
"!=",
"0.... | Averages out values passed as a comma-separated
list, disregarding the zero-valued entries. | [
"Averages",
"out",
"values",
"passed",
"as",
"a",
"comma",
"-",
"separated",
"list",
"disregarding",
"the",
"zero",
"-",
"valued",
"entries",
"."
] | python | train |
sci-bots/svg-model | svg_model/draw.py | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/draw.py#L13-L92 | def draw_shapes_svg_layer(df_shapes, shape_i_columns, layer_name,
layer_number=1, use_svg_path=True):
'''
Draw shapes as a layer in a SVG file.
Args:
df_shapes (pandas.DataFrame): Table of shape vertices (one row per
vertex).
shape_i_columns (str or li... | [
"def",
"draw_shapes_svg_layer",
"(",
"df_shapes",
",",
"shape_i_columns",
",",
"layer_name",
",",
"layer_number",
"=",
"1",
",",
"use_svg_path",
"=",
"True",
")",
":",
"# Note that `svgwrite.Drawing` requires a filepath to be specified during",
"# construction, *but* nothing is... | Draw shapes as a layer in a SVG file.
Args:
df_shapes (pandas.DataFrame): Table of shape vertices (one row per
vertex).
shape_i_columns (str or list) : Either a single column name as a string
or a list of column names in ``df_shapes``. Rows in ``df_shapes``
wit... | [
"Draw",
"shapes",
"as",
"a",
"layer",
"in",
"a",
"SVG",
"file",
"."
] | python | train |
monarch-initiative/dipper | dipper/sources/Bgee.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/Bgee.py#L110-L155 | def fetch(self, is_dl_forced=False):
"""
:param is_dl_forced: boolean, force download
:return:
"""
(files_to_download, ftp) = self._get_file_list(
self.files['anat_entity']['path'],
self.files['anat_entity']['pattern'])
LOG.info(
'Wil... | [
"def",
"fetch",
"(",
"self",
",",
"is_dl_forced",
"=",
"False",
")",
":",
"(",
"files_to_download",
",",
"ftp",
")",
"=",
"self",
".",
"_get_file_list",
"(",
"self",
".",
"files",
"[",
"'anat_entity'",
"]",
"[",
"'path'",
"]",
",",
"self",
".",
"files"... | :param is_dl_forced: boolean, force download
:return: | [
":",
"param",
"is_dl_forced",
":",
"boolean",
"force",
"download",
":",
"return",
":"
] | python | train |
chrisrink10/basilisp | src/basilisp/lang/runtime.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L1102-L1122 | def lrepr(o, human_readable: bool = False) -> str:
"""Produce a string representation of an object. If human_readable is False,
the string representation of Lisp objects is something that can be read back
in by the reader as the same object."""
core_ns = Namespace.get(sym.symbol(CORE_NS))
assert cor... | [
"def",
"lrepr",
"(",
"o",
",",
"human_readable",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"core_ns",
"=",
"Namespace",
".",
"get",
"(",
"sym",
".",
"symbol",
"(",
"CORE_NS",
")",
")",
"assert",
"core_ns",
"is",
"not",
"None",
"return",
"lobj... | Produce a string representation of an object. If human_readable is False,
the string representation of Lisp objects is something that can be read back
in by the reader as the same object. | [
"Produce",
"a",
"string",
"representation",
"of",
"an",
"object",
".",
"If",
"human_readable",
"is",
"False",
"the",
"string",
"representation",
"of",
"Lisp",
"objects",
"is",
"something",
"that",
"can",
"be",
"read",
"back",
"in",
"by",
"the",
"reader",
"as... | python | test |
eeue56/PyChat.js | pychatjs/server/connections.py | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/connections.py#L43-L48 | def send_to_room(self, message, room_name):
""" Sends a given message to a given room """
room = self.get_room(room_name)
if room is not None:
room.send_message(message) | [
"def",
"send_to_room",
"(",
"self",
",",
"message",
",",
"room_name",
")",
":",
"room",
"=",
"self",
".",
"get_room",
"(",
"room_name",
")",
"if",
"room",
"is",
"not",
"None",
":",
"room",
".",
"send_message",
"(",
"message",
")"
] | Sends a given message to a given room | [
"Sends",
"a",
"given",
"message",
"to",
"a",
"given",
"room"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.