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 |
|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/cloud/clouds/digitalocean.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1342-L1353 | def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_out... | [
"def",
"_get_full_output",
"(",
"node",
",",
"for_output",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"item",
"in",
"six",
".",
"iterkeys",
"(",
"node",
")",
":",
"value",
"=",
"node",
"[",
"item",
"]",
"if",
"value",
"is",
"not",
"None",... | Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node. | [
"Helper",
"function",
"for",
"_list_nodes",
"to",
"loop",
"through",
"all",
"node",
"information",
".",
"Returns",
"a",
"dictionary",
"containing",
"the",
"full",
"information",
"of",
"a",
"node",
"."
] | python | train |
SatelliteQE/nailgun | nailgun/entities.py | https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L1722-L1734 | def create_missing(self):
"""Customize the process of auto-generating instance attributes.
Populate ``template_kind`` if:
* this template is not a snippet, and
* the ``template_kind`` instance attribute is unset.
"""
super(ProvisioningTemplate, self).create_missing()
... | [
"def",
"create_missing",
"(",
"self",
")",
":",
"super",
"(",
"ProvisioningTemplate",
",",
"self",
")",
".",
"create_missing",
"(",
")",
"if",
"(",
"getattr",
"(",
"self",
",",
"'snippet'",
",",
"None",
")",
"is",
"False",
"and",
"not",
"hasattr",
"(",
... | Customize the process of auto-generating instance attributes.
Populate ``template_kind`` if:
* this template is not a snippet, and
* the ``template_kind`` instance attribute is unset. | [
"Customize",
"the",
"process",
"of",
"auto",
"-",
"generating",
"instance",
"attributes",
"."
] | python | train |
google/grr | grr/client/grr_response_client/comms.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/comms.py#L1220-L1277 | def Run(self):
"""The main run method of the client.
This method does not normally return. Only if there have been more than
connection_error_limit failures, the method returns and allows the
client to exit.
"""
while True:
if self.http_manager.ErrorLimitReached():
return
#... | [
"def",
"Run",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"http_manager",
".",
"ErrorLimitReached",
"(",
")",
":",
"return",
"# Check if there is a message from the nanny to be sent.",
"self",
".",
"client_worker",
".",
"SendNannyMessage",
"(",
... | The main run method of the client.
This method does not normally return. Only if there have been more than
connection_error_limit failures, the method returns and allows the
client to exit. | [
"The",
"main",
"run",
"method",
"of",
"the",
"client",
"."
] | python | train |
signalfx/signalfx-python | signalfx/signalflow/computation.py | https://github.com/signalfx/signalfx-python/blob/650eb9a2b301bcc795e4e3a8c031574ade69849d/signalfx/signalflow/computation.py#L76-L169 | def stream(self):
"""Iterate over the messages from the computation's output.
Control and metadata messages are intercepted and interpreted to
enhance this Computation's object knowledge of the computation's
context. Data and event messages are yielded back to the caller as a
ge... | [
"def",
"stream",
"(",
"self",
")",
":",
"iterator",
"=",
"iter",
"(",
"self",
".",
"_stream",
")",
"while",
"self",
".",
"_state",
"<",
"Computation",
".",
"STATE_COMPLETED",
":",
"try",
":",
"message",
"=",
"next",
"(",
"iterator",
")",
"except",
"Sto... | Iterate over the messages from the computation's output.
Control and metadata messages are intercepted and interpreted to
enhance this Computation's object knowledge of the computation's
context. Data and event messages are yielded back to the caller as a
generator. | [
"Iterate",
"over",
"the",
"messages",
"from",
"the",
"computation",
"s",
"output",
"."
] | python | train |
mLewisLogic/foursquare | foursquare/__init__.py | https://github.com/mLewisLogic/foursquare/blob/420f3b588b9af154688ec82649f24a70f96c1665/foursquare/__init__.py#L776-L787 | def _process_response(response):
"""Make the request and handle exception processing"""
# Read the response as JSON
try:
data = response.json()
except ValueError:
_log_and_raise_exception('Invalid response', response.text)
# Default case, Got proper response
if response.status_c... | [
"def",
"_process_response",
"(",
"response",
")",
":",
"# Read the response as JSON",
"try",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"_log_and_raise_exception",
"(",
"'Invalid response'",
",",
"response",
".",
"text",
")",... | Make the request and handle exception processing | [
"Make",
"the",
"request",
"and",
"handle",
"exception",
"processing"
] | python | train |
happyleavesaoc/python-limitlessled | limitlessled/__init__.py | https://github.com/happyleavesaoc/python-limitlessled/blob/70307c2bf8c91430a99579d2ad18b228ec7a8488/limitlessled/__init__.py#L36-L42 | def add_bridge(self, bridge):
""" Add bridge groups.
:param bridge: Add groups from this bridge.
"""
for group in bridge.groups:
self._groups[group.name] = group | [
"def",
"add_bridge",
"(",
"self",
",",
"bridge",
")",
":",
"for",
"group",
"in",
"bridge",
".",
"groups",
":",
"self",
".",
"_groups",
"[",
"group",
".",
"name",
"]",
"=",
"group"
] | Add bridge groups.
:param bridge: Add groups from this bridge. | [
"Add",
"bridge",
"groups",
"."
] | python | train |
pantsbuild/pants | src/python/pants/util/dirutil.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L341-L357 | def safe_rm_oldest_items_in_dir(root_dir, num_of_items_to_keep, excludes=frozenset()):
"""
Keep `num_of_items_to_keep` newly modified items besides `excludes` in `root_dir` then remove the rest.
:param root_dir: the folder to examine
:param num_of_items_to_keep: number of files/folders/symlinks to keep after th... | [
"def",
"safe_rm_oldest_items_in_dir",
"(",
"root_dir",
",",
"num_of_items_to_keep",
",",
"excludes",
"=",
"frozenset",
"(",
")",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"root_dir",
")",
":",
"found_files",
"=",
"[",
"]",
"for",
"old_file",
"i... | Keep `num_of_items_to_keep` newly modified items besides `excludes` in `root_dir` then remove the rest.
:param root_dir: the folder to examine
:param num_of_items_to_keep: number of files/folders/symlinks to keep after the cleanup
:param excludes: absolute paths excluded from removal (must be prefixed with `root_... | [
"Keep",
"num_of_items_to_keep",
"newly",
"modified",
"items",
"besides",
"excludes",
"in",
"root_dir",
"then",
"remove",
"the",
"rest",
".",
":",
"param",
"root_dir",
":",
"the",
"folder",
"to",
"examine",
":",
"param",
"num_of_items_to_keep",
":",
"number",
"of... | python | train |
talkincode/toughlib | toughlib/btforms/net.py | https://github.com/talkincode/toughlib/blob/1c2f7dde3a7f101248f1b5f5d428cc85466995cf/toughlib/btforms/net.py#L100-L114 | def urlquote(val):
"""
Quotes a string for use in a URL.
>>> urlquote('://?f=1&j=1')
'%3A//%3Ff%3D1%26j%3D1'
>>> urlquote(None)
''
>>> urlquote(u'\u203d')
'%E2%80%BD'
"""
if val is None: return ''
if not isinstance(val, unicode): val = str(val)
... | [
"def",
"urlquote",
"(",
"val",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"''",
"if",
"not",
"isinstance",
"(",
"val",
",",
"unicode",
")",
":",
"val",
"=",
"str",
"(",
"val",
")",
"else",
":",
"val",
"=",
"val",
".",
"encode",
"(",
"'... | Quotes a string for use in a URL.
>>> urlquote('://?f=1&j=1')
'%3A//%3Ff%3D1%26j%3D1'
>>> urlquote(None)
''
>>> urlquote(u'\u203d')
'%E2%80%BD' | [
"Quotes",
"a",
"string",
"for",
"use",
"in",
"a",
"URL",
".",
">>>",
"urlquote",
"(",
":",
"//",
"?f",
"=",
"1&j",
"=",
"1",
")",
"%3A",
"//",
"%3Ff%3D1%26j%3D1",
">>>",
"urlquote",
"(",
"None",
")",
">>>",
"urlquote",
"(",
"u",
"\\",
"u203d",
")",... | python | train |
davgeo/clear | clear/util.py | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L162-L240 | def UserAcceptance(
matchList,
recursiveLookup = True,
promptComment = None,
promptOnly = False,
xStrOverride = "to skip this selection"
):
"""
Prompt user to select a entry from a given match list or to enter a new
string to look up. If the match list is empty user must enter a new string
or exit.
... | [
"def",
"UserAcceptance",
"(",
"matchList",
",",
"recursiveLookup",
"=",
"True",
",",
"promptComment",
"=",
"None",
",",
"promptOnly",
"=",
"False",
",",
"xStrOverride",
"=",
"\"to skip this selection\"",
")",
":",
"matchString",
"=",
"', '",
".",
"join",
"(",
... | Prompt user to select a entry from a given match list or to enter a new
string to look up. If the match list is empty user must enter a new string
or exit.
Parameters
----------
matchList : list
A list of entries which the user can select a valid match from.
recursiveLookup : boolean [optional: ... | [
"Prompt",
"user",
"to",
"select",
"a",
"entry",
"from",
"a",
"given",
"match",
"list",
"or",
"to",
"enter",
"a",
"new",
"string",
"to",
"look",
"up",
".",
"If",
"the",
"match",
"list",
"is",
"empty",
"user",
"must",
"enter",
"a",
"new",
"string",
"or... | python | train |
Kortemme-Lab/klab | klab/bio/clustalo.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/clustalo.py#L664-L679 | def _get_uniparc_sequences_through_uniprot_ACs(self, mapping_pdb_id, uniprot_ACs, cache_dir):
'''Get the UniParc sequences associated with the UniProt accession number.'''
# Map the UniProt ACs to the UniParc IDs
m = uniprot_map('ACC', 'UPARC', uniprot_ACs, cache_dir = cache_dir)
UniPar... | [
"def",
"_get_uniparc_sequences_through_uniprot_ACs",
"(",
"self",
",",
"mapping_pdb_id",
",",
"uniprot_ACs",
",",
"cache_dir",
")",
":",
"# Map the UniProt ACs to the UniParc IDs",
"m",
"=",
"uniprot_map",
"(",
"'ACC'",
",",
"'UPARC'",
",",
"uniprot_ACs",
",",
"cache_di... | Get the UniParc sequences associated with the UniProt accession number. | [
"Get",
"the",
"UniParc",
"sequences",
"associated",
"with",
"the",
"UniProt",
"accession",
"number",
"."
] | python | train |
dwavesystems/dwavebinarycsp | dwavebinarycsp/compilers/stitcher.py | https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/compilers/stitcher.py#L34-L196 | def stitch(csp, min_classical_gap=2.0, max_graph_size=8):
"""Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction
problem.
Args:
csp (:obj:`.ConstraintSatisfactionProblem`):
Constraint satisfaction problem.
min_classica... | [
"def",
"stitch",
"(",
"csp",
",",
"min_classical_gap",
"=",
"2.0",
",",
"max_graph_size",
"=",
"8",
")",
":",
"# ensure we have penaltymodel factory available",
"try",
":",
"dwavebinarycsp",
".",
"assert_penaltymodel_factory_available",
"(",
")",
"except",
"AssertionErr... | Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction
problem.
Args:
csp (:obj:`.ConstraintSatisfactionProblem`):
Constraint satisfaction problem.
min_classical_gap (float, optional, default=2.0):
Minimum energy ... | [
"Build",
"a",
"binary",
"quadratic",
"model",
"with",
"minimal",
"energy",
"levels",
"at",
"solutions",
"to",
"the",
"specified",
"constraint",
"satisfaction",
"problem",
"."
] | python | valid |
rochacbruno/dynaconf | docs/customexts/aafig.py | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/docs/customexts/aafig.py#L153-L212 | def render_aafigure(app, text, options):
"""
Render an ASCII art figure into the requested format output file.
"""
if aafigure is None:
raise AafigError('aafigure module not installed')
fname = get_basename(text, options)
fname = '%s.%s' % (get_basename(text, options), options['format'... | [
"def",
"render_aafigure",
"(",
"app",
",",
"text",
",",
"options",
")",
":",
"if",
"aafigure",
"is",
"None",
":",
"raise",
"AafigError",
"(",
"'aafigure module not installed'",
")",
"fname",
"=",
"get_basename",
"(",
"text",
",",
"options",
")",
"fname",
"="... | Render an ASCII art figure into the requested format output file. | [
"Render",
"an",
"ASCII",
"art",
"figure",
"into",
"the",
"requested",
"format",
"output",
"file",
"."
] | python | train |
sirfoga/pyhal | hal/data/linked_list.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/data/linked_list.py#L141-L163 | def remove_last(self):
"""Removes last
:return: True iff last element has been removed
"""
if self.length() <= 1:
self.head = None
return True
node = self.head
while node is not None:
is_last_but_one = node.next_node is not None and... | [
"def",
"remove_last",
"(",
"self",
")",
":",
"if",
"self",
".",
"length",
"(",
")",
"<=",
"1",
":",
"self",
".",
"head",
"=",
"None",
"return",
"True",
"node",
"=",
"self",
".",
"head",
"while",
"node",
"is",
"not",
"None",
":",
"is_last_but_one",
... | Removes last
:return: True iff last element has been removed | [
"Removes",
"last"
] | python | train |
dslackw/slpkg | slpkg/sbo/network.py | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/sbo/network.py#L388-L394 | def install(self):
"""Install SBo package found in /tmp directory.
"""
binary = slack_package(self.prgnam)
print("[ {0}Installing{1} ] --> {2}".format(self.green, self.endc,
self.name))
PackageManager(binary).upgrade(flag="--ins... | [
"def",
"install",
"(",
"self",
")",
":",
"binary",
"=",
"slack_package",
"(",
"self",
".",
"prgnam",
")",
"print",
"(",
"\"[ {0}Installing{1} ] --> {2}\"",
".",
"format",
"(",
"self",
".",
"green",
",",
"self",
".",
"endc",
",",
"self",
".",
"name",
")",... | Install SBo package found in /tmp directory. | [
"Install",
"SBo",
"package",
"found",
"in",
"/",
"tmp",
"directory",
"."
] | python | train |
pyviz/holoviews | holoviews/operation/datashader.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/operation/datashader.py#L270-L340 | def get_agg_data(cls, obj, category=None):
"""
Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated.
"""
paths = []
if isinstance(obj, Graph):
obj = obj.edgepaths
kdims = list(obj.kdims)
vdims = list(... | [
"def",
"get_agg_data",
"(",
"cls",
",",
"obj",
",",
"category",
"=",
"None",
")",
":",
"paths",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"Graph",
")",
":",
"obj",
"=",
"obj",
".",
"edgepaths",
"kdims",
"=",
"list",
"(",
"obj",
".",
"kd... | Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated. | [
"Reduces",
"any",
"Overlay",
"or",
"NdOverlay",
"of",
"Elements",
"into",
"a",
"single",
"xarray",
"Dataset",
"that",
"can",
"be",
"aggregated",
"."
] | python | train |
data-8/datascience | datascience/tables.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L246-L285 | def column(self, index_or_label):
"""Return the values of a column as an array.
table.column(label) is equivalent to table[label].
>>> tiles = Table().with_columns(
... 'letter', make_array('c', 'd'),
... 'count', make_array(2, 4),
... )
>>> list(tiles... | [
"def",
"column",
"(",
"self",
",",
"index_or_label",
")",
":",
"if",
"(",
"isinstance",
"(",
"index_or_label",
",",
"str",
")",
"and",
"index_or_label",
"not",
"in",
"self",
".",
"labels",
")",
":",
"raise",
"ValueError",
"(",
"'The column \"{}\" is not in the... | Return the values of a column as an array.
table.column(label) is equivalent to table[label].
>>> tiles = Table().with_columns(
... 'letter', make_array('c', 'd'),
... 'count', make_array(2, 4),
... )
>>> list(tiles.column('letter'))
['c', 'd']
... | [
"Return",
"the",
"values",
"of",
"a",
"column",
"as",
"an",
"array",
"."
] | python | train |
stephen-bunn/file-config | src/file_config/contrib/ini_parser.py | https://github.com/stephen-bunn/file-config/blob/93429360c949985202e1f2b9cd0340731819ba75/src/file_config/contrib/ini_parser.py#L81-L117 | def _build_dict(
cls, parser_dict, delimiter=DEFAULT_DELIMITER, dict_type=collections.OrderedDict
):
""" Builds a dictionary of ``dict_type`` given the ``parser._sections`` dict.
:param dict parser_dict: The ``parser._sections`` mapping
:param str delimiter: The delimiter for nested... | [
"def",
"_build_dict",
"(",
"cls",
",",
"parser_dict",
",",
"delimiter",
"=",
"DEFAULT_DELIMITER",
",",
"dict_type",
"=",
"collections",
".",
"OrderedDict",
")",
":",
"result",
"=",
"dict_type",
"(",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"parser_... | Builds a dictionary of ``dict_type`` given the ``parser._sections`` dict.
:param dict parser_dict: The ``parser._sections`` mapping
:param str delimiter: The delimiter for nested dictionaries,
defaults to ":", optional
:param class dict_type: The dictionary type to use for building ... | [
"Builds",
"a",
"dictionary",
"of",
"dict_type",
"given",
"the",
"parser",
".",
"_sections",
"dict",
"."
] | python | train |
vaexio/vaex | packages/vaex-core/vaex/export.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/export.py#L270-L330 | def export_fits(dataset, path, column_names=None, shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True):
"""
:param DatasetLocal dataset: dataset to export
:param str path: path for file
:param lis[str] column_names: list of column names to export or None for all column... | [
"def",
"export_fits",
"(",
"dataset",
",",
"path",
",",
"column_names",
"=",
"None",
",",
"shuffle",
"=",
"False",
",",
"selection",
"=",
"False",
",",
"progress",
"=",
"None",
",",
"virtual",
"=",
"True",
",",
"sort",
"=",
"None",
",",
"ascending",
"=... | :param DatasetLocal dataset: dataset to export
:param str path: path for file
:param lis[str] column_names: list of column names to export or None for all columns
:param bool shuffle: export rows in random order
:param bool selection: export selection or not
:param progress: progress callback that g... | [
":",
"param",
"DatasetLocal",
"dataset",
":",
"dataset",
"to",
"export",
":",
"param",
"str",
"path",
":",
"path",
"for",
"file",
":",
"param",
"lis",
"[",
"str",
"]",
"column_names",
":",
"list",
"of",
"column",
"names",
"to",
"export",
"or",
"None",
... | python | test |
helium/helium-python | helium/resource.py | https://github.com/helium/helium-python/blob/db73480b143da4fc48e95c4414bd69c576a3a390/helium/resource.py#L201-L225 | def find(cls, session, resource_id, include=None):
"""Retrieve a single resource.
This should only be called from sub-classes.
Args:
session(Session): The session to find the resource in
resource_id: The ``id`` for the resource to look up
Keyword Args:
... | [
"def",
"find",
"(",
"cls",
",",
"session",
",",
"resource_id",
",",
"include",
"=",
"None",
")",
":",
"url",
"=",
"session",
".",
"_build_url",
"(",
"cls",
".",
"_resource_path",
"(",
")",
",",
"resource_id",
")",
"params",
"=",
"build_request_include",
... | Retrieve a single resource.
This should only be called from sub-classes.
Args:
session(Session): The session to find the resource in
resource_id: The ``id`` for the resource to look up
Keyword Args:
include: Resource classes to include
Returns:
... | [
"Retrieve",
"a",
"single",
"resource",
"."
] | python | train |
Anaconda-Platform/anaconda-client | binstar_client/inspect_package/pypi.py | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/inspect_package/pypi.py#L111-L126 | def get_header_description(filedata):
"""Get description from metadata file and remove any empty lines at end."""
python_version = sys.version_info.major
if python_version == 3:
filedata = Parser().parsestr(filedata)
else:
filedata = Parser().parsestr(filedata.encode("UTF-8", "replace"))... | [
"def",
"get_header_description",
"(",
"filedata",
")",
":",
"python_version",
"=",
"sys",
".",
"version_info",
".",
"major",
"if",
"python_version",
"==",
"3",
":",
"filedata",
"=",
"Parser",
"(",
")",
".",
"parsestr",
"(",
"filedata",
")",
"else",
":",
"f... | Get description from metadata file and remove any empty lines at end. | [
"Get",
"description",
"from",
"metadata",
"file",
"and",
"remove",
"any",
"empty",
"lines",
"at",
"end",
"."
] | python | train |
Fantomas42/django-blog-zinnia | zinnia/templatetags/zinnia.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/templatetags/zinnia.py#L411-L420 | def week_number(date):
"""
Return the Python week number of a date.
The django \|date:"W" returns incompatible value
with the view implementation.
"""
week_number = date.strftime('%W')
if int(week_number) < 10:
week_number = week_number[-1]
return week_number | [
"def",
"week_number",
"(",
"date",
")",
":",
"week_number",
"=",
"date",
".",
"strftime",
"(",
"'%W'",
")",
"if",
"int",
"(",
"week_number",
")",
"<",
"10",
":",
"week_number",
"=",
"week_number",
"[",
"-",
"1",
"]",
"return",
"week_number"
] | Return the Python week number of a date.
The django \|date:"W" returns incompatible value
with the view implementation. | [
"Return",
"the",
"Python",
"week",
"number",
"of",
"a",
"date",
".",
"The",
"django",
"\\",
"|date",
":",
"W",
"returns",
"incompatible",
"value",
"with",
"the",
"view",
"implementation",
"."
] | python | train |
tornadoweb/tornado | tornado/gen.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L619-L637 | def sleep(duration: float) -> "Future[None]":
"""Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
... | [
"def",
"sleep",
"(",
"duration",
":",
"float",
")",
"->",
"\"Future[None]\"",
":",
"f",
"=",
"_create_future",
"(",
")",
"IOLoop",
".",
"current",
"(",
")",
".",
"call_later",
"(",
"duration",
",",
"lambda",
":",
"future_set_result_unless_cancelled",
"(",
"f... | Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
Note that calling this function on its own does n... | [
"Return",
"a",
".",
"Future",
"that",
"resolves",
"after",
"the",
"given",
"number",
"of",
"seconds",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/image/image.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L86-L140 | def imresize(src, w, h, *args, **kwargs):
r"""Resize image with OpenCV.
.. note:: `imresize` uses OpenCV (not the CV2 Python library). MXNet must have been built
with USE_OPENCV=1 for `imresize` to work.
Parameters
----------
src : NDArray
source image
w : int, required
... | [
"def",
"imresize",
"(",
"src",
",",
"w",
",",
"h",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_internal",
".",
"_cvimresize",
"(",
"src",
",",
"w",
",",
"h",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | r"""Resize image with OpenCV.
.. note:: `imresize` uses OpenCV (not the CV2 Python library). MXNet must have been built
with USE_OPENCV=1 for `imresize` to work.
Parameters
----------
src : NDArray
source image
w : int, required
Width of resized image.
h : int, required
... | [
"r",
"Resize",
"image",
"with",
"OpenCV",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/client/asyncresult.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/client/asyncresult.py#L443-L543 | def display_outputs(self, groupby="type"):
"""republish the outputs of the computation
Parameters
----------
groupby : str [default: type]
if 'type':
Group outputs by type (show all stdout, then all stderr, etc.):
... | [
"def",
"display_outputs",
"(",
"self",
",",
"groupby",
"=",
"\"type\"",
")",
":",
"if",
"self",
".",
"_single_result",
":",
"self",
".",
"_display_single_result",
"(",
")",
"return",
"stdouts",
"=",
"self",
".",
"stdout",
"stderrs",
"=",
"self",
".",
"stde... | republish the outputs of the computation
Parameters
----------
groupby : str [default: type]
if 'type':
Group outputs by type (show all stdout, then all stderr, etc.):
[stdout:1] foo
[stdout:2] foo
... | [
"republish",
"the",
"outputs",
"of",
"the",
"computation",
"Parameters",
"----------",
"groupby",
":",
"str",
"[",
"default",
":",
"type",
"]",
"if",
"type",
":",
"Group",
"outputs",
"by",
"type",
"(",
"show",
"all",
"stdout",
"then",
"all",
"stderr",
"etc... | python | test |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L669-L686 | def remove_ref(self, ref):
"""Remove reference from self to ref
>>> iip = Resource('instance-ip',
uuid='30213cf9-4b03-4afc-b8f9-c9971a216978',
fetch=True)
>>> for vmi in iip['virtual_machine_interface_refs']:
iip.remove_ref(v... | [
"def",
"remove_ref",
"(",
"self",
",",
"ref",
")",
":",
"self",
".",
"session",
".",
"remove_ref",
"(",
"self",
",",
"ref",
")",
"return",
"self",
".",
"fetch",
"(",
")"
] | Remove reference from self to ref
>>> iip = Resource('instance-ip',
uuid='30213cf9-4b03-4afc-b8f9-c9971a216978',
fetch=True)
>>> for vmi in iip['virtual_machine_interface_refs']:
iip.remove_ref(vmi)
>>> iip['virtual_machine_i... | [
"Remove",
"reference",
"from",
"self",
"to",
"ref"
] | python | train |
brutasse/graphite-api | graphite_api/render/glyph.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L2219-L2246 | def format_units(v, step=None, system="si", units=None):
"""Format the given value in standardized units.
``system`` is either 'binary' or 'si'
For more info, see:
http://en.wikipedia.org/wiki/SI_prefix
http://en.wikipedia.org/wiki/Binary_prefix
"""
if v is None:
return 0, ... | [
"def",
"format_units",
"(",
"v",
",",
"step",
"=",
"None",
",",
"system",
"=",
"\"si\"",
",",
"units",
"=",
"None",
")",
":",
"if",
"v",
"is",
"None",
":",
"return",
"0",
",",
"''",
"for",
"prefix",
",",
"size",
"in",
"UnitSystems",
"[",
"system",
... | Format the given value in standardized units.
``system`` is either 'binary' or 'si'
For more info, see:
http://en.wikipedia.org/wiki/SI_prefix
http://en.wikipedia.org/wiki/Binary_prefix | [
"Format",
"the",
"given",
"value",
"in",
"standardized",
"units",
"."
] | python | train |
numenta/nupic | src/nupic/frameworks/opf/opf_task_driver.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_task_driver.py#L120-L129 | def _getImpl(self, model):
""" Creates and returns the _IterationPhase-based instance corresponding
to this phase specification
model: Model instance
"""
impl = _IterationPhaseInferOnly(model=model,
nIters=self.__nIters,
... | [
"def",
"_getImpl",
"(",
"self",
",",
"model",
")",
":",
"impl",
"=",
"_IterationPhaseInferOnly",
"(",
"model",
"=",
"model",
",",
"nIters",
"=",
"self",
".",
"__nIters",
",",
"inferenceArgs",
"=",
"self",
".",
"__inferenceArgs",
")",
"return",
"impl"
] | Creates and returns the _IterationPhase-based instance corresponding
to this phase specification
model: Model instance | [
"Creates",
"and",
"returns",
"the",
"_IterationPhase",
"-",
"based",
"instance",
"corresponding",
"to",
"this",
"phase",
"specification"
] | python | valid |
limodou/uliweb | uliweb/contrib/rbac/rbac.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/rbac/rbac.py#L42-L78 | def has_role(user, *roles, **kwargs):
"""
Judge is the user belongs to the role, and if does, then return the role object
if not then return False. kwargs will be passed to role_func.
"""
Role = get_model('role')
if isinstance(user, (unicode, str)):
User = get_model('user')
... | [
"def",
"has_role",
"(",
"user",
",",
"*",
"roles",
",",
"*",
"*",
"kwargs",
")",
":",
"Role",
"=",
"get_model",
"(",
"'role'",
")",
"if",
"isinstance",
"(",
"user",
",",
"(",
"unicode",
",",
"str",
")",
")",
":",
"User",
"=",
"get_model",
"(",
"'... | Judge is the user belongs to the role, and if does, then return the role object
if not then return False. kwargs will be passed to role_func. | [
"Judge",
"is",
"the",
"user",
"belongs",
"to",
"the",
"role",
"and",
"if",
"does",
"then",
"return",
"the",
"role",
"object",
"if",
"not",
"then",
"return",
"False",
".",
"kwargs",
"will",
"be",
"passed",
"to",
"role_func",
"."
] | python | train |
arcus-io/puppetdb-python | puppetdb/v2/facts.py | https://github.com/arcus-io/puppetdb-python/blob/d772eb80a1dfb1154a1f421c7ecdc1ac951b5ea2/puppetdb/v2/facts.py#L34-L42 | def get_facts_by_name(api_url=None, fact_name=None, verify=False, cert=list()):
"""
Returns facts by name
:param api_url: Base PuppetDB API url
:param fact_name: Name of fact
"""
return utils._make_api_request(api_url, '/facts/{0}'.format(fact_name), verify, cert) | [
"def",
"get_facts_by_name",
"(",
"api_url",
"=",
"None",
",",
"fact_name",
"=",
"None",
",",
"verify",
"=",
"False",
",",
"cert",
"=",
"list",
"(",
")",
")",
":",
"return",
"utils",
".",
"_make_api_request",
"(",
"api_url",
",",
"'/facts/{0}'",
".",
"for... | Returns facts by name
:param api_url: Base PuppetDB API url
:param fact_name: Name of fact | [
"Returns",
"facts",
"by",
"name"
] | python | train |
fermiPy/fermipy | fermipy/jobs/job_archive.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L362-L368 | def make_dict(cls, table):
"""Build a dictionary map int to `JobDetails` from an `astropy.table.Table`"""
ret_dict = {}
for row in table:
job_details = cls.create_from_row(row)
ret_dict[job_details.dbkey] = job_details
return ret_dict | [
"def",
"make_dict",
"(",
"cls",
",",
"table",
")",
":",
"ret_dict",
"=",
"{",
"}",
"for",
"row",
"in",
"table",
":",
"job_details",
"=",
"cls",
".",
"create_from_row",
"(",
"row",
")",
"ret_dict",
"[",
"job_details",
".",
"dbkey",
"]",
"=",
"job_detail... | Build a dictionary map int to `JobDetails` from an `astropy.table.Table` | [
"Build",
"a",
"dictionary",
"map",
"int",
"to",
"JobDetails",
"from",
"an",
"astropy",
".",
"table",
".",
"Table"
] | python | train |
peri-source/peri | peri/comp/psfcalc.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/psfcalc.py#L421-L462 | def get_polydisp_pts_wts(kfki, sigkf, dist_type='gaussian', nkpts=3):
"""
Calculates a set of Gauss quadrature points & weights for polydisperse
light.
Returns a list of points and weights of the final wavevector's distri-
bution, in units of the initial wavevector.
Parameters
----------
... | [
"def",
"get_polydisp_pts_wts",
"(",
"kfki",
",",
"sigkf",
",",
"dist_type",
"=",
"'gaussian'",
",",
"nkpts",
"=",
"3",
")",
":",
"if",
"dist_type",
".",
"lower",
"(",
")",
"==",
"'gaussian'",
":",
"pts",
",",
"wts",
"=",
"np",
".",
"polynomial",
".",
... | Calculates a set of Gauss quadrature points & weights for polydisperse
light.
Returns a list of points and weights of the final wavevector's distri-
bution, in units of the initial wavevector.
Parameters
----------
kfki : Float
The mean of the polydisperse outgoing wavevectors.... | [
"Calculates",
"a",
"set",
"of",
"Gauss",
"quadrature",
"points",
"&",
"weights",
"for",
"polydisperse",
"light",
"."
] | python | valid |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L305-L341 | def upload_file(self, filepath, key):
"""Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
... | [
"def",
"upload_file",
"(",
"self",
",",
"filepath",
",",
"key",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.upload_file'",
")",
"log",
".",
"info",
"(",
"'Attempting to upload file %s to S3 bucket %s as key %s...'",
... | Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
:return: True if upload is successful, Fals... | [
"Uploads",
"a",
"file",
"using",
"the",
"passed",
"S3",
"key"
] | python | train |
airbus-cert/mispy | mispy/misp.py | https://github.com/airbus-cert/mispy/blob/6d523d6f134d2bd38ec8264be74e73b68403da65/mispy/misp.py#L800-L811 | def GET(self, path):
"""
Raw GET to the MISP server
:param path: URL fragment (ie /events/)
:returns: HTTP raw content (as seen by :class:`requests.Response`)
"""
url = self._absolute_url(path)
resp = requests.get(url, headers=self.headers, verify=self.verify_ssl... | [
"def",
"GET",
"(",
"self",
",",
"path",
")",
":",
"url",
"=",
"self",
".",
"_absolute_url",
"(",
"path",
")",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"verify",
"=",
"self",
".",
"verify_ssl... | Raw GET to the MISP server
:param path: URL fragment (ie /events/)
:returns: HTTP raw content (as seen by :class:`requests.Response`) | [
"Raw",
"GET",
"to",
"the",
"MISP",
"server"
] | python | train |
intake/intake | intake/gui/base.py | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L202-L214 | def add(self, items):
"""Add items to options"""
options = self._create_options(items)
for k, v in options.items():
if k in self.labels and v not in self.items:
options.pop(k)
count = 0
while f'{k}_{count}' in self.labels:
... | [
"def",
"add",
"(",
"self",
",",
"items",
")",
":",
"options",
"=",
"self",
".",
"_create_options",
"(",
"items",
")",
"for",
"k",
",",
"v",
"in",
"options",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"self",
".",
"labels",
"and",
"v",
"not",
... | Add items to options | [
"Add",
"items",
"to",
"options"
] | python | train |
mjirik/imtools | imtools/tools.py | https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/tools.py#L1421-L1451 | def split_to_tiles(img, columns, rows):
"""
Split an image into a specified number of tiles.
Args:
img (ndarray): The image to split.
number_tiles (int): The number of tiles required.
Returns:
Tuple of tiles
"""
# validate_image(img, number_tiles)
im_w, im_h = img.sh... | [
"def",
"split_to_tiles",
"(",
"img",
",",
"columns",
",",
"rows",
")",
":",
"# validate_image(img, number_tiles)",
"im_w",
",",
"im_h",
"=",
"img",
".",
"shape",
"# columns, rows = calc_columns_rows(number_tiles)",
"# extras = (columns * rows) - number_tiles",
"tile_w",
","... | Split an image into a specified number of tiles.
Args:
img (ndarray): The image to split.
number_tiles (int): The number of tiles required.
Returns:
Tuple of tiles | [
"Split",
"an",
"image",
"into",
"a",
"specified",
"number",
"of",
"tiles",
".",
"Args",
":",
"img",
"(",
"ndarray",
")",
":",
"The",
"image",
"to",
"split",
".",
"number_tiles",
"(",
"int",
")",
":",
"The",
"number",
"of",
"tiles",
"required",
".",
"... | python | train |
scivision/pymap3d | pymap3d/lox.py | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/lox.py#L130-L202 | def loxodrome_inverse(lat1: float, lon1: float, lat2: float, lon2: float,
ell: Ellipsoid = None, deg: bool = True):
"""
computes the arc length and azimuth of the loxodrome
between two points on the surface of the reference ellipsoid
Parameters
----------
lat1 : float or ... | [
"def",
"loxodrome_inverse",
"(",
"lat1",
":",
"float",
",",
"lon1",
":",
"float",
",",
"lat2",
":",
"float",
",",
"lon2",
":",
"float",
",",
"ell",
":",
"Ellipsoid",
"=",
"None",
",",
"deg",
":",
"bool",
"=",
"True",
")",
":",
"# set ellipsoid parame... | computes the arc length and azimuth of the loxodrome
between two points on the surface of the reference ellipsoid
Parameters
----------
lat1 : float or numpy.ndarray of float
geodetic latitude of first point
lon1 : float or numpy.ndarray of float
geodetic longitude of first point
... | [
"computes",
"the",
"arc",
"length",
"and",
"azimuth",
"of",
"the",
"loxodrome",
"between",
"two",
"points",
"on",
"the",
"surface",
"of",
"the",
"reference",
"ellipsoid"
] | python | train |
robotools/extractor | Lib/extractor/formats/opentype.py | https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L702-L711 | def _replaceRenamedPairMembers(kerning, leftRename, rightRename):
"""
Populate the renamed pair members into the kerning.
"""
renamedKerning = {}
for (left, right), value in kerning.items():
left = leftRename.get(left, left)
right = rightRename.get(right, right)
renamedKernin... | [
"def",
"_replaceRenamedPairMembers",
"(",
"kerning",
",",
"leftRename",
",",
"rightRename",
")",
":",
"renamedKerning",
"=",
"{",
"}",
"for",
"(",
"left",
",",
"right",
")",
",",
"value",
"in",
"kerning",
".",
"items",
"(",
")",
":",
"left",
"=",
"leftRe... | Populate the renamed pair members into the kerning. | [
"Populate",
"the",
"renamed",
"pair",
"members",
"into",
"the",
"kerning",
"."
] | python | train |
ylogx/universal | universal/builder.py | https://github.com/ylogx/universal/blob/1be04c2e828d9f97a94d48bff64031b14c2b8463/universal/builder.py#L41-L53 | def compile_files(args, mem_test=False):
''' Copiles the files and runs memory tests
if needed.
PARAM args: list of files passed as CMD args
to be compiled.
PARAM mem_test: Weither to perform memory test ?
'''
for filename in args:
if not os.path.isfile(fi... | [
"def",
"compile_files",
"(",
"args",
",",
"mem_test",
"=",
"False",
")",
":",
"for",
"filename",
"in",
"args",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"print",
"(",
"'The file doesn\\'t exits'",
")",
"return",
"buil... | Copiles the files and runs memory tests
if needed.
PARAM args: list of files passed as CMD args
to be compiled.
PARAM mem_test: Weither to perform memory test ? | [
"Copiles",
"the",
"files",
"and",
"runs",
"memory",
"tests",
"if",
"needed",
".",
"PARAM",
"args",
":",
"list",
"of",
"files",
"passed",
"as",
"CMD",
"args",
"to",
"be",
"compiled",
".",
"PARAM",
"mem_test",
":",
"Weither",
"to",
"perform",
"memory",
"te... | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_1/git/git_client_base.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/git/git_client_base.py#L405-L429 | def get_commit(self, commit_id, repository_id, project=None, change_count=None):
"""GetCommit.
[Preview API] Retrieve a particular commit.
:param str commit_id: The id of the commit.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId ... | [
"def",
"get_commit",
"(",
"self",
",",
"commit_id",
",",
"repository_id",
",",
"project",
"=",
"None",
",",
"change_count",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
... | GetCommit.
[Preview API] Retrieve a particular commit.
:param str commit_id: The id of the commit.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param str project: Project ID or project name
:para... | [
"GetCommit",
".",
"[",
"Preview",
"API",
"]",
"Retrieve",
"a",
"particular",
"commit",
".",
":",
"param",
"str",
"commit_id",
":",
"The",
"id",
"of",
"the",
"commit",
".",
":",
"param",
"str",
"repository_id",
":",
"The",
"id",
"or",
"friendly",
"name",
... | python | train |
kylef/refract.py | refract/elements/base.py | https://github.com/kylef/refract.py/blob/f58ddf619038b580ab50c2e7f867d59d153eabbb/refract/elements/base.py#L104-L132 | def defract(self):
"""
Returns the underlying (unrefracted) value of element
>>> Element(content='Hello').defract
'Hello'
>>> Element(content=Element(content='Hello')).defract
'Hello'
>>> Element(content=[Element(content='Hello')]).defract
['Hello']
... | [
"def",
"defract",
"(",
"self",
")",
":",
"from",
"refract",
".",
"elements",
".",
"object",
"import",
"Object",
"def",
"get_value",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"KeyValuePair",
")",
":",
"return",
"(",
"get_value",
"(",
... | Returns the underlying (unrefracted) value of element
>>> Element(content='Hello').defract
'Hello'
>>> Element(content=Element(content='Hello')).defract
'Hello'
>>> Element(content=[Element(content='Hello')]).defract
['Hello'] | [
"Returns",
"the",
"underlying",
"(",
"unrefracted",
")",
"value",
"of",
"element"
] | python | train |
obriencj/python-javatools | javatools/report.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L81-L93 | def add_formats_by_name(self, rfmt_list):
"""
adds formats by short label descriptors, such as 'txt', 'json', or
'html'
"""
for fmt in rfmt_list:
if fmt == "json":
self.add_report_format(JSONReportFormat)
elif fmt in ("txt", "text"):
... | [
"def",
"add_formats_by_name",
"(",
"self",
",",
"rfmt_list",
")",
":",
"for",
"fmt",
"in",
"rfmt_list",
":",
"if",
"fmt",
"==",
"\"json\"",
":",
"self",
".",
"add_report_format",
"(",
"JSONReportFormat",
")",
"elif",
"fmt",
"in",
"(",
"\"txt\"",
",",
"\"te... | adds formats by short label descriptors, such as 'txt', 'json', or
'html' | [
"adds",
"formats",
"by",
"short",
"label",
"descriptors",
"such",
"as",
"txt",
"json",
"or",
"html"
] | python | train |
openthread/openthread | tools/harness-automation/autothreadharness/harness_case.py | https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-automation/autothreadharness/harness_case.py#L262-L285 | def _init_browser(self):
"""Open harness web page.
Open a quiet chrome which:
1. disables extensions,
2. ignore certificate errors and
3. always allow notifications.
"""
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-ext... | [
"def",
"_init_browser",
"(",
"self",
")",
":",
"chrome_options",
"=",
"webdriver",
".",
"ChromeOptions",
"(",
")",
"chrome_options",
".",
"add_argument",
"(",
"'--disable-extensions'",
")",
"chrome_options",
".",
"add_argument",
"(",
"'--disable-infobars'",
")",
"ch... | Open harness web page.
Open a quiet chrome which:
1. disables extensions,
2. ignore certificate errors and
3. always allow notifications. | [
"Open",
"harness",
"web",
"page",
"."
] | python | train |
twisted/axiom | axiom/sequence.py | https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/sequence.py#L40-L60 | def _fixIndex(self, index, truncate=False):
"""
@param truncate: If true, negative indices which go past the
beginning of the list will be evaluated as zero.
For example::
>>> L = List([1,2,3,4,5])
>>> l... | [
"def",
"_fixIndex",
"(",
"self",
",",
"index",
",",
"truncate",
"=",
"False",
")",
":",
"assert",
"not",
"isinstance",
"(",
"index",
",",
"slice",
")",
",",
"'slices are not supported (yet)'",
"if",
"index",
"<",
"0",
":",
"index",
"+=",
"self",
".",
"le... | @param truncate: If true, negative indices which go past the
beginning of the list will be evaluated as zero.
For example::
>>> L = List([1,2,3,4,5])
>>> len(L)
5
>>> L.... | [
"@param",
"truncate",
":",
"If",
"true",
"negative",
"indices",
"which",
"go",
"past",
"the",
"beginning",
"of",
"the",
"list",
"will",
"be",
"evaluated",
"as",
"zero",
".",
"For",
"example",
"::"
] | python | train |
inasafe/inasafe | safe/utilities/settings.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L42-L58 | def set_general_setting(key, value, qsettings=None):
"""Set value to QSettings based on key.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use t... | [
"def",
"set_general_setting",
"(",
"key",
",",
"value",
",",
"qsettings",
"=",
"None",
")",
":",
"if",
"not",
"qsettings",
":",
"qsettings",
"=",
"QSettings",
"(",
")",
"qsettings",
".",
"setValue",
"(",
"key",
",",
"deep_convert_dict",
"(",
"value",
")",
... | Set value to QSettings based on key.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use the default one.
:type qsettings: qgis.PyQt.QtCore.QSetti... | [
"Set",
"value",
"to",
"QSettings",
"based",
"on",
"key",
"."
] | python | train |
helixyte/everest | everest/resources/utils.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/resources/utils.py#L176-L183 | def get_registered_collection_resources():
"""
Returns a list of all registered collection resource classes.
"""
reg = get_current_registry()
return [util.component
for util in reg.registeredUtilities()
if util.name == 'collection-class'] | [
"def",
"get_registered_collection_resources",
"(",
")",
":",
"reg",
"=",
"get_current_registry",
"(",
")",
"return",
"[",
"util",
".",
"component",
"for",
"util",
"in",
"reg",
".",
"registeredUtilities",
"(",
")",
"if",
"util",
".",
"name",
"==",
"'collection-... | Returns a list of all registered collection resource classes. | [
"Returns",
"a",
"list",
"of",
"all",
"registered",
"collection",
"resource",
"classes",
"."
] | python | train |
jaywink/federation | federation/protocols/activitypub/protocol.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L26-L37 | def identify_request(request: RequestType) -> bool:
"""
Try to identify whether this is an ActivityPub request.
"""
# noinspection PyBroadException
try:
data = json.loads(decode_if_bytes(request.body))
if "@context" in data:
return True
except Exception:
pass
... | [
"def",
"identify_request",
"(",
"request",
":",
"RequestType",
")",
"->",
"bool",
":",
"# noinspection PyBroadException",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"decode_if_bytes",
"(",
"request",
".",
"body",
")",
")",
"if",
"\"@context\"",
"in",
... | Try to identify whether this is an ActivityPub request. | [
"Try",
"to",
"identify",
"whether",
"this",
"is",
"an",
"ActivityPub",
"request",
"."
] | python | train |
dylanaraps/pywal | pywal/colors.py | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/colors.py#L86-L94 | def cache_fname(img, backend, light, cache_dir, sat=""):
"""Create the cache file name."""
color_type = "light" if light else "dark"
file_name = re.sub("[/|\\|.]", "_", img)
file_size = os.path.getsize(img)
file_parts = [file_name, color_type, backend,
sat, file_size, __cache_vers... | [
"def",
"cache_fname",
"(",
"img",
",",
"backend",
",",
"light",
",",
"cache_dir",
",",
"sat",
"=",
"\"\"",
")",
":",
"color_type",
"=",
"\"light\"",
"if",
"light",
"else",
"\"dark\"",
"file_name",
"=",
"re",
".",
"sub",
"(",
"\"[/|\\\\|.]\"",
",",
"\"_\"... | Create the cache file name. | [
"Create",
"the",
"cache",
"file",
"name",
"."
] | python | train |
aegirhall/console-menu | consolemenu/prompt_utils.py | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/prompt_utils.py#L116-L130 | def input_password(self, message=None):
"""
Prompt the user for a password. This is equivalent to the input() method, but does not echo inputted
characters to the screen.
:param message: the prompt message.
"""
message = self.__prompt_formatter.format_prompt(message)
... | [
"def",
"input_password",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"message",
"=",
"self",
".",
"__prompt_formatter",
".",
"format_prompt",
"(",
"message",
")",
"try",
":",
"if",
"message",
":",
"return",
"getpass",
".",
"getpass",
"(",
"message"... | Prompt the user for a password. This is equivalent to the input() method, but does not echo inputted
characters to the screen.
:param message: the prompt message. | [
"Prompt",
"the",
"user",
"for",
"a",
"password",
".",
"This",
"is",
"equivalent",
"to",
"the",
"input",
"()",
"method",
"but",
"does",
"not",
"echo",
"inputted",
"characters",
"to",
"the",
"screen",
".",
":",
"param",
"message",
":",
"the",
"prompt",
"me... | python | train |
open-homeautomation/pknx | knxip/core.py | https://github.com/open-homeautomation/pknx/blob/a8aed8271563923c447aa330ba7c1c2927286f7a/knxip/core.py#L141-L162 | def to_frame(self):
"""Convert the object to its frame format."""
self.sanitize()
res = []
res.append((1 << 7) + (1 << 4) + (self.repeat << 5) +
(self.priority << 2))
res.append(self.src_addr >> 8)
res.append(self.src_addr % 0x100)
res.append(se... | [
"def",
"to_frame",
"(",
"self",
")",
":",
"self",
".",
"sanitize",
"(",
")",
"res",
"=",
"[",
"]",
"res",
".",
"append",
"(",
"(",
"1",
"<<",
"7",
")",
"+",
"(",
"1",
"<<",
"4",
")",
"+",
"(",
"self",
".",
"repeat",
"<<",
"5",
")",
"+",
"... | Convert the object to its frame format. | [
"Convert",
"the",
"object",
"to",
"its",
"frame",
"format",
"."
] | python | train |
duguyue100/minesweeper | minesweeper/msboard.py | https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/msboard.py#L144-L155 | def check_board(self):
"""Check the board status and give feedback."""
num_mines = np.sum(self.info_map == 12)
num_undiscovered = np.sum(self.info_map == 11)
num_questioned = np.sum(self.info_map == 10)
if num_mines > 0:
return 0
elif np.array_equal(self.info... | [
"def",
"check_board",
"(",
"self",
")",
":",
"num_mines",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"info_map",
"==",
"12",
")",
"num_undiscovered",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"info_map",
"==",
"11",
")",
"num_questioned",
"=",
"np",
"."... | Check the board status and give feedback. | [
"Check",
"the",
"board",
"status",
"and",
"give",
"feedback",
"."
] | python | train |
Capitains/flask-capitains-nemo | flask_nemo/common.py | https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/common.py#L12-L21 | def resource_qualifier(resource):
""" Split a resource in (filename, directory) tuple with taking care of external resources
:param resource: A file path or a URI
:return: (Filename, Directory) for files, (URI, None) for URI
"""
if resource.startswith("//") or resource.startswith("http"):
r... | [
"def",
"resource_qualifier",
"(",
"resource",
")",
":",
"if",
"resource",
".",
"startswith",
"(",
"\"//\"",
")",
"or",
"resource",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"return",
"resource",
",",
"None",
"else",
":",
"return",
"reversed",
"(",
"op"... | Split a resource in (filename, directory) tuple with taking care of external resources
:param resource: A file path or a URI
:return: (Filename, Directory) for files, (URI, None) for URI | [
"Split",
"a",
"resource",
"in",
"(",
"filename",
"directory",
")",
"tuple",
"with",
"taking",
"care",
"of",
"external",
"resources"
] | python | valid |
slackapi/python-slackclient | tutorial/PythOnBoardingBot/app.py | https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/tutorial/PythOnBoardingBot/app.py#L38-L53 | def onboarding_message(**payload):
"""Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future.
"""
# Get WebClient so you can communicate back to Slack.
web_client = payload["web_client"]
# Get the id of the Sla... | [
"def",
"onboarding_message",
"(",
"*",
"*",
"payload",
")",
":",
"# Get WebClient so you can communicate back to Slack.",
"web_client",
"=",
"payload",
"[",
"\"web_client\"",
"]",
"# Get the id of the Slack user associated with the incoming event",
"user_id",
"=",
"payload",
"[... | Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future. | [
"Create",
"and",
"send",
"an",
"onboarding",
"welcome",
"message",
"to",
"new",
"users",
".",
"Save",
"the",
"time",
"stamp",
"of",
"this",
"message",
"so",
"we",
"can",
"update",
"this",
"message",
"in",
"the",
"future",
"."
] | python | train |
priendeau/UnderscoreX | setup.py | https://github.com/priendeau/UnderscoreX/blob/ac83e13627cfa009dc5731a1fb31f9c6145d983a/setup.py#L68-L82 | def Kargs2Attr( ):
"""
This Decorator Will:
Read **kwargs key and add it to current Object-class ClassTinyDecl under current
name readed from **kwargs key name.
"""
def decorator( func ):
def inner( **kwargs ):
for ItemName in kwargs.keys():
set... | [
"def",
"Kargs2Attr",
"(",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"*",
"kwargs",
")",
":",
"for",
"ItemName",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"setattr",
"(",
"__builtins__",
",",
"ItemName",
",",
"... | This Decorator Will:
Read **kwargs key and add it to current Object-class ClassTinyDecl under current
name readed from **kwargs key name. | [
"This",
"Decorator",
"Will",
":",
"Read",
"**",
"kwargs",
"key",
"and",
"add",
"it",
"to",
"current",
"Object",
"-",
"class",
"ClassTinyDecl",
"under",
"current",
"name",
"readed",
"from",
"**",
"kwargs",
"key",
"name",
"."
] | python | train |
glomex/gcdt | gcdt/iam.py | https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/iam.py#L190-L221 | def build_bucket(self, name, lifecycle_configuration=False,
use_plain_name=False):
"""
Generate S3 bucket statement
:param name: Name of the bucket
:param lifecycle_configuration: Additional lifecycle configuration (default=False)
:param use_plain_name: Just ... | [
"def",
"build_bucket",
"(",
"self",
",",
"name",
",",
"lifecycle_configuration",
"=",
"False",
",",
"use_plain_name",
"=",
"False",
")",
":",
"if",
"use_plain_name",
":",
"name_aws",
"=",
"name_bucket",
"=",
"name",
"name_aws",
"=",
"name_aws",
".",
"title",
... | Generate S3 bucket statement
:param name: Name of the bucket
:param lifecycle_configuration: Additional lifecycle configuration (default=False)
:param use_plain_name: Just use the given name and do not add prefix
:return: Ref to new bucket | [
"Generate",
"S3",
"bucket",
"statement",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"bucket",
":",
"param",
"lifecycle_configuration",
":",
"Additional",
"lifecycle",
"configuration",
"(",
"default",
"=",
"False",
")",
":",
"param",
"use_plain_name",
":",
... | python | train |
rbarrois/mpdlcd | mpdlcd/mpdwrapper.py | https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/mpdwrapper.py#L135-L146 | def get(self, tags):
"""Find an adequate value for this field from a dict of tags."""
# Try to find our name
value = tags.get(self.name, '')
for name in self.alternate_tags:
# Iterate of alternates until a non-empty value is found
value = value or tags.get(name, ... | [
"def",
"get",
"(",
"self",
",",
"tags",
")",
":",
"# Try to find our name",
"value",
"=",
"tags",
".",
"get",
"(",
"self",
".",
"name",
",",
"''",
")",
"for",
"name",
"in",
"self",
".",
"alternate_tags",
":",
"# Iterate of alternates until a non-empty value is... | Find an adequate value for this field from a dict of tags. | [
"Find",
"an",
"adequate",
"value",
"for",
"this",
"field",
"from",
"a",
"dict",
"of",
"tags",
"."
] | python | train |
priestc/moneywagon | moneywagon/tx.py | https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L31-L43 | def from_unit_to_satoshi(self, value, unit='satoshi'):
"""
Convert a value to satoshis. units can be any fiat currency.
By default the unit is satoshi.
"""
if not unit or unit == 'satoshi':
return value
if unit == 'bitcoin' or unit == 'btc':
return... | [
"def",
"from_unit_to_satoshi",
"(",
"self",
",",
"value",
",",
"unit",
"=",
"'satoshi'",
")",
":",
"if",
"not",
"unit",
"or",
"unit",
"==",
"'satoshi'",
":",
"return",
"value",
"if",
"unit",
"==",
"'bitcoin'",
"or",
"unit",
"==",
"'btc'",
":",
"return",
... | Convert a value to satoshis. units can be any fiat currency.
By default the unit is satoshi. | [
"Convert",
"a",
"value",
"to",
"satoshis",
".",
"units",
"can",
"be",
"any",
"fiat",
"currency",
".",
"By",
"default",
"the",
"unit",
"is",
"satoshi",
"."
] | python | train |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L221-L244 | def license(self, key, value):
"""Populate the ``license`` key."""
def _get_license(value):
a_values = force_list(value.get('a'))
oa_licenses = [el for el in a_values if el == 'OA' or el == 'Open Access']
other_licenses = [el for el in a_values if el != 'OA' and el != 'Open Access']
... | [
"def",
"license",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"def",
"_get_license",
"(",
"value",
")",
":",
"a_values",
"=",
"force_list",
"(",
"value",
".",
"get",
"(",
"'a'",
")",
")",
"oa_licenses",
"=",
"[",
"el",
"for",
"el",
"in",
"a_va... | Populate the ``license`` key. | [
"Populate",
"the",
"license",
"key",
"."
] | python | train |
synw/dataswim | dataswim/data/count.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/count.py#L10-L22 | def count_nulls(self, field):
"""
Count the number of null values in a column
"""
try:
n = self.df[field].isnull().sum()
except KeyError:
self.warning("Can not find column", field)
return
except Exception as e:
self.err(e, "... | [
"def",
"count_nulls",
"(",
"self",
",",
"field",
")",
":",
"try",
":",
"n",
"=",
"self",
".",
"df",
"[",
"field",
"]",
".",
"isnull",
"(",
")",
".",
"sum",
"(",
")",
"except",
"KeyError",
":",
"self",
".",
"warning",
"(",
"\"Can not find column\"",
... | Count the number of null values in a column | [
"Count",
"the",
"number",
"of",
"null",
"values",
"in",
"a",
"column"
] | python | train |
limpyd/redis-limpyd | limpyd/collection.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/collection.py#L206-L222 | def _prepare_sort_options(self, has_pk):
"""
Prepare "sort" options to use when calling the collection, depending
on "_sort" and "_sort_limits" attributes
"""
sort_options = {}
if self._sort is not None and not has_pk:
sort_options.update(self._sort)
i... | [
"def",
"_prepare_sort_options",
"(",
"self",
",",
"has_pk",
")",
":",
"sort_options",
"=",
"{",
"}",
"if",
"self",
".",
"_sort",
"is",
"not",
"None",
"and",
"not",
"has_pk",
":",
"sort_options",
".",
"update",
"(",
"self",
".",
"_sort",
")",
"if",
"sel... | Prepare "sort" options to use when calling the collection, depending
on "_sort" and "_sort_limits" attributes | [
"Prepare",
"sort",
"options",
"to",
"use",
"when",
"calling",
"the",
"collection",
"depending",
"on",
"_sort",
"and",
"_sort_limits",
"attributes"
] | python | train |
spulec/moto | moto/ec2/utils.py | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/ec2/utils.py#L204-L240 | def dhcp_configuration_from_querystring(querystring, option=u'DhcpConfiguration'):
"""
turn:
{u'AWSAccessKeyId': [u'the_key'],
u'Action': [u'CreateDhcpOptions'],
u'DhcpConfiguration.1.Key': [u'domain-name'],
u'DhcpConfiguration.1.Value.1': [u'example.com'],
u'DhcpConf... | [
"def",
"dhcp_configuration_from_querystring",
"(",
"querystring",
",",
"option",
"=",
"u'DhcpConfiguration'",
")",
":",
"key_needle",
"=",
"re",
".",
"compile",
"(",
"u'{0}.[0-9]+.Key'",
".",
"format",
"(",
"option",
")",
",",
"re",
".",
"UNICODE",
")",
"respons... | turn:
{u'AWSAccessKeyId': [u'the_key'],
u'Action': [u'CreateDhcpOptions'],
u'DhcpConfiguration.1.Key': [u'domain-name'],
u'DhcpConfiguration.1.Value.1': [u'example.com'],
u'DhcpConfiguration.2.Key': [u'domain-name-servers'],
u'DhcpConfiguration.2.Value.1': [u'10.0.0.... | [
"turn",
":",
"{",
"u",
"AWSAccessKeyId",
":",
"[",
"u",
"the_key",
"]",
"u",
"Action",
":",
"[",
"u",
"CreateDhcpOptions",
"]",
"u",
"DhcpConfiguration",
".",
"1",
".",
"Key",
":",
"[",
"u",
"domain",
"-",
"name",
"]",
"u",
"DhcpConfiguration",
".",
... | python | train |
numenta/htmresearch | htmresearch/frameworks/pytorch/sparse_speech_experiment.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/sparse_speech_experiment.py#L266-L282 | def createOptimizer(self, params, model):
"""
Create a new instance of the optimizer
"""
lr = params["learning_rate"]
print("Creating optimizer with learning rate=", lr)
if params["optimizer"] == "SGD":
optimizer = optim.SGD(model.parameters(), lr=lr,
momentum=p... | [
"def",
"createOptimizer",
"(",
"self",
",",
"params",
",",
"model",
")",
":",
"lr",
"=",
"params",
"[",
"\"learning_rate\"",
"]",
"print",
"(",
"\"Creating optimizer with learning rate=\"",
",",
"lr",
")",
"if",
"params",
"[",
"\"optimizer\"",
"]",
"==",
"\"SG... | Create a new instance of the optimizer | [
"Create",
"a",
"new",
"instance",
"of",
"the",
"optimizer"
] | python | train |
materialsproject/pymatgen | pymatgen/io/phonopy.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/phonopy.py#L174-L190 | def get_ph_bs_symm_line(bands_path, has_nac=False, labels_dict=None):
"""
Creates a pymatgen PhononBandStructure from a band.yaml file.
The labels will be extracted from the dictionary, if present.
If the 'eigenvector' key is found the eigendisplacements will be
calculated according to the formula:... | [
"def",
"get_ph_bs_symm_line",
"(",
"bands_path",
",",
"has_nac",
"=",
"False",
",",
"labels_dict",
"=",
"None",
")",
":",
"return",
"get_ph_bs_symm_line_from_dict",
"(",
"loadfn",
"(",
"bands_path",
")",
",",
"has_nac",
",",
"labels_dict",
")"
] | Creates a pymatgen PhononBandStructure from a band.yaml file.
The labels will be extracted from the dictionary, if present.
If the 'eigenvector' key is found the eigendisplacements will be
calculated according to the formula:
\\exp(2*pi*i*(frac_coords \\dot q) / sqrt(mass) * v
and added to the obj... | [
"Creates",
"a",
"pymatgen",
"PhononBandStructure",
"from",
"a",
"band",
".",
"yaml",
"file",
".",
"The",
"labels",
"will",
"be",
"extracted",
"from",
"the",
"dictionary",
"if",
"present",
".",
"If",
"the",
"eigenvector",
"key",
"is",
"found",
"the",
"eigendi... | python | train |
yyuu/botornado | boto/route53/connection.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/route53/connection.py#L78-L108 | def get_all_hosted_zones(self, start_marker=None, zone_list=None):
"""
Returns a Python data structure with information about all
Hosted Zones defined for the AWS account.
:param int start_marker: start marker to pass when fetching additional
results after a truncated list
... | [
"def",
"get_all_hosted_zones",
"(",
"self",
",",
"start_marker",
"=",
"None",
",",
"zone_list",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"start_marker",
":",
"params",
"=",
"{",
"'marker'",
":",
"start_marker",
"}",
"response",
"=",
"self",
... | Returns a Python data structure with information about all
Hosted Zones defined for the AWS account.
:param int start_marker: start marker to pass when fetching additional
results after a truncated list
:param list zone_list: a HostedZones list to prepend to results | [
"Returns",
"a",
"Python",
"data",
"structure",
"with",
"information",
"about",
"all",
"Hosted",
"Zones",
"defined",
"for",
"the",
"AWS",
"account",
"."
] | python | train |
apache/spark | python/pyspark/context.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/context.py#L568-L579 | def pickleFile(self, name, minPartitions=None):
"""
Load an RDD previously saved using L{RDD.saveAsPickleFile} method.
>>> tmpFile = NamedTemporaryFile(delete=True)
>>> tmpFile.close()
>>> sc.parallelize(range(10)).saveAsPickleFile(tmpFile.name, 5)
>>> sorted(sc.pickleFi... | [
"def",
"pickleFile",
"(",
"self",
",",
"name",
",",
"minPartitions",
"=",
"None",
")",
":",
"minPartitions",
"=",
"minPartitions",
"or",
"self",
".",
"defaultMinPartitions",
"return",
"RDD",
"(",
"self",
".",
"_jsc",
".",
"objectFile",
"(",
"name",
",",
"m... | Load an RDD previously saved using L{RDD.saveAsPickleFile} method.
>>> tmpFile = NamedTemporaryFile(delete=True)
>>> tmpFile.close()
>>> sc.parallelize(range(10)).saveAsPickleFile(tmpFile.name, 5)
>>> sorted(sc.pickleFile(tmpFile.name, 3).collect())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9... | [
"Load",
"an",
"RDD",
"previously",
"saved",
"using",
"L",
"{",
"RDD",
".",
"saveAsPickleFile",
"}",
"method",
"."
] | python | train |
Guake/guake | guake/terminal.py | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/terminal.py#L299-L327 | def button_press(self, terminal, event):
"""Handles the button press event in the terminal widget. If
any match string is caught, another application is open to
handle the matched resource uri.
"""
self.matched_value = ''
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 4... | [
"def",
"button_press",
"(",
"self",
",",
"terminal",
",",
"event",
")",
":",
"self",
".",
"matched_value",
"=",
"''",
"if",
"(",
"Vte",
".",
"MAJOR_VERSION",
",",
"Vte",
".",
"MINOR_VERSION",
")",
">=",
"(",
"0",
",",
"46",
")",
":",
"matched_string",
... | Handles the button press event in the terminal widget. If
any match string is caught, another application is open to
handle the matched resource uri. | [
"Handles",
"the",
"button",
"press",
"event",
"in",
"the",
"terminal",
"widget",
".",
"If",
"any",
"match",
"string",
"is",
"caught",
"another",
"application",
"is",
"open",
"to",
"handle",
"the",
"matched",
"resource",
"uri",
"."
] | python | train |
caseyjlaw/sdmreader | sdmreader/sdmreader.py | https://github.com/caseyjlaw/sdmreader/blob/b6c3498f1915138727819715ee00d2c46353382d/sdmreader/sdmreader.py#L351-L440 | def _parse (self):
"""Parse the BDF mime structure and record the locations of the binary
blobs. Sets up various data fields in the BDFData object."""
feedparser = FeedParser (Message)
binarychunks = {}
sizeinfo = None
headxml = None
self.fp.seek (0, 0)
... | [
"def",
"_parse",
"(",
"self",
")",
":",
"feedparser",
"=",
"FeedParser",
"(",
"Message",
")",
"binarychunks",
"=",
"{",
"}",
"sizeinfo",
"=",
"None",
"headxml",
"=",
"None",
"self",
".",
"fp",
".",
"seek",
"(",
"0",
",",
"0",
")",
"while",
"True",
... | Parse the BDF mime structure and record the locations of the binary
blobs. Sets up various data fields in the BDFData object. | [
"Parse",
"the",
"BDF",
"mime",
"structure",
"and",
"record",
"the",
"locations",
"of",
"the",
"binary",
"blobs",
".",
"Sets",
"up",
"various",
"data",
"fields",
"in",
"the",
"BDFData",
"object",
"."
] | python | train |
ucsb-cs/submit | submit/models.py | https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/models.py#L919-L926 | def get_value(cls, value):
'''Takes the class of the item that we want to
query, along with a potential instance of that class.
If the value is an instance of int or basestring, then
we will treat it like an id for that instance.'''
if isinstance(value, (basestring, int)):
... | [
"def",
"get_value",
"(",
"cls",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"basestring",
",",
"int",
")",
")",
":",
"value",
"=",
"cls",
".",
"fetch_by",
"(",
"id",
"=",
"value",
")",
"return",
"value",
"if",
"isinstance",
... | Takes the class of the item that we want to
query, along with a potential instance of that class.
If the value is an instance of int or basestring, then
we will treat it like an id for that instance. | [
"Takes",
"the",
"class",
"of",
"the",
"item",
"that",
"we",
"want",
"to",
"query",
"along",
"with",
"a",
"potential",
"instance",
"of",
"that",
"class",
".",
"If",
"the",
"value",
"is",
"an",
"instance",
"of",
"int",
"or",
"basestring",
"then",
"we",
"... | python | train |
openstack/horizon | openstack_dashboard/api/neutron.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1795-L1808 | def list_extensions(request):
"""List neutron extensions.
:param request: django request object
"""
neutron_api = neutronclient(request)
try:
extensions_list = neutron_api.list_extensions()
except exceptions.ServiceCatalogException:
return {}
if 'extensions' in extensions_li... | [
"def",
"list_extensions",
"(",
"request",
")",
":",
"neutron_api",
"=",
"neutronclient",
"(",
"request",
")",
"try",
":",
"extensions_list",
"=",
"neutron_api",
".",
"list_extensions",
"(",
")",
"except",
"exceptions",
".",
"ServiceCatalogException",
":",
"return"... | List neutron extensions.
:param request: django request object | [
"List",
"neutron",
"extensions",
"."
] | python | train |
coordt/django-alphabetfilter | alphafilter/templatetags/alphafilter.py | https://github.com/coordt/django-alphabetfilter/blob/a7bc21c0ea985c2021a4668241bf643c615c6c1f/alphafilter/templatetags/alphafilter.py#L13-L35 | def _get_default_letters(model_admin=None):
"""
Returns the set of letters defined in the configuration variable
DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or
list and returns a set.
If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET
attribute and use... | [
"def",
"_get_default_letters",
"(",
"model_admin",
"=",
"None",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"import",
"string",
"default_ltrs",
"=",
"string",
".",
"digits",
"+",
"string",
".",
"ascii_uppercase",
"default_letters",
"=",
"getat... | Returns the set of letters defined in the configuration variable
DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or
list and returns a set.
If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET
attribute and use it instead. | [
"Returns",
"the",
"set",
"of",
"letters",
"defined",
"in",
"the",
"configuration",
"variable",
"DEFAULT_ALPHABET",
".",
"DEFAULT_ALPHABET",
"can",
"be",
"a",
"callable",
"string",
"tuple",
"or",
"list",
"and",
"returns",
"a",
"set",
"."
] | python | train |
hotdoc/hotdoc | hotdoc/core/project.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L151-L160 | def persist(self):
"""
Banana banana
"""
if self.app.dry:
return
for proj in self.subprojects.values():
proj.persist() | [
"def",
"persist",
"(",
"self",
")",
":",
"if",
"self",
".",
"app",
".",
"dry",
":",
"return",
"for",
"proj",
"in",
"self",
".",
"subprojects",
".",
"values",
"(",
")",
":",
"proj",
".",
"persist",
"(",
")"
] | Banana banana | [
"Banana",
"banana"
] | python | train |
LuminosoInsight/ordered-set | ordered_set.py | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L310-L327 | def union(self, *sets):
"""
Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>... | [
"def",
"union",
"(",
"self",
",",
"*",
"sets",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"if",
"isinstance",
"(",
"self",
",",
"OrderedSet",
")",
"else",
"OrderedSet",
"containers",
"=",
"map",
"(",
"list",
",",
"it",
".",
"chain",
"(",
"[",
... | Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>> oset.union([8, 9])
OrderedSet(... | [
"Combines",
"all",
"unique",
"items",
".",
"Each",
"items",
"order",
"is",
"defined",
"by",
"its",
"first",
"appearance",
"."
] | python | train |
MIT-LCP/wfdb-python | wfdb/io/annotation.py | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/annotation.py#L781-L859 | def get_contained_labels(self, inplace=True):
"""
Get the set of unique labels contained in this annotation.
Returns a pandas dataframe or sets the contained_labels
attribute of the object.
Requires the label_store field to be set.
Function will try to use attributes c... | [
"def",
"get_contained_labels",
"(",
"self",
",",
"inplace",
"=",
"True",
")",
":",
"if",
"self",
".",
"custom_labels",
"is",
"not",
"None",
":",
"self",
".",
"check_field",
"(",
"'custom_labels'",
")",
"# Create the label map",
"label_map",
"=",
"ann_label_table... | Get the set of unique labels contained in this annotation.
Returns a pandas dataframe or sets the contained_labels
attribute of the object.
Requires the label_store field to be set.
Function will try to use attributes contained in the order:
1. label_store
2. symbol
... | [
"Get",
"the",
"set",
"of",
"unique",
"labels",
"contained",
"in",
"this",
"annotation",
".",
"Returns",
"a",
"pandas",
"dataframe",
"or",
"sets",
"the",
"contained_labels",
"attribute",
"of",
"the",
"object",
"."
] | python | train |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L424-L461 | def remove(self,
entity_id,
property_uri,
value):
"""Method removes a triple for the given/subject.
Args:
entity_id(string): Fedora Object ID, ideally URI of the subject
property_uri(string):
value(string):
Return... | [
"def",
"remove",
"(",
"self",
",",
"entity_id",
",",
"property_uri",
",",
"value",
")",
":",
"if",
"not",
"entity_id",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"entity_uri",
"=",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"self",
".",
"base_url",
... | Method removes a triple for the given/subject.
Args:
entity_id(string): Fedora Object ID, ideally URI of the subject
property_uri(string):
value(string):
Return:
boolean: True if triple was removed from the object | [
"Method",
"removes",
"a",
"triple",
"for",
"the",
"given",
"/",
"subject",
"."
] | python | train |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/message.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/message.py#L369-L379 | def __pack_message(operation, data):
"""Takes message data and adds a message header based on the operation.
Returns the resultant message string.
"""
request_id = _randint()
message = struct.pack("<i", 16 + len(data))
message += struct.pack("<i", request_id)
message += _ZERO_32 # response... | [
"def",
"__pack_message",
"(",
"operation",
",",
"data",
")",
":",
"request_id",
"=",
"_randint",
"(",
")",
"message",
"=",
"struct",
".",
"pack",
"(",
"\"<i\"",
",",
"16",
"+",
"len",
"(",
"data",
")",
")",
"message",
"+=",
"struct",
".",
"pack",
"("... | Takes message data and adds a message header based on the operation.
Returns the resultant message string. | [
"Takes",
"message",
"data",
"and",
"adds",
"a",
"message",
"header",
"based",
"on",
"the",
"operation",
"."
] | python | train |
dougalsutherland/skl-groups | skl_groups/preprocessing.py | https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/preprocessing.py#L78-L97 | def fit_transform(self, X, y=None, **params):
'''
Fit and transform the stacked points.
Parameters
----------
X : :class:`Features` or list of bag feature arrays
Data to train on and transform.
any other keyword argument :
Passed on as keyword ar... | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"X",
"=",
"as_features",
"(",
"X",
",",
"stack",
"=",
"True",
")",
"X_new",
"=",
"self",
".",
"transformer",
".",
"fit_transform",
"(",
"X",
... | Fit and transform the stacked points.
Parameters
----------
X : :class:`Features` or list of bag feature arrays
Data to train on and transform.
any other keyword argument :
Passed on as keyword arguments to the transformer's ``transform()``.
Returns
... | [
"Fit",
"and",
"transform",
"the",
"stacked",
"points",
"."
] | python | valid |
ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L935-L941 | def sound_pressure(self):
"""
A measurement of the measured sound pressure level, as a
percent. Uses a flat weighting.
"""
self._ensure_mode(self.MODE_DB)
return self.value(0) * self._scale('DB') | [
"def",
"sound_pressure",
"(",
"self",
")",
":",
"self",
".",
"_ensure_mode",
"(",
"self",
".",
"MODE_DB",
")",
"return",
"self",
".",
"value",
"(",
"0",
")",
"*",
"self",
".",
"_scale",
"(",
"'DB'",
")"
] | A measurement of the measured sound pressure level, as a
percent. Uses a flat weighting. | [
"A",
"measurement",
"of",
"the",
"measured",
"sound",
"pressure",
"level",
"as",
"a",
"percent",
".",
"Uses",
"a",
"flat",
"weighting",
"."
] | python | train |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/anchor/holderprover.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/holderprover.py#L149-L199 | async def _sync_revoc_for_proof(self, rr_id: str) -> None:
"""
Pick up tails file reader handle for input revocation registry identifier. If no symbolic
link is present, get the revocation registry definition to retrieve its tails file hash,
then find the tails file and link it.
... | [
"async",
"def",
"_sync_revoc_for_proof",
"(",
"self",
",",
"rr_id",
":",
"str",
")",
"->",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'HolderProver._sync_revoc_for_proof >>> rr_id: %s'",
",",
"rr_id",
")",
"if",
"not",
"ok_rev_reg_id",
"(",
"rr_id",
")",
":",
... | Pick up tails file reader handle for input revocation registry identifier. If no symbolic
link is present, get the revocation registry definition to retrieve its tails file hash,
then find the tails file and link it.
Raise AbsentTails for missing corresponding tails file.
:param rr_id... | [
"Pick",
"up",
"tails",
"file",
"reader",
"handle",
"for",
"input",
"revocation",
"registry",
"identifier",
".",
"If",
"no",
"symbolic",
"link",
"is",
"present",
"get",
"the",
"revocation",
"registry",
"definition",
"to",
"retrieve",
"its",
"tails",
"file",
"ha... | python | train |
ethereum/pyrlp | rlp/sedes/serializable.py | https://github.com/ethereum/pyrlp/blob/bb898f8056da3973204c699621350bf9565e43df/rlp/sedes/serializable.py#L82-L90 | def _eq(left, right):
"""
Equality comparison that allows for equality between tuple and list types
with equivalent elements.
"""
if isinstance(left, (tuple, list)) and isinstance(right, (tuple, list)):
return len(left) == len(right) and all(_eq(*pair) for pair in zip(left, right))
else:... | [
"def",
"_eq",
"(",
"left",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"isinstance",
"(",
"right",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"len",
"(",
"left",
")",
"... | Equality comparison that allows for equality between tuple and list types
with equivalent elements. | [
"Equality",
"comparison",
"that",
"allows",
"for",
"equality",
"between",
"tuple",
"and",
"list",
"types",
"with",
"equivalent",
"elements",
"."
] | python | train |
CodeReclaimers/neat-python | neat/statistics.py | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/statistics.py#L124-L129 | def save_species_count(self, delimiter=' ', filename='speciation.csv'):
""" Log speciation throughout evolution. """
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
for s in self.get_species_sizes():
w.writerow(s) | [
"def",
"save_species_count",
"(",
"self",
",",
"delimiter",
"=",
"' '",
",",
"filename",
"=",
"'speciation.csv'",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"w",
"=",
"csv",
".",
"writer",
"(",
"f",
",",
"delimiter",
... | Log speciation throughout evolution. | [
"Log",
"speciation",
"throughout",
"evolution",
"."
] | python | train |
chrisjrn/registrasion | registrasion/templatetags/registrasion_tags.py | https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/templatetags/registrasion_tags.py#L124-L149 | def sold_out_and_unregistered(context):
''' If the current user is unregistered, returns True if there are no
products in the TICKET_PRODUCT_CATEGORY that are available to that user.
If there *are* products available, the return False.
If the current user *is* registered, then return None (it's not a
... | [
"def",
"sold_out_and_unregistered",
"(",
"context",
")",
":",
"user",
"=",
"user_for_context",
"(",
"context",
")",
"if",
"hasattr",
"(",
"user",
",",
"\"attendee\"",
")",
"and",
"user",
".",
"attendee",
".",
"completed_registration",
":",
"# This user has complet... | If the current user is unregistered, returns True if there are no
products in the TICKET_PRODUCT_CATEGORY that are available to that user.
If there *are* products available, the return False.
If the current user *is* registered, then return None (it's not a
pertinent question for people who already ha... | [
"If",
"the",
"current",
"user",
"is",
"unregistered",
"returns",
"True",
"if",
"there",
"are",
"no",
"products",
"in",
"the",
"TICKET_PRODUCT_CATEGORY",
"that",
"are",
"available",
"to",
"that",
"user",
"."
] | python | test |
sagemath/sage-package | sage_package/sphinx.py | https://github.com/sagemath/sage-package/blob/6e511753fb0667b202f497fc00b763647456a066/sage_package/sphinx.py#L72-L79 | def themes_path():
"""
Retrieve the location of the themes directory from the location of this package
This is taken from Sphinx's theme documentation
"""
package_dir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(package_dir, 'themes') | [
"def",
"themes_path",
"(",
")",
":",
"package_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"package_dir",
",",
"'themes'",
")"
] | Retrieve the location of the themes directory from the location of this package
This is taken from Sphinx's theme documentation | [
"Retrieve",
"the",
"location",
"of",
"the",
"themes",
"directory",
"from",
"the",
"location",
"of",
"this",
"package"
] | python | test |
qweeze/wex-api-client | wex/client.py | https://github.com/qweeze/wex-api-client/blob/e84d139be229aab2c7c5eda5976b812be651807b/wex/client.py#L80-L88 | def ticker(self, pair, ignore_invalid=0):
"""
This method provides all the information about currently active pairs, such as: the maximum price,
the minimum price, average price, trade volume, trade volume in currency, the last trade, Buy and Sell price.
All information is provided over ... | [
"def",
"ticker",
"(",
"self",
",",
"pair",
",",
"ignore_invalid",
"=",
"0",
")",
":",
"return",
"self",
".",
"_public_api_call",
"(",
"'ticker'",
",",
"pair",
"=",
"pair",
",",
"ignore_invalid",
"=",
"ignore_invalid",
")"
] | This method provides all the information about currently active pairs, such as: the maximum price,
the minimum price, average price, trade volume, trade volume in currency, the last trade, Buy and Sell price.
All information is provided over the past 24 hours.
:param str or iterable pair: pair (... | [
"This",
"method",
"provides",
"all",
"the",
"information",
"about",
"currently",
"active",
"pairs",
"such",
"as",
":",
"the",
"maximum",
"price",
"the",
"minimum",
"price",
"average",
"price",
"trade",
"volume",
"trade",
"volume",
"in",
"currency",
"the",
"las... | python | train |
NASA-AMMOS/AIT-Core | ait/core/log.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/log.py#L66-L76 | def formatTime (self, record, datefmt=None):
"""Return the creation time of the specified LogRecord as formatted
text."""
if datefmt is None:
datefmt = '%Y-%m-%d %H:%M:%S'
ct = self.converter(record.created)
t = time.strftime(datefmt, ct)
s = '%s.%03d' % (t... | [
"def",
"formatTime",
"(",
"self",
",",
"record",
",",
"datefmt",
"=",
"None",
")",
":",
"if",
"datefmt",
"is",
"None",
":",
"datefmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
"ct",
"=",
"self",
".",
"converter",
"(",
"record",
".",
"created",
")",
"t",
"=",
"time"... | Return the creation time of the specified LogRecord as formatted
text. | [
"Return",
"the",
"creation",
"time",
"of",
"the",
"specified",
"LogRecord",
"as",
"formatted",
"text",
"."
] | python | train |
rabitt/pysox | sox/transform.py | https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L3026-L3116 | def vad(self, location=1, normalize=True, activity_threshold=7.0,
min_activity_duration=0.25, initial_search_buffer=1.0,
max_gap=0.25, initial_pad=0.0):
'''Voice Activity Detector. Attempts to trim silence and quiet
background sounds from the ends of recordings of speech. The alg... | [
"def",
"vad",
"(",
"self",
",",
"location",
"=",
"1",
",",
"normalize",
"=",
"True",
",",
"activity_threshold",
"=",
"7.0",
",",
"min_activity_duration",
"=",
"0.25",
",",
"initial_search_buffer",
"=",
"1.0",
",",
"max_gap",
"=",
"0.25",
",",
"initial_pad",
... | Voice Activity Detector. Attempts to trim silence and quiet
background sounds from the ends of recordings of speech. The algorithm
currently uses a simple cepstral power measurement to detect voice, so
may be fooled by other things, especially music.
The effect can trim only from the fr... | [
"Voice",
"Activity",
"Detector",
".",
"Attempts",
"to",
"trim",
"silence",
"and",
"quiet",
"background",
"sounds",
"from",
"the",
"ends",
"of",
"recordings",
"of",
"speech",
".",
"The",
"algorithm",
"currently",
"uses",
"a",
"simple",
"cepstral",
"power",
"mea... | python | valid |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/metric.py | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/metric.py#L243-L277 | def data(self):
"""Metric data
Args:
value (:obj:`bool` or :obj:`int` or :obj:`long` or :obj:`float`
or :obj:`basestring` or :obj:`bytes`)
Returns:
value
Raises:
:obj:`TypeError`
"""
if self._data_type == int:
... | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_type",
"==",
"int",
":",
"if",
"self",
".",
"_pb",
".",
"HasField",
"(",
"\"int64_data\"",
")",
":",
"return",
"self",
".",
"_pb",
".",
"int64_data",
"if",
"self",
".",
"_pb",
".",
"Ha... | Metric data
Args:
value (:obj:`bool` or :obj:`int` or :obj:`long` or :obj:`float`
or :obj:`basestring` or :obj:`bytes`)
Returns:
value
Raises:
:obj:`TypeError` | [
"Metric",
"data"
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/directory.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L155-L189 | def collect_metadata_files(cwd, new_files, existing_files):
"""
Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict exist... | [
"def",
"collect_metadata_files",
"(",
"cwd",
",",
"new_files",
",",
"existing_files",
")",
":",
"obj",
"=",
"{",
"}",
"try",
":",
"os",
".",
"chdir",
"(",
"cwd",
")",
"# Special case: User uses gui to mult-select 2+ files. You'll be given a list of file paths.",
"if",
... | Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict existing_files: Files currently loaded, separated by type
:return list: A... | [
"Collect",
"all",
"files",
"from",
"a",
"given",
"path",
".",
"Separate",
"by",
"file",
"type",
"and",
"return",
"one",
"list",
"for",
"each",
"type",
"If",
"files",
"contains",
"specific",
":",
"param",
"str",
"cwd",
":",
"Directory",
"w",
"/",
"target"... | python | train |
getfleety/coralillo | coralillo/hashing.py | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/hashing.py#L146-L153 | def mask_hash(hash, show=6, char="*"):
"""
Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons.
"""
masked = hash[:show]
masked += char * len(hash[show:])
return masked | [
"def",
"mask_hash",
"(",
"hash",
",",
"show",
"=",
"6",
",",
"char",
"=",
"\"*\"",
")",
":",
"masked",
"=",
"hash",
"[",
":",
"show",
"]",
"masked",
"+=",
"char",
"*",
"len",
"(",
"hash",
"[",
"show",
":",
"]",
")",
"return",
"masked"
] | Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons. | [
"Return",
"the",
"given",
"hash",
"with",
"only",
"the",
"first",
"show",
"number",
"shown",
".",
"The",
"rest",
"are",
"masked",
"with",
"char",
"for",
"security",
"reasons",
"."
] | python | train |
adrianliaw/PyCuber | pycuber/solver/cfop/cross.py | https://github.com/adrianliaw/PyCuber/blob/e44b5ba48c831b964ce73d046fb813222771853f/pycuber/solver/cfop/cross.py#L82-L144 | def cross_state_value(state):
"""
Compute the state value of the cross solving search.
"""
centres, edges = state
value = 0
for edge in edges:
if "U" in edge:
if edge["U"] == centres["D"]["D"]:
value += 1
els... | [
"def",
"cross_state_value",
"(",
"state",
")",
":",
"centres",
",",
"edges",
"=",
"state",
"value",
"=",
"0",
"for",
"edge",
"in",
"edges",
":",
"if",
"\"U\"",
"in",
"edge",
":",
"if",
"edge",
"[",
"\"U\"",
"]",
"==",
"centres",
"[",
"\"D\"",
"]",
... | Compute the state value of the cross solving search. | [
"Compute",
"the",
"state",
"value",
"of",
"the",
"cross",
"solving",
"search",
"."
] | python | train |
saltstack/salt | salt/modules/nilrt_ip.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L85-L94 | def _get_state():
'''
Returns the state of connman
'''
try:
return pyconnman.ConnManager().get_property('State')
except KeyError:
return 'offline'
except dbus.DBusException as exc:
raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) | [
"def",
"_get_state",
"(",
")",
":",
"try",
":",
"return",
"pyconnman",
".",
"ConnManager",
"(",
")",
".",
"get_property",
"(",
"'State'",
")",
"except",
"KeyError",
":",
"return",
"'offline'",
"except",
"dbus",
".",
"DBusException",
"as",
"exc",
":",
"rais... | Returns the state of connman | [
"Returns",
"the",
"state",
"of",
"connman"
] | python | train |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L174-L194 | def register(self, server_info):
"""Register attributes that can be computed with the server info."""
# Path relative to the server directory
self.path = os.path.relpath(self.filename,
start=server_info['notebook_dir'])
# Replace backslashes on Window... | [
"def",
"register",
"(",
"self",
",",
"server_info",
")",
":",
"# Path relative to the server directory",
"self",
".",
"path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"self",
".",
"filename",
",",
"start",
"=",
"server_info",
"[",
"'notebook_dir'",
"]",
... | Register attributes that can be computed with the server info. | [
"Register",
"attributes",
"that",
"can",
"be",
"computed",
"with",
"the",
"server",
"info",
"."
] | python | train |
zblz/naima | naima/plot.py | https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L1282-L1376 | def plot_data(
input_data,
xlabel=None,
ylabel=None,
sed=True,
figure=None,
e_unit=None,
ulim_opts={},
errorbar_opts={},
):
"""
Plot spectral data.
Parameters
----------
input_data : `emcee.EnsembleSampler`, `astropy.table.Table`, or `dict`
Spectral data to p... | [
"def",
"plot_data",
"(",
"input_data",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",",
"sed",
"=",
"True",
",",
"figure",
"=",
"None",
",",
"e_unit",
"=",
"None",
",",
"ulim_opts",
"=",
"{",
"}",
",",
"errorbar_opts",
"=",
"{",
"}",
",... | Plot spectral data.
Parameters
----------
input_data : `emcee.EnsembleSampler`, `astropy.table.Table`, or `dict`
Spectral data to plot. Can be given as a data table, a dict generated
with `validate_data_table` or a `emcee.EnsembleSampler` with a data
property.
xlabel : str, opti... | [
"Plot",
"spectral",
"data",
"."
] | python | train |
rlisagor/freshen | freshen/stepregistry.py | https://github.com/rlisagor/freshen/blob/5578f7368e8d53b4cf51c589fb192090d3524968/freshen/stepregistry.py#L250-L263 | def hook_decorator(cb_type):
""" Decorator to wrap hook definitions in. Registers hook. """
def decorator_wrapper(*tags_or_func):
if len(tags_or_func) == 1 and callable(tags_or_func[0]):
# No tags were passed to this decorator
func = tags_or_func[0]
return HookImpl(cb... | [
"def",
"hook_decorator",
"(",
"cb_type",
")",
":",
"def",
"decorator_wrapper",
"(",
"*",
"tags_or_func",
")",
":",
"if",
"len",
"(",
"tags_or_func",
")",
"==",
"1",
"and",
"callable",
"(",
"tags_or_func",
"[",
"0",
"]",
")",
":",
"# No tags were passed to th... | Decorator to wrap hook definitions in. Registers hook. | [
"Decorator",
"to",
"wrap",
"hook",
"definitions",
"in",
".",
"Registers",
"hook",
"."
] | python | train |
pennersr/django-allauth | allauth/account/adapter.py | https://github.com/pennersr/django-allauth/blob/f70cb3d622f992f15fe9b57098e0b328445b664e/allauth/account/adapter.py#L139-L153 | def get_login_redirect_url(self, request):
"""
Returns the default URL to redirect to after logging in. Note
that URLs passed explicitly (e.g. by passing along a `next`
GET parameter) take precedence over the value returned here.
"""
assert request.user.is_authenticated
... | [
"def",
"get_login_redirect_url",
"(",
"self",
",",
"request",
")",
":",
"assert",
"request",
".",
"user",
".",
"is_authenticated",
"url",
"=",
"getattr",
"(",
"settings",
",",
"\"LOGIN_REDIRECT_URLNAME\"",
",",
"None",
")",
"if",
"url",
":",
"warnings",
".",
... | Returns the default URL to redirect to after logging in. Note
that URLs passed explicitly (e.g. by passing along a `next`
GET parameter) take precedence over the value returned here. | [
"Returns",
"the",
"default",
"URL",
"to",
"redirect",
"to",
"after",
"logging",
"in",
".",
"Note",
"that",
"URLs",
"passed",
"explicitly",
"(",
"e",
".",
"g",
".",
"by",
"passing",
"along",
"a",
"next",
"GET",
"parameter",
")",
"take",
"precedence",
"ove... | python | train |
spotify/luigi | luigi/tools/range.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L316-L321 | def parameters_to_datetime(self, p):
"""
Given a dictionary of parameters, will extract the ranged task parameter value
"""
dt = p[self._param_name]
return datetime(dt.year, dt.month, dt.day) | [
"def",
"parameters_to_datetime",
"(",
"self",
",",
"p",
")",
":",
"dt",
"=",
"p",
"[",
"self",
".",
"_param_name",
"]",
"return",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
")"
] | Given a dictionary of parameters, will extract the ranged task parameter value | [
"Given",
"a",
"dictionary",
"of",
"parameters",
"will",
"extract",
"the",
"ranged",
"task",
"parameter",
"value"
] | python | train |
fossasia/knittingpattern | knittingpattern/convert/KnittingPatternToSVG.py | https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/KnittingPatternToSVG.py#L74-L97 | def _register_instruction_in_defs(self, instruction):
"""Create a definition for the instruction.
:return: the id of a symbol in the defs for the specified
:paramref:`instruction`
:rtype: str
If no symbol yet exists in the defs for the :paramref:`instruction` a
symbol... | [
"def",
"_register_instruction_in_defs",
"(",
"self",
",",
"instruction",
")",
":",
"type_",
"=",
"instruction",
".",
"type",
"color_",
"=",
"instruction",
".",
"color",
"instruction_to_svg_dict",
"=",
"self",
".",
"_instruction_to_svg",
".",
"instruction_to_svg_dict",... | Create a definition for the instruction.
:return: the id of a symbol in the defs for the specified
:paramref:`instruction`
:rtype: str
If no symbol yet exists in the defs for the :paramref:`instruction` a
symbol is created and saved using :meth:`_make_symbol`. | [
"Create",
"a",
"definition",
"for",
"the",
"instruction",
"."
] | python | valid |
Seeed-Studio/wio-cli | wio/commands/cmd_state.py | https://github.com/Seeed-Studio/wio-cli/blob/ce83f4c2d30be7f72d1a128acd123dfc5effa563/wio/commands/cmd_state.py#L6-L34 | def cli(wio):
'''
Login state.
\b
DOES:
Display login email, token, server url.
\b
USE:
wio state
'''
user_token = wio.config.get("token", None)
mserver_url = wio.config.get("mserver", None)
if not mserver_url or not user_token:
click.echo(click.style('>... | [
"def",
"cli",
"(",
"wio",
")",
":",
"user_token",
"=",
"wio",
".",
"config",
".",
"get",
"(",
"\"token\"",
",",
"None",
")",
"mserver_url",
"=",
"wio",
".",
"config",
".",
"get",
"(",
"\"mserver\"",
",",
"None",
")",
"if",
"not",
"mserver_url",
"or",... | Login state.
\b
DOES:
Display login email, token, server url.
\b
USE:
wio state | [
"Login",
"state",
"."
] | python | train |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1637-L1666 | def plot_evec(fignum, Vs, symsize, title):
"""
plots eigenvector directions of S vectors
Paramters
________
fignum : matplotlib figure number
Vs : nested list of eigenvectors
symsize : size in pts for symbol
title : title for plot
"""
#
plt.figure(num=fignum)
plt.text(-1.1, ... | [
"def",
"plot_evec",
"(",
"fignum",
",",
"Vs",
",",
"symsize",
",",
"title",
")",
":",
"#",
"plt",
".",
"figure",
"(",
"num",
"=",
"fignum",
")",
"plt",
".",
"text",
"(",
"-",
"1.1",
",",
"1.15",
",",
"title",
")",
"# plot V1s as squares, V2s as triangl... | plots eigenvector directions of S vectors
Paramters
________
fignum : matplotlib figure number
Vs : nested list of eigenvectors
symsize : size in pts for symbol
title : title for plot | [
"plots",
"eigenvector",
"directions",
"of",
"S",
"vectors"
] | python | train |
slundberg/shap | shap/benchmark/models.py | https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/models.py#L133-L141 | def cric__lasso():
""" Lasso Regression
"""
model = sklearn.linear_model.LogisticRegression(penalty="l1", C=0.002)
# we want to explain the raw probability outputs of the trees
model.predict = lambda X: model.predict_proba(X)[:,1]
return model | [
"def",
"cric__lasso",
"(",
")",
":",
"model",
"=",
"sklearn",
".",
"linear_model",
".",
"LogisticRegression",
"(",
"penalty",
"=",
"\"l1\"",
",",
"C",
"=",
"0.002",
")",
"# we want to explain the raw probability outputs of the trees",
"model",
".",
"predict",
"=",
... | Lasso Regression | [
"Lasso",
"Regression"
] | python | train |
materialsproject/pymatgen | pymatgen/io/feff/inputs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/feff/inputs.py#L925-L941 | def get_absorbing_atom_symbol_index(absorbing_atom, structure):
"""
Return the absorbing atom symboll and site index in the given structure.
Args:
absorbing_atom (str/int): symbol or site index
structure (Structure)
Returns:
str, int: symbol and site index
"""
if isinst... | [
"def",
"get_absorbing_atom_symbol_index",
"(",
"absorbing_atom",
",",
"structure",
")",
":",
"if",
"isinstance",
"(",
"absorbing_atom",
",",
"str",
")",
":",
"return",
"absorbing_atom",
",",
"structure",
".",
"indices_from_symbol",
"(",
"absorbing_atom",
")",
"[",
... | Return the absorbing atom symboll and site index in the given structure.
Args:
absorbing_atom (str/int): symbol or site index
structure (Structure)
Returns:
str, int: symbol and site index | [
"Return",
"the",
"absorbing",
"atom",
"symboll",
"and",
"site",
"index",
"in",
"the",
"given",
"structure",
"."
] | python | train |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiV4As.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiV4As.py#L36-L49 | def search(self, **kwargs):
"""
Method to search asns based on extends search.
:param search: Dict containing QuerySets to find asns.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fi... | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ApiV4As",
",",
"self",
")",
".",
"get",
"(",
"self",
".",
"prepare_url",
"(",
"'api/v4/as/'",
",",
"kwargs",
")",
")"
] | Method to search asns based on extends search.
:param search: Dict containing QuerySets to find asns.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override defau... | [
"Method",
"to",
"search",
"asns",
"based",
"on",
"extends",
"search",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.