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 |
|---|---|---|---|---|---|---|---|---|---|
numenta/htmresearch | projects/energy_based_pooling/energy_based_models/energy_based_pooler.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/energy_based_pooling/energy_based_models/energy_based_pooler.py#L215-L221 | def learn(self, x):
"""Encodes an input array, and performs weight updates and updates to the activity
statistics according to the respective methods implemented below."""
y = self.encode(x)
self.update_statistics([y])
self.update_weights([x],[y])
return y | [
"def",
"learn",
"(",
"self",
",",
"x",
")",
":",
"y",
"=",
"self",
".",
"encode",
"(",
"x",
")",
"self",
".",
"update_statistics",
"(",
"[",
"y",
"]",
")",
"self",
".",
"update_weights",
"(",
"[",
"x",
"]",
",",
"[",
"y",
"]",
")",
"return",
... | Encodes an input array, and performs weight updates and updates to the activity
statistics according to the respective methods implemented below. | [
"Encodes",
"an",
"input",
"array",
"and",
"performs",
"weight",
"updates",
"and",
"updates",
"to",
"the",
"activity",
"statistics",
"according",
"to",
"the",
"respective",
"methods",
"implemented",
"below",
"."
] | python | train | 42.857143 |
boundary/pulse-api-cli | boundary/property_handler.py | https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/property_handler.py#L22-L31 | def _process_properties(self, properties):
"""
Transforms the command line properties into python dictionary
:return:
"""
if properties is not None:
self._properties = {}
for p in properties:
d = p.split('=')
self._propertie... | [
"def",
"_process_properties",
"(",
"self",
",",
"properties",
")",
":",
"if",
"properties",
"is",
"not",
"None",
":",
"self",
".",
"_properties",
"=",
"{",
"}",
"for",
"p",
"in",
"properties",
":",
"d",
"=",
"p",
".",
"split",
"(",
"'='",
")",
"self"... | Transforms the command line properties into python dictionary
:return: | [
"Transforms",
"the",
"command",
"line",
"properties",
"into",
"python",
"dictionary",
":",
"return",
":"
] | python | test | 32.5 |
broadinstitute/fiss | firecloud/fiss.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/fiss.py#L737-L765 | def config_new(args):
'''Attempt to install a new method config into a workspace, by: generating
a template from a versioned method in the methods repo, then launching
a local editor (respecting the $EDITOR environment variable) to fill in
the incomplete input/output fields. Returns True if th... | [
"def",
"config_new",
"(",
"args",
")",
":",
"cfg",
"=",
"config_template",
"(",
"args",
")",
"# Iteratively try to edit/install the config: exit iteration by EITHER",
"# Successful config_put() after editing",
"# Leaving config unchanged in editor, e.g. quitting out of VI with :q",
... | Attempt to install a new method config into a workspace, by: generating
a template from a versioned method in the methods repo, then launching
a local editor (respecting the $EDITOR environment variable) to fill in
the incomplete input/output fields. Returns True if the config was
successfu... | [
"Attempt",
"to",
"install",
"a",
"new",
"method",
"config",
"into",
"a",
"workspace",
"by",
":",
"generating",
"a",
"template",
"from",
"a",
"versioned",
"method",
"in",
"the",
"methods",
"repo",
"then",
"launching",
"a",
"local",
"editor",
"(",
"respecting"... | python | train | 42.103448 |
CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L774-L788 | def _update_param(self):
r"""Update parameters
This method updates the values of the algorthm parameters with the
methods provided
"""
# Update the gamma parameter.
if not isinstance(self._gamma_update, type(None)):
self._gamma = self._gamma_update(self._ga... | [
"def",
"_update_param",
"(",
"self",
")",
":",
"# Update the gamma parameter.",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_gamma_update",
",",
"type",
"(",
"None",
")",
")",
":",
"self",
".",
"_gamma",
"=",
"self",
".",
"_gamma_update",
"(",
"self",
".... | r"""Update parameters
This method updates the values of the algorthm parameters with the
methods provided | [
"r",
"Update",
"parameters"
] | python | train | 31.933333 |
edx/edx-enterprise | consent/helpers.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/helpers.py#L34-L49 | def get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid):
"""
Get the data sharing consent object associated with a certain user of a customer for a course.
:param username: The user that grants consent.
:param course_id: The course for which consent is granted.
:param ent... | [
"def",
"get_course_data_sharing_consent",
"(",
"username",
",",
"course_id",
",",
"enterprise_customer_uuid",
")",
":",
"# Prevent circular imports.",
"DataSharingConsent",
"=",
"apps",
".",
"get_model",
"(",
"'consent'",
",",
"'DataSharingConsent'",
")",
"# pylint: disable... | Get the data sharing consent object associated with a certain user of a customer for a course.
:param username: The user that grants consent.
:param course_id: The course for which consent is granted.
:param enterprise_customer_uuid: The consent requester.
:return: The data sharing consent object | [
"Get",
"the",
"data",
"sharing",
"consent",
"object",
"associated",
"with",
"a",
"certain",
"user",
"of",
"a",
"customer",
"for",
"a",
"course",
"."
] | python | valid | 44.5 |
alfred82santa/dirty-models | dirty_models/base.py | https://github.com/alfred82santa/dirty-models/blob/354becdb751b21f673515eae928c256c7e923c50/dirty_models/base.py#L29-L35 | def set_read_only(self, value):
"""
Sets whether model could be modified or not
"""
if self.__read_only__ != value:
self.__read_only__ = value
self._update_read_only() | [
"def",
"set_read_only",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"__read_only__",
"!=",
"value",
":",
"self",
".",
"__read_only__",
"=",
"value",
"self",
".",
"_update_read_only",
"(",
")"
] | Sets whether model could be modified or not | [
"Sets",
"whether",
"model",
"could",
"be",
"modified",
"or",
"not"
] | python | train | 31 |
hbldh/flask-pybankid | flask_pybankid.py | https://github.com/hbldh/flask-pybankid/blob/b9af666f587b027391b25d811788d934a12b57e6/flask_pybankid.py#L192-L203 | def create_from_pybankid_exception(cls, exception):
"""Class method for initiating from a `PyBankID` exception.
:param bankid.exceptions.BankIDError exception:
:return: The wrapped exception.
:rtype: :py:class:`~FlaskPyBankIDError`
"""
return cls(
"{0}: {1}"... | [
"def",
"create_from_pybankid_exception",
"(",
"cls",
",",
"exception",
")",
":",
"return",
"cls",
"(",
"\"{0}: {1}\"",
".",
"format",
"(",
"exception",
".",
"__class__",
".",
"__name__",
",",
"str",
"(",
"exception",
")",
")",
",",
"_exception_class_to_status_co... | Class method for initiating from a `PyBankID` exception.
:param bankid.exceptions.BankIDError exception:
:return: The wrapped exception.
:rtype: :py:class:`~FlaskPyBankIDError` | [
"Class",
"method",
"for",
"initiating",
"from",
"a",
"PyBankID",
"exception",
"."
] | python | train | 36.916667 |
honzamach/pynspect | pynspect/traversers.py | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L642-L649 | def evaluate_binop_logical(self, operation, left, right, **kwargs):
"""
Evaluate given logical binary operation with given operands.
"""
if not operation in self.binops_logical:
raise ValueError("Invalid logical binary operation '{}'".format(operation))
result = self.... | [
"def",
"evaluate_binop_logical",
"(",
"self",
",",
"operation",
",",
"left",
",",
"right",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"operation",
"in",
"self",
".",
"binops_logical",
":",
"raise",
"ValueError",
"(",
"\"Invalid logical binary operation '{}'... | Evaluate given logical binary operation with given operands. | [
"Evaluate",
"given",
"logical",
"binary",
"operation",
"with",
"given",
"operands",
"."
] | python | train | 47.375 |
Crypto-toolbox/btfxwss | btfxwss/connection.py | https://github.com/Crypto-toolbox/btfxwss/blob/16827fa6aacb2c0e289aa852bf61a18df6905835/btfxwss/connection.py#L505-L535 | def _resubscribe(self, soft=False):
"""Resubscribes to all channels found in self.channel_configs.
:param soft: if True, unsubscribes first.
:return: None
"""
# Restore non-default Bitfinex websocket configuration
if self.bitfinex_config:
self.send(**self.bit... | [
"def",
"_resubscribe",
"(",
"self",
",",
"soft",
"=",
"False",
")",
":",
"# Restore non-default Bitfinex websocket configuration",
"if",
"self",
".",
"bitfinex_config",
":",
"self",
".",
"send",
"(",
"*",
"*",
"self",
".",
"bitfinex_config",
")",
"q_list",
"=",
... | Resubscribes to all channels found in self.channel_configs.
:param soft: if True, unsubscribes first.
:return: None | [
"Resubscribes",
"to",
"all",
"channels",
"found",
"in",
"self",
".",
"channel_configs",
"."
] | python | test | 33.741935 |
angr/angr | angr/state_plugins/posix.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/posix.py#L540-L551 | def dump_file_by_path(self, path, **kwargs):
"""
Returns the concrete content for a file by path.
:param path: file path as string
:param kwargs: passed to state.solver.eval
:return: file contents as string
"""
file = self.state.fs.get(path)
if file is No... | [
"def",
"dump_file_by_path",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"file",
"=",
"self",
".",
"state",
".",
"fs",
".",
"get",
"(",
"path",
")",
"if",
"file",
"is",
"None",
":",
"return",
"None",
"return",
"file",
".",
"concreti... | Returns the concrete content for a file by path.
:param path: file path as string
:param kwargs: passed to state.solver.eval
:return: file contents as string | [
"Returns",
"the",
"concrete",
"content",
"for",
"a",
"file",
"by",
"path",
"."
] | python | train | 31.416667 |
Jajcus/pyxmpp2 | pyxmpp2/mainloop/poll.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/poll.py#L89-L108 | def _prepare_io_handler(self, handler):
"""Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
"""
logger.debug(" preparing handler: {0!r}".format(handler))
ret = handler.prepare()
logger.debug(" prepare result: ... | [
"def",
"_prepare_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"logger",
".",
"debug",
"(",
"\" preparing handler: {0!r}\"",
".",
"format",
"(",
"handler",
")",
")",
"ret",
"=",
"handler",
".",
"prepare",
"(",
")",
"logger",
".",
"debug",
"(",
"\" ... | Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done. | [
"Call",
"the",
"interfaces",
".",
"IOHandler",
".",
"prepare",
"method",
"and",
"remove",
"the",
"handler",
"from",
"unprepared",
"handler",
"list",
"when",
"done",
"."
] | python | valid | 42.25 |
nameko/nameko | nameko/utils/concurrency/__init__.py | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/utils/concurrency/__init__.py#L7-L49 | def fail_fast_imap(pool, call, items):
""" Run a function against each item in a given list, yielding each
function result in turn, where the function call is handled in a
:class:`~eventlet.greenthread.GreenThread` spawned by the provided pool.
If any function raises an exception, all other ongoing thr... | [
"def",
"fail_fast_imap",
"(",
"pool",
",",
"call",
",",
"items",
")",
":",
"result_queue",
"=",
"LightQueue",
"(",
"maxsize",
"=",
"len",
"(",
"items",
")",
")",
"spawned_threads",
"=",
"set",
"(",
")",
"def",
"handle_result",
"(",
"finished_thread",
")",
... | Run a function against each item in a given list, yielding each
function result in turn, where the function call is handled in a
:class:`~eventlet.greenthread.GreenThread` spawned by the provided pool.
If any function raises an exception, all other ongoing threads are killed,
and the exception is raise... | [
"Run",
"a",
"function",
"against",
"each",
"item",
"in",
"a",
"given",
"list",
"yielding",
"each",
"function",
"result",
"in",
"turn",
"where",
"the",
"function",
"call",
"is",
"handled",
"in",
"a",
":",
"class",
":",
"~eventlet",
".",
"greenthread",
".",
... | python | train | 38.511628 |
J535D165/recordlinkage | recordlinkage/adapters.py | https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/adapters.py#L57-L78 | def _prob_match(self, features):
"""Compute match probabilities.
Parameters
----------
features : numpy.ndarray
The data to train the model on.
Returns
-------
numpy.ndarray
The match probabilties.
"""
# compute the proba... | [
"def",
"_prob_match",
"(",
"self",
",",
"features",
")",
":",
"# compute the probabilities",
"probs",
"=",
"self",
".",
"kernel",
".",
"predict_proba",
"(",
"features",
")",
"# get the position of match probabilities",
"classes",
"=",
"list",
"(",
"self",
".",
"ke... | Compute match probabilities.
Parameters
----------
features : numpy.ndarray
The data to train the model on.
Returns
-------
numpy.ndarray
The match probabilties. | [
"Compute",
"match",
"probabilities",
"."
] | python | train | 25 |
OLC-LOC-Bioinformatics/GenomeQAML | genomeqaml/extract_features.py | https://github.com/OLC-LOC-Bioinformatics/GenomeQAML/blob/2953e574c185afab23075641da4ce5392bc003e9/genomeqaml/extract_features.py#L98-L130 | def find_genus(files, database, threads=12):
"""
Uses MASH to find the genus of fasta files.
:param files: File dictionary returned by filer method.
:param database: Path to reduced refseq database sketch.
:param threads: Number of threads to run mash with.
:return: genus_dict: Dictionary of gen... | [
"def",
"find_genus",
"(",
"files",
",",
"database",
",",
"threads",
"=",
"12",
")",
":",
"genus_dict",
"=",
"dict",
"(",
")",
"tmpdir",
"=",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"if"... | Uses MASH to find the genus of fasta files.
:param files: File dictionary returned by filer method.
:param database: Path to reduced refseq database sketch.
:param threads: Number of threads to run mash with.
:return: genus_dict: Dictionary of genus for each sample. Will return NA if genus could not be ... | [
"Uses",
"MASH",
"to",
"find",
"the",
"genus",
"of",
"fasta",
"files",
".",
":",
"param",
"files",
":",
"File",
"dictionary",
"returned",
"by",
"filer",
"method",
".",
":",
"param",
"database",
":",
"Path",
"to",
"reduced",
"refseq",
"database",
"sketch",
... | python | train | 37.272727 |
google/dotty | efilter/parsers/common/token_stream.py | https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/token_stream.py#L87-L99 | def reject(self, f, *args):
"""Like 'match', but throw a parse error if 'f' matches.
This is useful when a parser wants to be strict about specific things
being prohibited. For example, DottySQL bans the use of SQL keywords as
variable names.
"""
match = self.match(f, *a... | [
"def",
"reject",
"(",
"self",
",",
"f",
",",
"*",
"args",
")",
":",
"match",
"=",
"self",
".",
"match",
"(",
"f",
",",
"*",
"args",
")",
"if",
"match",
":",
"token",
"=",
"self",
".",
"peek",
"(",
"0",
")",
"raise",
"errors",
".",
"EfilterParse... | Like 'match', but throw a parse error if 'f' matches.
This is useful when a parser wants to be strict about specific things
being prohibited. For example, DottySQL bans the use of SQL keywords as
variable names. | [
"Like",
"match",
"but",
"throw",
"a",
"parse",
"error",
"if",
"f",
"matches",
"."
] | python | train | 41.076923 |
Esri/ArcREST | src/arcrest/webmap/operationallayers.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/webmap/operationallayers.py#L72-L90 | def __look_up_geom(self, geomType):
""" compares the geometry object's type verse the JSOn
specs for geometry types
Inputs:
geomType - string - geometry object's type
Returns:
string JSON geometry type or None if not an allowed type
"""
... | [
"def",
"__look_up_geom",
"(",
"self",
",",
"geomType",
")",
":",
"if",
"geomType",
".",
"lower",
"(",
")",
"==",
"\"point\"",
":",
"return",
"\"esriGeometryPoint\"",
"elif",
"geomType",
".",
"lower",
"(",
")",
"==",
"\"polyline\"",
":",
"return",
"\"esriGeom... | compares the geometry object's type verse the JSOn
specs for geometry types
Inputs:
geomType - string - geometry object's type
Returns:
string JSON geometry type or None if not an allowed type | [
"compares",
"the",
"geometry",
"object",
"s",
"type",
"verse",
"the",
"JSOn",
"specs",
"for",
"geometry",
"types",
"Inputs",
":",
"geomType",
"-",
"string",
"-",
"geometry",
"object",
"s",
"type",
"Returns",
":",
"string",
"JSON",
"geometry",
"type",
"or",
... | python | train | 35.789474 |
senaite/senaite.core | bika/lims/workflow/analysisrequest/guards.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/workflow/analysisrequest/guards.py#L171-L180 | def guard_sample(analysis_request):
"""Returns whether 'sample' transition can be performed or not. Returns
True only if the analysis request has the DateSampled and Sampler set or if
the user belongs to the Samplers group
"""
if analysis_request.getDateSampled() and analysis_request.getSampler():
... | [
"def",
"guard_sample",
"(",
"analysis_request",
")",
":",
"if",
"analysis_request",
".",
"getDateSampled",
"(",
")",
"and",
"analysis_request",
".",
"getSampler",
"(",
")",
":",
"return",
"True",
"current_user",
"=",
"api",
".",
"get_current_user",
"(",
")",
"... | Returns whether 'sample' transition can be performed or not. Returns
True only if the analysis request has the DateSampled and Sampler set or if
the user belongs to the Samplers group | [
"Returns",
"whether",
"sample",
"transition",
"can",
"be",
"performed",
"or",
"not",
".",
"Returns",
"True",
"only",
"if",
"the",
"analysis",
"request",
"has",
"the",
"DateSampled",
"and",
"Sampler",
"set",
"or",
"if",
"the",
"user",
"belongs",
"to",
"the",
... | python | train | 44.5 |
vtkiorg/vtki | vtki/examples/examples.py | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/examples/examples.py#L77-L109 | def plot_ants_plane(off_screen=False, notebook=None):
"""
Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane
"""
# load and shrink airplane
airplane = vtki.PolyData(planefile)
airplane.points /= 10
# pts = airpla... | [
"def",
"plot_ants_plane",
"(",
"off_screen",
"=",
"False",
",",
"notebook",
"=",
"None",
")",
":",
"# load and shrink airplane",
"airplane",
"=",
"vtki",
".",
"PolyData",
"(",
"planefile",
")",
"airplane",
".",
"points",
"/=",
"10",
"# pts = airplane.points # gets... | Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane | [
"Demonstrate",
"how",
"to",
"create",
"a",
"plot",
"class",
"to",
"plot",
"multiple",
"meshes",
"while",
"adding",
"scalars",
"and",
"text",
"."
] | python | train | 30.69697 |
saltstack/salt | salt/states/lxd_container.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_container.py#L716-L852 | def migrated(name,
remote_addr,
cert,
key,
verify_cert,
src_remote_addr,
stop_and_start=False,
src_cert=None,
src_key=None,
src_verify_cert=None):
''' Ensure a container is migrated to another host
... | [
"def",
"migrated",
"(",
"name",
",",
"remote_addr",
",",
"cert",
",",
"key",
",",
"verify_cert",
",",
"src_remote_addr",
",",
"stop_and_start",
"=",
"False",
",",
"src_cert",
"=",
"None",
",",
"src_key",
"=",
"None",
",",
"src_verify_cert",
"=",
"None",
")... | Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs need to be authenticated,
use :mod:`lxd.authenticate <salt.states.... | [
"Ensure",
"a",
"container",
"is",
"migrated",
"to",
"another",
"host"
] | python | train | 26.89781 |
ewels/MultiQC | multiqc/modules/hicpro/hicpro.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L269-L299 | def hicpro_mapping_chart (self):
""" Generate the HiC-Pro Aligned reads plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['Full_Alignments_Read'] = { 'color': '#005ce6', 'name': 'Full reads Alignments' }
keys['Trimmed_Alignments_Read']... | [
"def",
"hicpro_mapping_chart",
"(",
"self",
")",
":",
"# Specify the order of the different possible categories",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'Full_Alignments_Read'",
"]",
"=",
"{",
"'color'",
":",
"'#005ce6'",
",",
"'name'",
":",
"'Full reads ... | Generate the HiC-Pro Aligned reads plot | [
"Generate",
"the",
"HiC",
"-",
"Pro",
"Aligned",
"reads",
"plot"
] | python | train | 46.806452 |
jmcarp/robobrowser | robobrowser/helpers.py | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/helpers.py#L46-L54 | def find(soup, name=None, attrs=None, recursive=True, text=None, **kwargs):
"""Modified find method; see `find_all`, above.
"""
tags = find_all(
soup, name, attrs or {}, recursive, text, 1, **kwargs
)
if tags:
return tags[0] | [
"def",
"find",
"(",
"soup",
",",
"name",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"recursive",
"=",
"True",
",",
"text",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"tags",
"=",
"find_all",
"(",
"soup",
",",
"name",
",",
"attrs",
"or",
... | Modified find method; see `find_all`, above. | [
"Modified",
"find",
"method",
";",
"see",
"find_all",
"above",
"."
] | python | train | 28.111111 |
googleapis/google-cloud-python | api_core/google/api_core/datetime_helpers.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/datetime_helpers.py#L269-L279 | def timestamp_pb(self):
"""Return a timestamp message.
Returns:
(:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message
"""
inst = self if self.tzinfo is not None else self.replace(tzinfo=pytz.UTC)
delta = inst - _UTC_EPOCH
seconds = int(delta.... | [
"def",
"timestamp_pb",
"(",
"self",
")",
":",
"inst",
"=",
"self",
"if",
"self",
".",
"tzinfo",
"is",
"not",
"None",
"else",
"self",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"UTC",
")",
"delta",
"=",
"inst",
"-",
"_UTC_EPOCH",
"seconds",
"=",... | Return a timestamp message.
Returns:
(:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message | [
"Return",
"a",
"timestamp",
"message",
"."
] | python | train | 41.363636 |
WebarchivCZ/WA-KAT | src/wa_kat/templates/static/js/Lib/site-packages/components/author_picker.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/templates/static/js/Lib/site-packages/components/author_picker.py#L246-L253 | def bind(cls):
"""
Bind the buttons to adapter's event handler.
"""
super(cls, cls).bind()
cls.search_btn_el.bind("click", cls.start)
cls.input_el.bind("keypress", func_on_enter(cls.start)) | [
"def",
"bind",
"(",
"cls",
")",
":",
"super",
"(",
"cls",
",",
"cls",
")",
".",
"bind",
"(",
")",
"cls",
".",
"search_btn_el",
".",
"bind",
"(",
"\"click\"",
",",
"cls",
".",
"start",
")",
"cls",
".",
"input_el",
".",
"bind",
"(",
"\"keypress\"",
... | Bind the buttons to adapter's event handler. | [
"Bind",
"the",
"buttons",
"to",
"adapter",
"s",
"event",
"handler",
"."
] | python | train | 28.875 |
zimeon/iiif | iiif/flask_utils.py | https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L375-L381 | def error_response(self, e):
"""Make response for an IIIFError e.
Also add compliance header.
"""
self.add_compliance_header()
return self.make_response(*e.image_server_response(self.api_version)) | [
"def",
"error_response",
"(",
"self",
",",
"e",
")",
":",
"self",
".",
"add_compliance_header",
"(",
")",
"return",
"self",
".",
"make_response",
"(",
"*",
"e",
".",
"image_server_response",
"(",
"self",
".",
"api_version",
")",
")"
] | Make response for an IIIFError e.
Also add compliance header. | [
"Make",
"response",
"for",
"an",
"IIIFError",
"e",
"."
] | python | train | 33 |
ionelmc/python-cogen | cogen/web/wsgi.py | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/web/wsgi.py#L250-L533 | def run(self):
"""A bit bulky atm..."""
self.close_connection = False
try:
while True:
self.started_response = False
self.status = ""
self.outheaders = []
self.sent_headers = False
self.chunked_write = False
self.write_buffer = StringIO.Strin... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"close_connection",
"=",
"False",
"try",
":",
"while",
"True",
":",
"self",
".",
"started_response",
"=",
"False",
"self",
".",
"status",
"=",
"\"\"",
"self",
".",
"outheaders",
"=",
"[",
"]",
"self",
... | A bit bulky atm... | [
"A",
"bit",
"bulky",
"atm",
"..."
] | python | train | 38.549296 |
pydata/xarray | xarray/backends/file_manager.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/backends/file_manager.py#L134-L140 | def _make_key(self):
"""Make a key for caching files in the LRU cache."""
value = (self._opener,
self._args,
'a' if self._mode == 'w' else self._mode,
tuple(sorted(self._kwargs.items())))
return _HashedSequence(value) | [
"def",
"_make_key",
"(",
"self",
")",
":",
"value",
"=",
"(",
"self",
".",
"_opener",
",",
"self",
".",
"_args",
",",
"'a'",
"if",
"self",
".",
"_mode",
"==",
"'w'",
"else",
"self",
".",
"_mode",
",",
"tuple",
"(",
"sorted",
"(",
"self",
".",
"_k... | Make a key for caching files in the LRU cache. | [
"Make",
"a",
"key",
"for",
"caching",
"files",
"in",
"the",
"LRU",
"cache",
"."
] | python | train | 40.857143 |
danielfrg/word2vec | word2vec/scripts_interface.py | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/scripts_interface.py#L6-L112 | def word2vec(
train,
output,
size=100,
window=5,
sample="1e-3",
hs=0,
negative=5,
threads=12,
iter_=5,
min_count=5,
alpha=0.025,
debug=2,
binary=1,
cbow=1,
save_vocab=None,
read_vocab=None,
... | [
"def",
"word2vec",
"(",
"train",
",",
"output",
",",
"size",
"=",
"100",
",",
"window",
"=",
"5",
",",
"sample",
"=",
"\"1e-3\"",
",",
"hs",
"=",
"0",
",",
"negative",
"=",
"5",
",",
"threads",
"=",
"12",
",",
"iter_",
"=",
"5",
",",
"min_count",... | word2vec execution
Parameters for training:
train <file>
Use text data from <file> to train the model
output <file>
Use <file> to save the resulting word vectors / word clusters
size <int>
Set size of word vectors; default is 100
window <int>
... | [
"word2vec",
"execution"
] | python | train | 26.401869 |
diogobaeder/pycket | pycket/session.py | https://github.com/diogobaeder/pycket/blob/b21d1553b4100d820a6922eeb55baa2329bc02c2/pycket/session.py#L89-L97 | def get(self, name, default=None):
'''
Gets the object for "name", or None if there's no such object. If
"default" is provided, return it if no object is found.
'''
session = self.__get_session_from_db()
return session.get(name, default) | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"session",
"=",
"self",
".",
"__get_session_from_db",
"(",
")",
"return",
"session",
".",
"get",
"(",
"name",
",",
"default",
")"
] | Gets the object for "name", or None if there's no such object. If
"default" is provided, return it if no object is found. | [
"Gets",
"the",
"object",
"for",
"name",
"or",
"None",
"if",
"there",
"s",
"no",
"such",
"object",
".",
"If",
"default",
"is",
"provided",
"return",
"it",
"if",
"no",
"object",
"is",
"found",
"."
] | python | train | 31 |
ethereum/py-evm | eth/vm/state.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/state.py#L283-L293 | def get_computation(self,
message: Message,
transaction_context: 'BaseTransactionContext') -> 'BaseComputation':
"""
Return a computation instance for the given `message` and `transaction_context`
"""
if self.computation_class is None:
... | [
"def",
"get_computation",
"(",
"self",
",",
"message",
":",
"Message",
",",
"transaction_context",
":",
"'BaseTransactionContext'",
")",
"->",
"'BaseComputation'",
":",
"if",
"self",
".",
"computation_class",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"\"N... | Return a computation instance for the given `message` and `transaction_context` | [
"Return",
"a",
"computation",
"instance",
"for",
"the",
"given",
"message",
"and",
"transaction_context"
] | python | train | 47.090909 |
log2timeline/plaso | plaso/preprocessors/windows.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/preprocessors/windows.py#L421-L438 | def _GetUsernameFromProfilePath(self, path):
"""Retrieves the username from a Windows profile path.
Trailing path path segment are ignored.
Args:
path (str): a Windows path with '\\' as path segment separator.
Returns:
str: basename which is the last path segment.
"""
# Strip trai... | [
"def",
"_GetUsernameFromProfilePath",
"(",
"self",
",",
"path",
")",
":",
"# Strip trailing key separators.",
"while",
"path",
"and",
"path",
"[",
"-",
"1",
"]",
"==",
"'\\\\'",
":",
"path",
"=",
"path",
"[",
":",
"-",
"1",
"]",
"if",
"path",
":",
"_",
... | Retrieves the username from a Windows profile path.
Trailing path path segment are ignored.
Args:
path (str): a Windows path with '\\' as path segment separator.
Returns:
str: basename which is the last path segment. | [
"Retrieves",
"the",
"username",
"from",
"a",
"Windows",
"profile",
"path",
"."
] | python | train | 25.222222 |
horazont/aioxmpp | aioxmpp/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1520-L1530 | def is_depsignal_handler(class_, signal_name, cb, *, defer=False):
"""
Return true if `cb` has been decorated with :func:`depsignal` for the given
signal, class and connection mode.
"""
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
return _depsignal_... | [
"def",
"is_depsignal_handler",
"(",
"class_",
",",
"signal_name",
",",
"cb",
",",
"*",
",",
"defer",
"=",
"False",
")",
":",
"try",
":",
"handlers",
"=",
"get_magic_attr",
"(",
"cb",
")",
"except",
"AttributeError",
":",
"return",
"False",
"return",
"_deps... | Return true if `cb` has been decorated with :func:`depsignal` for the given
signal, class and connection mode. | [
"Return",
"true",
"if",
"cb",
"has",
"been",
"decorated",
"with",
":",
"func",
":",
"depsignal",
"for",
"the",
"given",
"signal",
"class",
"and",
"connection",
"mode",
"."
] | python | train | 32.545455 |
spotify/luigi | luigi/worker.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L1041-L1109 | def _handle_next_task(self):
"""
We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies adde... | [
"def",
"_handle_next_task",
"(",
"self",
")",
":",
"self",
".",
"_idle_since",
"=",
"None",
"while",
"True",
":",
"self",
".",
"_purge_children",
"(",
")",
"# Deal with subprocess failures",
"try",
":",
"task_id",
",",
"status",
",",
"expl",
",",
"missing",
... | We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies added,
3. child process dies: we need to catc... | [
"We",
"have",
"to",
"catch",
"three",
"ways",
"a",
"task",
"can",
"be",
"done",
":"
] | python | train | 41.434783 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/setuptools/package_index.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/package_index.py#L1025-L1049 | def local_open(url):
"""Read a local path, with special support for directories"""
scheme, server, path, param, query, frag = urlparse(url)
filename = url2pathname(path)
if os.path.isfile(filename):
return urllib2.urlopen(url)
elif path.endswith('/') and os.path.isdir(filename):
file... | [
"def",
"local_open",
"(",
"url",
")",
":",
"scheme",
",",
"server",
",",
"path",
",",
"param",
",",
"query",
",",
"frag",
"=",
"urlparse",
"(",
"url",
")",
"filename",
"=",
"url2pathname",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"... | Read a local path, with special support for directories | [
"Read",
"a",
"local",
"path",
"with",
"special",
"support",
"for",
"directories"
] | python | test | 40 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/bson/__init__.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/bson/__init__.py#L623-L628 | def _encode_long(name, value, dummy0, dummy1):
"""Encode a python long (python 2.x)"""
try:
return b"\x12" + name + _PACK_LONG(value)
except struct.error:
raise OverflowError("BSON can only handle up to 8-byte ints") | [
"def",
"_encode_long",
"(",
"name",
",",
"value",
",",
"dummy0",
",",
"dummy1",
")",
":",
"try",
":",
"return",
"b\"\\x12\"",
"+",
"name",
"+",
"_PACK_LONG",
"(",
"value",
")",
"except",
"struct",
".",
"error",
":",
"raise",
"OverflowError",
"(",
"\"BSON... | Encode a python long (python 2.x) | [
"Encode",
"a",
"python",
"long",
"(",
"python",
"2",
".",
"x",
")"
] | python | train | 39.833333 |
pgmpy/pgmpy | pgmpy/inference/mplp.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/inference/mplp.py#L144-L203 | def _update_message(self, sending_cluster):
"""
This is the message-update method.
Parameters
----------
sending_cluster: The resulting messages are lambda_{c-->s} from the given
cluster 'c' to all of its intersection_sets 's'.
Here 's' are the elements ... | [
"def",
"_update_message",
"(",
"self",
",",
"sending_cluster",
")",
":",
"# The new updates will take place for the intersection_sets of this cluster.",
"# The new updates are:",
"# \\delta_{f \\rightarrow i}(x_i) = - \\delta_i^{-f} +",
"# 1/{\\| f \\|} max_{x_{f-i}}\\left[{\\theta_f(x_f) + \\... | This is the message-update method.
Parameters
----------
sending_cluster: The resulting messages are lambda_{c-->s} from the given
cluster 'c' to all of its intersection_sets 's'.
Here 's' are the elements of intersection_sets_for_cluster_c.
Reference
--... | [
"This",
"is",
"the",
"message",
"-",
"update",
"method",
"."
] | python | train | 51.716667 |
gem/oq-engine | openquake/hazardlib/geo/geodetic.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/geodetic.py#L434-L486 | def distance_to_semi_arc(alon, alat, aazimuth, plons, plats):
"""
In this method we use a reference system centerd on (alon, alat) and with
the y-axis corresponding to aazimuth direction to calculate the minimum
distance from a semiarc with generates in (alon, alat).
Parameters are the same as for ... | [
"def",
"distance_to_semi_arc",
"(",
"alon",
",",
"alat",
",",
"aazimuth",
",",
"plons",
",",
"plats",
")",
":",
"if",
"type",
"(",
"plons",
")",
"is",
"float",
":",
"plons",
"=",
"numpy",
".",
"array",
"(",
"[",
"plons",
"]",
")",
"plats",
"=",
"nu... | In this method we use a reference system centerd on (alon, alat) and with
the y-axis corresponding to aazimuth direction to calculate the minimum
distance from a semiarc with generates in (alon, alat).
Parameters are the same as for :func:`distance_to_arc`. | [
"In",
"this",
"method",
"we",
"use",
"a",
"reference",
"system",
"centerd",
"on",
"(",
"alon",
"alat",
")",
"and",
"with",
"the",
"y",
"-",
"axis",
"corresponding",
"to",
"aazimuth",
"direction",
"to",
"calculate",
"the",
"minimum",
"distance",
"from",
"a"... | python | train | 43.754717 |
saltstack/salt | salt/states/win_powercfg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_powercfg.py#L40-L150 | def set_timeout(name, value, power='ac', scheme=None):
'''
Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``
... | [
"def",
"set_timeout",
"(",
"name",
",",
"value",
",",
"power",
"=",
"'ac'",
",",
"scheme",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
... | Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``
- ``hibernate``
value (int):
Th... | [
"Set",
"the",
"sleep",
"timeouts",
"of",
"specific",
"items",
"such",
"as",
"disk",
"monitor",
"etc",
"."
] | python | train | 29.216216 |
berkerpeksag/astor | astor/node_util.py | https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/node_util.py#L174-L208 | def fast_compare(tree1, tree2):
""" This is optimized to compare two AST trees for equality.
It makes several assumptions that are currently true for
AST trees used by rtrip, and it doesn't examine the _attributes.
"""
geta = ast.AST.__getattribute__
work = [(tree1, tree2)]
pop = w... | [
"def",
"fast_compare",
"(",
"tree1",
",",
"tree2",
")",
":",
"geta",
"=",
"ast",
".",
"AST",
".",
"__getattribute__",
"work",
"=",
"[",
"(",
"tree1",
",",
"tree2",
")",
"]",
"pop",
"=",
"work",
".",
"pop",
"extend",
"=",
"work",
".",
"extend",
"# T... | This is optimized to compare two AST trees for equality.
It makes several assumptions that are currently true for
AST trees used by rtrip, and it doesn't examine the _attributes. | [
"This",
"is",
"optimized",
"to",
"compare",
"two",
"AST",
"trees",
"for",
"equality",
".",
"It",
"makes",
"several",
"assumptions",
"that",
"are",
"currently",
"true",
"for",
"AST",
"trees",
"used",
"by",
"rtrip",
"and",
"it",
"doesn",
"t",
"examine",
"the... | python | train | 29.2 |
jic-dtool/dtool-irods | dtool_irods/__init__.py | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/__init__.py#L24-L38 | def _call_cmd_line(self):
"""Run the command line tool."""
try:
logging.info("Calling Popen with: {}".format(self.args))
p = Popen(self.args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
except OSError:
raise(RuntimeError("No such command found in PATH"))
# ... | [
"def",
"_call_cmd_line",
"(",
"self",
")",
":",
"try",
":",
"logging",
".",
"info",
"(",
"\"Calling Popen with: {}\"",
".",
"format",
"(",
"self",
".",
"args",
")",
")",
"p",
"=",
"Popen",
"(",
"self",
".",
"args",
",",
"stdin",
"=",
"PIPE",
",",
"st... | Run the command line tool. | [
"Run",
"the",
"command",
"line",
"tool",
"."
] | python | train | 44.533333 |
openstack/proliantutils | proliantutils/ilo/common.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/common.py#L37-L81 | def wait_for_operation_to_complete(
has_operation_completed, retries=10, delay_bw_retries=5,
delay_before_attempts=10, failover_exc=exception.IloError,
failover_msg=("Operation did not complete even after multiple "
"attempts."), is_silent_loop_exit=False):
"""Attempts ... | [
"def",
"wait_for_operation_to_complete",
"(",
"has_operation_completed",
",",
"retries",
"=",
"10",
",",
"delay_bw_retries",
"=",
"5",
",",
"delay_before_attempts",
"=",
"10",
",",
"failover_exc",
"=",
"exception",
".",
"IloError",
",",
"failover_msg",
"=",
"(",
"... | Attempts the provided operation for a specified number of times.
If it runs out of attempts, then it raises an exception. On success,
it breaks out of the loop.
:param has_operation_completed: the method to retry and it needs to return
a boolean to indicate success or fa... | [
"Attempts",
"the",
"provided",
"operation",
"for",
"a",
"specified",
"number",
"of",
"times",
"."
] | python | train | 50.044444 |
kapadia/usgs | usgs/api.py | https://github.com/kapadia/usgs/blob/0608346f0bc3c34e20f4ecc77ad71d0b514db7ee/usgs/api.py#L217-L244 | def metadata(dataset, node, entityids, extended=False, api_key=None):
"""
Request metadata for a given scene in a USGS dataset.
:param dataset:
:param node:
:param entityids:
:param extended:
Send a second request to the metadata url to get extended metadata on the scene.
:param api... | [
"def",
"metadata",
"(",
"dataset",
",",
"node",
",",
"entityids",
",",
"extended",
"=",
"False",
",",
"api_key",
"=",
"None",
")",
":",
"api_key",
"=",
"_get_api_key",
"(",
"api_key",
")",
"url",
"=",
"'{}/metadata'",
".",
"format",
"(",
"USGS_API",
")",... | Request metadata for a given scene in a USGS dataset.
:param dataset:
:param node:
:param entityids:
:param extended:
Send a second request to the metadata url to get extended metadata on the scene.
:param api_key: | [
"Request",
"metadata",
"for",
"a",
"given",
"scene",
"in",
"a",
"USGS",
"dataset",
"."
] | python | train | 30.464286 |
google/transitfeed | merge.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L283-L350 | def WriteOutput(self, output_file, feed_merger,
old_feed_path, new_feed_path, merged_feed_path):
"""Write the HTML output to a file.
Args:
output_file: The file object that the HTML output will be written to.
feed_merger: The FeedMerger instance.
old_feed_path: The path to t... | [
"def",
"WriteOutput",
"(",
"self",
",",
"output_file",
",",
"feed_merger",
",",
"old_feed_path",
",",
"new_feed_path",
",",
"merged_feed_path",
")",
":",
"if",
"merged_feed_path",
"is",
"None",
":",
"html_merged_feed_path",
"=",
"''",
"else",
":",
"html_merged_fee... | Write the HTML output to a file.
Args:
output_file: The file object that the HTML output will be written to.
feed_merger: The FeedMerger instance.
old_feed_path: The path to the old feed file as a string.
new_feed_path: The path to the new feed file as a string
merged_feed_path: The p... | [
"Write",
"the",
"HTML",
"output",
"to",
"a",
"file",
"."
] | python | train | 39.779412 |
wglass/lighthouse | lighthouse/haproxy/stanzas/stanza.py | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/haproxy/stanzas/stanza.py#L50-L64 | def is_valid_line(self, line):
"""
Validates a given line against the associated "section" (e.g. 'global'
or 'frontend', etc.) of a stanza.
If a line represents a directive that shouldn't be within the stanza
it is rejected. See the `directives.json` file for a condensed look
... | [
"def",
"is_valid_line",
"(",
"self",
",",
"line",
")",
":",
"adjusted_line",
"=",
"line",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"return",
"any",
"(",
"[",
"adjusted_line",
".",
"startswith",
"(",
"directive",
")",
"for",
"directive",
"in",
"d... | Validates a given line against the associated "section" (e.g. 'global'
or 'frontend', etc.) of a stanza.
If a line represents a directive that shouldn't be within the stanza
it is rejected. See the `directives.json` file for a condensed look
at valid directives based on section. | [
"Validates",
"a",
"given",
"line",
"against",
"the",
"associated",
"section",
"(",
"e",
".",
"g",
".",
"global",
"or",
"frontend",
"etc",
".",
")",
"of",
"a",
"stanza",
"."
] | python | train | 37.2 |
cocagne/txdbus | txdbus/interface.py | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/interface.py#L162-L170 | def addMethod(self, m):
"""
Adds a L{Method} to the interface
"""
if m.nargs == -1:
m.nargs = len([a for a in marshal.genCompleteTypes(m.sigIn)])
m.nret = len([a for a in marshal.genCompleteTypes(m.sigOut)])
self.methods[m.name] = m
self._xml = Non... | [
"def",
"addMethod",
"(",
"self",
",",
"m",
")",
":",
"if",
"m",
".",
"nargs",
"==",
"-",
"1",
":",
"m",
".",
"nargs",
"=",
"len",
"(",
"[",
"a",
"for",
"a",
"in",
"marshal",
".",
"genCompleteTypes",
"(",
"m",
".",
"sigIn",
")",
"]",
")",
"m",... | Adds a L{Method} to the interface | [
"Adds",
"a",
"L",
"{",
"Method",
"}",
"to",
"the",
"interface"
] | python | train | 34.777778 |
hyperledger/indy-node | indy_node/server/restarter.py | https://github.com/hyperledger/indy-node/blob/8fabd364eaf7d940a56df2911d9215b1e512a2de/indy_node/server/restarter.py#L177-L192 | def _callRestartAgent(self, ev_data: RestartLogData, failTimeout) -> None:
"""
Callback which is called when restart time come.
Writes restart record to restart log and asks
node control service to perform restart
:param ev_data: restart event data
:param version: versio... | [
"def",
"_callRestartAgent",
"(",
"self",
",",
"ev_data",
":",
"RestartLogData",
",",
"failTimeout",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"\"{}'s restart calling agent for restart\"",
".",
"format",
"(",
"self",
")",
")",
"self",
".",
"_actionLog",... | Callback which is called when restart time come.
Writes restart record to restart log and asks
node control service to perform restart
:param ev_data: restart event data
:param version: version to restart to | [
"Callback",
"which",
"is",
"called",
"when",
"restart",
"time",
"come",
".",
"Writes",
"restart",
"record",
"to",
"restart",
"log",
"and",
"asks",
"node",
"control",
"service",
"to",
"perform",
"restart"
] | python | train | 38.75 |
FutunnOpen/futuquant | futuquant/quote/open_quote_context.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/quote/open_quote_context.py#L40-L97 | def on_api_socket_reconnected(self):
"""for API socket reconnected"""
# auto subscriber
resub_count = 0
subtype_list = []
code_list = []
resub_dict = copy(self._ctx_subscribe)
subtype_all_cnt = len(resub_dict.keys())
subtype_cur_cnt = 0
ret_code ... | [
"def",
"on_api_socket_reconnected",
"(",
"self",
")",
":",
"# auto subscriber",
"resub_count",
"=",
"0",
"subtype_list",
"=",
"[",
"]",
"code_list",
"=",
"[",
"]",
"resub_dict",
"=",
"copy",
"(",
"self",
".",
"_ctx_subscribe",
")",
"subtype_all_cnt",
"=",
"len... | for API socket reconnected | [
"for",
"API",
"socket",
"reconnected"
] | python | train | 38.948276 |
orb-framework/orb | orb/core/connection_types/sql/mysql/mysqlconnection.py | https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/connection_types/sql/mysql/mysqlconnection.py#L40-L105 | def _execute(self,
native,
command,
data=None,
returning=True,
mapper=dict):
"""
Executes the inputted command into the current \
connection cursor.
:param command | <str>
da... | [
"def",
"_execute",
"(",
"self",
",",
"native",
",",
"command",
",",
"data",
"=",
"None",
",",
"returning",
"=",
"True",
",",
"mapper",
"=",
"dict",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"with",
"native",
".",
"cursor",
... | Executes the inputted command into the current \
connection cursor.
:param command | <str>
data | <dict> || None
:return [{<str> key: <variant>, ..}, ..], <int> count | [
"Executes",
"the",
"inputted",
"command",
"into",
"the",
"current",
"\\",
"connection",
"cursor",
"."
] | python | train | 34.227273 |
ceph/ceph-deploy | ceph_deploy/hosts/remotes.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L384-L398 | def zeroing(dev):
""" zeroing last few blocks of device """
# this kills the crab
#
# sgdisk will wipe out the main copy of the GPT partition
# table (sorry), but it doesn't remove the backup copies, and
# subsequent commands will continue to complain and fail when
# they see those. zeroing... | [
"def",
"zeroing",
"(",
"dev",
")",
":",
"# this kills the crab",
"#",
"# sgdisk will wipe out the main copy of the GPT partition",
"# table (sorry), but it doesn't remove the backup copies, and",
"# subsequent commands will continue to complain and fail when",
"# they see those. zeroing the l... | zeroing last few blocks of device | [
"zeroing",
"last",
"few",
"blocks",
"of",
"device"
] | python | train | 35.066667 |
mikedh/trimesh | trimesh/scene/transforms.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/scene/transforms.py#L255-L298 | def get(self, frame_to, frame_from=None):
"""
Get the transform from one frame to another, assuming they are connected
in the transform tree.
If the frames are not connected a NetworkXNoPath error will be raised.
Parameters
---------
frame_from: hashable object,... | [
"def",
"get",
"(",
"self",
",",
"frame_to",
",",
"frame_from",
"=",
"None",
")",
":",
"if",
"frame_from",
"is",
"None",
":",
"frame_from",
"=",
"self",
".",
"base_frame",
"cache_key",
"=",
"str",
"(",
"frame_from",
")",
"+",
"':'",
"+",
"str",
"(",
"... | Get the transform from one frame to another, assuming they are connected
in the transform tree.
If the frames are not connected a NetworkXNoPath error will be raised.
Parameters
---------
frame_from: hashable object, usually a string (eg 'world').
If left as... | [
"Get",
"the",
"transform",
"from",
"one",
"frame",
"to",
"another",
"assuming",
"they",
"are",
"connected",
"in",
"the",
"transform",
"tree",
"."
] | python | train | 32.181818 |
JonathonReinhart/scuba | scuba/dockerutil.py | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L53-L60 | def docker_pull(image):
'''Pulls an image'''
args = ['docker', 'pull', image]
# If this fails, the default docker stdout/stderr looks good to the user.
ret = call(args)
if ret != 0:
raise DockerError('Failed to pull image "{}"'.format(image)) | [
"def",
"docker_pull",
"(",
"image",
")",
":",
"args",
"=",
"[",
"'docker'",
",",
"'pull'",
",",
"image",
"]",
"# If this fails, the default docker stdout/stderr looks good to the user.",
"ret",
"=",
"call",
"(",
"args",
")",
"if",
"ret",
"!=",
"0",
":",
"raise",... | Pulls an image | [
"Pulls",
"an",
"image"
] | python | train | 33 |
insilichem/pychimera | pychimera/core.py | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/core.py#L279-L318 | def run_cli_options(args):
"""
Quick implementation of Python interpreter's -m, -c and file execution.
The resulting dictionary is imported into global namespace, just in case
someone is using interactive mode.
We try to keep argument order as to pass them correctly to the subcommands.
"""
... | [
"def",
"run_cli_options",
"(",
"args",
")",
":",
"if",
"_interactive_mode",
"(",
"args",
".",
"interactive",
")",
":",
"os",
".",
"environ",
"[",
"'PYTHONINSPECT'",
"]",
"=",
"'1'",
"if",
"in_ipython",
"(",
")",
":",
"return",
"exclusive_choices",
"=",
"["... | Quick implementation of Python interpreter's -m, -c and file execution.
The resulting dictionary is imported into global namespace, just in case
someone is using interactive mode.
We try to keep argument order as to pass them correctly to the subcommands. | [
"Quick",
"implementation",
"of",
"Python",
"interpreter",
"s",
"-",
"m",
"-",
"c",
"and",
"file",
"execution",
".",
"The",
"resulting",
"dictionary",
"is",
"imported",
"into",
"global",
"namespace",
"just",
"in",
"case",
"someone",
"is",
"using",
"interactive"... | python | train | 38.25 |
newville/asteval | asteval/asteval.py | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L528-L533 | def on_augassign(self, node): # ('target', 'op', 'value')
"""Augmented assign."""
return self.on_assign(ast.Assign(targets=[node.target],
value=ast.BinOp(left=node.target,
op=node.op,
... | [
"def",
"on_augassign",
"(",
"self",
",",
"node",
")",
":",
"# ('target', 'op', 'value')",
"return",
"self",
".",
"on_assign",
"(",
"ast",
".",
"Assign",
"(",
"targets",
"=",
"[",
"node",
".",
"target",
"]",
",",
"value",
"=",
"ast",
".",
"BinOp",
"(",
... | Augmented assign. | [
"Augmented",
"assign",
"."
] | python | train | 62 |
OpenMath/py-openmath | openmath/convert_pickle.py | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert_pickle.py#L331-L389 | def cls_build(inst, state):
"""
Apply the setstate protocol to initialize `inst` from `state`.
INPUT:
- ``inst`` -- a raw instance of a class
- ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values
EXAMPLES::
>>> from openmath.convert_pickl... | [
"def",
"cls_build",
"(",
"inst",
",",
"state",
")",
":",
"# Copied from Pickler.load_build",
"setstate",
"=",
"getattr",
"(",
"inst",
",",
"\"__setstate__\"",
",",
"None",
")",
"if",
"setstate",
":",
"setstate",
"(",
"state",
")",
"return",
"inst",
"slotstate"... | Apply the setstate protocol to initialize `inst` from `state`.
INPUT:
- ``inst`` -- a raw instance of a class
- ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values
EXAMPLES::
>>> from openmath.convert_pickle import cls_build
>>> class A(o... | [
"Apply",
"the",
"setstate",
"protocol",
"to",
"initialize",
"inst",
"from",
"state",
"."
] | python | test | 31.491525 |
saulpw/visidata | visidata/canvas.py | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L205-L214 | def rowsWithin(self, bbox):
'return list of deduped rows within bbox'
ret = {}
for y in range(bbox.ymin, bbox.ymax+1):
for x in range(bbox.xmin, bbox.xmax+1):
for attr, rows in self.pixels[y][x].items():
if attr not in self.hiddenAttrs:
... | [
"def",
"rowsWithin",
"(",
"self",
",",
"bbox",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"y",
"in",
"range",
"(",
"bbox",
".",
"ymin",
",",
"bbox",
".",
"ymax",
"+",
"1",
")",
":",
"for",
"x",
"in",
"range",
"(",
"bbox",
".",
"xmin",
",",
"bbox"... | return list of deduped rows within bbox | [
"return",
"list",
"of",
"deduped",
"rows",
"within",
"bbox"
] | python | train | 41.5 |
NUAA-Open-Source/NUAA-iCal-Python | NUAAiCal/AddToGCal.py | https://github.com/NUAA-Open-Source/NUAA-iCal-Python/blob/1bdc4016e4d8b236a12bba5047a5150f889bc880/NUAAiCal/AddToGCal.py#L25-L51 | def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
... | [
"def",
"get_credentials",
"(",
")",
":",
"home_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"credential_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home_dir",
",",
"'.credentials'",
")",
"if",
"not",
"os",
".",
"path",
".",
... | Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential. | [
"Gets",
"valid",
"user",
"credentials",
"from",
"storage",
"."
] | python | train | 39.074074 |
StackStorm/pybind | pybind/nos/v6_0_2f/qos/map_/dscp_mutation/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/qos/map_/dscp_mutation/__init__.py#L131-L152 | def _set_mark(self, v, load=False):
"""
Setter method for mark, mapped from YANG variable /qos/map/dscp_mutation/mark (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mark is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_mark",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for mark, mapped from YANG variable /qos/map/dscp_mutation/mark (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mark is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mark() directly. | [
"Setter",
"method",
"for",
"mark",
"mapped",
"from",
"YANG",
"variable",
"/",
"qos",
"/",
"map",
"/",
"dscp_mutation",
"/",
"mark",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
... | python | train | 113.954545 |
albert12132/templar | templar/markdown.py | https://github.com/albert12132/templar/blob/39851c89730ab69e5c73d0a46adca2a44ecc4165/templar/markdown.py#L564-L605 | def hash_reference_links(text, hashes, markdown_obj):
"""Hashes an <a> link or an <img> link.
This function only converts reference link styles:
[text here][ref id]
![alt text here][ref id]
For inline style links, see hash_inline_links.
Reference ids can be defined anywhere in the Ma... | [
"def",
"hash_reference_links",
"(",
"text",
",",
"hashes",
",",
"markdown_obj",
")",
":",
"def",
"sub",
"(",
"match",
")",
":",
"is_img",
"=",
"match",
".",
"group",
"(",
"1",
")",
"!=",
"''",
"content",
"=",
"match",
".",
"group",
"(",
"2",
")",
"... | Hashes an <a> link or an <img> link.
This function only converts reference link styles:
[text here][ref id]
![alt text here][ref id]
For inline style links, see hash_inline_links.
Reference ids can be defined anywhere in the Markdown text.
Reference ids can also be omitted, in which ... | [
"Hashes",
"an",
"<a",
">",
"link",
"or",
"an",
"<img",
">",
"link",
"."
] | python | train | 33.214286 |
goose3/goose3 | goose3/extractors/content.py | https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/extractors/content.py#L321-L332 | def nodes_to_check(self, docs):
"""\
returns a list of nodes we want to search
on like paragraphs and tables
"""
nodes_to_check = []
for doc in docs:
for tag in ['p', 'pre', 'td']:
items = self.parser.getElementsByTag(doc, tag=tag)
... | [
"def",
"nodes_to_check",
"(",
"self",
",",
"docs",
")",
":",
"nodes_to_check",
"=",
"[",
"]",
"for",
"doc",
"in",
"docs",
":",
"for",
"tag",
"in",
"[",
"'p'",
",",
"'pre'",
",",
"'td'",
"]",
":",
"items",
"=",
"self",
".",
"parser",
".",
"getElemen... | \
returns a list of nodes we want to search
on like paragraphs and tables | [
"\\",
"returns",
"a",
"list",
"of",
"nodes",
"we",
"want",
"to",
"search",
"on",
"like",
"paragraphs",
"and",
"tables"
] | python | valid | 30.583333 |
vladcalin/gemstone | gemstone/core/handlers.py | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/handlers.py#L246-L268 | def prepare_method_call(self, method, args):
"""
Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a ... | [
"def",
"prepare_method_call",
"(",
"self",
",",
"method",
",",
"args",
")",
":",
"if",
"self",
".",
"_method_requires_handler_ref",
"(",
"method",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"list",
")",
":",
"args",
"=",
"[",
"self",
"]",
"+",
"ar... | Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a 'patched' callable | [
"Wraps",
"a",
"method",
"so",
"that",
"method",
"()",
"will",
"call",
"method",
"(",
"*",
"args",
")",
"or",
"method",
"(",
"**",
"args",
")",
"depending",
"of",
"args",
"type"
] | python | train | 37.391304 |
espressif/esptool | ecdsa/numbertheory.py | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L124-L145 | def jacobi( a, n ):
"""Jacobi symbol"""
# Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.
# This function has been tested by comparison with a small
# table printed in HAC, and by extensive use in calculating
# modular square roots.
assert n >= 3
assert n%2 == 1
a = a % n
if a... | [
"def",
"jacobi",
"(",
"a",
",",
"n",
")",
":",
"# Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.",
"# This function has been tested by comparison with a small",
"# table printed in HAC, and by extensive use in calculating",
"# modular square roots.",
"assert",
"n",
... | Jacobi symbol | [
"Jacobi",
"symbol"
] | python | train | 24.818182 |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/json_util.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/json_util.py#L183-L201 | def get_value_for_datastore(self, model_instance):
"""Gets value for datastore.
Args:
model_instance: instance of the model class.
Returns:
datastore-compatible value.
"""
value = super(JsonProperty, self).get_value_for_datastore(model_instance)
if not value:
return None
... | [
"def",
"get_value_for_datastore",
"(",
"self",
",",
"model_instance",
")",
":",
"value",
"=",
"super",
"(",
"JsonProperty",
",",
"self",
")",
".",
"get_value_for_datastore",
"(",
"model_instance",
")",
"if",
"not",
"value",
":",
"return",
"None",
"json_value",
... | Gets value for datastore.
Args:
model_instance: instance of the model class.
Returns:
datastore-compatible value. | [
"Gets",
"value",
"for",
"datastore",
"."
] | python | train | 27.894737 |
apache/airflow | airflow/contrib/hooks/cassandra_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/cassandra_hook.py#L108-L115 | def get_conn(self):
"""
Returns a cassandra Session object
"""
if self.session and not self.session.is_shutdown:
return self.session
self.session = self.cluster.connect(self.keyspace)
return self.session | [
"def",
"get_conn",
"(",
"self",
")",
":",
"if",
"self",
".",
"session",
"and",
"not",
"self",
".",
"session",
".",
"is_shutdown",
":",
"return",
"self",
".",
"session",
"self",
".",
"session",
"=",
"self",
".",
"cluster",
".",
"connect",
"(",
"self",
... | Returns a cassandra Session object | [
"Returns",
"a",
"cassandra",
"Session",
"object"
] | python | test | 32 |
jazzband/django-mongonaut | mongonaut/forms/form_mixins.py | https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/form_mixins.py#L82-L108 | def get_form_field_dict(self, model_dict):
"""
Takes a model dictionary representation and creates a dictionary
keyed by form field. Each value is a keyed 4 tuple of:
(widget, mode_field_instance, model_field_type, field_key)
"""
return_dict = OrderedDict()
# Wo... | [
"def",
"get_form_field_dict",
"(",
"self",
",",
"model_dict",
")",
":",
"return_dict",
"=",
"OrderedDict",
"(",
")",
"# Workaround: mongoengine doesn't preserve form fields ordering from metaclass __new__",
"if",
"hasattr",
"(",
"self",
".",
"model",
",",
"'Meta'",
")",
... | Takes a model dictionary representation and creates a dictionary
keyed by form field. Each value is a keyed 4 tuple of:
(widget, mode_field_instance, model_field_type, field_key) | [
"Takes",
"a",
"model",
"dictionary",
"representation",
"and",
"creates",
"a",
"dictionary",
"keyed",
"by",
"form",
"field",
".",
"Each",
"value",
"is",
"a",
"keyed",
"4",
"tuple",
"of",
":",
"(",
"widget",
"mode_field_instance",
"model_field_type",
"field_key",
... | python | valid | 56.777778 |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/iam/apis/developer_api.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/iam/apis/developer_api.py#L36-L56 | def add_my_api_key_to_groups(self, body, **kwargs): # noqa: E501
"""Add API key to a list of groups. # noqa: E501
An endpoint for adding API key to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586... | [
"def",
"add_my_api_key_to_groups",
"(",
"self",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
... | Add API key to a list of groups. # noqa: E501
An endpoint for adding API key to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f30242590700000000]' -H 'content-type: application/json' -H 'Authorization: B... | [
"Add",
"API",
"key",
"to",
"a",
"list",
"of",
"groups",
".",
"#",
"noqa",
":",
"E501"
] | python | train | 58.904762 |
mozilla-releng/scriptworker | scriptworker/utils.py | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L501-L528 | def read_from_file(path, file_type='text', exception=ScriptWorkerException):
"""Read from ``path``.
Small helper function to read from ``file``.
Args:
path (str): the path to read from.
file_type (str, optional): the type of file. Currently accepts
``text`` or ``binary``. Defau... | [
"def",
"read_from_file",
"(",
"path",
",",
"file_type",
"=",
"'text'",
",",
"exception",
"=",
"ScriptWorkerException",
")",
":",
"FILE_TYPE_MAP",
"=",
"{",
"'text'",
":",
"'r'",
",",
"'binary'",
":",
"'rb'",
"}",
"if",
"file_type",
"not",
"in",
"FILE_TYPE_MA... | Read from ``path``.
Small helper function to read from ``file``.
Args:
path (str): the path to read from.
file_type (str, optional): the type of file. Currently accepts
``text`` or ``binary``. Defaults to ``text``.
exception (Exception, optional): the exception to raise
... | [
"Read",
"from",
"path",
"."
] | python | train | 37.964286 |
boundary/pulse-api-cli | boundary/api_call.py | https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L111-L120 | def method(self, value):
"""
Before assigning the value validate that is in one of the
HTTP methods we implement
"""
keys = self._methods.keys()
if value not in keys:
raise AttributeError("Method value not in " + str(keys))
else:
self._meth... | [
"def",
"method",
"(",
"self",
",",
"value",
")",
":",
"keys",
"=",
"self",
".",
"_methods",
".",
"keys",
"(",
")",
"if",
"value",
"not",
"in",
"keys",
":",
"raise",
"AttributeError",
"(",
"\"Method value not in \"",
"+",
"str",
"(",
"keys",
")",
")",
... | Before assigning the value validate that is in one of the
HTTP methods we implement | [
"Before",
"assigning",
"the",
"value",
"validate",
"that",
"is",
"in",
"one",
"of",
"the",
"HTTP",
"methods",
"we",
"implement"
] | python | test | 32.1 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L5527-L5539 | def createNotification(self, ulOverlayHandle, ulUserValue, type_, pchText, style):
"""
Create a notification and enqueue it to be shown to the user.
An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it.
To create a two-line n... | [
"def",
"createNotification",
"(",
"self",
",",
"ulOverlayHandle",
",",
"ulUserValue",
",",
"type_",
",",
"pchText",
",",
"style",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"createNotification",
"pImage",
"=",
"NotificationBitmap_t",
"(",
")",
"p... | Create a notification and enqueue it to be shown to the user.
An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it.
To create a two-line notification, use a line break ('\n') to split the text into two lines.
The pImage argument may ... | [
"Create",
"a",
"notification",
"and",
"enqueue",
"it",
"to",
"be",
"shown",
"to",
"the",
"user",
".",
"An",
"overlay",
"handle",
"is",
"required",
"to",
"create",
"a",
"notification",
"as",
"otherwise",
"it",
"would",
"be",
"impossible",
"for",
"a",
"user"... | python | train | 61 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L1699-L1716 | def _populate_lp(self, dataset, **kwargs):
"""
Populate columns necessary for an LP dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables`
"""
logger.debug("{}._populate_lp(dataset={})".format(se... | [
"def",
"_populate_lp",
"(",
"self",
",",
"dataset",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}._populate_lp(dataset={})\"",
".",
"format",
"(",
"self",
".",
"component",
",",
"dataset",
")",
")",
"profile_rest",
"=",
"kwargs",
".... | Populate columns necessary for an LP dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables` | [
"Populate",
"columns",
"necessary",
"for",
"an",
"LP",
"dataset"
] | python | train | 35.666667 |
tensorflow/probability | tensorflow_probability/python/internal/distribution_util.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L506-L542 | def pick_scalar_condition(pred, true_value, false_value, name=None):
"""Convenience function that chooses one of two values based on the predicate.
This utility is equivalent to a version of `tf.where` that accepts only a
scalar predicate and computes its result statically when possible. It may also
be used in... | [
"def",
"pick_scalar_condition",
"(",
"pred",
",",
"true_value",
",",
"false_value",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"pick_scalar_condition\"",
")",
":",
"pred",
"=",
"tf",
".",
"convert_to_tensor",
"(... | Convenience function that chooses one of two values based on the predicate.
This utility is equivalent to a version of `tf.where` that accepts only a
scalar predicate and computes its result statically when possible. It may also
be used in place of `tf.cond` when both branches yield a `Tensor` of the same
shap... | [
"Convenience",
"function",
"that",
"chooses",
"one",
"of",
"two",
"values",
"based",
"on",
"the",
"predicate",
"."
] | python | test | 53 |
wimglenn/advent-of-code-data | aocd/get.py | https://github.com/wimglenn/advent-of-code-data/blob/a3856459d225840f2b6919659fc65aa7a6a74533/aocd/get.py#L70-L134 | def get_day_and_year():
"""
Returns tuple (day, year).
Here be dragons!
The correct date is determined with introspection of the call stack, first
finding the filename of the module from which ``aocd`` was imported.
This means your filenames should be something sensible, which identify the
... | [
"def",
"get_day_and_year",
"(",
")",
":",
"pattern_year",
"=",
"r\"201[5-9]|202[0-9]\"",
"pattern_day",
"=",
"r\"2[0-5]|1[0-9]|[1-9]\"",
"stack",
"=",
"[",
"f",
"[",
"0",
"]",
"for",
"f",
"in",
"traceback",
".",
"extract_stack",
"(",
")",
"]",
"for",
"name",
... | Returns tuple (day, year).
Here be dragons!
The correct date is determined with introspection of the call stack, first
finding the filename of the module from which ``aocd`` was imported.
This means your filenames should be something sensible, which identify the
day and year unambiguously. The ex... | [
"Returns",
"tuple",
"(",
"day",
"year",
")",
"."
] | python | train | 39.030769 |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L49-L94 | def search(cls,
query_string,
options=None,
enable_facet_discovery=False,
return_facets=None,
facet_options=None,
facet_refinements=None,
deadline=None,
**kwargs):
"""
Searches the ind... | [
"def",
"search",
"(",
"cls",
",",
"query_string",
",",
"options",
"=",
"None",
",",
"enable_facet_discovery",
"=",
"False",
",",
"return_facets",
"=",
"None",
",",
"facet_options",
"=",
"None",
",",
"facet_refinements",
"=",
"None",
",",
"deadline",
"=",
"No... | Searches the index. Conveniently searches only for documents that belong to instances of this class.
:param query_string: The query to match against documents in the index. See search.Query() for details.
:param options: A QueryOptions describing post-processing of search results.
:param enable... | [
"Searches",
"the",
"index",
".",
"Conveniently",
"searches",
"only",
"for",
"documents",
"that",
"belong",
"to",
"instances",
"of",
"this",
"class",
"."
] | python | train | 52.608696 |
choldgraf/download | download/download.py | https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L137-L232 | def _fetch_file(url, file_name, resume=True,
hash_=None, timeout=10., progressbar=True, verbose=True):
"""Load requested file, downloading it if needed or requested.
Parameters
----------
url: string
The url of file to be downloaded.
file_name: string
Name, along wit... | [
"def",
"_fetch_file",
"(",
"url",
",",
"file_name",
",",
"resume",
"=",
"True",
",",
"hash_",
"=",
"None",
",",
"timeout",
"=",
"10.",
",",
"progressbar",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"# Adapted from NISL and MNE-python:",
"# https://g... | Load requested file, downloading it if needed or requested.
Parameters
----------
url: string
The url of file to be downloaded.
file_name: string
Name, along with the path, of where downloaded file will be saved.
resume: bool, optional
If true, try to resume partially downlo... | [
"Load",
"requested",
"file",
"downloading",
"it",
"if",
"needed",
"or",
"requested",
"."
] | python | train | 42.291667 |
saltstack/salt | salt/modules/pkgng.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgng.py#L2029-L2073 | def list_locked(**kwargs):
'''
Query the package database those packages which are
locked against reinstallation, modification or deletion.
Returns returns a list of package names with version strings
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locked
jail
List l... | [
"def",
"list_locked",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"'{0}-{1}'",
".",
"format",
"(",
"pkgname",
",",
"version",
"(",
"pkgname",
",",
"*",
"*",
"kwargs",
")",
")",
"for",
"pkgname",
"in",
"_lockcmd",
"(",
"'lock'",
",",
"name",
"="... | Query the package database those packages which are
locked against reinstallation, modification or deletion.
Returns returns a list of package names with version strings
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locked
jail
List locked packages within the specified jai... | [
"Query",
"the",
"package",
"database",
"those",
"packages",
"which",
"are",
"locked",
"against",
"reinstallation",
"modification",
"or",
"deletion",
"."
] | python | train | 22.533333 |
Sheeprider/BitBucket-api | bitbucket/repository.py | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/repository.py#L79-L82 | def create(self, repo_name, scm='git', private=True, **kwargs):
""" Creates a new repository on own Bitbucket account and return it."""
url = self.bitbucket.url('CREATE_REPO')
return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, name=repo_name, scm=scm, is_private=private, **kwa... | [
"def",
"create",
"(",
"self",
",",
"repo_name",
",",
"scm",
"=",
"'git'",
",",
"private",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'CREATE_REPO'",
")",
"return",
"self",
".",
"bitbucket",... | Creates a new repository on own Bitbucket account and return it. | [
"Creates",
"a",
"new",
"repository",
"on",
"own",
"Bitbucket",
"account",
"and",
"return",
"it",
"."
] | python | train | 80.25 |
tanghaibao/goatools | goatools/grouper/grprobj_init.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj_init.py#L49-L62 | def _init_usrgos(self, goids):
"""Return user GO IDs which have GO Terms."""
usrgos = set()
goids_missing = set()
_go2obj = self.gosubdag.go2obj
for goid in goids:
if goid in _go2obj:
usrgos.add(goid)
else:
goids_missing.add... | [
"def",
"_init_usrgos",
"(",
"self",
",",
"goids",
")",
":",
"usrgos",
"=",
"set",
"(",
")",
"goids_missing",
"=",
"set",
"(",
")",
"_go2obj",
"=",
"self",
".",
"gosubdag",
".",
"go2obj",
"for",
"goid",
"in",
"goids",
":",
"if",
"goid",
"in",
"_go2obj... | Return user GO IDs which have GO Terms. | [
"Return",
"user",
"GO",
"IDs",
"which",
"have",
"GO",
"Terms",
"."
] | python | train | 37.428571 |
BerkeleyAutomation/perception | perception/image.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L797-L807 | def finite_pixels(self):
""" Return an array of the finite pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the finite pixels
"""
finite_px = np.where(np.isfinite(self.data))
finite_px = np.c_[finite_px[0], finite_px[1]]
return finit... | [
"def",
"finite_pixels",
"(",
"self",
")",
":",
"finite_px",
"=",
"np",
".",
"where",
"(",
"np",
".",
"isfinite",
"(",
"self",
".",
"data",
")",
")",
"finite_px",
"=",
"np",
".",
"c_",
"[",
"finite_px",
"[",
"0",
"]",
",",
"finite_px",
"[",
"1",
"... | Return an array of the finite pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the finite pixels | [
"Return",
"an",
"array",
"of",
"the",
"finite",
"pixels",
"."
] | python | train | 28.545455 |
DigitalGlobe/gbdxtools | gbdxtools/catalog.py | https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/catalog.py#L73-L97 | def get_strip_metadata(self, catID):
'''Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a class object with int... | [
"def",
"get_strip_metadata",
"(",
"self",
",",
"catID",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Retrieving strip catalog metadata'",
")",
"url",
"=",
"'%(base_url)s/record/%(catID)s?includeRelationships=false'",
"%",
"{",
"'base_url'",
":",
"self",
".",
... | Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a class object with interesting information exposed. | [
"Retrieves",
"the",
"strip",
"catalog",
"metadata",
"given",
"a",
"cat",
"ID",
"."
] | python | valid | 36.68 |
mathiasertl/django-ca | ca/django_ca/models.py | https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/models.py#L721-L739 | def max_pathlen(self):
"""The maximum pathlen for any intermediate CAs signed by this CA.
This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an
``int`` if any parent CA has the attribute.
"""
pathlen = self.pathlen
if self.p... | [
"def",
"max_pathlen",
"(",
"self",
")",
":",
"pathlen",
"=",
"self",
".",
"pathlen",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"pathlen",
"max_parent",
"=",
"self",
".",
"parent",
".",
"max_pathlen",
"if",
"max_parent",
"is",
"None",
":",... | The maximum pathlen for any intermediate CAs signed by this CA.
This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an
``int`` if any parent CA has the attribute. | [
"The",
"maximum",
"pathlen",
"for",
"any",
"intermediate",
"CAs",
"signed",
"by",
"this",
"CA",
"."
] | python | train | 30.473684 |
ThreatConnect-Inc/tcex | tcex/tcex_cache.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_cache.py#L36-L48 | def add(self, rid, data, raise_on_error=True):
"""Write cache data to the data store.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
... | [
"def",
"add",
"(",
"self",
",",
"rid",
",",
"data",
",",
"raise_on_error",
"=",
"True",
")",
":",
"cache_data",
"=",
"{",
"'cache-date'",
":",
"self",
".",
"_dt_to_epoch",
"(",
"datetime",
".",
"now",
"(",
")",
")",
",",
"'cache-data'",
":",
"data",
... | Write cache data to the data store.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response. | [
"Write",
"cache",
"data",
"to",
"the",
"data",
"store",
"."
] | python | train | 39 |
hydpy-dev/hydpy | hydpy/exe/servertools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/exe/servertools.py#L933-L940 | def GET_close_server(self) -> None:
"""Stop and close the *HydPy* server."""
def _close_server():
self.server.shutdown()
self.server.server_close()
shutter = threading.Thread(target=_close_server)
shutter.deamon = True
shutter.start() | [
"def",
"GET_close_server",
"(",
"self",
")",
"->",
"None",
":",
"def",
"_close_server",
"(",
")",
":",
"self",
".",
"server",
".",
"shutdown",
"(",
")",
"self",
".",
"server",
".",
"server_close",
"(",
")",
"shutter",
"=",
"threading",
".",
"Thread",
"... | Stop and close the *HydPy* server. | [
"Stop",
"and",
"close",
"the",
"*",
"HydPy",
"*",
"server",
"."
] | python | train | 36.375 |
saltstack/salt | salt/modules/smartos_vmadm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_vmadm.py#L492-L532 | def info(vm, info_type='all', key='uuid'):
'''
Lookup info on running kvm
vm : string
vm to be targeted
info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc]
info type to return
key : string [uuid|alias|hostname]
value type of 'vm' parameter
C... | [
"def",
"info",
"(",
"vm",
",",
"info_type",
"=",
"'all'",
",",
"key",
"=",
"'uuid'",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"info_type",
"not",
"in",
"[",
"'all'",
",",
"'block'",
",",
"'blockstats'",
",",
"'chardev'",
",",
"'cpus'",
",",
"'kvm'",
"... | Lookup info on running kvm
vm : string
vm to be targeted
info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc]
info type to return
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*'... | [
"Lookup",
"info",
"on",
"running",
"kvm"
] | python | train | 33.02439 |
viveksck/changepoint | changepoint/mean_shift_model.py | https://github.com/viveksck/changepoint/blob/001792cb148c991ec704463d3213997ebb7171af/changepoint/mean_shift_model.py#L20-L25 | def get_ts_stats_significance(self, x, ts, stat_ts_func, null_ts_func, B=1000, permute_fast=False, label_ts=''):
""" Returns the statistics, pvalues and the actual number of bootstrap
samples. """
stats_ts, pvals, nums = ts_stats_significance(
ts, stat_ts_func, null_ts_func, B=B,... | [
"def",
"get_ts_stats_significance",
"(",
"self",
",",
"x",
",",
"ts",
",",
"stat_ts_func",
",",
"null_ts_func",
",",
"B",
"=",
"1000",
",",
"permute_fast",
"=",
"False",
",",
"label_ts",
"=",
"''",
")",
":",
"stats_ts",
",",
"pvals",
",",
"nums",
"=",
... | Returns the statistics, pvalues and the actual number of bootstrap
samples. | [
"Returns",
"the",
"statistics",
"pvalues",
"and",
"the",
"actual",
"number",
"of",
"bootstrap",
"samples",
"."
] | python | train | 63.166667 |
vertexproject/synapse | synapse/glob.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/glob.py#L82-L115 | def synchelp(f):
'''
The synchelp decorator allows the transparent execution of
a coroutine using the global loop from a thread other than
the event loop. In both use cases, teh actual work is done
by the global event loop.
Examples:
Use as a decorator::
@s_glob.synchelp
... | [
"def",
"synchelp",
"(",
"f",
")",
":",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"coro",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"iAmLoop",
"(",
")",
":",
"return",
"sync",
"(",
"coro",... | The synchelp decorator allows the transparent execution of
a coroutine using the global loop from a thread other than
the event loop. In both use cases, teh actual work is done
by the global event loop.
Examples:
Use as a decorator::
@s_glob.synchelp
async def stuff(x... | [
"The",
"synchelp",
"decorator",
"allows",
"the",
"transparent",
"execution",
"of",
"a",
"coroutine",
"using",
"the",
"global",
"loop",
"from",
"a",
"thread",
"other",
"than",
"the",
"event",
"loop",
".",
"In",
"both",
"use",
"cases",
"teh",
"actual",
"work",... | python | train | 22.852941 |
bokeh/bokeh | bokeh/server/views/ws.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L194-L230 | def on_message(self, fragment):
''' Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames
from binary frames. Tornado passes us either a text or binary string
depending on that opcode, we have to look at the type of the fragment... | [
"def",
"on_message",
"(",
"self",
",",
"fragment",
")",
":",
"# We shouldn't throw exceptions from on_message because the caller is",
"# just Tornado and it doesn't know what to do with them other than",
"# report them as an unhandled Future",
"try",
":",
"message",
"=",
"yield",
"se... | Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames
from binary frames. Tornado passes us either a text or binary string
depending on that opcode, we have to look at the type of the fragment
to see what we got.
Args:
... | [
"Process",
"an",
"individual",
"wire",
"protocol",
"fragment",
"."
] | python | train | 40.918919 |
radujica/baloo | baloo/weld/weld_utils.py | https://github.com/radujica/baloo/blob/f6e05e35b73a75e8a300754c6bdc575e5f2d53b9/baloo/weld/weld_utils.py#L182-L211 | def weld_combine_scalars(scalars, weld_type):
"""Combine column-wise aggregations (so resulting scalars) into a single array.
Parameters
----------
scalars : tuple of WeldObjects
WeldObjects to combine.
weld_type : WeldType
The Weld type of the result. Currently expecting scalars to... | [
"def",
"weld_combine_scalars",
"(",
"scalars",
",",
"weld_type",
")",
":",
"weld_obj",
"=",
"create_empty_weld_object",
"(",
")",
"obj_ids",
"=",
"(",
"get_weld_obj_id",
"(",
"weld_obj",
",",
"scalar",
")",
"for",
"scalar",
"in",
"scalars",
")",
"merges",
"=",... | Combine column-wise aggregations (so resulting scalars) into a single array.
Parameters
----------
scalars : tuple of WeldObjects
WeldObjects to combine.
weld_type : WeldType
The Weld type of the result. Currently expecting scalars to be of the same type.
Returns
-------
We... | [
"Combine",
"column",
"-",
"wise",
"aggregations",
"(",
"so",
"resulting",
"scalars",
")",
"into",
"a",
"single",
"array",
"."
] | python | train | 27.766667 |
Tanganelli/CoAPthon3 | coapthon/layers/cachelayer.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/cachelayer.py#L57-L70 | def send_response(self, transaction):
"""
updates the cache with the response if there was a cache miss
:param transaction:
:return:
"""
if transaction.cacheHit is False:
"""
handling response based on the code
"""
logger.d... | [
"def",
"send_response",
"(",
"self",
",",
"transaction",
")",
":",
"if",
"transaction",
".",
"cacheHit",
"is",
"False",
":",
"\"\"\"\n handling response based on the code\n \"\"\"",
"logger",
".",
"debug",
"(",
"\"handling response\"",
")",
"self",
... | updates the cache with the response if there was a cache miss
:param transaction:
:return: | [
"updates",
"the",
"cache",
"with",
"the",
"response",
"if",
"there",
"was",
"a",
"cache",
"miss"
] | python | train | 29 |
angr/angr | angr/calling_conventions.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/calling_conventions.py#L467-L483 | def arg(self, state, index, stack_base=None):
"""
Returns a bitvector expression representing the nth argument of a function.
`stack_base` is an optional pointer to the top of the stack at the function start. If it is not
specified, use the current stack pointer.
WARNING: this ... | [
"def",
"arg",
"(",
"self",
",",
"state",
",",
"index",
",",
"stack_base",
"=",
"None",
")",
":",
"session",
"=",
"self",
".",
"arg_session",
"if",
"self",
".",
"args",
"is",
"None",
":",
"arg_loc",
"=",
"[",
"session",
".",
"next_arg",
"(",
"False",
... | Returns a bitvector expression representing the nth argument of a function.
`stack_base` is an optional pointer to the top of the stack at the function start. If it is not
specified, use the current stack pointer.
WARNING: this assumes that none of the arguments are floating-point and they're ... | [
"Returns",
"a",
"bitvector",
"expression",
"representing",
"the",
"nth",
"argument",
"of",
"a",
"function",
"."
] | python | train | 41.529412 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1464-L1488 | def UpsertStoredProcedure(self, collection_link, sproc, options=None):
"""Upserts a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
... | [
"def",
"UpsertStoredProcedure",
"(",
"self",
",",
"collection_link",
",",
"sproc",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"collection_id",
",",
"path",
",",
"sproc",
"=",
"self",
".",
"_GetCon... | Upserts a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:
The upserted Stored Procedure.
:rtype:
... | [
"Upserts",
"a",
"stored",
"procedure",
"in",
"a",
"collection",
"."
] | python | train | 30.6 |
google/identity-toolkit-python-client | identitytoolkit/gitkitclient.py | https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L343-L390 | def GetOobResult(self, param, user_ip, gitkit_token=None):
"""Gets out-of-band code for ResetPassword/ChangeEmail request.
Args:
param: dict of HTTP POST params
user_ip: string, end user's IP address
gitkit_token: string, the gitkit token if user logged in
Returns:
A dict of {
... | [
"def",
"GetOobResult",
"(",
"self",
",",
"param",
",",
"user_ip",
",",
"gitkit_token",
"=",
"None",
")",
":",
"if",
"'action'",
"in",
"param",
":",
"try",
":",
"if",
"param",
"[",
"'action'",
"]",
"==",
"GitkitClient",
".",
"RESET_PASSWORD_ACTION",
":",
... | Gets out-of-band code for ResetPassword/ChangeEmail request.
Args:
param: dict of HTTP POST params
user_ip: string, end user's IP address
gitkit_token: string, the gitkit token if user logged in
Returns:
A dict of {
email: user email who initializes the request
new_emai... | [
"Gets",
"out",
"-",
"of",
"-",
"band",
"code",
"for",
"ResetPassword",
"/",
"ChangeEmail",
"request",
"."
] | python | train | 42.041667 |
robotframework/Rammbock | src/Rammbock/core.py | https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L136-L147 | def reset_rammbock(self):
"""Closes all connections, deletes all servers, clients, and protocols.
You should call this method before exiting your test run. This will
close all the connections and the ports will therefore be available for
reuse faster.
"""
for client in s... | [
"def",
"reset_rammbock",
"(",
"self",
")",
":",
"for",
"client",
"in",
"self",
".",
"_clients",
":",
"client",
".",
"close",
"(",
")",
"for",
"server",
"in",
"self",
".",
"_servers",
":",
"server",
".",
"close",
"(",
")",
"self",
".",
"_init_caches",
... | Closes all connections, deletes all servers, clients, and protocols.
You should call this method before exiting your test run. This will
close all the connections and the ports will therefore be available for
reuse faster. | [
"Closes",
"all",
"connections",
"deletes",
"all",
"servers",
"clients",
"and",
"protocols",
"."
] | python | train | 36.75 |
bcbio/bcbio-nextgen | bcbio/variation/vardict.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vardict.py#L295-L360 | def _run_vardict_paired(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Detect variants with Vardict.
This is used for paired tumor / normal samples.
"""
config = items[0]["config"]
if out_file is None:
out_file = "%s-paired-variants.vcf.g... | [
"def",
"_run_vardict_paired",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"if",
"out_file",
"is",... | Detect variants with Vardict.
This is used for paired tumor / normal samples. | [
"Detect",
"variants",
"with",
"Vardict",
"."
] | python | train | 66.984848 |
Kortemme-Lab/klab | klab/deprecated/rosettadb.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/deprecated/rosettadb.py#L109-L111 | def locked_execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False):
'''We are lock-happy here but SQL performance is not currently an issue daemon-side.'''
return self.execute(sql, parameters, cursorClass, quiet = quiet, locked = True) | [
"def",
"locked_execute",
"(",
"self",
",",
"sql",
",",
"parameters",
"=",
"None",
",",
"cursorClass",
"=",
"DictCursor",
",",
"quiet",
"=",
"False",
")",
":",
"return",
"self",
".",
"execute",
"(",
"sql",
",",
"parameters",
",",
"cursorClass",
",",
"quie... | We are lock-happy here but SQL performance is not currently an issue daemon-side. | [
"We",
"are",
"lock",
"-",
"happy",
"here",
"but",
"SQL",
"performance",
"is",
"not",
"currently",
"an",
"issue",
"daemon",
"-",
"side",
"."
] | python | train | 87 |
ome/omego | omego/upgrade.py | https://github.com/ome/omego/blob/2dadbf3c6342b6c995f9e0dceaf3c0b7fab030fb/omego/upgrade.py#L75-L132 | def _handle_args(self, cmd, args):
"""
We need to support deprecated behaviour for now which makes this
quite complicated
Current behaviour:
- install: Installs a new server, existing server causes an error
- install --upgrade: Installs or upgrades a server
- ins... | [
"def",
"_handle_args",
"(",
"self",
",",
"cmd",
",",
"args",
")",
":",
"if",
"cmd",
"==",
"'install'",
":",
"if",
"args",
".",
"upgrade",
":",
"# Current behaviour: install or upgrade",
"if",
"args",
".",
"initdb",
"or",
"args",
".",
"upgradedb",
":",
"rai... | We need to support deprecated behaviour for now which makes this
quite complicated
Current behaviour:
- install: Installs a new server, existing server causes an error
- install --upgrade: Installs or upgrades a server
- install --managedb: Automatically initialise or upgrade th... | [
"We",
"need",
"to",
"support",
"deprecated",
"behaviour",
"for",
"now",
"which",
"makes",
"this",
"quite",
"complicated"
] | python | train | 37.482759 |
pecan/pecan | pecan/commands/serve.py | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/serve.py#L213-L229 | def log_message(self, format, *args):
"""
overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
warnin... | [
"def",
"log_message",
"(",
"self",
",",
"format",
",",
"*",
"args",
")",
":",
"code",
"=",
"args",
"[",
"1",
"]",
"[",
"0",
"]",
"levels",
"=",
"{",
"'4'",
":",
"'warning'",
",",
"'5'",
":",
"'error'",
"}",
"log_handler",
"=",
"getattr",
"(",
"lo... | overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
warnings, 5XX as errors and everything else as INFO level. | [
"overrides",
"the",
"log_message",
"method",
"from",
"the",
"wsgiref",
"server",
"so",
"that",
"normal",
"logging",
"works",
"with",
"whatever",
"configuration",
"the",
"application",
"has",
"been",
"set",
"to",
"."
] | python | train | 33.882353 |
ethereum/py-evm | eth/chains/base.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L671-L683 | def get_transaction_result(
self,
transaction: BaseOrSpoofTransaction,
at_header: BlockHeader) -> bytes:
"""
Return the result of running the given transaction.
This is referred to as a `call()` in web3.
"""
with self.get_vm(at_header).state_in... | [
"def",
"get_transaction_result",
"(",
"self",
",",
"transaction",
":",
"BaseOrSpoofTransaction",
",",
"at_header",
":",
"BlockHeader",
")",
"->",
"bytes",
":",
"with",
"self",
".",
"get_vm",
"(",
"at_header",
")",
".",
"state_in_temp_block",
"(",
")",
"as",
"s... | Return the result of running the given transaction.
This is referred to as a `call()` in web3. | [
"Return",
"the",
"result",
"of",
"running",
"the",
"given",
"transaction",
".",
"This",
"is",
"referred",
"to",
"as",
"a",
"call",
"()",
"in",
"web3",
"."
] | python | train | 36.692308 |
log2timeline/plaso | plaso/cli/storage_media_tool.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/storage_media_tool.py#L945-L959 | def _ScanFileSystem(self, scan_node, base_path_specs):
"""Scans a file system scan node for file systems.
Args:
scan_node (SourceScanNode): file system scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
SourceScannerError: if the scan node is inval... | [
"def",
"_ScanFileSystem",
"(",
"self",
",",
"scan_node",
",",
"base_path_specs",
")",
":",
"if",
"not",
"scan_node",
"or",
"not",
"scan_node",
".",
"path_spec",
":",
"raise",
"errors",
".",
"SourceScannerError",
"(",
"'Invalid or missing file system scan node.'",
")... | Scans a file system scan node for file systems.
Args:
scan_node (SourceScanNode): file system scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
SourceScannerError: if the scan node is invalid. | [
"Scans",
"a",
"file",
"system",
"scan",
"node",
"for",
"file",
"systems",
"."
] | python | train | 33.933333 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/decoders/parser_csv.py | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/decoders/parser_csv.py#L45-L94 | def decode(data):
"""
Handles decoding of the CSV `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data.
"""
# try to guess dialect of the csv file
dialect = None
try:
dialect = csv.Sniffer().sniff(data)
except Exc... | [
"def",
"decode",
"(",
"data",
")",
":",
"# try to guess dialect of the csv file",
"dialect",
"=",
"None",
"try",
":",
"dialect",
"=",
"csv",
".",
"Sniffer",
"(",
")",
".",
"sniff",
"(",
"data",
")",
"except",
"Exception",
":",
"pass",
"# parse data with csv pa... | Handles decoding of the CSV `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data. | [
"Handles",
"decoding",
"of",
"the",
"CSV",
"data",
"."
] | python | train | 26.76 |
nickjj/ansigenome | ansigenome/export.py | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/export.py#L258-L266 | def dump(self):
"""
Dump the output to json.
"""
report_as_json_string = utils.dict_to_json(self.report)
if self.out_file:
utils.string_to_file(self.out_file, report_as_json_string)
else:
print report_as_json_string | [
"def",
"dump",
"(",
"self",
")",
":",
"report_as_json_string",
"=",
"utils",
".",
"dict_to_json",
"(",
"self",
".",
"report",
")",
"if",
"self",
".",
"out_file",
":",
"utils",
".",
"string_to_file",
"(",
"self",
".",
"out_file",
",",
"report_as_json_string",... | Dump the output to json. | [
"Dump",
"the",
"output",
"to",
"json",
"."
] | python | train | 31 |
grangier/python-goose | goose/extractors/content.py | https://github.com/grangier/python-goose/blob/09023ec9f5ef26a628a2365616c0a7c864f0ecea/goose/extractors/content.py#L224-L250 | def get_siblings_score(self, top_node):
"""\
we could have long articles that have tons of paragraphs
so if we tried to calculate the base score against
the total text score of those paragraphs it would be unfair.
So we need to normalize the score based on the average scoring
... | [
"def",
"get_siblings_score",
"(",
"self",
",",
"top_node",
")",
":",
"base",
"=",
"100000",
"paragraphs_number",
"=",
"0",
"paragraphs_score",
"=",
"0",
"nodes_to_check",
"=",
"self",
".",
"parser",
".",
"getElementsByTag",
"(",
"top_node",
",",
"tag",
"=",
... | \
we could have long articles that have tons of paragraphs
so if we tried to calculate the base score against
the total text score of those paragraphs it would be unfair.
So we need to normalize the score based on the average scoring
of the paragraphs within the top node.
... | [
"\\",
"we",
"could",
"have",
"long",
"articles",
"that",
"have",
"tons",
"of",
"paragraphs",
"so",
"if",
"we",
"tried",
"to",
"calculate",
"the",
"base",
"score",
"against",
"the",
"total",
"text",
"score",
"of",
"those",
"paragraphs",
"it",
"would",
"be",... | python | train | 44.259259 |
scanny/python-pptx | pptx/parts/presentation.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/parts/presentation.py#L131-L139 | def _next_slide_partname(self):
"""
Return |PackURI| instance containing the partname for a slide to be
appended to this slide collection, e.g. ``/ppt/slides/slide9.xml``
for a slide collection containing 8 slides.
"""
sldIdLst = self._element.get_or_add_sldIdLst()
... | [
"def",
"_next_slide_partname",
"(",
"self",
")",
":",
"sldIdLst",
"=",
"self",
".",
"_element",
".",
"get_or_add_sldIdLst",
"(",
")",
"partname_str",
"=",
"'/ppt/slides/slide%d.xml'",
"%",
"(",
"len",
"(",
"sldIdLst",
")",
"+",
"1",
")",
"return",
"PackURI",
... | Return |PackURI| instance containing the partname for a slide to be
appended to this slide collection, e.g. ``/ppt/slides/slide9.xml``
for a slide collection containing 8 slides. | [
"Return",
"|PackURI|",
"instance",
"containing",
"the",
"partname",
"for",
"a",
"slide",
"to",
"be",
"appended",
"to",
"this",
"slide",
"collection",
"e",
".",
"g",
".",
"/",
"ppt",
"/",
"slides",
"/",
"slide9",
".",
"xml",
"for",
"a",
"slide",
"collecti... | python | train | 45.666667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.