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 |
|---|---|---|---|---|---|---|---|---|
bokeh/bokeh | bokeh/io/showing.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/showing.py#L46-L145 | def show(obj, browser=None, new="tab", notebook_handle=False, notebook_url="localhost:8888", **kw):
''' Immediately display a Bokeh object or application.
:func:`show` may be called multiple times in a single Jupyter notebook
cell to display multiple objects. The objects are displayed in order.
... | [
"def",
"show",
"(",
"obj",
",",
"browser",
"=",
"None",
",",
"new",
"=",
"\"tab\"",
",",
"notebook_handle",
"=",
"False",
",",
"notebook_url",
"=",
"\"localhost:8888\"",
",",
"*",
"*",
"kw",
")",
":",
"state",
"=",
"curstate",
"(",
")",
"is_application",... | Immediately display a Bokeh object or application.
:func:`show` may be called multiple times in a single Jupyter notebook
cell to display multiple objects. The objects are displayed in order.
Args:
obj (LayoutDOM or Application or callable) :
A Bokeh object to display.
... | [
"Immediately",
"display",
"a",
"Bokeh",
"object",
"or",
"application",
"."
] | python | train |
marrow/WebCore | web/server/cherrypy_.py | https://github.com/marrow/WebCore/blob/38d50f8022ca62976a1e5ff23f7714bd647b6532/web/server/cherrypy_.py#L14-L27 | def serve(application, host='127.0.0.1', port=8080):
"""CherryPy-based WSGI-HTTP server."""
# Instantiate the server with our configuration and application.
server = CherryPyWSGIServer((host, int(port)), application, server_name=host)
# Try to be handy as many terminals allow clicking links.
print("serving on ... | [
"def",
"serve",
"(",
"application",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8080",
")",
":",
"# Instantiate the server with our configuration and application.",
"server",
"=",
"CherryPyWSGIServer",
"(",
"(",
"host",
",",
"int",
"(",
"port",
")",
")",
... | CherryPy-based WSGI-HTTP server. | [
"CherryPy",
"-",
"based",
"WSGI",
"-",
"HTTP",
"server",
"."
] | python | train |
raymondEhlers/pachyderm | pachyderm/generic_config.py | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/generic_config.py#L451-L466 | def iterate_with_selected_objects(analysis_objects: Mapping[Any, Any], **selections: Mapping[str, Any]) -> Iterator[Tuple[Any, Any]]:
""" Iterate over an analysis dictionary with selected attributes.
Args:
analysis_objects: Analysis objects dictionary.
selections: Keyword arguments used to sele... | [
"def",
"iterate_with_selected_objects",
"(",
"analysis_objects",
":",
"Mapping",
"[",
"Any",
",",
"Any",
"]",
",",
"*",
"*",
"selections",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
"]... | Iterate over an analysis dictionary with selected attributes.
Args:
analysis_objects: Analysis objects dictionary.
selections: Keyword arguments used to select attributes from the analysis dictionary.
Yields:
object: Matching analysis object. | [
"Iterate",
"over",
"an",
"analysis",
"dictionary",
"with",
"selected",
"attributes",
"."
] | python | train |
improbable-research/keanu | keanu-python/keanu/vertex/generated.py | https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/vertex/generated.py#L347-L354 | def Multiplication(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Multiplies one vertex by another
:param left: vertex to be multiplied
:param right: vertex to be multiplied
"""
return Double(context.jvm_view().Multipli... | [
"def",
"Multiplication",
"(",
"left",
":",
"vertex_constructor_param_types",
",",
"right",
":",
"vertex_constructor_param_types",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Vertex",
":",
"return",
"Double",
"(",
"context",
".",
"j... | Multiplies one vertex by another
:param left: vertex to be multiplied
:param right: vertex to be multiplied | [
"Multiplies",
"one",
"vertex",
"by",
"another",
":",
"param",
"left",
":",
"vertex",
"to",
"be",
"multiplied",
":",
"param",
"right",
":",
"vertex",
"to",
"be",
"multiplied"
] | python | train |
pandas-dev/pandas | pandas/io/excel/_util.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/excel/_util.py#L89-L119 | def _range2cols(areas):
"""
Convert comma separated list of column names and ranges to indices.
Parameters
----------
areas : str
A string containing a sequence of column ranges (or areas).
Returns
-------
cols : list
A list of 0-based column indices.
Examples
... | [
"def",
"_range2cols",
"(",
"areas",
")",
":",
"cols",
"=",
"[",
"]",
"for",
"rng",
"in",
"areas",
".",
"split",
"(",
"\",\"",
")",
":",
"if",
"\":\"",
"in",
"rng",
":",
"rng",
"=",
"rng",
".",
"split",
"(",
"\":\"",
")",
"cols",
".",
"extend",
... | Convert comma separated list of column names and ranges to indices.
Parameters
----------
areas : str
A string containing a sequence of column ranges (or areas).
Returns
-------
cols : list
A list of 0-based column indices.
Examples
--------
>>> _range2cols('A:E')
... | [
"Convert",
"comma",
"separated",
"list",
"of",
"column",
"names",
"and",
"ranges",
"to",
"indices",
"."
] | python | train |
pyviz/holoviews | holoviews/plotting/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/util.py#L194-L204 | def is_dynamic_overlay(dmap):
"""
Traverses a DynamicMap graph and determines if any components
were overlaid dynamically (i.e. by * on a DynamicMap).
"""
if not isinstance(dmap, DynamicMap):
return False
elif dmap.callback._is_overlay:
return True
else:
return any(is... | [
"def",
"is_dynamic_overlay",
"(",
"dmap",
")",
":",
"if",
"not",
"isinstance",
"(",
"dmap",
",",
"DynamicMap",
")",
":",
"return",
"False",
"elif",
"dmap",
".",
"callback",
".",
"_is_overlay",
":",
"return",
"True",
"else",
":",
"return",
"any",
"(",
"is... | Traverses a DynamicMap graph and determines if any components
were overlaid dynamically (i.e. by * on a DynamicMap). | [
"Traverses",
"a",
"DynamicMap",
"graph",
"and",
"determines",
"if",
"any",
"components",
"were",
"overlaid",
"dynamically",
"(",
"i",
".",
"e",
".",
"by",
"*",
"on",
"a",
"DynamicMap",
")",
"."
] | python | train |
RJT1990/pyflux | pyflux/inference/metropolis_hastings.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/metropolis_hastings.py#L66-L100 | def tune_scale(acceptance, scale):
""" Tunes scale for M-H algorithm
Parameters
----------
acceptance : float
The most recent acceptance rate
scale : float
The current scale parameter
Returns
----------
scale : float
... | [
"def",
"tune_scale",
"(",
"acceptance",
",",
"scale",
")",
":",
"if",
"acceptance",
">",
"0.8",
":",
"scale",
"*=",
"2.0",
"elif",
"acceptance",
"<=",
"0.8",
"and",
"acceptance",
">",
"0.4",
":",
"scale",
"*=",
"1.3",
"elif",
"acceptance",
"<",
"0.234",
... | Tunes scale for M-H algorithm
Parameters
----------
acceptance : float
The most recent acceptance rate
scale : float
The current scale parameter
Returns
----------
scale : float
An adjusted scale parameter
Notes
... | [
"Tunes",
"scale",
"for",
"M",
"-",
"H",
"algorithm"
] | python | train |
numenta/nupic | src/nupic/encoders/date.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/date.py#L274-L349 | def getEncodedValues(self, input):
""" See method description in base.py """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
return numpy.array([None])
assert isinstance(input, datetime.datetime)
values = []
# -------------------------------------------------------------------------
# Get ... | [
"def",
"getEncodedValues",
"(",
"self",
",",
"input",
")",
":",
"if",
"input",
"==",
"SENTINEL_VALUE_FOR_MISSING_DATA",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"None",
"]",
")",
"assert",
"isinstance",
"(",
"input",
",",
"datetime",
".",
"datetime",
... | See method description in base.py | [
"See",
"method",
"description",
"in",
"base",
".",
"py"
] | python | valid |
sorgerlab/indra | indra/sources/geneways/find_full_text_sentence.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/find_full_text_sentence.py#L142-L169 | def sentence_matches(self, sentence_text):
"""Returns true iff the sentence contains this mention's upstream
and downstream participants, and if one of the stemmed verbs in
the sentence is the same as the stemmed action type."""
has_upstream = False
has_downstream = False
... | [
"def",
"sentence_matches",
"(",
"self",
",",
"sentence_text",
")",
":",
"has_upstream",
"=",
"False",
"has_downstream",
"=",
"False",
"has_verb",
"=",
"False",
"# Get the first word of the action type and assume this is the verb",
"# (Ex. get depends for depends on)",
"actionty... | Returns true iff the sentence contains this mention's upstream
and downstream participants, and if one of the stemmed verbs in
the sentence is the same as the stemmed action type. | [
"Returns",
"true",
"iff",
"the",
"sentence",
"contains",
"this",
"mention",
"s",
"upstream",
"and",
"downstream",
"participants",
"and",
"if",
"one",
"of",
"the",
"stemmed",
"verbs",
"in",
"the",
"sentence",
"is",
"the",
"same",
"as",
"the",
"stemmed",
"acti... | python | train |
fermiPy/fermipy | fermipy/gtanalysis.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtanalysis.py#L511-L549 | def create(cls, infile, config=None, params=None, mask=None):
"""Create a new instance of GTAnalysis from an analysis output file
generated with `~fermipy.GTAnalysis.write_roi`. By default
the new instance will inherit the configuration of the saved
analysis instance. The configuration... | [
"def",
"create",
"(",
"cls",
",",
"infile",
",",
"config",
"=",
"None",
",",
"params",
"=",
"None",
",",
"mask",
"=",
"None",
")",
":",
"infile",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"infile",
")",
"roi_file",
",",
"roi_data",
"=",
"utils",... | Create a new instance of GTAnalysis from an analysis output file
generated with `~fermipy.GTAnalysis.write_roi`. By default
the new instance will inherit the configuration of the saved
analysis instance. The configuration may be overriden by
passing a configuration file path with the `... | [
"Create",
"a",
"new",
"instance",
"of",
"GTAnalysis",
"from",
"an",
"analysis",
"output",
"file",
"generated",
"with",
"~fermipy",
".",
"GTAnalysis",
".",
"write_roi",
".",
"By",
"default",
"the",
"new",
"instance",
"will",
"inherit",
"the",
"configuration",
"... | python | train |
SoCo/SoCo | soco/groups.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/groups.py#L106-L116 | def short_label(self):
"""str: A short description of the group.
>>> device.group.short_label
'Kitchen + 1'
"""
group_names = sorted([m.player_name for m in self.members])
group_label = group_names[0]
if len(group_names) > 1:
group_label += " + {}".fo... | [
"def",
"short_label",
"(",
"self",
")",
":",
"group_names",
"=",
"sorted",
"(",
"[",
"m",
".",
"player_name",
"for",
"m",
"in",
"self",
".",
"members",
"]",
")",
"group_label",
"=",
"group_names",
"[",
"0",
"]",
"if",
"len",
"(",
"group_names",
")",
... | str: A short description of the group.
>>> device.group.short_label
'Kitchen + 1' | [
"str",
":",
"A",
"short",
"description",
"of",
"the",
"group",
"."
] | python | train |
pypyr/pypyr-cli | pypyr/utils/filesystem.py | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L56-L156 | def files_in_to_out(self, in_path, out_path=None):
"""Write in files to out, calling the line_handler on each line.
Calls file_in_to_out under the hood to format the in_path payload. The
formatting processing is done by the self.formatter instance.
Args:
in_path: str, path-... | [
"def",
"files_in_to_out",
"(",
"self",
",",
"in_path",
",",
"out_path",
"=",
"None",
")",
":",
"in_paths",
"=",
"get_glob",
"(",
"in_path",
")",
"in_count",
"=",
"len",
"(",
"in_paths",
")",
"if",
"in_count",
"==",
"0",
":",
"logger",
".",
"debug",
"("... | Write in files to out, calling the line_handler on each line.
Calls file_in_to_out under the hood to format the in_path payload. The
formatting processing is done by the self.formatter instance.
Args:
in_path: str, path-like, or an iterable (list/tuple) of
stri... | [
"Write",
"in",
"files",
"to",
"out",
"calling",
"the",
"line_handler",
"on",
"each",
"line",
"."
] | python | train |
jorgeecardona/dynect | dynect/__init__.py | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L242-L251 | def add_address(self, fqdn, address, ttl=0):
" Add a new address to a domain."
data = {'rdata': {'address': address}, 'ttl': str(ttl)}
# Make request.
response = self.post('/REST/ARecord/%s/%s' % (
self.zone, fqdn), data=data)
return Address(self, data=response.con... | [
"def",
"add_address",
"(",
"self",
",",
"fqdn",
",",
"address",
",",
"ttl",
"=",
"0",
")",
":",
"data",
"=",
"{",
"'rdata'",
":",
"{",
"'address'",
":",
"address",
"}",
",",
"'ttl'",
":",
"str",
"(",
"ttl",
")",
"}",
"# Make request.",
"response",
... | Add a new address to a domain. | [
"Add",
"a",
"new",
"address",
"to",
"a",
"domain",
"."
] | python | train |
adamcharnock/django-hordak | hordak/models/core.py | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L366-L370 | def sum_to_balance(self):
"""Sum the Legs of the QuerySet to get a `Balance`_ object
"""
result = self.values("amount_currency").annotate(total=models.Sum("amount"))
return Balance([Money(r["total"], r["amount_currency"]) for r in result]) | [
"def",
"sum_to_balance",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"values",
"(",
"\"amount_currency\"",
")",
".",
"annotate",
"(",
"total",
"=",
"models",
".",
"Sum",
"(",
"\"amount\"",
")",
")",
"return",
"Balance",
"(",
"[",
"Money",
"(",
"... | Sum the Legs of the QuerySet to get a `Balance`_ object | [
"Sum",
"the",
"Legs",
"of",
"the",
"QuerySet",
"to",
"get",
"a",
"Balance",
"_",
"object"
] | python | train |
JasonKessler/scattertext | scattertext/features/PhraseMachinePhrases.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/features/PhraseMachinePhrases.py#L12-L25 | def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Doc
Returns
-------
Counter noun chunk -> count
'''
ngram_counter = Counter()
for sent in doc.sents:
ngram_counter += _phrase_counts(sent)
return ngram_counter | [
"def",
"get_feats",
"(",
"self",
",",
"doc",
")",
":",
"ngram_counter",
"=",
"Counter",
"(",
")",
"for",
"sent",
"in",
"doc",
".",
"sents",
":",
"ngram_counter",
"+=",
"_phrase_counts",
"(",
"sent",
")",
"return",
"ngram_counter"
] | Parameters
----------
doc, Spacy Doc
Returns
-------
Counter noun chunk -> count | [
"Parameters",
"----------",
"doc",
"Spacy",
"Doc"
] | python | train |
streamlink/streamlink | src/streamlink/plugins/crunchyroll.py | https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugins/crunchyroll.py#L222-L239 | def get_info(self, media_id, fields=None, schema=None):
"""
Returns the data for a certain media item.
:param media_id: id that identifies the media item to be accessed.
:param fields: list of the media"s field to be returned. By default the
API returns some fiel... | [
"def",
"get_info",
"(",
"self",
",",
"media_id",
",",
"fields",
"=",
"None",
",",
"schema",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"media_id\"",
":",
"media_id",
"}",
"if",
"fields",
":",
"params",
"[",
"\"fields\"",
"]",
"=",
"\",\"",
".",
"jo... | Returns the data for a certain media item.
:param media_id: id that identifies the media item to be accessed.
:param fields: list of the media"s field to be returned. By default the
API returns some fields, but others are not returned unless they are
explicity asked for.... | [
"Returns",
"the",
"data",
"for",
"a",
"certain",
"media",
"item",
"."
] | python | test |
Komnomnomnom/swigibpy | swigibpy.py | https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L2591-L2593 | def realtimeBar(self, reqId, time, open, high, low, close, volume, wap, count):
"""realtimeBar(EWrapper self, TickerId reqId, long time, double open, double high, double low, double close, long volume, double wap, int count)"""
return _swigibpy.EWrapper_realtimeBar(self, reqId, time, open, high, low, cl... | [
"def",
"realtimeBar",
"(",
"self",
",",
"reqId",
",",
"time",
",",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"volume",
",",
"wap",
",",
"count",
")",
":",
"return",
"_swigibpy",
".",
"EWrapper_realtimeBar",
"(",
"self",
",",
"reqId",
",",
"... | realtimeBar(EWrapper self, TickerId reqId, long time, double open, double high, double low, double close, long volume, double wap, int count) | [
"realtimeBar",
"(",
"EWrapper",
"self",
"TickerId",
"reqId",
"long",
"time",
"double",
"open",
"double",
"high",
"double",
"low",
"double",
"close",
"long",
"volume",
"double",
"wap",
"int",
"count",
")"
] | python | train |
PyconUK/ConferenceScheduler | src/conference_scheduler/scheduler.py | https://github.com/PyconUK/ConferenceScheduler/blob/fb139f0ef2eab5ac8f4919aa4994d94d4e040030/src/conference_scheduler/scheduler.py#L31-L102 | def heuristic(events,
slots,
objective_function=None,
algorithm=heu.hill_climber,
initial_solution=None,
initial_solution_algorithm_kwargs={},
objective_function_algorithm_kwargs={},
**kwargs):
"""
Compute a schedu... | [
"def",
"heuristic",
"(",
"events",
",",
"slots",
",",
"objective_function",
"=",
"None",
",",
"algorithm",
"=",
"heu",
".",
"hill_climber",
",",
"initial_solution",
"=",
"None",
",",
"initial_solution_algorithm_kwargs",
"=",
"{",
"}",
",",
"objective_function_algo... | Compute a schedule using a heuristic
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
algorithm : callable
a heuristic algorithm from conference_scheduler.heuristics
initial... | [
"Compute",
"a",
"schedule",
"using",
"a",
"heuristic"
] | python | train |
gwastro/pycbc | pycbc/workflow/jobsetup.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/jobsetup.py#L118-L177 | def select_generic_executable(workflow, exe_tag):
""" Returns a class that is appropriate for setting up jobs to run executables
having specific tags in the workflow config.
Executables should not be "specialized" jobs fitting into one of the
select_XXX_class functions above, i.e. not a matched filter o... | [
"def",
"select_generic_executable",
"(",
"workflow",
",",
"exe_tag",
")",
":",
"exe_path",
"=",
"workflow",
".",
"cp",
".",
"get",
"(",
"\"executables\"",
",",
"exe_tag",
")",
"exe_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"exe_path",
")",
"exe_... | Returns a class that is appropriate for setting up jobs to run executables
having specific tags in the workflow config.
Executables should not be "specialized" jobs fitting into one of the
select_XXX_class functions above, i.e. not a matched filter or template
bank job, which require extra setup.
P... | [
"Returns",
"a",
"class",
"that",
"is",
"appropriate",
"for",
"setting",
"up",
"jobs",
"to",
"run",
"executables",
"having",
"specific",
"tags",
"in",
"the",
"workflow",
"config",
".",
"Executables",
"should",
"not",
"be",
"specialized",
"jobs",
"fitting",
"int... | python | train |
apache/incubator-heron | heron/tools/cli/src/python/jars.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/jars.py#L28-L36 | def pick(dirname, pattern):
'''
Get the topology jars
:param dirname:
:param pattern:
:return:
'''
file_list = fnmatch.filter(os.listdir(dirname), pattern)
return file_list[0] if file_list else None | [
"def",
"pick",
"(",
"dirname",
",",
"pattern",
")",
":",
"file_list",
"=",
"fnmatch",
".",
"filter",
"(",
"os",
".",
"listdir",
"(",
"dirname",
")",
",",
"pattern",
")",
"return",
"file_list",
"[",
"0",
"]",
"if",
"file_list",
"else",
"None"
] | Get the topology jars
:param dirname:
:param pattern:
:return: | [
"Get",
"the",
"topology",
"jars",
":",
"param",
"dirname",
":",
":",
"param",
"pattern",
":",
":",
"return",
":"
] | python | valid |
project-ncl/pnc-cli | pnc_cli/buildrecords.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildrecords.py#L111-L117 | def list_dependency_artifacts(id, page_size=200, page_index=0, sort="", q=""):
"""
List dependency artifacts associated with a BuildRecord
"""
data = list_dependency_artifacts_raw(id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_dependency_artifacts",
"(",
"id",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_dependency_artifacts_raw",
"(",
"id",
",",
"page_size",
",",
"page_index... | List dependency artifacts associated with a BuildRecord | [
"List",
"dependency",
"artifacts",
"associated",
"with",
"a",
"BuildRecord"
] | python | train |
Unidata/MetPy | metpy/io/_tools.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/io/_tools.py#L123-L125 | def unpack(self, s):
"""Parse bytes and return a namedtuple."""
return self._create(super(NamedStruct, self).unpack(s)) | [
"def",
"unpack",
"(",
"self",
",",
"s",
")",
":",
"return",
"self",
".",
"_create",
"(",
"super",
"(",
"NamedStruct",
",",
"self",
")",
".",
"unpack",
"(",
"s",
")",
")"
] | Parse bytes and return a namedtuple. | [
"Parse",
"bytes",
"and",
"return",
"a",
"namedtuple",
"."
] | python | train |
pydata/xarray | xarray/core/indexes.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/indexes.py#L39-L58 | def default_indexes(
coords: Mapping[Any, Variable],
dims: Iterable,
) -> 'OrderedDict[Any, pd.Index]':
"""Default indexes for a Dataset/DataArray.
Parameters
----------
coords : Mapping[Any, xarray.Variable]
Coordinate variables from which to draw default indexes.
dims : iterable
... | [
"def",
"default_indexes",
"(",
"coords",
":",
"Mapping",
"[",
"Any",
",",
"Variable",
"]",
",",
"dims",
":",
"Iterable",
",",
")",
"->",
"'OrderedDict[Any, pd.Index]'",
":",
"return",
"OrderedDict",
"(",
"(",
"key",
",",
"coords",
"[",
"key",
"]",
".",
"... | Default indexes for a Dataset/DataArray.
Parameters
----------
coords : Mapping[Any, xarray.Variable]
Coordinate variables from which to draw default indexes.
dims : iterable
Iterable of dimension names.
Returns
-------
Mapping from indexing keys (levels/dimension names) to ... | [
"Default",
"indexes",
"for",
"a",
"Dataset",
"/",
"DataArray",
"."
] | python | train |
AtomHash/evernode | evernode/classes/json.py | https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/json.py#L55-L58 | def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True) | [
"def",
"from_file",
"(",
"file_path",
")",
"->",
"dict",
":",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"json_stream",
":",
"return",
"Json",
".",
"parse",
"(",
"json_stream",
",",
"True",
")"
... | Load JSON file | [
"Load",
"JSON",
"file"
] | python | train |
alex-kostirin/pyatomac | atomac/ldtpd/core.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L257-L288 | def getobjectinfo(self, window_name, object_name):
"""
Get object properties.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
... | [
"def",
"getobjectinfo",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"try",
":",
"obj_info",
"=",
"self",
".",
"_get_object_map",
"(",
"window_name",
",",
"object_name",
",",
"wait_for_object",
"=",
"False",
")",
"except",
"atomac",
".",
"_... | Get object properties.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type object_nam... | [
"Get",
"object",
"properties",
"."
] | python | valid |
dylanaraps/pywal | pywal/sequences.py | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L38-L69 | def create_sequences(colors, vte_fix=False):
"""Create the escape sequences."""
alpha = colors["alpha"]
# Colors 0-15.
sequences = [set_color(index, colors["colors"]["color%s" % index])
for index in range(16)]
# Special colors.
# Source: https://goo.gl/KcoQgP
# 10 = foregr... | [
"def",
"create_sequences",
"(",
"colors",
",",
"vte_fix",
"=",
"False",
")",
":",
"alpha",
"=",
"colors",
"[",
"\"alpha\"",
"]",
"# Colors 0-15.",
"sequences",
"=",
"[",
"set_color",
"(",
"index",
",",
"colors",
"[",
"\"colors\"",
"]",
"[",
"\"color%s\"",
... | Create the escape sequences. | [
"Create",
"the",
"escape",
"sequences",
"."
] | python | train |
ValvePython/steam | steam/client/builtins/leaderboards.py | https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/client/builtins/leaderboards.py#L164-L186 | def get_iter(self, times, seconds, chunk_size=2000):
"""Make a iterator over the entries
See :class:`steam.util.throttle.ConstantRateLimit` for ``times`` and ``seconds`` parameters.
:param chunk_size: number of entries per request
:type chunk_size: :class:`int`
:returns: genera... | [
"def",
"get_iter",
"(",
"self",
",",
"times",
",",
"seconds",
",",
"chunk_size",
"=",
"2000",
")",
":",
"def",
"entry_generator",
"(",
")",
":",
"with",
"ConstantRateLimit",
"(",
"times",
",",
"seconds",
",",
"sleep_func",
"=",
"self",
".",
"_steam",
"."... | Make a iterator over the entries
See :class:`steam.util.throttle.ConstantRateLimit` for ``times`` and ``seconds`` parameters.
:param chunk_size: number of entries per request
:type chunk_size: :class:`int`
:returns: generator object
:rtype: :class:`generator`
The itera... | [
"Make",
"a",
"iterator",
"over",
"the",
"entries"
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L342-L353 | def encode(self, value):
"""Encodes the given value according to this FieldDefinition."""
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
if type(value) == int:
if self.shift > 0:
value <<= self.shift
if se... | [
"def",
"encode",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"str",
"and",
"self",
".",
"enum",
"and",
"value",
"in",
"self",
".",
"enum",
":",
"value",
"=",
"self",
".",
"enum",
"[",
"value",
"]",
"if",
"type",
... | Encodes the given value according to this FieldDefinition. | [
"Encodes",
"the",
"given",
"value",
"according",
"to",
"this",
"FieldDefinition",
"."
] | python | train |
morepath/more.jwtauth | more/jwtauth/refresh.py | https://github.com/morepath/more.jwtauth/blob/1c3c5731612069a092e44cf612641c05edf1f083/more/jwtauth/refresh.py#L4-L21 | def verify_refresh_request(request):
"""
Wrapper around JWTIdentityPolicy.verify_refresh which verify
if the request to refresh the token is valid.
If valid it returns the userid which can be used to create to
create an updated identity with ``remember_identity``.
Otherwise it raises an exceptio... | [
"def",
"verify_refresh_request",
"(",
"request",
")",
":",
"jwtauth_settings",
"=",
"request",
".",
"app",
".",
"settings",
".",
"jwtauth",
".",
"__dict__",
".",
"copy",
"(",
")",
"identity_policy",
"=",
"JWTIdentityPolicy",
"(",
"*",
"*",
"jwtauth_settings",
... | Wrapper around JWTIdentityPolicy.verify_refresh which verify
if the request to refresh the token is valid.
If valid it returns the userid which can be used to create to
create an updated identity with ``remember_identity``.
Otherwise it raises an exception based on InvalidTokenError.
:param request... | [
"Wrapper",
"around",
"JWTIdentityPolicy",
".",
"verify_refresh",
"which",
"verify",
"if",
"the",
"request",
"to",
"refresh",
"the",
"token",
"is",
"valid",
".",
"If",
"valid",
"it",
"returns",
"the",
"userid",
"which",
"can",
"be",
"used",
"to",
"create",
"t... | python | train |
lambdalisue/maidenhair | src/maidenhair/parsers/base.py | https://github.com/lambdalisue/maidenhair/blob/d5095c1087d1f4d71cc57410492151d2803a9f0d/src/maidenhair/parsers/base.py#L33-L49 | def load(self, filename, **kwargs):
"""
Parse a file specified with the filename and return an numpy array
Parameters
----------
filename : string
A path of a file
Returns
-------
ndarray
An instance of numpy array
... | [
"def",
"load",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"self",
".",
"parse",
"(",
"f",
",",
"*",
"*",
"kwargs",
")"
] | Parse a file specified with the filename and return an numpy array
Parameters
----------
filename : string
A path of a file
Returns
-------
ndarray
An instance of numpy array | [
"Parse",
"a",
"file",
"specified",
"with",
"the",
"filename",
"and",
"return",
"an",
"numpy",
"array"
] | python | train |
openxc/openxc-python | openxc/sources/base.py | https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/sources/base.py#L141-L163 | def run(self):
"""Continuously read data from the source and attempt to parse a valid
message from the buffer of bytes. When a message is parsed, passes it
off to the callback if one is set.
"""
message_buffer = b""
while self.running:
try:
mes... | [
"def",
"run",
"(",
"self",
")",
":",
"message_buffer",
"=",
"b\"\"",
"while",
"self",
".",
"running",
":",
"try",
":",
"message_buffer",
"+=",
"self",
".",
"source",
".",
"read_logs",
"(",
")",
"except",
"DataSourceError",
"as",
"e",
":",
"if",
"self",
... | Continuously read data from the source and attempt to parse a valid
message from the buffer of bytes. When a message is parsed, passes it
off to the callback if one is set. | [
"Continuously",
"read",
"data",
"from",
"the",
"source",
"and",
"attempt",
"to",
"parse",
"a",
"valid",
"message",
"from",
"the",
"buffer",
"of",
"bytes",
".",
"When",
"a",
"message",
"is",
"parsed",
"passes",
"it",
"off",
"to",
"the",
"callback",
"if",
... | python | train |
SwissDataScienceCenter/renku-python | renku/cli/workflow.py | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/workflow.py#L120-L123 | def rename(client, old, new, force):
"""Rename the workflow named <old> to <new>."""
from renku.models.refs import LinkReference
LinkReference(client=client, name=_ref(old)).rename(_ref(new), force=force) | [
"def",
"rename",
"(",
"client",
",",
"old",
",",
"new",
",",
"force",
")",
":",
"from",
"renku",
".",
"models",
".",
"refs",
"import",
"LinkReference",
"LinkReference",
"(",
"client",
"=",
"client",
",",
"name",
"=",
"_ref",
"(",
"old",
")",
")",
"."... | Rename the workflow named <old> to <new>. | [
"Rename",
"the",
"workflow",
"named",
"<old",
">",
"to",
"<new",
">",
"."
] | python | train |
mandiant/ioc_writer | ioc_writer/ioc_common.py | https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_common.py#L237-L250 | def make_fileitem_peinfo_detectedentrypointsignature_name(entrypoint_name, condition='is', negate=False,
preserve_case=False):
"""
Create a node for FileItem/PEInfo/DetectedEntryPointSignature/Name
:return: A IndicatorItem represented as an Elem... | [
"def",
"make_fileitem_peinfo_detectedentrypointsignature_name",
"(",
"entrypoint_name",
",",
"condition",
"=",
"'is'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'FileItem'",
"search",
"=",
"'FileItem/PEInfo/DetectedEntr... | Create a node for FileItem/PEInfo/DetectedEntryPointSignature/Name
:return: A IndicatorItem represented as an Element node | [
"Create",
"a",
"node",
"for",
"FileItem",
"/",
"PEInfo",
"/",
"DetectedEntryPointSignature",
"/",
"Name",
":",
"return",
":",
"A",
"IndicatorItem",
"represented",
"as",
"an",
"Element",
"node"
] | python | train |
numenta/htmresearch | htmresearch/frameworks/poirazi_neuron_model/data_tools.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L317-L329 | def generate_RF_bins(data, dim = 40, num_bins = 10):
"""
Generates bins for the encoder. Bins are designed to have equal frequency,
per Poirazi & Mel (2001), which requires reading the data once.
Bins are represented as the intervals dividing them.
"""
intervals = []
for i in range(dim):
current_dim_... | [
"def",
"generate_RF_bins",
"(",
"data",
",",
"dim",
"=",
"40",
",",
"num_bins",
"=",
"10",
")",
":",
"intervals",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"dim",
")",
":",
"current_dim_data",
"=",
"[",
"data",
"[",
"x",
"]",
"[",
"i",
"]",
... | Generates bins for the encoder. Bins are designed to have equal frequency,
per Poirazi & Mel (2001), which requires reading the data once.
Bins are represented as the intervals dividing them. | [
"Generates",
"bins",
"for",
"the",
"encoder",
".",
"Bins",
"are",
"designed",
"to",
"have",
"equal",
"frequency",
"per",
"Poirazi",
"&",
"Mel",
"(",
"2001",
")",
"which",
"requires",
"reading",
"the",
"data",
"once",
".",
"Bins",
"are",
"represented",
"as"... | python | train |
gebn/wood | wood/__init__.py | https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/__init__.py#L63-L88 | def compare(left: Union[str, pathlib.Path, _Entity],
right: Union[str, pathlib.Path, _Entity]) -> Comparison:
"""
Compare two paths.
:param left: The left side or "before" entity.
:param right: The right side or "after" entity.
:return: A comparison details what has changed from the lef... | [
"def",
"compare",
"(",
"left",
":",
"Union",
"[",
"str",
",",
"pathlib",
".",
"Path",
",",
"_Entity",
"]",
",",
"right",
":",
"Union",
"[",
"str",
",",
"pathlib",
".",
"Path",
",",
"_Entity",
"]",
")",
"->",
"Comparison",
":",
"def",
"normalise",
"... | Compare two paths.
:param left: The left side or "before" entity.
:param right: The right side or "after" entity.
:return: A comparison details what has changed from the left side to the
right side. | [
"Compare",
"two",
"paths",
"."
] | python | train |
jayclassless/basicserial | src/basicserial/__init__.py | https://github.com/jayclassless/basicserial/blob/da779edd955ba1009d14fae4e5926e29ad112b9d/src/basicserial/__init__.py#L372-L393 | def from_toml(value, native_datetimes=True):
"""
Deserializes the given value from TOML.
:param value: the value to deserialize
:type value: str
:param native_datetimes:
whether or not strings that look like dates/times should be
automatically cast to the native objects, or left as ... | [
"def",
"from_toml",
"(",
"value",
",",
"native_datetimes",
"=",
"True",
")",
":",
"if",
"not",
"toml",
":",
"raise",
"NotImplementedError",
"(",
"'No supported TOML library available'",
")",
"result",
"=",
"toml",
".",
"loads",
"(",
"value",
")",
"if",
"native... | Deserializes the given value from TOML.
:param value: the value to deserialize
:type value: str
:param native_datetimes:
whether or not strings that look like dates/times should be
automatically cast to the native objects, or left as strings; if not
specified, defaults to ``True``
... | [
"Deserializes",
"the",
"given",
"value",
"from",
"TOML",
"."
] | python | train |
estnltk/estnltk | estnltk/prettyprinter/marker.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/prettyprinter/marker.py#L100-L132 | def create_tags_with_concatenated_css_classes(tags):
"""Function that creates <mark> tags such that they are not overlapping.
In order to do this, it concatenates the css classes and stores the concatenated
result in new tags.
"""
current_classes = set()
result = []
for pos, group in group_t... | [
"def",
"create_tags_with_concatenated_css_classes",
"(",
"tags",
")",
":",
"current_classes",
"=",
"set",
"(",
")",
"result",
"=",
"[",
"]",
"for",
"pos",
",",
"group",
"in",
"group_tags_at_same_position",
"(",
"tags",
")",
":",
"opening",
",",
"closing",
"=",... | Function that creates <mark> tags such that they are not overlapping.
In order to do this, it concatenates the css classes and stores the concatenated
result in new tags. | [
"Function",
"that",
"creates",
"<mark",
">",
"tags",
"such",
"that",
"they",
"are",
"not",
"overlapping",
".",
"In",
"order",
"to",
"do",
"this",
"it",
"concatenates",
"the",
"css",
"classes",
"and",
"stores",
"the",
"concatenated",
"result",
"in",
"new",
... | python | train |
alextricity25/dwell_in_you_richly | diyr/utils/bible.py | https://github.com/alextricity25/dwell_in_you_richly/blob/e705e1bc4fc0b8d2aa25680dfc432762b361c783/diyr/utils/bible.py#L122-L141 | def get_chapter(self, book_name, book_chapter, cache_chapter = True):
"""
Returns a chapter of the bible, first checking to see if that
chapter is on disk. If not, hen it attempts to fetch it from
the internet.
NOTE: This is public facing method. If the method signature changes,... | [
"def",
"get_chapter",
"(",
"self",
",",
"book_name",
",",
"book_chapter",
",",
"cache_chapter",
"=",
"True",
")",
":",
"try",
":",
"logging",
".",
"debug",
"(",
"\"Attempting to read chapter from disk\"",
")",
"verses_list",
"=",
"self",
".",
"_get_ondisk_chapter"... | Returns a chapter of the bible, first checking to see if that
chapter is on disk. If not, hen it attempts to fetch it from
the internet.
NOTE: This is public facing method. If the method signature changes,
then it needs to be documented and backwards-compatablity
nee... | [
"Returns",
"a",
"chapter",
"of",
"the",
"bible",
"first",
"checking",
"to",
"see",
"if",
"that",
"chapter",
"is",
"on",
"disk",
".",
"If",
"not",
"hen",
"it",
"attempts",
"to",
"fetch",
"it",
"from",
"the",
"internet",
"."
] | python | train |
jaywink/federation | federation/entities/diaspora/entities.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/entities/diaspora/entities.py#L36-L47 | def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"text": self.raw_content},
{"guid": self.guid},
{"author": self.handle},
{"public": "true" if self.public else "false"},
{... | [
"def",
"to_xml",
"(",
"self",
")",
":",
"element",
"=",
"etree",
".",
"Element",
"(",
"self",
".",
"_tag_name",
")",
"struct_to_xml",
"(",
"element",
",",
"[",
"{",
"\"text\"",
":",
"self",
".",
"raw_content",
"}",
",",
"{",
"\"guid\"",
":",
"self",
... | Convert to XML message. | [
"Convert",
"to",
"XML",
"message",
"."
] | python | train |
ActionAgile/trellostats | trellostats/cli.py | https://github.com/ActionAgile/trellostats/blob/695039ba9a787d0fdb71ec90cee52193ca98e489/trellostats/cli.py#L79-L100 | def report(ctx, board, done, output):
ctx.obj['board_id'] = board
ts = TrelloStats(ctx.obj)
"""
Reporting mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
... | [
"def",
"report",
"(",
"ctx",
",",
"board",
",",
"done",
",",
"output",
")",
":",
"ctx",
".",
"obj",
"[",
"'board_id'",
"]",
"=",
"board",
"ts",
"=",
"TrelloStats",
"(",
"ctx",
".",
"obj",
")",
"ct",
"=",
"cycle_time",
"(",
"ts",
",",
"board",
","... | Reporting mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
--done=Done | [
"Reporting",
"mode",
"-",
"Daily",
"snapshots",
"of",
"a",
"board",
"for",
"ongoing",
"reporting",
":",
"-",
">",
"trellis",
"report",
"--",
"board",
"=",
"87hiudhw",
"--",
"spend",
"--",
"revenue",
"--",
"done",
"=",
"Done"
] | python | train |
spotify/gordon-janitor | gordon_janitor/main.py | https://github.com/spotify/gordon-janitor/blob/e0df2002caf3aac528818743d8d0717790957044/gordon_janitor/main.py#L76-L98 | def setup(config_root=''):
"""
Service configuration and logging setup.
Configuration defined in ``gordon-janitor-user.toml`` will overwrite
``gordon-janitor.toml``.
Args:
config_root (str): where configuration should load from,
defaults to current working directory.
Return... | [
"def",
"setup",
"(",
"config_root",
"=",
"''",
")",
":",
"config",
"=",
"_load_config",
"(",
"root",
"=",
"config_root",
")",
"logging_config",
"=",
"config",
".",
"get",
"(",
"'core'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'logging'",
",",
"{",
"}",... | Service configuration and logging setup.
Configuration defined in ``gordon-janitor-user.toml`` will overwrite
``gordon-janitor.toml``.
Args:
config_root (str): where configuration should load from,
defaults to current working directory.
Returns:
A dict for Gordon service co... | [
"Service",
"configuration",
"and",
"logging",
"setup",
"."
] | python | train |
openego/ding0 | ding0/core/network/grids.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/network/grids.py#L526-L655 | def set_default_branch_type(self, debug=False):
""" Determines default branch type according to grid district's peak load and standard equipment.
Args
----
debug: bool, defaults to False
If True, information is printed during process
Returns
-------
... | [
"def",
"set_default_branch_type",
"(",
"self",
",",
"debug",
"=",
"False",
")",
":",
"# decide whether cable or line is used (initially for entire grid) and set grid's attribute",
"if",
"self",
".",
"v_level",
"==",
"20",
":",
"self",
".",
"default_branch_kind",
"=",
"'li... | Determines default branch type according to grid district's peak load and standard equipment.
Args
----
debug: bool, defaults to False
If True, information is printed during process
Returns
-------
:pandas:`pandas.Series<series>`
default branc... | [
"Determines",
"default",
"branch",
"type",
"according",
"to",
"grid",
"district",
"s",
"peak",
"load",
"and",
"standard",
"equipment",
"."
] | python | train |
cs50/python-cs50 | src/cs50/cs50.py | https://github.com/cs50/python-cs50/blob/f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a/src/cs50/cs50.py#L91-L109 | def get_float(prompt=None):
"""
Read a line of text from standard input and return the equivalent float
as precisely as possible; if text does not represent a double, user is
prompted to retry. If line can't be read, return None.
"""
while True:
s = get_string(prompt)
if s is Non... | [
"def",
"get_float",
"(",
"prompt",
"=",
"None",
")",
":",
"while",
"True",
":",
"s",
"=",
"get_string",
"(",
"prompt",
")",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"if",
"len",
"(",
"s",
")",
">",
"0",
"and",
"re",
".",
"search",
"(",
"... | Read a line of text from standard input and return the equivalent float
as precisely as possible; if text does not represent a double, user is
prompted to retry. If line can't be read, return None. | [
"Read",
"a",
"line",
"of",
"text",
"from",
"standard",
"input",
"and",
"return",
"the",
"equivalent",
"float",
"as",
"precisely",
"as",
"possible",
";",
"if",
"text",
"does",
"not",
"represent",
"a",
"double",
"user",
"is",
"prompted",
"to",
"retry",
".",
... | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_hardware.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_hardware.py#L428-L440 | def get_flexports_output_flexport_list_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_flexports = ET.Element("get_flexports")
config = get_flexports
output = ET.SubElement(get_flexports, "output")
flexport_list = ET.SubElemen... | [
"def",
"get_flexports_output_flexport_list_port_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_flexports",
"=",
"ET",
".",
"Element",
"(",
"\"get_flexports\"",
")",
"config",
"=",
"get_fle... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
JasonKessler/scattertext | scattertext/representations/EmbeddingsResolver.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/representations/EmbeddingsResolver.py#L81-L97 | def project(self, projection_model=None):
'''
:param projection_model: sklearn unsupervised model (e.g., PCA) by default the recommended model is umap.UMAP,
which requires UMAP in to be installed
:return: array, shape (num dimension, vocab size)
'''
if self.embeddings_ i... | [
"def",
"project",
"(",
"self",
",",
"projection_model",
"=",
"None",
")",
":",
"if",
"self",
".",
"embeddings_",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Run set_embeddings_model or set_embeddings to get embeddings\"",
")",
"if",
"projection_model",
"is",
"N... | :param projection_model: sklearn unsupervised model (e.g., PCA) by default the recommended model is umap.UMAP,
which requires UMAP in to be installed
:return: array, shape (num dimension, vocab size) | [
":",
"param",
"projection_model",
":",
"sklearn",
"unsupervised",
"model",
"(",
"e",
".",
"g",
".",
"PCA",
")",
"by",
"default",
"the",
"recommended",
"model",
"is",
"umap",
".",
"UMAP",
"which",
"requires",
"UMAP",
"in",
"to",
"be",
"installed"
] | python | train |
saltstack/salt | salt/runners/net.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L121-L132 | def _get_net_runner_opts():
'''
Return the net.find runner options.
'''
runner_opts = __opts__.get('runners', {}).get('net.find', {})
return {
'target': runner_opts.get('target', _DEFAULT_TARGET),
'expr_form': runner_opts.get('expr_form', _DEFAULT_EXPR_FORM),
'ignore_interfac... | [
"def",
"_get_net_runner_opts",
"(",
")",
":",
"runner_opts",
"=",
"__opts__",
".",
"get",
"(",
"'runners'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'net.find'",
",",
"{",
"}",
")",
"return",
"{",
"'target'",
":",
"runner_opts",
".",
"get",
"(",
"'target'... | Return the net.find runner options. | [
"Return",
"the",
"net",
".",
"find",
"runner",
"options",
"."
] | python | train |
gabstopper/smc-python | smc/routing/route_map.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/route_map.py#L229-L307 | def create(self, name, action='permit', goto=None, finish=False,
call=None, comment=None, add_pos=None, after=None,
before=None, **match_condition):
"""
Create a route map rule. You can provide match conditions
by using keyword arguments specifying the required type... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"action",
"=",
"'permit'",
",",
"goto",
"=",
"None",
",",
"finish",
"=",
"False",
",",
"call",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"add_pos",
"=",
"None",
",",
"after",
"=",
"None",
",",
... | Create a route map rule. You can provide match conditions
by using keyword arguments specifying the required types.
You can also create the route map rule and add match conditions
after.
:param str name: name for this rule
:param str action: permit or deny
:param... | [
"Create",
"a",
"route",
"map",
"rule",
".",
"You",
"can",
"provide",
"match",
"conditions",
"by",
"using",
"keyword",
"arguments",
"specifying",
"the",
"required",
"types",
".",
"You",
"can",
"also",
"create",
"the",
"route",
"map",
"rule",
"and",
"add",
"... | python | train |
gwastro/pycbc | pycbc/transforms.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L1686-L1711 | def read_transforms_from_config(cp, section="transforms"):
"""Returns a list of PyCBC transform instances for a section in the
given configuration file.
If the transforms are nested (i.e., the output of one transform is the
input of another), the returned list will be sorted by the order of the
nes... | [
"def",
"read_transforms_from_config",
"(",
"cp",
",",
"section",
"=",
"\"transforms\"",
")",
":",
"trans",
"=",
"[",
"]",
"for",
"subsection",
"in",
"cp",
".",
"get_subsections",
"(",
"section",
")",
":",
"name",
"=",
"cp",
".",
"get_opt_tag",
"(",
"sectio... | Returns a list of PyCBC transform instances for a section in the
given configuration file.
If the transforms are nested (i.e., the output of one transform is the
input of another), the returned list will be sorted by the order of the
nests.
Parameters
----------
cp : WorflowConfigParser
... | [
"Returns",
"a",
"list",
"of",
"PyCBC",
"transform",
"instances",
"for",
"a",
"section",
"in",
"the",
"given",
"configuration",
"file",
"."
] | python | train |
fedelemantuano/tika-app-python | tikapp/utils.py | https://github.com/fedelemantuano/tika-app-python/blob/9a462aa611af2032306c78a9c996c8545288c212/tikapp/utils.py#L87-L113 | def write_payload(payload=None, objectInput=None):
"""
This function writes a base64 payload or file object on disk.
Args:
payload (string): payload in base64
objectInput (object): file object/standard input to analyze
Returns:
Path of file
"""
temp = tempfile.mkstemp(... | [
"def",
"write_payload",
"(",
"payload",
"=",
"None",
",",
"objectInput",
"=",
"None",
")",
":",
"temp",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"[",
"1",
"]",
"log",
".",
"debug",
"(",
"\"Write payload in temp file {!r}\"",
".",
"format",
"(",
"temp",
... | This function writes a base64 payload or file object on disk.
Args:
payload (string): payload in base64
objectInput (object): file object/standard input to analyze
Returns:
Path of file | [
"This",
"function",
"writes",
"a",
"base64",
"payload",
"or",
"file",
"object",
"on",
"disk",
"."
] | python | train |
cdgriffith/Reusables | reusables/cli.py | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/cli.py#L204-L231 | def cp(src, dst, overwrite=False):
"""
Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it?
"""
if not isinstance(src, list):
src = [sr... | [
"def",
"cp",
"(",
"src",
",",
"dst",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"src",
",",
"list",
")",
":",
"src",
"=",
"[",
"src",
"]",
"dst",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"dst",
")",
"dst_fo... | Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it? | [
"Copy",
"files",
"to",
"a",
"new",
"location",
"."
] | python | train |
Jammy2211/PyAutoLens | autolens/data/array/scaled_array.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/scaled_array.py#L351-L371 | def resized_scaled_array_from_array(self, new_shape, new_centre_pixels=None, new_centre_arcsec=None):
"""resized the array to a new shape and at a new origin.
Parameters
-----------
new_shape : (int, int)
The new two-dimensional shape of the array.
"""
if new... | [
"def",
"resized_scaled_array_from_array",
"(",
"self",
",",
"new_shape",
",",
"new_centre_pixels",
"=",
"None",
",",
"new_centre_arcsec",
"=",
"None",
")",
":",
"if",
"new_centre_pixels",
"is",
"None",
"and",
"new_centre_arcsec",
"is",
"None",
":",
"new_centre",
"... | resized the array to a new shape and at a new origin.
Parameters
-----------
new_shape : (int, int)
The new two-dimensional shape of the array. | [
"resized",
"the",
"array",
"to",
"a",
"new",
"shape",
"and",
"at",
"a",
"new",
"origin",
"."
] | python | valid |
iotile/coretools | iotileemulate/iotile/emulate/internal/rpc_queue.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/rpc_queue.py#L44-L58 | def put_task(self, func, args, response):
"""Place a task onto the RPC queue.
This temporary functionality will go away but it lets you run a
task synchronously with RPC dispatch by placing it onto the
RCP queue.
Args:
func (callable): The function to execute
... | [
"def",
"put_task",
"(",
"self",
",",
"func",
",",
"args",
",",
"response",
")",
":",
"self",
".",
"_rpc_queue",
".",
"put_nowait",
"(",
"(",
"func",
",",
"args",
",",
"response",
")",
")"
] | Place a task onto the RPC queue.
This temporary functionality will go away but it lets you run a
task synchronously with RPC dispatch by placing it onto the
RCP queue.
Args:
func (callable): The function to execute
args (iterable): The function arguments
... | [
"Place",
"a",
"task",
"onto",
"the",
"RPC",
"queue",
"."
] | python | train |
sentinel-hub/sentinelhub-py | sentinelhub/aws.py | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L534-L557 | def get_aws_index(self):
"""
Returns tile index on AWS. If `tile_index` was not set during class initialization it will be determined
according to existing tiles on AWS.
:return: Index of tile on AWS
:rtype: int
"""
if self.aws_index is not None:
retu... | [
"def",
"get_aws_index",
"(",
"self",
")",
":",
"if",
"self",
".",
"aws_index",
"is",
"not",
"None",
":",
"return",
"self",
".",
"aws_index",
"tile_info_list",
"=",
"get_tile_info",
"(",
"self",
".",
"tile_name",
",",
"self",
".",
"datetime",
",",
"all_tile... | Returns tile index on AWS. If `tile_index` was not set during class initialization it will be determined
according to existing tiles on AWS.
:return: Index of tile on AWS
:rtype: int | [
"Returns",
"tile",
"index",
"on",
"AWS",
".",
"If",
"tile_index",
"was",
"not",
"set",
"during",
"class",
"initialization",
"it",
"will",
"be",
"determined",
"according",
"to",
"existing",
"tiles",
"on",
"AWS",
"."
] | python | train |
FPGAwars/apio | apio/commands/examples.py | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/examples.py#L29-L45 | def cli(ctx, list, dir, files, project_dir, sayno):
"""Manage verilog examples.\n
Install with `apio install examples`"""
exit_code = 0
if list:
exit_code = Examples().list_examples()
elif dir:
exit_code = Examples().copy_example_dir(dir, project_dir, sayno)
elif files:
... | [
"def",
"cli",
"(",
"ctx",
",",
"list",
",",
"dir",
",",
"files",
",",
"project_dir",
",",
"sayno",
")",
":",
"exit_code",
"=",
"0",
"if",
"list",
":",
"exit_code",
"=",
"Examples",
"(",
")",
".",
"list_examples",
"(",
")",
"elif",
"dir",
":",
"exit... | Manage verilog examples.\n
Install with `apio install examples` | [
"Manage",
"verilog",
"examples",
".",
"\\",
"n",
"Install",
"with",
"apio",
"install",
"examples"
] | python | train |
trailofbits/manticore | manticore/native/cpu/x86.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L529-L548 | def _get_flags(self, reg):
""" Build EFLAGS/RFLAGS from flags """
def make_symbolic(flag_expr):
register_size = 32 if reg == 'EFLAGS' else 64
value, offset = flag_expr
return Operators.ITEBV(register_size, value,
BitVecConstant(regis... | [
"def",
"_get_flags",
"(",
"self",
",",
"reg",
")",
":",
"def",
"make_symbolic",
"(",
"flag_expr",
")",
":",
"register_size",
"=",
"32",
"if",
"reg",
"==",
"'EFLAGS'",
"else",
"64",
"value",
",",
"offset",
"=",
"flag_expr",
"return",
"Operators",
".",
"IT... | Build EFLAGS/RFLAGS from flags | [
"Build",
"EFLAGS",
"/",
"RFLAGS",
"from",
"flags"
] | python | valid |
infothrill/python-dyndnsc | dyndnsc/plugins/manager.py | https://github.com/infothrill/python-dyndnsc/blob/2196d48aa6098da9835a7611fbdb0b5f0fbf51e4/dyndnsc/plugins/manager.py#L129-L135 | def add_plugin(self, plugin):
"""Add the given plugin."""
# allow plugins loaded via entry points to override builtin plugins
new_name = self.plugin_name(plugin)
self._plugins[:] = [p for p in self._plugins
if self.plugin_name(p) != new_name]
self._plu... | [
"def",
"add_plugin",
"(",
"self",
",",
"plugin",
")",
":",
"# allow plugins loaded via entry points to override builtin plugins",
"new_name",
"=",
"self",
".",
"plugin_name",
"(",
"plugin",
")",
"self",
".",
"_plugins",
"[",
":",
"]",
"=",
"[",
"p",
"for",
"p",
... | Add the given plugin. | [
"Add",
"the",
"given",
"plugin",
"."
] | python | train |
openstack/proliantutils | proliantutils/ilo/ris.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ris.py#L790-L807 | def _perform_power_op(self, oper):
"""Perform requested power operation.
:param oper: Type of power button press to simulate.
Supported values: 'ON', 'ForceOff', 'ForceRestart' and
'Nmi'
:raises: IloError, on an error from iLO.
"""
powe... | [
"def",
"_perform_power_op",
"(",
"self",
",",
"oper",
")",
":",
"power_settings",
"=",
"{",
"\"Action\"",
":",
"\"Reset\"",
",",
"\"ResetType\"",
":",
"oper",
"}",
"systems_uri",
"=",
"\"/rest/v1/Systems/1\"",
"status",
",",
"headers",
",",
"response",
"=",
"s... | Perform requested power operation.
:param oper: Type of power button press to simulate.
Supported values: 'ON', 'ForceOff', 'ForceRestart' and
'Nmi'
:raises: IloError, on an error from iLO. | [
"Perform",
"requested",
"power",
"operation",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L228-L262 | def get_gan_loss(self, true_frames, gen_frames, name):
"""Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be g... | [
"def",
"get_gan_loss",
"(",
"self",
",",
"true_frames",
",",
"gen_frames",
",",
"name",
")",
":",
"# D - STEP",
"with",
"tf",
".",
"variable_scope",
"(",
"\"%s_discriminator\"",
"%",
"name",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"gan_d_loss",... | Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be ground truth.
gen_frames: 5-D Tensor of shape (num_steps,... | [
"Get",
"the",
"discriminator",
"+",
"generator",
"loss",
"at",
"every",
"step",
"."
] | python | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L845-L866 | def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminio... | [
"def",
"delete_cors",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
... | Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket | [
"Delete",
"the",
"CORS",
"configuration",
"for",
"the",
"given",
"bucket"
] | python | train |
housecanary/hc-api-python | housecanary/excel/analytics_data_excel.py | https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/excel/analytics_data_excel.py#L222-L297 | def process_data(key, data_list, result_info_key, identifier_keys):
""" Given a key as the endpoint name, pulls the data for that endpoint out
of the data_list for each address, processes the data into a more
excel-friendly format and returns that data.
Args:
key: the endpoint n... | [
"def",
"process_data",
"(",
"key",
",",
"data_list",
",",
"result_info_key",
",",
"identifier_keys",
")",
":",
"master_data",
"=",
"[",
"]",
"for",
"item_data",
"in",
"data_list",
":",
"data",
"=",
"item_data",
"[",
"key",
"]",
"if",
"data",
"is",
"None",
... | Given a key as the endpoint name, pulls the data for that endpoint out
of the data_list for each address, processes the data into a more
excel-friendly format and returns that data.
Args:
key: the endpoint name of the data to process
data_list: the main data list to take... | [
"Given",
"a",
"key",
"as",
"the",
"endpoint",
"name",
"pulls",
"the",
"data",
"for",
"that",
"endpoint",
"out",
"of",
"the",
"data_list",
"for",
"each",
"address",
"processes",
"the",
"data",
"into",
"a",
"more",
"excel",
"-",
"friendly",
"format",
"and",
... | python | train |
aparsons/threadfix_api | threadfix_api/threadfix.py | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L244-L251 | def get_waf_rules_by_application(self, waf_id, application_id):
"""
Returns the WAF rule text for one or all of the applications in a WAF. If the application id is -1, it will get
rules for all apps. If the application is a valid application id, rules will be generated for that application.
... | [
"def",
"get_waf_rules_by_application",
"(",
"self",
",",
"waf_id",
",",
"application_id",
")",
":",
"return",
"self",
".",
"_request",
"(",
"'GET'",
",",
"'rest/wafs/'",
"+",
"str",
"(",
"waf_id",
")",
"+",
"'/rules/app/'",
"+",
"str",
"(",
"application_id",
... | Returns the WAF rule text for one or all of the applications in a WAF. If the application id is -1, it will get
rules for all apps. If the application is a valid application id, rules will be generated for that application.
:param waf_id: WAF identifier.
:param application_id: Application identi... | [
"Returns",
"the",
"WAF",
"rule",
"text",
"for",
"one",
"or",
"all",
"of",
"the",
"applications",
"in",
"a",
"WAF",
".",
"If",
"the",
"application",
"id",
"is",
"-",
"1",
"it",
"will",
"get",
"rules",
"for",
"all",
"apps",
".",
"If",
"the",
"applicati... | python | train |
karan/TPB | tpb/tpb.py | https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L29-L41 | def self_if_parameters(func):
"""
If any parameter is given, the method's binded object is returned after
executing the function. Else the function's result is returned.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if args or kwargs:
... | [
"def",
"self_if_parameters",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",... | If any parameter is given, the method's binded object is returned after
executing the function. Else the function's result is returned. | [
"If",
"any",
"parameter",
"is",
"given",
"the",
"method",
"s",
"binded",
"object",
"is",
"returned",
"after",
"executing",
"the",
"function",
".",
"Else",
"the",
"function",
"s",
"result",
"is",
"returned",
"."
] | python | train |
alan-turing-institute/topic-modelling-tools | topicmodels/LDA/gibbs.py | https://github.com/alan-turing-institute/topic-modelling-tools/blob/f0cf90cdd06f1072e824b446f201c7469b9de5df/topicmodels/LDA/gibbs.py#L196-L204 | def perplexity(self):
"""
Compute perplexity for each sample.
"""
return samplers_lda.perplexity_comp(self.docid, self.tokens,
self.tt, self.dt, self.N,
self.K, self.samples) | [
"def",
"perplexity",
"(",
"self",
")",
":",
"return",
"samplers_lda",
".",
"perplexity_comp",
"(",
"self",
".",
"docid",
",",
"self",
".",
"tokens",
",",
"self",
".",
"tt",
",",
"self",
".",
"dt",
",",
"self",
".",
"N",
",",
"self",
".",
"K",
",",
... | Compute perplexity for each sample. | [
"Compute",
"perplexity",
"for",
"each",
"sample",
"."
] | python | train |
minio/minio-py | minio/api.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L758-L838 | def put_object(self, bucket_name, object_name, data, length,
content_type='application/octet-stream',
metadata=None, sse=None, progress=None,
part_size=DEFAULT_PART_SIZE):
"""
Add a new object to the cloud storage server.
NOTE: Maximum ob... | [
"def",
"put_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"data",
",",
"length",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"metadata",
"=",
"None",
",",
"sse",
"=",
"None",
",",
"progress",
"=",
"None",
",",
"part_size... | Add a new object to the cloud storage server.
NOTE: Maximum object size supported by this API is 5TiB.
Examples:
file_stat = os.stat('hello.txt')
with open('hello.txt', 'rb') as data:
minio.put_object('foo', 'bar', data, file_stat.st_size, 'text/plain')
- For le... | [
"Add",
"a",
"new",
"object",
"to",
"the",
"cloud",
"storage",
"server",
"."
] | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/flask/app.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/app.py#L827-L837 | def save_session(self, session, response):
"""Saves the session if it needs updates. For the default
implementation, check :meth:`open_session`. Instead of overriding this
method we recommend replacing the :class:`session_interface`.
:param session: the session to be saved (a
... | [
"def",
"save_session",
"(",
"self",
",",
"session",
",",
"response",
")",
":",
"return",
"self",
".",
"session_interface",
".",
"save_session",
"(",
"self",
",",
"session",
",",
"response",
")"
] | Saves the session if it needs updates. For the default
implementation, check :meth:`open_session`. Instead of overriding this
method we recommend replacing the :class:`session_interface`.
:param session: the session to be saved (a
:class:`~werkzeug.contrib.securecookie... | [
"Saves",
"the",
"session",
"if",
"it",
"needs",
"updates",
".",
"For",
"the",
"default",
"implementation",
"check",
":",
"meth",
":",
"open_session",
".",
"Instead",
"of",
"overriding",
"this",
"method",
"we",
"recommend",
"replacing",
"the",
":",
"class",
"... | python | test |
softlayer/softlayer-python | SoftLayer/CLI/ssl/add.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/add.py#L23-L42 | def cli(env, crt, csr, icc, key, notes):
"""Add and upload SSL certificate details."""
template = {
'intermediateCertificate': '',
'certificateSigningRequest': '',
'notes': notes,
}
template['certificate'] = open(crt).read()
template['privateKey'] = open(key).read()
if c... | [
"def",
"cli",
"(",
"env",
",",
"crt",
",",
"csr",
",",
"icc",
",",
"key",
",",
"notes",
")",
":",
"template",
"=",
"{",
"'intermediateCertificate'",
":",
"''",
",",
"'certificateSigningRequest'",
":",
"''",
",",
"'notes'",
":",
"notes",
",",
"}",
"temp... | Add and upload SSL certificate details. | [
"Add",
"and",
"upload",
"SSL",
"certificate",
"details",
"."
] | python | train |
cirruscluster/cirruscluster | cirruscluster/cluster/mapr.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/mapr.py#L365-L376 | def __StartMaster(self):
""" Starts a master node, configures it, and starts services. """
num_masters = len(self.cluster.get_instances_in_role("master", "running"))
assert(num_masters < 1)
logging.info( "waiting for masters to start")
if self.config.master_on_spot_instances:
sel... | [
"def",
"__StartMaster",
"(",
"self",
")",
":",
"num_masters",
"=",
"len",
"(",
"self",
".",
"cluster",
".",
"get_instances_in_role",
"(",
"\"master\"",
",",
"\"running\"",
")",
")",
"assert",
"(",
"num_masters",
"<",
"1",
")",
"logging",
".",
"info",
"(",
... | Starts a master node, configures it, and starts services. | [
"Starts",
"a",
"master",
"node",
"configures",
"it",
"and",
"starts",
"services",
"."
] | python | train |
globus/globus-cli | globus_cli/helpers/auth_flows.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/helpers/auth_flows.py#L26-L62 | def do_link_auth_flow(session_params=None, force_new_client=False):
"""
Prompts the user with a link to authenticate with globus auth
and authorize the CLI to act on their behalf.
"""
session_params = session_params or {}
# get the ConfidentialApp client object
auth_client = internal_auth_c... | [
"def",
"do_link_auth_flow",
"(",
"session_params",
"=",
"None",
",",
"force_new_client",
"=",
"False",
")",
":",
"session_params",
"=",
"session_params",
"or",
"{",
"}",
"# get the ConfidentialApp client object",
"auth_client",
"=",
"internal_auth_client",
"(",
"require... | Prompts the user with a link to authenticate with globus auth
and authorize the CLI to act on their behalf. | [
"Prompts",
"the",
"user",
"with",
"a",
"link",
"to",
"authenticate",
"with",
"globus",
"auth",
"and",
"authorize",
"the",
"CLI",
"to",
"act",
"on",
"their",
"behalf",
"."
] | python | train |
teepark/greenhouse | greenhouse/emulation/__init__.py | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/emulation/__init__.py#L26-L72 | def patched(module_name):
"""import and return a named module with patches applied locally only
this function returns a module after importing it in such as way that it
will operate cooperatively, but not overriding the module globally.
>>> green_httplib = patched("httplib")
>>> # using green_http... | [
"def",
"patched",
"(",
"module_name",
")",
":",
"if",
"module_name",
"in",
"_patchers",
":",
"return",
"_patched_copy",
"(",
"module_name",
",",
"_patchers",
"[",
"module_name",
"]",
")",
"# grab the unpatched version of the module for posterity",
"old_module",
"=",
"... | import and return a named module with patches applied locally only
this function returns a module after importing it in such as way that it
will operate cooperatively, but not overriding the module globally.
>>> green_httplib = patched("httplib")
>>> # using green_httplib will only block greenlets
... | [
"import",
"and",
"return",
"a",
"named",
"module",
"with",
"patches",
"applied",
"locally",
"only"
] | python | train |
mushkevych/scheduler | synergy/workers/abstract_cli_worker.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/workers/abstract_cli_worker.py#L27-L49 | def _poll_process(self):
""" between death of a process and its actual termination lies poorly documented requirement -
<purging process' io pipes and reading exit status>.
this can be done either by os.wait() or process.wait()
:return tuple (boolean: alive, int: return_code)... | [
"def",
"_poll_process",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"self",
".",
"cli_process",
".",
"stderr",
".",
"read",
"(",
")",
")",
"self",
".",
"logger",
".",
"info",
"(",
"self",
".",
"cli_process",
".",
... | between death of a process and its actual termination lies poorly documented requirement -
<purging process' io pipes and reading exit status>.
this can be done either by os.wait() or process.wait()
:return tuple (boolean: alive, int: return_code) | [
"between",
"death",
"of",
"a",
"process",
"and",
"its",
"actual",
"termination",
"lies",
"poorly",
"documented",
"requirement",
"-",
"<purging",
"process",
"io",
"pipes",
"and",
"reading",
"exit",
"status",
">",
".",
"this",
"can",
"be",
"done",
"either",
"b... | python | train |
tanghaibao/jcvi | jcvi/apps/ks.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L412-L467 | def prepare(args):
"""
%prog prepare pairsfile cdsfile [pepfile] -o paired.cds.fasta
Pick sequences from cdsfile to form pairs, ready to be calculated. The
pairsfile can be generated from formats.blast.cscore(). The first two
columns contain the pair.
"""
from jcvi.formats.fasta import Fast... | [
"def",
"prepare",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"Fasta",
"p",
"=",
"OptionParser",
"(",
"prepare",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_arg... | %prog prepare pairsfile cdsfile [pepfile] -o paired.cds.fasta
Pick sequences from cdsfile to form pairs, ready to be calculated. The
pairsfile can be generated from formats.blast.cscore(). The first two
columns contain the pair. | [
"%prog",
"prepare",
"pairsfile",
"cdsfile",
"[",
"pepfile",
"]",
"-",
"o",
"paired",
".",
"cds",
".",
"fasta"
] | python | train |
josuebrunel/yahoo-oauth | yahoo_oauth/yahoo_oauth.py | https://github.com/josuebrunel/yahoo-oauth/blob/40eff7809366850c46e1a3340469044f33cd1713/yahoo_oauth/yahoo_oauth.py#L147-L156 | def generate_oauth2_headers(self):
"""Generates header for oauth2
"""
encoded_credentials = base64.b64encode(('{0}:{1}'.format(self.consumer_key,self.consumer_secret)).encode('utf-8'))
headers={
'Authorization':'Basic {0}'.format(encoded_credentials.decode('utf-8')),
... | [
"def",
"generate_oauth2_headers",
"(",
"self",
")",
":",
"encoded_credentials",
"=",
"base64",
".",
"b64encode",
"(",
"(",
"'{0}:{1}'",
".",
"format",
"(",
"self",
".",
"consumer_key",
",",
"self",
".",
"consumer_secret",
")",
")",
".",
"encode",
"(",
"'utf-... | Generates header for oauth2 | [
"Generates",
"header",
"for",
"oauth2"
] | python | valid |
jepegit/cellpy | cellpy/readers/cellreader.py | https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/cellreader.py#L3054-L3065 | def get_number_of_cycles(self, dataset_number=None, steptable=None):
"""Get the number of cycles in the test."""
if steptable is None:
dataset_number = self._validate_dataset_number(dataset_number)
if dataset_number is None:
self._report_empty_dataset()
... | [
"def",
"get_number_of_cycles",
"(",
"self",
",",
"dataset_number",
"=",
"None",
",",
"steptable",
"=",
"None",
")",
":",
"if",
"steptable",
"is",
"None",
":",
"dataset_number",
"=",
"self",
".",
"_validate_dataset_number",
"(",
"dataset_number",
")",
"if",
"da... | Get the number of cycles in the test. | [
"Get",
"the",
"number",
"of",
"cycles",
"in",
"the",
"test",
"."
] | python | train |
marcotcr/lime | lime/lime_text.py | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L182-L199 | def _segment_with_tokens(text, tokens):
"""Segment a string around the tokens created by a passed-in tokenizer"""
list_form = []
text_ptr = 0
for token in tokens:
inter_token_string = []
while not text[text_ptr:].startswith(token):
inter_token_stri... | [
"def",
"_segment_with_tokens",
"(",
"text",
",",
"tokens",
")",
":",
"list_form",
"=",
"[",
"]",
"text_ptr",
"=",
"0",
"for",
"token",
"in",
"tokens",
":",
"inter_token_string",
"=",
"[",
"]",
"while",
"not",
"text",
"[",
"text_ptr",
":",
"]",
".",
"st... | Segment a string around the tokens created by a passed-in tokenizer | [
"Segment",
"a",
"string",
"around",
"the",
"tokens",
"created",
"by",
"a",
"passed",
"-",
"in",
"tokenizer"
] | python | train |
pypyr/pypyr-cli | pypyr/steps/dsl/fileinoutrewriter.py | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/dsl/fileinoutrewriter.py#L133-L141 | def run_step(self):
"""Write in to out, replacing strings per the replace_pairs."""
formatted_replacements = self.context.get_formatted_iterable(
self.replace_pairs)
iter = StreamReplacePairsRewriterStep.iter_replace_strings(
formatted_replacements)
rewriter = St... | [
"def",
"run_step",
"(",
"self",
")",
":",
"formatted_replacements",
"=",
"self",
".",
"context",
".",
"get_formatted_iterable",
"(",
"self",
".",
"replace_pairs",
")",
"iter",
"=",
"StreamReplacePairsRewriterStep",
".",
"iter_replace_strings",
"(",
"formatted_replacem... | Write in to out, replacing strings per the replace_pairs. | [
"Write",
"in",
"to",
"out",
"replacing",
"strings",
"per",
"the",
"replace_pairs",
"."
] | python | train |
hydpy-dev/hydpy | hydpy/auxs/armatools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L725-L740 | def plot(self, threshold=None, **kwargs):
"""Barplot of the ARMA response."""
try:
# Works under matplotlib 3.
pyplot.bar(x=self.ma.delays+.5, height=self.response,
width=1., fill=False, **kwargs)
except TypeError: # pragma: no cover
#... | [
"def",
"plot",
"(",
"self",
",",
"threshold",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# Works under matplotlib 3.",
"pyplot",
".",
"bar",
"(",
"x",
"=",
"self",
".",
"ma",
".",
"delays",
"+",
".5",
",",
"height",
"=",
"self",
"... | Barplot of the ARMA response. | [
"Barplot",
"of",
"the",
"ARMA",
"response",
"."
] | python | train |
google/grr | grr/server/grr_response_server/console_utils.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L491-L538 | def ExportClientsByKeywords(keywords, filename, token=None):
r"""A script to export clients summaries selected by a keyword search.
This script does a client search for machines matching all of keywords and
writes a .csv summary of the results to filename. Multi-value fields are '\n'
separated.
Args:
ke... | [
"def",
"ExportClientsByKeywords",
"(",
"keywords",
",",
"filename",
",",
"token",
"=",
"None",
")",
":",
"index",
"=",
"client_index",
".",
"CreateClientIndex",
"(",
"token",
"=",
"token",
")",
"client_list",
"=",
"index",
".",
"LookupClients",
"(",
"keywords"... | r"""A script to export clients summaries selected by a keyword search.
This script does a client search for machines matching all of keywords and
writes a .csv summary of the results to filename. Multi-value fields are '\n'
separated.
Args:
keywords: a list of keywords to search for
filename: the name... | [
"r",
"A",
"script",
"to",
"export",
"clients",
"summaries",
"selected",
"by",
"a",
"keyword",
"search",
"."
] | python | train |
Vito2015/pyextend | pyextend/core/log.py | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L192-L212 | def set_logger(name=None, filename=None, mode='a', level='NOTSET:NOTSET',
fmt=
'%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelname)-7s] %(message)s',
# fmt='[%(levelname)s] %(asctime)s %(message)s',
backup_count=5, limit=20480,... | [
"def",
"set_logger",
"(",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"mode",
"=",
"'a'",
",",
"level",
"=",
"'NOTSET:NOTSET'",
",",
"fmt",
"=",
"'%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelname)-7s] %(message)s'",
",",
"#... | Configure the global logger. | [
"Configure",
"the",
"global",
"logger",
"."
] | python | train |
openstack/python-scciclient | scciclient/irmc/elcm.py | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L974-L1000 | def _create_raid_adapter_profile(irmc_info):
"""Attempt delete exist adapter then create new raid adapter on the server.
:param irmc_info: node info
:returns: result: a dict with following values:
{
'raid_config': <data of raid adapter profile>,
'warn... | [
"def",
"_create_raid_adapter_profile",
"(",
"irmc_info",
")",
":",
"try",
":",
"# Attempt erase exist adapter on BM Server",
"elcm_profile_delete",
"(",
"irmc_info",
",",
"PROFILE_RAID_CONFIG",
")",
"except",
"ELCMProfileNotFound",
":",
"# Ignore this error as it's not an error i... | Attempt delete exist adapter then create new raid adapter on the server.
:param irmc_info: node info
:returns: result: a dict with following values:
{
'raid_config': <data of raid adapter profile>,
'warning': <warning message if there is>
... | [
"Attempt",
"delete",
"exist",
"adapter",
"then",
"create",
"new",
"raid",
"adapter",
"on",
"the",
"server",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/image/detection.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L235-L250 | def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height):
"""Check if constrains are satisfied"""
if (xmax - xmin) * (ymax - ymin) < 2:
return False # only 1 pixel
x1 = float(xmin) / width
y1 = float(ymin) / height
x2 = float(xmax) / width
... | [
"def",
"_check_satisfy_constraints",
"(",
"self",
",",
"label",
",",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
",",
"width",
",",
"height",
")",
":",
"if",
"(",
"xmax",
"-",
"xmin",
")",
"*",
"(",
"ymax",
"-",
"ymin",
")",
"<",
"2",
":",
"re... | Check if constrains are satisfied | [
"Check",
"if",
"constrains",
"are",
"satisfied"
] | python | train |
SiLab-Bonn/pyBAR | pybar/analysis/analyze_raw_data.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/analysis/analyze_raw_data.py#L643-L921 | def interpret_word_table(self, analyzed_data_file=None, use_settings_from_file=True, fei4b=None):
'''Interprets the raw data word table of all given raw data files with the c++ library.
Creates the h5 output file and PDF plots.
Parameters
----------
analyzed_data_file : string
... | [
"def",
"interpret_word_table",
"(",
"self",
",",
"analyzed_data_file",
"=",
"None",
",",
"use_settings_from_file",
"=",
"True",
",",
"fei4b",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"'Interpreting raw data file(s): '",
"+",
"(",
"', '",
")",
".",
"... | Interprets the raw data word table of all given raw data files with the c++ library.
Creates the h5 output file and PDF plots.
Parameters
----------
analyzed_data_file : string
The file name of the output analyzed data file. If None, the output analyzed data file
... | [
"Interprets",
"the",
"raw",
"data",
"word",
"table",
"of",
"all",
"given",
"raw",
"data",
"files",
"with",
"the",
"c",
"++",
"library",
".",
"Creates",
"the",
"h5",
"output",
"file",
"and",
"PDF",
"plots",
"."
] | python | train |
IAMconsortium/pyam | pyam/core.py | https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1084-L1131 | def load_metadata(self, path, *args, **kwargs):
"""Load metadata exported from `pyam.IamDataFrame` instance
Parameters
----------
path: string
xlsx file with metadata exported from `pyam.IamDataFrame` instance
"""
if not os.path.exists(path):
rais... | [
"def",
"load_metadata",
"(",
"self",
",",
"path",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"ValueError",
"(",
"\"no metadata file '\"",
"+",
"path",
"+",
"\"' ... | Load metadata exported from `pyam.IamDataFrame` instance
Parameters
----------
path: string
xlsx file with metadata exported from `pyam.IamDataFrame` instance | [
"Load",
"metadata",
"exported",
"from",
"pyam",
".",
"IamDataFrame",
"instance"
] | python | train |
happyleavesaoc/python-limitlessled | limitlessled/group/rgbww.py | https://github.com/happyleavesaoc/python-limitlessled/blob/70307c2bf8c91430a99579d2ad18b228ec7a8488/limitlessled/group/rgbww.py#L157-L195 | def transition(self, duration,
color=None, brightness=None, temperature=None):
""" Transition wrapper.
Short-circuit transition as necessary.
:param duration: Time to transition.
:param color: Transition to this color.
:param brightness: Transition to this br... | [
"def",
"transition",
"(",
"self",
",",
"duration",
",",
"color",
"=",
"None",
",",
"brightness",
"=",
"None",
",",
"temperature",
"=",
"None",
")",
":",
"if",
"color",
"and",
"temperature",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot ... | Transition wrapper.
Short-circuit transition as necessary.
:param duration: Time to transition.
:param color: Transition to this color.
:param brightness: Transition to this brightness.
:param temperature: Transition to this temperature. | [
"Transition",
"wrapper",
"."
] | python | train |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/ir_lowering_common.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/ir_lowering_common.py#L14-L29 | def merge_consecutive_filter_clauses(ir_blocks):
"""Merge consecutive Filter(x), Filter(y) blocks into Filter(x && y) block."""
if not ir_blocks:
return ir_blocks
new_ir_blocks = [ir_blocks[0]]
for block in ir_blocks[1:]:
last_block = new_ir_blocks[-1]
if isinstance(last_block,... | [
"def",
"merge_consecutive_filter_clauses",
"(",
"ir_blocks",
")",
":",
"if",
"not",
"ir_blocks",
":",
"return",
"ir_blocks",
"new_ir_blocks",
"=",
"[",
"ir_blocks",
"[",
"0",
"]",
"]",
"for",
"block",
"in",
"ir_blocks",
"[",
"1",
":",
"]",
":",
"last_block",... | Merge consecutive Filter(x), Filter(y) blocks into Filter(x && y) block. | [
"Merge",
"consecutive",
"Filter",
"(",
"x",
")",
"Filter",
"(",
"y",
")",
"blocks",
"into",
"Filter",
"(",
"x",
"&&",
"y",
")",
"block",
"."
] | python | train |
cltk/cltk | cltk/phonology/syllabify.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/syllabify.py#L330-L379 | def legal_onsets(self, syllables):
"""
Filters syllable respecting the legality principle
:param syllables: str list
Example:
The method scans for invalid syllable onsets:
>>> s = Syllabifier(["i", "u", "y"], ["o", "ø", "e"], ["a"], ["r"], ["l"], ["m", "n"], ["f... | [
"def",
"legal_onsets",
"(",
"self",
",",
"syllables",
")",
":",
"vowels",
"=",
"self",
".",
"vowels",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"syllables",
")",
")",
":",
"onset",
"=",
"\"\"",
"for",
"letter",
"in",
"syllables",
"[",
"... | Filters syllable respecting the legality principle
:param syllables: str list
Example:
The method scans for invalid syllable onsets:
>>> s = Syllabifier(["i", "u", "y"], ["o", "ø", "e"], ["a"], ["r"], ["l"], ["m", "n"], ["f", "v", "s", "h"], ["k", "g", "b", "p", "t", "d"])
... | [
"Filters",
"syllable",
"respecting",
"the",
"legality",
"principle",
":",
"param",
"syllables",
":",
"str",
"list"
] | python | train |
erikrose/more-itertools | more_itertools/more.py | https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L715-L746 | def substrings_indexes(seq, reverse=False):
"""Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` objects.
>>> for item i... | [
"def",
"substrings_indexes",
"(",
"seq",
",",
"reverse",
"=",
"False",
")",
":",
"r",
"=",
"range",
"(",
"1",
",",
"len",
"(",
"seq",
")",
"+",
"1",
")",
"if",
"reverse",
":",
"r",
"=",
"reversed",
"(",
"r",
")",
"return",
"(",
"(",
"seq",
"[",... | Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` objects.
>>> for item in substrings_indexes('more'):
... print(item... | [
"Yield",
"all",
"substrings",
"and",
"their",
"positions",
"in",
"*",
"seq",
"*"
] | python | train |
rwl/pylon | pylon/case.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/case.py#L925-L929 | def save_matpower(self, fd):
""" Serialize the case as a MATPOWER data file.
"""
from pylon.io import MATPOWERWriter
MATPOWERWriter(self).write(fd) | [
"def",
"save_matpower",
"(",
"self",
",",
"fd",
")",
":",
"from",
"pylon",
".",
"io",
"import",
"MATPOWERWriter",
"MATPOWERWriter",
"(",
"self",
")",
".",
"write",
"(",
"fd",
")"
] | Serialize the case as a MATPOWER data file. | [
"Serialize",
"the",
"case",
"as",
"a",
"MATPOWER",
"data",
"file",
"."
] | python | train |
port-zero/mite | mite/mite.py | https://github.com/port-zero/mite/blob/b5fa941f60bf43e04ef654ed580ed7ef91211c22/mite/mite.py#L229-L237 | def create_customer(self, name, **kwargs):
"""
Creates a customer with a name. All other parameters are optional. They
are: `note`, `active_hourly_rate`, `hourly_rate`,
`hourly_rates_per_service`, and `archived`.
"""
data = self._wrap_dict("customer", kwargs)
data... | [
"def",
"create_customer",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"_wrap_dict",
"(",
"\"customer\"",
",",
"kwargs",
")",
"data",
"[",
"\"customer\"",
"]",
"[",
"\"name\"",
"]",
"=",
"name",
"return",
"self... | Creates a customer with a name. All other parameters are optional. They
are: `note`, `active_hourly_rate`, `hourly_rate`,
`hourly_rates_per_service`, and `archived`. | [
"Creates",
"a",
"customer",
"with",
"a",
"name",
".",
"All",
"other",
"parameters",
"are",
"optional",
".",
"They",
"are",
":",
"note",
"active_hourly_rate",
"hourly_rate",
"hourly_rates_per_service",
"and",
"archived",
"."
] | python | train |
tonybaloney/wily | wily/commands/index.py | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/commands/index.py#L13-L61 | def index(config, include_message=False):
"""
Show information about the cache and runtime.
:param config: The wily configuration
:type config: :namedtuple:`wily.config.WilyConfig`
:param include_message: Include revision messages
:type include_message: ``bool``
"""
state = State(con... | [
"def",
"index",
"(",
"config",
",",
"include_message",
"=",
"False",
")",
":",
"state",
"=",
"State",
"(",
"config",
"=",
"config",
")",
"logger",
".",
"debug",
"(",
"\"Running show command\"",
")",
"logger",
".",
"info",
"(",
"\"--------Configuration---------... | Show information about the cache and runtime.
:param config: The wily configuration
:type config: :namedtuple:`wily.config.WilyConfig`
:param include_message: Include revision messages
:type include_message: ``bool`` | [
"Show",
"information",
"about",
"the",
"cache",
"and",
"runtime",
"."
] | python | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/common.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L163-L168 | def set (self, id, param, value):
""" Sets the value of a configuration parameter. """
assert isinstance(id, basestring)
assert isinstance(param, basestring)
assert is_iterable_typed(value, basestring)
self.params_.setdefault(param, {})[id] = value | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"param",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"param",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basest... | Sets the value of a configuration parameter. | [
"Sets",
"the",
"value",
"of",
"a",
"configuration",
"parameter",
"."
] | python | train |
rigetti/grove | grove/tomography/tomography.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/tomography.py#L111-L135 | def is_functional(cls):
"""
Checks lazily whether a convex solver is installed that handles positivity constraints.
:return: True if a solver supporting positivity constraints is installed.
:rtype: bool
"""
if not cls._tested:
cls._tested = True
n... | [
"def",
"is_functional",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"_tested",
":",
"cls",
".",
"_tested",
"=",
"True",
"np",
".",
"random",
".",
"seed",
"(",
"SEED",
")",
"test_problem_dimension",
"=",
"10",
"mat",
"=",
"np",
".",
"random",
".",
... | Checks lazily whether a convex solver is installed that handles positivity constraints.
:return: True if a solver supporting positivity constraints is installed.
:rtype: bool | [
"Checks",
"lazily",
"whether",
"a",
"convex",
"solver",
"is",
"installed",
"that",
"handles",
"positivity",
"constraints",
"."
] | python | train |
SwoopSearch/pyaddress | address/address.py | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L377-L393 | def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffi... | [
"def",
"check_street_suffix",
"(",
"self",
",",
"token",
")",
":",
"# Suffix must come before street",
"# print \"Suffix check\", token, \"suffix\", self.street_suffix, \"street\", self.street",
"if",
"self",
".",
"street_suffix",
"is",
"None",
"and",
"self",
".",
"street",
"... | Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave." | [
"Attempts",
"to",
"match",
"a",
"street",
"suffix",
".",
"If",
"found",
"it",
"will",
"return",
"the",
"abbreviation",
"with",
"the",
"first",
"letter",
"capitalized",
"and",
"a",
"period",
"after",
"it",
".",
"E",
".",
"g",
".",
"St",
".",
"or",
"Ave"... | python | train |
bbangert/lettuce_webdriver | lettuce_webdriver/util.py | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L79-L85 | def _elements(self):
"""
The cached list of elements.
"""
if not hasattr(self, '_elements_cached'):
setattr(self, '_elements_cached', list(self._select()))
return self._elements_cached | [
"def",
"_elements",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_elements_cached'",
")",
":",
"setattr",
"(",
"self",
",",
"'_elements_cached'",
",",
"list",
"(",
"self",
".",
"_select",
"(",
")",
")",
")",
"return",
"self",
".",... | The cached list of elements. | [
"The",
"cached",
"list",
"of",
"elements",
"."
] | python | train |
AmanoTeam/amanobot | amanobot/aio/__init__.py | https://github.com/AmanoTeam/amanobot/blob/fe546e2e294eec88e637da0b2567c7e7e8662437/amanobot/aio/__init__.py#L521-L530 | async def editMessageMedia(self, msg_identifier, media,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagemedia
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`
"""
p = _strip(lo... | [
"async",
"def",
"editMessageMedia",
"(",
"self",
",",
"msg_identifier",
",",
"media",
",",
"reply_markup",
"=",
"None",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
",",
"more",
"=",
"[",
"'msg_identifier'",
"]",
")",
"p",
".",
"update",
"(",... | See: https://core.telegram.org/bots/api#editmessagemedia
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText` | [
"See",
":",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api#editmessagemedia"
] | python | train |
MycroftAI/mycroft-precise | precise/util.py | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/util.py#L31-L33 | def buffer_to_audio(buffer: bytes) -> np.ndarray:
"""Convert a raw mono audio byte string to numpy array of floats"""
return np.fromstring(buffer, dtype='<i2').astype(np.float32, order='C') / 32768.0 | [
"def",
"buffer_to_audio",
"(",
"buffer",
":",
"bytes",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"np",
".",
"fromstring",
"(",
"buffer",
",",
"dtype",
"=",
"'<i2'",
")",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"order",
"=",
"'C'",
")",
... | Convert a raw mono audio byte string to numpy array of floats | [
"Convert",
"a",
"raw",
"mono",
"audio",
"byte",
"string",
"to",
"numpy",
"array",
"of",
"floats"
] | python | train |
lwcook/horsetail-matching | horsetailmatching/hm.py | https://github.com/lwcook/horsetail-matching/blob/f3d5f8d01249debbca978f412ce4eae017458119/horsetailmatching/hm.py#L921-L936 | def _matrix_integration(q, h, t):
''' Returns the dp metric for a single horsetail
curve at a given value of the epistemic uncertainties'''
N = len(q)
# correction if CDF has gone out of trapezium range
if h[-1] < 0.9: h[-1] = 1.0
W = np.zeros([N, N])
for i in range(N):
W[i, i] = ... | [
"def",
"_matrix_integration",
"(",
"q",
",",
"h",
",",
"t",
")",
":",
"N",
"=",
"len",
"(",
"q",
")",
"# correction if CDF has gone out of trapezium range",
"if",
"h",
"[",
"-",
"1",
"]",
"<",
"0.9",
":",
"h",
"[",
"-",
"1",
"]",
"=",
"1.0",
"W",
"... | Returns the dp metric for a single horsetail
curve at a given value of the epistemic uncertainties | [
"Returns",
"the",
"dp",
"metric",
"for",
"a",
"single",
"horsetail",
"curve",
"at",
"a",
"given",
"value",
"of",
"the",
"epistemic",
"uncertainties"
] | python | train |
wright-group/WrightTools | WrightTools/artists/_helpers.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L53-L75 | def _title(fig, title, subtitle="", *, margin=1, fontsize=20, subfontsize=18):
"""Add a title to a figure.
Parameters
----------
fig : matplotlib Figure
Figure.
title : string
Title.
subtitle : string
Subtitle.
margin : number (optional)
Distance from top of ... | [
"def",
"_title",
"(",
"fig",
",",
"title",
",",
"subtitle",
"=",
"\"\"",
",",
"*",
",",
"margin",
"=",
"1",
",",
"fontsize",
"=",
"20",
",",
"subfontsize",
"=",
"18",
")",
":",
"fig",
".",
"suptitle",
"(",
"title",
",",
"fontsize",
"=",
"fontsize",... | Add a title to a figure.
Parameters
----------
fig : matplotlib Figure
Figure.
title : string
Title.
subtitle : string
Subtitle.
margin : number (optional)
Distance from top of plot, in inches. Default is 1.
fontsize : number (optional)
Title fontsize... | [
"Add",
"a",
"title",
"to",
"a",
"figure",
"."
] | python | train |
log2timeline/plaso | plaso/analysis/chrome_extension.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/chrome_extension.py#L154-L207 | def ExamineEvent(self, mediator, event):
"""Analyzes an event.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
event (EventObject): event to examine.
"""
# Only interested in filesystem events.
... | [
"def",
"ExamineEvent",
"(",
"self",
",",
"mediator",
",",
"event",
")",
":",
"# Only interested in filesystem events.",
"if",
"event",
".",
"data_type",
"!=",
"'fs:stat'",
":",
"return",
"filename",
"=",
"getattr",
"(",
"event",
",",
"'filename'",
",",
"None",
... | Analyzes an event.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
event (EventObject): event to examine. | [
"Analyzes",
"an",
"event",
"."
] | python | train |
twilio/twilio-python | twilio/base/serialize.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/base/serialize.py#L22-L32 | def iso8601_datetime(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date):
... | [
"def",
"iso8601_datetime",
"(",
"d",
")",
":",
"if",
"d",
"==",
"values",
".",
"unset",
":",
"return",
"d",
"elif",
"isinstance",
"(",
"d",
",",
"datetime",
".",
"datetime",
")",
"or",
"isinstance",
"(",
"d",
",",
"datetime",
".",
"date",
")",
":",
... | Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date | [
"Return",
"a",
"string",
"representation",
"of",
"a",
"date",
"that",
"the",
"Twilio",
"API",
"understands",
"Format",
"is",
"YYYY",
"-",
"MM",
"-",
"DD",
".",
"Returns",
"None",
"if",
"d",
"is",
"not",
"a",
"string",
"datetime",
"or",
"date"
] | python | train |
lobocv/pyperform | pyperform/tools.py | https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/tools.py#L48-L64 | def remove_decorators(src):
""" Remove decorators from the source code """
src = src.strip()
src_lines = src.splitlines()
multi_line = False
n_deleted = 0
for n in range(len(src_lines)):
line = src_lines[n - n_deleted].strip()
if (line.startswith('@') and 'Benchmark' in line) or ... | [
"def",
"remove_decorators",
"(",
"src",
")",
":",
"src",
"=",
"src",
".",
"strip",
"(",
")",
"src_lines",
"=",
"src",
".",
"splitlines",
"(",
")",
"multi_line",
"=",
"False",
"n_deleted",
"=",
"0",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"src_lin... | Remove decorators from the source code | [
"Remove",
"decorators",
"from",
"the",
"source",
"code"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.