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 |
|---|---|---|---|---|---|---|---|---|---|
LREN-CHUV/data-tracking | data_tracking/files_recording.py | https://github.com/LREN-CHUV/data-tracking/blob/f645a0d6426e6019c92d5aaf4be225cff2864417/data_tracking/files_recording.py#L124-L191 | def create_provenance(dataset, software_versions=None, db_url=None):
"""Create (or get if already exists) a provenance entity, store it in the database and get back a provenance ID.
Arguments:
:param dataset: Name of the data set.
:param software_versions: (optional) Version of the software components ... | [
"def",
"create_provenance",
"(",
"dataset",
",",
"software_versions",
"=",
"None",
",",
"db_url",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"\"Connecting to database...\"",
")",
"db_conn",
"=",
"connection",
".",
"Connection",
"(",
"db_url",
")",
"tr... | Create (or get if already exists) a provenance entity, store it in the database and get back a provenance ID.
Arguments:
:param dataset: Name of the data set.
:param software_versions: (optional) Version of the software components used to get the data. It is a dictionary
that accepts the following fiel... | [
"Create",
"(",
"or",
"get",
"if",
"already",
"exists",
")",
"a",
"provenance",
"entity",
"store",
"it",
"in",
"the",
"database",
"and",
"get",
"back",
"a",
"provenance",
"ID",
"."
] | python | train | 35.882353 |
graphql-python/graphql-core-next | graphql/language/parser.py | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L1107-L1118 | def expect_optional_keyword(lexer: Lexer, value: str) -> Optional[Token]:
"""Expect the next token optionally to be a given keyword.
If the next token is a given keyword, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None.
"""
token = lexer.token
... | [
"def",
"expect_optional_keyword",
"(",
"lexer",
":",
"Lexer",
",",
"value",
":",
"str",
")",
"->",
"Optional",
"[",
"Token",
"]",
":",
"token",
"=",
"lexer",
".",
"token",
"if",
"token",
".",
"kind",
"==",
"TokenKind",
".",
"NAME",
"and",
"token",
".",... | Expect the next token optionally to be a given keyword.
If the next token is a given keyword, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None. | [
"Expect",
"the",
"next",
"token",
"optionally",
"to",
"be",
"a",
"given",
"keyword",
"."
] | python | train | 36 |
CalebBell/thermo | thermo/electrochem.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/electrochem.py#L329-L373 | def Laliberte_density(T, ws, CASRNs):
r'''Calculate the density of an aqueous electrolyte mixture using the form proposed by [1]_.
Parameters are loaded by the function as needed. Units are Kelvin and Pa*s.
.. math::
\rho_m = \left(\frac{w_w}{\rho_w} + \sum_i \frac{w_i}{\rho_{app_i}}\right)^{-1}
... | [
"def",
"Laliberte_density",
"(",
"T",
",",
"ws",
",",
"CASRNs",
")",
":",
"rho_w",
"=",
"Laliberte_density_w",
"(",
"T",
")",
"w_w",
"=",
"1",
"-",
"sum",
"(",
"ws",
")",
"rho",
"=",
"w_w",
"/",
"rho_w",
"for",
"i",
"in",
"range",
"(",
"len",
"("... | r'''Calculate the density of an aqueous electrolyte mixture using the form proposed by [1]_.
Parameters are loaded by the function as needed. Units are Kelvin and Pa*s.
.. math::
\rho_m = \left(\frac{w_w}{\rho_w} + \sum_i \frac{w_i}{\rho_{app_i}}\right)^{-1}
Parameters
----------
T : float... | [
"r",
"Calculate",
"the",
"density",
"of",
"an",
"aqueous",
"electrolyte",
"mixture",
"using",
"the",
"form",
"proposed",
"by",
"[",
"1",
"]",
"_",
".",
"Parameters",
"are",
"loaded",
"by",
"the",
"function",
"as",
"needed",
".",
"Units",
"are",
"Kelvin",
... | python | valid | 30.355556 |
facelessuser/backrefs | tools/unipropgen.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/tools/unipropgen.py#L66-L76 | def create_span(unirange, is_bytes=False):
"""Clamp the Unicode range."""
if len(unirange) < 2:
unirange.append(unirange[0])
if is_bytes:
if unirange[0] > MAXASCII:
return None
if unirange[1] > MAXASCII:
unirange[1] = MAXASCII
return [x for x in range(uni... | [
"def",
"create_span",
"(",
"unirange",
",",
"is_bytes",
"=",
"False",
")",
":",
"if",
"len",
"(",
"unirange",
")",
"<",
"2",
":",
"unirange",
".",
"append",
"(",
"unirange",
"[",
"0",
"]",
")",
"if",
"is_bytes",
":",
"if",
"unirange",
"[",
"0",
"]"... | Clamp the Unicode range. | [
"Clamp",
"the",
"Unicode",
"range",
"."
] | python | train | 30.636364 |
basilfx/flask-daapserver | daapserver/provider.py | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/provider.py#L120-L131 | def destroy_session(self, session_id):
"""
Destroy an (existing) session.
"""
try:
del self.sessions[session_id]
except KeyError:
pass
# Invoke hooks
invoke_hooks(self.hooks, "session_destroyed", session_id) | [
"def",
"destroy_session",
"(",
"self",
",",
"session_id",
")",
":",
"try",
":",
"del",
"self",
".",
"sessions",
"[",
"session_id",
"]",
"except",
"KeyError",
":",
"pass",
"# Invoke hooks",
"invoke_hooks",
"(",
"self",
".",
"hooks",
",",
"\"session_destroyed\""... | Destroy an (existing) session. | [
"Destroy",
"an",
"(",
"existing",
")",
"session",
"."
] | python | train | 23.166667 |
clchiou/startup | startup.py | https://github.com/clchiou/startup/blob/13cbf3ce1deffbc10d33a5f64c396a73129a5929/startup.py#L297-L305 | def _write_values(kwargs, variables):
"""Write values of kwargs and return thus-satisfied closures."""
writeto = []
for var_name, value in kwargs.items():
var = variables[var_name]
var.notify_will_write()
var.write(value)
writeto.append(var)
return _notify_reader_writes(w... | [
"def",
"_write_values",
"(",
"kwargs",
",",
"variables",
")",
":",
"writeto",
"=",
"[",
"]",
"for",
"var_name",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"var",
"=",
"variables",
"[",
"var_name",
"]",
"var",
".",
"notify_will_write",
"... | Write values of kwargs and return thus-satisfied closures. | [
"Write",
"values",
"of",
"kwargs",
"and",
"return",
"thus",
"-",
"satisfied",
"closures",
"."
] | python | train | 35.444444 |
jerith/txTwitter | txtwitter/twitter.py | https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L132-L172 | def set_int_param(params, name, value, min=None, max=None):
"""
Set a int parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param int value:
The value of the parameter. If ``None``, the field will not be... | [
"def",
"set_int_param",
"(",
"params",
",",
"name",
",",
"value",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"value",
"=",
"int",
"(",
"str",
"(",
"value",
")",
")",
"except... | Set a int parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param int value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of a numeric type or a string that can be t... | [
"Set",
"a",
"int",
"parameter",
"if",
"applicable",
"."
] | python | train | 31.902439 |
marrabld/planarradpy | gui/gui_mainLayout.py | https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/gui/gui_mainLayout.py#L477-L533 | def data_processing(self):
"""
This function separates data, from the file to display curves, and will put them in the good arrays.
"""
the_file_name = str(self.result_file)
the_file = open(the_file_name, 'r')
lines = the_file.readlines()
# We put all lines in a... | [
"def",
"data_processing",
"(",
"self",
")",
":",
"the_file_name",
"=",
"str",
"(",
"self",
".",
"result_file",
")",
"the_file",
"=",
"open",
"(",
"the_file_name",
",",
"'r'",
")",
"lines",
"=",
"the_file",
".",
"readlines",
"(",
")",
"# We put all lines in a... | This function separates data, from the file to display curves, and will put them in the good arrays. | [
"This",
"function",
"separates",
"data",
"from",
"the",
"file",
"to",
"display",
"curves",
"and",
"will",
"put",
"them",
"in",
"the",
"good",
"arrays",
"."
] | python | test | 49.473684 |
Parsl/parsl | parsl/executors/serialize/canning.py | https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/canning.py#L323-L334 | def istype(obj, check):
"""Like isinstance(obj, check), but strict.
This won't catch subclasses.
"""
if isinstance(check, tuple):
for cls in check:
if type(obj) is cls:
return True
return False
else:
return type(obj) is check | [
"def",
"istype",
"(",
"obj",
",",
"check",
")",
":",
"if",
"isinstance",
"(",
"check",
",",
"tuple",
")",
":",
"for",
"cls",
"in",
"check",
":",
"if",
"type",
"(",
"obj",
")",
"is",
"cls",
":",
"return",
"True",
"return",
"False",
"else",
":",
"r... | Like isinstance(obj, check), but strict.
This won't catch subclasses. | [
"Like",
"isinstance",
"(",
"obj",
"check",
")",
"but",
"strict",
"."
] | python | valid | 23.916667 |
aiortc/aiortc | aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/rtcsctptransport.py#L1171-L1218 | async def _send(self, stream_id, pp_id, user_data,
expiry=None, max_retransmits=None, ordered=True):
"""
Send data ULP -> stream.
"""
if ordered:
stream_seq = self._outbound_stream_seq.get(stream_id, 0)
else:
stream_seq = 0
fra... | [
"async",
"def",
"_send",
"(",
"self",
",",
"stream_id",
",",
"pp_id",
",",
"user_data",
",",
"expiry",
"=",
"None",
",",
"max_retransmits",
"=",
"None",
",",
"ordered",
"=",
"True",
")",
":",
"if",
"ordered",
":",
"stream_seq",
"=",
"self",
".",
"_outb... | Send data ULP -> stream. | [
"Send",
"data",
"ULP",
"-",
">",
"stream",
"."
] | python | train | 34.583333 |
serkanyersen/underscore.py | src/underscore.py | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L1055-L1068 | def isEmpty(self):
"""
Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties.
"""
if self.obj is None:
return True
if self._clean.isString():
ret = self.obj.strip() is ""
elif self._clean.isDict():
... | [
"def",
"isEmpty",
"(",
"self",
")",
":",
"if",
"self",
".",
"obj",
"is",
"None",
":",
"return",
"True",
"if",
"self",
".",
"_clean",
".",
"isString",
"(",
")",
":",
"ret",
"=",
"self",
".",
"obj",
".",
"strip",
"(",
")",
"is",
"\"\"",
"elif",
"... | Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties. | [
"Is",
"a",
"given",
"array",
"string",
"or",
"object",
"empty?",
"An",
"empty",
"object",
"has",
"no",
"enumerable",
"own",
"-",
"properties",
"."
] | python | train | 30.714286 |
pybel/pybel-tools | src/pybel_tools/selection/group_nodes.py | https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/group_nodes.py#L66-L86 | def group_nodes_by_annotation_filtered(graph: BELGraph,
node_predicates: NodePredicates = None,
annotation: str = 'Subgraph',
) -> Mapping[str, Set[BaseEntity]]:
"""Group the nodes occurring in edges... | [
"def",
"group_nodes_by_annotation_filtered",
"(",
"graph",
":",
"BELGraph",
",",
"node_predicates",
":",
"NodePredicates",
"=",
"None",
",",
"annotation",
":",
"str",
"=",
"'Subgraph'",
",",
")",
"->",
"Mapping",
"[",
"str",
",",
"Set",
"[",
"BaseEntity",
"]",... | Group the nodes occurring in edges by the given annotation, with a node filter applied.
:param graph: A BEL graph
:param node_predicates: A predicate or list of predicates (graph, node) -> bool
:param annotation: The annotation to use for grouping
:return: A dictionary of {annotation value: set of node... | [
"Group",
"the",
"nodes",
"occurring",
"in",
"edges",
"by",
"the",
"given",
"annotation",
"with",
"a",
"node",
"filter",
"applied",
"."
] | python | valid | 41.428571 |
ibis-project/ibis | ibis/expr/api.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L3197-L3214 | def _table_limit(table, n, offset=0):
"""
Select the first n rows at beginning of table (may not be deterministic
depending on implementation and presence of a sorting).
Parameters
----------
n : int
Number of rows to include
offset : int, default 0
Number of rows to skip first
... | [
"def",
"_table_limit",
"(",
"table",
",",
"n",
",",
"offset",
"=",
"0",
")",
":",
"op",
"=",
"ops",
".",
"Limit",
"(",
"table",
",",
"n",
",",
"offset",
"=",
"offset",
")",
"return",
"op",
".",
"to_expr",
"(",
")"
] | Select the first n rows at beginning of table (may not be deterministic
depending on implementation and presence of a sorting).
Parameters
----------
n : int
Number of rows to include
offset : int, default 0
Number of rows to skip first
Returns
-------
limited : TableExpr | [
"Select",
"the",
"first",
"n",
"rows",
"at",
"beginning",
"of",
"table",
"(",
"may",
"not",
"be",
"deterministic",
"depending",
"on",
"implementation",
"and",
"presence",
"of",
"a",
"sorting",
")",
"."
] | python | train | 23.722222 |
clinicedc/edc-notification | edc_notification/mailing_list_manager.py | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L56-L71 | def api_key(self):
"""Returns the api_key or None.
"""
if not self._api_key:
error_msg = (
f"Email is enabled but API_KEY is not set. "
f"See settings.{self.api_key_attr}"
)
try:
self._api_key = getattr(settings,... | [
"def",
"api_key",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_api_key",
":",
"error_msg",
"=",
"(",
"f\"Email is enabled but API_KEY is not set. \"",
"f\"See settings.{self.api_key_attr}\"",
")",
"try",
":",
"self",
".",
"_api_key",
"=",
"getattr",
"(",
"se... | Returns the api_key or None. | [
"Returns",
"the",
"api_key",
"or",
"None",
"."
] | python | train | 38.25 |
numenta/htmresearch | projects/l2_pooling/ideal_classifier_experiment.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/ideal_classifier_experiment.py#L432-L497 | def run_multiple_column_experiment():
"""
Compare the ideal observer against a multi-column sensorimotor network.
"""
# Create the objects
featureRange = [5, 10, 20, 30]
pointRange = 1
objectRange = [100]
numLocations = [10]
numPoints = 10
numTrials = 10
columnRange = [1, 2, 3, 4, 5, 6, 7, 8]
us... | [
"def",
"run_multiple_column_experiment",
"(",
")",
":",
"# Create the objects",
"featureRange",
"=",
"[",
"5",
",",
"10",
",",
"20",
",",
"30",
"]",
"pointRange",
"=",
"1",
"objectRange",
"=",
"[",
"100",
"]",
"numLocations",
"=",
"[",
"10",
"]",
"numPoint... | Compare the ideal observer against a multi-column sensorimotor network. | [
"Compare",
"the",
"ideal",
"observer",
"against",
"a",
"multi",
"-",
"column",
"sensorimotor",
"network",
"."
] | python | train | 29 |
henzk/django-productline | django_productline/tasks.py | https://github.com/henzk/django-productline/blob/24ff156924c1a8c07b99cbb8a1de0a42b8d81f60/django_productline/tasks.py#L168-L177 | def export_data(target_path):
"""
Exports the data of an application - media files plus database,
:param: target_path:
:return: a zip archive
"""
tasks.export_data_dir(target_path)
tasks.export_database(target_path)
tasks.export_context(target_path)
return target_path | [
"def",
"export_data",
"(",
"target_path",
")",
":",
"tasks",
".",
"export_data_dir",
"(",
"target_path",
")",
"tasks",
".",
"export_database",
"(",
"target_path",
")",
"tasks",
".",
"export_context",
"(",
"target_path",
")",
"return",
"target_path"
] | Exports the data of an application - media files plus database,
:param: target_path:
:return: a zip archive | [
"Exports",
"the",
"data",
"of",
"an",
"application",
"-",
"media",
"files",
"plus",
"database",
":",
"param",
":",
"target_path",
":",
":",
"return",
":",
"a",
"zip",
"archive"
] | python | train | 29.5 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/MacOS/backend_wx.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/backend_wx.py#L411-L446 | def get_wx_font(self, s, prop):
"""
Return a wx font. Cache instances in a font dictionary for
efficiency
"""
DEBUG_MSG("get_wx_font()", 1, self)
key = hash(prop)
fontprop = prop
fontname = fontprop.get_name()
font = self.fontd.get(key)
... | [
"def",
"get_wx_font",
"(",
"self",
",",
"s",
",",
"prop",
")",
":",
"DEBUG_MSG",
"(",
"\"get_wx_font()\"",
",",
"1",
",",
"self",
")",
"key",
"=",
"hash",
"(",
"prop",
")",
"fontprop",
"=",
"prop",
"fontname",
"=",
"fontprop",
".",
"get_name",
"(",
"... | Return a wx font. Cache instances in a font dictionary for
efficiency | [
"Return",
"a",
"wx",
"font",
".",
"Cache",
"instances",
"in",
"a",
"font",
"dictionary",
"for",
"efficiency"
] | python | train | 33.694444 |
minio/minio-py | minio/parsers.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L367-L389 | def parse_get_bucket_notification(data):
"""
Parser for a get_bucket_notification response from S3.
:param data: Body of response from get_bucket_notification.
:return: Returns bucket notification configuration
"""
root = S3Element.fromstring('GetBucketNotificationResult', data)
notificati... | [
"def",
"parse_get_bucket_notification",
"(",
"data",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'GetBucketNotificationResult'",
",",
"data",
")",
"notifications",
"=",
"_parse_add_notifying_service_config",
"(",
"root",
",",
"{",
"}",
",",
"'TopicC... | Parser for a get_bucket_notification response from S3.
:param data: Body of response from get_bucket_notification.
:return: Returns bucket notification configuration | [
"Parser",
"for",
"a",
"get_bucket_notification",
"response",
"from",
"S3",
"."
] | python | train | 32.434783 |
SoCo/SoCo | soco/plugins/wimp.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L200-L206 | def get_albums(self, search, start=0, max_items=100):
"""Search for albums.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('albums', search, start,
max_items) | [
"def",
"get_albums",
"(",
"self",
",",
"search",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
")",
":",
"return",
"self",
".",
"get_music_service_information",
"(",
"'albums'",
",",
"search",
",",
"start",
",",
"max_items",
")"
] | Search for albums.
See get_music_service_information for details on the arguments | [
"Search",
"for",
"albums",
"."
] | python | train | 42.428571 |
NLeSC/noodles | noodles/run/worker.py | https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/worker.py#L7-L22 | def worker(job):
"""Primary |worker| coroutine. This is a |pull| object that pulls jobs from
a source and yield evaluated results.
Input should be of type |JobMessage|, output of type |ResultMessage|.
.. |worker| replace:: :py:func::`worker`"""
if job is EndOfQueue:
return
if not isin... | [
"def",
"worker",
"(",
"job",
")",
":",
"if",
"job",
"is",
"EndOfQueue",
":",
"return",
"if",
"not",
"isinstance",
"(",
"job",
",",
"JobMessage",
")",
":",
"print",
"(",
"\"Warning: Job should be communicated using `JobMessage`.\"",
",",
"file",
"=",
"sys",
"."... | Primary |worker| coroutine. This is a |pull| object that pulls jobs from
a source and yield evaluated results.
Input should be of type |JobMessage|, output of type |ResultMessage|.
.. |worker| replace:: :py:func::`worker` | [
"Primary",
"|worker|",
"coroutine",
".",
"This",
"is",
"a",
"|pull|",
"object",
"that",
"pulls",
"jobs",
"from",
"a",
"source",
"and",
"yield",
"evaluated",
"results",
"."
] | python | train | 30.25 |
gem/oq-engine | openquake/hazardlib/gsim/bindi_2017.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bindi_2017.py#L110-L119 | def _get_distance_scaling(self, C, dists, mag):
"""
Implements the distance scaling function F(M, R) presented in equations
2 and 3. In the case of Joyner-Boore distance then the fixed-depth
term h is required
"""
r_h = self._get_rh(C, dists)
return (C["c1"] + C["... | [
"def",
"_get_distance_scaling",
"(",
"self",
",",
"C",
",",
"dists",
",",
"mag",
")",
":",
"r_h",
"=",
"self",
".",
"_get_rh",
"(",
"C",
",",
"dists",
")",
"return",
"(",
"C",
"[",
"\"c1\"",
"]",
"+",
"C",
"[",
"\"c2\"",
"]",
"*",
"(",
"mag",
"... | Implements the distance scaling function F(M, R) presented in equations
2 and 3. In the case of Joyner-Boore distance then the fixed-depth
term h is required | [
"Implements",
"the",
"distance",
"scaling",
"function",
"F",
"(",
"M",
"R",
")",
"presented",
"in",
"equations",
"2",
"and",
"3",
".",
"In",
"the",
"case",
"of",
"Joyner",
"-",
"Boore",
"distance",
"then",
"the",
"fixed",
"-",
"depth",
"term",
"h",
"is... | python | train | 45.7 |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2388-L2402 | def validate_dataset_string(self, dataset):
""" determine if a dataset string is valid, meaning it is in the format
of {username}/{dataset-slug}.
Parameters
==========
dataset: the dataset name to validate
"""
if dataset:
if '/' not in... | [
"def",
"validate_dataset_string",
"(",
"self",
",",
"dataset",
")",
":",
"if",
"dataset",
":",
"if",
"'/'",
"not",
"in",
"dataset",
":",
"raise",
"ValueError",
"(",
"'Dataset must be specified in the form of '",
"'\\'{username}/{dataset-slug}\\''",
")",
"split",
"=",
... | determine if a dataset string is valid, meaning it is in the format
of {username}/{dataset-slug}.
Parameters
==========
dataset: the dataset name to validate | [
"determine",
"if",
"a",
"dataset",
"string",
"is",
"valid",
"meaning",
"it",
"is",
"in",
"the",
"format",
"of",
"{",
"username",
"}",
"/",
"{",
"dataset",
"-",
"slug",
"}",
".",
"Parameters",
"==========",
"dataset",
":",
"the",
"dataset",
"name",
"to",
... | python | train | 41.333333 |
Kane610/deconz | pydeconz/deconzdevice.py | https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/deconzdevice.py#L37-L40 | def remove_callback(self, callback):
"""Remove callback previously registered."""
if callback in self._async_callbacks:
self._async_callbacks.remove(callback) | [
"def",
"remove_callback",
"(",
"self",
",",
"callback",
")",
":",
"if",
"callback",
"in",
"self",
".",
"_async_callbacks",
":",
"self",
".",
"_async_callbacks",
".",
"remove",
"(",
"callback",
")"
] | Remove callback previously registered. | [
"Remove",
"callback",
"previously",
"registered",
"."
] | python | train | 45.75 |
dfm/george | george/utils.py | https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/utils.py#L11-L33 | def multivariate_gaussian_samples(matrix, N, mean=None):
"""
Generate samples from a multidimensional Gaussian with a given covariance.
:param matrix: ``(k, k)``
The covariance matrix.
:param N:
The number of samples to generate.
:param mean: ``(k,)`` (optional)
The mean o... | [
"def",
"multivariate_gaussian_samples",
"(",
"matrix",
",",
"N",
",",
"mean",
"=",
"None",
")",
":",
"if",
"mean",
"is",
"None",
":",
"mean",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"matrix",
")",
")",
"samples",
"=",
"np",
".",
"random",
".",
"m... | Generate samples from a multidimensional Gaussian with a given covariance.
:param matrix: ``(k, k)``
The covariance matrix.
:param N:
The number of samples to generate.
:param mean: ``(k,)`` (optional)
The mean of the Gaussian. Assumed to be zero if not given.
:returns sample... | [
"Generate",
"samples",
"from",
"a",
"multidimensional",
"Gaussian",
"with",
"a",
"given",
"covariance",
"."
] | python | train | 27.478261 |
rocky/python3-trepan | trepan/bwprocessor/main.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/main.py#L447-L454 | def _populate_cmd_lists(self):
""" Populate self.commands"""
self.commands = {}
for cmd_instance in self.cmd_instances:
cmd_name = cmd_instance.name
self.commands[cmd_name] = cmd_instance
pass
return | [
"def",
"_populate_cmd_lists",
"(",
"self",
")",
":",
"self",
".",
"commands",
"=",
"{",
"}",
"for",
"cmd_instance",
"in",
"self",
".",
"cmd_instances",
":",
"cmd_name",
"=",
"cmd_instance",
".",
"name",
"self",
".",
"commands",
"[",
"cmd_name",
"]",
"=",
... | Populate self.commands | [
"Populate",
"self",
".",
"commands"
] | python | test | 32.5 |
hasgeek/coaster | coaster/views/classview.py | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L407-L437 | def add_route_for(cls, _name, rule, **options):
"""
Add a route for an existing method or view. Useful for modifying routes
that a subclass inherits from a base class::
class BaseView(ClassView):
def latent_view(self):
return 'latent-view'
... | [
"def",
"add_route_for",
"(",
"cls",
",",
"_name",
",",
"rule",
",",
"*",
"*",
"options",
")",
":",
"setattr",
"(",
"cls",
",",
"_name",
",",
"route",
"(",
"rule",
",",
"*",
"*",
"options",
")",
"(",
"cls",
".",
"__get_raw_attr",
"(",
"_name",
")",
... | Add a route for an existing method or view. Useful for modifying routes
that a subclass inherits from a base class::
class BaseView(ClassView):
def latent_view(self):
return 'latent-view'
@route('other')
def other_view(self):
... | [
"Add",
"a",
"route",
"for",
"an",
"existing",
"method",
"or",
"view",
".",
"Useful",
"for",
"modifying",
"routes",
"that",
"a",
"subclass",
"inherits",
"from",
"a",
"base",
"class",
"::"
] | python | train | 35.548387 |
mediawiki-utilities/python-mwtypes | mwtypes/upload.py | https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/upload.py#L40-L71 | def initialize(self, timestamp=None, user=None, comment=None,
filename=None, source=None, size=None):
self.timestamp = none_or(timestamp, Timestamp)
"""
Upload timestamp : mwtypes.Timestamp | None
"""
self.user = none_or(user, User)
"""
Contri... | [
"def",
"initialize",
"(",
"self",
",",
"timestamp",
"=",
"None",
",",
"user",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"source",
"=",
"None",
",",
"size",
"=",
"None",
")",
":",
"self",
".",
"timestamp",
"=",
"no... | Upload timestamp : mwtypes.Timestamp | None | [
"Upload",
"timestamp",
":",
"mwtypes",
".",
"Timestamp",
"|",
"None"
] | python | train | 25.65625 |
docker/docker-py | docker/models/containers.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/models/containers.py#L274-L302 | def logs(self, **kwargs):
"""
Get logs from this container. Similar to the ``docker logs`` command.
The ``stream`` parameter makes the ``logs`` function return a blocking
generator you can iterate over to retrieve log output as it happens.
Args:
stdout (bool): Get `... | [
"def",
"logs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"api",
".",
"logs",
"(",
"self",
".",
"id",
",",
"*",
"*",
"kwargs",
")"
] | Get logs from this container. Similar to the ``docker logs`` command.
The ``stream`` parameter makes the ``logs`` function return a blocking
generator you can iterate over to retrieve log output as it happens.
Args:
stdout (bool): Get ``STDOUT``. Default ``True``
stderr... | [
"Get",
"logs",
"from",
"this",
"container",
".",
"Similar",
"to",
"the",
"docker",
"logs",
"command",
"."
] | python | train | 43.793103 |
msfrank/cifparser | cifparser/parser.py | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L191-L202 | def pop_frame(self):
"""
Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack
"""
self.frames.pop(0)
if len(self.frames) == 0:
raise Exception("stack ... | [
"def",
"pop_frame",
"(",
"self",
")",
":",
"self",
".",
"frames",
".",
"pop",
"(",
"0",
")",
"if",
"len",
"(",
"self",
".",
"frames",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"stack is exhausted\"",
")",
"return",
"self",
".",
"frames",
"[",... | Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack | [
"Remove",
"and",
"return",
"the",
"frame",
"at",
"the",
"top",
"of",
"the",
"stack",
"."
] | python | train | 29.416667 |
locationlabs/mockredis | mockredis/client.py | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1306-L1309 | def eval(self, script, numkeys, *keys_and_args):
"""Emulate eval"""
sha = self.script_load(script)
return self.evalsha(sha, numkeys, *keys_and_args) | [
"def",
"eval",
"(",
"self",
",",
"script",
",",
"numkeys",
",",
"*",
"keys_and_args",
")",
":",
"sha",
"=",
"self",
".",
"script_load",
"(",
"script",
")",
"return",
"self",
".",
"evalsha",
"(",
"sha",
",",
"numkeys",
",",
"*",
"keys_and_args",
")"
] | Emulate eval | [
"Emulate",
"eval"
] | python | train | 42.25 |
hazelcast/hazelcast-python-client | hazelcast/proxy/replicated_map.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/replicated_map.py#L154-L171 | def put(self, key, value, ttl=0):
"""
Associates the specified value with the specified key in this map. If the map previously contained a mapping for
the key, the old value is replaced by the specified value. If ttl is provided, entry will expire and get evicted
after the ttl.
... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"ttl",
"=",
"0",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be None\"",
")",
"check_not_none",
"(",
"key",
",",
"\"value can't be None\"",
")",
"key_data",
"=",
"self",
".",
"_to_data... | Associates the specified value with the specified key in this map. If the map previously contained a mapping for
the key, the old value is replaced by the specified value. If ttl is provided, entry will expire and get evicted
after the ttl.
:param key: (object), the specified key.
:para... | [
"Associates",
"the",
"specified",
"value",
"with",
"the",
"specified",
"key",
"in",
"this",
"map",
".",
"If",
"the",
"map",
"previously",
"contained",
"a",
"mapping",
"for",
"the",
"key",
"the",
"old",
"value",
"is",
"replaced",
"by",
"the",
"specified",
"... | python | train | 58.722222 |
apache/incubator-mxnet | tools/im2rec.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L228-L263 | def write_worker(q_out, fname, working_dir):
"""Function that will be spawned to fetch processed image
from the output queue and write to the .rec file.
Parameters
----------
q_out: queue
fname: string
working_dir: string
"""
pre_time = time.time()
count = 0
fname = os.path.b... | [
"def",
"write_worker",
"(",
"q_out",
",",
"fname",
",",
"working_dir",
")",
":",
"pre_time",
"=",
"time",
".",
"time",
"(",
")",
"count",
"=",
"0",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
")",
"fname_rec",
"=",
"os",
".",
"p... | Function that will be spawned to fetch processed image
from the output queue and write to the .rec file.
Parameters
----------
q_out: queue
fname: string
working_dir: string | [
"Function",
"that",
"will",
"be",
"spawned",
"to",
"fetch",
"processed",
"image",
"from",
"the",
"output",
"queue",
"and",
"write",
"to",
"the",
".",
"rec",
"file",
".",
"Parameters",
"----------",
"q_out",
":",
"queue",
"fname",
":",
"string",
"working_dir"... | python | train | 31.5 |
hyperledger/indy-plenum | plenum/server/replica.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L902-L912 | def processReqDuringBatch(
self,
req: Request,
cons_time: int):
"""
This method will do dynamic validation and apply requests.
If there is any errors during validation it would be raised
"""
if self.isMaster:
self.node.doDynamicVali... | [
"def",
"processReqDuringBatch",
"(",
"self",
",",
"req",
":",
"Request",
",",
"cons_time",
":",
"int",
")",
":",
"if",
"self",
".",
"isMaster",
":",
"self",
".",
"node",
".",
"doDynamicValidation",
"(",
"req",
")",
"self",
".",
"node",
".",
"applyReq",
... | This method will do dynamic validation and apply requests.
If there is any errors during validation it would be raised | [
"This",
"method",
"will",
"do",
"dynamic",
"validation",
"and",
"apply",
"requests",
".",
"If",
"there",
"is",
"any",
"errors",
"during",
"validation",
"it",
"would",
"be",
"raised"
] | python | train | 33.454545 |
chaoss/grimoirelab-elk | grimoire_elk/enriched/projects.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/projects.py#L37-L62 | def get_projects(self):
""" Get the projects list from database """
repos_list = []
gerrit_projects_db = self.projects_db
db = Database(user="root", passwd="", host="localhost", port=3306,
scrdb=None, shdb=gerrit_projects_db, prjdb=None)
sql = """
... | [
"def",
"get_projects",
"(",
"self",
")",
":",
"repos_list",
"=",
"[",
"]",
"gerrit_projects_db",
"=",
"self",
".",
"projects_db",
"db",
"=",
"Database",
"(",
"user",
"=",
"\"root\"",
",",
"passwd",
"=",
"\"\"",
",",
"host",
"=",
"\"localhost\"",
",",
"po... | Get the projects list from database | [
"Get",
"the",
"projects",
"list",
"from",
"database"
] | python | train | 31.538462 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L62-L91 | def _load_plugins(self):
'''
Sets up all plugins, defaults and settings.py
'''
plugins = self.settings['PLUGINS']
self.plugins_dict = {}
for key in plugins:
# skip loading the plugin if its value is None
if plugins[key] is None:
co... | [
"def",
"_load_plugins",
"(",
"self",
")",
":",
"plugins",
"=",
"self",
".",
"settings",
"[",
"'PLUGINS'",
"]",
"self",
".",
"plugins_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"plugins",
":",
"# skip loading the plugin if its value is None",
"if",
"plugins",
"[... | Sets up all plugins, defaults and settings.py | [
"Sets",
"up",
"all",
"plugins",
"defaults",
"and",
"settings",
".",
"py"
] | python | train | 39.166667 |
numenta/nupic | src/nupic/swarming/permutations_runner.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/permutations_runner.py#L639-L694 | def __startSearch(self):
"""Starts HyperSearch as a worker or runs it inline for the "dryRun" action
Parameters:
----------------------------------------------------------------------
retval: the new _HyperSearchJob instance representing the
HyperSearch job
"""
# Thi... | [
"def",
"__startSearch",
"(",
"self",
")",
":",
"# This search uses a pre-existing permutations script",
"params",
"=",
"_ClientJobUtils",
".",
"makeSearchJobParamsDict",
"(",
"options",
"=",
"self",
".",
"_options",
",",
"forRunning",
"=",
"True",
")",
"if",
"self",
... | Starts HyperSearch as a worker or runs it inline for the "dryRun" action
Parameters:
----------------------------------------------------------------------
retval: the new _HyperSearchJob instance representing the
HyperSearch job | [
"Starts",
"HyperSearch",
"as",
"a",
"worker",
"or",
"runs",
"it",
"inline",
"for",
"the",
"dryRun",
"action"
] | python | valid | 37.267857 |
aouyar/PyMunin | pymunin/__init__.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/__init__.py#L675-L685 | def getSubgraphFieldCount(self, parent_name, graph_name):
"""Returns number of fields for subgraph with name graph_name and parent
graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: Number of fields for... | [
"def",
"getSubgraphFieldCount",
"(",
"self",
",",
"parent_name",
",",
"graph_name",
")",
":",
"graph",
"=",
"self",
".",
"_getSubGraph",
"(",
"parent_name",
",",
"graph_name",
",",
"True",
")",
"return",
"graph",
".",
"getFieldCount",
"(",
")"
] | Returns number of fields for subgraph with name graph_name and parent
graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: Number of fields for subgraph. | [
"Returns",
"number",
"of",
"fields",
"for",
"subgraph",
"with",
"name",
"graph_name",
"and",
"parent",
"graph",
"with",
"name",
"parent_name",
"."
] | python | train | 40.272727 |
DarkEnergySurvey/ugali | ugali/pipeline/run_05.0_followup.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/pipeline/run_05.0_followup.py#L73-L136 | def do_plot(args):
""" Create plots of mcmc output """
import ugali.utils.plotting
import pylab as plt
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
samfile = filenames['samfile']
memfile = filenames['memfile']
if not exists(... | [
"def",
"do_plot",
"(",
"args",
")",
":",
"import",
"ugali",
".",
"utils",
".",
"plotting",
"import",
"pylab",
"as",
"plt",
"config",
",",
"name",
",",
"label",
",",
"coord",
"=",
"args",
"filenames",
"=",
"make_filenames",
"(",
"config",
",",
"label",
... | Create plots of mcmc output | [
"Create",
"plots",
"of",
"mcmc",
"output"
] | python | train | 32.78125 |
log2timeline/plaso | plaso/parsers/sqlite.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/sqlite.py#L293-L307 | def Query(self, query):
"""Queries the database.
Args:
query (str): SQL query.
Returns:
sqlite3.Cursor: results.
Raises:
sqlite3.DatabaseError: if querying the database fails.
"""
cursor = self._database.cursor()
cursor.execute(query)
return cursor | [
"def",
"Query",
"(",
"self",
",",
"query",
")",
":",
"cursor",
"=",
"self",
".",
"_database",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"query",
")",
"return",
"cursor"
] | Queries the database.
Args:
query (str): SQL query.
Returns:
sqlite3.Cursor: results.
Raises:
sqlite3.DatabaseError: if querying the database fails. | [
"Queries",
"the",
"database",
"."
] | python | train | 19.133333 |
pantsbuild/pants | src/python/pants/backend/jvm/tasks/classpath_util.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/classpath_util.py#L22-L47 | def compute_classpath_entries(cls, targets, classpath_products, extra_classpath_tuples, confs):
"""Return the list of classpath entries for a classpath covering the passed targets.
Filters and adds paths from extra_classpath_tuples to the end of the resulting list.
:param targets: The targets to generate ... | [
"def",
"compute_classpath_entries",
"(",
"cls",
",",
"targets",
",",
"classpath_products",
",",
"extra_classpath_tuples",
",",
"confs",
")",
":",
"classpath_iter",
"=",
"cls",
".",
"_classpath_iter",
"(",
"classpath_products",
".",
"get_classpath_entries_for_targets",
"... | Return the list of classpath entries for a classpath covering the passed targets.
Filters and adds paths from extra_classpath_tuples to the end of the resulting list.
:param targets: The targets to generate a classpath for.
:param ClasspathProducts classpath_products: Product containing classpath elements... | [
"Return",
"the",
"list",
"of",
"classpath",
"entries",
"for",
"a",
"classpath",
"covering",
"the",
"passed",
"targets",
"."
] | python | train | 44.076923 |
Kronuz/pyScss | scss/extension/compass/images.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/images.py#L258-L289 | def image_height(image):
"""
Returns the height of the image found at the path supplied by `image`
relative to your project's images directory.
"""
image_size_cache = _get_cache('image_size_cache')
if not Image:
raise SassMissingDependency('PIL', 'image manipulation')
filepath = Stri... | [
"def",
"image_height",
"(",
"image",
")",
":",
"image_size_cache",
"=",
"_get_cache",
"(",
"'image_size_cache'",
")",
"if",
"not",
"Image",
":",
"raise",
"SassMissingDependency",
"(",
"'PIL'",
",",
"'image manipulation'",
")",
"filepath",
"=",
"String",
".",
"un... | Returns the height of the image found at the path supplied by `image`
relative to your project's images directory. | [
"Returns",
"the",
"height",
"of",
"the",
"image",
"found",
"at",
"the",
"path",
"supplied",
"by",
"image",
"relative",
"to",
"your",
"project",
"s",
"images",
"directory",
"."
] | python | train | 32.6875 |
Workiva/furious | furious/async.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L625-L648 | def decode_async_options(options):
"""Decode Async options from JSON decoding."""
async_options = copy.deepcopy(options)
# JSON don't like datetimes.
eta = async_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
async_options['task_args']['eta'] = dateti... | [
"def",
"decode_async_options",
"(",
"options",
")",
":",
"async_options",
"=",
"copy",
".",
"deepcopy",
"(",
"options",
")",
"# JSON don't like datetimes.",
"eta",
"=",
"async_options",
".",
"get",
"(",
"'task_args'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'e... | Decode Async options from JSON decoding. | [
"Decode",
"Async",
"options",
"from",
"JSON",
"decoding",
"."
] | python | train | 35.458333 |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2621-L2676 | def to_clipboard(self, excel=True, sep=None, **kwargs):
r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
... | [
"def",
"to_clipboard",
"(",
"self",
",",
"excel",
"=",
"True",
",",
"sep",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pandas",
".",
"io",
"import",
"clipboards",
"clipboards",
".",
"to_clipboard",
"(",
"self",
",",
"excel",
"=",
"excel",
... | r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
- True, use the provided separator, writing in a csv format ... | [
"r",
"Copy",
"object",
"to",
"the",
"system",
"clipboard",
"."
] | python | train | 31.25 |
hydpy-dev/hydpy | hydpy/core/hydpytools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/hydpytools.py#L559-L567 | def update_devices(self, selection=None):
"""Determines the order, in which the |Node| and |Element| objects
currently handled by the |HydPy| objects need to be processed during
a simulation time step. Optionally, a |Selection| object for defining
new |Node| and |Element| objects can be... | [
"def",
"update_devices",
"(",
"self",
",",
"selection",
"=",
"None",
")",
":",
"if",
"selection",
"is",
"not",
"None",
":",
"self",
".",
"nodes",
"=",
"selection",
".",
"nodes",
"self",
".",
"elements",
"=",
"selection",
".",
"elements",
"self",
".",
"... | Determines the order, in which the |Node| and |Element| objects
currently handled by the |HydPy| objects need to be processed during
a simulation time step. Optionally, a |Selection| object for defining
new |Node| and |Element| objects can be passed. | [
"Determines",
"the",
"order",
"in",
"which",
"the",
"|Node|",
"and",
"|Element|",
"objects",
"currently",
"handled",
"by",
"the",
"|HydPy|",
"objects",
"need",
"to",
"be",
"processed",
"during",
"a",
"simulation",
"time",
"step",
".",
"Optionally",
"a",
"|Sele... | python | train | 53.333333 |
nabetama/slacky | slacky/rest/rest.py | https://github.com/nabetama/slacky/blob/dde62ce49af9b8f581729c36d2ac790310b570e4/slacky/rest/rest.py#L173-L181 | def rename(self, channel_name, new_name):
""" https://api.slack.com/methods/channels.rename
"""
channel_id = self.get_channel_id(channel_name)
self.params.update({
'channel': channel_id,
'name': new_name,
})
return FromUrl('https://slack.c... | [
"def",
"rename",
"(",
"self",
",",
"channel_name",
",",
"new_name",
")",
":",
"channel_id",
"=",
"self",
".",
"get_channel_id",
"(",
"channel_name",
")",
"self",
".",
"params",
".",
"update",
"(",
"{",
"'channel'",
":",
"channel_id",
",",
"'name'",
":",
... | https://api.slack.com/methods/channels.rename | [
"https",
":",
"//",
"api",
".",
"slack",
".",
"com",
"/",
"methods",
"/",
"channels",
".",
"rename"
] | python | train | 41.888889 |
pydata/xarray | xarray/coding/cftime_offsets.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/coding/cftime_offsets.py#L215-L226 | def _adjust_n_years(other, n, month, reference_day):
"""Adjust the number of times an annual offset is applied based on
another date, and the reference day provided"""
if n > 0:
if other.month < month or (other.month == month and
other.day < reference_day):
... | [
"def",
"_adjust_n_years",
"(",
"other",
",",
"n",
",",
"month",
",",
"reference_day",
")",
":",
"if",
"n",
">",
"0",
":",
"if",
"other",
".",
"month",
"<",
"month",
"or",
"(",
"other",
".",
"month",
"==",
"month",
"and",
"other",
".",
"day",
"<",
... | Adjust the number of times an annual offset is applied based on
another date, and the reference day provided | [
"Adjust",
"the",
"number",
"of",
"times",
"an",
"annual",
"offset",
"is",
"applied",
"based",
"on",
"another",
"date",
"and",
"the",
"reference",
"day",
"provided"
] | python | train | 40.416667 |
rushter/heamy | heamy/pipeline.py | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/pipeline.py#L104-L150 | def stack(self, k=5, stratify=False, shuffle=True, seed=100, full_test=True, add_diff=False):
"""Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : i... | [
"def",
"stack",
"(",
"self",
",",
"k",
"=",
"5",
",",
"stratify",
"=",
"False",
",",
"shuffle",
"=",
"True",
",",
"seed",
"=",
"100",
",",
"full_test",
"=",
"True",
",",
"add_diff",
"=",
"False",
")",
":",
"result_train",
"=",
"[",
"]",
"result_tes... | Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : int, default 100
full_test : bool, default True
If True then evaluate test dataset on ... | [
"Stacks",
"sequence",
"of",
"models",
"."
] | python | train | 33.638298 |
denisenkom/pytds | src/pytds/tds_types.py | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds_types.py#L2257-L2305 | def write(self, w, val):
"""
Writes remaining part of TVP_TYPE_INFO structure, resuming from TVP_COLMETADATA
specs:
https://msdn.microsoft.com/en-us/library/dd302994.aspx
https://msdn.microsoft.com/en-us/library/dd305261.aspx
https://msdn.microsoft.com/en-us/library/dd30... | [
"def",
"write",
"(",
"self",
",",
"w",
",",
"val",
")",
":",
"if",
"val",
".",
"is_null",
"(",
")",
":",
"w",
".",
"put_usmallint",
"(",
"tds_base",
".",
"TVP_NULL_TOKEN",
")",
"else",
":",
"columns",
"=",
"self",
".",
"_table_type",
".",
"columns",
... | Writes remaining part of TVP_TYPE_INFO structure, resuming from TVP_COLMETADATA
specs:
https://msdn.microsoft.com/en-us/library/dd302994.aspx
https://msdn.microsoft.com/en-us/library/dd305261.aspx
https://msdn.microsoft.com/en-us/library/dd303230.aspx
@param w: TdsWriter
... | [
"Writes",
"remaining",
"part",
"of",
"TVP_TYPE_INFO",
"structure",
"resuming",
"from",
"TVP_COLMETADATA"
] | python | train | 36.632653 |
juju/charm-helpers | charmhelpers/contrib/peerstorage/__init__.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L60-L122 | def leader_get(attribute=None, rid=None):
"""Wrapper to ensure that settings are migrated from the peer relation.
This is to support upgrading an environment that does not support
Juju leadership election to one that does.
If a setting is not extant in the leader-get but is on the relation-get
pee... | [
"def",
"leader_get",
"(",
"attribute",
"=",
"None",
",",
"rid",
"=",
"None",
")",
":",
"migration_key",
"=",
"'__leader_get_migrated_settings__'",
"if",
"not",
"is_leader",
"(",
")",
":",
"return",
"_leader_get",
"(",
"attribute",
"=",
"attribute",
")",
"setti... | Wrapper to ensure that settings are migrated from the peer relation.
This is to support upgrading an environment that does not support
Juju leadership election to one that does.
If a setting is not extant in the leader-get but is on the relation-get
peer rel, it is migrated and marked as such so that ... | [
"Wrapper",
"to",
"ensure",
"that",
"settings",
"are",
"migrated",
"from",
"the",
"peer",
"relation",
"."
] | python | train | 33.68254 |
Ceasar/twosheds | twosheds/terminal.py | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/terminal.py#L50-L58 | def readlines(self):
"""Read a command from the terminal.
Returns a list of tokens containing the user's input.
"""
continuation = False
while True:
yield self.readline(continuation)
continuation = True | [
"def",
"readlines",
"(",
"self",
")",
":",
"continuation",
"=",
"False",
"while",
"True",
":",
"yield",
"self",
".",
"readline",
"(",
"continuation",
")",
"continuation",
"=",
"True"
] | Read a command from the terminal.
Returns a list of tokens containing the user's input. | [
"Read",
"a",
"command",
"from",
"the",
"terminal",
"."
] | python | train | 28.777778 |
stephantul/somber | somber/plsom.py | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/plsom.py#L149-L169 | def _calculate_influence(self, neighborhood):
"""
Pre-calculate the influence for a given value of sigma.
The neighborhood has size num_neurons * num_neurons, so for a
30 * 30 map, the neighborhood will be size (900, 900).
Parameters
----------
neighborhood : fl... | [
"def",
"_calculate_influence",
"(",
"self",
",",
"neighborhood",
")",
":",
"n",
"=",
"(",
"self",
".",
"beta",
"-",
"1",
")",
"*",
"np",
".",
"log",
"(",
"1",
"+",
"neighborhood",
"*",
"(",
"np",
".",
"e",
"-",
"1",
")",
")",
"+",
"1",
"grid",
... | Pre-calculate the influence for a given value of sigma.
The neighborhood has size num_neurons * num_neurons, so for a
30 * 30 map, the neighborhood will be size (900, 900).
Parameters
----------
neighborhood : float
The neighborhood value.
Returns
-... | [
"Pre",
"-",
"calculate",
"the",
"influence",
"for",
"a",
"given",
"value",
"of",
"sigma",
"."
] | python | train | 32.428571 |
ladybug-tools/ladybug | ladybug/epw.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L504-L663 | def _import_data(self, import_header_only=False):
"""Import data from an epw file.
Hourly data will be saved in self.data and the various header data
will be saved in the properties above.
"""
# perform checks on the file before opening it.
assert os.path.isfile(self._fi... | [
"def",
"_import_data",
"(",
"self",
",",
"import_header_only",
"=",
"False",
")",
":",
"# perform checks on the file before opening it.",
"assert",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"_file_path",
")",
",",
"'Cannot find an epw file at {}'",
".",
"f... | Import data from an epw file.
Hourly data will be saved in self.data and the various header data
will be saved in the properties above. | [
"Import",
"data",
"from",
"an",
"epw",
"file",
"."
] | python | train | 50.16875 |
tgbugs/pyontutils | pyontutils/obo_io.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/obo_io.py#L105-L120 | def id_fix(value):
""" fix @prefix values for ttl """
if value.startswith('KSC_M'):
pass
else:
value = value.replace(':','_')
if value.startswith('ERO') or value.startswith('OBI') or value.startswith('GO') or value.startswith('UBERON') or value.startswith('IAO'):
value = ... | [
"def",
"id_fix",
"(",
"value",
")",
":",
"if",
"value",
".",
"startswith",
"(",
"'KSC_M'",
")",
":",
"pass",
"else",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"':'",
",",
"'_'",
")",
"if",
"value",
".",
"startswith",
"(",
"'ERO'",
")",
"or",... | fix @prefix values for ttl | [
"fix"
] | python | train | 36.875 |
saltstack/salt | salt/modules/dnsutil.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L274-L298 | def AAAA(host, nameserver=None):
'''
Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com
'''
if _has_dig():
return __salt__['dig.AAAA'](host, nameserver)
... | [
"def",
"AAAA",
"(",
"host",
",",
"nameserver",
"=",
"None",
")",
":",
"if",
"_has_dig",
"(",
")",
":",
"return",
"__salt__",
"[",
"'dig.AAAA'",
"]",
"(",
"host",
",",
"nameserver",
")",
"elif",
"nameserver",
"is",
"None",
":",
"# fall back to the socket in... | Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com | [
"Return",
"the",
"AAAA",
"record",
"(",
"s",
")",
"for",
"host",
"."
] | python | train | 28.68 |
rodluger/everest | everest/user.py | https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/user.py#L1319-L1330 | def optimize(self, piter=3, pmaxf=300, ppert=0.1):
'''
Runs :py:obj:`pPLD` on the target in an attempt to further optimize the
values of the PLD priors. See :py:class:`everest.detrender.pPLD`.
'''
self._save_npz()
optimized = pPLD(self.ID, piter=piter, pmaxf=pmaxf,
... | [
"def",
"optimize",
"(",
"self",
",",
"piter",
"=",
"3",
",",
"pmaxf",
"=",
"300",
",",
"ppert",
"=",
"0.1",
")",
":",
"self",
".",
"_save_npz",
"(",
")",
"optimized",
"=",
"pPLD",
"(",
"self",
".",
"ID",
",",
"piter",
"=",
"piter",
",",
"pmaxf",
... | Runs :py:obj:`pPLD` on the target in an attempt to further optimize the
values of the PLD priors. See :py:class:`everest.detrender.pPLD`. | [
"Runs",
":",
"py",
":",
"obj",
":",
"pPLD",
"on",
"the",
"target",
"in",
"an",
"attempt",
"to",
"further",
"optimize",
"the",
"values",
"of",
"the",
"PLD",
"priors",
".",
"See",
":",
"py",
":",
"class",
":",
"everest",
".",
"detrender",
".",
"pPLD",
... | python | train | 34.75 |
saltstack/salt | salt/modules/boto_kms.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L340-L364 | def generate_data_key(key_id, encryption_context=None, number_of_bytes=None,
key_spec=None, grant_tokens=None, region=None, key=None,
keyid=None, profile=None):
'''
Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias... | [
"def",
"generate_data_key",
"(",
"key_id",
",",
"encryption_context",
"=",
"None",
",",
"number_of_bytes",
"=",
"None",
",",
"key_spec",
"=",
"None",
",",
"grant_tokens",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
... | Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 | [
"Generate",
"a",
"secure",
"data",
"key",
"."
] | python | train | 33.16 |
androguard/androguard | androguard/core/bytecodes/apk.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/apk.py#L1127-L1159 | def get_intent_filters(self, itemtype, name):
"""
Find intent filters for a given item and name.
Intent filter are attached to activities, services or receivers.
You can search for the intent filters of such items and get a dictionary of all
attached actions and intent categorie... | [
"def",
"get_intent_filters",
"(",
"self",
",",
"itemtype",
",",
"name",
")",
":",
"d",
"=",
"{",
"\"action\"",
":",
"[",
"]",
",",
"\"category\"",
":",
"[",
"]",
"}",
"for",
"i",
"in",
"self",
".",
"xml",
":",
"# TODO: this can probably be solved using a s... | Find intent filters for a given item and name.
Intent filter are attached to activities, services or receivers.
You can search for the intent filters of such items and get a dictionary of all
attached actions and intent categories.
:param itemtype: the type of parent item to look for, ... | [
"Find",
"intent",
"filters",
"for",
"a",
"given",
"item",
"and",
"name",
"."
] | python | train | 46.515152 |
boriel/zxbasic | basic.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/basic.py#L143-L158 | def sentence_bytes(self, sentence):
""" Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token.
"""
result = [TOKENS[sentence[0]]]
for i in sentence[1:]: # Remaining bytes
... | [
"def",
"sentence_bytes",
"(",
"self",
",",
"sentence",
")",
":",
"result",
"=",
"[",
"TOKENS",
"[",
"sentence",
"[",
"0",
"]",
"]",
"]",
"for",
"i",
"in",
"sentence",
"[",
"1",
":",
"]",
":",
"# Remaining bytes",
"if",
"isinstance",
"(",
"i",
",",
... | Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token. | [
"Return",
"bytes",
"of",
"a",
"sentence",
".",
"This",
"is",
"a",
"very",
"simple",
"parser",
".",
"Sentence",
"is",
"a",
"list",
"of",
"strings",
"and",
"numbers",
".",
"1st",
"element",
"of",
"sentence",
"MUST",
"match",
"a",
"token",
"."
] | python | train | 37.25 |
NuGrid/NuGridPy | scripts/nugrid_set/nugrid_set.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/scripts/nugrid_set/nugrid_set.py#L1169-L1208 | def set_plot_CO_mass(self,fig=3123,xaxis='mass',linestyle=['-'],marker=['o'],color=['r'],age_years=True,sparsity=500,markersparsity=200,withoutZlabel=False,t0_model=[]):
'''
PLots C/O surface number fraction
'''
if len(t0_model)==0:
t0_model = len(self.runs_H5_surf)*[0]
plt.figure(fig)
... | [
"def",
"set_plot_CO_mass",
"(",
"self",
",",
"fig",
"=",
"3123",
",",
"xaxis",
"=",
"'mass'",
",",
"linestyle",
"=",
"[",
"'-'",
"]",
",",
"marker",
"=",
"[",
"'o'",
"]",
",",
"color",
"=",
"[",
"'r'",
"]",
",",
"age_years",
"=",
"True",
",",
"sp... | PLots C/O surface number fraction | [
"PLots",
"C",
"/",
"O",
"surface",
"number",
"fraction"
] | python | train | 38.325 |
annoviko/pyclustering | pyclustering/cluster/agglomerative.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/agglomerative.py#L329-L347 | def __calculate_nearest_distance(self, index_cluster1, index_cluster2):
"""!
@brief Finds two nearest objects in two specified clusters and returns distance between them.
@param[in] (uint) Index of the first cluster.
@param[in] (uint) Index of the second cluster.
... | [
"def",
"__calculate_nearest_distance",
"(",
"self",
",",
"index_cluster1",
",",
"index_cluster2",
")",
":",
"candidate_minimum_distance",
"=",
"float",
"(",
"'Inf'",
")",
"for",
"index_object1",
"in",
"self",
".",
"__clusters",
"[",
"index_cluster1",
"]",
":",
"fo... | !
@brief Finds two nearest objects in two specified clusters and returns distance between them.
@param[in] (uint) Index of the first cluster.
@param[in] (uint) Index of the second cluster.
@return The nearest euclidean distance between two clusters. | [
"!"
] | python | valid | 45.789474 |
taskcluster/taskcluster-client.py | taskcluster/utils.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/utils.py#L314-L319 | def isExpired(certificate):
""" Check if certificate is expired """
if isinstance(certificate, six.string_types):
certificate = json.loads(certificate)
expiry = certificate.get('expiry', 0)
return expiry < int(time.time() * 1000) + 20 * 60 | [
"def",
"isExpired",
"(",
"certificate",
")",
":",
"if",
"isinstance",
"(",
"certificate",
",",
"six",
".",
"string_types",
")",
":",
"certificate",
"=",
"json",
".",
"loads",
"(",
"certificate",
")",
"expiry",
"=",
"certificate",
".",
"get",
"(",
"'expiry'... | Check if certificate is expired | [
"Check",
"if",
"certificate",
"is",
"expired"
] | python | train | 43 |
JasonKessler/scattertext | scattertext/PriorFactory.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/PriorFactory.py#L77-L88 | def use_custom_term_frequencies(self, custom_term_frequencies):
'''
Parameters
----------
pd.Series
term -> frequency
Returns
-------
PriorFactory
'''
self.priors += custom_term_frequencies.reindex(self.priors.index).fillna(0)
return self | [
"def",
"use_custom_term_frequencies",
"(",
"self",
",",
"custom_term_frequencies",
")",
":",
"self",
".",
"priors",
"+=",
"custom_term_frequencies",
".",
"reindex",
"(",
"self",
".",
"priors",
".",
"index",
")",
".",
"fillna",
"(",
"0",
")",
"return",
"self"
] | Parameters
----------
pd.Series
term -> frequency
Returns
-------
PriorFactory | [
"Parameters",
"----------",
"pd",
".",
"Series",
"term",
"-",
">",
"frequency",
"Returns",
"-------",
"PriorFactory"
] | python | train | 20.75 |
log2timeline/plaso | plaso/cli/pinfo_tool.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/pinfo_tool.py#L125-L141 | def _CompareStores(self, storage_reader, compare_storage_reader):
"""Compares the contents of two stores.
Args:
storage_reader (StorageReader): storage reader.
compare_storage_reader (StorageReader): storage to compare against.
Returns:
bool: True if the content of the stores is identica... | [
"def",
"_CompareStores",
"(",
"self",
",",
"storage_reader",
",",
"compare_storage_reader",
")",
":",
"storage_counters",
"=",
"self",
".",
"_CalculateStorageCounters",
"(",
"storage_reader",
")",
"compare_storage_counters",
"=",
"self",
".",
"_CalculateStorageCounters",
... | Compares the contents of two stores.
Args:
storage_reader (StorageReader): storage reader.
compare_storage_reader (StorageReader): storage to compare against.
Returns:
bool: True if the content of the stores is identical. | [
"Compares",
"the",
"contents",
"of",
"two",
"stores",
"."
] | python | train | 36 |
edx/edx-enterprise | enterprise/signals.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/signals.py#L92-L101 | def assign_enterprise_learner_role(sender, instance, **kwargs): # pylint: disable=unused-argument
"""
Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created.
"""
if kwargs['created'] and instance.user:
enterprise_learner_role, __ = SystemWideEnterpriseRo... | [
"def",
"assign_enterprise_learner_role",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"if",
"kwargs",
"[",
"'created'",
"]",
"and",
"instance",
".",
"user",
":",
"enterprise_learner_role",
",",
"__",
"=",
... | Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created. | [
"Assign",
"an",
"enterprise",
"learner",
"role",
"to",
"EnterpriseCustomerUser",
"whenever",
"a",
"new",
"record",
"is",
"created",
"."
] | python | valid | 51.8 |
zabertech/python-izaber | izaber/date.py | https://github.com/zabertech/python-izaber/blob/729bf9ef637e084c8ab3cc16c34cf659d3a79ee4/izaber/date.py#L340-L348 | def daily_hours(self,local=False):
""" This returns a number from 0 to 24 that describes the number
of hours passed in a day. This is very useful for hr.attendances
"""
data = self.get(local)
daily_hours = (data.hour +
data.minute / 60.0 +
... | [
"def",
"daily_hours",
"(",
"self",
",",
"local",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"get",
"(",
"local",
")",
"daily_hours",
"=",
"(",
"data",
".",
"hour",
"+",
"data",
".",
"minute",
"/",
"60.0",
"+",
"data",
".",
"second",
"/",
"... | This returns a number from 0 to 24 that describes the number
of hours passed in a day. This is very useful for hr.attendances | [
"This",
"returns",
"a",
"number",
"from",
"0",
"to",
"24",
"that",
"describes",
"the",
"number",
"of",
"hours",
"passed",
"in",
"a",
"day",
".",
"This",
"is",
"very",
"useful",
"for",
"hr",
".",
"attendances"
] | python | train | 42.111111 |
saltstack/salt | salt/modules/augeas_cfg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/augeas_cfg.py#L75-L91 | def _recurmatch(path, aug):
'''
Recursive generator providing the infrastructure for
augtools print behavior.
This function is based on test_augeas.py from
Harald Hoyer <harald@redhat.com> in the python-augeas
repository
'''
if path:
clean_path = path.rstrip('/*')
yield... | [
"def",
"_recurmatch",
"(",
"path",
",",
"aug",
")",
":",
"if",
"path",
":",
"clean_path",
"=",
"path",
".",
"rstrip",
"(",
"'/*'",
")",
"yield",
"(",
"clean_path",
",",
"aug",
".",
"get",
"(",
"path",
")",
")",
"for",
"i",
"in",
"aug",
".",
"matc... | Recursive generator providing the infrastructure for
augtools print behavior.
This function is based on test_augeas.py from
Harald Hoyer <harald@redhat.com> in the python-augeas
repository | [
"Recursive",
"generator",
"providing",
"the",
"infrastructure",
"for",
"augtools",
"print",
"behavior",
"."
] | python | train | 30.235294 |
PyconUK/ConferenceScheduler | src/conference_scheduler/scheduler.py | https://github.com/PyconUK/ConferenceScheduler/blob/fb139f0ef2eab5ac8f4919aa4994d94d4e040030/src/conference_scheduler/scheduler.py#L200-L224 | def schedule(events, slots, objective_function=None, solver=None, **kwargs):
"""Compute a schedule in schedule form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.s... | [
"def",
"schedule",
"(",
"events",
",",
"slots",
",",
"objective_function",
"=",
"None",
",",
"solver",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"conv",
".",
"solution_to_schedule",
"(",
"solution",
"(",
"events",
",",
"slots",
",",
"obje... | Compute a schedule in schedule form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.solver
a pulp solver
objective_function : callable
from lp_proble... | [
"Compute",
"a",
"schedule",
"in",
"schedule",
"form"
] | python | train | 29.2 |
F-Secure/see | see/context/resources/qemu.py | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/qemu.py#L360-L384 | def allocate(self):
"""Initializes libvirt resources."""
network_name = None
self._hypervisor = libvirt.open(
self.configuration.get('hypervisor', 'qemu:///system'))
self._storage_pool = self._retrieve_pool()
if 'network' in self.configuration:
self._ne... | [
"def",
"allocate",
"(",
"self",
")",
":",
"network_name",
"=",
"None",
"self",
".",
"_hypervisor",
"=",
"libvirt",
".",
"open",
"(",
"self",
".",
"configuration",
".",
"get",
"(",
"'hypervisor'",
",",
"'qemu:///system'",
")",
")",
"self",
".",
"_storage_po... | Initializes libvirt resources. | [
"Initializes",
"libvirt",
"resources",
"."
] | python | train | 36.6 |
mozilla-iot/webthing-python | webthing/server.py | https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/server.py#L767-L782 | def start(self):
"""Start listening for incoming connections."""
self.service_info = ServiceInfo(
'_webthing._tcp.local.',
'{}._webthing._tcp.local.'.format(self.name),
address=socket.inet_aton(get_ip()),
port=self.port,
properties={
... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"service_info",
"=",
"ServiceInfo",
"(",
"'_webthing._tcp.local.'",
",",
"'{}._webthing._tcp.local.'",
".",
"format",
"(",
"self",
".",
"name",
")",
",",
"address",
"=",
"socket",
".",
"inet_aton",
"(",
"ge... | Start listening for incoming connections. | [
"Start",
"listening",
"for",
"incoming",
"connections",
"."
] | python | test | 36.1875 |
harlowja/failure | failure/failure.py | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L584-L620 | def _extract_cause(cls, exc_val):
"""Helper routine to extract nested cause (if any)."""
# See: https://www.python.org/dev/peps/pep-3134/ for why/what
# these are...
#
# '__cause__' attribute for explicitly chained exceptions
# '__context__' attribute for implicitly chain... | [
"def",
"_extract_cause",
"(",
"cls",
",",
"exc_val",
")",
":",
"# See: https://www.python.org/dev/peps/pep-3134/ for why/what",
"# these are...",
"#",
"# '__cause__' attribute for explicitly chained exceptions",
"# '__context__' attribute for implicitly chained exceptions",
"# '__traceback... | Helper routine to extract nested cause (if any). | [
"Helper",
"routine",
"to",
"extract",
"nested",
"cause",
"(",
"if",
"any",
")",
"."
] | python | train | 41.054054 |
JarryShaw/PyPCAPKit | src/const/ospf/authentication.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ospf/authentication.py#L18-L24 | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Authentication(key)
if key not in Authentication._member_map_:
extend_enum(Authentication, key, default)
return Authentication[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"Authentication",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"Authentication",
".",
"_member_map_",
":",
"extend_enum",
... | Backport support for original codes. | [
"Backport",
"support",
"for",
"original",
"codes",
"."
] | python | train | 40.285714 |
72squared/redpipe | redpipe/pipelines.py | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/pipelines.py#L321-L344 | def execute(self):
"""
execute the commands inside the nested pipeline.
This causes all queued up commands to be passed upstream to the
parent, including callbacks.
The state of this pipeline object gets cleaned up.
:return:
"""
stack = self._stack
... | [
"def",
"execute",
"(",
"self",
")",
":",
"stack",
"=",
"self",
".",
"_stack",
"callbacks",
"=",
"self",
".",
"_callbacks",
"self",
".",
"_stack",
"=",
"[",
"]",
"self",
".",
"_callbacks",
"=",
"[",
"]",
"deferred",
"=",
"[",
"]",
"build",
"=",
"sel... | execute the commands inside the nested pipeline.
This causes all queued up commands to be passed upstream to the
parent, including callbacks.
The state of this pipeline object gets cleaned up.
:return: | [
"execute",
"the",
"commands",
"inside",
"the",
"nested",
"pipeline",
".",
"This",
"causes",
"all",
"queued",
"up",
"commands",
"to",
"be",
"passed",
"upstream",
"to",
"the",
"parent",
"including",
"callbacks",
".",
"The",
"state",
"of",
"this",
"pipeline",
"... | python | train | 31.291667 |
cokelaer/spectrum | src/spectrum/datasets.py | https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/datasets.py#L101-L121 | def data_cosine(N=1024, A=0.1, sampling=1024., freq=200):
r"""Return a noisy cosine at a given frequency.
:param N: the final data size
:param A: the strength of the noise
:param float sampling: sampling frequency of the input :attr:`data`.
:param float freq: the frequency :mat... | [
"def",
"data_cosine",
"(",
"N",
"=",
"1024",
",",
"A",
"=",
"0.1",
",",
"sampling",
"=",
"1024.",
",",
"freq",
"=",
"200",
")",
":",
"t",
"=",
"arange",
"(",
"0",
",",
"float",
"(",
"N",
")",
"/",
"sampling",
",",
"1.",
"/",
"sampling",
")",
... | r"""Return a noisy cosine at a given frequency.
:param N: the final data size
:param A: the strength of the noise
:param float sampling: sampling frequency of the input :attr:`data`.
:param float freq: the frequency :math:`f_0` of the cosine.
.. math:: x[t] = cos(2\pi t * f_0)... | [
"r",
"Return",
"a",
"noisy",
"cosine",
"at",
"a",
"given",
"frequency",
"."
] | python | valid | 31.857143 |
phaethon/kamene | kamene/contrib/igmp.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/igmp.py#L78-L107 | def igmpize(self, ip=None, ether=None):
"""Called to explicitely fixup associated IP and Ethernet headers
Parameters:
self The instantiation of an IGMP class.
ip The instantiation of the associated IP class.
ether The instantiation of the associated Ethernet.
Returns:
Tru... | [
"def",
"igmpize",
"(",
"self",
",",
"ip",
"=",
"None",
",",
"ether",
"=",
"None",
")",
":",
"# The rules are:",
"# 1. the Max Response time is meaningful only in Membership Queries and should be zero ",
"# otherwise (RFC 2236, section 2.2)",
"if",
"(",
"self",
".",
... | Called to explicitely fixup associated IP and Ethernet headers
Parameters:
self The instantiation of an IGMP class.
ip The instantiation of the associated IP class.
ether The instantiation of the associated Ethernet.
Returns:
True The tuple ether/ip/self passed all check a... | [
"Called",
"to",
"explicitely",
"fixup",
"associated",
"IP",
"and",
"Ethernet",
"headers"
] | python | train | 37.266667 |
dalloriam/engel | engel/widgets/abstract.py | https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/abstract.py#L30-L38 | def build(self, link_type, path):
super(HeadLink, self).build()
"""
:param link_type: Link type
:param target: Link target
"""
self.target = path
self.link_type = link_type
self.autoclosing = True | [
"def",
"build",
"(",
"self",
",",
"link_type",
",",
"path",
")",
":",
"super",
"(",
"HeadLink",
",",
"self",
")",
".",
"build",
"(",
")",
"self",
".",
"target",
"=",
"path",
"self",
".",
"link_type",
"=",
"link_type",
"self",
".",
"autoclosing",
"=",... | :param link_type: Link type
:param target: Link target | [
":",
"param",
"link_type",
":",
"Link",
"type",
":",
"param",
"target",
":",
"Link",
"target"
] | python | train | 26.666667 |
Wessie/hurler | hurler/filters.py | https://github.com/Wessie/hurler/blob/5719000237e24df9f24fb8229f1153ebfa684972/hurler/filters.py#L75-L104 | def filter(filter_creator):
"""
Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution.
"""
filter_func = [None]
def fun... | [
"def",
"filter",
"(",
"filter_creator",
")",
":",
"filter_func",
"=",
"[",
"None",
"]",
"def",
"function_getter",
"(",
"function",
")",
":",
"if",
"isinstance",
"(",
"function",
",",
"Filter",
")",
":",
"function",
".",
"add_filter",
"(",
"filter",
")",
... | Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution. | [
"Creates",
"a",
"decorator",
"that",
"can",
"be",
"used",
"as",
"a",
"filter",
"."
] | python | train | 25.266667 |
openstack/horizon | horizon/base.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L842-L851 | def _lazy_urls(self):
"""Lazy loading for URL patterns.
This method avoids problems associated with attempting to evaluate
the URLconf before the settings module has been loaded.
"""
def url_patterns():
return self._urls()[0]
return LazyURLPattern(url_patter... | [
"def",
"_lazy_urls",
"(",
"self",
")",
":",
"def",
"url_patterns",
"(",
")",
":",
"return",
"self",
".",
"_urls",
"(",
")",
"[",
"0",
"]",
"return",
"LazyURLPattern",
"(",
"url_patterns",
")",
",",
"self",
".",
"namespace",
",",
"self",
".",
"slug"
] | Lazy loading for URL patterns.
This method avoids problems associated with attempting to evaluate
the URLconf before the settings module has been loaded. | [
"Lazy",
"loading",
"for",
"URL",
"patterns",
"."
] | python | train | 34.1 |
saltstack/salt | salt/modules/zpool.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zpool.py#L445-L523 | def get(zpool, prop=None, show_source=False, parsable=True):
'''
.. versionadded:: 2016.3.0
Retrieves the given list of properties
zpool : string
Name of storage pool
prop : string
Optional name of property to retrieve
show_source : boolean
Show source of property
... | [
"def",
"get",
"(",
"zpool",
",",
"prop",
"=",
"None",
",",
"show_source",
"=",
"False",
",",
"parsable",
"=",
"True",
")",
":",
"ret",
"=",
"OrderedDict",
"(",
")",
"value_properties",
"=",
"[",
"'name'",
",",
"'property'",
",",
"'value'",
",",
"'sourc... | .. versionadded:: 2016.3.0
Retrieves the given list of properties
zpool : string
Name of storage pool
prop : string
Optional name of property to retrieve
show_source : boolean
Show source of property
parsable : boolean
Display numbers in parsable (exact) values
... | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | python | train | 27.860759 |
pantsbuild/pants | src/python/pants/task/task.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/task/task.py#L581-L616 | def do_check_artifact_cache(self, vts, post_process_cached_vts=None):
"""Checks the artifact cache for the specified list of VersionedTargetSets.
Returns a tuple (cached, uncached, uncached_causes) of VersionedTargets that were
satisfied/unsatisfied from the cache.
"""
if not vts:
return [], ... | [
"def",
"do_check_artifact_cache",
"(",
"self",
",",
"vts",
",",
"post_process_cached_vts",
"=",
"None",
")",
":",
"if",
"not",
"vts",
":",
"return",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"read_cache",
"=",
"self",
".",
"_cache_factory",
".",
"get_read_... | Checks the artifact cache for the specified list of VersionedTargetSets.
Returns a tuple (cached, uncached, uncached_causes) of VersionedTargets that were
satisfied/unsatisfied from the cache. | [
"Checks",
"the",
"artifact",
"cache",
"for",
"the",
"specified",
"list",
"of",
"VersionedTargetSets",
"."
] | python | train | 41 |
rochacbruno/flask_simplelogin | flask_simplelogin/__init__.py | https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/flask_simplelogin/__init__.py#L65-L125 | def login_required(function=None, username=None, basic=False, must=None):
"""Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_func... | [
"def",
"login_required",
"(",
"function",
"=",
"None",
",",
"username",
"=",
"None",
",",
"basic",
"=",
"False",
",",
"must",
"=",
"None",
")",
":",
"if",
"function",
"and",
"not",
"callable",
"(",
"function",
")",
":",
"raise",
"ValueError",
"(",
"'De... | Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function]) | [
"Decorate",
"views",
"to",
"require",
"login"
] | python | train | 35.311475 |
fboender/ansible-cmdb | lib/mako/cache.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/cache.py#L114-L124 | def get(self, key, **kw):
"""Retrieve a value from the cache.
:param key: the value's key.
:param \**kw: cache configuration arguments. The
backend is configured using these arguments upon first request.
Subsequent requests that use the same series of configuration
v... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"impl",
".",
"get",
"(",
"key",
",",
"*",
"*",
"self",
".",
"_get_cache_kw",
"(",
"kw",
",",
"None",
")",
")"
] | Retrieve a value from the cache.
:param key: the value's key.
:param \**kw: cache configuration arguments. The
backend is configured using these arguments upon first request.
Subsequent requests that use the same series of configuration
values will use that same backend. | [
"Retrieve",
"a",
"value",
"from",
"the",
"cache",
"."
] | python | train | 38.363636 |
CamDavidsonPilon/lifelines | lifelines/fitters/__init__.py | https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/__init__.py#L1215-L1325 | def fit(
self,
df,
duration_col,
event_col=None,
ancillary_df=None,
show_progress=False,
timeline=None,
weights_col=None,
robust=False,
initial_point=None,
entry_col=None,
):
"""
Fit the accelerated failure time ... | [
"def",
"fit",
"(",
"self",
",",
"df",
",",
"duration_col",
",",
"event_col",
"=",
"None",
",",
"ancillary_df",
"=",
"None",
",",
"show_progress",
"=",
"False",
",",
"timeline",
"=",
"None",
",",
"weights_col",
"=",
"None",
",",
"robust",
"=",
"False",
... | Fit the accelerated failure time model to a right-censored dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col` (see below), covariates columns, and special columns (weights).
`duration_col` ref... | [
"Fit",
"the",
"accelerated",
"failure",
"time",
"model",
"to",
"a",
"right",
"-",
"censored",
"dataset",
"."
] | python | train | 36.162162 |
log2timeline/plaso | plaso/parsers/selinux.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/selinux.py#L109-L167 | def ParseRecord(self, parser_mediator, key, structure):
"""Parses a structure of tokens derived from a line of a text file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the parsed structur... | [
"def",
"ParseRecord",
"(",
"self",
",",
"parser_mediator",
",",
"key",
",",
"structure",
")",
":",
"if",
"key",
"!=",
"'line'",
":",
"raise",
"errors",
".",
"ParseError",
"(",
"'Unable to parse record, unknown structure: {0:s}'",
".",
"format",
"(",
"key",
")",
... | Parses a structure of tokens derived from a line of a text file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the parsed structure.
structure (pyparsing.ParseResults): structure of token... | [
"Parses",
"a",
"structure",
"of",
"tokens",
"derived",
"from",
"a",
"line",
"of",
"a",
"text",
"file",
"."
] | python | train | 34.067797 |
qubole/qds-sdk-py | qds_sdk/cluster.py | https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/cluster.py#L733-L740 | def remove_node(cls, cluster_id_label, private_dns, parameters=None):
"""
Add a node to an existing cluster
"""
conn = Qubole.agent(version=Cluster.api_version)
parameters = {} if not parameters else parameters
data = {"private_dns" : private_dns, "parameters" : parameter... | [
"def",
"remove_node",
"(",
"cls",
",",
"cluster_id_label",
",",
"private_dns",
",",
"parameters",
"=",
"None",
")",
":",
"conn",
"=",
"Qubole",
".",
"agent",
"(",
"version",
"=",
"Cluster",
".",
"api_version",
")",
"parameters",
"=",
"{",
"}",
"if",
"not... | Add a node to an existing cluster | [
"Add",
"a",
"node",
"to",
"an",
"existing",
"cluster"
] | python | train | 49.375 |
spyder-ide/spyder | spyder/plugins/editor/widgets/editor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L76-L81 | def run(self):
"""Run analysis"""
try:
self.results = self.checker(self.source_code)
except Exception as e:
logger.error(e, exc_info=True) | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"results",
"=",
"self",
".",
"checker",
"(",
"self",
".",
"source_code",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"e",
",",
"exc_info",
"=",
"True",
")"
] | Run analysis | [
"Run",
"analysis"
] | python | train | 31 |
marcinmiklitz/pywindow | pywindow/utilities.py | https://github.com/marcinmiklitz/pywindow/blob/e5264812157224f22a691741ca2e0aefdc9bd2eb/pywindow/utilities.py#L1895-L1956 | def calculate_pore_shape(elements, coordinates, adjust=1, increment=0.1,
**kwargs):
"""Return average diameter for a molecule."""
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at orig... | [
"def",
"calculate_pore_shape",
"(",
"elements",
",",
"coordinates",
",",
"adjust",
"=",
"1",
",",
"increment",
"=",
"0.1",
",",
"*",
"*",
"kwargs",
")",
":",
"# Copy the coordinates as will perform many opertaions on them",
"coordinates",
"=",
"deepcopy",
"(",
"coor... | Return average diameter for a molecule. | [
"Return",
"average",
"diameter",
"for",
"a",
"molecule",
"."
] | python | train | 53.435484 |
praekeltfoundation/seaworthy | seaworthy/containers/rabbitmq.py | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/rabbitmq.py#L87-L98 | def exec_rabbitmqctl(self, command, args=[], rabbitmqctl_opts=['-q']):
"""
Execute a ``rabbitmqctl`` command inside a running container.
:param command: the command to run
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to... | [
"def",
"exec_rabbitmqctl",
"(",
"self",
",",
"command",
",",
"args",
"=",
"[",
"]",
",",
"rabbitmqctl_opts",
"=",
"[",
"'-q'",
"]",
")",
":",
"cmd",
"=",
"[",
"'rabbitmqctl'",
"]",
"+",
"rabbitmqctl_opts",
"+",
"[",
"command",
"]",
"+",
"args",
"return... | Execute a ``rabbitmqctl`` command inside a running container.
:param command: the command to run
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to pass to ``rabbitmqctl``
:returns: a tuple of the command exit code and output | [
"Execute",
"a",
"rabbitmqctl",
"command",
"inside",
"a",
"running",
"container",
"."
] | python | train | 43.083333 |
dwavesystems/dwave-system | dwave/embedding/diagnostic.py | https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/embedding/diagnostic.py#L23-L96 | def diagnose_embedding(emb, source, target):
"""A detailed diagnostic for minor embeddings.
This diagnostic produces a generator, which lists all issues with `emb`. The errors
are yielded in the form
ExceptionClass, arg1, arg2,...
where the arguments following the class are used to construct ... | [
"def",
"diagnose_embedding",
"(",
"emb",
",",
"source",
",",
"target",
")",
":",
"if",
"not",
"hasattr",
"(",
"source",
",",
"'edges'",
")",
":",
"source",
"=",
"nx",
".",
"Graph",
"(",
"source",
")",
"if",
"not",
"hasattr",
"(",
"target",
",",
"'edg... | A detailed diagnostic for minor embeddings.
This diagnostic produces a generator, which lists all issues with `emb`. The errors
are yielded in the form
ExceptionClass, arg1, arg2,...
where the arguments following the class are used to construct the exception object.
User-friendly variants of ... | [
"A",
"detailed",
"diagnostic",
"for",
"minor",
"embeddings",
"."
] | python | train | 37.175676 |
saltstack/salt | salt/modules/cimc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L749-L817 | def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an ... | [
"def",
"set_power_configuration",
"(",
"policy",
"=",
"None",
",",
"delayType",
"=",
"None",
",",
"delayValue",
"=",
"None",
")",
":",
"query",
"=",
"\"\"",
"if",
"policy",
"==",
"\"reset\"",
":",
"query",
"=",
"' vpResumeOnACPowerLoss=\"reset\"'",
"if",
"dela... | Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server... | [
"Sets",
"the",
"power",
"configuration",
"on",
"the",
"device",
".",
"This",
"is",
"only",
"available",
"for",
"some",
"C",
"-",
"Series",
"servers",
"."
] | python | train | 36.014493 |
saltstack/salt | salt/modules/purefa.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/purefa.py#L197-L204 | def _get_host(name, array):
'''Private function to check host'''
host = None
for temp in array.list_hosts():
if temp['name'] == name:
host = temp
break
return host | [
"def",
"_get_host",
"(",
"name",
",",
"array",
")",
":",
"host",
"=",
"None",
"for",
"temp",
"in",
"array",
".",
"list_hosts",
"(",
")",
":",
"if",
"temp",
"[",
"'name'",
"]",
"==",
"name",
":",
"host",
"=",
"temp",
"break",
"return",
"host"
] | Private function to check host | [
"Private",
"function",
"to",
"check",
"host"
] | python | train | 25.5 |
m32/endesive | endesive/pdf/fpdf/fpdf.py | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L565-L612 | def set_font(self, family,style='',size=0):
"Select a font; size given in points"
family=family.lower()
if(family==''):
family=self.font_family
if(family=='arial'):
family='helvetica'
elif(family=='symbol' or family=='zapfdingbats'):
style=''
... | [
"def",
"set_font",
"(",
"self",
",",
"family",
",",
"style",
"=",
"''",
",",
"size",
"=",
"0",
")",
":",
"family",
"=",
"family",
".",
"lower",
"(",
")",
"if",
"(",
"family",
"==",
"''",
")",
":",
"family",
"=",
"self",
".",
"font_family",
"if",
... | Select a font; size given in points | [
"Select",
"a",
"font",
";",
"size",
"given",
"in",
"points"
] | python | train | 41.875 |
angr/angr | angr/blade.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/blade.py#L133-L158 | def _get_irsb(self, v):
"""
Get the IRSB object from an address, a SimRun, or a CFGNode.
:param v: Can be one of the following: an address, or a CFGNode.
:return: The IRSB instance.
:rtype: pyvex.IRSB
"""
if isinstance(v, CFGNode):
v = v.addr
... | [
"def",
"_get_irsb",
"(",
"self",
",",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"CFGNode",
")",
":",
"v",
"=",
"v",
".",
"addr",
"if",
"type",
"(",
"v",
")",
"is",
"int",
":",
"# Generate an IRSB from self._project",
"if",
"v",
"in",
"self",
... | Get the IRSB object from an address, a SimRun, or a CFGNode.
:param v: Can be one of the following: an address, or a CFGNode.
:return: The IRSB instance.
:rtype: pyvex.IRSB | [
"Get",
"the",
"IRSB",
"object",
"from",
"an",
"address",
"a",
"SimRun",
"or",
"a",
"CFGNode",
".",
":",
"param",
"v",
":",
"Can",
"be",
"one",
"of",
"the",
"following",
":",
"an",
"address",
"or",
"a",
"CFGNode",
".",
":",
"return",
":",
"The",
"IR... | python | train | 32.807692 |
CS207-Final-Project-Group-10/cs207-FinalProject | fluxions/fluxion_node.py | https://github.com/CS207-Final-Project-Group-10/cs207-FinalProject/blob/842e9c2d3ca1490cef18c086dfde81856d8d3a82/fluxions/fluxion_node.py#L82-L156 | def _parse_args_forward_mode(self, *args) -> Tuple[dict, dict]:
"""
Parse input arguments used in forward mode differentiation.
End result will be two arrays X and dX, each of shape (n) or (T, n)
Allowed input shapes are:
(1) ARRAY_N: two arrays of size n
(2) ARRAY_TxN... | [
"def",
"_parse_args_forward_mode",
"(",
"self",
",",
"*",
"args",
")",
"->",
"Tuple",
"[",
"dict",
",",
"dict",
"]",
":",
"# Types for arg_vars and arg_seed",
"arg_vars",
":",
"np",
".",
"ndarray",
"=",
"{",
"}",
"arg_seed",
":",
"np",
".",
"ndarray",
"=",... | Parse input arguments used in forward mode differentiation.
End result will be two arrays X and dX, each of shape (n) or (T, n)
Allowed input shapes are:
(1) ARRAY_N: two arrays of size n
(2) ARRAY_TxN: two arrays of size Txn
(3) DICT: two dictionaries, each mapping var... | [
"Parse",
"input",
"arguments",
"used",
"in",
"forward",
"mode",
"differentiation",
".",
"End",
"result",
"will",
"be",
"two",
"arrays",
"X",
"and",
"dX",
"each",
"of",
"shape",
"(",
"n",
")",
"or",
"(",
"T",
"n",
")",
"Allowed",
"input",
"shapes",
"are... | python | train | 46.586667 |
bcbio/bcbio-nextgen | bcbio/variation/mutect2.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/mutect2.py#L19-L46 | def _add_tumor_params(paired, items, gatk_type):
"""Add tumor/normal BAM input parameters to command line.
"""
params = []
if not paired:
raise ValueError("Specified MuTect2 calling but 'tumor' phenotype not present in batch\n"
"https://bcbio-nextgen.readthedocs.org/en/l... | [
"def",
"_add_tumor_params",
"(",
"paired",
",",
"items",
",",
"gatk_type",
")",
":",
"params",
"=",
"[",
"]",
"if",
"not",
"paired",
":",
"raise",
"ValueError",
"(",
"\"Specified MuTect2 calling but 'tumor' phenotype not present in batch\\n\"",
"\"https://bcbio-nextgen.re... | Add tumor/normal BAM input parameters to command line. | [
"Add",
"tumor",
"/",
"normal",
"BAM",
"input",
"parameters",
"to",
"command",
"line",
"."
] | python | train | 47.785714 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L11-L26 | def parse_time(s):
"""
Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster.
"""
result = None
if "epoch" in s:
epoch_time = float(s.rstrip().split(' ')[1][:-1])
result = datetime.datetime.utcfromtimestamp(epoch_time)
else:
_, date_part, time_part = s... | [
"def",
"parse_time",
"(",
"s",
")",
":",
"result",
"=",
"None",
"if",
"\"epoch\"",
"in",
"s",
":",
"epoch_time",
"=",
"float",
"(",
"s",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"[",
"1",
"]",
"[",
":",
"-",
"1",
"]",
")",
"res... | Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster. | [
"Like",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"s",
"%w",
"%Y",
"/",
"%m",
"/",
"%d",
"%H",
":",
"%M",
":",
"%S",
")",
"but",
"5x",
"faster",
"."
] | python | train | 32.0625 |
SKA-ScienceDataProcessor/integration-prototype | sip/execution_control/configuration_db/sip_config_db/scheduling/workflow_definitions.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/configuration_db/sip_config_db/scheduling/workflow_definitions.py#L17-L52 | def add(workflow_definition: dict, templates_root: str):
"""Add a workflow definition to the Configuration Database.
Templates are expected to be found in a directory tree with the following
structure:
- workflow_id:
|- workflow_version
|- stage_id
|... | [
"def",
"add",
"(",
"workflow_definition",
":",
"dict",
",",
"templates_root",
":",
"str",
")",
":",
"schema_path",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"'schema'",
",",
"'workflow_definition.json'",
")",
"with",
"open",
"(",
"schema_path",
... | Add a workflow definition to the Configuration Database.
Templates are expected to be found in a directory tree with the following
structure:
- workflow_id:
|- workflow_version
|- stage_id
|- stage_version
|- <templates>
Args... | [
"Add",
"a",
"workflow",
"definition",
"to",
"the",
"Configuration",
"Database",
"."
] | python | train | 33.666667 |
tensorflow/datasets | tensorflow_datasets/core/utils/gcs_utils.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/gcs_utils.py#L52-L57 | def gcs_files(prefix_filter=None):
"""List all files in GCS bucket."""
top_level_xml_str = download_gcs_file("", prefix_filter=prefix_filter)
xml_root = ElementTree.fromstring(top_level_xml_str)
filenames = [el[0].text for el in xml_root if el.tag.endswith("Contents")]
return filenames | [
"def",
"gcs_files",
"(",
"prefix_filter",
"=",
"None",
")",
":",
"top_level_xml_str",
"=",
"download_gcs_file",
"(",
"\"\"",
",",
"prefix_filter",
"=",
"prefix_filter",
")",
"xml_root",
"=",
"ElementTree",
".",
"fromstring",
"(",
"top_level_xml_str",
")",
"filenam... | List all files in GCS bucket. | [
"List",
"all",
"files",
"in",
"GCS",
"bucket",
"."
] | python | train | 48.5 |
insomnia-lab/libreant | archivant/archivant.py | https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/archivant/archivant.py#L392-L411 | def shrink_local_fsdb(self, dangling=True, corrupted=True, dryrun=False):
'''shrink local fsdb by removing dangling and/or corrupted files
return number of deleted files
'''
log.debug('shrinking local fsdb [danglings={}, corrupted={}]'.format(dangling, corrupted))
count = 0
... | [
"def",
"shrink_local_fsdb",
"(",
"self",
",",
"dangling",
"=",
"True",
",",
"corrupted",
"=",
"True",
",",
"dryrun",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"'shrinking local fsdb [danglings={}, corrupted={}]'",
".",
"format",
"(",
"dangling",
",",
"... | shrink local fsdb by removing dangling and/or corrupted files
return number of deleted files | [
"shrink",
"local",
"fsdb",
"by",
"removing",
"dangling",
"and",
"/",
"or",
"corrupted",
"files"
] | python | train | 40.4 |
swistakm/graceful | src/graceful/resources/mixins.py | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L276-L304 | def on_post(self, req, resp, handler=None, **kwargs):
"""Respond on POST HTTP request assuming resource creation flow.
This request handler assumes that POST requests are associated with
resource creation. Thus default flow for such requests is:
* Create new resource instance and prepa... | [
"def",
"on_post",
"(",
"self",
",",
"req",
",",
"resp",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"self",
".",
"handle",
"(",
"handler",
"or",
"self",
".",
"create",
",",
"req",
",",
"resp",
",",
"*",
"*",
"kwa... | Respond on POST HTTP request assuming resource creation flow.
This request handler assumes that POST requests are associated with
resource creation. Thus default flow for such requests is:
* Create new resource instance and prepare its representation by
calling its creation method ha... | [
"Respond",
"on",
"POST",
"HTTP",
"request",
"assuming",
"resource",
"creation",
"flow",
"."
] | python | train | 42.689655 |
zblz/naima | naima/radiative.py | https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L821-L851 | def sed(self, photon_energy, distance=1 * u.kpc, seed=None):
"""Spectral energy distribution at a given distance from the source
Parameters
----------
photon_energy : :class:`~astropy.units.Quantity` float or array
Photon energy array.
distance : :class:`~astropy.un... | [
"def",
"sed",
"(",
"self",
",",
"photon_energy",
",",
"distance",
"=",
"1",
"*",
"u",
".",
"kpc",
",",
"seed",
"=",
"None",
")",
":",
"sed",
"=",
"super",
"(",
"InverseCompton",
",",
"self",
")",
".",
"sed",
"(",
"photon_energy",
",",
"distance",
"... | Spectral energy distribution at a given distance from the source
Parameters
----------
photon_energy : :class:`~astropy.units.Quantity` float or array
Photon energy array.
distance : :class:`~astropy.units.Quantity` float, optional
Distance to the source. If set... | [
"Spectral",
"energy",
"distribution",
"at",
"a",
"given",
"distance",
"from",
"the",
"source"
] | python | train | 34.935484 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.