repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
cocaine/cocaine-tools | cocaine/tools/dispatch.py | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L579-L645 | def metrics(ty, query, query_type, **kwargs):
"""
Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters, meters and... | [
"def",
"metrics",
"(",
"ty",
",",
"query",
",",
"query_type",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'metrics'",
",",
"*",
"*",
"{",
"'metrics'",
":",
"ctx",
".",
... | Outputs runtime metrics collected from cocaine-runtime and its services.
This command shows runtime metrics collected from cocaine-runtime and its services during their
lifetime.
There are four kind of metrics available: gauges, counters, meters and timers.
\b
- Gauges - an instantaneous measure... | [
"Outputs",
"runtime",
"metrics",
"collected",
"from",
"cocaine",
"-",
"runtime",
"and",
"its",
"services",
"."
] | python | train |
twisted/epsilon | epsilon/ampauth.py | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L275-L301 | def login(client, credentials):
"""
Authenticate using the given L{AMP} instance. The protocol must be
connected to a server with responders for L{PasswordLogin} and
L{PasswordChallengeResponse}.
@param client: A connected L{AMP} instance which will be used to issue
authentication commands... | [
"def",
"login",
"(",
"client",
",",
"credentials",
")",
":",
"if",
"not",
"IUsernamePassword",
".",
"providedBy",
"(",
"credentials",
")",
":",
"raise",
"UnhandledCredentials",
"(",
")",
"d",
"=",
"client",
".",
"callRemote",
"(",
"PasswordLogin",
",",
"user... | Authenticate using the given L{AMP} instance. The protocol must be
connected to a server with responders for L{PasswordLogin} and
L{PasswordChallengeResponse}.
@param client: A connected L{AMP} instance which will be used to issue
authentication commands.
@param credentials: An object providi... | [
"Authenticate",
"using",
"the",
"given",
"L",
"{",
"AMP",
"}",
"instance",
".",
"The",
"protocol",
"must",
"be",
"connected",
"to",
"a",
"server",
"with",
"responders",
"for",
"L",
"{",
"PasswordLogin",
"}",
"and",
"L",
"{",
"PasswordChallengeResponse",
"}",... | python | train |
tanghaibao/jcvi | jcvi/formats/gff.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/gff.py#L482-L488 | def _fasta_slice(fasta, seqid, start, stop, strand):
"""
Return slice of fasta, given (seqid, start, stop, strand)
"""
_strand = 1 if strand == '+' else -1
return fasta.sequence({'chr': seqid, 'start': start, 'stop': stop, \
'strand': _strand}) | [
"def",
"_fasta_slice",
"(",
"fasta",
",",
"seqid",
",",
"start",
",",
"stop",
",",
"strand",
")",
":",
"_strand",
"=",
"1",
"if",
"strand",
"==",
"'+'",
"else",
"-",
"1",
"return",
"fasta",
".",
"sequence",
"(",
"{",
"'chr'",
":",
"seqid",
",",
"'s... | Return slice of fasta, given (seqid, start, stop, strand) | [
"Return",
"slice",
"of",
"fasta",
"given",
"(",
"seqid",
"start",
"stop",
"strand",
")"
] | python | train |
svven/summary | summary/request.py | https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/request.py#L11-L25 | def get(url, **kwargs):
"""
Wrapper for `request.get` function to set params.
"""
headers = kwargs.get('headers', {})
headers['User-Agent'] = config.USER_AGENT # overwrite
kwargs['headers'] = headers
timeout = kwargs.get('timeout', config.TIMEOUT)
kwargs['timeout'] = timeout
kwargs... | [
"def",
"get",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"{",
"}",
")",
"headers",
"[",
"'User-Agent'",
"]",
"=",
"config",
".",
"USER_AGENT",
"# overwrite",
"kwargs",
"[",
"'headers'",
... | Wrapper for `request.get` function to set params. | [
"Wrapper",
"for",
"request",
".",
"get",
"function",
"to",
"set",
"params",
"."
] | python | train |
Becksteinlab/GromacsWrapper | gromacs/utilities.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L662-L672 | def iterable(obj):
"""Returns ``True`` if *obj* can be iterated over and is *not* a string."""
if isinstance(obj, string_types):
return False # avoid iterating over characters of a string
if hasattr(obj, 'next'):
return True # any iterator will do
try:
len(obj) # any... | [
"def",
"iterable",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"return",
"False",
"# avoid iterating over characters of a string",
"if",
"hasattr",
"(",
"obj",
",",
"'next'",
")",
":",
"return",
"True",
"# any iterator wi... | Returns ``True`` if *obj* can be iterated over and is *not* a string. | [
"Returns",
"True",
"if",
"*",
"obj",
"*",
"can",
"be",
"iterated",
"over",
"and",
"is",
"*",
"not",
"*",
"a",
"string",
"."
] | python | valid |
dead-beef/markovchain | markovchain/base.py | https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/base.py#L132-L145 | def from_storage(cls, storage):
"""Load from storage.
Parameters
----------
storage : `markovchain.storage.Storage`
Returns
-------
`markovchain.Markov`
"""
args = dict(storage.settings.get('markov', {}))
args['storage'] = storage
... | [
"def",
"from_storage",
"(",
"cls",
",",
"storage",
")",
":",
"args",
"=",
"dict",
"(",
"storage",
".",
"settings",
".",
"get",
"(",
"'markov'",
",",
"{",
"}",
")",
")",
"args",
"[",
"'storage'",
"]",
"=",
"storage",
"return",
"cls",
"(",
"*",
"*",
... | Load from storage.
Parameters
----------
storage : `markovchain.storage.Storage`
Returns
-------
`markovchain.Markov` | [
"Load",
"from",
"storage",
"."
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L10381-L10401 | def command_int_send(self, target_system, target_component, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, force_mavlink1=False):
'''
Message encoding a command with parameters as scaled integers. Scaling
depends on the actual command valu... | [
"def",
"command_int_send",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"frame",
",",
"command",
",",
"current",
",",
"autocontinue",
",",
"param1",
",",
"param2",
",",
"param3",
",",
"param4",
",",
"x",
",",
"y",
",",
"z",
",",
"forc... | Message encoding a command with parameters as scaled integers. Scaling
depends on the actual command value.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
frame : The coordinate syste... | [
"Message",
"encoding",
"a",
"command",
"with",
"parameters",
"as",
"scaled",
"integers",
".",
"Scaling",
"depends",
"on",
"the",
"actual",
"command",
"value",
"."
] | python | train |
dhermes/bezier | docs/make_images.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L797-L836 | def classify_intersection1(s, curve1, tangent1, curve2, tangent2):
"""Image for :func:`._surface_helpers.classify_intersection` docstring."""
if NO_IMAGES:
return
surface1 = bezier.Surface.from_nodes(
np.asfortranarray(
[[1.0, 1.75, 2.0, 1.0, 1.5, 1.0], [0.0, 0.25, 1.0, 1.0, 1.5... | [
"def",
"classify_intersection1",
"(",
"s",
",",
"curve1",
",",
"tangent1",
",",
"curve2",
",",
"tangent2",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"surface1",
"=",
"bezier",
".",
"Surface",
".",
"from_nodes",
"(",
"np",
".",
"asfortranarray",
"(",
"[",... | Image for :func:`._surface_helpers.classify_intersection` docstring. | [
"Image",
"for",
":",
"func",
":",
".",
"_surface_helpers",
".",
"classify_intersection",
"docstring",
"."
] | python | train |
apriha/lineage | src/lineage/resources.py | https://github.com/apriha/lineage/blob/13106a62a959a80ac26c68d1566422de08aa877b/src/lineage/resources.py#L156-L238 | def download_example_datasets(self):
""" Download example datasets from `openSNP <https://opensnp.org>`_.
Per openSNP, "the data is donated into the public domain using `CC0 1.0
<http://creativecommons.org/publicdomain/zero/1.0/>`_."
Returns
-------
paths : list of str ... | [
"def",
"download_example_datasets",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"paths",
".",
"append",
"(",
"self",
".",
"_download_file",
"(",
"\"https://opensnp.org/data/662.23andme.304\"",
",",
"\"662.23andme.304.txt.gz\"",
",",
"compress",
"=",
"True",
",",
... | Download example datasets from `openSNP <https://opensnp.org>`_.
Per openSNP, "the data is donated into the public domain using `CC0 1.0
<http://creativecommons.org/publicdomain/zero/1.0/>`_."
Returns
-------
paths : list of str or None
paths to example datasets
... | [
"Download",
"example",
"datasets",
"from",
"openSNP",
"<https",
":",
"//",
"opensnp",
".",
"org",
">",
"_",
"."
] | python | train |
coldfix/udiskie | udiskie/prompt.py | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/prompt.py#L160-L168 | async def get_password_tty(device, options):
"""Get the password to unlock a device from terminal."""
# TODO: make this a TRUE async
text = _('Enter password for {0.device_presentation}: ', device)
try:
return getpass.getpass(text)
except EOFError:
print("")
return None | [
"async",
"def",
"get_password_tty",
"(",
"device",
",",
"options",
")",
":",
"# TODO: make this a TRUE async",
"text",
"=",
"_",
"(",
"'Enter password for {0.device_presentation}: '",
",",
"device",
")",
"try",
":",
"return",
"getpass",
".",
"getpass",
"(",
"text",
... | Get the password to unlock a device from terminal. | [
"Get",
"the",
"password",
"to",
"unlock",
"a",
"device",
"from",
"terminal",
"."
] | python | train |
lyst/lightfm | lightfm/datasets/movielens.py | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/datasets/movielens.py#L12-L23 | def _read_raw_data(path):
"""
Return the raw lines of the train and test files.
"""
with zipfile.ZipFile(path) as datafile:
return (
datafile.read("ml-100k/ua.base").decode().split("\n"),
datafile.read("ml-100k/ua.test").decode().split("\n"),
datafile.read("m... | [
"def",
"_read_raw_data",
"(",
"path",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"as",
"datafile",
":",
"return",
"(",
"datafile",
".",
"read",
"(",
"\"ml-100k/ua.base\"",
")",
".",
"decode",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
... | Return the raw lines of the train and test files. | [
"Return",
"the",
"raw",
"lines",
"of",
"the",
"train",
"and",
"test",
"files",
"."
] | python | train |
icometrix/dicom2nifti | dicom2nifti/common.py | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L478-L492 | def write_bvec_file(bvecs, bvec_file):
"""
Write an array of bvecs to a bvec file
:param bvecs: array with the vectors
:param bvec_file: filepath to write to
"""
if bvec_file is None:
return
logger.info('Saving BVEC file: %s' % bvec_file)
with open(bvec_file, 'w') as text_file:
... | [
"def",
"write_bvec_file",
"(",
"bvecs",
",",
"bvec_file",
")",
":",
"if",
"bvec_file",
"is",
"None",
":",
"return",
"logger",
".",
"info",
"(",
"'Saving BVEC file: %s'",
"%",
"bvec_file",
")",
"with",
"open",
"(",
"bvec_file",
",",
"'w'",
")",
"as",
"text_... | Write an array of bvecs to a bvec file
:param bvecs: array with the vectors
:param bvec_file: filepath to write to | [
"Write",
"an",
"array",
"of",
"bvecs",
"to",
"a",
"bvec",
"file"
] | python | train |
tcalmant/ipopo | pelix/remote/beans.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L830-L848 | def format_specifications(specifications):
# type: (Iterable[str]) -> List[str]
"""
Transforms the interfaces names into URI strings, with the interface
implementation language as a scheme.
:param specifications: Specifications to transform
:return: The transformed names
"""
transformed... | [
"def",
"format_specifications",
"(",
"specifications",
")",
":",
"# type: (Iterable[str]) -> List[str]",
"transformed",
"=",
"set",
"(",
")",
"for",
"original",
"in",
"specifications",
":",
"try",
":",
"lang",
",",
"spec",
"=",
"_extract_specification_parts",
"(",
"... | Transforms the interfaces names into URI strings, with the interface
implementation language as a scheme.
:param specifications: Specifications to transform
:return: The transformed names | [
"Transforms",
"the",
"interfaces",
"names",
"into",
"URI",
"strings",
"with",
"the",
"interface",
"implementation",
"language",
"as",
"a",
"scheme",
"."
] | python | train |
jjgomera/iapws | iapws/_utils.py | https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/_utils.py#L194-L261 | def deriv_G(state, z, x, y, fase):
r"""Calculate generic partial derivative
:math:`\left.\frac{\partial z}{\partial x}\right|_{y}` from a fundamental
Gibbs free energy equation of state
Parameters
----------
state : any python object
Only need to define P and T properties, non phase spe... | [
"def",
"deriv_G",
"(",
"state",
",",
"z",
",",
"x",
",",
"y",
",",
"fase",
")",
":",
"mul",
"=",
"1",
"if",
"z",
"==",
"\"rho\"",
":",
"mul",
"=",
"-",
"fase",
".",
"rho",
"**",
"2",
"z",
"=",
"\"v\"",
"if",
"x",
"==",
"\"rho\"",
":",
"mul"... | r"""Calculate generic partial derivative
:math:`\left.\frac{\partial z}{\partial x}\right|_{y}` from a fundamental
Gibbs free energy equation of state
Parameters
----------
state : any python object
Only need to define P and T properties, non phase specific properties
z : str
Na... | [
"r",
"Calculate",
"generic",
"partial",
"derivative",
":",
"math",
":",
"\\",
"left",
".",
"\\",
"frac",
"{",
"\\",
"partial",
"z",
"}",
"{",
"\\",
"partial",
"x",
"}",
"\\",
"right|_",
"{",
"y",
"}",
"from",
"a",
"fundamental",
"Gibbs",
"free",
"ene... | python | train |
ewels/MultiQC | multiqc/plots/linegraph.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/plots/linegraph.py#L40-L161 | def plot (data, pconfig=None):
""" Plot a line graph with X,Y data.
:param data: 2D dict, first keys as sample names, then x:y data pairs
:param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md
:return: HTML and JS, ready to be inserted into the page
"""
# Don't just use {... | [
"def",
"plot",
"(",
"data",
",",
"pconfig",
"=",
"None",
")",
":",
"# Don't just use {} as the default argument as it's mutable. See:",
"# http://python-guide-pt-br.readthedocs.io/en/latest/writing/gotchas/",
"if",
"pconfig",
"is",
"None",
":",
"pconfig",
"=",
"{",
"}",
"# ... | Plot a line graph with X,Y data.
:param data: 2D dict, first keys as sample names, then x:y data pairs
:param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md
:return: HTML and JS, ready to be inserted into the page | [
"Plot",
"a",
"line",
"graph",
"with",
"X",
"Y",
"data",
".",
":",
"param",
"data",
":",
"2D",
"dict",
"first",
"keys",
"as",
"sample",
"names",
"then",
"x",
":",
"y",
"data",
"pairs",
":",
"param",
"pconfig",
":",
"optional",
"dict",
"with",
"config"... | python | train |
razor-x/scipy-data_fitting | scipy_data_fitting/model.py | https://github.com/razor-x/scipy-data_fitting/blob/c756a645da8629699b3f22244bfb7d5d4d88b179/scipy_data_fitting/model.py#L135-L184 | def replace(self, expression, replacements):
"""
All purpose method to reduce an expression by applying
successive replacement rules.
`expression` is either a SymPy expression
or a key in `scipy_data_fitting.Model.expressions`.
`replacements` can be any of the following... | [
"def",
"replace",
"(",
"self",
",",
"expression",
",",
"replacements",
")",
":",
"# When expression is a string,",
"# get the expressions from self.expressions.",
"if",
"isinstance",
"(",
"expression",
",",
"str",
")",
":",
"expression",
"=",
"self",
".",
"expressions... | All purpose method to reduce an expression by applying
successive replacement rules.
`expression` is either a SymPy expression
or a key in `scipy_data_fitting.Model.expressions`.
`replacements` can be any of the following,
or a list of any combination of the following:
... | [
"All",
"purpose",
"method",
"to",
"reduce",
"an",
"expression",
"by",
"applying",
"successive",
"replacement",
"rules",
"."
] | python | train |
goerz/clusterjob | clusterjob/__init__.py | https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L927-L952 | def status(self):
"""Return the job status as one of the codes defined in the
`clusterjob.status` module.
finished, communicate with the cluster to determine the job's status.
"""
if self._status >= COMPLETED:
return self._status
else:
cmd = self.b... | [
"def",
"status",
"(",
"self",
")",
":",
"if",
"self",
".",
"_status",
">=",
"COMPLETED",
":",
"return",
"self",
".",
"_status",
"else",
":",
"cmd",
"=",
"self",
".",
"backend",
".",
"cmd_status",
"(",
"self",
",",
"finished",
"=",
"False",
")",
"resp... | Return the job status as one of the codes defined in the
`clusterjob.status` module.
finished, communicate with the cluster to determine the job's status. | [
"Return",
"the",
"job",
"status",
"as",
"one",
"of",
"the",
"codes",
"defined",
"in",
"the",
"clusterjob",
".",
"status",
"module",
".",
"finished",
"communicate",
"with",
"the",
"cluster",
"to",
"determine",
"the",
"job",
"s",
"status",
"."
] | python | train |
subdownloader/subdownloader | subdownloader/util.py | https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/util.py#L43-L50 | def write_stream(src_file, destination_path):
"""
Write the file-like src_file object to the string dest_path
:param src_file: file-like data to be written
:param destination_path: string of the destionation file
"""
with open(destination_path, 'wb') as destination_file:
shutil.copyfileo... | [
"def",
"write_stream",
"(",
"src_file",
",",
"destination_path",
")",
":",
"with",
"open",
"(",
"destination_path",
",",
"'wb'",
")",
"as",
"destination_file",
":",
"shutil",
".",
"copyfileobj",
"(",
"fsrc",
"=",
"src_file",
",",
"fdst",
"=",
"destination_file... | Write the file-like src_file object to the string dest_path
:param src_file: file-like data to be written
:param destination_path: string of the destionation file | [
"Write",
"the",
"file",
"-",
"like",
"src_file",
"object",
"to",
"the",
"string",
"dest_path",
":",
"param",
"src_file",
":",
"file",
"-",
"like",
"data",
"to",
"be",
"written",
":",
"param",
"destination_path",
":",
"string",
"of",
"the",
"destionation",
... | python | train |
spacetelescope/synphot_refactor | synphot/spectrum.py | https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/spectrum.py#L204-L239 | def _merge_meta(left, right, result, clean=True):
"""Merge metadata from left and right onto results.
This is used during class initialization.
This should also be used by operators to merge metadata after
creating a new instance but before returning it.
Result's metadata is mod... | [
"def",
"_merge_meta",
"(",
"left",
",",
"right",
",",
"result",
",",
"clean",
"=",
"True",
")",
":",
"# Copies are returned because they need some clean-up below.",
"left",
"=",
"BaseSpectrum",
".",
"_get_meta",
"(",
"left",
")",
"right",
"=",
"BaseSpectrum",
".",... | Merge metadata from left and right onto results.
This is used during class initialization.
This should also be used by operators to merge metadata after
creating a new instance but before returning it.
Result's metadata is modified in-place.
Parameters
----------
... | [
"Merge",
"metadata",
"from",
"left",
"and",
"right",
"onto",
"results",
"."
] | python | train |
trombastic/PyScada | pyscada/utils/scheduler.py | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L818-L835 | def init_process(self):
"""
init a standard daq process for multiple devices
"""
for item in Device.objects.filter(protocol__daq_daemon=1, active=1, id__in=self.device_ids):
try:
tmp_device = item.get_device_instance()
if tmp_device is not Non... | [
"def",
"init_process",
"(",
"self",
")",
":",
"for",
"item",
"in",
"Device",
".",
"objects",
".",
"filter",
"(",
"protocol__daq_daemon",
"=",
"1",
",",
"active",
"=",
"1",
",",
"id__in",
"=",
"self",
".",
"device_ids",
")",
":",
"try",
":",
"tmp_device... | init a standard daq process for multiple devices | [
"init",
"a",
"standard",
"daq",
"process",
"for",
"multiple",
"devices"
] | python | train |
ConsenSys/mythril-classic | mythril/mythril/mythril_config.py | https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/mythril/mythril_config.py#L124-L139 | def _add_leveldb_option(config: ConfigParser, leveldb_fallback_dir: str) -> None:
"""
Sets a default leveldb path in .mythril/config.ini file
:param config: The config file object
:param leveldb_fallback_dir: The leveldb dir to use by default for searches
:return: None
""... | [
"def",
"_add_leveldb_option",
"(",
"config",
":",
"ConfigParser",
",",
"leveldb_fallback_dir",
":",
"str",
")",
"->",
"None",
":",
"config",
".",
"set",
"(",
"\"defaults\"",
",",
"\"#Default chaindata locations:\"",
",",
"\"\"",
")",
"config",
".",
"set",
"(",
... | Sets a default leveldb path in .mythril/config.ini file
:param config: The config file object
:param leveldb_fallback_dir: The leveldb dir to use by default for searches
:return: None | [
"Sets",
"a",
"default",
"leveldb",
"path",
"in",
".",
"mythril",
"/",
"config",
".",
"ini",
"file",
":",
"param",
"config",
":",
"The",
"config",
"file",
"object",
":",
"param",
"leveldb_fallback_dir",
":",
"The",
"leveldb",
"dir",
"to",
"use",
"by",
"de... | python | train |
pandas-profiling/pandas-profiling | pandas_profiling/describe.py | https://github.com/pandas-profiling/pandas-profiling/blob/003d236daee8b7aca39c62708b18d59bced0bc03/pandas_profiling/describe.py#L109-L131 | def describe_boolean_1d(series):
"""Compute summary statistics of a boolean (`TYPE_BOOL`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys.
... | [
"def",
"describe_boolean_1d",
"(",
"series",
")",
":",
"value_counts",
",",
"distinct_count",
"=",
"base",
".",
"get_groupby_statistic",
"(",
"series",
")",
"top",
",",
"freq",
"=",
"value_counts",
".",
"index",
"[",
"0",
"]",
",",
"value_counts",
".",
"iloc... | Compute summary statistics of a boolean (`TYPE_BOOL`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | [
"Compute",
"summary",
"statistics",
"of",
"a",
"boolean",
"(",
"TYPE_BOOL",
")",
"variable",
"(",
"a",
"Series",
")",
"."
] | python | train |
BlackEarth/bf | bf/scss.py | https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/scss.py#L13-L23 | def render_css(self, fn=None, text=None, margin='', indent='\t'):
"""output css using the Sass processor"""
fn = fn or os.path.splitext(self.fn)[0]+'.css'
if not os.path.exists(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
curdir = os.path.abspath(os.curdir)
... | [
"def",
"render_css",
"(",
"self",
",",
"fn",
"=",
"None",
",",
"text",
"=",
"None",
",",
"margin",
"=",
"''",
",",
"indent",
"=",
"'\\t'",
")",
":",
"fn",
"=",
"fn",
"or",
"os",
".",
"path",
".",
"splitext",
"(",
"self",
".",
"fn",
")",
"[",
... | output css using the Sass processor | [
"output",
"css",
"using",
"the",
"Sass",
"processor"
] | python | train |
jgillick/LendingClub | lendingclub/filters.py | https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L197-L207 | def __normalize_grades(self):
"""
Adjust the grades list.
If a grade has been set, set All to false
"""
if 'grades' in self and self['grades']['All'] is True:
for grade in self['grades']:
if grade != 'All' and self['grades'][grade] is True:
... | [
"def",
"__normalize_grades",
"(",
"self",
")",
":",
"if",
"'grades'",
"in",
"self",
"and",
"self",
"[",
"'grades'",
"]",
"[",
"'All'",
"]",
"is",
"True",
":",
"for",
"grade",
"in",
"self",
"[",
"'grades'",
"]",
":",
"if",
"grade",
"!=",
"'All'",
"and... | Adjust the grades list.
If a grade has been set, set All to false | [
"Adjust",
"the",
"grades",
"list",
".",
"If",
"a",
"grade",
"has",
"been",
"set",
"set",
"All",
"to",
"false"
] | python | train |
cnschema/cdata | cdata/summary.py | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/summary.py#L25-L117 | def summarize_entity_person(person):
"""
assume person entity using cnschma person vocabulary, http://cnschema.org/Person
"""
ret = []
value = person.get("name")
if not value:
return False
ret.append(value)
prop = "courtesyName"
value = json_get_first_item(person, prop)
... | [
"def",
"summarize_entity_person",
"(",
"person",
")",
":",
"ret",
"=",
"[",
"]",
"value",
"=",
"person",
".",
"get",
"(",
"\"name\"",
")",
"if",
"not",
"value",
":",
"return",
"False",
"ret",
".",
"append",
"(",
"value",
")",
"prop",
"=",
"\"courtesyNa... | assume person entity using cnschma person vocabulary, http://cnschema.org/Person | [
"assume",
"person",
"entity",
"using",
"cnschma",
"person",
"vocabulary",
"http",
":",
"//",
"cnschema",
".",
"org",
"/",
"Person"
] | python | train |
timothydmorton/simpledist | simpledist/distributions.py | https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L136-L158 | def pctile(self,pct,res=1000):
"""Returns the desired percentile of the distribution.
Will only work if properly normalized. Designed to mimic
the `ppf` method of the `scipy.stats` random variate objects.
Works by gridding the CDF at a given resolution and matching the nearest
... | [
"def",
"pctile",
"(",
"self",
",",
"pct",
",",
"res",
"=",
"1000",
")",
":",
"grid",
"=",
"np",
".",
"linspace",
"(",
"self",
".",
"minval",
",",
"self",
".",
"maxval",
",",
"res",
")",
"return",
"grid",
"[",
"np",
".",
"argmin",
"(",
"np",
"."... | Returns the desired percentile of the distribution.
Will only work if properly normalized. Designed to mimic
the `ppf` method of the `scipy.stats` random variate objects.
Works by gridding the CDF at a given resolution and matching the nearest
point. NB, this is of course not as preci... | [
"Returns",
"the",
"desired",
"percentile",
"of",
"the",
"distribution",
"."
] | python | train |
Neurita/boyle | boyle/nifti/storage.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/storage.py#L229-L252 | def all_childnodes_to_nifti1img(h5group):
"""Returns in a list all images found under h5group.
Parameters
----------
h5group: h5py.Group
HDF group
Returns
-------
list of nifti1Image
"""
child_nodes = []
def append_parent_if_dataset(name, obj):
if isinstance(obj... | [
"def",
"all_childnodes_to_nifti1img",
"(",
"h5group",
")",
":",
"child_nodes",
"=",
"[",
"]",
"def",
"append_parent_if_dataset",
"(",
"name",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"h5py",
".",
"Dataset",
")",
":",
"if",
"name",
".",
... | Returns in a list all images found under h5group.
Parameters
----------
h5group: h5py.Group
HDF group
Returns
-------
list of nifti1Image | [
"Returns",
"in",
"a",
"list",
"all",
"images",
"found",
"under",
"h5group",
"."
] | python | valid |
saltstack/salt | salt/modules/kapacitor.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L66-L106 | def get_task(name):
'''
Get a dict of data on a task.
name
Name of the task to get information about.
CLI Example:
.. code-block:: bash
salt '*' kapacitor.get_task cpu
'''
url = _get_url()
if version() < '0.13':
task_url = '{0}/task?name={1}'.format(url, name... | [
"def",
"get_task",
"(",
"name",
")",
":",
"url",
"=",
"_get_url",
"(",
")",
"if",
"version",
"(",
")",
"<",
"'0.13'",
":",
"task_url",
"=",
"'{0}/task?name={1}'",
".",
"format",
"(",
"url",
",",
"name",
")",
"else",
":",
"task_url",
"=",
"'{0}/kapacito... | Get a dict of data on a task.
name
Name of the task to get information about.
CLI Example:
.. code-block:: bash
salt '*' kapacitor.get_task cpu | [
"Get",
"a",
"dict",
"of",
"data",
"on",
"a",
"task",
"."
] | python | train |
knipknap/exscript | Exscript/stdlib/connection.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L124-L133 | def close(scope):
"""
Closes the existing connection with the remote host. This function is
rarely used, as normally Exscript closes the connection automatically
when the script has completed.
"""
conn = scope.get('__connection__')
conn.close(1)
scope.define(__response__=conn.response)
... | [
"def",
"close",
"(",
"scope",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"conn",
".",
"close",
"(",
"1",
")",
"scope",
".",
"define",
"(",
"__response__",
"=",
"conn",
".",
"response",
")",
"return",
"True"
] | Closes the existing connection with the remote host. This function is
rarely used, as normally Exscript closes the connection automatically
when the script has completed. | [
"Closes",
"the",
"existing",
"connection",
"with",
"the",
"remote",
"host",
".",
"This",
"function",
"is",
"rarely",
"used",
"as",
"normally",
"Exscript",
"closes",
"the",
"connection",
"automatically",
"when",
"the",
"script",
"has",
"completed",
"."
] | python | train |
yatiml/yatiml | yatiml/loader.py | https://github.com/yatiml/yatiml/blob/4f55c058b72388350f0af3076ac3ea9bc1c142b0/yatiml/loader.py#L81-L104 | def __savorize(self, node: yaml.Node, expected_type: Type) -> yaml.Node:
"""Removes syntactic sugar from the node.
This calls yatiml_savorize(), first on the class's base \
classes, then on the class itself.
Args:
node: The node to modify.
expected_type: The typ... | [
"def",
"__savorize",
"(",
"self",
",",
"node",
":",
"yaml",
".",
"Node",
",",
"expected_type",
":",
"Type",
")",
"->",
"yaml",
".",
"Node",
":",
"logger",
".",
"debug",
"(",
"'Savorizing node assuming type {}'",
".",
"format",
"(",
"expected_type",
".",
"_... | Removes syntactic sugar from the node.
This calls yatiml_savorize(), first on the class's base \
classes, then on the class itself.
Args:
node: The node to modify.
expected_type: The type to assume this type is. | [
"Removes",
"syntactic",
"sugar",
"from",
"the",
"node",
"."
] | python | train |
cbrand/vpnchooser | src/vpnchooser/connection/client.py | https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/connection/client.py#L82-L99 | def _parse(data: str) -> list:
"""
Parses the given data string and returns
a list of rule objects.
"""
if isinstance(data, bytes):
data = data.decode('utf-8')
lines = (
item for item in
(item.strip() for item in data.split('\n'))
... | [
"def",
"_parse",
"(",
"data",
":",
"str",
")",
"->",
"list",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
"lines",
"=",
"(",
"item",
"for",
"item",
"in",
"(",
"item",
".",
... | Parses the given data string and returns
a list of rule objects. | [
"Parses",
"the",
"given",
"data",
"string",
"and",
"returns",
"a",
"list",
"of",
"rule",
"objects",
"."
] | python | train |
ajdavis/GreenletProfiler | _vendorized_yappi/yappi.py | https://github.com/ajdavis/GreenletProfiler/blob/700349864a4f368a8a73a2a60f048c2e818d7cea/_vendorized_yappi/yappi.py#L342-L369 | def print_all(self, out=sys.stdout):
"""
Prints all of the child function profiler results to a given file. (stdout by default)
"""
if self.empty():
return
FUNC_NAME_LEN = 38
CALLCOUNT_LEN = 9
out.write(CRLF)
out.write("name ... | [
"def",
"print_all",
"(",
"self",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"self",
".",
"empty",
"(",
")",
":",
"return",
"FUNC_NAME_LEN",
"=",
"38",
"CALLCOUNT_LEN",
"=",
"9",
"out",
".",
"write",
"(",
"CRLF",
")",
"out",
".",
"write"... | Prints all of the child function profiler results to a given file. (stdout by default) | [
"Prints",
"all",
"of",
"the",
"child",
"function",
"profiler",
"results",
"to",
"a",
"given",
"file",
".",
"(",
"stdout",
"by",
"default",
")"
] | python | train |
pudo/banal | banal/cache.py | https://github.com/pudo/banal/blob/528c339be5138458e387a058581cf7d261285447/banal/cache.py#L11-L40 | def bytes_iter(obj):
"""Turn a complex object into an iterator of byte strings.
The resulting iterator can be used for caching.
"""
if obj is None:
return
elif isinstance(obj, six.binary_type):
yield obj
elif isinstance(obj, six.string_types):
yield obj
elif isinstanc... | [
"def",
"bytes_iter",
"(",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"elif",
"isinstance",
"(",
"obj",
",",
"six",
".",
"binary_type",
")",
":",
"yield",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
"... | Turn a complex object into an iterator of byte strings.
The resulting iterator can be used for caching. | [
"Turn",
"a",
"complex",
"object",
"into",
"an",
"iterator",
"of",
"byte",
"strings",
".",
"The",
"resulting",
"iterator",
"can",
"be",
"used",
"for",
"caching",
"."
] | python | train |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/__init__.py | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/__init__.py#L65-L83 | def generate_signature_class(cls):
"""
Generate a declarative model for storing signatures related to the given
cls parameter.
:param class cls: The declarative model to generate a signature class for.
:return: The signature class, as a declarative derived from Base.
"""
return type("%sSigs... | [
"def",
"generate_signature_class",
"(",
"cls",
")",
":",
"return",
"type",
"(",
"\"%sSigs\"",
"%",
"cls",
".",
"__name__",
",",
"(",
"Base",
",",
")",
",",
"{",
"'__tablename__'",
":",
"\"%s_sigs\"",
"%",
"cls",
".",
"__tablename__",
",",
"'id'",
":",
"s... | Generate a declarative model for storing signatures related to the given
cls parameter.
:param class cls: The declarative model to generate a signature class for.
:return: The signature class, as a declarative derived from Base. | [
"Generate",
"a",
"declarative",
"model",
"for",
"storing",
"signatures",
"related",
"to",
"the",
"given",
"cls",
"parameter",
"."
] | python | train |
secure-systems-lab/securesystemslib | securesystemslib/ecdsa_keys.py | https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/ecdsa_keys.py#L67-L155 | def generate_public_and_private(scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Generate a pair of ECDSA public and private keys with one of the supported,
external cryptography libraries. The public and private keys returned
conform to 'securesystemslib.formats.PEMECDSA_SCHEMA' and
'securesystemslib.... | [
"def",
"generate_public_and_private",
"(",
"scheme",
"=",
"'ecdsa-sha2-nistp256'",
")",
":",
"# Does 'scheme' have the correct format?",
"# Verify that 'scheme' is of the correct type, and that it's one of the",
"# supported ECDSA . It must conform to",
"# 'securesystemslib.formats.ECDSA_SCHE... | <Purpose>
Generate a pair of ECDSA public and private keys with one of the supported,
external cryptography libraries. The public and private keys returned
conform to 'securesystemslib.formats.PEMECDSA_SCHEMA' and
'securesystemslib.formats.PEMECDSA_SCHEMA', respectively.
The public ECDSA public ke... | [
"<Purpose",
">",
"Generate",
"a",
"pair",
"of",
"ECDSA",
"public",
"and",
"private",
"keys",
"with",
"one",
"of",
"the",
"supported",
"external",
"cryptography",
"libraries",
".",
"The",
"public",
"and",
"private",
"keys",
"returned",
"conform",
"to",
"secures... | python | train |
wuher/devil | devil/fields/representation.py | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/representation.py#L76-L92 | def get_declared_fields(bases, attrs):
""" Find all fields and return them as a dictionary.
note:: this function is copied and modified
from django.forms.get_declared_fields
"""
def is_field(prop):
return isinstance(prop, forms.Field) or \
isinstance(prop, BaseRepresentatio... | [
"def",
"get_declared_fields",
"(",
"bases",
",",
"attrs",
")",
":",
"def",
"is_field",
"(",
"prop",
")",
":",
"return",
"isinstance",
"(",
"prop",
",",
"forms",
".",
"Field",
")",
"or",
"isinstance",
"(",
"prop",
",",
"BaseRepresentation",
")",
"fields",
... | Find all fields and return them as a dictionary.
note:: this function is copied and modified
from django.forms.get_declared_fields | [
"Find",
"all",
"fields",
"and",
"return",
"them",
"as",
"a",
"dictionary",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L322-L370 | def meta_changed_notify_after(self, state_machine_m, _, info):
"""Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to t... | [
"def",
"meta_changed_notify_after",
"(",
"self",
",",
"state_machine_m",
",",
"_",
",",
"info",
")",
":",
"meta_signal_message",
"=",
"info",
"[",
"'arg'",
"]",
"if",
"meta_signal_message",
".",
"origin",
"==",
"\"graphical_editor_gaphas\"",
":",
"# Ignore changes c... | Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
:param str _: Always "state_meta_signal"
:param... | [
"Handle",
"notification",
"about",
"the",
"change",
"of",
"a",
"state",
"s",
"meta",
"data"
] | python | train |
ssato/python-anyconfig | src/anyconfig/template.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/template.py#L65-L89 | def make_template_paths(template_file, paths=None):
"""
Make up a list of template search paths from given 'template_file'
(absolute or relative path to the template file) and/or 'paths' (a list of
template search paths given by user).
NOTE: User-given 'paths' will take higher priority over a dir o... | [
"def",
"make_template_paths",
"(",
"template_file",
",",
"paths",
"=",
"None",
")",
":",
"tmpldir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"template_file",
")",
")",
"return",
"[",
"tmpldir",
"]",
"if",
"pa... | Make up a list of template search paths from given 'template_file'
(absolute or relative path to the template file) and/or 'paths' (a list of
template search paths given by user).
NOTE: User-given 'paths' will take higher priority over a dir of
template_file.
:param template_file: Absolute or rela... | [
"Make",
"up",
"a",
"list",
"of",
"template",
"search",
"paths",
"from",
"given",
"template_file",
"(",
"absolute",
"or",
"relative",
"path",
"to",
"the",
"template",
"file",
")",
"and",
"/",
"or",
"paths",
"(",
"a",
"list",
"of",
"template",
"search",
"p... | python | train |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/autoscaling_v2beta1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/autoscaling_v2beta1_api.py#L623-L652 | def list_namespaced_horizontal_pod_autoscaler(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_horizontal_pod_autoscaler # noqa: E501
list or watch objects of kind HorizontalPodAutoscaler # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asyn... | [
"def",
"list_namespaced_horizontal_pod_autoscaler",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",... | list_namespaced_horizontal_pod_autoscaler # noqa: E501
list or watch objects of kind HorizontalPodAutoscaler # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_horizont... | [
"list_namespaced_horizontal_pod_autoscaler",
"#",
"noqa",
":",
"E501"
] | python | train |
faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L297-L303 | def _handleEsc(self):
""" Handler for CTRL+Z keypresses """
if self._typingSms:
self.serial.write(self.ESC_CHARACTER)
self._typingSms = False
self.inputBuffer = []
self.cursorPos = 0 | [
"def",
"_handleEsc",
"(",
"self",
")",
":",
"if",
"self",
".",
"_typingSms",
":",
"self",
".",
"serial",
".",
"write",
"(",
"self",
".",
"ESC_CHARACTER",
")",
"self",
".",
"_typingSms",
"=",
"False",
"self",
".",
"inputBuffer",
"=",
"[",
"]",
"self",
... | Handler for CTRL+Z keypresses | [
"Handler",
"for",
"CTRL",
"+",
"Z",
"keypresses"
] | python | train |
aws/sagemaker-python-sdk | src/sagemaker/amazon/knn.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/amazon/knn.py#L102-L113 | def create_model(self, vpc_config_override=VPC_CONFIG_DEFAULT):
"""Return a :class:`~sagemaker.amazon.KNNModel` referencing the latest
s3 model data produced by this Estimator.
Args:
vpc_config_override (dict[str, list[str]]): Optional override for VpcConfig set on the model.
... | [
"def",
"create_model",
"(",
"self",
",",
"vpc_config_override",
"=",
"VPC_CONFIG_DEFAULT",
")",
":",
"return",
"KNNModel",
"(",
"self",
".",
"model_data",
",",
"self",
".",
"role",
",",
"sagemaker_session",
"=",
"self",
".",
"sagemaker_session",
",",
"vpc_config... | Return a :class:`~sagemaker.amazon.KNNModel` referencing the latest
s3 model data produced by this Estimator.
Args:
vpc_config_override (dict[str, list[str]]): Optional override for VpcConfig set on the model.
Default: use subnets and security groups from this Estimator.
... | [
"Return",
"a",
":",
"class",
":",
"~sagemaker",
".",
"amazon",
".",
"KNNModel",
"referencing",
"the",
"latest",
"s3",
"model",
"data",
"produced",
"by",
"this",
"Estimator",
"."
] | python | train |
cltl/KafNafParserPy | KafNafParserPy/causal_data.py | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/causal_data.py#L156-L165 | def remove_this_clink(self,clink_id):
"""
Removes the clink for the given clink identifier
@type clink_id: string
@param clink_id: the clink identifier to be removed
"""
for clink in self.get_clinks():
if clink.get_id() == clink_id:
self.node.r... | [
"def",
"remove_this_clink",
"(",
"self",
",",
"clink_id",
")",
":",
"for",
"clink",
"in",
"self",
".",
"get_clinks",
"(",
")",
":",
"if",
"clink",
".",
"get_id",
"(",
")",
"==",
"clink_id",
":",
"self",
".",
"node",
".",
"remove",
"(",
"clink",
".",
... | Removes the clink for the given clink identifier
@type clink_id: string
@param clink_id: the clink identifier to be removed | [
"Removes",
"the",
"clink",
"for",
"the",
"given",
"clink",
"identifier"
] | python | train |
PBR/MQ2 | MQ2/mapchart.py | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/mapchart.py#L124-L228 | def generate_map_chart_file(qtl_matrix, lod_threshold,
map_chart_file='MapChart.map'):
""" This function converts our QTL matrix file into a MapChart input
file.
:arg qtl_matrix: the path to the QTL matrix file generated by
the plugin.
:arg lod_threshold: threshold u... | [
"def",
"generate_map_chart_file",
"(",
"qtl_matrix",
",",
"lod_threshold",
",",
"map_chart_file",
"=",
"'MapChart.map'",
")",
":",
"qtl_matrix",
"=",
"read_input_file",
"(",
"qtl_matrix",
",",
"sep",
"=",
"','",
")",
"tmp_dic",
"=",
"{",
"}",
"cnt",
"=",
"1",
... | This function converts our QTL matrix file into a MapChart input
file.
:arg qtl_matrix: the path to the QTL matrix file generated by
the plugin.
:arg lod_threshold: threshold used to determine if a given LOD value
is reflective the presence of a QTL.
:kwarg map_chart_file: name of the o... | [
"This",
"function",
"converts",
"our",
"QTL",
"matrix",
"file",
"into",
"a",
"MapChart",
"input",
"file",
"."
] | python | train |
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L249-L252 | def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level) | [
"def",
"_update_handler",
"(",
"self",
",",
"handler_class",
",",
"level",
")",
":",
"handler",
"=",
"self",
".",
"_get_handler",
"(",
"handler_class",
")",
"handler",
".",
"setLevel",
"(",
"level",
")"
] | Update the level of an handler. | [
"Update",
"the",
"level",
"of",
"an",
"handler",
"."
] | python | train |
pyca/pyopenssl | src/OpenSSL/SSL.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/SSL.py#L1444-L1463 | def set_alpn_protos(self, protos):
"""
Specify the protocols that the client is prepared to speak after the
TLS connection has been negotiated using Application Layer Protocol
Negotiation.
:param protos: A list of the protocols to be offered to the server.
This list ... | [
"def",
"set_alpn_protos",
"(",
"self",
",",
"protos",
")",
":",
"# Take the list of protocols and join them together, prefixing them",
"# with their lengths.",
"protostr",
"=",
"b''",
".",
"join",
"(",
"chain",
".",
"from_iterable",
"(",
"(",
"int2byte",
"(",
"len",
"... | Specify the protocols that the client is prepared to speak after the
TLS connection has been negotiated using Application Layer Protocol
Negotiation.
:param protos: A list of the protocols to be offered to the server.
This list should be a Python list of bytestrings representing the... | [
"Specify",
"the",
"protocols",
"that",
"the",
"client",
"is",
"prepared",
"to",
"speak",
"after",
"the",
"TLS",
"connection",
"has",
"been",
"negotiated",
"using",
"Application",
"Layer",
"Protocol",
"Negotiation",
"."
] | python | test |
log2timeline/plaso | plaso/serializer/json_serializer.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/serializer/json_serializer.py#L419-L429 | def WriteSerialized(cls, attribute_container):
"""Writes an attribute container to serialized form.
Args:
attribute_container (AttributeContainer): attribute container.
Returns:
str: A JSON string containing the serialized form.
"""
json_dict = cls.WriteSerializedDict(attribute_contain... | [
"def",
"WriteSerialized",
"(",
"cls",
",",
"attribute_container",
")",
":",
"json_dict",
"=",
"cls",
".",
"WriteSerializedDict",
"(",
"attribute_container",
")",
"return",
"json",
".",
"dumps",
"(",
"json_dict",
")"
] | Writes an attribute container to serialized form.
Args:
attribute_container (AttributeContainer): attribute container.
Returns:
str: A JSON string containing the serialized form. | [
"Writes",
"an",
"attribute",
"container",
"to",
"serialized",
"form",
"."
] | python | train |
LCAV/pylocus | pylocus/algorithms.py | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L326-L375 | def reconstruct_dwmds(edm, X0, W=None, n=None, r=None, X_bar=None, print_out=False, tol=1e-10, sweeps=100):
""" Reconstruct point set using d(istributed)w(eighted) MDS.
Refer to paper "Distributed Weighted-Multidimensional Scaling for Node Localization in Sensor Networks" for
implementation details (doi.o... | [
"def",
"reconstruct_dwmds",
"(",
"edm",
",",
"X0",
",",
"W",
"=",
"None",
",",
"n",
"=",
"None",
",",
"r",
"=",
"None",
",",
"X_bar",
"=",
"None",
",",
"print_out",
"=",
"False",
",",
"tol",
"=",
"1e-10",
",",
"sweeps",
"=",
"100",
")",
":",
"f... | Reconstruct point set using d(istributed)w(eighted) MDS.
Refer to paper "Distributed Weighted-Multidimensional Scaling for Node Localization in Sensor Networks" for
implementation details (doi.org/10.1145/1138127.1138129)
:param X0: Nxd matrix of starting points.
:param n: Number of points of unknown... | [
"Reconstruct",
"point",
"set",
"using",
"d",
"(",
"istributed",
")",
"w",
"(",
"eighted",
")",
"MDS",
"."
] | python | train |
praekelt/panya-music | music/models.py | https://github.com/praekelt/panya-music/blob/9300b1866bc33178e721b6de4771ba866bfc4b11/music/models.py#L77-L97 | def get_primary_contributors(self, permitted=True):
"""
Returns a list of primary contributors, with primary being defined as those contributors that have the highest role assigned(in terms of priority). When permitted is set to True only permitted contributors are returned.
"""
primary_... | [
"def",
"get_primary_contributors",
"(",
"self",
",",
"permitted",
"=",
"True",
")",
":",
"primary_credits",
"=",
"[",
"]",
"credits",
"=",
"self",
".",
"credits",
".",
"exclude",
"(",
"role",
"=",
"None",
")",
".",
"order_by",
"(",
"'role'",
")",
"if",
... | Returns a list of primary contributors, with primary being defined as those contributors that have the highest role assigned(in terms of priority). When permitted is set to True only permitted contributors are returned. | [
"Returns",
"a",
"list",
"of",
"primary",
"contributors",
"with",
"primary",
"being",
"defined",
"as",
"those",
"contributors",
"that",
"have",
"the",
"highest",
"role",
"assigned",
"(",
"in",
"terms",
"of",
"priority",
")",
".",
"When",
"permitted",
"is",
"s... | python | train |
mila-iqia/fuel | fuel/converters/mnist.py | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/mnist.py#L111-L159 | def read_mnist_images(filename, dtype=None):
"""Read MNIST images from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read images.
dtype : 'float32', 'float64', or 'bool'
If unspecified, images will be returned in their original
... | [
"def",
"read_mnist_images",
"(",
"filename",
",",
"dtype",
"=",
"None",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"magic",
",",
"number",
",",
"rows",
",",
"cols",
"=",
"struct",
".",
"unpack",
"(",
"... | Read MNIST images from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read images.
dtype : 'float32', 'float64', or 'bool'
If unspecified, images will be returned in their original
unsigned byte format.
Returns
-------
... | [
"Read",
"MNIST",
"images",
"from",
"the",
"original",
"ubyte",
"file",
"format",
"."
] | python | train |
polyaxon/polyaxon-cli | polyaxon_cli/managers/ignore.py | https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/managers/ignore.py#L105-L109 | def _remove_trailing_spaces(line):
"""Remove trailing spaces unless they are quoted with a backslash."""
while line.endswith(' ') and not line.endswith('\\ '):
line = line[:-1]
return line.replace('\\ ', ' ') | [
"def",
"_remove_trailing_spaces",
"(",
"line",
")",
":",
"while",
"line",
".",
"endswith",
"(",
"' '",
")",
"and",
"not",
"line",
".",
"endswith",
"(",
"'\\\\ '",
")",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"return",
"line",
".",
"replace... | Remove trailing spaces unless they are quoted with a backslash. | [
"Remove",
"trailing",
"spaces",
"unless",
"they",
"are",
"quoted",
"with",
"a",
"backslash",
"."
] | python | valid |
heuer/cablemap | cablemap.tm/cablemap/tm/handler.py | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.tm/cablemap/tm/handler.py#L117-L124 | def create_ctm_handler(fileobj, title=u'Cablegate Topic Map', comment=u'Generated by Cablemap - https://github.com/heuer/cablemap', detect_prefixes=False):
"""\
Returns a `ICableHandler` instance which writes Compact Topic Maps syntax (CTM).
`fileobj`
A file-like object.
"""
return MIOCable... | [
"def",
"create_ctm_handler",
"(",
"fileobj",
",",
"title",
"=",
"u'Cablegate Topic Map'",
",",
"comment",
"=",
"u'Generated by Cablemap - https://github.com/heuer/cablemap'",
",",
"detect_prefixes",
"=",
"False",
")",
":",
"return",
"MIOCableHandler",
"(",
"create_ctm_mioha... | \
Returns a `ICableHandler` instance which writes Compact Topic Maps syntax (CTM).
`fileobj`
A file-like object. | [
"\\",
"Returns",
"a",
"ICableHandler",
"instance",
"which",
"writes",
"Compact",
"Topic",
"Maps",
"syntax",
"(",
"CTM",
")",
"."
] | python | train |
twisted/mantissa | xmantissa/people.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1658-L1669 | def getEditPerson(self, name):
"""
Get an L{EditPersonView} for editing the person named C{name}.
@param name: A person name.
@type name: C{unicode}
@rtype: L{EditPersonView}
"""
view = EditPersonView(self.organizer.personByName(name))
view.setFragmentPa... | [
"def",
"getEditPerson",
"(",
"self",
",",
"name",
")",
":",
"view",
"=",
"EditPersonView",
"(",
"self",
".",
"organizer",
".",
"personByName",
"(",
"name",
")",
")",
"view",
".",
"setFragmentParent",
"(",
"self",
")",
"return",
"view"
] | Get an L{EditPersonView} for editing the person named C{name}.
@param name: A person name.
@type name: C{unicode}
@rtype: L{EditPersonView} | [
"Get",
"an",
"L",
"{",
"EditPersonView",
"}",
"for",
"editing",
"the",
"person",
"named",
"C",
"{",
"name",
"}",
"."
] | python | train |
jrief/django-websocket-redis | ws4redis/websocket.py | https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L384-L425 | def encode_header(cls, fin, opcode, mask, length, flags):
"""
Encodes a WebSocket header.
:param fin: Whether this is the final frame for this opcode.
:param opcode: The opcode of the payload, see `OPCODE_*`
:param mask: Whether the payload is masked.
:param length: The ... | [
"def",
"encode_header",
"(",
"cls",
",",
"fin",
",",
"opcode",
",",
"mask",
",",
"length",
",",
"flags",
")",
":",
"first_byte",
"=",
"opcode",
"second_byte",
"=",
"0",
"if",
"six",
".",
"PY2",
":",
"extra",
"=",
"''",
"else",
":",
"extra",
"=",
"b... | Encodes a WebSocket header.
:param fin: Whether this is the final frame for this opcode.
:param opcode: The opcode of the payload, see `OPCODE_*`
:param mask: Whether the payload is masked.
:param length: The length of the frame.
:param flags: The RSV* flags.
:return: A ... | [
"Encodes",
"a",
"WebSocket",
"header",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/natural_language_understanding_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/natural_language_understanding_v1.py#L2230-L2239 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'entities') and self.entities is not None:
_dict['entities'] = [x._to_dict() for x in self.entities]
if hasattr(self, 'location') and self.location is not None:
... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'entities'",
")",
"and",
"self",
".",
"entities",
"is",
"not",
"None",
":",
"_dict",
"[",
"'entities'",
"]",
"=",
"[",
"x",
".",
"_to_dict",
"(",
... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
JarryShaw/DictDumper | src/tree.py | https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/tree.py#L221-L264 | def _append_branch(self, value, _file):
"""Call this function to write branch contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
if not value:
return
# return self._append_none(None, _file)... | [
"def",
"_append_branch",
"(",
"self",
",",
"value",
",",
"_file",
")",
":",
"if",
"not",
"value",
":",
"return",
"# return self._append_none(None, _file)",
"self",
".",
"_tctr",
"+=",
"1",
"_vlen",
"=",
"len",
"(",
"value",
")",
"for",
"(",
"_vctr",
",",
... | Call this function to write branch contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file | [
"Call",
"this",
"function",
"to",
"write",
"branch",
"contents",
"."
] | python | train |
veltzer/pytconf | pytconf/config.py | https://github.com/veltzer/pytconf/blob/8dee43ace35d0dd2ab1105fb94057f650393360f/pytconf/config.py#L639-L654 | def create_list_int(help_string=NO_HELP, default=NO_DEFAULT):
# type: (str, Union[List[int], NO_DEFAULT_TYPE]) -> List[int]
"""
Create a List[int] parameter
:param help_string:
:param default:
:return:
"""
# noinspection PyTypeChecker
return ParamF... | [
"def",
"create_list_int",
"(",
"help_string",
"=",
"NO_HELP",
",",
"default",
"=",
"NO_DEFAULT",
")",
":",
"# type: (str, Union[List[int], NO_DEFAULT_TYPE]) -> List[int]",
"# noinspection PyTypeChecker",
"return",
"ParamFunctions",
"(",
"help_string",
"=",
"help_string",
",",... | Create a List[int] parameter
:param help_string:
:param default:
:return: | [
"Create",
"a",
"List",
"[",
"int",
"]",
"parameter",
":",
"param",
"help_string",
":",
":",
"param",
"default",
":",
":",
"return",
":"
] | python | train |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1585-L1599 | def MakeExponentialPmf(lam, high, n=200):
"""Makes a PMF discrete approx to an exponential distribution.
lam: parameter lambda in events per unit time
high: upper bound
n: number of values in the Pmf
returns: normalized Pmf
"""
pmf = Pmf()
for x in numpy.linspace(0, high, n):
p... | [
"def",
"MakeExponentialPmf",
"(",
"lam",
",",
"high",
",",
"n",
"=",
"200",
")",
":",
"pmf",
"=",
"Pmf",
"(",
")",
"for",
"x",
"in",
"numpy",
".",
"linspace",
"(",
"0",
",",
"high",
",",
"n",
")",
":",
"p",
"=",
"EvalExponentialPdf",
"(",
"x",
... | Makes a PMF discrete approx to an exponential distribution.
lam: parameter lambda in events per unit time
high: upper bound
n: number of values in the Pmf
returns: normalized Pmf | [
"Makes",
"a",
"PMF",
"discrete",
"approx",
"to",
"an",
"exponential",
"distribution",
"."
] | python | train |
noxdafox/vminspect | vminspect/usnjrnl.py | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/usnjrnl.py#L51-L71 | def parse_journal_file(journal_file):
"""Iterates over the journal's file taking care of paddings."""
counter = count()
for block in read_next_block(journal_file):
block = remove_nullchars(block)
while len(block) > MIN_RECORD_SIZE:
header = RECORD_HEADER.unpack_from(block)
... | [
"def",
"parse_journal_file",
"(",
"journal_file",
")",
":",
"counter",
"=",
"count",
"(",
")",
"for",
"block",
"in",
"read_next_block",
"(",
"journal_file",
")",
":",
"block",
"=",
"remove_nullchars",
"(",
"block",
")",
"while",
"len",
"(",
"block",
")",
"... | Iterates over the journal's file taking care of paddings. | [
"Iterates",
"over",
"the",
"journal",
"s",
"file",
"taking",
"care",
"of",
"paddings",
"."
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/scatter/layer_artist.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/scatter/layer_artist.py#L110-L122 | def remove(self):
"""
Remove the layer artist from the visualization
"""
if self._multiscat is None:
return
self._multiscat.deallocate(self.id)
self._multiscat = None
self._viewer_state.remove_global_callback(self._update_scatter)
self.state... | [
"def",
"remove",
"(",
"self",
")",
":",
"if",
"self",
".",
"_multiscat",
"is",
"None",
":",
"return",
"self",
".",
"_multiscat",
".",
"deallocate",
"(",
"self",
".",
"id",
")",
"self",
".",
"_multiscat",
"=",
"None",
"self",
".",
"_viewer_state",
".",
... | Remove the layer artist from the visualization | [
"Remove",
"the",
"layer",
"artist",
"from",
"the",
"visualization"
] | python | train |
dw/mitogen | mitogen/core.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/core.py#L803-L837 | def unpickle(self, throw=True, throw_dead=True):
"""
Unpickle :attr:`data`, optionally raising any exceptions present.
:param bool throw_dead:
If :data:`True`, raise exceptions, otherwise it is the caller's
responsibility.
:raises CallError:
The seri... | [
"def",
"unpickle",
"(",
"self",
",",
"throw",
"=",
"True",
",",
"throw_dead",
"=",
"True",
")",
":",
"_vv",
"and",
"IOLOG",
".",
"debug",
"(",
"'%r.unpickle()'",
",",
"self",
")",
"if",
"throw_dead",
"and",
"self",
".",
"is_dead",
":",
"self",
".",
"... | Unpickle :attr:`data`, optionally raising any exceptions present.
:param bool throw_dead:
If :data:`True`, raise exceptions, otherwise it is the caller's
responsibility.
:raises CallError:
The serialized data contained CallError exception.
:raises ChannelErr... | [
"Unpickle",
":",
"attr",
":",
"data",
"optionally",
"raising",
"any",
"exceptions",
"present",
"."
] | python | train |
azogue/esiosdata | esiosdata/__main__.py | https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/__main__.py#L26-L96 | def main_cli():
"""
Actualiza la base de datos de PVPC/DEMANDA almacenados como dataframe en local,
creando una nueva si no existe o hubiere algún problema. Los datos registrados se guardan en HDF5
"""
def _get_parser_args():
p = argparse.ArgumentParser(description='Gestor de DB de PVPC/D... | [
"def",
"main_cli",
"(",
")",
":",
"def",
"_get_parser_args",
"(",
")",
":",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Gestor de DB de PVPC/DEMANDA (esios.ree.es)'",
")",
"p",
".",
"add_argument",
"(",
"'-d'",
",",
"'--dem'",
",",
... | Actualiza la base de datos de PVPC/DEMANDA almacenados como dataframe en local,
creando una nueva si no existe o hubiere algún problema. Los datos registrados se guardan en HDF5 | [
"Actualiza",
"la",
"base",
"de",
"datos",
"de",
"PVPC",
"/",
"DEMANDA",
"almacenados",
"como",
"dataframe",
"en",
"local",
"creando",
"una",
"nueva",
"si",
"no",
"existe",
"o",
"hubiere",
"algún",
"problema",
".",
"Los",
"datos",
"registrados",
"se",
"guarda... | python | valid |
dlecocq/nsq-py | nsq/sockets/base.py | https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/sockets/base.py#L31-L38 | def sendall(self, data, flags=0):
'''Same as socket.sendall'''
count = len(data)
while count:
sent = self.send(data, flags)
# This could probably be a buffer object
data = data[sent:]
count -= sent | [
"def",
"sendall",
"(",
"self",
",",
"data",
",",
"flags",
"=",
"0",
")",
":",
"count",
"=",
"len",
"(",
"data",
")",
"while",
"count",
":",
"sent",
"=",
"self",
".",
"send",
"(",
"data",
",",
"flags",
")",
"# This could probably be a buffer object",
"d... | Same as socket.sendall | [
"Same",
"as",
"socket",
".",
"sendall"
] | python | train |
geophysics-ubonn/crtomo_tools | lib/crtomo/grid.py | https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/grid.py#L231-L259 | def _read_elem_elements(self, fid):
"""Read all FE elements from the file stream. Elements are stored in
the self.element_data dict. The keys refer to the element types:
* 3: Triangular grid (three nodes)
* 8: Quadrangular grid (four nodes)
* 11: Mixed boundary element
... | [
"def",
"_read_elem_elements",
"(",
"self",
",",
"fid",
")",
":",
"elements",
"=",
"{",
"}",
"# read elements",
"for",
"element_type",
"in",
"range",
"(",
"0",
",",
"self",
".",
"header",
"[",
"'nr_element_types'",
"]",
")",
":",
"element_list",
"=",
"[",
... | Read all FE elements from the file stream. Elements are stored in
the self.element_data dict. The keys refer to the element types:
* 3: Triangular grid (three nodes)
* 8: Quadrangular grid (four nodes)
* 11: Mixed boundary element
* 12: Neumann (no-flow) boundary element | [
"Read",
"all",
"FE",
"elements",
"from",
"the",
"file",
"stream",
".",
"Elements",
"are",
"stored",
"in",
"the",
"self",
".",
"element_data",
"dict",
".",
"The",
"keys",
"refer",
"to",
"the",
"element",
"types",
":"
] | python | train |
Alignak-monitoring/alignak | alignak/basemodule.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L212-L232 | def clear_queues(self, manager):
"""Release the resources associated to the queues of this instance
:param manager: Manager() object
:type manager: None | object
:return: None
"""
for queue in (self.to_q, self.from_q):
if queue is None:
contin... | [
"def",
"clear_queues",
"(",
"self",
",",
"manager",
")",
":",
"for",
"queue",
"in",
"(",
"self",
".",
"to_q",
",",
"self",
".",
"from_q",
")",
":",
"if",
"queue",
"is",
"None",
":",
"continue",
"# If we got no manager, we directly call the clean",
"if",
"not... | Release the resources associated to the queues of this instance
:param manager: Manager() object
:type manager: None | object
:return: None | [
"Release",
"the",
"resources",
"associated",
"to",
"the",
"queues",
"of",
"this",
"instance"
] | python | train |
TaurusOlson/fntools | fntools/fntools.py | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L595-L608 | def find(fn, record):
"""Apply a function on the record and return the corresponding new record
:param fn: a function
:param record: a dictionary
:returns: a dictionary
>>> find(max, {'Terry': 30, 'Graham': 35, 'John': 27})
{'Graham': 35}
"""
values_result = fn(record.values())
ke... | [
"def",
"find",
"(",
"fn",
",",
"record",
")",
":",
"values_result",
"=",
"fn",
"(",
"record",
".",
"values",
"(",
")",
")",
"keys_result",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"record",
".",
"items",
"(",
")",
"if",
"v",
"==",
"values_resul... | Apply a function on the record and return the corresponding new record
:param fn: a function
:param record: a dictionary
:returns: a dictionary
>>> find(max, {'Terry': 30, 'Graham': 35, 'John': 27})
{'Graham': 35} | [
"Apply",
"a",
"function",
"on",
"the",
"record",
"and",
"return",
"the",
"corresponding",
"new",
"record"
] | python | train |
belbio/bel | bel/lang/migrate_1_2.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L128-L144 | def convert_activity(ast):
"""Convert BEL1 activities to BEL2 act()"""
if len(ast.args) > 1:
log.error(f"Activity should not have more than 1 argument {ast.to_string()}")
p_arg = ast.args[0] # protein argument
print("p_arg", p_arg)
ma_arg = Function("ma", bo.spec)
ma_arg.add_argument(... | [
"def",
"convert_activity",
"(",
"ast",
")",
":",
"if",
"len",
"(",
"ast",
".",
"args",
")",
">",
"1",
":",
"log",
".",
"error",
"(",
"f\"Activity should not have more than 1 argument {ast.to_string()}\"",
")",
"p_arg",
"=",
"ast",
".",
"args",
"[",
"0",
"]",... | Convert BEL1 activities to BEL2 act() | [
"Convert",
"BEL1",
"activities",
"to",
"BEL2",
"act",
"()"
] | python | train |
lsst-epo/vela | astropixie-widgets/astropixie_widgets/visual.py | https://github.com/lsst-epo/vela/blob/8e17ebec509be5c3cc2063f4645dfe9e26b49c18/astropixie-widgets/astropixie_widgets/visual.py#L164-L172 | def hr_diagram(cluster_name, output=None):
"""Create a :class:`~bokeh.plotting.figure.Figure` to create an H-R
diagram using the cluster_name; then show it.
Re
"""
cluster = get_hr_data(cluster_name)
pf = hr_diagram_figure(cluster)
show_with_bokeh_server(pf) | [
"def",
"hr_diagram",
"(",
"cluster_name",
",",
"output",
"=",
"None",
")",
":",
"cluster",
"=",
"get_hr_data",
"(",
"cluster_name",
")",
"pf",
"=",
"hr_diagram_figure",
"(",
"cluster",
")",
"show_with_bokeh_server",
"(",
"pf",
")"
] | Create a :class:`~bokeh.plotting.figure.Figure` to create an H-R
diagram using the cluster_name; then show it.
Re | [
"Create",
"a",
":",
"class",
":",
"~bokeh",
".",
"plotting",
".",
"figure",
".",
"Figure",
"to",
"create",
"an",
"H",
"-",
"R",
"diagram",
"using",
"the",
"cluster_name",
";",
"then",
"show",
"it",
"."
] | python | valid |
kwikteam/phy | phy/gui/actions.py | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/actions.py#L285-L289 | def remove(self, name):
"""Remove an action."""
self.gui.removeAction(self._actions_dict[name].qaction)
del self._actions_dict[name]
delattr(self, name) | [
"def",
"remove",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"gui",
".",
"removeAction",
"(",
"self",
".",
"_actions_dict",
"[",
"name",
"]",
".",
"qaction",
")",
"del",
"self",
".",
"_actions_dict",
"[",
"name",
"]",
"delattr",
"(",
"self",
","... | Remove an action. | [
"Remove",
"an",
"action",
"."
] | python | train |
rwl/pylon | pylon/io/psat.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psat.py#L245-L278 | def _get_demand_array_construct(self):
""" Returns a construct for an array of power demand data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
p_direction = real.setResultsName("p_direction") # p.u.
q_direction = real.setR... | [
"def",
"_get_demand_array_construct",
"(",
"self",
")",
":",
"bus_no",
"=",
"integer",
".",
"setResultsName",
"(",
"\"bus_no\"",
")",
"s_rating",
"=",
"real",
".",
"setResultsName",
"(",
"\"s_rating\"",
")",
"# MVA",
"p_direction",
"=",
"real",
".",
"setResultsN... | Returns a construct for an array of power demand data. | [
"Returns",
"a",
"construct",
"for",
"an",
"array",
"of",
"power",
"demand",
"data",
"."
] | python | train |
nwilming/ocupy | ocupy/stimuli.py | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/stimuli.py#L219-L278 | def DirectoryStimuliFactory(loader):
"""
Takes an input path to the images folder of an experiment and generates
automatically the category - filenumber list needed to construct an
appropriate _categories object.
Parameters :
loader : Loader object which contains
impath : s... | [
"def",
"DirectoryStimuliFactory",
"(",
"loader",
")",
":",
"impath",
"=",
"loader",
".",
"impath",
"ftrpath",
"=",
"loader",
".",
"ftrpath",
"# checks whether user has reading permission for the path",
"assert",
"os",
".",
"access",
"(",
"impath",
",",
"os",
".",
... | Takes an input path to the images folder of an experiment and generates
automatically the category - filenumber list needed to construct an
appropriate _categories object.
Parameters :
loader : Loader object which contains
impath : string
path to the input, i.e. ima... | [
"Takes",
"an",
"input",
"path",
"to",
"the",
"images",
"folder",
"of",
"an",
"experiment",
"and",
"generates",
"automatically",
"the",
"category",
"-",
"filenumber",
"list",
"needed",
"to",
"construct",
"an",
"appropriate",
"_categories",
"object",
".",
"Paramet... | python | train |
influxdata/influxdb-python | influxdb/client.py | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L454-L514 | def write_points(self,
points,
time_precision=None,
database=None,
retention_policy=None,
tags=None,
batch_size=None,
protocol='json',
consistency=None
... | [
"def",
"write_points",
"(",
"self",
",",
"points",
",",
"time_precision",
"=",
"None",
",",
"database",
"=",
"None",
",",
"retention_policy",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"protocol",
"=",
"'json'",
",",
"con... | Write to multiple time series names.
:param points: the list of points to be written in the database
:type points: list of dictionaries, each dictionary represents a point
:type points: (if protocol is 'json') list of dicts, where each dict
represents... | [
"Write",
"to",
"multiple",
"time",
"series",
"names",
"."
] | python | train |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L282-L298 | def set(self, index, value):
"""Set the ``Node`` at *index* to *value*.
Raises :exc:`IndexError` if *index* is out of range, or
:exc:`ValueError` if *value* cannot be coerced into one :class:`.Node`.
To insert multiple nodes at an index, use :meth:`get` with either
:meth:`remove... | [
"def",
"set",
"(",
"self",
",",
"index",
",",
"value",
")",
":",
"nodes",
"=",
"parse_anything",
"(",
"value",
")",
".",
"nodes",
"if",
"len",
"(",
"nodes",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Cannot coerce multiple nodes into one index\"",
... | Set the ``Node`` at *index* to *value*.
Raises :exc:`IndexError` if *index* is out of range, or
:exc:`ValueError` if *value* cannot be coerced into one :class:`.Node`.
To insert multiple nodes at an index, use :meth:`get` with either
:meth:`remove` and :meth:`insert` or :meth:`replace`. | [
"Set",
"the",
"Node",
"at",
"*",
"index",
"*",
"to",
"*",
"value",
"*",
"."
] | python | train |
kata198/QueryableList | QueryableList/Base.py | https://github.com/kata198/QueryableList/blob/279286d46205ce8268af42e03b75820a7483fddb/QueryableList/Base.py#L22-L86 | def getFiltersFromArgs(kwargs):
'''
getFiltersFromArgs - Returns a dictionary of each filter type, and the corrosponding field/value
@param kwargs <dict> - Dictionary of filter arguments
@return - Dictionary of each filter type (minus the ones that are optimized into others), each contain... | [
"def",
"getFiltersFromArgs",
"(",
"kwargs",
")",
":",
"# Create a copy of each possible filter in FILTER_TYPES and link to empty list.",
"# This object will be filled with all of the filters requested",
"ret",
"=",
"{",
"filterType",
":",
"list",
"(",
")",
"for",
"filterType",
"... | getFiltersFromArgs - Returns a dictionary of each filter type, and the corrosponding field/value
@param kwargs <dict> - Dictionary of filter arguments
@return - Dictionary of each filter type (minus the ones that are optimized into others), each containing a list of tuples, (fieldName, matchingValue) | [
"getFiltersFromArgs",
"-",
"Returns",
"a",
"dictionary",
"of",
"each",
"filter",
"type",
"and",
"the",
"corrosponding",
"field",
"/",
"value"
] | python | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L197-L217 | def get_transactions(self, date_from: datetime, date_to: datetime) -> List[Transaction]:
""" Returns account transactions """
assert isinstance(date_from, datetime)
assert isinstance(date_to, datetime)
# fix up the parameters as we need datetime
dt_from = Datum()
dt_from... | [
"def",
"get_transactions",
"(",
"self",
",",
"date_from",
":",
"datetime",
",",
"date_to",
":",
"datetime",
")",
"->",
"List",
"[",
"Transaction",
"]",
":",
"assert",
"isinstance",
"(",
"date_from",
",",
"datetime",
")",
"assert",
"isinstance",
"(",
"date_to... | Returns account transactions | [
"Returns",
"account",
"transactions"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L863-L868 | def set_verbose_logging(verbose: bool) -> None:
"""Chooses basic or verbose logging."""
if verbose:
set_loglevel(logging.DEBUG)
else:
set_loglevel(logging.INFO) | [
"def",
"set_verbose_logging",
"(",
"verbose",
":",
"bool",
")",
"->",
"None",
":",
"if",
"verbose",
":",
"set_loglevel",
"(",
"logging",
".",
"DEBUG",
")",
"else",
":",
"set_loglevel",
"(",
"logging",
".",
"INFO",
")"
] | Chooses basic or verbose logging. | [
"Chooses",
"basic",
"or",
"verbose",
"logging",
"."
] | python | train |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L668-L702 | def add_roast_event(self, event):
"""Add an event to the roast log.
This method should be used for registering events that may be worth
tracking like first crack, second crack and the dropping of coffee.
Similar to the standard reading output from the roaster, manually
created e... | [
"def",
"add_roast_event",
"(",
"self",
",",
"event",
")",
":",
"event_time",
"=",
"self",
".",
"get_roast_time",
"(",
")",
"def",
"get_valid_config",
"(",
")",
":",
"\"\"\"Keep grabbing configs until we have a valid one.\n\n In rare cases, the configuration will be... | Add an event to the roast log.
This method should be used for registering events that may be worth
tracking like first crack, second crack and the dropping of coffee.
Similar to the standard reading output from the roaster, manually
created events will include the current configuration ... | [
"Add",
"an",
"event",
"to",
"the",
"roast",
"log",
"."
] | python | train |
trailofbits/manticore | manticore/platforms/evm.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1101-L1105 | def _store(self, offset, value, size=1):
"""Stores value in memory as a big endian"""
self.memory.write_BE(offset, value, size)
for i in range(size):
self._publish('did_evm_write_memory', offset + i, Operators.EXTRACT(value, (size - i - 1) * 8, 8)) | [
"def",
"_store",
"(",
"self",
",",
"offset",
",",
"value",
",",
"size",
"=",
"1",
")",
":",
"self",
".",
"memory",
".",
"write_BE",
"(",
"offset",
",",
"value",
",",
"size",
")",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"self",
".",
"_... | Stores value in memory as a big endian | [
"Stores",
"value",
"in",
"memory",
"as",
"a",
"big",
"endian"
] | python | valid |
pallets/flask-sqlalchemy | flask_sqlalchemy/__init__.py | https://github.com/pallets/flask-sqlalchemy/blob/3d3261f4fc6d28f5bf407cf7d523e36a09a8c144/flask_sqlalchemy/__init__.py#L758-L772 | def create_session(self, options):
"""Create the session factory used by :meth:`create_scoped_session`.
The factory **must** return an object that SQLAlchemy recognizes as a session,
or registering session events may raise an exception.
Valid factories include a :class:`~sqlalchemy.orm... | [
"def",
"create_session",
"(",
"self",
",",
"options",
")",
":",
"return",
"orm",
".",
"sessionmaker",
"(",
"class_",
"=",
"SignallingSession",
",",
"db",
"=",
"self",
",",
"*",
"*",
"options",
")"
] | Create the session factory used by :meth:`create_scoped_session`.
The factory **must** return an object that SQLAlchemy recognizes as a session,
or registering session events may raise an exception.
Valid factories include a :class:`~sqlalchemy.orm.session.Session`
class or a :class:`~... | [
"Create",
"the",
"session",
"factory",
"used",
"by",
":",
"meth",
":",
"create_scoped_session",
"."
] | python | train |
zyga/call | call/__init__.py | https://github.com/zyga/call/blob/dcef9a5aac7f9085bd4829dd6bcedc5fc2945d87/call/__init__.py#L46-L62 | def bind(self, args, kwargs):
"""
Bind arguments and keyword arguments to the encapsulated function.
Returns a dictionary of parameters (named according to function
parameters) with the values that were bound to each name.
"""
spec = self._spec
resolution = self.... | [
"def",
"bind",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"spec",
"=",
"self",
".",
"_spec",
"resolution",
"=",
"self",
".",
"resolve",
"(",
"args",
",",
"kwargs",
")",
"params",
"=",
"dict",
"(",
"zip",
"(",
"spec",
".",
"args",
",",
"re... | Bind arguments and keyword arguments to the encapsulated function.
Returns a dictionary of parameters (named according to function
parameters) with the values that were bound to each name. | [
"Bind",
"arguments",
"and",
"keyword",
"arguments",
"to",
"the",
"encapsulated",
"function",
"."
] | python | train |
dw/mitogen | ansible_mitogen/connection.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/connection.py#L259-L274 | def _connect_su(spec):
"""
Return ContextService arguments for su as a become method.
"""
return {
'method': 'su',
'enable_lru': True,
'kwargs': {
'username': spec.become_user(),
'password': spec.become_pass(),
'python_path': spec.python_path()... | [
"def",
"_connect_su",
"(",
"spec",
")",
":",
"return",
"{",
"'method'",
":",
"'su'",
",",
"'enable_lru'",
":",
"True",
",",
"'kwargs'",
":",
"{",
"'username'",
":",
"spec",
".",
"become_user",
"(",
")",
",",
"'password'",
":",
"spec",
".",
"become_pass",... | Return ContextService arguments for su as a become method. | [
"Return",
"ContextService",
"arguments",
"for",
"su",
"as",
"a",
"become",
"method",
"."
] | python | train |
proycon/pynlpl | pynlpl/formats/folia.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L3263-L3266 | def layers(self, annotationtype=None,set=None):
"""Returns a list of annotation layers found *directly* under this element, does not include alternative layers"""
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
return [ x for x in self.select(AbstractAnnotation... | [
"def",
"layers",
"(",
"self",
",",
"annotationtype",
"=",
"None",
",",
"set",
"=",
"None",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"annotationtype",
")",
":",
"annotationtype",
"=",
"annotationtype",
".",
"ANNOTATIONTYPE",
"return",
"[",
"x",
"for"... | Returns a list of annotation layers found *directly* under this element, does not include alternative layers | [
"Returns",
"a",
"list",
"of",
"annotation",
"layers",
"found",
"*",
"directly",
"*",
"under",
"this",
"element",
"does",
"not",
"include",
"alternative",
"layers"
] | python | train |
pinterest/pymemcache | pymemcache/client/base.py | https://github.com/pinterest/pymemcache/blob/f3a348f4ce2248cce8b398e93e08d984fb9100e5/pymemcache/client/base.py#L504-L526 | def delete(self, key, noreply=None):
"""
The memcached "delete" command.
Args:
key: str, see class docs for details.
noreply: optional bool, True to not wait for the reply (defaults to
self.default_noreply).
Returns:
If noreply is True, ... | [
"def",
"delete",
"(",
"self",
",",
"key",
",",
"noreply",
"=",
"None",
")",
":",
"if",
"noreply",
"is",
"None",
":",
"noreply",
"=",
"self",
".",
"default_noreply",
"cmd",
"=",
"b'delete '",
"+",
"self",
".",
"check_key",
"(",
"key",
")",
"if",
"nore... | The memcached "delete" command.
Args:
key: str, see class docs for details.
noreply: optional bool, True to not wait for the reply (defaults to
self.default_noreply).
Returns:
If noreply is True, always returns True. Otherwise returns True if
... | [
"The",
"memcached",
"delete",
"command",
"."
] | python | train |
senaite/senaite.core.supermodel | src/senaite/core/supermodel/model.py | https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L243-L249 | def brain(self):
"""Catalog brain of the wrapped object
"""
if self._brain is None:
logger.debug("SuperModel::brain: *Fetch catalog brain*")
self._brain = self.get_brain_by_uid(self.uid)
return self._brain | [
"def",
"brain",
"(",
"self",
")",
":",
"if",
"self",
".",
"_brain",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"SuperModel::brain: *Fetch catalog brain*\"",
")",
"self",
".",
"_brain",
"=",
"self",
".",
"get_brain_by_uid",
"(",
"self",
".",
"uid",
"... | Catalog brain of the wrapped object | [
"Catalog",
"brain",
"of",
"the",
"wrapped",
"object"
] | python | train |
selik/xport | xport/v56.py | https://github.com/selik/xport/blob/fafd15a24ccd102fc92d0c0123b9877a0c752182/xport/v56.py#L421-L426 | def header_match(cls, data):
'''
Parse a member namestrs header (1 line, 80 bytes).
'''
mo = cls.header_re.match(data)
return int(mo['n_variables']) | [
"def",
"header_match",
"(",
"cls",
",",
"data",
")",
":",
"mo",
"=",
"cls",
".",
"header_re",
".",
"match",
"(",
"data",
")",
"return",
"int",
"(",
"mo",
"[",
"'n_variables'",
"]",
")"
] | Parse a member namestrs header (1 line, 80 bytes). | [
"Parse",
"a",
"member",
"namestrs",
"header",
"(",
"1",
"line",
"80",
"bytes",
")",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_bin_lib.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_lib.py#L144-L230 | def install_libs(self):
"""Install Required Libraries using pip."""
# default or current python version
lib_data = [{'python_executable': sys.executable, 'lib_dir': self.lib_directory}]
# check for requirements.txt
if not os.path.isfile(self.requirements_file):
self.... | [
"def",
"install_libs",
"(",
"self",
")",
":",
"# default or current python version",
"lib_data",
"=",
"[",
"{",
"'python_executable'",
":",
"sys",
".",
"executable",
",",
"'lib_dir'",
":",
"self",
".",
"lib_directory",
"}",
"]",
"# check for requirements.txt",
"if",... | Install Required Libraries using pip. | [
"Install",
"Required",
"Libraries",
"using",
"pip",
"."
] | python | train |
megacool/flask-canonical | flask_canonical/canonical_logger.py | https://github.com/megacool/flask-canonical/blob/384c10205a1f5eefe859b3ae3c3152327bd4e7b7/flask_canonical/canonical_logger.py#L160-L182 | def get_view_function(app, url, method):
"""Match a url and return the view and arguments
it will be called with, or None if there is no view.
Creds: http://stackoverflow.com/a/38488506
"""
# pylint: disable=too-many-return-statements
adapter = app.create_url_adapter(request)
try:
... | [
"def",
"get_view_function",
"(",
"app",
",",
"url",
",",
"method",
")",
":",
"# pylint: disable=too-many-return-statements",
"adapter",
"=",
"app",
".",
"create_url_adapter",
"(",
"request",
")",
"try",
":",
"match",
"=",
"adapter",
".",
"match",
"(",
"url",
"... | Match a url and return the view and arguments
it will be called with, or None if there is no view.
Creds: http://stackoverflow.com/a/38488506 | [
"Match",
"a",
"url",
"and",
"return",
"the",
"view",
"and",
"arguments",
"it",
"will",
"be",
"called",
"with",
"or",
"None",
"if",
"there",
"is",
"no",
"view",
".",
"Creds",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"3848850... | python | valid |
fabiobatalha/crossrefapi | crossref/restful.py | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L1418-L1427 | def works(self, member_id):
"""
This method retrieve a iterable of Works of the given member.
args: Member ID (Integer)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(member_id))
return Works(context=context) | [
"def",
"works",
"(",
"self",
",",
"member_id",
")",
":",
"context",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"ENDPOINT",
",",
"str",
"(",
"member_id",
")",
")",
"return",
"Works",
"(",
"context",
"=",
"context",
")"
] | This method retrieve a iterable of Works of the given member.
args: Member ID (Integer)
return: Works() | [
"This",
"method",
"retrieve",
"a",
"iterable",
"of",
"Works",
"of",
"the",
"given",
"member",
"."
] | python | train |
openstack/proliantutils | proliantutils/hpssa/objects.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/hpssa/objects.py#L113-L124 | def _convert_to_dict(stdout):
"""Wrapper function for parsing hpssacli/ssacli command.
This function gets the output from hpssacli/ssacli command
and calls the recursive function _get_dict to return
the complete dictionary containing the RAID information.
"""
lines = stdout.split("\n")
lin... | [
"def",
"_convert_to_dict",
"(",
"stdout",
")",
":",
"lines",
"=",
"stdout",
".",
"split",
"(",
"\"\\n\"",
")",
"lines",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"lines",
")",
")",
"info_dict",
",",
"j",
"=",
"_get_dict",
"(",
"lines",
",",
"0",
... | Wrapper function for parsing hpssacli/ssacli command.
This function gets the output from hpssacli/ssacli command
and calls the recursive function _get_dict to return
the complete dictionary containing the RAID information. | [
"Wrapper",
"function",
"for",
"parsing",
"hpssacli",
"/",
"ssacli",
"command",
"."
] | python | train |
chimera0/accel-brain-code | Reinforcement-Learning/pyqlearning/q_learning.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/q_learning.py#L255-L305 | def learn(self, state_key, limit=1000):
'''
Learning and searching the optimal solution.
Args:
state_key: Initial state.
limit: The maximum number of iterative updates based on value iteration algorithms.
'''
self.t = 1
while... | [
"def",
"learn",
"(",
"self",
",",
"state_key",
",",
"limit",
"=",
"1000",
")",
":",
"self",
".",
"t",
"=",
"1",
"while",
"self",
".",
"t",
"<=",
"limit",
":",
"next_action_list",
"=",
"self",
".",
"extract_possible_actions",
"(",
"state_key",
")",
"if"... | Learning and searching the optimal solution.
Args:
state_key: Initial state.
limit: The maximum number of iterative updates based on value iteration algorithms. | [
"Learning",
"and",
"searching",
"the",
"optimal",
"solution",
".",
"Args",
":",
"state_key",
":",
"Initial",
"state",
".",
"limit",
":",
"The",
"maximum",
"number",
"of",
"iterative",
"updates",
"based",
"on",
"value",
"iteration",
"algorithms",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L372-L389 | def overlay_gateway_site_bfd_params_interval_min_tx(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")... | [
"def",
"overlay_gateway_site_bfd_params_interval_min_tx",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
","... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
yymao/generic-catalog-reader | GCR/query.py | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/query.py#L28-L33 | def check_scalar(self, scalar_dict):
"""
check if `scalar_dict` satisfy query
"""
table = {k: np.array([v]) for k, v in scalar_dict.items()}
return self.mask(table)[0] | [
"def",
"check_scalar",
"(",
"self",
",",
"scalar_dict",
")",
":",
"table",
"=",
"{",
"k",
":",
"np",
".",
"array",
"(",
"[",
"v",
"]",
")",
"for",
"k",
",",
"v",
"in",
"scalar_dict",
".",
"items",
"(",
")",
"}",
"return",
"self",
".",
"mask",
"... | check if `scalar_dict` satisfy query | [
"check",
"if",
"scalar_dict",
"satisfy",
"query"
] | python | train |
gem/oq-engine | openquake/baselib/sap.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/sap.py#L116-L128 | def _add(self, name, *args, **kw):
"""
Add an argument to the underlying parser and grow the list
.all_arguments and the set .names
"""
argname = list(self.argdict)[self._argno]
if argname != name:
raise NameError(
'Setting argument %s, but it ... | [
"def",
"_add",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"argname",
"=",
"list",
"(",
"self",
".",
"argdict",
")",
"[",
"self",
".",
"_argno",
"]",
"if",
"argname",
"!=",
"name",
":",
"raise",
"NameError",
"(",
... | Add an argument to the underlying parser and grow the list
.all_arguments and the set .names | [
"Add",
"an",
"argument",
"to",
"the",
"underlying",
"parser",
"and",
"grow",
"the",
"list",
".",
"all_arguments",
"and",
"the",
"set",
".",
"names"
] | python | train |
NiklasRosenstein/py-bundler | bundler/nativedeps/windll.py | https://github.com/NiklasRosenstein/py-bundler/blob/80dd6dc971667ba015f7f67481417c45cc757231/bundler/nativedeps/windll.py#L60-L94 | def get_dependency_walker():
"""
Checks if `depends.exe` is in the system PATH. If not, it will be downloaded
and extracted to a temporary directory. Note that the file will not be
deleted afterwards.
Returns the path to the Dependency Walker executable.
"""
for dirname in os.getenv('PATH', '').split(os... | [
"def",
"get_dependency_walker",
"(",
")",
":",
"for",
"dirname",
"in",
"os",
".",
"getenv",
"(",
"'PATH'",
",",
"''",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'de... | Checks if `depends.exe` is in the system PATH. If not, it will be downloaded
and extracted to a temporary directory. Note that the file will not be
deleted afterwards.
Returns the path to the Dependency Walker executable. | [
"Checks",
"if",
"depends",
".",
"exe",
"is",
"in",
"the",
"system",
"PATH",
".",
"If",
"not",
"it",
"will",
"be",
"downloaded",
"and",
"extracted",
"to",
"a",
"temporary",
"directory",
".",
"Note",
"that",
"the",
"file",
"will",
"not",
"be",
"deleted",
... | python | train |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L231-L238 | def endInstance(self):
"""
Finalise the instance definition started by startInstance().
"""
if self.currentInstance is None:
return
allInstances = self.root.findall('.instances')[0].append(self.currentInstance)
self.currentInstance = None | [
"def",
"endInstance",
"(",
"self",
")",
":",
"if",
"self",
".",
"currentInstance",
"is",
"None",
":",
"return",
"allInstances",
"=",
"self",
".",
"root",
".",
"findall",
"(",
"'.instances'",
")",
"[",
"0",
"]",
".",
"append",
"(",
"self",
".",
"current... | Finalise the instance definition started by startInstance(). | [
"Finalise",
"the",
"instance",
"definition",
"started",
"by",
"startInstance",
"()",
"."
] | python | train |
saltstack/salt | salt/modules/neutron.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L643-L668 | def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin... | [
"def",
"update_router",
"(",
"router",
",",
"name",
"=",
"None",
",",
"admin_state_up",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"update_router",
"(",... | Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gatew... | [
"Updates",
"a",
"router"
] | python | train |
pycontribs/pyrax | pyrax/cloudloadbalancers.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudloadbalancers.py#L1052-L1061 | def _get_lb(self, lb_or_id):
"""
Accepts either a loadbalancer or the ID of a loadbalancer, and returns
the CloudLoadBalancer instance.
"""
if isinstance(lb_or_id, CloudLoadBalancer):
ret = lb_or_id
else:
ret = self.get(lb_or_id)
return ret | [
"def",
"_get_lb",
"(",
"self",
",",
"lb_or_id",
")",
":",
"if",
"isinstance",
"(",
"lb_or_id",
",",
"CloudLoadBalancer",
")",
":",
"ret",
"=",
"lb_or_id",
"else",
":",
"ret",
"=",
"self",
".",
"get",
"(",
"lb_or_id",
")",
"return",
"ret"
] | Accepts either a loadbalancer or the ID of a loadbalancer, and returns
the CloudLoadBalancer instance. | [
"Accepts",
"either",
"a",
"loadbalancer",
"or",
"the",
"ID",
"of",
"a",
"loadbalancer",
"and",
"returns",
"the",
"CloudLoadBalancer",
"instance",
"."
] | python | train |
arokem/python-matlab-bridge | pymatbridge/messenger/make.py | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/messenger/make.py#L88-L118 | def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.
Note
----
This function is taken from the pexpect module, see module d... | [
"def",
"which",
"(",
"filename",
")",
":",
"# Special case where filename contains an explicit path.",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"!=",
"''",
"and",
"is_executable_file",
"(",
"filename",
")",
":",
"return",
"filename",
"if",
... | This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.
Note
----
This function is taken from the pexpect module, see module doc-string for
license. | [
"This",
"takes",
"a",
"given",
"filename",
";",
"tries",
"to",
"find",
"it",
"in",
"the",
"environment",
"path",
";",
"then",
"checks",
"if",
"it",
"is",
"executable",
".",
"This",
"returns",
"the",
"full",
"path",
"to",
"the",
"filename",
"if",
"found",... | python | train |
eandersson/amqpstorm | examples/flask_threaded_rpc_client.py | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/examples/flask_threaded_rpc_client.py#L38-L44 | def _create_process_thread(self):
"""Create a thread responsible for consuming messages in response
to RPC requests.
"""
thread = threading.Thread(target=self._process_data_events)
thread.setDaemon(True)
thread.start() | [
"def",
"_create_process_thread",
"(",
"self",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_process_data_events",
")",
"thread",
".",
"setDaemon",
"(",
"True",
")",
"thread",
".",
"start",
"(",
")"
] | Create a thread responsible for consuming messages in response
to RPC requests. | [
"Create",
"a",
"thread",
"responsible",
"for",
"consuming",
"messages",
"in",
"response",
"to",
"RPC",
"requests",
"."
] | python | train |
idlesign/django-admirarchy | admirarchy/utils.py | https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L56-L92 | def hierarchy_nav(self, obj):
"""Renders hierarchy navigation elements (folders)."""
result_repr = '' # For items without children.
ch_count = getattr(obj, Hierarchy.CHILD_COUNT_MODEL_ATTR, 0)
is_parent_link = getattr(obj, Hierarchy.UPPER_LEVEL_MODEL_ATTR, False)
if is_parent... | [
"def",
"hierarchy_nav",
"(",
"self",
",",
"obj",
")",
":",
"result_repr",
"=",
"''",
"# For items without children.",
"ch_count",
"=",
"getattr",
"(",
"obj",
",",
"Hierarchy",
".",
"CHILD_COUNT_MODEL_ATTR",
",",
"0",
")",
"is_parent_link",
"=",
"getattr",
"(",
... | Renders hierarchy navigation elements (folders). | [
"Renders",
"hierarchy",
"navigation",
"elements",
"(",
"folders",
")",
"."
] | python | train |
peri-source/peri | peri/util.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L34-L59 | def listify(a):
"""
Convert a scalar ``a`` to a list and all iterables to list as well.
Examples
--------
>>> listify(0)
[0]
>>> listify([1,2,3])
[1, 2, 3]
>>> listify('a')
['a']
>>> listify(np.array([1,2,3]))
[1, 2, 3]
>>> listify('string')
['string']
""... | [
"def",
"listify",
"(",
"a",
")",
":",
"if",
"a",
"is",
"None",
":",
"return",
"[",
"]",
"elif",
"not",
"isinstance",
"(",
"a",
",",
"(",
"tuple",
",",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"return",
"[",
"a",
"]",
"return",
"list",
... | Convert a scalar ``a`` to a list and all iterables to list as well.
Examples
--------
>>> listify(0)
[0]
>>> listify([1,2,3])
[1, 2, 3]
>>> listify('a')
['a']
>>> listify(np.array([1,2,3]))
[1, 2, 3]
>>> listify('string')
['string'] | [
"Convert",
"a",
"scalar",
"a",
"to",
"a",
"list",
"and",
"all",
"iterables",
"to",
"list",
"as",
"well",
"."
] | python | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.