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 |
|---|---|---|---|---|---|---|---|---|
abilian/abilian-core | abilian/core/sqlalchemy.py | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L114-L124 | def filter_cols(model, *filtered_columns):
"""Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest
"""
m = sa.orm.class_mapper(model)
return list(
{p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference(
... | [
"def",
"filter_cols",
"(",
"model",
",",
"*",
"filtered_columns",
")",
":",
"m",
"=",
"sa",
".",
"orm",
".",
"class_mapper",
"(",
"model",
")",
"return",
"list",
"(",
"{",
"p",
".",
"key",
"for",
"p",
"in",
"m",
".",
"iterate_properties",
"if",
"hasa... | Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest | [
"Return",
"columnsnames",
"for",
"a",
"model",
"except",
"named",
"ones",
"."
] | python | train |
OpenGov/carpenter | carpenter/carpenter.py | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/carpenter.py#L110-L128 | def split_block_by_row_length(block, split_row_length):
'''
Splits the block by finding all rows with less consequetive, non-empty rows than the
min_row_length input.
'''
split_blocks = []
current_block = []
for row in block:
if row_content_length(row) <= split_row_length:
... | [
"def",
"split_block_by_row_length",
"(",
"block",
",",
"split_row_length",
")",
":",
"split_blocks",
"=",
"[",
"]",
"current_block",
"=",
"[",
"]",
"for",
"row",
"in",
"block",
":",
"if",
"row_content_length",
"(",
"row",
")",
"<=",
"split_row_length",
":",
... | Splits the block by finding all rows with less consequetive, non-empty rows than the
min_row_length input. | [
"Splits",
"the",
"block",
"by",
"finding",
"all",
"rows",
"with",
"less",
"consequetive",
"non",
"-",
"empty",
"rows",
"than",
"the",
"min_row_length",
"input",
"."
] | python | train |
google/openhtf | openhtf/util/conf.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L463-L481 | def help_text(self):
"""Return a string with all config keys and their descriptions."""
result = []
for name in sorted(self._declarations.keys()):
result.append(name)
result.append('-' * len(name))
decl = self._declarations[name]
if decl.description:
result.append(decl.descri... | [
"def",
"help_text",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"sorted",
"(",
"self",
".",
"_declarations",
".",
"keys",
"(",
")",
")",
":",
"result",
".",
"append",
"(",
"name",
")",
"result",
".",
"append",
"(",
"'-'",
... | Return a string with all config keys and their descriptions. | [
"Return",
"a",
"string",
"with",
"all",
"config",
"keys",
"and",
"their",
"descriptions",
"."
] | python | train |
stbraun/fuzzing | features/steps/ft_singleton.py | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_singleton.py#L74-L80 | def step_impl07(context):
"""Test for singleton property.
:param context: test context.
"""
assert context.st_1 is context.st_2
assert context.st_2 is context.st_3 | [
"def",
"step_impl07",
"(",
"context",
")",
":",
"assert",
"context",
".",
"st_1",
"is",
"context",
".",
"st_2",
"assert",
"context",
".",
"st_2",
"is",
"context",
".",
"st_3"
] | Test for singleton property.
:param context: test context. | [
"Test",
"for",
"singleton",
"property",
"."
] | python | train |
entrepreneur-interet-general/mkinx | mkinx/commands.py | https://github.com/entrepreneur-interet-general/mkinx/blob/70ccf81d3fad974283829ca4ec069a873341461d/mkinx/commands.py#L141-L243 | def build(args):
"""Build the documentation for the projects specified in the CLI.
It will do 4 different things for each project the
user asks for (see flags):
1. Update mkdocs's index.md file with links to project
documentations
2. Build these documentations
3. Update th... | [
"def",
"build",
"(",
"args",
")",
":",
"# Proceed?",
"go",
"=",
"False",
"# Current working directory",
"dir_path",
"=",
"Path",
"(",
")",
".",
"resolve",
"(",
")",
"# Set of all available projects in the dir",
"# Projects must contain a PROJECT_MARKER file.",
"all_projec... | Build the documentation for the projects specified in the CLI.
It will do 4 different things for each project the
user asks for (see flags):
1. Update mkdocs's index.md file with links to project
documentations
2. Build these documentations
3. Update the documentations' index.... | [
"Build",
"the",
"documentation",
"for",
"the",
"projects",
"specified",
"in",
"the",
"CLI",
".",
"It",
"will",
"do",
"4",
"different",
"things",
"for",
"each",
"project",
"the",
"user",
"asks",
"for",
"(",
"see",
"flags",
")",
":",
"1",
".",
"Update",
... | python | train |
librosa/librosa | librosa/core/harmonic.py | https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/harmonic.py#L13-L104 | def salience(S, freqs, h_range, weights=None, aggregate=None,
filter_peaks=True, fill_value=np.nan, kind='linear', axis=0):
"""Harmonic salience function.
Parameters
----------
S : np.ndarray [shape=(d, n)]
input time frequency magnitude representation (stft, ifgram, etc).
... | [
"def",
"salience",
"(",
"S",
",",
"freqs",
",",
"h_range",
",",
"weights",
"=",
"None",
",",
"aggregate",
"=",
"None",
",",
"filter_peaks",
"=",
"True",
",",
"fill_value",
"=",
"np",
".",
"nan",
",",
"kind",
"=",
"'linear'",
",",
"axis",
"=",
"0",
... | Harmonic salience function.
Parameters
----------
S : np.ndarray [shape=(d, n)]
input time frequency magnitude representation (stft, ifgram, etc).
Must be real-valued and non-negative.
freqs : np.ndarray, shape=(S.shape[axis])
The frequency values corresponding to S's elements a... | [
"Harmonic",
"salience",
"function",
"."
] | python | test |
henzk/django-productline | django_productline/features/staticfiles/tasks.py | https://github.com/henzk/django-productline/blob/24ff156924c1a8c07b99cbb8a1de0a42b8d81f60/django_productline/features/staticfiles/tasks.py#L8-L22 | def collectstatic(force=False):
"""
collect static files for production httpd
If run with ``settings.DEBUG==True``, this is a no-op
unless ``force`` is set to ``True``
"""
# noise reduction: only collectstatic if not in debug mode
from django.conf import settings
if force or not setting... | [
"def",
"collectstatic",
"(",
"force",
"=",
"False",
")",
":",
"# noise reduction: only collectstatic if not in debug mode",
"from",
"django",
".",
"conf",
"import",
"settings",
"if",
"force",
"or",
"not",
"settings",
".",
"DEBUG",
":",
"tasks",
".",
"manage",
"(",... | collect static files for production httpd
If run with ``settings.DEBUG==True``, this is a no-op
unless ``force`` is set to ``True`` | [
"collect",
"static",
"files",
"for",
"production",
"httpd"
] | python | train |
pypa/pipenv | pipenv/patched/notpip/_internal/vcs/bazaar.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/vcs/bazaar.py#L37-L51 | def export(self, location):
"""
Export the Bazaar repository at the url to the destination location
"""
# Remove the location to make sure Bazaar can export it correctly
if os.path.exists(location):
rmtree(location)
with TempDirectory(kind="export") as temp_d... | [
"def",
"export",
"(",
"self",
",",
"location",
")",
":",
"# Remove the location to make sure Bazaar can export it correctly",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"rmtree",
"(",
"location",
")",
"with",
"TempDirectory",
"(",
"kind",
... | Export the Bazaar repository at the url to the destination location | [
"Export",
"the",
"Bazaar",
"repository",
"at",
"the",
"url",
"to",
"the",
"destination",
"location"
] | python | train |
Tivix/django-common | django_common/db_fields.py | https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/db_fields.py#L46-L55 | def get_prep_value(self, value):
"""Convert our JSON object to a string before we save"""
if value == "":
return None
if isinstance(value, dict):
value = json.dumps(value, cls=DjangoJSONEncoder)
return value | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"\"\"",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value",
"=",
"json",
".",
"dumps",
"(",
"value",
",",
"cls",
"=",
"DjangoJSONE... | Convert our JSON object to a string before we save | [
"Convert",
"our",
"JSON",
"object",
"to",
"a",
"string",
"before",
"we",
"save"
] | python | train |
kimdhamilton/merkle-proofs | merkleproof/MerkleTree.py | https://github.com/kimdhamilton/merkle-proofs/blob/77551cc65f72b50ac203f10a5069cb1a5b3ffb49/merkleproof/MerkleTree.py#L162-L171 | def validate_proof(self, proof, target_hash, merkle_root):
"""
Takes a proof array, a target hash value, and a merkle root
Checks the validity of the proof and return true or false
:param proof:
:param target_hash:
:param merkle_root:
:return:
"""
... | [
"def",
"validate_proof",
"(",
"self",
",",
"proof",
",",
"target_hash",
",",
"merkle_root",
")",
":",
"return",
"validate_proof",
"(",
"proof",
",",
"target_hash",
",",
"merkle_root",
",",
"self",
".",
"hash_f",
")"
] | Takes a proof array, a target hash value, and a merkle root
Checks the validity of the proof and return true or false
:param proof:
:param target_hash:
:param merkle_root:
:return: | [
"Takes",
"a",
"proof",
"array",
"a",
"target",
"hash",
"value",
"and",
"a",
"merkle",
"root",
"Checks",
"the",
"validity",
"of",
"the",
"proof",
"and",
"return",
"true",
"or",
"false",
":",
"param",
"proof",
":",
":",
"param",
"target_hash",
":",
":",
... | python | train |
myusuf3/delorean | delorean/interface.py | https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/interface.py#L116-L121 | def range_hourly(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
HOURLY stops
"""
return stops(start=start, stop=stop, freq=HOURLY, timezone=timezone, count=count) | [
"def",
"range_hourly",
"(",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"timezone",
"=",
"'UTC'",
",",
"count",
"=",
"None",
")",
":",
"return",
"stops",
"(",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"freq",
"=",
"HOURLY",
","... | This an alternative way to generating sets of Delorean objects with
HOURLY stops | [
"This",
"an",
"alternative",
"way",
"to",
"generating",
"sets",
"of",
"Delorean",
"objects",
"with",
"HOURLY",
"stops"
] | python | train |
apache/airflow | airflow/utils/timezone.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/timezone.py#L82-L95 | def convert_to_utc(value):
"""
Returns the datetime with the default timezone added if timezone
information was not associated
:param value: datetime
:return: datetime with tzinfo
"""
if not value:
return value
if not is_localized(value):
value = pendulum.instance(value,... | [
"def",
"convert_to_utc",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"value",
"if",
"not",
"is_localized",
"(",
"value",
")",
":",
"value",
"=",
"pendulum",
".",
"instance",
"(",
"value",
",",
"TIMEZONE",
")",
"return",
"value",
".",
"... | Returns the datetime with the default timezone added if timezone
information was not associated
:param value: datetime
:return: datetime with tzinfo | [
"Returns",
"the",
"datetime",
"with",
"the",
"default",
"timezone",
"added",
"if",
"timezone",
"information",
"was",
"not",
"associated",
":",
"param",
"value",
":",
"datetime",
":",
"return",
":",
"datetime",
"with",
"tzinfo"
] | python | test |
Diaoul/pyjulius | pyjulius/core.py | https://github.com/Diaoul/pyjulius/blob/48f2752ff4e0f3bd7b578754b1c583cabdc24b09/pyjulius/core.py#L191-L203 | def _readxml(self):
"""Read a block and return the result as XML
:return: block as xml
:rtype: xml.etree.ElementTree
"""
block = re.sub(r'<(/?)s>', r'<\1s>', self._readblock())
try:
xml = XML(block)
except ParseError:
xml = None
... | [
"def",
"_readxml",
"(",
"self",
")",
":",
"block",
"=",
"re",
".",
"sub",
"(",
"r'<(/?)s>'",
",",
"r'<\\1s>'",
",",
"self",
".",
"_readblock",
"(",
")",
")",
"try",
":",
"xml",
"=",
"XML",
"(",
"block",
")",
"except",
"ParseError",
":",
"xml",
... | Read a block and return the result as XML
:return: block as xml
:rtype: xml.etree.ElementTree | [
"Read",
"a",
"block",
"and",
"return",
"the",
"result",
"as",
"XML"
] | python | valid |
thespacedoctor/neddy | neddy/_basesearch.py | https://github.com/thespacedoctor/neddy/blob/f32653b7d6a39a2c46c5845f83b3a29056311e5e/neddy/_basesearch.py#L88-L146 | def _parse_the_ned_position_results(
self,
ra,
dec,
nedResults):
"""
*parse the ned results*
**Key Arguments:**
- ``ra`` -- the search ra
- ``dec`` -- the search dec
**Return:**
- ``results`` -- list of... | [
"def",
"_parse_the_ned_position_results",
"(",
"self",
",",
"ra",
",",
"dec",
",",
"nedResults",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_parse_the_ned_results`` method'",
")",
"results",
"=",
"[",
"]",
"resultLen",
"=",
"0",
"if",
"ne... | *parse the ned results*
**Key Arguments:**
- ``ra`` -- the search ra
- ``dec`` -- the search dec
**Return:**
- ``results`` -- list of result dictionaries | [
"*",
"parse",
"the",
"ned",
"results",
"*"
] | python | train |
tensorflow/cleverhans | cleverhans/attacks/deep_fool.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L168-L252 | def deepfool_attack(sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
... | [
"def",
"deepfool_attack",
"(",
"sess",
",",
"x",
",",
"predictions",
",",
"logits",
",",
"grads",
",",
"sample",
",",
"nb_candidate",
",",
"overshoot",
",",
"max_iter",
",",
"clip_min",
",",
"clip_max",
",",
"feed",
"=",
"None",
")",
":",
"adv_x",
"=",
... | TensorFlow implementation of DeepFool.
Paper link: see https://arxiv.org/pdf/1511.04599.pdf
:param sess: TF session
:param x: The input placeholder
:param predictions: The model's sorted symbolic output of logits, only the
top nb_candidate classes are contained
:param logits: The model's ... | [
"TensorFlow",
"implementation",
"of",
"DeepFool",
".",
"Paper",
"link",
":",
"see",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1511",
".",
"04599",
".",
"pdf",
":",
"param",
"sess",
":",
"TF",
"session",
":",
"param",
"x",
":",
"The",... | python | train |
unitedstack/steth | stetho/agent/api.py | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/api.py#L132-L141 | def setup_iperf_server(self, protocol='TCP', port=5001, window=None):
"""iperf -s
"""
iperf = iperf_driver.IPerfDriver()
try:
data = iperf.start_server(protocol='TCP', port=5001, window=None)
return agent_utils.make_response(code=0, data=data)
except:
... | [
"def",
"setup_iperf_server",
"(",
"self",
",",
"protocol",
"=",
"'TCP'",
",",
"port",
"=",
"5001",
",",
"window",
"=",
"None",
")",
":",
"iperf",
"=",
"iperf_driver",
".",
"IPerfDriver",
"(",
")",
"try",
":",
"data",
"=",
"iperf",
".",
"start_server",
... | iperf -s | [
"iperf",
"-",
"s"
] | python | train |
leancloud/python-sdk | leancloud/object_.py | https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/object_.py#L466-L474 | def remove(self, attr, item):
"""
在对象此字段对应的数组中,将指定对象全部移除。
:param attr: 字段名
:param item: 要移除的对象
:return: 当前对象
"""
return self.set(attr, operation.Remove([item])) | [
"def",
"remove",
"(",
"self",
",",
"attr",
",",
"item",
")",
":",
"return",
"self",
".",
"set",
"(",
"attr",
",",
"operation",
".",
"Remove",
"(",
"[",
"item",
"]",
")",
")"
] | 在对象此字段对应的数组中,将指定对象全部移除。
:param attr: 字段名
:param item: 要移除的对象
:return: 当前对象 | [
"在对象此字段对应的数组中,将指定对象全部移除。"
] | python | train |
hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2906-L2941 | def _execute_pep8(pep8_options, source):
"""Execute pycodestyle via python method calls."""
class QuietReport(pycodestyle.BaseReport):
"""Version of checker that does not print."""
def __init__(self, options):
super(QuietReport, self).__init__(options)
self.__full_error... | [
"def",
"_execute_pep8",
"(",
"pep8_options",
",",
"source",
")",
":",
"class",
"QuietReport",
"(",
"pycodestyle",
".",
"BaseReport",
")",
":",
"\"\"\"Version of checker that does not print.\"\"\"",
"def",
"__init__",
"(",
"self",
",",
"options",
")",
":",
"super",
... | Execute pycodestyle via python method calls. | [
"Execute",
"pycodestyle",
"via",
"python",
"method",
"calls",
"."
] | python | train |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L175-L186 | def set_name(self, new_name):
"""
Renames this Ethernet switch.
:param new_name: New name for this switch
"""
yield from self._hypervisor.send('ethsw rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name))
log.info('Ethernet switch "{name}" [{id}]: ren... | [
"def",
"set_name",
"(",
"self",
",",
"new_name",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'ethsw rename \"{name}\" \"{new_name}\"'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"new_name",
"=",
"new_name",
")"... | Renames this Ethernet switch.
:param new_name: New name for this switch | [
"Renames",
"this",
"Ethernet",
"switch",
"."
] | python | train |
ulfalizer/Kconfiglib | kconfiglib.py | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/kconfiglib.py#L1448-L1544 | def sync_deps(self, path):
"""
Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each build, before
compili... | [
"def",
"sync_deps",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"exists",
"(",
"path",
")",
":",
"os",
".",
"mkdir",
"(",
"path",
",",
"0o755",
")",
"# Load old values from auto.conf, if any",
"self",
".",
"_load_old_vals",
"(",
"path",
")",
"for",
... | Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each build, before
compiling source files that depend on configuration sy... | [
"Creates",
"or",
"updates",
"a",
"directory",
"structure",
"that",
"can",
"be",
"used",
"to",
"avoid",
"doing",
"a",
"full",
"rebuild",
"whenever",
"the",
"configuration",
"is",
"changed",
"mirroring",
"include",
"/",
"config",
"/",
"in",
"the",
"kernel",
".... | python | train |
sibirrer/lenstronomy | lenstronomy/Util/simulation_util.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Util/simulation_util.py#L36-L68 | def psf_configure_simple(psf_type="GAUSSIAN", fwhm=1, kernelsize=11, deltaPix=1, truncate=6, kernel=None):
"""
this routine generates keyword arguments to initialize a PSF() class in lenstronomy. Have a look at the PSF class
documentation to see the full possibilities.
:param psf_type: string, type of ... | [
"def",
"psf_configure_simple",
"(",
"psf_type",
"=",
"\"GAUSSIAN\"",
",",
"fwhm",
"=",
"1",
",",
"kernelsize",
"=",
"11",
",",
"deltaPix",
"=",
"1",
",",
"truncate",
"=",
"6",
",",
"kernel",
"=",
"None",
")",
":",
"if",
"psf_type",
"==",
"'GAUSSIAN'",
... | this routine generates keyword arguments to initialize a PSF() class in lenstronomy. Have a look at the PSF class
documentation to see the full possibilities.
:param psf_type: string, type of PSF model
:param fwhm: Full width at half maximum of PSF (if GAUSSIAN psf)
:param kernelsize: size in pixel of ... | [
"this",
"routine",
"generates",
"keyword",
"arguments",
"to",
"initialize",
"a",
"PSF",
"()",
"class",
"in",
"lenstronomy",
".",
"Have",
"a",
"look",
"at",
"the",
"PSF",
"class",
"documentation",
"to",
"see",
"the",
"full",
"possibilities",
"."
] | python | train |
cloud9ers/gurumate | environment/share/doc/ipython/examples/parallel/pi/pidigits.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/pi/pidigits.py#L64-L70 | def compute_n_digit_freqs(filename, n):
"""
Read digits of pi from a file and compute the n digit frequencies.
"""
d = txt_file_to_digits(filename)
freqs = n_digit_freqs(d, n)
return freqs | [
"def",
"compute_n_digit_freqs",
"(",
"filename",
",",
"n",
")",
":",
"d",
"=",
"txt_file_to_digits",
"(",
"filename",
")",
"freqs",
"=",
"n_digit_freqs",
"(",
"d",
",",
"n",
")",
"return",
"freqs"
] | Read digits of pi from a file and compute the n digit frequencies. | [
"Read",
"digits",
"of",
"pi",
"from",
"a",
"file",
"and",
"compute",
"the",
"n",
"digit",
"frequencies",
"."
] | python | test |
keon/algorithms | algorithms/matrix/multiply.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/matrix/multiply.py#L10-L28 | def multiply(multiplicand: list, multiplier: list) -> list:
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
multiplicand_row, multiplicand_col = len(
multiplicand), len(multiplicand[0])
multiplier_row, multiplier_col = len(multiplier), len(multiplier... | [
"def",
"multiply",
"(",
"multiplicand",
":",
"list",
",",
"multiplier",
":",
"list",
")",
"->",
"list",
":",
"multiplicand_row",
",",
"multiplicand_col",
"=",
"len",
"(",
"multiplicand",
")",
",",
"len",
"(",
"multiplicand",
"[",
"0",
"]",
")",
"multiplier... | :type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]] | [
":",
"type",
"A",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"type",
"B",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] | python | train |
weld-project/weld | python/pyweld/weld/bindings.py | https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/pyweld/weld/bindings.py#L53-L72 | def run(self, conf, arg, err):
"""
WeldContext is currently hidden from the Python API. We create a new
context per Weld run and give ownership of it to the resulting value.
NOTE: This can leak the context if the result of the Weld run is an
error.
"""
weld_conte... | [
"def",
"run",
"(",
"self",
",",
"conf",
",",
"arg",
",",
"err",
")",
":",
"weld_context_new",
"=",
"weld",
".",
"weld_context_new",
"weld_context_new",
".",
"argtypes",
"=",
"[",
"c_weld_conf",
"]",
"weld_context_new",
".",
"restype",
"=",
"c_weld_context",
... | WeldContext is currently hidden from the Python API. We create a new
context per Weld run and give ownership of it to the resulting value.
NOTE: This can leak the context if the result of the Weld run is an
error. | [
"WeldContext",
"is",
"currently",
"hidden",
"from",
"the",
"Python",
"API",
".",
"We",
"create",
"a",
"new",
"context",
"per",
"Weld",
"run",
"and",
"give",
"ownership",
"of",
"it",
"to",
"the",
"resulting",
"value",
"."
] | python | train |
croscon/fleaker | fleaker/config.py | https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/config.py#L346-L379 | def _run_post_configure_callbacks(self, configure_args):
"""Run all post configure callbacks we have stored.
Functions are passed the configuration that resulted from the call to
:meth:`configure` as the first argument, in an immutable form; and are
given the arguments passed to :meth:`... | [
"def",
"_run_post_configure_callbacks",
"(",
"self",
",",
"configure_args",
")",
":",
"resulting_configuration",
"=",
"ImmutableDict",
"(",
"self",
".",
"config",
")",
"# copy callbacks in case people edit them while running",
"multiple_callbacks",
"=",
"copy",
".",
"copy",... | Run all post configure callbacks we have stored.
Functions are passed the configuration that resulted from the call to
:meth:`configure` as the first argument, in an immutable form; and are
given the arguments passed to :meth:`configure` for the second
argument.
Returns from ca... | [
"Run",
"all",
"post",
"configure",
"callbacks",
"we",
"have",
"stored",
"."
] | python | train |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L438-L453 | def ftp_close(self, connId='default'):
"""
Closes FTP connection. Returns None.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
try:
thisConn.quit()
self.__remo... | [
"def",
"ftp_close",
"(",
"self",
",",
"connId",
"=",
"'default'",
")",
":",
"thisConn",
"=",
"self",
".",
"__getConnection",
"(",
"connId",
")",
"try",
":",
"thisConn",
".",
"quit",
"(",
")",
"self",
".",
"__removeConnection",
"(",
"connId",
")",
"except... | Closes FTP connection. Returns None.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | [
"Closes",
"FTP",
"connection",
".",
"Returns",
"None",
".",
"Parameters",
":",
"-",
"connId",
"(",
"optional",
")",
"-",
"connection",
"identifier",
".",
"By",
"default",
"equals",
"default"
] | python | train |
uber/tchannel-python | tchannel/tornado/tchannel.py | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/tchannel.py#L189-L232 | def advertise(
self,
routers=None,
name=None,
timeout=None,
router_file=None,
jitter=None,
):
"""Make a service available on the Hyperbahn routing mesh.
This will make contact with a Hyperbahn host from a list of known
Hyperbahn routers. Addit... | [
"def",
"advertise",
"(",
"self",
",",
"routers",
"=",
"None",
",",
"name",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"router_file",
"=",
"None",
",",
"jitter",
"=",
"None",
",",
")",
":",
"name",
"=",
"name",
"or",
"self",
".",
"name",
"if",
... | Make a service available on the Hyperbahn routing mesh.
This will make contact with a Hyperbahn host from a list of known
Hyperbahn routers. Additional Hyperbahn connections will be established
once contact has been made with the network.
:param router:
A seed list of addre... | [
"Make",
"a",
"service",
"available",
"on",
"the",
"Hyperbahn",
"routing",
"mesh",
"."
] | python | train |
mwouts/jupytext | jupytext/cell_metadata.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_metadata.py#L213-L251 | def rmd_options_to_metadata(options):
"""
Parse rmd options and return a metadata dictionary
:param options:
:return:
"""
options = re.split(r'\s|,', options, 1)
if len(options) == 1:
language = options[0]
chunk_options = []
else:
language, others = options
... | [
"def",
"rmd_options_to_metadata",
"(",
"options",
")",
":",
"options",
"=",
"re",
".",
"split",
"(",
"r'\\s|,'",
",",
"options",
",",
"1",
")",
"if",
"len",
"(",
"options",
")",
"==",
"1",
":",
"language",
"=",
"options",
"[",
"0",
"]",
"chunk_options"... | Parse rmd options and return a metadata dictionary
:param options:
:return: | [
"Parse",
"rmd",
"options",
"and",
"return",
"a",
"metadata",
"dictionary",
":",
"param",
"options",
":",
":",
"return",
":"
] | python | train |
AdvancedClimateSystems/uModbus | umodbus/client/serial/redundancy_check.py | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/redundancy_check.py#L34-L56 | def get_crc(msg):
""" Return CRC of 2 byte for message.
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes.
"""
register = 0xFFFF
for byte_ in msg:
try:
val = struct.unpack('<B', byte_)[0]
... | [
"def",
"get_crc",
"(",
"msg",
")",
":",
"register",
"=",
"0xFFFF",
"for",
"byte_",
"in",
"msg",
":",
"try",
":",
"val",
"=",
"struct",
".",
"unpack",
"(",
"'<B'",
",",
"byte_",
")",
"[",
"0",
"]",
"# Iterating over a bit-like objects in Python 3 gets you int... | Return CRC of 2 byte for message.
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes. | [
"Return",
"CRC",
"of",
"2",
"byte",
"for",
"message",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L6739-L6747 | def _from_dict(cls, _dict):
"""Initialize a ListConfigurationsResponse object from a json dictionary."""
args = {}
if 'configurations' in _dict:
args['configurations'] = [
Configuration._from_dict(x)
for x in (_dict.get('configurations'))
]... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'configurations'",
"in",
"_dict",
":",
"args",
"[",
"'configurations'",
"]",
"=",
"[",
"Configuration",
".",
"_from_dict",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"_... | Initialize a ListConfigurationsResponse object from a json dictionary. | [
"Initialize",
"a",
"ListConfigurationsResponse",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | python | train |
Robpol86/colorclass | colorclass/core.py | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/core.py#L37-L48 | def decode(self, encoding='utf-8', errors='strict'):
"""Decode using the codec registered for encoding. Default encoding is 'utf-8'.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possible values a... | [
"def",
"decode",
"(",
"self",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"original_class",
"=",
"getattr",
"(",
"self",
",",
"'original_class'",
")",
"return",
"original_class",
"(",
"super",
"(",
"ColorBytes",
",",
"self",
... | Decode using the codec registered for encoding. Default encoding is 'utf-8'.
errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name
regi... | [
"Decode",
"using",
"the",
"codec",
"registered",
"for",
"encoding",
".",
"Default",
"encoding",
"is",
"utf",
"-",
"8",
"."
] | python | train |
hubo1016/vlcp | vlcp/server/module.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L781-L806 | async def batch_call_api(container, apis, timeout = 120.0):
"""
DEPRECATED - use execute_all instead
"""
apiHandles = [(object(), api) for api in apis]
apiEvents = [ModuleAPICall(handle, targetname, name, params = params)
for handle, (targetname, name, params) in apiHandles]
api... | [
"async",
"def",
"batch_call_api",
"(",
"container",
",",
"apis",
",",
"timeout",
"=",
"120.0",
")",
":",
"apiHandles",
"=",
"[",
"(",
"object",
"(",
")",
",",
"api",
")",
"for",
"api",
"in",
"apis",
"]",
"apiEvents",
"=",
"[",
"ModuleAPICall",
"(",
"... | DEPRECATED - use execute_all instead | [
"DEPRECATED",
"-",
"use",
"execute_all",
"instead"
] | python | train |
wummel/linkchecker | third_party/dnspython/dns/renderer.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/renderer.py#L138-L157 | def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN):
"""Add a question to the message.
@param qname: the question name
@type qname: dns.name.Name
@param rdtype: the question rdata type
@type rdtype: int
@param rdclass: the question rdata class
@type ... | [
"def",
"add_question",
"(",
"self",
",",
"qname",
",",
"rdtype",
",",
"rdclass",
"=",
"dns",
".",
"rdataclass",
".",
"IN",
")",
":",
"self",
".",
"_set_section",
"(",
"QUESTION",
")",
"before",
"=",
"self",
".",
"output",
".",
"tell",
"(",
")",
"qnam... | Add a question to the message.
@param qname: the question name
@type qname: dns.name.Name
@param rdtype: the question rdata type
@type rdtype: int
@param rdclass: the question rdata class
@type rdclass: int | [
"Add",
"a",
"question",
"to",
"the",
"message",
"."
] | python | train |
sosy-lab/benchexec | benchexec/model.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/model.py#L672-L697 | def expand_filename_pattern(self, pattern, base_dir, sourcefile=None):
"""
The function expand_filename_pattern expands a filename pattern to a sorted list
of filenames. The pattern can contain variables and wildcards.
If base_dir is given and pattern is not absolute, base_dir and patter... | [
"def",
"expand_filename_pattern",
"(",
"self",
",",
"pattern",
",",
"base_dir",
",",
"sourcefile",
"=",
"None",
")",
":",
"# replace vars like ${benchmark_path},",
"# with converting to list and back, we can use the function 'substitute_vars()'",
"expandedPattern",
"=",
"substitu... | The function expand_filename_pattern expands a filename pattern to a sorted list
of filenames. The pattern can contain variables and wildcards.
If base_dir is given and pattern is not absolute, base_dir and pattern are joined. | [
"The",
"function",
"expand_filename_pattern",
"expands",
"a",
"filename",
"pattern",
"to",
"a",
"sorted",
"list",
"of",
"filenames",
".",
"The",
"pattern",
"can",
"contain",
"variables",
"and",
"wildcards",
".",
"If",
"base_dir",
"is",
"given",
"and",
"pattern",... | python | train |
orbingol/NURBS-Python | geomdl/operations.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1054-L1078 | def length_curve(obj):
""" Computes the approximate length of the parametric curve.
Uses the following equation to compute the approximate length:
.. math::
\\sum_{i=0}^{n-1} \\sqrt{P_{i + 1}^2-P_{i}^2}
where :math:`n` is number of evaluated curve points and :math:`P` is the n-dimensional po... | [
"def",
"length_curve",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"abstract",
".",
"Curve",
")",
":",
"raise",
"GeomdlException",
"(",
"\"Input shape must be an instance of abstract.Curve class\"",
")",
"length",
"=",
"0.0",
"evalpts",
"=",
... | Computes the approximate length of the parametric curve.
Uses the following equation to compute the approximate length:
.. math::
\\sum_{i=0}^{n-1} \\sqrt{P_{i + 1}^2-P_{i}^2}
where :math:`n` is number of evaluated curve points and :math:`P` is the n-dimensional point.
:param obj: input cur... | [
"Computes",
"the",
"approximate",
"length",
"of",
"the",
"parametric",
"curve",
"."
] | python | train |
SuperCowPowers/workbench | workbench/server/workbench_server.py | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L844-L874 | def run():
""" Run the workbench server """
# Load the configuration file relative to this script location
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
workbench_conf = ConfigParser.ConfigParser()
config_ini = workbench_conf.read(config_path)
if not conf... | [
"def",
"run",
"(",
")",
":",
"# Load the configuration file relative to this script location",
"config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
","... | Run the workbench server | [
"Run",
"the",
"workbench",
"server"
] | python | train |
JoeVirtual/KonFoo | konfoo/core.py | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L1080-L1102 | def extend(self, iterable):
""" Extends the `Sequence` by appending items from the *iterable*.
:param iterable: any *iterable* that contains items of :class:`Structure`,
:class:`Sequence`, :class:`Array` or :class:`Field` instances. If the
*iterable* is one of these instances it... | [
"def",
"extend",
"(",
"self",
",",
"iterable",
")",
":",
"# Sequence",
"if",
"is_sequence",
"(",
"iterable",
")",
":",
"self",
".",
"_data",
".",
"extend",
"(",
"iterable",
")",
"# Structure",
"elif",
"is_structure",
"(",
"iterable",
")",
":",
"members",
... | Extends the `Sequence` by appending items from the *iterable*.
:param iterable: any *iterable* that contains items of :class:`Structure`,
:class:`Sequence`, :class:`Array` or :class:`Field` instances. If the
*iterable* is one of these instances itself then the *iterable* itself
... | [
"Extends",
"the",
"Sequence",
"by",
"appending",
"items",
"from",
"the",
"*",
"iterable",
"*",
"."
] | python | train |
marshmallow-code/flask-marshmallow | src/flask_marshmallow/__init__.py | https://github.com/marshmallow-code/flask-marshmallow/blob/8483fa55cab47f0d0ed23e3fa876b22a1d8e7873/src/flask_marshmallow/__init__.py#L105-L116 | def init_app(self, app):
"""Initializes the application with the extension.
:param Flask app: The Flask application object.
"""
app.extensions = getattr(app, "extensions", {})
# If using Flask-SQLAlchemy, attach db.session to ModelSchema
if has_sqla and "sqlalchemy" in ... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"extensions",
"=",
"getattr",
"(",
"app",
",",
"\"extensions\"",
",",
"{",
"}",
")",
"# If using Flask-SQLAlchemy, attach db.session to ModelSchema",
"if",
"has_sqla",
"and",
"\"sqlalchemy\"",
"in",... | Initializes the application with the extension.
:param Flask app: The Flask application object. | [
"Initializes",
"the",
"application",
"with",
"the",
"extension",
"."
] | python | train |
michael-lazar/rtv | rtv/packages/praw/__init__.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L1966-L1985 | def get_mod_log(self, subreddit, mod=None, action=None, *args, **kwargs):
"""Return a get_content generator for moderation log items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the modlog for.
:param mod: If given, only return the actions made... | [
"def",
"get_mod_log",
"(",
"self",
",",
"subreddit",
",",
"mod",
"=",
"None",
",",
"action",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"kwargs",
".",
"setdefault",
"(",
"'params'",
",",
"{",
"}",
")",
"if",
... | Return a get_content generator for moderation log items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the modlog for.
:param mod: If given, only return the actions made by this moderator.
Both a moderator name or Redditor object can be used ... | [
"Return",
"a",
"get_content",
"generator",
"for",
"moderation",
"log",
"items",
"."
] | python | train |
openpermissions/chub | chub/api.py | https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L150-L158 | def login(self, email, password):
"""
login using email and password
:param email: email address
:param password: password
"""
rsp = self._request()
self.default_headers['Authorization'] = rsp.data['token']
return rsp | [
"def",
"login",
"(",
"self",
",",
"email",
",",
"password",
")",
":",
"rsp",
"=",
"self",
".",
"_request",
"(",
")",
"self",
".",
"default_headers",
"[",
"'Authorization'",
"]",
"=",
"rsp",
".",
"data",
"[",
"'token'",
"]",
"return",
"rsp"
] | login using email and password
:param email: email address
:param password: password | [
"login",
"using",
"email",
"and",
"password",
":",
"param",
"email",
":",
"email",
"address",
":",
"param",
"password",
":",
"password"
] | python | train |
OpenKMIP/PyKMIP | kmip/core/messages/payloads/create.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/messages/payloads/create.py#L95-L161 | def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Create request payload and decode it into
its constituent parts.
Args:
input_buffer (stream): A data buffer containing encoded object
data, supporting a read... | [
"def",
"read",
"(",
"self",
",",
"input_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"CreateRequestPayload",
",",
"self",
")",
".",
"read",
"(",
"input_buffer",
",",
"kmip_version",
"=",
"kmip_versi... | Read the data encoding the Create request payload and decode it into
its constituent parts.
Args:
input_buffer (stream): A data buffer containing encoded object
data, supporting a read method.
kmip_version (KMIPVersion): An enumeration defining the KMIP
... | [
"Read",
"the",
"data",
"encoding",
"the",
"Create",
"request",
"payload",
"and",
"decode",
"it",
"into",
"its",
"constituent",
"parts",
"."
] | python | test |
rafaelsierra/django-json-mixin-form | src/sierra/dj/mixins/forms.py | https://github.com/rafaelsierra/django-json-mixin-form/blob/004149a1077eba8c072ebbfb6eb6b86a57564ecf/src/sierra/dj/mixins/forms.py#L52-L58 | def _get_field_error_dict(self, field):
'''Returns the dict containing the field errors information'''
return {
'name': field.html_name,
'id': 'id_{}'.format(field.html_name), # This may be a problem
'errors': field.errors,
} | [
"def",
"_get_field_error_dict",
"(",
"self",
",",
"field",
")",
":",
"return",
"{",
"'name'",
":",
"field",
".",
"html_name",
",",
"'id'",
":",
"'id_{}'",
".",
"format",
"(",
"field",
".",
"html_name",
")",
",",
"# This may be a problem",
"'errors'",
":",
... | Returns the dict containing the field errors information | [
"Returns",
"the",
"dict",
"containing",
"the",
"field",
"errors",
"information"
] | python | train |
collectiveacuity/labPack | labpack/storage/aws/s3.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/storage/aws/s3.py#L790-L867 | def delete_bucket(self, bucket_name):
'''
a method to delete a bucket in s3 and all its contents
:param bucket_name: string with name of bucket
:return: string with status of method
'''
title = '%s.delete_bucket' % self.__class__.__name__
# validate in... | [
"def",
"delete_bucket",
"(",
"self",
",",
"bucket_name",
")",
":",
"title",
"=",
"'%s.delete_bucket'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs",
"input_fields",
"=",
"{",
"'bucket_name'",
":",
"bucket_name",
"}",
"for",
"key",
",",
"... | a method to delete a bucket in s3 and all its contents
:param bucket_name: string with name of bucket
:return: string with status of method | [
"a",
"method",
"to",
"delete",
"a",
"bucket",
"in",
"s3",
"and",
"all",
"its",
"contents"
] | python | train |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L148-L163 | def do_POST(self):
"""
Perform a POST request
"""
# Doesn't do anything with posted data
# print "uri: ", self.client_address, self.path
self.do_initial_operations()
payload = self.coap_uri.get_payload()
if payload is None:
logger.error("BAD PO... | [
"def",
"do_POST",
"(",
"self",
")",
":",
"# Doesn't do anything with posted data",
"# print \"uri: \", self.client_address, self.path",
"self",
".",
"do_initial_operations",
"(",
")",
"payload",
"=",
"self",
".",
"coap_uri",
".",
"get_payload",
"(",
")",
"if",
"payload"... | Perform a POST request | [
"Perform",
"a",
"POST",
"request"
] | python | train |
metric-learn/metric-learn | metric_learn/mmc.py | https://github.com/metric-learn/metric-learn/blob/d945df1342c69012608bb70b92520392a0853de6/metric_learn/mmc.py#L88-L210 | def _fit_full(self, pairs, y):
"""Learn full metric using MMC.
Parameters
----------
X : (n x d) data matrix
each row corresponds to a single instance
constraints : 4-tuple of arrays
(a,b,c,d) indices into X, with (a,b) specifying similar and (c,d)
dissimilar pairs
"""
... | [
"def",
"_fit_full",
"(",
"self",
",",
"pairs",
",",
"y",
")",
":",
"num_dim",
"=",
"pairs",
".",
"shape",
"[",
"2",
"]",
"error1",
"=",
"error2",
"=",
"1e10",
"eps",
"=",
"0.01",
"# error-bound of iterative projection on C1 and C2",
"A",
"=",
"self",
".",
... | Learn full metric using MMC.
Parameters
----------
X : (n x d) data matrix
each row corresponds to a single instance
constraints : 4-tuple of arrays
(a,b,c,d) indices into X, with (a,b) specifying similar and (c,d)
dissimilar pairs | [
"Learn",
"full",
"metric",
"using",
"MMC",
"."
] | python | train |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2656-L2711 | def get_profiles(hypervisor=None, **kwargs):
'''
Return the virt profiles for hypervisor.
Currently there are profiles for:
- nic
- disk
:param hypervisor: override the default machine type.
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0... | [
"def",
"get_profiles",
"(",
"hypervisor",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"caps",
"=",
"capabilities",
"(",
"*",
"*",
"kwargs",
")",
"hypervisors",
"=",
"sorted",
"(",
"{",
"x",
"for",
"y",
"in",
"[",
"guest",
... | Return the virt profiles for hypervisor.
Currently there are profiles for:
- nic
- disk
:param hypervisor: override the default machine type.
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overridin... | [
"Return",
"the",
"virt",
"profiles",
"for",
"hypervisor",
"."
] | python | train |
michael-lazar/rtv | rtv/packages/praw/objects.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/objects.py#L1432-L1448 | def sticky(self, bottom=True):
"""Sticky a post in its subreddit.
If there is already a stickied post in the designated slot it will be
unstickied.
:param bottom: Set this as the top or bottom sticky. If no top sticky
exists, this submission will become the top sticky regar... | [
"def",
"sticky",
"(",
"self",
",",
"bottom",
"=",
"True",
")",
":",
"url",
"=",
"self",
".",
"reddit_session",
".",
"config",
"[",
"'sticky_submission'",
"]",
"data",
"=",
"{",
"'id'",
":",
"self",
".",
"fullname",
",",
"'state'",
":",
"True",
"}",
"... | Sticky a post in its subreddit.
If there is already a stickied post in the designated slot it will be
unstickied.
:param bottom: Set this as the top or bottom sticky. If no top sticky
exists, this submission will become the top sticky regardless.
:returns: The json respons... | [
"Sticky",
"a",
"post",
"in",
"its",
"subreddit",
"."
] | python | train |
tamasgal/km3pipe | km3pipe/db.py | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L645-L648 | def unit(self, parameter):
"Get the unit for given parameter"
parameter = self._get_parameter_name(parameter).lower()
return self._parameters[parameter]['Unit'] | [
"def",
"unit",
"(",
"self",
",",
"parameter",
")",
":",
"parameter",
"=",
"self",
".",
"_get_parameter_name",
"(",
"parameter",
")",
".",
"lower",
"(",
")",
"return",
"self",
".",
"_parameters",
"[",
"parameter",
"]",
"[",
"'Unit'",
"]"
] | Get the unit for given parameter | [
"Get",
"the",
"unit",
"for",
"given",
"parameter"
] | python | train |
blockchain/api-v1-client-python | blockchain/blockexplorer.py | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L228-L250 | def get_blocks(time=None, pool_name=None, api_code=None):
"""Get a list of blocks for a specific day or mining pool.
Both parameters are optional but at least one is required.
:param int time: time in milliseconds
:param str pool_name: name of the mining pool
:param str api_code: Blockchain.info AP... | [
"def",
"get_blocks",
"(",
"time",
"=",
"None",
",",
"pool_name",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'blocks/{0}?format=json'",
"if",
"api_code",
"is",
"not",
"None",
":",
"resource",
"+=",
"'&api_code='",
"+",
"api_code",
... | Get a list of blocks for a specific day or mining pool.
Both parameters are optional but at least one is required.
:param int time: time in milliseconds
:param str pool_name: name of the mining pool
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`SimpleBlock` o... | [
"Get",
"a",
"list",
"of",
"blocks",
"for",
"a",
"specific",
"day",
"or",
"mining",
"pool",
".",
"Both",
"parameters",
"are",
"optional",
"but",
"at",
"least",
"one",
"is",
"required",
"."
] | python | train |
riga/tfdeploy | tfdeploy.py | https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L2077-L2082 | def Softmax(a):
"""
Softmax op.
"""
e = np.exp(a)
return np.divide(e, np.sum(e, axis=-1, keepdims=True)), | [
"def",
"Softmax",
"(",
"a",
")",
":",
"e",
"=",
"np",
".",
"exp",
"(",
"a",
")",
"return",
"np",
".",
"divide",
"(",
"e",
",",
"np",
".",
"sum",
"(",
"e",
",",
"axis",
"=",
"-",
"1",
",",
"keepdims",
"=",
"True",
")",
")",
","
] | Softmax op. | [
"Softmax",
"op",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2214-L2224 | def set_custom_getter_compose(custom_getter):
"""Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter.
"""
tf.get_variable_scope().set_custom_getter(
_compose_custom_getters(tf.get_variable_sco... | [
"def",
"set_custom_getter_compose",
"(",
"custom_getter",
")",
":",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"set_custom_getter",
"(",
"_compose_custom_getters",
"(",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"custom_getter",
",",
"custom_getter",
")",
... | Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter. | [
"Set",
"a",
"custom",
"getter",
"in",
"the",
"current",
"variable",
"scope",
"."
] | python | train |
katerina7479/pypdflite | pypdflite/pdfdocument.py | https://github.com/katerina7479/pypdflite/blob/ac2501f30d6619eae9dea5644717575ca9263d0a/pypdflite/pdfdocument.py#L71-L86 | def _set_color_scheme(self, draw_color=None, fill_color=None, text_color=None):
""" Default color object is black letters
& black lines."""
if draw_color is None:
draw_color = PDFColor()
draw_color._set_type('d')
if fill_color is None:
fill_... | [
"def",
"_set_color_scheme",
"(",
"self",
",",
"draw_color",
"=",
"None",
",",
"fill_color",
"=",
"None",
",",
"text_color",
"=",
"None",
")",
":",
"if",
"draw_color",
"is",
"None",
":",
"draw_color",
"=",
"PDFColor",
"(",
")",
"draw_color",
".",
"_set_type... | Default color object is black letters
& black lines. | [
"Default",
"color",
"object",
"is",
"black",
"letters",
"&",
"black",
"lines",
"."
] | python | test |
tanghaibao/goatools | goatools/base.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L175-L187 | def http_get(url, fout=None):
"""Download a file from http. Save it in a file named by fout"""
print('requests.get({URL}, stream=True)'.format(URL=url))
rsp = requests.get(url, stream=True)
if rsp.status_code == 200 and fout is not None:
with open(fout, 'wb') as prt:
for chunk in rsp... | [
"def",
"http_get",
"(",
"url",
",",
"fout",
"=",
"None",
")",
":",
"print",
"(",
"'requests.get({URL}, stream=True)'",
".",
"format",
"(",
"URL",
"=",
"url",
")",
")",
"rsp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"... | Download a file from http. Save it in a file named by fout | [
"Download",
"a",
"file",
"from",
"http",
".",
"Save",
"it",
"in",
"a",
"file",
"named",
"by",
"fout"
] | python | train |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_reactor_config.py | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_reactor_config.py#L26-L42 | def get_config(workflow):
"""
Obtain configuration object
Does not fail
:return: ReactorConfig instance
"""
try:
workspace = workflow.plugin_workspace[ReactorConfigPlugin.key]
return workspace[WORKSPACE_CONF_KEY]
except KeyError:
# The plugin did not run or was not s... | [
"def",
"get_config",
"(",
"workflow",
")",
":",
"try",
":",
"workspace",
"=",
"workflow",
".",
"plugin_workspace",
"[",
"ReactorConfigPlugin",
".",
"key",
"]",
"return",
"workspace",
"[",
"WORKSPACE_CONF_KEY",
"]",
"except",
"KeyError",
":",
"# The plugin did not ... | Obtain configuration object
Does not fail
:return: ReactorConfig instance | [
"Obtain",
"configuration",
"object",
"Does",
"not",
"fail"
] | python | train |
Datary/scrapbag | scrapbag/geo/__init__.py | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/__init__.py#L35-L46 | def get_location(address=""):
"""
Retrieve location coordinates from an address introduced.
"""
coordinates = None
try:
geolocator = Nominatim()
location = geolocator.geocode(address)
coordinates = (location.latitude, location.longitude)
except Exception as ex:
lo... | [
"def",
"get_location",
"(",
"address",
"=",
"\"\"",
")",
":",
"coordinates",
"=",
"None",
"try",
":",
"geolocator",
"=",
"Nominatim",
"(",
")",
"location",
"=",
"geolocator",
".",
"geocode",
"(",
"address",
")",
"coordinates",
"=",
"(",
"location",
".",
... | Retrieve location coordinates from an address introduced. | [
"Retrieve",
"location",
"coordinates",
"from",
"an",
"address",
"introduced",
"."
] | python | train |
saltstack/salt | salt/cli/daemons.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L512-L525 | def shutdown(self, exitcode=0, exitmsg=None):
'''
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
'''
if hasattr(self, 'minion') and 'proxymodule' in self.minion.opts:
proxy_fn = self.minion.opts['proxymodule'].loade... | [
"def",
"shutdown",
"(",
"self",
",",
"exitcode",
"=",
"0",
",",
"exitmsg",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'minion'",
")",
"and",
"'proxymodule'",
"in",
"self",
".",
"minion",
".",
"opts",
":",
"proxy_fn",
"=",
"self",
".",... | If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg | [
"If",
"sub",
"-",
"classed",
"run",
"any",
"shutdown",
"operations",
"on",
"this",
"method",
"."
] | python | train |
ccxt/ccxt | python/ccxt/async_support/base/exchange.py | https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/async_support/base/exchange.py#L117-L168 | async def fetch(self, url, method='GET', headers=None, body=None):
"""Perform a HTTP request and return decoded JSON data"""
request_headers = self.prepare_request_headers(headers)
url = self.proxy + url
if self.verbose:
print("\nRequest:", method, url, headers, body)
... | [
"async",
"def",
"fetch",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"request_headers",
"=",
"self",
".",
"prepare_request_headers",
"(",
"headers",
")",
"url",
"=",
"self",
"."... | Perform a HTTP request and return decoded JSON data | [
"Perform",
"a",
"HTTP",
"request",
"and",
"return",
"decoded",
"JSON",
"data"
] | python | train |
croscon/fleaker | fleaker/orm.py | https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/orm.py#L83-L116 | def _discover_ideal_backend(orm_backend):
"""Auto-discover the ideal backend based on what is installed.
Right now, handles discovery of:
* PeeWee
* SQLAlchemy
Args:
orm_backend (str): The ``orm_backend`` value that was passed to the
``create_app`` function. That is, the OR... | [
"def",
"_discover_ideal_backend",
"(",
"orm_backend",
")",
":",
"if",
"orm_backend",
":",
"return",
"orm_backend",
"if",
"peewee",
"is",
"not",
"MISSING",
"and",
"sqlalchemy",
"is",
"not",
"MISSING",
":",
"raise",
"RuntimeError",
"(",
"'Both PeeWee and SQLAlchemy de... | Auto-discover the ideal backend based on what is installed.
Right now, handles discovery of:
* PeeWee
* SQLAlchemy
Args:
orm_backend (str): The ``orm_backend`` value that was passed to the
``create_app`` function. That is, the ORM Backend the User
indicated they wan... | [
"Auto",
"-",
"discover",
"the",
"ideal",
"backend",
"based",
"on",
"what",
"is",
"installed",
"."
] | python | train |
kislyuk/ensure | ensure/main.py | https://github.com/kislyuk/ensure/blob/0a562a4b469ffbaf71c75dc4d394e94334c831f0/ensure/main.py#L369-L378 | def is_none_or(self):
"""
Ensures :attr:`subject` is either ``None``, or satisfies subsequent (chained) conditions::
Ensure(None).is_none_or.is_an(int)
"""
if self._subject is None:
return NoOpInspector(subject=self._subject, error_factory=self._error_factory)
... | [
"def",
"is_none_or",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subject",
"is",
"None",
":",
"return",
"NoOpInspector",
"(",
"subject",
"=",
"self",
".",
"_subject",
",",
"error_factory",
"=",
"self",
".",
"_error_factory",
")",
"else",
":",
"return",
"... | Ensures :attr:`subject` is either ``None``, or satisfies subsequent (chained) conditions::
Ensure(None).is_none_or.is_an(int) | [
"Ensures",
":",
"attr",
":",
"subject",
"is",
"either",
"None",
"or",
"satisfies",
"subsequent",
"(",
"chained",
")",
"conditions",
"::"
] | python | train |
sci-bots/svg-model | svg_model/merge.py | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/merge.py#L56-L97 | def merge_svg_layers(svg_sources, share_transform=True):
'''
Merge layers from input svg sources into a single XML document.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
share_transform (bool) : If exactly one layer has a trans... | [
"def",
"merge_svg_layers",
"(",
"svg_sources",
",",
"share_transform",
"=",
"True",
")",
":",
"# Get list of XML layers.",
"(",
"width",
",",
"height",
")",
",",
"layers",
"=",
"get_svg_layers",
"(",
"svg_sources",
")",
"if",
"share_transform",
":",
"transforms",
... | Merge layers from input svg sources into a single XML document.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
share_transform (bool) : If exactly one layer has a transform, apply it
to *all* other layers as well.
Return... | [
"Merge",
"layers",
"from",
"input",
"svg",
"sources",
"into",
"a",
"single",
"XML",
"document",
"."
] | python | train |
iotile/coretools | iotilecore/iotile/core/utilities/linebuffer_ui.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/linebuffer_ui.py#L62-L70 | def run(self, refresh_interval=0.05):
"""Set up the loop, check that the tool is installed"""
try:
from asciimatics.screen import Screen
except ImportError:
raise ExternalError("You must have asciimatics installed to use LinebufferUI",
sugg... | [
"def",
"run",
"(",
"self",
",",
"refresh_interval",
"=",
"0.05",
")",
":",
"try",
":",
"from",
"asciimatics",
".",
"screen",
"import",
"Screen",
"except",
"ImportError",
":",
"raise",
"ExternalError",
"(",
"\"You must have asciimatics installed to use LinebufferUI\"",... | Set up the loop, check that the tool is installed | [
"Set",
"up",
"the",
"loop",
"check",
"that",
"the",
"tool",
"is",
"installed"
] | python | train |
tensorforce/tensorforce | tensorforce/agents/agent.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/agents/agent.py#L166-L197 | def observe(self, terminal, reward, index=0):
"""
Observe experience from the environment to learn from. Optionally pre-processes rewards
Child classes should call super to get the processed reward
EX: terminal, reward = super()...
Args:
terminal (bool): boolean indi... | [
"def",
"observe",
"(",
"self",
",",
"terminal",
",",
"reward",
",",
"index",
"=",
"0",
")",
":",
"self",
".",
"current_terminal",
"=",
"terminal",
"self",
".",
"current_reward",
"=",
"reward",
"if",
"self",
".",
"batched_observe",
":",
"# Batched observe for... | Observe experience from the environment to learn from. Optionally pre-processes rewards
Child classes should call super to get the processed reward
EX: terminal, reward = super()...
Args:
terminal (bool): boolean indicating if the episode terminated after the observation.
... | [
"Observe",
"experience",
"from",
"the",
"environment",
"to",
"learn",
"from",
".",
"Optionally",
"pre",
"-",
"processes",
"rewards",
"Child",
"classes",
"should",
"call",
"super",
"to",
"get",
"the",
"processed",
"reward",
"EX",
":",
"terminal",
"reward",
"=",... | python | valid |
log2timeline/plaso | plaso/preprocessors/windows.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/preprocessors/windows.py#L226-L244 | def _ParseValueData(self, knowledge_base, value_data):
"""Parses Windows Registry value data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
value_data (object): Windows Registry value data.
Raises:
errors.PreProcessFail: if th... | [
"def",
"_ParseValueData",
"(",
"self",
",",
"knowledge_base",
",",
"value_data",
")",
":",
"if",
"not",
"isinstance",
"(",
"value_data",
",",
"py2to3",
".",
"UNICODE_TYPE",
")",
":",
"raise",
"errors",
".",
"PreProcessFail",
"(",
"'Unsupported Windows Registry val... | Parses Windows Registry value data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
value_data (object): Windows Registry value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | [
"Parses",
"Windows",
"Registry",
"value",
"data",
"for",
"a",
"preprocessing",
"attribute",
"."
] | python | train |
seomoz/reppy | reppy/cache/__init__.py | https://github.com/seomoz/reppy/blob/4cfa55894859a2eb2e656f191aeda5981c4df550/reppy/cache/__init__.py#L81-L83 | def allowed(self, url, agent):
'''Return true if the provided URL is allowed to agent.'''
return self.get(url).allowed(url, agent) | [
"def",
"allowed",
"(",
"self",
",",
"url",
",",
"agent",
")",
":",
"return",
"self",
".",
"get",
"(",
"url",
")",
".",
"allowed",
"(",
"url",
",",
"agent",
")"
] | Return true if the provided URL is allowed to agent. | [
"Return",
"true",
"if",
"the",
"provided",
"URL",
"is",
"allowed",
"to",
"agent",
"."
] | python | train |
NiklasRosenstein-Python/nr-deprecated | nr/tundras/field.py | https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/tundras/field.py#L106-L115 | def check_type(self, value):
"""
Raises a #TypeError if *value* is not an instance of the field's #type.
"""
if self.null and value is None:
return
if self.type is not None and not isinstance(value, self.type):
msg = '{0!r} expected type {1}'
raise TypeError(msg.format(self.full_n... | [
"def",
"check_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"null",
"and",
"value",
"is",
"None",
":",
"return",
"if",
"self",
".",
"type",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"type",
")... | Raises a #TypeError if *value* is not an instance of the field's #type. | [
"Raises",
"a",
"#TypeError",
"if",
"*",
"value",
"*",
"is",
"not",
"an",
"instance",
"of",
"the",
"field",
"s",
"#type",
"."
] | python | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L101-L117 | def set_swimlane(self, value):
"""Store record ids in separate location for later use, but ignore initial value"""
# Move single record into list to be handled the same by cursor class
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]... | [
"def",
"set_swimlane",
"(",
"self",
",",
"value",
")",
":",
"# Move single record into list to be handled the same by cursor class",
"if",
"not",
"self",
".",
"multiselect",
":",
"if",
"value",
"and",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"valu... | Store record ids in separate location for later use, but ignore initial value | [
"Store",
"record",
"ids",
"in",
"separate",
"location",
"for",
"later",
"use",
"but",
"ignore",
"initial",
"value"
] | python | train |
Zaeb0s/max-threads | maxthreads/maxthreads.py | https://github.com/Zaeb0s/max-threads/blob/dce4ae784aa1c07fdb910359c0099907047403f9/maxthreads/maxthreads.py#L107-L141 | def add_task(self, target, args=(), kwargs=None, priority=None):
"""
Args:
target: A callable object to be invoked
args: Arguments sent to the callable object upon invocation
kwargs: Keyword arguments sent to the callable object upon invocation
priority: D... | [
"def",
"add_task",
"(",
"self",
",",
"target",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"None",
",",
"priority",
"=",
"None",
")",
":",
"if",
"self",
".",
"_stop",
":",
"raise",
"RuntimeError",
"(",
"\"Can't add new task, the MaxThreads object is in c... | Args:
target: A callable object to be invoked
args: Arguments sent to the callable object upon invocation
kwargs: Keyword arguments sent to the callable object upon invocation
priority: Determines where to put the callable object in the list of tasks, Can be any type of o... | [
"Args",
":",
"target",
":",
"A",
"callable",
"object",
"to",
"be",
"invoked",
"args",
":",
"Arguments",
"sent",
"to",
"the",
"callable",
"object",
"upon",
"invocation",
"kwargs",
":",
"Keyword",
"arguments",
"sent",
"to",
"the",
"callable",
"object",
"upon",... | python | train |
mozilla/amo-validator | validator/errorbundler.py | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/errorbundler.py#L161-L174 | def drop_message(self, message):
"""Drop the given message object from the appropriate message list.
Returns True if the message was found, otherwise False."""
for type_ in 'errors', 'warnings', 'notices':
list_ = getattr(self, type_)
if message in list_:
... | [
"def",
"drop_message",
"(",
"self",
",",
"message",
")",
":",
"for",
"type_",
"in",
"'errors'",
",",
"'warnings'",
",",
"'notices'",
":",
"list_",
"=",
"getattr",
"(",
"self",
",",
"type_",
")",
"if",
"message",
"in",
"list_",
":",
"list_",
".",
"remov... | Drop the given message object from the appropriate message list.
Returns True if the message was found, otherwise False. | [
"Drop",
"the",
"given",
"message",
"object",
"from",
"the",
"appropriate",
"message",
"list",
"."
] | python | train |
rstoneback/pysat | pysat/utils.py | https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/utils.py#L78-L362 | def load_netcdf4(fnames=None, strict_meta=False, file_format=None, epoch_name='Epoch',
units_label='units', name_label='long_name',
notes_label='notes', desc_label='desc',
plot_label='label', axis_label='axis',
scale_label='scale',
m... | [
"def",
"load_netcdf4",
"(",
"fnames",
"=",
"None",
",",
"strict_meta",
"=",
"False",
",",
"file_format",
"=",
"None",
",",
"epoch_name",
"=",
"'Epoch'",
",",
"units_label",
"=",
"'units'",
",",
"name_label",
"=",
"'long_name'",
",",
"notes_label",
"=",
"'not... | Load netCDF-3/4 file produced by pysat.
Parameters
----------
fnames : string or array_like of strings
filenames to load
strict_meta : boolean
check if metadata across fnames is the same
file_format : string
file_format keyword passed to netCDF4 routine
NETCDF3_CLASS... | [
"Load",
"netCDF",
"-",
"3",
"/",
"4",
"file",
"produced",
"by",
"pysat",
"."
] | python | train |
gboeing/osmnx | osmnx/plot.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/plot.py#L100-L115 | def rgb_color_list_to_hex(color_list):
"""
Convert a list of RGBa colors to a list of hexadecimal color codes.
Parameters
----------
color_list : list
the list of RGBa colors
Returns
-------
color_list_hex : list
"""
color_list_rgb = [[int(x*255) for x in c[0:3]] for c ... | [
"def",
"rgb_color_list_to_hex",
"(",
"color_list",
")",
":",
"color_list_rgb",
"=",
"[",
"[",
"int",
"(",
"x",
"*",
"255",
")",
"for",
"x",
"in",
"c",
"[",
"0",
":",
"3",
"]",
"]",
"for",
"c",
"in",
"color_list",
"]",
"color_list_hex",
"=",
"[",
"'... | Convert a list of RGBa colors to a list of hexadecimal color codes.
Parameters
----------
color_list : list
the list of RGBa colors
Returns
-------
color_list_hex : list | [
"Convert",
"a",
"list",
"of",
"RGBa",
"colors",
"to",
"a",
"list",
"of",
"hexadecimal",
"color",
"codes",
"."
] | python | train |
jobovy/galpy | galpy/potential/SpiralArmsPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/SpiralArmsPotential.py#L570-L574 | def _B(self, R):
"""Return numpy array from B1 up to and including Bn. (eqn. 6)"""
HNn_R = self._HNn / R
return HNn_R / self._sin_alpha * (0.4 * HNn_R / self._sin_alpha + 1) | [
"def",
"_B",
"(",
"self",
",",
"R",
")",
":",
"HNn_R",
"=",
"self",
".",
"_HNn",
"/",
"R",
"return",
"HNn_R",
"/",
"self",
".",
"_sin_alpha",
"*",
"(",
"0.4",
"*",
"HNn_R",
"/",
"self",
".",
"_sin_alpha",
"+",
"1",
")"
] | Return numpy array from B1 up to and including Bn. (eqn. 6) | [
"Return",
"numpy",
"array",
"from",
"B1",
"up",
"to",
"and",
"including",
"Bn",
".",
"(",
"eqn",
".",
"6",
")"
] | python | train |
tgsmith61591/pmdarima | pmdarima/arima/arima.py | https://github.com/tgsmith61591/pmdarima/blob/a133de78ba5bd68da9785b061f519ba28cd514cc/pmdarima/arima/arima.py#L515-L584 | def predict(self, n_periods=10, exogenous=None,
return_conf_int=False, alpha=0.05):
"""Forecast future values
Generate predictions (forecasts) ``n_periods`` in the future.
Note that if ``exogenous`` variables were used in the model fit, they
will be expected for the pred... | [
"def",
"predict",
"(",
"self",
",",
"n_periods",
"=",
"10",
",",
"exogenous",
"=",
"None",
",",
"return_conf_int",
"=",
"False",
",",
"alpha",
"=",
"0.05",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"'arima_res_'",
")",
"if",
"not",
"isinstance",
"("... | Forecast future values
Generate predictions (forecasts) ``n_periods`` in the future.
Note that if ``exogenous`` variables were used in the model fit, they
will be expected for the predict procedure and will fail otherwise.
Parameters
----------
n_periods : int, optional... | [
"Forecast",
"future",
"values"
] | python | train |
woolfson-group/isambard | isambard/ampal/analyse_protein.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/analyse_protein.py#L674-L724 | def make_primitive_extrapolate_ends(cas_coords, smoothing_level=2):
"""Generates smoothed helix primitives and extrapolates lost ends.
Notes
-----
From an input list of CA coordinates, the running average is
calculated to form a primitive. The smoothing_level dictates how
many times to calculat... | [
"def",
"make_primitive_extrapolate_ends",
"(",
"cas_coords",
",",
"smoothing_level",
"=",
"2",
")",
":",
"try",
":",
"smoothed_primitive",
"=",
"make_primitive_smoothed",
"(",
"cas_coords",
",",
"smoothing_level",
"=",
"smoothing_level",
")",
"except",
"ValueError",
"... | Generates smoothed helix primitives and extrapolates lost ends.
Notes
-----
From an input list of CA coordinates, the running average is
calculated to form a primitive. The smoothing_level dictates how
many times to calculate the running average. A higher
smoothing_level generates a 'smoother' ... | [
"Generates",
"smoothed",
"helix",
"primitives",
"and",
"extrapolates",
"lost",
"ends",
"."
] | python | train |
senaite/senaite.core | bika/lims/browser/widgets/serviceswidget.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/widgets/serviceswidget.py#L129-L190 | def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | [
"def",
"folderitem",
"(",
"self",
",",
"obj",
",",
"item",
",",
"index",
")",
":",
"# ensure we have an object and not a brain",
"obj",
"=",
"api",
".",
"get_object",
"(",
"obj",
")",
"uid",
"=",
"api",
".",
"get_uid",
"(",
"obj",
")",
"url",
"=",
"api",... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current i... | [
"Service",
"triggered",
"each",
"time",
"an",
"item",
"is",
"iterated",
"in",
"folderitems",
"."
] | python | train |
zyga/python-glibc | pyglibc/_signalfd.py | https://github.com/zyga/python-glibc/blob/d6fdb306b123a995471584a5201155c60a34448a/pyglibc/_signalfd.py#L103-L116 | def close(self):
"""
Close the internal signalfd file descriptor if it isn't closed
:raises OSError:
If the underlying ``close(2)`` fails. The error message matches
those found in the manual page.
"""
with self._close_lock:
sfd = self._sfd
... | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"_close_lock",
":",
"sfd",
"=",
"self",
".",
"_sfd",
"if",
"sfd",
">=",
"0",
":",
"self",
".",
"_sfd",
"=",
"-",
"1",
"self",
".",
"_signals",
"=",
"frozenset",
"(",
")",
"close",
"(",
... | Close the internal signalfd file descriptor if it isn't closed
:raises OSError:
If the underlying ``close(2)`` fails. The error message matches
those found in the manual page. | [
"Close",
"the",
"internal",
"signalfd",
"file",
"descriptor",
"if",
"it",
"isn",
"t",
"closed"
] | python | train |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L43-L52 | def custom_prefix_lax(instance):
"""Ensure custom content follows lenient naming style conventions
for forward-compatibility.
"""
for error in chain(custom_object_prefix_lax(instance),
custom_property_prefix_lax(instance),
custom_observable_object_prefix_lax... | [
"def",
"custom_prefix_lax",
"(",
"instance",
")",
":",
"for",
"error",
"in",
"chain",
"(",
"custom_object_prefix_lax",
"(",
"instance",
")",
",",
"custom_property_prefix_lax",
"(",
"instance",
")",
",",
"custom_observable_object_prefix_lax",
"(",
"instance",
")",
",... | Ensure custom content follows lenient naming style conventions
for forward-compatibility. | [
"Ensure",
"custom",
"content",
"follows",
"lenient",
"naming",
"style",
"conventions",
"for",
"forward",
"-",
"compatibility",
"."
] | python | train |
jeroyang/txttk | txttk/nlptools.py | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/nlptools.py#L130-L154 | def count_start(tokenizer):
"""
A decorator which wrap the given tokenizer to yield (token, start).
Notice! the decorated tokenizer must take a int arguments stands for the start position of the input context/sentence
>>> tokenizer = lambda sentence: sentence.split(' ')
>>> tokenizer('The quick bro... | [
"def",
"count_start",
"(",
"tokenizer",
")",
":",
"def",
"wrapper",
"(",
"context",
",",
"base",
")",
":",
"tokens",
"=",
"list",
"(",
"tokenizer",
"(",
"context",
")",
")",
"flag",
"=",
"0",
"for",
"token",
"in",
"tokens",
":",
"start",
"=",
"contex... | A decorator which wrap the given tokenizer to yield (token, start).
Notice! the decorated tokenizer must take a int arguments stands for the start position of the input context/sentence
>>> tokenizer = lambda sentence: sentence.split(' ')
>>> tokenizer('The quick brown fox jumps over the lazy dog')
['T... | [
"A",
"decorator",
"which",
"wrap",
"the",
"given",
"tokenizer",
"to",
"yield",
"(",
"token",
"start",
")",
".",
"Notice!",
"the",
"decorated",
"tokenizer",
"must",
"take",
"a",
"int",
"arguments",
"stands",
"for",
"the",
"start",
"position",
"of",
"the",
"... | python | train |
openeemeter/eemeter | eemeter/caltrack/usage_per_day.py | https://github.com/openeemeter/eemeter/blob/e03b1cc5f4906e8f4f7fd16183bc037107d1dfa0/eemeter/caltrack/usage_per_day.py#L367-L388 | def plot(
self,
best=False,
ax=None,
title=None,
figsize=None,
temp_range=None,
alpha=None,
**kwargs
):
""" Plot
"""
return plot_caltrack_candidate(
self,
best=best,
ax=ax,
title=t... | [
"def",
"plot",
"(",
"self",
",",
"best",
"=",
"False",
",",
"ax",
"=",
"None",
",",
"title",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"temp_range",
"=",
"None",
",",
"alpha",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"plot_c... | Plot | [
"Plot"
] | python | train |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L498-L512 | def __update_molar_mass(self, compound='', element=''):
"""Re-calculate the molar mass of the element given due to stoichiometric changes
Parameters:
==========
compound: string (default is '') name of compound
element: string (default is '') name of element
"""
... | [
"def",
"__update_molar_mass",
"(",
"self",
",",
"compound",
"=",
"''",
",",
"element",
"=",
"''",
")",
":",
"_molar_mass_element",
"=",
"0",
"list_ratio",
"=",
"self",
".",
"stack",
"[",
"compound",
"]",
"[",
"element",
"]",
"[",
"'isotopes'",
"]",
"[",
... | Re-calculate the molar mass of the element given due to stoichiometric changes
Parameters:
==========
compound: string (default is '') name of compound
element: string (default is '') name of element | [
"Re",
"-",
"calculate",
"the",
"molar",
"mass",
"of",
"the",
"element",
"given",
"due",
"to",
"stoichiometric",
"changes"
] | python | train |
radjkarl/fancyTools | fancytools/geometry/polygon.py | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/geometry/polygon.py#L43-L74 | def pointInsidePolygon(x, y, poly):
"""
Determine if a point is inside a given polygon or not
Polygon is a list of (x,y) pairs.
[code taken from: http://www.ariel.com.au/a/python-point-int-poly.html]
let's make an easy square:
>>> poly = [ (0,0),\
(1,0),\
(1,... | [
"def",
"pointInsidePolygon",
"(",
"x",
",",
"y",
",",
"poly",
")",
":",
"n",
"=",
"len",
"(",
"poly",
")",
"inside",
"=",
"False",
"p1x",
",",
"p1y",
"=",
"poly",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
"+",
"1",
")",
":",
"p2x",
... | Determine if a point is inside a given polygon or not
Polygon is a list of (x,y) pairs.
[code taken from: http://www.ariel.com.au/a/python-point-int-poly.html]
let's make an easy square:
>>> poly = [ (0,0),\
(1,0),\
(1,1),\
(0,1) ]
>>> pointInsid... | [
"Determine",
"if",
"a",
"point",
"is",
"inside",
"a",
"given",
"polygon",
"or",
"not",
"Polygon",
"is",
"a",
"list",
"of",
"(",
"x",
"y",
")",
"pairs",
"."
] | python | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L389-L413 | def add(cls, model, commit=True):
"""Adds a model instance to session and commits the
transaction.
Args:
model: The instance to add.
Examples:
>>> customer = Customer.new(name="hari", email="hari@gmail.com")
>>> Customer.add(customer)
... | [
"def",
"add",
"(",
"cls",
",",
"model",
",",
"commit",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"cls",
")",
":",
"raise",
"ValueError",
"(",
"'%s is not of type %s'",
"%",
"(",
"model",
",",
"cls",
")",
")",
"cls",
".",
... | Adds a model instance to session and commits the
transaction.
Args:
model: The instance to add.
Examples:
>>> customer = Customer.new(name="hari", email="hari@gmail.com")
>>> Customer.add(customer)
hari@gmail.com | [
"Adds",
"a",
"model",
"instance",
"to",
"session",
"and",
"commits",
"the",
"transaction",
"."
] | python | train |
hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1206-L1218 | def fix_w391(self, _):
"""Remove trailing blank lines."""
blank_count = 0
for line in reversed(self.source):
line = line.rstrip()
if line:
break
else:
blank_count += 1
original_length = len(self.source)
self.sou... | [
"def",
"fix_w391",
"(",
"self",
",",
"_",
")",
":",
"blank_count",
"=",
"0",
"for",
"line",
"in",
"reversed",
"(",
"self",
".",
"source",
")",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"line",
":",
"break",
"else",
":",
"blank_count"... | Remove trailing blank lines. | [
"Remove",
"trailing",
"blank",
"lines",
"."
] | python | train |
5monkeys/django-bananas | bananas/admin/api/schemas/yasg.py | https://github.com/5monkeys/django-bananas/blob/cfd318c737f6c4580036c13d2acf32bca96654bf/bananas/admin/api/schemas/yasg.py#L45-L76 | def get_summary(self):
"""
Compat: drf-yasg 1.11
"""
title = None
method_name = getattr(self.view, "action", self.method.lower())
action = getattr(self.view, method_name, None)
action_kwargs = getattr(action, "kwargs", None)
if action_kwargs:
... | [
"def",
"get_summary",
"(",
"self",
")",
":",
"title",
"=",
"None",
"method_name",
"=",
"getattr",
"(",
"self",
".",
"view",
",",
"\"action\"",
",",
"self",
".",
"method",
".",
"lower",
"(",
")",
")",
"action",
"=",
"getattr",
"(",
"self",
".",
"view"... | Compat: drf-yasg 1.11 | [
"Compat",
":",
"drf",
"-",
"yasg",
"1",
".",
"11"
] | python | test |
tcalmant/ipopo | pelix/services/configadmin.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/services/configadmin.py#L266-L296 | def update(self, properties=None):
# pylint: disable=W0212
"""
If called without properties, only notifies listeners
Update the properties of this Configuration object.
Stores the properties in persistent storage after adding or overwriting
the following properties:
... | [
"def",
"update",
"(",
"self",
",",
"properties",
"=",
"None",
")",
":",
"# pylint: disable=W0212",
"with",
"self",
".",
"__lock",
":",
"# Update properties",
"if",
"self",
".",
"__properties_update",
"(",
"properties",
")",
":",
"# Update configurations, if somethin... | If called without properties, only notifies listeners
Update the properties of this Configuration object.
Stores the properties in persistent storage after adding or overwriting
the following properties:
* "service.pid" : is set to be the PID of this configuration.
* "service.f... | [
"If",
"called",
"without",
"properties",
"only",
"notifies",
"listeners"
] | python | train |
edoburu/django-any-urlfield | any_urlfield/registry.py | https://github.com/edoburu/django-any-urlfield/blob/8d7d36c8a1fc251930f6dbdcc8b5b5151d20e3ab/any_urlfield/registry.py#L57-L72 | def get_widget(self):
"""
Create the widget for the URL type.
"""
form_field = self.get_form_field()
widget = form_field.widget
if isinstance(widget, type):
widget = widget()
# Widget instantiation needs to happen manually.
# Auto skip if choi... | [
"def",
"get_widget",
"(",
"self",
")",
":",
"form_field",
"=",
"self",
".",
"get_form_field",
"(",
")",
"widget",
"=",
"form_field",
".",
"widget",
"if",
"isinstance",
"(",
"widget",
",",
"type",
")",
":",
"widget",
"=",
"widget",
"(",
")",
"# Widget ins... | Create the widget for the URL type. | [
"Create",
"the",
"widget",
"for",
"the",
"URL",
"type",
"."
] | python | train |
rodluger/everest | everest/user.py | https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/user.py#L850-L925 | def plot_pipeline(self, pipeline, *args, **kwargs):
'''
Plots the light curve for the target de-trended with a given pipeline.
:param str pipeline: The name of the pipeline (lowercase). Options \
are 'everest2', 'everest1', and other mission-specific \
pipelines. F... | [
"def",
"plot_pipeline",
"(",
"self",
",",
"pipeline",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"pipeline",
"!=",
"'everest2'",
":",
"return",
"getattr",
"(",
"missions",
",",
"self",
".",
"mission",
")",
".",
"pipelines",
".",
"plot",... | Plots the light curve for the target de-trended with a given pipeline.
:param str pipeline: The name of the pipeline (lowercase). Options \
are 'everest2', 'everest1', and other mission-specific \
pipelines. For `K2`, the available pipelines are 'k2sff' \
and 'k2sc'... | [
"Plots",
"the",
"light",
"curve",
"for",
"the",
"target",
"de",
"-",
"trended",
"with",
"a",
"given",
"pipeline",
"."
] | python | train |
saltstack/salt | salt/modules/flatpak.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/flatpak.py#L82-L109 | def uninstall(pkg):
'''
Uninstall the specified package.
Args:
pkg (str): The package name.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.uninstall org.gimp.GIMP
'''
ret = {'result': None, 'output': ''}
... | [
"def",
"uninstall",
"(",
"pkg",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"None",
",",
"'output'",
":",
"''",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"FLATPAK_BINARY_NAME",
"+",
"' uninstall '",
"+",
"pkg",
")",
"if",
"out",
"[",... | Uninstall the specified package.
Args:
pkg (str): The package name.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.uninstall org.gimp.GIMP | [
"Uninstall",
"the",
"specified",
"package",
"."
] | python | train |
shexSpec/grammar | parsers/python/pyshexc/parser_impl/parser_context.py | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/parser_context.py#L86-L91 | def prefixedname_to_iriref(self, prefix: ShExDocParser.PrefixedNameContext) -> ShExJ.IRIREF:
""" prefixedName: PNAME_LN | PNAME_NS
PNAME_NS: PN_PREFIX? ':' ;
PNAME_LN: PNAME_NS PN_LOCAL ;
"""
return ShExJ.IRIREF(self.prefixedname_to_str(prefix)) | [
"def",
"prefixedname_to_iriref",
"(",
"self",
",",
"prefix",
":",
"ShExDocParser",
".",
"PrefixedNameContext",
")",
"->",
"ShExJ",
".",
"IRIREF",
":",
"return",
"ShExJ",
".",
"IRIREF",
"(",
"self",
".",
"prefixedname_to_str",
"(",
"prefix",
")",
")"
] | prefixedName: PNAME_LN | PNAME_NS
PNAME_NS: PN_PREFIX? ':' ;
PNAME_LN: PNAME_NS PN_LOCAL ; | [
"prefixedName",
":",
"PNAME_LN",
"|",
"PNAME_NS",
"PNAME_NS",
":",
"PN_PREFIX?",
":",
";",
"PNAME_LN",
":",
"PNAME_NS",
"PN_LOCAL",
";"
] | python | train |
aegirhall/console-menu | consolemenu/menu_formatter.py | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_formatter.py#L107-L114 | def set_top_margin(self, top_margin):
"""
Set the top margin of the menu. This will determine the number of console lines between the top edge
of the screen and the top menu border.
:param top_margin: an integer value
"""
self.__header.style.margins.top = top_margin
... | [
"def",
"set_top_margin",
"(",
"self",
",",
"top_margin",
")",
":",
"self",
".",
"__header",
".",
"style",
".",
"margins",
".",
"top",
"=",
"top_margin",
"return",
"self"
] | Set the top margin of the menu. This will determine the number of console lines between the top edge
of the screen and the top menu border.
:param top_margin: an integer value | [
"Set",
"the",
"top",
"margin",
"of",
"the",
"menu",
".",
"This",
"will",
"determine",
"the",
"number",
"of",
"console",
"lines",
"between",
"the",
"top",
"edge",
"of",
"the",
"screen",
"and",
"the",
"top",
"menu",
"border",
".",
":",
"param",
"top_margin... | python | train |
jciskey/pygraph | pygraph/functions/planarity/kocay_algorithm.py | https://github.com/jciskey/pygraph/blob/037bb2f32503fecb60d62921f9766d54109f15e2/pygraph/functions/planarity/kocay_algorithm.py#L490-L510 | def merge_Fm(dfs_data):
"""Merges Fm-1 and Fm, as defined on page 19 of the paper."""
FG = dfs_data['FG']
m = FG['m']
FGm = FG[m]
FGm1 = FG[m-1]
if FGm[0]['u'] < FGm1[0]['u']:
FGm1[0]['u'] = FGm[0]['u']
if FGm[0]['v'] > FGm1[0]['v']:
FGm1[0]['v'] = FGm[0]['v']
if FGm[1... | [
"def",
"merge_Fm",
"(",
"dfs_data",
")",
":",
"FG",
"=",
"dfs_data",
"[",
"'FG'",
"]",
"m",
"=",
"FG",
"[",
"'m'",
"]",
"FGm",
"=",
"FG",
"[",
"m",
"]",
"FGm1",
"=",
"FG",
"[",
"m",
"-",
"1",
"]",
"if",
"FGm",
"[",
"0",
"]",
"[",
"'u'",
"... | Merges Fm-1 and Fm, as defined on page 19 of the paper. | [
"Merges",
"Fm",
"-",
"1",
"and",
"Fm",
"as",
"defined",
"on",
"page",
"19",
"of",
"the",
"paper",
"."
] | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/utils/nan_warnings.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/utils/nan_warnings.py#L10-L44 | def filter_missing(X, y=None):
"""
Removes rows that contain np.nan values in data. If y is given,
X and y will be filtered together so that their shape remains identical.
For example, rows in X with nans will also remove rows in y, or rows in y
with np.nans will also remove corresponding rows in X.... | [
"def",
"filter_missing",
"(",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"y",
"is",
"not",
"None",
":",
"return",
"filter_missing_X_and_y",
"(",
"X",
",",
"y",
")",
"else",
":",
"return",
"X",
"[",
"~",
"np",
".",
"isnan",
"(",
"X",
")",
".",
... | Removes rows that contain np.nan values in data. If y is given,
X and y will be filtered together so that their shape remains identical.
For example, rows in X with nans will also remove rows in y, or rows in y
with np.nans will also remove corresponding rows in X.
Parameters
------------
X : a... | [
"Removes",
"rows",
"that",
"contain",
"np",
".",
"nan",
"values",
"in",
"data",
".",
"If",
"y",
"is",
"given",
"X",
"and",
"y",
"will",
"be",
"filtered",
"together",
"so",
"that",
"their",
"shape",
"remains",
"identical",
".",
"For",
"example",
"rows",
... | python | train |
ronaldguillen/wave | wave/request.py | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/request.py#L308-L326 | def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
Returns a three-tuple of (authenticator, user, authtoken).
"""
for authenticator in self.authenticators:
try:
user_auth_tuple = authent... | [
"def",
"_authenticate",
"(",
"self",
")",
":",
"for",
"authenticator",
"in",
"self",
".",
"authenticators",
":",
"try",
":",
"user_auth_tuple",
"=",
"authenticator",
".",
"authenticate",
"(",
"self",
")",
"except",
"exceptions",
".",
"APIException",
":",
"self... | Attempt to authenticate the request using each authentication instance
in turn.
Returns a three-tuple of (authenticator, user, authtoken). | [
"Attempt",
"to",
"authenticate",
"the",
"request",
"using",
"each",
"authentication",
"instance",
"in",
"turn",
".",
"Returns",
"a",
"three",
"-",
"tuple",
"of",
"(",
"authenticator",
"user",
"authtoken",
")",
"."
] | python | train |
fractalego/parvusdb | parvusdb/utils/code_container.py | https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/code_container.py#L68-L90 | def substitute_namespace_into_graph(self, graph):
"""
Creates a graph from the local namespace of the code (to be used after the execution of the code)
:param graph: The graph to use as a recipient of the namespace
:return: the updated graph
"""
for key, value in self.na... | [
"def",
"substitute_namespace_into_graph",
"(",
"self",
",",
"graph",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"namespace",
".",
"items",
"(",
")",
":",
"try",
":",
"nodes",
"=",
"graph",
".",
"vs",
".",
"select",
"(",
"name",
"=",
"ke... | Creates a graph from the local namespace of the code (to be used after the execution of the code)
:param graph: The graph to use as a recipient of the namespace
:return: the updated graph | [
"Creates",
"a",
"graph",
"from",
"the",
"local",
"namespace",
"of",
"the",
"code",
"(",
"to",
"be",
"used",
"after",
"the",
"execution",
"of",
"the",
"code",
")"
] | python | train |
vmonaco/pohmm | pohmm/utils.py | https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/utils.py#L106-L119 | def gen_stochastic_matrix(size, random_state=None):
"""
Generate a unfiformly-random stochastic array or matrix
"""
if not type(size) is tuple:
size = (1, size)
assert len(size) == 2
n = random_state.uniform(size=(size[0], size[1] - 1))
n = np.concatenate([np.zeros((size[0], 1)), n... | [
"def",
"gen_stochastic_matrix",
"(",
"size",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"not",
"type",
"(",
"size",
")",
"is",
"tuple",
":",
"size",
"=",
"(",
"1",
",",
"size",
")",
"assert",
"len",
"(",
"size",
")",
"==",
"2",
"n",
"=",
"... | Generate a unfiformly-random stochastic array or matrix | [
"Generate",
"a",
"unfiformly",
"-",
"random",
"stochastic",
"array",
"or",
"matrix"
] | python | train |
keenlabs/KeenClient-Python | keen/saved_queries.py | https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/saved_queries.py#L48-L58 | def results(self, query_name):
"""
Gets a single saved query with a 'result' object for a project from the
Keen IO API given a query name.
Read or Master key must be set.
"""
url = "{0}/{1}/result".format(self.saved_query_url, query_name)
response = self._get_jso... | [
"def",
"results",
"(",
"self",
",",
"query_name",
")",
":",
"url",
"=",
"\"{0}/{1}/result\"",
".",
"format",
"(",
"self",
".",
"saved_query_url",
",",
"query_name",
")",
"response",
"=",
"self",
".",
"_get_json",
"(",
"HTTPMethods",
".",
"GET",
",",
"url",... | Gets a single saved query with a 'result' object for a project from the
Keen IO API given a query name.
Read or Master key must be set. | [
"Gets",
"a",
"single",
"saved",
"query",
"with",
"a",
"result",
"object",
"for",
"a",
"project",
"from",
"the",
"Keen",
"IO",
"API",
"given",
"a",
"query",
"name",
".",
"Read",
"or",
"Master",
"key",
"must",
"be",
"set",
"."
] | python | train |
HPENetworking/PYHPEIMC | archived/pyhpimc.py | https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L543-L566 | def create_dev_vlan(devid, vlanid, vlan_name):
"""
function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the
specified VLAN from the target device. VLAN Name MUST be valid on target device.
:param devid: int or str value of the target device
... | [
"def",
"create_dev_vlan",
"(",
"devid",
",",
"vlanid",
",",
"vlan_name",
")",
":",
"if",
"auth",
"is",
"None",
"or",
"url",
"is",
"None",
":",
"# checks to see if the imc credentials are already available",
"set_imc_creds",
"(",
")",
"create_dev_vlan_url",
"=",
"\"/... | function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the
specified VLAN from the target device. VLAN Name MUST be valid on target device.
:param devid: int or str value of the target device
:param vlanid:int or str value of target 802.1q VLAN
... | [
"function",
"takes",
"devid",
"and",
"vlanid",
"vlan_name",
"of",
"specific",
"device",
"and",
"802",
".",
"1q",
"VLAN",
"tag",
"and",
"issues",
"a",
"RESTFUL",
"call",
"to",
"add",
"the",
"specified",
"VLAN",
"from",
"the",
"target",
"device",
".",
"VLAN"... | python | train |
ebu/PlugIt | plugit_proxy/views.py | https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L495-L530 | def build_final_response(request, meta, result, menu, hproject, proxyMode, context):
"""Build the final response to send back to the browser"""
if 'no_template' in meta and meta['no_template']: # Just send the json back
return HttpResponse(result)
# TODO this breaks pages not using new template
... | [
"def",
"build_final_response",
"(",
"request",
",",
"meta",
",",
"result",
",",
"menu",
",",
"hproject",
",",
"proxyMode",
",",
"context",
")",
":",
"if",
"'no_template'",
"in",
"meta",
"and",
"meta",
"[",
"'no_template'",
"]",
":",
"# Just send the json back"... | Build the final response to send back to the browser | [
"Build",
"the",
"final",
"response",
"to",
"send",
"back",
"to",
"the",
"browser"
] | python | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree_ensemble.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree_ensemble.py#L75-L156 | def convert_tree_ensemble(model, feature_names, target, force_32bit_float):
"""Convert a generic tree model to the protobuf spec.
This currently supports:
* Decision tree regression
Parameters
----------
model: str | Booster
Path on disk where the XGboost JSON representation of the m... | [
"def",
"convert_tree_ensemble",
"(",
"model",
",",
"feature_names",
",",
"target",
",",
"force_32bit_float",
")",
":",
"if",
"not",
"(",
"_HAS_XGBOOST",
")",
":",
"raise",
"RuntimeError",
"(",
"'xgboost not found. xgboost conversion API is disabled.'",
")",
"import",
... | Convert a generic tree model to the protobuf spec.
This currently supports:
* Decision tree regression
Parameters
----------
model: str | Booster
Path on disk where the XGboost JSON representation of the model is or
a handle to the XGboost model.
feature_names : list of stri... | [
"Convert",
"a",
"generic",
"tree",
"model",
"to",
"the",
"protobuf",
"spec",
"."
] | python | train |
decryptus/httpdis | httpdis/httpdis.py | https://github.com/decryptus/httpdis/blob/5d198cdc5558f416634602689b3df2c8aeb34984/httpdis/httpdis.py#L1114-L1134 | def sigterm_handler(signum, stack_frame):
"""
Just tell the server to exit.
WARNING: There are race conditions, for example with TimeoutSocket.accept.
We don't care: the user can just rekill the process after like 1 sec. if
the first kill did not work.
"""
# pylint: disable-msg=W0613
gl... | [
"def",
"sigterm_handler",
"(",
"signum",
",",
"stack_frame",
")",
":",
"# pylint: disable-msg=W0613",
"global",
"_KILLED",
"for",
"name",
",",
"cmd",
"in",
"_COMMANDS",
".",
"iteritems",
"(",
")",
":",
"if",
"cmd",
".",
"at_stop",
":",
"LOG",
".",
"info",
... | Just tell the server to exit.
WARNING: There are race conditions, for example with TimeoutSocket.accept.
We don't care: the user can just rekill the process after like 1 sec. if
the first kill did not work. | [
"Just",
"tell",
"the",
"server",
"to",
"exit",
"."
] | python | train |
mdickinson/bigfloat | bigfloat/core.py | https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L512-L523 | def copy_neg(self):
""" Return a copy of self with the opposite sign bit.
Unlike -self, this does not make use of the context: the result
has the same precision as the original.
"""
result = mpfr.Mpfr_t.__new__(BigFloat)
mpfr.mpfr_init2(result, self.precision)
... | [
"def",
"copy_neg",
"(",
"self",
")",
":",
"result",
"=",
"mpfr",
".",
"Mpfr_t",
".",
"__new__",
"(",
"BigFloat",
")",
"mpfr",
".",
"mpfr_init2",
"(",
"result",
",",
"self",
".",
"precision",
")",
"new_sign",
"=",
"not",
"self",
".",
"_sign",
"(",
")"... | Return a copy of self with the opposite sign bit.
Unlike -self, this does not make use of the context: the result
has the same precision as the original. | [
"Return",
"a",
"copy",
"of",
"self",
"with",
"the",
"opposite",
"sign",
"bit",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.