repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
mitsei/dlkit | dlkit/json_/resource/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/sessions.py#L3075-L3094 | def is_descendant_of_bin(self, id_, bin_id):
"""Tests if an ``Id`` is a descendant of a bin.
arg: id (osid.id.Id): an ``Id``
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bin_id,`` ``false`` other... | [
"def",
"is_descendant_of_bin",
"(",
"self",
",",
"id_",
",",
"bin_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_descendant_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_cata... | Tests if an ``Id`` is a descendant of a bin.
arg: id (osid.id.Id): an ``Id``
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bin_id,`` ``false`` otherwise
raise: NotFound - ``bin_id`` is not found
... | [
"Tests",
"if",
"an",
"Id",
"is",
"a",
"descendant",
"of",
"a",
"bin",
"."
] | python | train | 51.05 |
senaite/senaite.core | bika/lims/browser/analysisrequest/manage_analyses.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analysisrequest/manage_analyses.py#L175-L180 | def folderitems(self):
"""XXX refactor if possible to non-classic mode
"""
items = super(AnalysisRequestAnalysesView, self).folderitems()
self.categories.sort()
return items | [
"def",
"folderitems",
"(",
"self",
")",
":",
"items",
"=",
"super",
"(",
"AnalysisRequestAnalysesView",
",",
"self",
")",
".",
"folderitems",
"(",
")",
"self",
".",
"categories",
".",
"sort",
"(",
")",
"return",
"items"
] | XXX refactor if possible to non-classic mode | [
"XXX",
"refactor",
"if",
"possible",
"to",
"non",
"-",
"classic",
"mode"
] | python | train | 34.666667 |
the01/python-paps | paps/si/app/sensorServer.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L326-L342 | def _add_membership_multicast_socket(self):
"""
Make membership request to multicast
:rtype: None
"""
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
... | [
"def",
"_add_membership_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"_membership_request",
"=",
"socket",
".",
"inet_aton",
"(",
"self",
".",
"_multicast_group",
")",
"+",
"socket",
".",
"inet_aton",
"(",
"self",
".",
"_multicast_ip",
")",
"# Send add... | Make membership request to multicast
:rtype: None | [
"Make",
"membership",
"request",
"to",
"multicast"
] | python | train | 32.647059 |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L4427-L4474 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self,
'credential_type') and self.credential_type is not None:
_dict['credential_type'] = self.credential_type
if hasattr(self, 'client_id') and self.client_id... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'credential_type'",
")",
"and",
"self",
".",
"credential_type",
"is",
"not",
"None",
":",
"_dict",
"[",
"'credential_type'",
"]",
"=",
"self",
".",
"c... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train | 55.145833 |
yaml/pyyaml | lib/yaml/__init__.py | https://github.com/yaml/pyyaml/blob/e471e86bf6dabdad45a1438c20a4a5c033eb9034/lib/yaml/__init__.py#L288-L293 | def dump(data, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=Dumper, **kwds) | [
"def",
"dump",
"(",
"data",
",",
"stream",
"=",
"None",
",",
"Dumper",
"=",
"Dumper",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"dump_all",
"(",
"[",
"data",
"]",
",",
"stream",
",",
"Dumper",
"=",
"Dumper",
",",
"*",
"*",
"kwds",
")"
] | Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead. | [
"Serialize",
"a",
"Python",
"object",
"into",
"a",
"YAML",
"stream",
".",
"If",
"stream",
"is",
"None",
"return",
"the",
"produced",
"string",
"instead",
"."
] | python | train | 38.333333 |
simoninireland/epyc | epyc/summaryexperiment.py | https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/summaryexperiment.py#L76-L110 | def summarise( self, results ):
"""Generate a summary of results from a list of result dicts
returned by running the underlying experiment. By default we generate
mean, median, variance, and extrema for each value recorded.
Override this method to create different or extra summary stati... | [
"def",
"summarise",
"(",
"self",
",",
"results",
")",
":",
"if",
"len",
"(",
"results",
")",
"==",
"0",
":",
"return",
"dict",
"(",
")",
"else",
":",
"summary",
"=",
"dict",
"(",
")",
"# work out the fields to summarise",
"allKeys",
"=",
"results",
"[",
... | Generate a summary of results from a list of result dicts
returned by running the underlying experiment. By default we generate
mean, median, variance, and extrema for each value recorded.
Override this method to create different or extra summary statistics.
:param results: an array of... | [
"Generate",
"a",
"summary",
"of",
"results",
"from",
"a",
"list",
"of",
"result",
"dicts",
"returned",
"by",
"running",
"the",
"underlying",
"experiment",
".",
"By",
"default",
"we",
"generate",
"mean",
"median",
"variance",
"and",
"extrema",
"for",
"each",
... | python | train | 41.714286 |
f3at/feat | src/feat/agents/monitor/monitor_agent.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/agents/monitor/monitor_agent.py#L560-L568 | def restart_complete(self, state, new_address):
'''
Called when we get notified that the restart has been completed by
some agent who has volontureed to do so.
'''
if state.timeout_call_id:
state.agent.cancel_delayed_call(state.timeout_call_id)
state.timeo... | [
"def",
"restart_complete",
"(",
"self",
",",
"state",
",",
"new_address",
")",
":",
"if",
"state",
".",
"timeout_call_id",
":",
"state",
".",
"agent",
".",
"cancel_delayed_call",
"(",
"state",
".",
"timeout_call_id",
")",
"state",
".",
"timeout_call_id",
"=",
... | Called when we get notified that the restart has been completed by
some agent who has volontureed to do so. | [
"Called",
"when",
"we",
"get",
"notified",
"that",
"the",
"restart",
"has",
"been",
"completed",
"by",
"some",
"agent",
"who",
"has",
"volontureed",
"to",
"do",
"so",
"."
] | python | train | 43.555556 |
andresriancho/docker-tag-naming | docker_tag_naming/utils.py | https://github.com/andresriancho/docker-tag-naming/blob/8c043d69a63fb2fa9f38eda5bee1c0d7a3fd1b2b/docker_tag_naming/utils.py#L208-L219 | def get_all_tags(image_name, branch=None):
"""
GET /v1/repositories/<namespace>/<repository_name>/tags
:param image_name: The docker image name
:param branch: The branch to filter by
:return: A list of Version instances, latest first
"""
try:
return get_all_tags_no_auth(image_name, ... | [
"def",
"get_all_tags",
"(",
"image_name",
",",
"branch",
"=",
"None",
")",
":",
"try",
":",
"return",
"get_all_tags_no_auth",
"(",
"image_name",
",",
"branch",
")",
"except",
"AuthException",
":",
"return",
"get_all_tags_with_auth",
"(",
"image_name",
",",
"bran... | GET /v1/repositories/<namespace>/<repository_name>/tags
:param image_name: The docker image name
:param branch: The branch to filter by
:return: A list of Version instances, latest first | [
"GET",
"/",
"v1",
"/",
"repositories",
"/",
"<namespace",
">",
"/",
"<repository_name",
">",
"/",
"tags"
] | python | train | 33.333333 |
Godley/MuseParse | MuseParse/classes/ObjectHierarchy/ItemClasses/Directions.py | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/ObjectHierarchy/ItemClasses/Directions.py#L33-L46 | def get(self):
"""
method to fetch all contents as a list
:return: list
"""
ret_list = []
if hasattr(self, "font"):
ret_list.append(self.font)
if hasattr(self, "size"):
ret_list.append(self.size)
if hasattr(self, "text"):
... | [
"def",
"get",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"self",
",",
"\"font\"",
")",
":",
"ret_list",
".",
"append",
"(",
"self",
".",
"font",
")",
"if",
"hasattr",
"(",
"self",
",",
"\"size\"",
")",
":",
"ret_list",
... | method to fetch all contents as a list
:return: list | [
"method",
"to",
"fetch",
"all",
"contents",
"as",
"a",
"list"
] | python | train | 25.714286 |
desbma/GoogleSpeech | google_speech/__init__.py | https://github.com/desbma/GoogleSpeech/blob/6d3ec62dc26400ccb4f2e77b8ccd4cb416141233/google_speech/__init__.py#L236-L252 | def play(self, sox_effects=()):
""" Play the segment. """
audio_data = self.getAudioData()
logging.getLogger().info("Playing speech segment (%s): '%s'" % (self.lang, self))
cmd = ["sox", "-q", "-t", "mp3", "-"]
if sys.platform.startswith("win32"):
cmd.extend(("-t", "waveaudio"))
cmd.extend... | [
"def",
"play",
"(",
"self",
",",
"sox_effects",
"=",
"(",
")",
")",
":",
"audio_data",
"=",
"self",
".",
"getAudioData",
"(",
")",
"logging",
".",
"getLogger",
"(",
")",
".",
"info",
"(",
"\"Playing speech segment (%s): '%s'\"",
"%",
"(",
"self",
".",
"l... | Play the segment. | [
"Play",
"the",
"segment",
"."
] | python | train | 43.411765 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L1092-L1102 | def get_experiment_summ_ids( self, coinc_event_id ):
"""
Gets all the experiment_summ_ids that map to a given coinc_event_id.
"""
experiment_summ_ids = []
for row in self:
if row.coinc_event_id == coinc_event_id:
experiment_summ_ids.append(row.experiment_summ_id)
if len(experiment_summ_ids) == 0:
... | [
"def",
"get_experiment_summ_ids",
"(",
"self",
",",
"coinc_event_id",
")",
":",
"experiment_summ_ids",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
":",
"if",
"row",
".",
"coinc_event_id",
"==",
"coinc_event_id",
":",
"experiment_summ_ids",
".",
"append",
"(",
"... | Gets all the experiment_summ_ids that map to a given coinc_event_id. | [
"Gets",
"all",
"the",
"experiment_summ_ids",
"that",
"map",
"to",
"a",
"given",
"coinc_event_id",
"."
] | python | train | 38.818182 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L2241-L2263 | def FindSourceFiles(self, node='.'):
""" returns a list of all source files.
"""
node = self.arg2nodes(node, self.fs.Entry)[0]
sources = []
def build_source(ss):
for s in ss:
if isinstance(s, SCons.Node.FS.Dir):
build_source(s.all_... | [
"def",
"FindSourceFiles",
"(",
"self",
",",
"node",
"=",
"'.'",
")",
":",
"node",
"=",
"self",
".",
"arg2nodes",
"(",
"node",
",",
"self",
".",
"fs",
".",
"Entry",
")",
"[",
"0",
"]",
"sources",
"=",
"[",
"]",
"def",
"build_source",
"(",
"ss",
")... | returns a list of all source files. | [
"returns",
"a",
"list",
"of",
"all",
"source",
"files",
"."
] | python | train | 34.565217 |
chibisov/drf-extensions | docs/backdoc.py | https://github.com/chibisov/drf-extensions/blob/1d28a4b28890eab5cd19e93e042f8590c8c2fb8b/docs/backdoc.py#L2082-L2095 | def _dedent(text, tabsize=8, skip_first_line=False):
"""_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
"text" is the text to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should
... | [
"def",
"_dedent",
"(",
"text",
",",
"tabsize",
"=",
"8",
",",
"skip_first_line",
"=",
"False",
")",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
"1",
")",
"_dedentlines",
"(",
"lines",
",",
"tabsize",
"=",
"tabsize",
",",
"skip_first_line",
"=",
... | _dedent(text, tabsize=8, skip_first_line=False) -> dedented text
"text" is the text to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should
be skipped for calculating the indent width and for dede... | [
"_dedent",
"(",
"text",
"tabsize",
"=",
"8",
"skip_first_line",
"=",
"False",
")",
"-",
">",
"dedented",
"text"
] | python | train | 45.285714 |
fm4d/KickassAPI | KickassAPI.py | https://github.com/fm4d/KickassAPI/blob/6ecc6846dcec0d6f6e493bf776031aa92d55604f/KickassAPI.py#L328-L336 | def order(self, field, order=None):
"""
Set field and order set by arguments
"""
if not order:
order = ORDER.DESC
self.url.order = (field, order)
self.url.set_page(1)
return self | [
"def",
"order",
"(",
"self",
",",
"field",
",",
"order",
"=",
"None",
")",
":",
"if",
"not",
"order",
":",
"order",
"=",
"ORDER",
".",
"DESC",
"self",
".",
"url",
".",
"order",
"=",
"(",
"field",
",",
"order",
")",
"self",
".",
"url",
".",
"set... | Set field and order set by arguments | [
"Set",
"field",
"and",
"order",
"set",
"by",
"arguments"
] | python | train | 26.444444 |
opereto/pyopereto | pyopereto/client.py | https://github.com/opereto/pyopereto/blob/16ca987738a7e1b82b52b0b099794a74ed557223/pyopereto/client.py#L1148-L1159 | def get_process_rca(self, pid=None):
'''
get_process_rca(self, pid=None)
Get the RCA tree of a given failed process. The RCA tree contains all failed child processes that caused the failure of the given process.
:Parameters:
* *pid* (`string`) -- Identifier of an existing proce... | [
"def",
"get_process_rca",
"(",
"self",
",",
"pid",
"=",
"None",
")",
":",
"pid",
"=",
"self",
".",
"_get_pid",
"(",
"pid",
")",
"return",
"self",
".",
"_call_rest_api",
"(",
"'get'",
",",
"'/processes/'",
"+",
"pid",
"+",
"'/rca'",
",",
"error",
"=",
... | get_process_rca(self, pid=None)
Get the RCA tree of a given failed process. The RCA tree contains all failed child processes that caused the failure of the given process.
:Parameters:
* *pid* (`string`) -- Identifier of an existing process | [
"get_process_rca",
"(",
"self",
"pid",
"=",
"None",
")"
] | python | train | 39.166667 |
crytic/slither | utils/possible_paths/possible_paths.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/utils/possible_paths/possible_paths.py#L4-L26 | def resolve_function(slither, contract_name, function_name):
"""
Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:return: Returns the resolved func... | [
"def",
"resolve_function",
"(",
"slither",
",",
"contract_name",
",",
"function_name",
")",
":",
"# Obtain the target contract",
"contract",
"=",
"slither",
".",
"get_contract_from_name",
"(",
"contract_name",
")",
"# Verify the contract was resolved successfully",
"if",
"c... | Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:return: Returns the resolved function, raises an exception otherwise. | [
"Resolves",
"a",
"function",
"instance",
"given",
"a",
"contract",
"name",
"and",
"function",
".",
":",
"param",
"contract_name",
":",
"The",
"name",
"of",
"the",
"contract",
"the",
"function",
"is",
"declared",
"in",
".",
":",
"param",
"function_name",
":",... | python | train | 44.782609 |
instana/python-sensor | instana/meter.py | https://github.com/instana/python-sensor/blob/58aecb90924c48bafcbc4f93bd9b7190980918bc/instana/meter.py#L158-L189 | def process(self):
""" Collects, processes & reports metrics """
if self.agent.machine.fsm.current is "wait4init":
# Test the host agent if we're ready to send data
if self.agent.is_agent_ready():
self.agent.machine.fsm.ready()
else:
re... | [
"def",
"process",
"(",
"self",
")",
":",
"if",
"self",
".",
"agent",
".",
"machine",
".",
"fsm",
".",
"current",
"is",
"\"wait4init\"",
":",
"# Test the host agent if we're ready to send data",
"if",
"self",
".",
"agent",
".",
"is_agent_ready",
"(",
")",
":",
... | Collects, processes & reports metrics | [
"Collects",
"processes",
"&",
"reports",
"metrics"
] | python | train | 41.15625 |
CalebBell/fluids | fluids/saltation.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/saltation.py#L390-L468 | def Weber_saltation(mp, rhop, dp, rhog, D, Vterminal=4):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_.
If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2.
.. math::
Fr_s = \left(7 + \frac{8}{3... | [
"def",
"Weber_saltation",
"(",
"mp",
",",
"rhop",
",",
"dp",
",",
"rhog",
",",
"D",
",",
"Vterminal",
"=",
"4",
")",
":",
"if",
"Vterminal",
"<=",
"3",
":",
"term1",
"=",
"(",
"7",
"+",
"8",
"/",
"3.",
"*",
"Vterminal",
")",
"*",
"(",
"dp",
"... | r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_.
If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2.
.. math::
Fr_s = \left(7 + \frac{8}{3}V_{terminal}\right)\mu^{0.25}
\left(\frac{d_p}{D}\ri... | [
"r",
"Calculates",
"saltation",
"velocity",
"of",
"the",
"gas",
"for",
"pneumatic",
"conveying",
"according",
"to",
"[",
"1",
"]",
"_",
"as",
"described",
"in",
"[",
"2",
"]",
"_",
"[",
"3",
"]",
"_",
"[",
"4",
"]",
"_",
"and",
"[",
"5",
"]",
"_"... | python | train | 33.772152 |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/exmaralda.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/exmaralda.py#L55-L65 | def write(self, output_filepath):
"""
serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created
"""
with open(output_filepath, 'w') as out_fil... | [
"def",
"write",
"(",
"self",
",",
"output_filepath",
")",
":",
"with",
"open",
"(",
"output_filepath",
",",
"'w'",
")",
"as",
"out_file",
":",
"out_file",
".",
"write",
"(",
"self",
".",
"__str__",
"(",
")",
")"
] | serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created | [
"serialize",
"the",
"ExmaraldaFile",
"instance",
"and",
"write",
"it",
"to",
"a",
"file",
"."
] | python | train | 32.272727 |
xenadevel/PyXenaManager | xenamanager/api/xena_rest.py | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/api/xena_rest.py#L102-L111 | def get_attributes(self, obj):
""" Get all object's attributes.
Sends multi-parameter info/config queries and returns the result as dictionary.
:param obj: requested object.
:returns: dictionary of <name, value> of all attributes returned by the query.
:rtype: dict of (str, str... | [
"def",
"get_attributes",
"(",
"self",
",",
"obj",
")",
":",
"return",
"self",
".",
"_get_attributes",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"session_url",
",",
"obj",
".",
"ref",
")",
")"
] | Get all object's attributes.
Sends multi-parameter info/config queries and returns the result as dictionary.
:param obj: requested object.
:returns: dictionary of <name, value> of all attributes returned by the query.
:rtype: dict of (str, str) | [
"Get",
"all",
"object",
"s",
"attributes",
"."
] | python | train | 40.3 |
mwouts/jupytext | jupytext/contentsmanager.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/contentsmanager.py#L206-L216 | def default_formats(self, path):
"""Return the default formats, if they apply to the current path #157"""
formats = long_form_multiple_formats(self.default_jupytext_formats)
for fmt in formats:
try:
base_path(path, fmt)
return self.default_jupytext_for... | [
"def",
"default_formats",
"(",
"self",
",",
"path",
")",
":",
"formats",
"=",
"long_form_multiple_formats",
"(",
"self",
".",
"default_jupytext_formats",
")",
"for",
"fmt",
"in",
"formats",
":",
"try",
":",
"base_path",
"(",
"path",
",",
"fmt",
")",
"return"... | Return the default formats, if they apply to the current path #157 | [
"Return",
"the",
"default",
"formats",
"if",
"they",
"apply",
"to",
"the",
"current",
"path",
"#157"
] | python | train | 36.090909 |
alaudet/hcsr04sensor | recipes/imperial_distance.py | https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/imperial_distance.py#L6-L31 | def main():
'''Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
# Create a distance reading with the hcsr04 sensor module
# and overide ... | [
"def",
"main",
"(",
")",
":",
"trig_pin",
"=",
"17",
"echo_pin",
"=",
"27",
"# Default values",
"# unit = 'metric'",
"# temperature = 20",
"# round_to = 1",
"# Create a distance reading with the hcsr04 sensor module",
"# and overide the default values for temp, unit and rounding)",
... | Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi | [
"Calculate",
"the",
"distance",
"of",
"an",
"object",
"in",
"inches",
"using",
"a",
"HCSR04",
"sensor",
"and",
"a",
"Raspberry",
"Pi"
] | python | train | 31.038462 |
dancsalo/TensorBase | tensorbase/base.py | https://github.com/dancsalo/TensorBase/blob/3d42a326452bd03427034916ff2fb90730020204/tensorbase/base.py#L483-L518 | def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', bn=True, activation_fn=tf.nn.relu,
b_value=0.0, s_value=1.0, trainable=True):
"""
2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stri... | [
"def",
"conv2d",
"(",
"self",
",",
"filter_size",
",",
"output_channels",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
",",
"bn",
"=",
"True",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
",",
"b_value",
"=",
"0.0",
",",
"s_val... | 2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float | [
"2D",
"Convolutional",
"Layer",
".",
":",
"param",
"filter_size",
":",
"int",
".",
"assumes",
"square",
"filter",
":",
"param",
"output_channels",
":",
"int",
":",
"param",
"stride",
":",
"int",
":",
"param",
"padding",
":",
"VALID",
"or",
"SAME",
":",
"... | python | train | 50.972222 |
libtcod/python-tcod | tcod/libtcodpy.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1138-L1151 | def console_set_default_background(
con: tcod.console.Console, col: Tuple[int, int, int]
) -> None:
"""Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color i... | [
"def",
"console_set_default_background",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"col",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_default_background",
"(",
"_console",
... | Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
Use :any:`Console.default_bg` instead. | [
"Change",
"the",
"default",
"background",
"color",
"for",
"a",
"console",
"."
] | python | train | 32.785714 |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L274-L287 | def from_app(cls, app, environ, buffered=False):
"""Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the `write()` callable
returned by the `start_response` funct... | [
"def",
"from_app",
"(",
"cls",
",",
"app",
",",
"environ",
",",
"buffered",
"=",
"False",
")",
":",
"return",
"cls",
"(",
"*",
"_run_wsgi_app",
"(",
"app",
",",
"environ",
",",
"buffered",
")",
")"
] | Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the `write()` callable
returned by the `start_response` function. This tries to resolve such
edge cases automati... | [
"Create",
"a",
"new",
"response",
"object",
"from",
"an",
"application",
"output",
".",
"This",
"works",
"best",
"if",
"you",
"pass",
"it",
"an",
"application",
"that",
"returns",
"a",
"generator",
"all",
"the",
"time",
".",
"Sometimes",
"applications",
"may... | python | train | 55.142857 |
postmanlabs/httpbin | httpbin/core.py | https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L1423-L1450 | def random_bytes(n):
"""Returns n random bytes generated with given seed
---
tags:
- Dynamic data
parameters:
- in: path
name: n
type: int
produces:
- application/octet-stream
responses:
200:
description: Bytes.
"""
n = min(n, 100 * 1024) ... | [
"def",
"random_bytes",
"(",
"n",
")",
":",
"n",
"=",
"min",
"(",
"n",
",",
"100",
"*",
"1024",
")",
"# set 100KB limit",
"params",
"=",
"CaseInsensitiveDict",
"(",
"request",
".",
"args",
".",
"items",
"(",
")",
")",
"if",
"\"seed\"",
"in",
"params",
... | Returns n random bytes generated with given seed
---
tags:
- Dynamic data
parameters:
- in: path
name: n
type: int
produces:
- application/octet-stream
responses:
200:
description: Bytes. | [
"Returns",
"n",
"random",
"bytes",
"generated",
"with",
"given",
"seed",
"---",
"tags",
":",
"-",
"Dynamic",
"data",
"parameters",
":",
"-",
"in",
":",
"path",
"name",
":",
"n",
"type",
":",
"int",
"produces",
":",
"-",
"application",
"/",
"octet",
"-"... | python | train | 24.428571 |
pandas-dev/pandas | pandas/_config/config.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/_config/config.py#L533-L548 | def _select_options(pat):
"""returns a list of keys matching `pat`
if pat=="all", returns all registered options
"""
# short-circuit for exact key
if pat in _registered_options:
return [pat]
# else look through all of them
keys = sorted(_registered_options.keys())
if pat == 'a... | [
"def",
"_select_options",
"(",
"pat",
")",
":",
"# short-circuit for exact key",
"if",
"pat",
"in",
"_registered_options",
":",
"return",
"[",
"pat",
"]",
"# else look through all of them",
"keys",
"=",
"sorted",
"(",
"_registered_options",
".",
"keys",
"(",
")",
... | returns a list of keys matching `pat`
if pat=="all", returns all registered options | [
"returns",
"a",
"list",
"of",
"keys",
"matching",
"pat"
] | python | train | 25.125 |
odlgroup/odl | odl/space/fspace.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L892-L954 | def byaxis_out(self):
"""Object to index along output dimensions.
This is only valid for non-trivial `out_shape`.
Examples
--------
Indexing with integers or slices:
>>> domain = odl.IntervalProd(0, 1)
>>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2... | [
"def",
"byaxis_out",
"(",
"self",
")",
":",
"space",
"=",
"self",
"class",
"FspaceByaxisOut",
"(",
"object",
")",
":",
"\"\"\"Helper class for indexing by output axes.\"\"\"",
"def",
"__getitem__",
"(",
"self",
",",
"indices",
")",
":",
"\"\"\"Return ``self[indices]``... | Object to index along output dimensions.
This is only valid for non-trivial `out_shape`.
Examples
--------
Indexing with integers or slices:
>>> domain = odl.IntervalProd(0, 1)
>>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2, 3, 4)))
>>> fspace.byax... | [
"Object",
"to",
"index",
"along",
"output",
"dimensions",
"."
] | python | train | 33.047619 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/inputs.py | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/inputs.py#L69-L88 | def url_input(url_string, download=True):
"""
This method expects a direct URL link to an xml file. It will apply no
modifications to the received URL string, so ensure good input.
"""
log.debug('URL Input - {0}'.format(url_string))
try:
open_xml = urllib.request.urlopen(url_string)
... | [
"def",
"url_input",
"(",
"url_string",
",",
"download",
"=",
"True",
")",
":",
"log",
".",
"debug",
"(",
"'URL Input - {0}'",
".",
"format",
"(",
"url_string",
")",
")",
"try",
":",
"open_xml",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"url_str... | This method expects a direct URL link to an xml file. It will apply no
modifications to the received URL string, so ensure good input. | [
"This",
"method",
"expects",
"a",
"direct",
"URL",
"link",
"to",
"an",
"xml",
"file",
".",
"It",
"will",
"apply",
"no",
"modifications",
"to",
"the",
"received",
"URL",
"string",
"so",
"ensure",
"good",
"input",
"."
] | python | train | 44.2 |
pandas-dev/pandas | pandas/io/sas/sas_xport.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sas/sas_xport.py#L170-L224 | def _parse_float_vec(vec):
"""
Parse a vector of float values representing IBM 8 byte floats into
native 8 byte floats.
"""
dtype = np.dtype('>u4,>u4')
vec1 = vec.view(dtype=dtype)
xport1 = vec1['f0']
xport2 = vec1['f1']
# Start by setting first half of ieee number to first half of... | [
"def",
"_parse_float_vec",
"(",
"vec",
")",
":",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"'>u4,>u4'",
")",
"vec1",
"=",
"vec",
".",
"view",
"(",
"dtype",
"=",
"dtype",
")",
"xport1",
"=",
"vec1",
"[",
"'f0'",
"]",
"xport2",
"=",
"vec1",
"[",
"'f1'",... | Parse a vector of float values representing IBM 8 byte floats into
native 8 byte floats. | [
"Parse",
"a",
"vector",
"of",
"float",
"values",
"representing",
"IBM",
"8",
"byte",
"floats",
"into",
"native",
"8",
"byte",
"floats",
"."
] | python | train | 39.218182 |
skelsec/minidump | minidump/minidumpreader.py | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L141-L150 | def read_int(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(self.read(8... | [
"def",
"read_int",
"(",
"self",
")",
":",
"if",
"self",
".",
"reader",
".",
"sysinfo",
".",
"ProcessorArchitecture",
"==",
"PROCESSOR_ARCHITECTURE",
".",
"AMD64",
":",
"return",
"int",
".",
"from_bytes",
"(",
"self",
".",
"read",
"(",
"8",
")",
",",
"byt... | Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch | [
"Reads",
"an",
"integer",
".",
"The",
"size",
"depends",
"on",
"the",
"architecture",
".",
"Reads",
"a",
"4",
"byte",
"small",
"-",
"endian",
"singed",
"int",
"on",
"32",
"bit",
"arch",
"Reads",
"an",
"8",
"byte",
"small",
"-",
"endian",
"singed",
"int... | python | train | 43.4 |
wylee/runcommands | runcommands/command.py | https://github.com/wylee/runcommands/blob/b1d7c262885b9ced7ab89b63562f5464ca9970fe/runcommands/command.py#L310-L314 | def find_parameter(self, name):
"""Find parameter by name or normalized arg name."""
name = self.normalize_name(name)
arg = self.args.get(name)
return None if arg is None else arg.parameter | [
"def",
"find_parameter",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"normalize_name",
"(",
"name",
")",
"arg",
"=",
"self",
".",
"args",
".",
"get",
"(",
"name",
")",
"return",
"None",
"if",
"arg",
"is",
"None",
"else",
"arg",
".... | Find parameter by name or normalized arg name. | [
"Find",
"parameter",
"by",
"name",
"or",
"normalized",
"arg",
"name",
"."
] | python | train | 43.4 |
google/grumpy | third_party/stdlib/rfc822.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L666-L682 | def getdomain(self):
"""Get the complete domain name from an address."""
sdlist = []
while self.pos < len(self.field):
if self.field[self.pos] in self.LWS:
self.pos += 1
elif self.field[self.pos] == '(':
self.commentlist.append(self.getcomm... | [
"def",
"getdomain",
"(",
"self",
")",
":",
"sdlist",
"=",
"[",
"]",
"while",
"self",
".",
"pos",
"<",
"len",
"(",
"self",
".",
"field",
")",
":",
"if",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"in",
"self",
".",
"LWS",
":",
"self",
... | Get the complete domain name from an address. | [
"Get",
"the",
"complete",
"domain",
"name",
"from",
"an",
"address",
"."
] | python | valid | 39.941176 |
bslatkin/dpxdt | dpxdt/tools/url_pair_diff.py | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/tools/url_pair_diff.py#L132-L152 | def real_main(new_url=None,
baseline_url=None,
upload_build_id=None,
upload_release_name=None):
"""Runs the ur_pair_diff."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
item = UrlPairDiff(
new_url,
... | [
"def",
"real_main",
"(",
"new_url",
"=",
"None",
",",
"baseline_url",
"=",
"None",
",",
"upload_build_id",
"=",
"None",
",",
"upload_release_name",
"=",
"None",
")",
":",
"coordinator",
"=",
"workers",
".",
"get_coordinator",
"(",
")",
"fetch_worker",
".",
"... | Runs the ur_pair_diff. | [
"Runs",
"the",
"ur_pair_diff",
"."
] | python | train | 27.095238 |
PmagPy/PmagPy | pmagpy/nlt.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/nlt.py#L72-L82 | def NRM(f,a,b,best):
WARN = True # Warn, rather than stop if I encounter a NaN...
"""
Calculate NRM expected lab field and estimated ancient field
NRM(blab,best)= (best/blab)*TRM(blab)
"""
if float(f)==0:
print('ERROR: NRM: f==0.')
if not WARN : sys.exit()
m = (old_div(float(... | [
"def",
"NRM",
"(",
"f",
",",
"a",
",",
"b",
",",
"best",
")",
":",
"WARN",
"=",
"True",
"# Warn, rather than stop if I encounter a NaN...",
"if",
"float",
"(",
"f",
")",
"==",
"0",
":",
"print",
"(",
"'ERROR: NRM: f==0.'",
")",
"if",
"not",
"WARN",
":",
... | Calculate NRM expected lab field and estimated ancient field
NRM(blab,best)= (best/blab)*TRM(blab) | [
"Calculate",
"NRM",
"expected",
"lab",
"field",
"and",
"estimated",
"ancient",
"field",
"NRM",
"(",
"blab",
"best",
")",
"=",
"(",
"best",
"/",
"blab",
")",
"*",
"TRM",
"(",
"blab",
")"
] | python | train | 32.636364 |
wonambi-python/wonambi | wonambi/widgets/info.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/info.py#L449-L458 | def get_channels(self):
"""Get the selected channel(s in order). """
selectedItems = self.idx_chan.selectedItems()
selected_chan = [x.text() for x in selectedItems]
chan_in_order = []
for chan in self.chan:
if chan in selected_chan:
chan_in_order.appen... | [
"def",
"get_channels",
"(",
"self",
")",
":",
"selectedItems",
"=",
"self",
".",
"idx_chan",
".",
"selectedItems",
"(",
")",
"selected_chan",
"=",
"[",
"x",
".",
"text",
"(",
")",
"for",
"x",
"in",
"selectedItems",
"]",
"chan_in_order",
"=",
"[",
"]",
... | Get the selected channel(s in order). | [
"Get",
"the",
"selected",
"channel",
"(",
"s",
"in",
"order",
")",
"."
] | python | train | 34.8 |
gwastro/pycbc | pycbc/workflow/grb_utils.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/grb_utils.py#L69-L135 | def get_coh_PTF_files(cp, ifos, run_dir, bank_veto=False, summary_files=False):
"""
Retrieve files needed to run coh_PTF jobs within a PyGRB workflow
Parameters
----------
cp : pycbc.workflow.configuration.WorkflowConfigParser object
The parsed configuration options of a pycbc.workflow.core.Wor... | [
"def",
"get_coh_PTF_files",
"(",
"cp",
",",
"ifos",
",",
"run_dir",
",",
"bank_veto",
"=",
"False",
",",
"summary_files",
"=",
"False",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"\"LAL_SRC\"",
")",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"The en... | Retrieve files needed to run coh_PTF jobs within a PyGRB workflow
Parameters
----------
cp : pycbc.workflow.configuration.WorkflowConfigParser object
The parsed configuration options of a pycbc.workflow.core.Workflow.
ifos : str
String containing the analysis interferometer IDs.
run_dir :... | [
"Retrieve",
"files",
"needed",
"to",
"run",
"coh_PTF",
"jobs",
"within",
"a",
"PyGRB",
"workflow"
] | python | train | 41.149254 |
romana/vpc-router | vpcrouter/monitor/plugins/multi.py | https://github.com/romana/vpc-router/blob/d696c2e023f1111ceb61f9c6fbabfafed8e14040/vpcrouter/monitor/plugins/multi.py#L58-L65 | def _expire_data(self):
"""
Remove all expired entries.
"""
expire_time_stamp = time.time() - self.expire_time
self.timed_data = {d: t for d, t in self.timed_data.items()
if t > expire_time_stamp} | [
"def",
"_expire_data",
"(",
"self",
")",
":",
"expire_time_stamp",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"expire_time",
"self",
".",
"timed_data",
"=",
"{",
"d",
":",
"t",
"for",
"d",
",",
"t",
"in",
"self",
".",
"timed_data",
".",
... | Remove all expired entries. | [
"Remove",
"all",
"expired",
"entries",
"."
] | python | train | 32.625 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L46-L61 | def checkForSpiceError(f):
"""
Internal function to check
:param f:
:raise stypes.SpiceyError:
"""
if failed():
errorparts = {
"tkvsn": tkvrsn("TOOLKIT").replace("CSPICE_", ""),
"short": getmsg("SHORT", 26),
"explain": getmsg("EXPLAIN", 100).strip(),
... | [
"def",
"checkForSpiceError",
"(",
"f",
")",
":",
"if",
"failed",
"(",
")",
":",
"errorparts",
"=",
"{",
"\"tkvsn\"",
":",
"tkvrsn",
"(",
"\"TOOLKIT\"",
")",
".",
"replace",
"(",
"\"CSPICE_\"",
",",
"\"\"",
")",
",",
"\"short\"",
":",
"getmsg",
"(",
"\"... | Internal function to check
:param f:
:raise stypes.SpiceyError: | [
"Internal",
"function",
"to",
"check",
":",
"param",
"f",
":",
":",
"raise",
"stypes",
".",
"SpiceyError",
":"
] | python | train | 31.125 |
barryp/py-amqplib | amqplib/client_0_8/channel.py | https://github.com/barryp/py-amqplib/blob/2b3a47de34b4712c111d0a55d7ff109dffc2a7b2/amqplib/client_0_8/channel.py#L1821-L1948 | def basic_consume(self, queue='', consumer_tag='', no_local=False,
no_ack=False, exclusive=False, nowait=False,
callback=None, ticket=None):
"""
start a queue consumer
This method asks the server to start a "consumer", which is a
transient request for messages from a spe... | [
"def",
"basic_consume",
"(",
"self",
",",
"queue",
"=",
"''",
",",
"consumer_tag",
"=",
"''",
",",
"no_local",
"=",
"False",
",",
"no_ack",
"=",
"False",
",",
"exclusive",
"=",
"False",
",",
"nowait",
"=",
"False",
",",
"callback",
"=",
"None",
",",
... | start a queue consumer
This method asks the server to start a "consumer", which is a
transient request for messages from a specific queue.
Consumers last as long as the channel they were created on, or
until the client cancels them.
RULE:
The server SHOULD support ... | [
"start",
"a",
"queue",
"consumer"
] | python | train | 35.765625 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L816-L823 | def do_imports(self):
"""
Import all importable options
"""
self.do_import('worker_class', Worker)
self.do_import('queue_model', self.options.worker_class.queue_model)
self.do_import('error_model', self.options.worker_class.error_model)
self.do_import('callback', ... | [
"def",
"do_imports",
"(",
"self",
")",
":",
"self",
".",
"do_import",
"(",
"'worker_class'",
",",
"Worker",
")",
"self",
".",
"do_import",
"(",
"'queue_model'",
",",
"self",
".",
"options",
".",
"worker_class",
".",
"queue_model",
")",
"self",
".",
"do_imp... | Import all importable options | [
"Import",
"all",
"importable",
"options"
] | python | train | 43.5 |
pypa/pipenv | pipenv/vendor/pathlib2/__init__.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1512-L1518 | def rename(self, target):
"""
Rename this path to the given path.
"""
if self._closed:
self._raise_closed()
self._accessor.rename(self, target) | [
"def",
"rename",
"(",
"self",
",",
"target",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"self",
".",
"_accessor",
".",
"rename",
"(",
"self",
",",
"target",
")"
] | Rename this path to the given path. | [
"Rename",
"this",
"path",
"to",
"the",
"given",
"path",
"."
] | python | train | 27 |
NYUCCL/psiTurk | psiturk/psiturk_org_services.py | https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_org_services.py#L50-L53 | def update_credentials(self, key, secret):
''' Update credentials '''
self.access_key = key
self.secret_key = secret | [
"def",
"update_credentials",
"(",
"self",
",",
"key",
",",
"secret",
")",
":",
"self",
".",
"access_key",
"=",
"key",
"self",
".",
"secret_key",
"=",
"secret"
] | Update credentials | [
"Update",
"credentials"
] | python | train | 34.25 |
CalebBell/thermo | thermo/thermal_conductivity.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L1274-L1314 | def calculate(self, T, P, zs, ws, method):
r'''Method to calculate thermal conductivity of a liquid mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for tha... | [
"def",
"calculate",
"(",
"self",
",",
"T",
",",
"P",
",",
"zs",
",",
"ws",
",",
"method",
")",
":",
"if",
"method",
"==",
"SIMPLE",
":",
"ks",
"=",
"[",
"i",
"(",
"T",
",",
"P",
")",
"for",
"i",
"in",
"self",
".",
"ThermalConductivityLiquids",
... | r'''Method to calculate thermal conductivity of a liquid mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
Parameters
----------
T... | [
"r",
"Method",
"to",
"calculate",
"thermal",
"conductivity",
"of",
"a",
"liquid",
"mixture",
"at",
"temperature",
"T",
"pressure",
"P",
"mole",
"fractions",
"zs",
"and",
"weight",
"fractions",
"ws",
"with",
"a",
"given",
"method",
"."
] | python | valid | 37.756098 |
seleniumbase/SeleniumBase | seleniumbase/fixtures/page_actions.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/page_actions.py#L392-L402 | def find_visible_elements(driver, selector, by=By.CSS_SELECTOR):
"""
Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator that is used to search the DOM (required)
by - the met... | [
"def",
"find_visible_elements",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
")",
":",
"elements",
"=",
"driver",
".",
"find_elements",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"return",
"[",
"element",
"for... | Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator that is used to search the DOM (required)
by - the method to search for the locator (Default: By.CSS_SELECTOR) | [
"Finds",
"all",
"WebElements",
"that",
"match",
"a",
"selector",
"and",
"are",
"visible",
".",
"Similar",
"to",
"webdriver",
".",
"find_elements",
"."
] | python | train | 45.818182 |
tensorflow/tensor2tensor | tensor2tensor/models/research/transformer_moe.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L267-L311 | def transformer_moe_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.norm_type = "layer"
hparams.hidden_size = 512
hparams.batch_size = 4096
hparams.max_length = 2001
hparams.max_input_seq_length = 2000
hparams.max_target_seq_length = 2000
hparams.dropout = 0.0
... | [
"def",
"transformer_moe_base",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"norm_type",
"=",
"\"layer\"",
"hparams",
".",
"hidden_size",
"=",
"512",
"hparams",
".",
"batch_size",
"=",
"4096",
"hparams",
".",... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | python | train | 38 |
crs4/hl7apy | hl7apy/factories.py | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/factories.py#L108-L155 | def date_factory(value, datatype_cls, validation_level=None):
"""
Creates a :class:`DT <hl7apy.base_datatypes.DT>` object
The value in input must be a string parsable with :meth:`datetime.strptime`.
The date format is chosen according to the length of the value as stated in this table:
+-------+--... | [
"def",
"date_factory",
"(",
"value",
",",
"datatype_cls",
",",
"validation_level",
"=",
"None",
")",
":",
"dt_value",
",",
"fmt",
"=",
"get_date_info",
"(",
"value",
")",
"return",
"datatype_cls",
"(",
"dt_value",
",",
"fmt",
")"
] | Creates a :class:`DT <hl7apy.base_datatypes.DT>` object
The value in input must be a string parsable with :meth:`datetime.strptime`.
The date format is chosen according to the length of the value as stated in this table:
+-------+-----------+
|Length |Format |
+=======+===========+
|4 ... | [
"Creates",
"a",
":",
"class",
":",
"DT",
"<hl7apy",
".",
"base_datatypes",
".",
"DT",
">",
"object"
] | python | train | 34.583333 |
inasafe/inasafe | safe/gui/tools/wizard/step_fc90_analysis.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L312-L319 | def hide_busy(self):
"""Unlock buttons A helper function to indicate processing is done."""
self.progress_bar.hide()
self.parent.pbnNext.setEnabled(True)
self.parent.pbnBack.setEnabled(True)
self.parent.pbnCancel.setEnabled(True)
self.parent.repaint()
disable_busy... | [
"def",
"hide_busy",
"(",
"self",
")",
":",
"self",
".",
"progress_bar",
".",
"hide",
"(",
")",
"self",
".",
"parent",
".",
"pbnNext",
".",
"setEnabled",
"(",
"True",
")",
"self",
".",
"parent",
".",
"pbnBack",
".",
"setEnabled",
"(",
"True",
")",
"se... | Unlock buttons A helper function to indicate processing is done. | [
"Unlock",
"buttons",
"A",
"helper",
"function",
"to",
"indicate",
"processing",
"is",
"done",
"."
] | python | train | 40.25 |
tonysimpson/nanomsg-python | _nanomsg_ctypes/__init__.py | https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/_nanomsg_ctypes/__init__.py#L142-L158 | def nn_setsockopt(socket, level, option, value):
"""set a socket option
socket - socket number
level - option level
option - option
value - a readable byte buffer (not a Unicode string) containing the value
returns - 0 on success or < 0 on error
"""
try:
return _nn_setsockopt(s... | [
"def",
"nn_setsockopt",
"(",
"socket",
",",
"level",
",",
"option",
",",
"value",
")",
":",
"try",
":",
"return",
"_nn_setsockopt",
"(",
"socket",
",",
"level",
",",
"option",
",",
"ctypes",
".",
"addressof",
"(",
"value",
")",
",",
"len",
"(",
"value"... | set a socket option
socket - socket number
level - option level
option - option
value - a readable byte buffer (not a Unicode string) containing the value
returns - 0 on success or < 0 on error | [
"set",
"a",
"socket",
"option"
] | python | train | 35.941176 |
MisterY/price-database | pricedb/app.py | https://github.com/MisterY/price-database/blob/b4fd366b7763891c690fe3000b8840e656da023e/pricedb/app.py#L323-L345 | def __get_securities(self, currency: str, agent: str, symbol: str,
namespace: str) -> List[dal.Security]:
""" Fetches the securities that match the given filters """
repo = self.get_security_repository()
query = repo.query
if currency is not None:
qu... | [
"def",
"__get_securities",
"(",
"self",
",",
"currency",
":",
"str",
",",
"agent",
":",
"str",
",",
"symbol",
":",
"str",
",",
"namespace",
":",
"str",
")",
"->",
"List",
"[",
"dal",
".",
"Security",
"]",
":",
"repo",
"=",
"self",
".",
"get_security_... | Fetches the securities that match the given filters | [
"Fetches",
"the",
"securities",
"that",
"match",
"the",
"given",
"filters"
] | python | test | 34.869565 |
SwissDataScienceCenter/renku-python | renku/cli/workflow.py | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/workflow.py#L59-L77 | def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name... | [
"def",
"workflow",
"(",
"ctx",
",",
"client",
")",
":",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"None",
":",
"from",
"renku",
".",
"models",
".",
"refs",
"import",
"LinkReference",
"names",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"ref",
"in",
... | List or manage workflows with subcommands. | [
"List",
"or",
"manage",
"workflows",
"with",
"subcommands",
"."
] | python | train | 36.105263 |
stevearc/dql | dql/__init__.py | https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/__init__.py#L30-L76 | def main():
""" Start the DQL client. """
parse = argparse.ArgumentParser(description=main.__doc__)
parse.add_argument("-c", "--command", help="Run this command and exit")
region = os.environ.get("AWS_REGION", "us-west-1")
parse.add_argument(
"-r",
"--region",
default=region,... | [
"def",
"main",
"(",
")",
":",
"parse",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parse",
".",
"add_argument",
"(",
"\"-c\"",
",",
"\"--command\"",
",",
"help",
"=",
"\"Run this command and exit\"",
")",
"r... | Start the DQL client. | [
"Start",
"the",
"DQL",
"client",
"."
] | python | train | 27.12766 |
molmod/molmod | molmod/ic.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/ic.py#L778-L802 | def _sin_to_angle(result, deriv, side=1):
"""Convert a sine and its derivatives to an angle and its derivatives"""
v = np.arcsin(np.clip(result[0], -1, 1))
sign = side
if sign == -1:
if v < 0:
offset = -np.pi
else:
offset = np.pi
else:
offset = 0.0
... | [
"def",
"_sin_to_angle",
"(",
"result",
",",
"deriv",
",",
"side",
"=",
"1",
")",
":",
"v",
"=",
"np",
".",
"arcsin",
"(",
"np",
".",
"clip",
"(",
"result",
"[",
"0",
"]",
",",
"-",
"1",
",",
"1",
")",
")",
"sign",
"=",
"side",
"if",
"sign",
... | Convert a sine and its derivatives to an angle and its derivatives | [
"Convert",
"a",
"sine",
"and",
"its",
"derivatives",
"to",
"an",
"angle",
"and",
"its",
"derivatives"
] | python | train | 30 |
spacetelescope/pysynphot | pysynphot/spectrum.py | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L207-L247 | def validate_wavetable(self):
"""Enforce monotonic, ascending wavelength array with no zero or
negative values.
Raises
------
pysynphot.exceptions.DuplicateWavelength
Wavelength array contains duplicate entries.
pysynphot.exceptions.UnsortedWavelength
... | [
"def",
"validate_wavetable",
"(",
"self",
")",
":",
"# First check for invalid values",
"wave",
"=",
"self",
".",
"_wavetable",
"if",
"N",
".",
"any",
"(",
"wave",
"<=",
"0",
")",
":",
"wrong",
"=",
"N",
".",
"where",
"(",
"wave",
"<=",
"0",
")",
"[",
... | Enforce monotonic, ascending wavelength array with no zero or
negative values.
Raises
------
pysynphot.exceptions.DuplicateWavelength
Wavelength array contains duplicate entries.
pysynphot.exceptions.UnsortedWavelength
Wavelength array is not monotonic a... | [
"Enforce",
"monotonic",
"ascending",
"wavelength",
"array",
"with",
"no",
"zero",
"or",
"negative",
"values",
"."
] | python | train | 35.609756 |
dpa-newslab/livebridge | livebridge/base/posts.py | https://github.com/dpa-newslab/livebridge/blob/d930e887faa2f882d15b574f0f1fe4a580d7c5fa/livebridge/base/posts.py#L98-L107 | def target_doc(self):
"""Returns resource doc as at the target, when the posting was already created \
at the target. This property normally contains the **target_doc** data from \
the livebrigde storage item, saved in a syndication earlier.
:returns: dict"""
if not hasatt... | [
"def",
"target_doc",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_target_doc\"",
")",
"or",
"not",
"self",
".",
"_target_doc",
":",
"if",
"self",
".",
"_existing",
":",
"self",
".",
"_target_doc",
"=",
"self",
".",
"_existing",
... | Returns resource doc as at the target, when the posting was already created \
at the target. This property normally contains the **target_doc** data from \
the livebrigde storage item, saved in a syndication earlier.
:returns: dict | [
"Returns",
"resource",
"doc",
"as",
"at",
"the",
"target",
"when",
"the",
"posting",
"was",
"already",
"created",
"\\",
"at",
"the",
"target",
".",
"This",
"property",
"normally",
"contains",
"the",
"**",
"target_doc",
"**",
"data",
"from",
"\\",
"the",
"l... | python | train | 49.3 |
berkeley-cocosci/Wallace | wallace/networks.py | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/networks.py#L138-L170 | def add_node(self, node):
"""Link the agent to a random member of the previous generation."""
nodes = [n for n in self.nodes() if not isinstance(n, Source)]
num_agents = len(nodes)
curr_generation = int((num_agents - 1) / float(self.generation_size))
node.generation = curr_genera... | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"nodes",
"=",
"[",
"n",
"for",
"n",
"in",
"self",
".",
"nodes",
"(",
")",
"if",
"not",
"isinstance",
"(",
"n",
",",
"Source",
")",
"]",
"num_agents",
"=",
"len",
"(",
"nodes",
")",
"curr_gene... | Link the agent to a random member of the previous generation. | [
"Link",
"the",
"agent",
"to",
"a",
"random",
"member",
"of",
"the",
"previous",
"generation",
"."
] | python | train | 38.424242 |
assemblerflow/flowcraft | flowcraft/generator/report.py | https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/generator/report.py#L309-L379 | def _send_live_report(self, report_id):
"""Sends a PUT request with the report JSON files currently in the
report_queue attribute.
Parameters
----------
report_id : str
Hash of the report JSON as retrieved from :func:`~_get_report_hash`
"""
# Determi... | [
"def",
"_send_live_report",
"(",
"self",
",",
"report_id",
")",
":",
"# Determines the maximum number of reports sent at the same time in",
"# the same payload",
"buffer_size",
"=",
"100",
"logger",
".",
"debug",
"(",
"\"Report buffer size set to: {}\"",
".",
"format",
"(",
... | Sends a PUT request with the report JSON files currently in the
report_queue attribute.
Parameters
----------
report_id : str
Hash of the report JSON as retrieved from :func:`~_get_report_hash` | [
"Sends",
"a",
"PUT",
"request",
"with",
"the",
"report",
"JSON",
"files",
"currently",
"in",
"the",
"report_queue",
"attribute",
"."
] | python | test | 39.183099 |
chrisjrn/registrasion | registrasion/controllers/invoice.py | https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/controllers/invoice.py#L76-L104 | def manual_invoice(cls, user, due_delta, description_price_pairs):
''' Generates an invoice for arbitrary items, not held in a user's
cart.
Arguments:
user (User): The user the invoice is being generated for.
due_delta (datetime.timedelta): The length until the invoice i... | [
"def",
"manual_invoice",
"(",
"cls",
",",
"user",
",",
"due_delta",
",",
"description_price_pairs",
")",
":",
"line_items",
"=",
"[",
"]",
"for",
"description",
",",
"price",
"in",
"description_price_pairs",
":",
"line_item",
"=",
"commerce",
".",
"LineItem",
... | Generates an invoice for arbitrary items, not held in a user's
cart.
Arguments:
user (User): The user the invoice is being generated for.
due_delta (datetime.timedelta): The length until the invoice is
due.
description_price_pairs ([(str, long or Deci... | [
"Generates",
"an",
"invoice",
"for",
"arbitrary",
"items",
"not",
"held",
"in",
"a",
"user",
"s",
"cart",
"."
] | python | test | 36.724138 |
mrstephenneal/mysql-toolkit | mysql/toolkit/datatypes/text.py | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/datatypes/text.py#L10-L16 | def is_varchar(self):
"""Determine if a data record is of the type VARCHAR."""
dt = DATA_TYPES['varchar']
if type(self.data) is dt['type'] and len(self.data) < dt['max']:
self.type = 'VARCHAR'
self.len = len(self.data)
return True | [
"def",
"is_varchar",
"(",
"self",
")",
":",
"dt",
"=",
"DATA_TYPES",
"[",
"'varchar'",
"]",
"if",
"type",
"(",
"self",
".",
"data",
")",
"is",
"dt",
"[",
"'type'",
"]",
"and",
"len",
"(",
"self",
".",
"data",
")",
"<",
"dt",
"[",
"'max'",
"]",
... | Determine if a data record is of the type VARCHAR. | [
"Determine",
"if",
"a",
"data",
"record",
"is",
"of",
"the",
"type",
"VARCHAR",
"."
] | python | train | 40.571429 |
bitesofcode/projexui | projexui/widgets/xganttwidget/xganttscene.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttscene.py#L58-L68 | def dateAt(self, x):
"""
Returns the date at the inputed x position.
:return <QDate>
"""
gantt = self.ganttWidget()
dstart = gantt.dateStart()
days = int(x / float(gantt.cellWidth()))
return dstart.addDays(... | [
"def",
"dateAt",
"(",
"self",
",",
"x",
")",
":",
"gantt",
"=",
"self",
".",
"ganttWidget",
"(",
")",
"dstart",
"=",
"gantt",
".",
"dateStart",
"(",
")",
"days",
"=",
"int",
"(",
"x",
"/",
"float",
"(",
"gantt",
".",
"cellWidth",
"(",
")",
")",
... | Returns the date at the inputed x position.
:return <QDate> | [
"Returns",
"the",
"date",
"at",
"the",
"inputed",
"x",
"position",
".",
":",
"return",
"<QDate",
">"
] | python | train | 28.636364 |
scanny/python-pptx | pptx/shapes/connector.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/shapes/connector.py#L88-L96 | def begin_y(self):
"""
Return the Y-position of the begin point of this connector, in
English Metric Units (as a |Length| object).
"""
cxnSp = self._element
y, cy, flipV = cxnSp.y, cxnSp.cy, cxnSp.flipV
begin_y = y+cy if flipV else y
return Emu(begin_y) | [
"def",
"begin_y",
"(",
"self",
")",
":",
"cxnSp",
"=",
"self",
".",
"_element",
"y",
",",
"cy",
",",
"flipV",
"=",
"cxnSp",
".",
"y",
",",
"cxnSp",
".",
"cy",
",",
"cxnSp",
".",
"flipV",
"begin_y",
"=",
"y",
"+",
"cy",
"if",
"flipV",
"else",
"y... | Return the Y-position of the begin point of this connector, in
English Metric Units (as a |Length| object). | [
"Return",
"the",
"Y",
"-",
"position",
"of",
"the",
"begin",
"point",
"of",
"this",
"connector",
"in",
"English",
"Metric",
"Units",
"(",
"as",
"a",
"|Length|",
"object",
")",
"."
] | python | train | 34.333333 |
shoebot/shoebot | examples/libraries/making_libraries/daisylib.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/examples/libraries/making_libraries/daisylib.py#L16-L55 | def drawdaisy(x, y, color='#fefefe'):
"""
Draw a daisy at x, y
"""
# save location, size etc
_ctx.push()
# save fill and stroke
_fill =_ctx.fill()
_stroke = _ctx.stroke()
sc = (1.0 / _ctx.HEIGHT) * float(y * 0.5) * 4.0
# draw stalk
_ctx.strokewidth(sc * 2.0)
_ctx.s... | [
"def",
"drawdaisy",
"(",
"x",
",",
"y",
",",
"color",
"=",
"'#fefefe'",
")",
":",
"# save location, size etc",
"_ctx",
".",
"push",
"(",
")",
"# save fill and stroke",
"_fill",
"=",
"_ctx",
".",
"fill",
"(",
")",
"_stroke",
"=",
"_ctx",
".",
"stroke",
"(... | Draw a daisy at x, y | [
"Draw",
"a",
"daisy",
"at",
"x",
"y"
] | python | valid | 20.375 |
ContextLab/quail | quail/helpers.py | https://github.com/ContextLab/quail/blob/71dd53c792dd915dc84879d8237e3582dd68b7a4/quail/helpers.py#L11-L43 | def list2pd(all_data, subjindex=None, listindex=None):
"""
Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for pre... | [
"def",
"list2pd",
"(",
"all_data",
",",
"subjindex",
"=",
"None",
",",
"listindex",
"=",
"None",
")",
":",
"# set default index if it is not defined",
"# max_nlists = max(map(lambda x: len(x), all_data))",
"listindex",
"=",
"[",
"[",
"idx",
"for",
"idx",
"in",
"range"... | Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for presented / recalled ints and floats, if desired
Returns
---... | [
"Makes",
"multi",
"-",
"indexed",
"dataframe",
"of",
"subject",
"data"
] | python | train | 40.606061 |
EconForge/dolo | dolo/numeric/interpolation/smolyak.py | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/interpolation/smolyak.py#L256-L267 | def set_values(self,x):
""" Updates self.theta parameter. No returns values"""
x = numpy.atleast_2d(x)
x = x.real # ahem
C_inv = self.__C_inv__
theta = numpy.dot( x, C_inv )
self.theta = theta
return theta | [
"def",
"set_values",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"numpy",
".",
"atleast_2d",
"(",
"x",
")",
"x",
"=",
"x",
".",
"real",
"# ahem",
"C_inv",
"=",
"self",
".",
"__C_inv__",
"theta",
"=",
"numpy",
".",
"dot",
"(",
"x",
",",
"C_inv",
... | Updates self.theta parameter. No returns values | [
"Updates",
"self",
".",
"theta",
"parameter",
".",
"No",
"returns",
"values"
] | python | train | 21.166667 |
PMEAL/OpenPNM | openpnm/core/ModelsMixin.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/core/ModelsMixin.py#L75-L94 | def dependency_map(self):
r"""
Create a graph of the dependency graph in a decent format
See Also
--------
dependency_graph
dependency_list
"""
dtree = self.dependency_graph()
fig = nx.draw_spectral(dtree,
with_labe... | [
"def",
"dependency_map",
"(",
"self",
")",
":",
"dtree",
"=",
"self",
".",
"dependency_graph",
"(",
")",
"fig",
"=",
"nx",
".",
"draw_spectral",
"(",
"dtree",
",",
"with_labels",
"=",
"True",
",",
"arrowsize",
"=",
"50",
",",
"node_size",
"=",
"2000",
... | r"""
Create a graph of the dependency graph in a decent format
See Also
--------
dependency_graph
dependency_list | [
"r",
"Create",
"a",
"graph",
"of",
"the",
"dependency",
"graph",
"in",
"a",
"decent",
"format"
] | python | train | 30.65 |
bionikspoon/pureyaml | pureyaml/grammar/utils.py | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/grammar/utils.py#L11-L24 | def strict(*types):
"""Decorator, type check production rule output"""
def decorate(func):
@wraps(func)
def wrapper(self, p):
func(self, p)
if not isinstance(p[0], types):
raise YAMLStrictTypeError(p[0], types, func)
wrapper.co_firstlineno = func... | [
"def",
"strict",
"(",
"*",
"types",
")",
":",
"def",
"decorate",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"p",
")",
":",
"func",
"(",
"self",
",",
"p",
")",
"if",
"not",
"isinstance",
"(",
"p",
... | Decorator, type check production rule output | [
"Decorator",
"type",
"check",
"production",
"rule",
"output"
] | python | train | 26.785714 |
awslabs/sockeye | sockeye/decoder.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/decoder.py#L56-L69 | def register(cls, config_type: Type[DecoderConfig], suffix: str):
"""
Registers decoder type for configuration. Suffix is appended to decoder prefix.
:param config_type: Configuration type for decoder.
:param suffix: String to append to decoder prefix.
:return: Class decorator.... | [
"def",
"register",
"(",
"cls",
",",
"config_type",
":",
"Type",
"[",
"DecoderConfig",
"]",
",",
"suffix",
":",
"str",
")",
":",
"def",
"wrapper",
"(",
"target_cls",
")",
":",
"cls",
".",
"__registry",
"[",
"config_type",
"]",
"=",
"(",
"target_cls",
",... | Registers decoder type for configuration. Suffix is appended to decoder prefix.
:param config_type: Configuration type for decoder.
:param suffix: String to append to decoder prefix.
:return: Class decorator. | [
"Registers",
"decoder",
"type",
"for",
"configuration",
".",
"Suffix",
"is",
"appended",
"to",
"decoder",
"prefix",
"."
] | python | train | 33.5 |
ace0/pyrelic | pyrelic/pbc.py | https://github.com/ace0/pyrelic/blob/f23d4e6586674675f72304d5938548267d6413bf/pyrelic/pbc.py#L50-L56 | def inverse(self):
"""
Retrieves the inverse of a G1 element.
"""
result = G1Element()
librelic.g1_neg_abi(byref(result), byref(self))
return result | [
"def",
"inverse",
"(",
"self",
")",
":",
"result",
"=",
"G1Element",
"(",
")",
"librelic",
".",
"g1_neg_abi",
"(",
"byref",
"(",
"result",
")",
",",
"byref",
"(",
"self",
")",
")",
"return",
"result"
] | Retrieves the inverse of a G1 element. | [
"Retrieves",
"the",
"inverse",
"of",
"a",
"G1",
"element",
"."
] | python | train | 27.142857 |
ryan-roemer/django-cloud-browser | cloud_browser/views.py | https://github.com/ryan-roemer/django-cloud-browser/blob/b06cdd24885a6309e843ed924dbf1705b67e7f48/cloud_browser/views.py#L20-L47 | def settings_view_decorator(function):
"""Insert decorator from settings, if any.
.. note:: Decorator in ``CLOUD_BROWSER_VIEW_DECORATOR`` can be either a
callable or a fully-qualified string path (the latter, which we'll
lazy import).
"""
dec = settings.CLOUD_BROWSER_VIEW_DECORATOR
... | [
"def",
"settings_view_decorator",
"(",
"function",
")",
":",
"dec",
"=",
"settings",
".",
"CLOUD_BROWSER_VIEW_DECORATOR",
"# Trade-up string to real decorator.",
"if",
"isinstance",
"(",
"dec",
",",
"str",
")",
":",
"# Split into module and decorator strings.",
"mod_str",
... | Insert decorator from settings, if any.
.. note:: Decorator in ``CLOUD_BROWSER_VIEW_DECORATOR`` can be either a
callable or a fully-qualified string path (the latter, which we'll
lazy import). | [
"Insert",
"decorator",
"from",
"settings",
"if",
"any",
"."
] | python | train | 31.642857 |
Spinmob/spinmob | egg/_gui.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L1773-L1784 | def block_events(self):
"""
Special version of block_events that loops over all tree elements.
"""
# block events in the usual way
BaseObject.block_events(self)
# loop over all top level parameters
for i in range(self._widget.topLevelItemCount()):
... | [
"def",
"block_events",
"(",
"self",
")",
":",
"# block events in the usual way",
"BaseObject",
".",
"block_events",
"(",
"self",
")",
"# loop over all top level parameters",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_widget",
".",
"topLevelItemCount",
"(",
")",
... | Special version of block_events that loops over all tree elements. | [
"Special",
"version",
"of",
"block_events",
"that",
"loops",
"over",
"all",
"tree",
"elements",
"."
] | python | train | 33 |
glomex/gcdt | gcdt/kumo_core.py | https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/kumo_core.py#L67-L120 | def get_parameter_diff(awsclient, config):
"""get differences between local config and currently active config
"""
client_cf = awsclient.get_client('cloudformation')
try:
stack_name = config['stack']['StackName']
if stack_name:
response = client_cf.describe_stacks(StackName=s... | [
"def",
"get_parameter_diff",
"(",
"awsclient",
",",
"config",
")",
":",
"client_cf",
"=",
"awsclient",
".",
"get_client",
"(",
"'cloudformation'",
")",
"try",
":",
"stack_name",
"=",
"config",
"[",
"'stack'",
"]",
"[",
"'StackName'",
"]",
"if",
"stack_name",
... | get differences between local config and currently active config | [
"get",
"differences",
"between",
"local",
"config",
"and",
"currently",
"active",
"config"
] | python | train | 35.833333 |
ooici/elasticpy | elasticpy/search.py | https://github.com/ooici/elasticpy/blob/ec221800a80c39e80d8c31667c5b138da39219f2/elasticpy/search.py#L350-L369 | def raw(self, module, method='GET', data=None):
'''
Submits or requsts raw input
'''
request = self.session
url = 'http://%s:%s/%s' % (self.host, self.port, module)
if self.verbose:
print data
if method=='GET':
response = request.get(url)
... | [
"def",
"raw",
"(",
"self",
",",
"module",
",",
"method",
"=",
"'GET'",
",",
"data",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"session",
"url",
"=",
"'http://%s:%s/%s'",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"modul... | Submits or requsts raw input | [
"Submits",
"or",
"requsts",
"raw",
"input"
] | python | train | 31.4 |
pytroll/satpy | satpy/scene.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/scene.py#L1216-L1229 | def save_datasets(self, writer="geotiff", datasets=None, compute=True, **kwargs):
"""Save all the datasets present in a scene to disk using *writer*."""
if datasets is not None:
datasets = [self[ds] for ds in datasets]
else:
datasets = [self.datasets.get(ds) for ds in sel... | [
"def",
"save_datasets",
"(",
"self",
",",
"writer",
"=",
"\"geotiff\"",
",",
"datasets",
"=",
"None",
",",
"compute",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"datasets",
"is",
"not",
"None",
":",
"datasets",
"=",
"[",
"self",
"[",
"ds",... | Save all the datasets present in a scene to disk using *writer*. | [
"Save",
"all",
"the",
"datasets",
"present",
"in",
"a",
"scene",
"to",
"disk",
"using",
"*",
"writer",
"*",
"."
] | python | train | 63.071429 |
rapidpro/dash | dash/orgs/views.py | https://github.com/rapidpro/dash/blob/e9dc05b31b86fe3fe72e956975d1ee0a275ac016/dash/orgs/views.py#L72-L87 | def has_permission(self, request, *args, **kwargs):
"""
Figures out if the current user has permissions for this view.
"""
self.kwargs = kwargs
self.args = args
self.request = request
self.org = self.derive_org()
if self.get_user().is_superuser:
... | [
"def",
"has_permission",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"kwargs",
"=",
"kwargs",
"self",
".",
"args",
"=",
"args",
"self",
".",
"request",
"=",
"request",
"self",
".",
"org",
"=",
"sel... | Figures out if the current user has permissions for this view. | [
"Figures",
"out",
"if",
"the",
"current",
"user",
"has",
"permissions",
"for",
"this",
"view",
"."
] | python | train | 28.0625 |
google/grr | grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py#L111-L116 | def CheckCronJobAccess(self, username, cron_job_id):
"""Checks whether a given user can access given cron job."""
self._CheckAccess(
username, str(cron_job_id),
rdf_objects.ApprovalRequest.ApprovalType.APPROVAL_TYPE_CRON_JOB) | [
"def",
"CheckCronJobAccess",
"(",
"self",
",",
"username",
",",
"cron_job_id",
")",
":",
"self",
".",
"_CheckAccess",
"(",
"username",
",",
"str",
"(",
"cron_job_id",
")",
",",
"rdf_objects",
".",
"ApprovalRequest",
".",
"ApprovalType",
".",
"APPROVAL_TYPE_CRON_... | Checks whether a given user can access given cron job. | [
"Checks",
"whether",
"a",
"given",
"user",
"can",
"access",
"given",
"cron",
"job",
"."
] | python | train | 40.833333 |
HDI-Project/ballet | ballet/validation/entropy.py | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L285-L316 | def estimate_mutual_information(x, y):
"""Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the K... | [
"def",
"estimate_mutual_information",
"(",
"x",
",",
"y",
")",
":",
"xy",
"=",
"np",
".",
"concatenate",
"(",
"(",
"x",
",",
"y",
")",
",",
"axis",
"=",
"1",
")",
"epsilon",
"=",
"_calculate_epsilon",
"(",
"xy",
")",
"h_x",
"=",
"estimate_entropy",
"... | Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
... | [
"Estimate",
"the",
"mutual",
"information",
"of",
"two",
"datasets",
"."
] | python | train | 34.84375 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2d.py | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2d.py#L406-L431 | def ximshow_unrectified(self, slitlet2d):
"""Display unrectified image with spectrails and frontiers.
Parameters
----------
slitlet2d : numpy array
Array containing the unrectified slitlet image.
"""
title = "Slitlet#" + str(self.islitlet)
ax = xims... | [
"def",
"ximshow_unrectified",
"(",
"self",
",",
"slitlet2d",
")",
":",
"title",
"=",
"\"Slitlet#\"",
"+",
"str",
"(",
"self",
".",
"islitlet",
")",
"ax",
"=",
"ximshow",
"(",
"slitlet2d",
",",
"title",
"=",
"title",
",",
"first_pixel",
"=",
"(",
"self",
... | Display unrectified image with spectrails and frontiers.
Parameters
----------
slitlet2d : numpy array
Array containing the unrectified slitlet image. | [
"Display",
"unrectified",
"image",
"with",
"spectrails",
"and",
"frontiers",
"."
] | python | train | 38.538462 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/geometry/triangulation.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/triangulation.py#L760-L766 | def _projection(self, a, b, c):
"""Return projection of (a,b) onto (a,c)
Arguments are point locations, not indexes.
"""
ab = b - a
ac = c - a
return a + ((ab*ac).sum() / (ac*ac).sum()) * ac | [
"def",
"_projection",
"(",
"self",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"ab",
"=",
"b",
"-",
"a",
"ac",
"=",
"c",
"-",
"a",
"return",
"a",
"+",
"(",
"(",
"ab",
"*",
"ac",
")",
".",
"sum",
"(",
")",
"/",
"(",
"ac",
"*",
"ac",
")",
"... | Return projection of (a,b) onto (a,c)
Arguments are point locations, not indexes. | [
"Return",
"projection",
"of",
"(",
"a",
"b",
")",
"onto",
"(",
"a",
"c",
")",
"Arguments",
"are",
"point",
"locations",
"not",
"indexes",
"."
] | python | train | 33.142857 |
shoebot/shoebot | lib/web/wikipedia.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/wikipedia.py#L657-L672 | def convert_table(self, markup):
""" Subtitutes <table> content to Wikipedia markup.
"""
for table in re.findall(self.re["html-table"], markup):
wiki = table
wiki = re.sub(r"<table(.*?)>", "{|\\1", wiki)
wiki = re.sub(r"<tr(.*?)>", "|-\\1", w... | [
"def",
"convert_table",
"(",
"self",
",",
"markup",
")",
":",
"for",
"table",
"in",
"re",
".",
"findall",
"(",
"self",
".",
"re",
"[",
"\"html-table\"",
"]",
",",
"markup",
")",
":",
"wiki",
"=",
"table",
"wiki",
"=",
"re",
".",
"sub",
"(",
"r\"<ta... | Subtitutes <table> content to Wikipedia markup. | [
"Subtitutes",
"<table",
">",
"content",
"to",
"Wikipedia",
"markup",
"."
] | python | valid | 36.875 |
gagneurlab/concise | concise/legacy/concise.py | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1342-L1358 | def _from_dict(self, obj_dict):
"""
Initialize a model from the dictionary
"""
self._n_folds = obj_dict["param"]["n_folds"]
self._n_rows = obj_dict["param"]["n_rows"]
self._use_stored_folds = obj_dict["param"]["use_stored_folds"]
self._concise_model = Concise.fro... | [
"def",
"_from_dict",
"(",
"self",
",",
"obj_dict",
")",
":",
"self",
".",
"_n_folds",
"=",
"obj_dict",
"[",
"\"param\"",
"]",
"[",
"\"n_folds\"",
"]",
"self",
".",
"_n_rows",
"=",
"obj_dict",
"[",
"\"param\"",
"]",
"[",
"\"n_rows\"",
"]",
"self",
".",
... | Initialize a model from the dictionary | [
"Initialize",
"a",
"model",
"from",
"the",
"dictionary"
] | python | train | 44.941176 |
user-cont/conu | conu/backend/docker/image.py | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/docker/image.py#L725-L738 | def layers(self, rev=True):
"""
Get list of DockerImage for every layer in image
:param rev: get layers rev
:return: list of DockerImages
"""
image_layers = [
DockerImage(None, identifier=x, pull_policy=DockerImagePullPolicy.NEVER)
for x in self.g... | [
"def",
"layers",
"(",
"self",
",",
"rev",
"=",
"True",
")",
":",
"image_layers",
"=",
"[",
"DockerImage",
"(",
"None",
",",
"identifier",
"=",
"x",
",",
"pull_policy",
"=",
"DockerImagePullPolicy",
".",
"NEVER",
")",
"for",
"x",
"in",
"self",
".",
"get... | Get list of DockerImage for every layer in image
:param rev: get layers rev
:return: list of DockerImages | [
"Get",
"list",
"of",
"DockerImage",
"for",
"every",
"layer",
"in",
"image"
] | python | train | 29.571429 |
pyQode/pyqode.core | pyqode/core/panels/marker.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/marker.py#L166-L180 | def marker_for_line(self, line):
"""
Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker
"""
markers = []
for marker in self._markers:
... | [
"def",
"marker_for_line",
"(",
"self",
",",
"line",
")",
":",
"markers",
"=",
"[",
"]",
"for",
"marker",
"in",
"self",
".",
"_markers",
":",
"if",
"line",
"==",
"marker",
".",
"position",
":",
"markers",
".",
"append",
"(",
"marker",
")",
"return",
"... | Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker | [
"Returns",
"the",
"marker",
"that",
"is",
"displayed",
"at",
"the",
"specified",
"line",
"number",
"if",
"any",
"."
] | python | train | 26.6 |
Alignak-monitoring/alignak | alignak/objects/satellitelink.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/satellitelink.py#L892-L906 | def push_results(self, results, scheduler_name):
"""Send a HTTP request to the satellite (POST /put_results)
Send actions results to the satellite
:param results: Results list to send
:type results: list
:param scheduler_name: Scheduler name
:type scheduler_name: uuid
... | [
"def",
"push_results",
"(",
"self",
",",
"results",
",",
"scheduler_name",
")",
":",
"logger",
".",
"debug",
"(",
"\"Pushing %d results\"",
",",
"len",
"(",
"results",
")",
")",
"result",
"=",
"self",
".",
"con",
".",
"post",
"(",
"'put_results'",
",",
"... | Send a HTTP request to the satellite (POST /put_results)
Send actions results to the satellite
:param results: Results list to send
:type results: list
:param scheduler_name: Scheduler name
:type scheduler_name: uuid
:return: True on success, False on failure
:rt... | [
"Send",
"a",
"HTTP",
"request",
"to",
"the",
"satellite",
"(",
"POST",
"/",
"put_results",
")",
"Send",
"actions",
"results",
"to",
"the",
"satellite"
] | python | train | 40 |
mapnik/Cascadenik | cascadenik/compile.py | https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L146-L169 | def output_path(self, path_name):
""" Modify a path so it fits expectations.
Avoid returning relative paths that start with '../' and possibly
return relative paths when output and cache directories match.
"""
# make sure it is a valid posix format
... | [
"def",
"output_path",
"(",
"self",
",",
"path_name",
")",
":",
"# make sure it is a valid posix format",
"path",
"=",
"to_posix",
"(",
"path_name",
")",
"assert",
"(",
"path",
"==",
"path_name",
")",
",",
"\"path_name passed to output_path must be in posix format\"",
"i... | Modify a path so it fits expectations.
Avoid returning relative paths that start with '../' and possibly
return relative paths when output and cache directories match. | [
"Modify",
"a",
"path",
"so",
"it",
"fits",
"expectations",
".",
"Avoid",
"returning",
"relative",
"paths",
"that",
"start",
"with",
"..",
"/",
"and",
"possibly",
"return",
"relative",
"paths",
"when",
"output",
"and",
"cache",
"directories",
"match",
"."
] | python | train | 36.333333 |
saltstack/salt | salt/modules/solr.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L313-L335 | def _get_admin_info(command, host=None, core_name=None):
'''
PRIVATE METHOD
Calls the _http_request method and passes the admin command to execute
and stores the data. This data is fairly static but should be refreshed
periodically to make sure everything this OK. The data object will contain
th... | [
"def",
"_get_admin_info",
"(",
"command",
",",
"host",
"=",
"None",
",",
"core_name",
"=",
"None",
")",
":",
"url",
"=",
"_format_url",
"(",
"\"admin/{0}\"",
".",
"format",
"(",
"command",
")",
",",
"host",
",",
"core_name",
"=",
"core_name",
")",
"resp"... | PRIVATE METHOD
Calls the _http_request method and passes the admin command to execute
and stores the data. This data is fairly static but should be refreshed
periodically to make sure everything this OK. The data object will contain
the JSON response.
command : str
The admin command to exec... | [
"PRIVATE",
"METHOD",
"Calls",
"the",
"_http_request",
"method",
"and",
"passes",
"the",
"admin",
"command",
"to",
"execute",
"and",
"stores",
"the",
"data",
".",
"This",
"data",
"is",
"fairly",
"static",
"but",
"should",
"be",
"refreshed",
"periodically",
"to"... | python | train | 37 |
Calysto/calysto | calysto/ai/conx.py | https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L1313-L1331 | def verifyArguments(self, arg):
"""
Verifies that arguments to setInputs and setTargets are appropriately formatted.
"""
for l in arg:
if not type(l) == list and \
not type(l) == type(Numeric.array([0.0])) and \
not type(l) == tuple and \
... | [
"def",
"verifyArguments",
"(",
"self",
",",
"arg",
")",
":",
"for",
"l",
"in",
"arg",
":",
"if",
"not",
"type",
"(",
"l",
")",
"==",
"list",
"and",
"not",
"type",
"(",
"l",
")",
"==",
"type",
"(",
"Numeric",
".",
"array",
"(",
"[",
"0.0",
"]",
... | Verifies that arguments to setInputs and setTargets are appropriately formatted. | [
"Verifies",
"that",
"arguments",
"to",
"setInputs",
"and",
"setTargets",
"are",
"appropriately",
"formatted",
"."
] | python | train | 36.473684 |
greenbender/pynntp | nntp/nntp.py | https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L505-L530 | def capabilities(self, keyword=None):
"""CAPABILITIES command.
Determines the capabilities of the server.
Although RFC3977 states that this is a required command for servers to
implement not all servers do, so expect that NNTPPermanentError may be
raised when this command is is... | [
"def",
"capabilities",
"(",
"self",
",",
"keyword",
"=",
"None",
")",
":",
"args",
"=",
"keyword",
"code",
",",
"message",
"=",
"self",
".",
"command",
"(",
"\"CAPABILITIES\"",
",",
"args",
")",
"if",
"code",
"!=",
"101",
":",
"raise",
"NNTPReplyError",
... | CAPABILITIES command.
Determines the capabilities of the server.
Although RFC3977 states that this is a required command for servers to
implement not all servers do, so expect that NNTPPermanentError may be
raised when this command is issued.
See <http://tools.ietf.org/html/rf... | [
"CAPABILITIES",
"command",
"."
] | python | test | 34.153846 |
Dispersive-Hydrodynamics-Lab/PACE | PACE/PACE.py | https://github.com/Dispersive-Hydrodynamics-Lab/PACE/blob/4ce27d5fc9b02cc2ce55f6fea7fc8d6015317e1f/PACE/PACE.py#L275-L308 | def _loadedges(self) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray, float, np.ndarray]:
"""
Attempts to intelligently load the .mat file and take average of left and right edges
:return: left and right averages
:return: times for each column
:return: accept/reject for each ... | [
"def",
"_loadedges",
"(",
"self",
")",
"->",
"typing",
".",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
",",
"float",
",",
"np",
".",
"ndarray",
"]",
":",
"data",
"=",
"sco",
".",
"loadmat",
"(",
"sel... | Attempts to intelligently load the .mat file and take average of left and right edges
:return: left and right averages
:return: times for each column
:return: accept/reject for each column
:return: pixel-inch ratio | [
"Attempts",
"to",
"intelligently",
"load",
"the",
".",
"mat",
"file",
"and",
"take",
"average",
"of",
"left",
"and",
"right",
"edges"
] | python | train | 32.911765 |
joeyespo/py-getch | getch/pause.py | https://github.com/joeyespo/py-getch/blob/295f0c2e602e6043ba0d338076abe847a7b29b0b/getch/pause.py#L7-L15 | def pause(message='Press any key to continue . . . '):
"""
Prints the specified message if it's not None and waits for a keypress.
"""
if message is not None:
print(message, end='')
sys.stdout.flush()
getch()
print() | [
"def",
"pause",
"(",
"message",
"=",
"'Press any key to continue . . . '",
")",
":",
"if",
"message",
"is",
"not",
"None",
":",
"print",
"(",
"message",
",",
"end",
"=",
"''",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"getch",
"(",
")",
"print... | Prints the specified message if it's not None and waits for a keypress. | [
"Prints",
"the",
"specified",
"message",
"if",
"it",
"s",
"not",
"None",
"and",
"waits",
"for",
"a",
"keypress",
"."
] | python | train | 27.555556 |
pyviz/holoviews | holoviews/plotting/bokeh/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/util.py#L812-L828 | def colormesh(X, Y):
"""
Generates line paths for a quadmesh given 2D arrays of X and Y
coordinates.
"""
X1 = X[0:-1, 0:-1].ravel()
Y1 = Y[0:-1, 0:-1].ravel()
X2 = X[1:, 0:-1].ravel()
Y2 = Y[1:, 0:-1].ravel()
X3 = X[1:, 1:].ravel()
Y3 = Y[1:, 1:].ravel()
X4 = X[0:-1, 1:].rave... | [
"def",
"colormesh",
"(",
"X",
",",
"Y",
")",
":",
"X1",
"=",
"X",
"[",
"0",
":",
"-",
"1",
",",
"0",
":",
"-",
"1",
"]",
".",
"ravel",
"(",
")",
"Y1",
"=",
"Y",
"[",
"0",
":",
"-",
"1",
",",
"0",
":",
"-",
"1",
"]",
".",
"ravel",
"(... | Generates line paths for a quadmesh given 2D arrays of X and Y
coordinates. | [
"Generates",
"line",
"paths",
"for",
"a",
"quadmesh",
"given",
"2D",
"arrays",
"of",
"X",
"and",
"Y",
"coordinates",
"."
] | python | train | 26.176471 |
mitsei/dlkit | dlkit/json_/assessment/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/managers.py#L958-L976 | def get_item_notification_session(self, item_receiver):
"""Gets the notification session for notifications pertaining to item changes.
arg: item_receiver (osid.assessment.ItemReceiver): the item
receiver interface
return: (osid.assessment.ItemNotificationSession) - an
... | [
"def",
"get_item_notification_session",
"(",
"self",
",",
"item_receiver",
")",
":",
"if",
"not",
"self",
".",
"supports_item_notification",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
... | Gets the notification session for notifications pertaining to item changes.
arg: item_receiver (osid.assessment.ItemReceiver): the item
receiver interface
return: (osid.assessment.ItemNotificationSession) - an
``ItemNotificationSession``
raise: NullArgument -... | [
"Gets",
"the",
"notification",
"session",
"for",
"notifications",
"pertaining",
"to",
"item",
"changes",
"."
] | python | train | 48 |
emc-openstack/storops | storops/lib/converter.py | https://github.com/emc-openstack/storops/blob/24b4b13bf065c0ef0538dd0b5ebb8f25d24176bd/storops/lib/converter.py#L257-L286 | def parse_host_address(addr):
"""
parse host address to get domain name or ipv4/v6 address,
cidr prefix and net mask code string if given a subnet address
:param addr:
:type addr: str
:return: parsed domain name/ipv4 address/ipv6 address,
cidr prefix if there is,
net m... | [
"def",
"parse_host_address",
"(",
"addr",
")",
":",
"if",
"addr",
".",
"startswith",
"(",
"'['",
")",
"and",
"addr",
".",
"endswith",
"(",
"']'",
")",
":",
"addr",
"=",
"addr",
"[",
"1",
":",
"-",
"1",
"]",
"parts",
"=",
"addr",
".",
"split",
"("... | parse host address to get domain name or ipv4/v6 address,
cidr prefix and net mask code string if given a subnet address
:param addr:
:type addr: str
:return: parsed domain name/ipv4 address/ipv6 address,
cidr prefix if there is,
net mask code string if there is
:rtype: (s... | [
"parse",
"host",
"address",
"to",
"get",
"domain",
"name",
"or",
"ipv4",
"/",
"v6",
"address",
"cidr",
"prefix",
"and",
"net",
"mask",
"code",
"string",
"if",
"given",
"a",
"subnet",
"address"
] | python | train | 32.566667 |
projectatomic/atomic-reactor | atomic_reactor/core.py | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/core.py#L764-L782 | def get_volumes_for_container(self, container_id, skip_empty_source=True):
"""
get a list of volumes mounter in a container
:param container_id: str
:param skip_empty_source: bool, don't list volumes which are not created on FS
:return: list, a list of volume names
"""
... | [
"def",
"get_volumes_for_container",
"(",
"self",
",",
"container_id",
",",
"skip_empty_source",
"=",
"True",
")",
":",
"logger",
".",
"info",
"(",
"\"listing volumes for container '%s'\"",
",",
"container_id",
")",
"inspect_output",
"=",
"self",
".",
"d",
".",
"in... | get a list of volumes mounter in a container
:param container_id: str
:param skip_empty_source: bool, don't list volumes which are not created on FS
:return: list, a list of volume names | [
"get",
"a",
"list",
"of",
"volumes",
"mounter",
"in",
"a",
"container"
] | python | train | 41.578947 |
davebridges/mousedb | mousedb/animal/views.py | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L56-L61 | def get_context_data(self, **kwargs):
"""This add in the context of list_type and returns this as Alive."""
context = super(AnimalListAlive, self).get_context_data(**kwargs)
context['list_type'] = 'Alive'
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"AnimalListAlive",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
"[",
"'list_type'",
"]",
"=",
"'Alive'",
"retu... | This add in the context of list_type and returns this as Alive. | [
"This",
"add",
"in",
"the",
"context",
"of",
"list_type",
"and",
"returns",
"this",
"as",
"Alive",
"."
] | python | train | 42.5 |
ARMmbed/icetea | icetea_lib/cloud.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/cloud.py#L136-L179 | def _convert_to_db_tc_metadata(tc_metadata):
"""
Convert tc_metadata to match Opentmi metadata format
:param tc_metadata: metadata as dict
:return: converted metadata
"""
db_meta = copy.deepcopy(tc_metadata)
# tcid is a mandatory field, it should throw an error i... | [
"def",
"_convert_to_db_tc_metadata",
"(",
"tc_metadata",
")",
":",
"db_meta",
"=",
"copy",
".",
"deepcopy",
"(",
"tc_metadata",
")",
"# tcid is a mandatory field, it should throw an error if it is missing",
"db_meta",
"[",
"'tcid'",
"]",
"=",
"db_meta",
"[",
"'name'",
"... | Convert tc_metadata to match Opentmi metadata format
:param tc_metadata: metadata as dict
:return: converted metadata | [
"Convert",
"tc_metadata",
"to",
"match",
"Opentmi",
"metadata",
"format",
":",
"param",
"tc_metadata",
":",
"metadata",
"as",
"dict",
":",
"return",
":",
"converted",
"metadata"
] | python | train | 34 |
codeforamerica/three | three/core.py | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L274-L282 | def token(self, id, **kwargs):
"""
Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}}
"""
data = self.get('tokens', id, **kwargs)
return data | [
"def",
"token",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"get",
"(",
"'tokens'",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
"return",
"data"
] | Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}} | [
"Retrieve",
"a",
"service",
"request",
"ID",
"from",
"a",
"token",
"."
] | python | train | 30.666667 |
getfleety/coralillo | coralillo/core.py | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L126-L137 | def set_engine(cls, neweng):
''' Sets the given coralillo engine so the model uses it to communicate
with the redis database '''
assert isinstance(neweng, Engine), 'Provided object must be of class Engine'
if hasattr(cls, 'Meta'):
cls.Meta.engine = neweng
else:
... | [
"def",
"set_engine",
"(",
"cls",
",",
"neweng",
")",
":",
"assert",
"isinstance",
"(",
"neweng",
",",
"Engine",
")",
",",
"'Provided object must be of class Engine'",
"if",
"hasattr",
"(",
"cls",
",",
"'Meta'",
")",
":",
"cls",
".",
"Meta",
".",
"engine",
... | Sets the given coralillo engine so the model uses it to communicate
with the redis database | [
"Sets",
"the",
"given",
"coralillo",
"engine",
"so",
"the",
"model",
"uses",
"it",
"to",
"communicate",
"with",
"the",
"redis",
"database"
] | python | train | 32.333333 |
KE-works/pykechain | pykechain/client.py | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L203-L214 | def _request(self, method, url, **kwargs):
# type: (str, str, **Any) -> requests.Response
"""Perform the request on the API."""
self.last_request = None
self.last_response = self.session.request(method, url, auth=self.auth, headers=self.headers, **kwargs)
self.last_request = self... | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, str, **Any) -> requests.Response",
"self",
".",
"last_request",
"=",
"None",
"self",
".",
"last_response",
"=",
"self",
".",
"session",
".",
"request",... | Perform the request on the API. | [
"Perform",
"the",
"request",
"on",
"the",
"API",
"."
] | python | train | 47.416667 |
albahnsen/CostSensitiveClassification | costcla/models/directcost.py | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L56-L74 | def fit(self,y_true_cal=None, y_prob_cal=None):
""" If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
y_pr... | [
"def",
"fit",
"(",
"self",
",",
"y_true_cal",
"=",
"None",
",",
"y_prob_cal",
"=",
"None",
")",
":",
"if",
"self",
".",
"calibration",
":",
"self",
".",
"cal",
"=",
"ROCConvexHull",
"(",
")",
"self",
".",
"cal",
".",
"fit",
"(",
"y_true_cal",
",",
... | If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
y_prob_cal : array-like of shape = [n_samples, 2], optional defa... | [
"If",
"calibration",
"then",
"train",
"the",
"calibration",
"of",
"probabilities"
] | python | train | 35.210526 |
saltstack/salt | salt/modules/openbsdpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L362-L413 | def upgrade(name=None,
pkgs=None,
**kwargs):
'''
Run a full package upgrade (``pkg_add -u``), or upgrade a specific package
if ``name`` or ``pkgs`` is provided.
``name`` is ignored when ``pkgs`` is specified.
Returns a dictionary containing the changes:
.. versionadded:... | [
"def",
"upgrade",
"(",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"old",
"=",
"list_pkgs",
"(",
")",
"cmd",
"=",
"[",
"'pkg_add'",
",",
"'-Ix'",
",",
"'-u'",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'noop'",
... | Run a full package upgrade (``pkg_add -u``), or upgrade a specific package
if ``name`` or ``pkgs`` is provided.
``name`` is ignored when ``pkgs`` is specified.
Returns a dictionary containing the changes:
.. versionadded:: 2019.2.0
.. code-block:: python
{'<package>': {'old': '<old-versi... | [
"Run",
"a",
"full",
"package",
"upgrade",
"(",
"pkg_add",
"-",
"u",
")",
"or",
"upgrade",
"a",
"specific",
"package",
"if",
"name",
"or",
"pkgs",
"is",
"provided",
".",
"name",
"is",
"ignored",
"when",
"pkgs",
"is",
"specified",
"."
] | python | train | 24.903846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.