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 |
|---|---|---|---|---|---|---|---|---|
Chilipp/funcargparse | funcargparse/__init__.py | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L467-L474 | def _get_corresponding_parsers(self, func):
"""Get the parser that has been set up by the given `function`"""
if func in self._used_functions:
yield self
if self._subparsers_action is not None:
for parser in self._subparsers_action.choices.values():
for sp... | [
"def",
"_get_corresponding_parsers",
"(",
"self",
",",
"func",
")",
":",
"if",
"func",
"in",
"self",
".",
"_used_functions",
":",
"yield",
"self",
"if",
"self",
".",
"_subparsers_action",
"is",
"not",
"None",
":",
"for",
"parser",
"in",
"self",
".",
"_subp... | Get the parser that has been set up by the given `function` | [
"Get",
"the",
"parser",
"that",
"has",
"been",
"set",
"up",
"by",
"the",
"given",
"function"
] | python | train |
yymao/generic-catalog-reader | GCR/base.py | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L102-L124 | def has_quantities(self, quantities, include_native=True):
"""
Check if ALL *quantities* specified are available in this catalog
Parameters
----------
quantities : iterable
a list of quantity names to check
include_native : bool, optional
whether... | [
"def",
"has_quantities",
"(",
"self",
",",
"quantities",
",",
"include_native",
"=",
"True",
")",
":",
"quantities",
"=",
"set",
"(",
"quantities",
")",
"if",
"include_native",
":",
"return",
"all",
"(",
"q",
"in",
"self",
".",
"_native_quantities",
"for",
... | Check if ALL *quantities* specified are available in this catalog
Parameters
----------
quantities : iterable
a list of quantity names to check
include_native : bool, optional
whether or not to include native quantity names when checking
Returns
... | [
"Check",
"if",
"ALL",
"*",
"quantities",
"*",
"specified",
"are",
"available",
"in",
"this",
"catalog"
] | python | train |
kejbaly2/metrique | metrique/utils.py | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/utils.py#L374-L429 | def debug_setup(logger=None, level=None, log2file=None,
log_file=None, log_format=None, log_dir=None,
log2stdout=None, truncate=False):
'''
Local object instance logger setup.
Verbosity levels are determined as such::
if level in [-1, False]:
logger.setL... | [
"def",
"debug_setup",
"(",
"logger",
"=",
"None",
",",
"level",
"=",
"None",
",",
"log2file",
"=",
"None",
",",
"log_file",
"=",
"None",
",",
"log_format",
"=",
"None",
",",
"log_dir",
"=",
"None",
",",
"log2stdout",
"=",
"None",
",",
"truncate",
"=",
... | Local object instance logger setup.
Verbosity levels are determined as such::
if level in [-1, False]:
logger.setLevel(logging.WARN)
elif level in [0, None]:
logger.setLevel(logging.INFO)
elif level in [True, 1, 2]:
logger.setLevel(logging.DEBUG)
If... | [
"Local",
"object",
"instance",
"logger",
"setup",
"."
] | python | train |
noahbenson/pimms | pimms/immutable.py | https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/immutable.py#L588-L618 | def _imm_merge_class(cls, parent):
'''
_imm_merge_class(imm_class, parent) updates the given immutable class imm_class to have the
appropriate attributes of its given parent class. The parents should be passed through this
function in method-resolution order.
'''
# If this is not an immutable pa... | [
"def",
"_imm_merge_class",
"(",
"cls",
",",
"parent",
")",
":",
"# If this is not an immutable parent, ignore it",
"if",
"not",
"hasattr",
"(",
"parent",
",",
"'_pimms_immutable_data_'",
")",
":",
"return",
"cls",
"# otherwise, let's look at the data",
"cdat",
"=",
"cls... | _imm_merge_class(imm_class, parent) updates the given immutable class imm_class to have the
appropriate attributes of its given parent class. The parents should be passed through this
function in method-resolution order. | [
"_imm_merge_class",
"(",
"imm_class",
"parent",
")",
"updates",
"the",
"given",
"immutable",
"class",
"imm_class",
"to",
"have",
"the",
"appropriate",
"attributes",
"of",
"its",
"given",
"parent",
"class",
".",
"The",
"parents",
"should",
"be",
"passed",
"throug... | python | train |
SCIP-Interfaces/PySCIPOpt | examples/finished/read_tsplib.py | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/read_tsplib.py#L14-L24 | def distL2(x1,y1,x2,y2):
"""Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
xdiff = x2 - x1
ydiff ... | [
"def",
"distL2",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
":",
"xdiff",
"=",
"x2",
"-",
"x1",
"ydiff",
"=",
"y2",
"-",
"y1",
"return",
"int",
"(",
"math",
".",
"sqrt",
"(",
"xdiff",
"*",
"xdiff",
"+",
"ydiff",
"*",
"ydiff",
")",
"+",
... | Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters | [
"Compute",
"the",
"L2",
"-",
"norm",
"(",
"Euclidean",
")",
"distance",
"between",
"two",
"points",
"."
] | python | train |
portfors-lab/sparkle | sparkle/tools/audiotools.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L399-L427 | def calibrate_signal(signal, resp, fs, frange):
"""Given original signal and recording, spits out a calibrated signal"""
# remove dc offset from recorded response (synthesized orignal shouldn't have one)
dc = np.mean(resp)
resp = resp - dc
npts = len(signal)
f0 = np.ceil(frange[0] / (float(fs) ... | [
"def",
"calibrate_signal",
"(",
"signal",
",",
"resp",
",",
"fs",
",",
"frange",
")",
":",
"# remove dc offset from recorded response (synthesized orignal shouldn't have one)",
"dc",
"=",
"np",
".",
"mean",
"(",
"resp",
")",
"resp",
"=",
"resp",
"-",
"dc",
"npts",... | Given original signal and recording, spits out a calibrated signal | [
"Given",
"original",
"signal",
"and",
"recording",
"spits",
"out",
"a",
"calibrated",
"signal"
] | python | train |
ralphje/imagemounter | imagemounter/unmounter.py | https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/unmounter.py#L103-L114 | def _index_loopbacks(self):
"""Finds all loopbacks and stores them in :attr:`loopbacks`"""
self.loopbacks = {}
try:
result = _util.check_output_(['losetup', '-a'])
for line in result.splitlines():
m = re.match(r'(.+): (.+) \((.+)\).*', line)
... | [
"def",
"_index_loopbacks",
"(",
"self",
")",
":",
"self",
".",
"loopbacks",
"=",
"{",
"}",
"try",
":",
"result",
"=",
"_util",
".",
"check_output_",
"(",
"[",
"'losetup'",
",",
"'-a'",
"]",
")",
"for",
"line",
"in",
"result",
".",
"splitlines",
"(",
... | Finds all loopbacks and stores them in :attr:`loopbacks` | [
"Finds",
"all",
"loopbacks",
"and",
"stores",
"them",
"in",
":",
"attr",
":",
"loopbacks"
] | python | train |
Parsl/parsl | parsl/data_provider/data_manager.py | https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/data_provider/data_manager.py#L51-L57 | def get_data_manager(cls):
"""Return the DataManager of the currently loaded DataFlowKernel.
"""
from parsl.dataflow.dflow import DataFlowKernelLoader
dfk = DataFlowKernelLoader.dfk()
return dfk.executors['data_manager'] | [
"def",
"get_data_manager",
"(",
"cls",
")",
":",
"from",
"parsl",
".",
"dataflow",
".",
"dflow",
"import",
"DataFlowKernelLoader",
"dfk",
"=",
"DataFlowKernelLoader",
".",
"dfk",
"(",
")",
"return",
"dfk",
".",
"executors",
"[",
"'data_manager'",
"]"
] | Return the DataManager of the currently loaded DataFlowKernel. | [
"Return",
"the",
"DataManager",
"of",
"the",
"currently",
"loaded",
"DataFlowKernel",
"."
] | python | valid |
zimeon/iiif | iiif/manipulator.py | https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L49-L68 | def compliance_uri(self):
"""Compliance URI based on api_version.
Value is based on api_version and complicance_level, will be
None if either are unset/unrecognized. The assumption here is
that the api_version and level are orthogonal, override this
method if that isn't true.
... | [
"def",
"compliance_uri",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"api_version",
"==",
"'1.0'",
")",
":",
"uri_pattern",
"=",
"r'http://library.stanford.edu/iiif/image-api/compliance.html#level%d'",
"elif",
"(",
"self",
".",
"api_version",
"==",
"'1.1'",
")",
... | Compliance URI based on api_version.
Value is based on api_version and complicance_level, will be
None if either are unset/unrecognized. The assumption here is
that the api_version and level are orthogonal, override this
method if that isn't true. | [
"Compliance",
"URI",
"based",
"on",
"api_version",
"."
] | python | train |
autokey/autokey | lib/autokey/qtapp.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtapp.py#L182-L192 | def _create_storage_directories():
"""Create various storage directories, if those do not exist."""
# Create configuration directory
if not os.path.exists(common.CONFIG_DIR):
os.makedirs(common.CONFIG_DIR)
# Create data directory (for log file)
if not os.path.exists(c... | [
"def",
"_create_storage_directories",
"(",
")",
":",
"# Create configuration directory",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"common",
".",
"CONFIG_DIR",
")",
":",
"os",
".",
"makedirs",
"(",
"common",
".",
"CONFIG_DIR",
")",
"# Create data direc... | Create various storage directories, if those do not exist. | [
"Create",
"various",
"storage",
"directories",
"if",
"those",
"do",
"not",
"exist",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sizeformatter.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sizeformatter.py#L29-L38 | def sizeof_fmt(num: float, suffix: str = 'B') -> str:
"""
Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
"""
for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'):
if abs(num) < 1024.0:
... | [
"def",
"sizeof_fmt",
"(",
"num",
":",
"float",
",",
"suffix",
":",
"str",
"=",
"'B'",
")",
"->",
"str",
":",
"for",
"unit",
"in",
"(",
"''",
",",
"'Ki'",
",",
"'Mi'",
",",
"'Gi'",
",",
"'Ti'",
",",
"'Pi'",
",",
"'Ei'",
",",
"'Zi'",
")",
":",
... | Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841. | [
"Formats",
"a",
"number",
"of",
"bytes",
"in",
"a",
"human",
"-",
"readable",
"binary",
"format",
"(",
"e",
".",
"g",
".",
"2048",
"becomes",
"2",
"KiB",
")",
";",
"from",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"109484... | python | train |
tanghaibao/jcvi | jcvi/assembly/unitig.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/unitig.py#L346-L370 | def pull(args):
"""
%prog pull version partID unitigID
For example, `%prog pull 5 530` will pull the utg530 from partition 5
The layout is written to `unitig530`
"""
p = OptionParser(pull.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
... | [
"def",
"pull",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"pull",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"3",
":",
"sys",
".",
"exit",
"(",
"not",... | %prog pull version partID unitigID
For example, `%prog pull 5 530` will pull the utg530 from partition 5
The layout is written to `unitig530` | [
"%prog",
"pull",
"version",
"partID",
"unitigID"
] | python | train |
SystemRDL/systemrdl-compiler | systemrdl/compiler.py | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/compiler.py#L94-L152 | def compile_file(self, path, incl_search_paths=None):
"""
Parse & compile a single file and append it to RDLCompiler's root
namespace.
If any exceptions (:class:`~systemrdl.RDLCompileError` or other)
occur during compilation, then the RDLCompiler object should be discarded.
... | [
"def",
"compile_file",
"(",
"self",
",",
"path",
",",
"incl_search_paths",
"=",
"None",
")",
":",
"if",
"incl_search_paths",
"is",
"None",
":",
"incl_search_paths",
"=",
"[",
"]",
"fpp",
"=",
"preprocessor",
".",
"FilePreprocessor",
"(",
"self",
".",
"env",
... | Parse & compile a single file and append it to RDLCompiler's root
namespace.
If any exceptions (:class:`~systemrdl.RDLCompileError` or other)
occur during compilation, then the RDLCompiler object should be discarded.
Parameters
----------
path:str
Path to an... | [
"Parse",
"&",
"compile",
"a",
"single",
"file",
"and",
"append",
"it",
"to",
"RDLCompiler",
"s",
"root",
"namespace",
"."
] | python | train |
SKA-ScienceDataProcessor/integration-prototype | sip/platform/logging/sip_logging/sip_logging.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/platform/logging/sip_logging/sip_logging.py#L111-L116 | def disable_logger(logger_name: str, propagate: bool = False):
"""Disable output for the logger of the specified name."""
log = logging.getLogger(logger_name)
log.propagate = propagate
for handler in log.handlers:
log.removeHandler(handler) | [
"def",
"disable_logger",
"(",
"logger_name",
":",
"str",
",",
"propagate",
":",
"bool",
"=",
"False",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"logger_name",
")",
"log",
".",
"propagate",
"=",
"propagate",
"for",
"handler",
"in",
"log",
".... | Disable output for the logger of the specified name. | [
"Disable",
"output",
"for",
"the",
"logger",
"of",
"the",
"specified",
"name",
"."
] | python | train |
junzis/pyModeS | pyModeS/extra/tcpclient.py | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/extra/tcpclient.py#L67-L145 | def read_beast_buffer(self):
'''
<esc> "1" : 6 byte MLAT timestamp, 1 byte signal level,
2 byte Mode-AC
<esc> "2" : 6 byte MLAT timestamp, 1 byte signal level,
7 byte Mode-S short frame
<esc> "3" : 6 byte MLAT timestamp, 1 byte signal level,
14 byte Mo... | [
"def",
"read_beast_buffer",
"(",
"self",
")",
":",
"messages_mlat",
"=",
"[",
"]",
"msg",
"=",
"[",
"]",
"i",
"=",
"0",
"# process the buffer until the last divider <esc> 0x1a",
"# then, reset the self.buffer with the remainder",
"while",
"i",
"<",
"len",
"(",
"self",... | <esc> "1" : 6 byte MLAT timestamp, 1 byte signal level,
2 byte Mode-AC
<esc> "2" : 6 byte MLAT timestamp, 1 byte signal level,
7 byte Mode-S short frame
<esc> "3" : 6 byte MLAT timestamp, 1 byte signal level,
14 byte Mode-S long frame
<esc> "4" : 6 byte MLAT t... | [
"<esc",
">",
"1",
":",
"6",
"byte",
"MLAT",
"timestamp",
"1",
"byte",
"signal",
"level",
"2",
"byte",
"Mode",
"-",
"AC",
"<esc",
">",
"2",
":",
"6",
"byte",
"MLAT",
"timestamp",
"1",
"byte",
"signal",
"level",
"7",
"byte",
"Mode",
"-",
"S",
"short"... | python | train |
biocore/burrito-fillings | bfillings/uclust.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L433-L482 | def uclust_cluster_from_sorted_fasta_filepath(
fasta_filepath,
uc_save_filepath=None,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
enable_rev_strand_matc... | [
"def",
"uclust_cluster_from_sorted_fasta_filepath",
"(",
"fasta_filepath",
",",
"uc_save_filepath",
"=",
"None",
",",
"percent_ID",
"=",
"0.97",
",",
"max_accepts",
"=",
"1",
",",
"max_rejects",
"=",
"8",
",",
"stepwords",
"=",
"8",
",",
"word_length",
"=",
"8",... | Returns clustered uclust file from sorted fasta | [
"Returns",
"clustered",
"uclust",
"file",
"from",
"sorted",
"fasta"
] | python | train |
pytries/DAWG-Python | dawg_python/wrapper.py | https://github.com/pytries/DAWG-Python/blob/e56241ec919b78735ff79014bf18d7fd1f8e08b9/dawg_python/wrapper.py#L51-L59 | def follow_char(self, label, index):
"Follows a transition"
offset = units.offset(self._units[index])
next_index = (index ^ offset ^ label) & units.PRECISION_MASK
if units.label(self._units[next_index]) != label:
return None
return next_index | [
"def",
"follow_char",
"(",
"self",
",",
"label",
",",
"index",
")",
":",
"offset",
"=",
"units",
".",
"offset",
"(",
"self",
".",
"_units",
"[",
"index",
"]",
")",
"next_index",
"=",
"(",
"index",
"^",
"offset",
"^",
"label",
")",
"&",
"units",
"."... | Follows a transition | [
"Follows",
"a",
"transition"
] | python | train |
Azure/blobxfer | blobxfer/operations/download.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/download.py#L659-L671 | def _cleanup_temporary_files(self):
# type: (Downloader) -> None
"""Cleanup temporary files in case of an exception or interrupt.
This function is not thread-safe.
:param Downloader self: this
"""
# iterate through dd map and cleanup files
for key in self._dd_map:... | [
"def",
"_cleanup_temporary_files",
"(",
"self",
")",
":",
"# type: (Downloader) -> None",
"# iterate through dd map and cleanup files",
"for",
"key",
"in",
"self",
".",
"_dd_map",
":",
"dd",
"=",
"self",
".",
"_dd_map",
"[",
"key",
"]",
"try",
":",
"dd",
".",
"c... | Cleanup temporary files in case of an exception or interrupt.
This function is not thread-safe.
:param Downloader self: this | [
"Cleanup",
"temporary",
"files",
"in",
"case",
"of",
"an",
"exception",
"or",
"interrupt",
".",
"This",
"function",
"is",
"not",
"thread",
"-",
"safe",
".",
":",
"param",
"Downloader",
"self",
":",
"this"
] | python | train |
lanius/tinyik | tinyik/solver.py | https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/solver.py#L26-L32 | def solve(self, angles):
"""Calculate a position of the end-effector and return it."""
return reduce(
lambda a, m: np.dot(m, a),
reversed(self._matrices(angles)),
np.array([0., 0., 0., 1.])
)[:3] | [
"def",
"solve",
"(",
"self",
",",
"angles",
")",
":",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"m",
":",
"np",
".",
"dot",
"(",
"m",
",",
"a",
")",
",",
"reversed",
"(",
"self",
".",
"_matrices",
"(",
"angles",
")",
")",
",",
"np",
".",
"... | Calculate a position of the end-effector and return it. | [
"Calculate",
"a",
"position",
"of",
"the",
"end",
"-",
"effector",
"and",
"return",
"it",
"."
] | python | train |
FujiMakoto/IPS-Vagrant | ips_vagrant/installer/V_4_1_3_2.py | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/installer/V_4_1_3_2.py#L76-L113 | def install(self):
"""
Run the actual installation
"""
self._start_install()
mr_link = self._get_mr_link()
# Set up the progress bar
pbar = ProgressBar(100, 'Running installation...')
pbar.start()
mr_j, mr_r = self._ajax(mr_link)
# Loop u... | [
"def",
"install",
"(",
"self",
")",
":",
"self",
".",
"_start_install",
"(",
")",
"mr_link",
"=",
"self",
".",
"_get_mr_link",
"(",
")",
"# Set up the progress bar",
"pbar",
"=",
"ProgressBar",
"(",
"100",
",",
"'Running installation...'",
")",
"pbar",
".",
... | Run the actual installation | [
"Run",
"the",
"actual",
"installation"
] | python | train |
janpipek/physt | physt/plotting/matplotlib.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L865-L958 | def _apply_xy_lims(ax: Axes, h: Union[Histogram1D, Histogram2D], data: np.ndarray, kwargs: dict):
"""Apply axis limits and scales from kwargs.
Note: if exponential binning is used, the scale defaults to "log"
Parameters
----------
data : np.ndarray
The frequencies or densities or otherwise... | [
"def",
"_apply_xy_lims",
"(",
"ax",
":",
"Axes",
",",
"h",
":",
"Union",
"[",
"Histogram1D",
",",
"Histogram2D",
"]",
",",
"data",
":",
"np",
".",
"ndarray",
",",
"kwargs",
":",
"dict",
")",
":",
"ylim",
"=",
"kwargs",
".",
"pop",
"(",
"\"ylim\"",
... | Apply axis limits and scales from kwargs.
Note: if exponential binning is used, the scale defaults to "log"
Parameters
----------
data : np.ndarray
The frequencies or densities or otherwise manipulated data
kwargs: dict
xscale : Optional[str]
If "log", the horizontal ax... | [
"Apply",
"axis",
"limits",
"and",
"scales",
"from",
"kwargs",
"."
] | python | train |
jxtech/wechatpy | wechatpy/pay/api/coupon.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/pay/api/coupon.py#L43-L60 | def query_stock(self, stock_id, op_user_id=None, device_info=None):
"""
查询代金券批次
:param stock_id: 代金券批次 ID
:param op_user_id: 可选,操作员账号,默认为商户号
:param device_info: 可选,微信支付分配的终端设备号
:return: 返回的结果信息
"""
data = {
'appid': self.appid,
'co... | [
"def",
"query_stock",
"(",
"self",
",",
"stock_id",
",",
"op_user_id",
"=",
"None",
",",
"device_info",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'appid'",
":",
"self",
".",
"appid",
",",
"'coupon_stock_id'",
":",
"stock_id",
",",
"'op_user_id'",
":",
"o... | 查询代金券批次
:param stock_id: 代金券批次 ID
:param op_user_id: 可选,操作员账号,默认为商户号
:param device_info: 可选,微信支付分配的终端设备号
:return: 返回的结果信息 | [
"查询代金券批次"
] | python | train |
frascoweb/frasco-users | frasco_users/__init__.py | https://github.com/frascoweb/frasco-users/blob/16591ca466de5b7c80d7a2384327d9cf2d919c41/frasco_users/__init__.py#L431-L439 | def _login(self, user, provider=None, remember=False, force=False, **attrs):
"""Updates user attributes and login the user in flask-login
"""
user.last_login_at = datetime.datetime.now()
user.last_login_provider = provider or self.options["default_auth_provider_name"]
user.last_l... | [
"def",
"_login",
"(",
"self",
",",
"user",
",",
"provider",
"=",
"None",
",",
"remember",
"=",
"False",
",",
"force",
"=",
"False",
",",
"*",
"*",
"attrs",
")",
":",
"user",
".",
"last_login_at",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"... | Updates user attributes and login the user in flask-login | [
"Updates",
"user",
"attributes",
"and",
"login",
"the",
"user",
"in",
"flask",
"-",
"login"
] | python | train |
tuomas2/automate | src/automate/callable.py | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/callable.py#L192-L211 | def setup_callable_system(self, system, init=False):
"""
This function basically sets up :attr:`.system`, if it is not yet set up. After that,
other Callable initialization actions are performed.
:param init: value ``True`` is given when running this at the initialization ph... | [
"def",
"setup_callable_system",
"(",
"self",
",",
"system",
",",
"init",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"system",
"or",
"init",
":",
"self",
".",
"system",
"=",
"system",
"self",
".",
"_fix_list",
"(",
"self",
".",
"_args",
")",
"s... | This function basically sets up :attr:`.system`, if it is not yet set up. After that,
other Callable initialization actions are performed.
:param init: value ``True`` is given when running this at the initialization phase. Then system
attribute is set already, but calla... | [
"This",
"function",
"basically",
"sets",
"up",
":",
"attr",
":",
".",
"system",
"if",
"it",
"is",
"not",
"yet",
"set",
"up",
".",
"After",
"that",
"other",
"Callable",
"initialization",
"actions",
"are",
"performed",
"."
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/proxy/transactional_map.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/transactional_map.py#L35-L47 | def get_for_update(self, key):
"""
Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at
the end of the transaction (either commit or rollback).
:param key: (object), the specified key.
:return: (object), the value for t... | [
"def",
"get_for_update",
"(",
"self",
",",
"key",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be none\"",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"transactional_map_get_for_update_codec",
",",
"key",
"=",
"self",
".",
"_to_data",
"(",
"k... | Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at
the end of the transaction (either commit or rollback).
:param key: (object), the specified key.
:return: (object), the value for the specified key.
.. seealso::
... | [
"Locks",
"the",
"key",
"and",
"then",
"gets",
"and",
"returns",
"the",
"value",
"to",
"which",
"the",
"specified",
"key",
"is",
"mapped",
".",
"Lock",
"will",
"be",
"released",
"at",
"the",
"end",
"of",
"the",
"transaction",
"(",
"either",
"commit",
"or"... | python | train |
cloudendpoints/endpoints-python | endpoints/parameter_converter.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/parameter_converter.py#L126-L147 | def _get_parameter_conversion_entry(parameter_config):
"""Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Re... | [
"def",
"_get_parameter_conversion_entry",
"(",
"parameter_config",
")",
":",
"entry",
"=",
"_PARAM_CONVERSION_MAP",
".",
"get",
"(",
"parameter_config",
".",
"get",
"(",
"'type'",
")",
")",
"# Special handling for enum parameters. An enum's type is 'string', so we",
"# need ... | Get information needed to convert the given parameter to its API type.
Args:
parameter_config: The dictionary containing information specific to the
parameter in question. This is retrieved from request.parameters in the
method config.
Returns:
The entry from _PARAM_CONVERSION_MAP with functio... | [
"Get",
"information",
"needed",
"to",
"convert",
"the",
"given",
"parameter",
"to",
"its",
"API",
"type",
"."
] | python | train |
biocore/burrito-fillings | bfillings/clearcut.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clearcut.py#L319-L364 | def build_tree_from_distance_matrix(matrix, best_tree=False, params={},\
working_dir='/tmp'):
"""Returns a tree from a distance matrix.
matrix: a square Dict2D object (cogent.util.dict2d)
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: ... | [
"def",
"build_tree_from_distance_matrix",
"(",
"matrix",
",",
"best_tree",
"=",
"False",
",",
"params",
"=",
"{",
"}",
",",
"working_dir",
"=",
"'/tmp'",
")",
":",
"params",
"[",
"'--out'",
"]",
"=",
"get_tmp_filename",
"(",
"working_dir",
")",
"# Create insta... | Returns a tree from a distance matrix.
matrix: a square Dict2D object (cogent.util.dict2d)
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree... | [
"Returns",
"a",
"tree",
"from",
"a",
"distance",
"matrix",
"."
] | python | train |
bblfsh/client-python | bblfsh/client.py | https://github.com/bblfsh/client-python/blob/815835d191d5e385973f3c685849cc3b46aa20a5/bblfsh/client.py#L56-L85 | def parse(self, filename: str, language: Optional[str]=None,
contents: Optional[str]=None, mode: Optional[ModeType]=None,
timeout: Optional[int]=None) -> ResultContext:
"""
Queries the Babelfish server and receives the UAST response for the specified
file.
:p... | [
"def",
"parse",
"(",
"self",
",",
"filename",
":",
"str",
",",
"language",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"contents",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"mode",
":",
"Optional",
"[",
"ModeType",
"]",
"=",
"None... | Queries the Babelfish server and receives the UAST response for the specified
file.
:param filename: The path to the file. Can be arbitrary if contents \
is not None.
:param language: The programming language of the file. Refer to \
https://doc.... | [
"Queries",
"the",
"Babelfish",
"server",
"and",
"receives",
"the",
"UAST",
"response",
"for",
"the",
"specified",
"file",
"."
] | python | train |
wrobstory/vincent | vincent/data.py | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L367-L430 | def keypairs(cls, data, columns=None, use_index=False, name=None):
"""This will format the data as Key: Value pairs, rather than the
idx/col/val style. This is useful for some transforms, and to
key choropleth map data
Standard Data Types:
List: [0, 10, 20, 30, 40]
... | [
"def",
"keypairs",
"(",
"cls",
",",
"data",
",",
"columns",
"=",
"None",
",",
"use_index",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"'table'",
"cls",
".",
"raw_data",
"=",
"data",
"# Tuples",
"if",
"i... | This will format the data as Key: Value pairs, rather than the
idx/col/val style. This is useful for some transforms, and to
key choropleth map data
Standard Data Types:
List: [0, 10, 20, 30, 40]
Paired Tuples: ((0, 1), (0, 2), (0, 3))
Dict: {'A': 10, 'B': 20... | [
"This",
"will",
"format",
"the",
"data",
"as",
"Key",
":",
"Value",
"pairs",
"rather",
"than",
"the",
"idx",
"/",
"col",
"/",
"val",
"style",
".",
"This",
"is",
"useful",
"for",
"some",
"transforms",
"and",
"to",
"key",
"choropleth",
"map",
"data"
] | python | train |
pypa/pipenv | pipenv/vendor/dotenv/cli.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L72-L80 | def unset(ctx, key):
'''Removes the given key.'''
file = ctx.obj['FILE']
quote = ctx.obj['QUOTE']
success, key = unset_key(file, key, quote)
if success:
click.echo("Successfully removed %s" % key)
else:
exit(1) | [
"def",
"unset",
"(",
"ctx",
",",
"key",
")",
":",
"file",
"=",
"ctx",
".",
"obj",
"[",
"'FILE'",
"]",
"quote",
"=",
"ctx",
".",
"obj",
"[",
"'QUOTE'",
"]",
"success",
",",
"key",
"=",
"unset_key",
"(",
"file",
",",
"key",
",",
"quote",
")",
"if... | Removes the given key. | [
"Removes",
"the",
"given",
"key",
"."
] | python | train |
oceanprotocol/squid-py | squid_py/agreements/service_factory.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L100-L137 | def build_service(service_descriptor, did):
"""
Build a service.
:param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes
and the second item is a dict of parameters and values required by the service
:param did: DID, str
:return: Service... | [
"def",
"build_service",
"(",
"service_descriptor",
",",
"did",
")",
":",
"assert",
"isinstance",
"(",
"service_descriptor",
",",
"tuple",
")",
"and",
"len",
"(",
"service_descriptor",
")",
"==",
"2",
",",
"'Unknown service descriptor format.'",
"service_type",
",",
... | Build a service.
:param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes
and the second item is a dict of parameters and values required by the service
:param did: DID, str
:return: Service | [
"Build",
"a",
"service",
"."
] | python | train |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L444-L476 | def create_back_links(env):
"""
Create back-links in all found needs.
But do this only once, as all needs are already collected and this sorting is for all
needs and not only for the ones of the current document.
:param env: sphinx enviroment
:return: None
"""
if env.needs_workflow['bac... | [
"def",
"create_back_links",
"(",
"env",
")",
":",
"if",
"env",
".",
"needs_workflow",
"[",
"'backlink_creation'",
"]",
":",
"return",
"needs",
"=",
"env",
".",
"needs_all_needs",
"for",
"key",
",",
"need",
"in",
"needs",
".",
"items",
"(",
")",
":",
"for... | Create back-links in all found needs.
But do this only once, as all needs are already collected and this sorting is for all
needs and not only for the ones of the current document.
:param env: sphinx enviroment
:return: None | [
"Create",
"back",
"-",
"links",
"in",
"all",
"found",
"needs",
".",
"But",
"do",
"this",
"only",
"once",
"as",
"all",
"needs",
"are",
"already",
"collected",
"and",
"this",
"sorting",
"is",
"for",
"all",
"needs",
"and",
"not",
"only",
"for",
"the",
"on... | python | train |
n1analytics/python-paillier | phe/util.py | https://github.com/n1analytics/python-paillier/blob/955f8c0bfa9623be15b75462b121d28acf70f04b/phe/util.py#L367-L404 | def miller_rabin(n, k):
"""Run the Miller-Rabin test on n with at most k iterations
Arguments:
n (int): number whose primality is to be tested
k (int): maximum number of iterations to run
Returns:
bool: If n is prime, then True is returned. Otherwise, False is
returned, exc... | [
"def",
"miller_rabin",
"(",
"n",
",",
"k",
")",
":",
"assert",
"n",
">",
"3",
"# find r and d such that n-1 = 2^r × d",
"d",
"=",
"n",
"-",
"1",
"r",
"=",
"0",
"while",
"d",
"%",
"2",
"==",
"0",
":",
"d",
"//=",
"2",
"r",
"+=",
"1",
"assert",
"n"... | Run the Miller-Rabin test on n with at most k iterations
Arguments:
n (int): number whose primality is to be tested
k (int): maximum number of iterations to run
Returns:
bool: If n is prime, then True is returned. Otherwise, False is
returned, except with probability less than ... | [
"Run",
"the",
"Miller",
"-",
"Rabin",
"test",
"on",
"n",
"with",
"at",
"most",
"k",
"iterations"
] | python | train |
TheOneHyer/arandomness | build/lib.linux-x86_64-3.6/arandomness/str/max_substring.py | https://github.com/TheOneHyer/arandomness/blob/ae9f630e9a1d67b0eb6d61644a49756de8a5268c/build/lib.linux-x86_64-3.6/arandomness/str/max_substring.py#L31-L71 | def max_substring(words, position=0, _last_letter=''):
"""Finds max substring shared by all strings starting at position
Args:
words (list): list of unicode of all words to compare
position (int): starting position in each word to begin analyzing
for substring
... | [
"def",
"max_substring",
"(",
"words",
",",
"position",
"=",
"0",
",",
"_last_letter",
"=",
"''",
")",
":",
"# If end of word is reached, begin reconstructing the substring",
"try",
":",
"letter",
"=",
"[",
"word",
"[",
"position",
"]",
"for",
"word",
"in",
"word... | Finds max substring shared by all strings starting at position
Args:
words (list): list of unicode of all words to compare
position (int): starting position in each word to begin analyzing
for substring
_last_letter (unicode): last common letter, only for use
... | [
"Finds",
"max",
"substring",
"shared",
"by",
"all",
"strings",
"starting",
"at",
"position"
] | python | train |
hydpy-dev/hydpy | hydpy/auxs/armatools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L201-L233 | def update_coefs(self):
"""(Re)calculate the MA coefficients based on the instantaneous
unit hydrograph."""
coefs = []
sum_coefs = 0.
moment1 = self.iuh.moment1
for t in itertools.count(0., 1.):
points = (moment1 % 1,) if t <= moment1 <= (t+2.) else ()
... | [
"def",
"update_coefs",
"(",
"self",
")",
":",
"coefs",
"=",
"[",
"]",
"sum_coefs",
"=",
"0.",
"moment1",
"=",
"self",
".",
"iuh",
".",
"moment1",
"for",
"t",
"in",
"itertools",
".",
"count",
"(",
"0.",
",",
"1.",
")",
":",
"points",
"=",
"(",
"mo... | (Re)calculate the MA coefficients based on the instantaneous
unit hydrograph. | [
"(",
"Re",
")",
"calculate",
"the",
"MA",
"coefficients",
"based",
"on",
"the",
"instantaneous",
"unit",
"hydrograph",
"."
] | python | train |
cgrok/cr-async | examples/crcog.py | https://github.com/cgrok/cr-async/blob/f65a968e54704168706d137d1ba662f55f8ab852/examples/crcog.py#L22-L42 | async def profile(self, ctx, tag):
'''Example command for use inside a discord bot cog.'''
if not self.check_valid_tag(tag):
return await ctx.send('Invalid tag!')
profile = await self.cr.get_profile(tag)
em = discord.Embed(color=0x00FFFFF)
em.set_author(name=str(pro... | [
"async",
"def",
"profile",
"(",
"self",
",",
"ctx",
",",
"tag",
")",
":",
"if",
"not",
"self",
".",
"check_valid_tag",
"(",
"tag",
")",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Invalid tag!'",
")",
"profile",
"=",
"await",
"self",
".",
"cr"... | Example command for use inside a discord bot cog. | [
"Example",
"command",
"for",
"use",
"inside",
"a",
"discord",
"bot",
"cog",
"."
] | python | train |
MAVENSDC/cdflib | cdflib/cdfread.py | https://github.com/MAVENSDC/cdflib/blob/d237c60e5db67db0f92d96054209c25c4042465c/cdflib/cdfread.py#L2196-L2211 | def _find_block(starts, ends, cur_block, rec_num): # @NoSelf
'''
Finds the block that rec_num is in if it is found. Otherwise it returns -1.
It also returns the block that has the physical data either at or
preceeding the rec_num.
It could be -1 if the preceeding block does not... | [
"def",
"_find_block",
"(",
"starts",
",",
"ends",
",",
"cur_block",
",",
"rec_num",
")",
":",
"# @NoSelf",
"total",
"=",
"len",
"(",
"starts",
")",
"if",
"(",
"cur_block",
"==",
"-",
"1",
")",
":",
"cur_block",
"=",
"0",
"for",
"x",
"in",
"range",
... | Finds the block that rec_num is in if it is found. Otherwise it returns -1.
It also returns the block that has the physical data either at or
preceeding the rec_num.
It could be -1 if the preceeding block does not exists. | [
"Finds",
"the",
"block",
"that",
"rec_num",
"is",
"in",
"if",
"it",
"is",
"found",
".",
"Otherwise",
"it",
"returns",
"-",
"1",
".",
"It",
"also",
"returns",
"the",
"block",
"that",
"has",
"the",
"physical",
"data",
"either",
"at",
"or",
"preceeding",
... | python | train |
pyecore/pyecore | pyecore/ordered_set_patch.py | https://github.com/pyecore/pyecore/blob/22b67ad8799594f8f44fd8bee497583d4f12ed63/pyecore/ordered_set_patch.py#L8-L27 | def insert(self, index, key):
"""Adds an element at a dedicated position in an OrderedSet.
This implementation is meant for the OrderedSet from the ordered_set
package only.
"""
if key in self.map:
return
# compute the right index
size = len(self.items)
if index < 0:
ind... | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"map",
":",
"return",
"# compute the right index",
"size",
"=",
"len",
"(",
"self",
".",
"items",
")",
"if",
"index",
"<",
"0",
":",
"index",
"=",
"si... | Adds an element at a dedicated position in an OrderedSet.
This implementation is meant for the OrderedSet from the ordered_set
package only. | [
"Adds",
"an",
"element",
"at",
"a",
"dedicated",
"position",
"in",
"an",
"OrderedSet",
"."
] | python | train |
HttpRunner/HttpRunner | httprunner/report.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/report.py#L92-L106 | def stringify_summary(summary):
""" stringify summary, in order to dump json file and generate html report.
"""
for index, suite_summary in enumerate(summary["details"]):
if not suite_summary.get("name"):
suite_summary["name"] = "testcase {}".format(index)
for record in suite_s... | [
"def",
"stringify_summary",
"(",
"summary",
")",
":",
"for",
"index",
",",
"suite_summary",
"in",
"enumerate",
"(",
"summary",
"[",
"\"details\"",
"]",
")",
":",
"if",
"not",
"suite_summary",
".",
"get",
"(",
"\"name\"",
")",
":",
"suite_summary",
"[",
"\"... | stringify summary, in order to dump json file and generate html report. | [
"stringify",
"summary",
"in",
"order",
"to",
"dump",
"json",
"file",
"and",
"generate",
"html",
"report",
"."
] | python | train |
jut-io/jut-python-tools | jut/commands/jobs.py | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/jobs.py#L116-L145 | def list(options):
"""
show all currently running jobs
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name']
client_id = c... | [
"def",
"list",
"(",
"options",
")",
":",
"configuration",
"=",
"config",
".",
"get_default",
"(",
")",
"app_url",
"=",
"configuration",
"[",
"'app_url'",
"]",
"if",
"options",
".",
"deployment",
"!=",
"None",
":",
"deployment_name",
"=",
"options",
".",
"d... | show all currently running jobs | [
"show",
"all",
"currently",
"running",
"jobs"
] | python | train |
quantopian/zipline | zipline/data/hdf5_daily_bars.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L745-L757 | def from_file(cls, h5_file):
"""
Construct from an h5py.File.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file.
"""
return cls({
country: HDF5DailyBarReader.from_file(h5_file, country)
for country in h5_file... | [
"def",
"from_file",
"(",
"cls",
",",
"h5_file",
")",
":",
"return",
"cls",
"(",
"{",
"country",
":",
"HDF5DailyBarReader",
".",
"from_file",
"(",
"h5_file",
",",
"country",
")",
"for",
"country",
"in",
"h5_file",
".",
"keys",
"(",
")",
"}",
")"
] | Construct from an h5py.File.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file. | [
"Construct",
"from",
"an",
"h5py",
".",
"File",
"."
] | python | train |
ib-lundgren/flask-oauthprovider | examples/demoprovider/login.py | https://github.com/ib-lundgren/flask-oauthprovider/blob/6c91e8c11fc3cee410cb755d52d9d2c5331ee324/examples/demoprovider/login.py#L33-L46 | def login():
"""Does the login via OpenID. Has to call into `oid.try_login`
to start the OpenID machinery.
"""
# if we are already logged in, go back to were we came from
if g.user is not None:
return redirect(oid.get_next_url())
if request.method == 'POST':
openid = request.for... | [
"def",
"login",
"(",
")",
":",
"# if we are already logged in, go back to were we came from",
"if",
"g",
".",
"user",
"is",
"not",
"None",
":",
"return",
"redirect",
"(",
"oid",
".",
"get_next_url",
"(",
")",
")",
"if",
"request",
".",
"method",
"==",
"'POST'"... | Does the login via OpenID. Has to call into `oid.try_login`
to start the OpenID machinery. | [
"Does",
"the",
"login",
"via",
"OpenID",
".",
"Has",
"to",
"call",
"into",
"oid",
".",
"try_login",
"to",
"start",
"the",
"OpenID",
"machinery",
"."
] | python | train |
Microsoft/LightGBM | helpers/parameter_generator.py | https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L12-L77 | def get_parameter_infos(config_hpp):
"""Parse config header file.
Parameters
----------
config_hpp : string
Path to the config header file.
Returns
-------
infos : tuple
Tuple with names and content of sections.
"""
is_inparameter = False
parameter_group = None
... | [
"def",
"get_parameter_infos",
"(",
"config_hpp",
")",
":",
"is_inparameter",
"=",
"False",
"parameter_group",
"=",
"None",
"cur_key",
"=",
"None",
"cur_info",
"=",
"{",
"}",
"keys",
"=",
"[",
"]",
"member_infos",
"=",
"[",
"]",
"with",
"open",
"(",
"config... | Parse config header file.
Parameters
----------
config_hpp : string
Path to the config header file.
Returns
-------
infos : tuple
Tuple with names and content of sections. | [
"Parse",
"config",
"header",
"file",
"."
] | python | train |
openstack/monasca-common | monasca_common/kafka_lib/conn.py | https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/kafka_lib/conn.py#L199-L217 | def close(self):
"""
Shutdown and close the connection socket
"""
log.debug("Closing socket connection for %s:%d" % (self.host, self.port))
if self._sock:
# Call shutdown to be a good TCP client
# But expect an error if the socket has already been
... | [
"def",
"close",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Closing socket connection for %s:%d\"",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
")",
"if",
"self",
".",
"_sock",
":",
"# Call shutdown to be a good TCP client",
"# But ex... | Shutdown and close the connection socket | [
"Shutdown",
"and",
"close",
"the",
"connection",
"socket"
] | python | train |
DLR-RM/RAFCON | source/rafcon/core/states/container_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1583-L1590 | def add_default_values_of_scoped_variables_to_scoped_data(self):
"""Add the scoped variables default values to the scoped_data dictionary
"""
for key, scoped_var in self.scoped_variables.items():
self.scoped_data[str(scoped_var.data_port_id) + self.state_id] = \
Scop... | [
"def",
"add_default_values_of_scoped_variables_to_scoped_data",
"(",
"self",
")",
":",
"for",
"key",
",",
"scoped_var",
"in",
"self",
".",
"scoped_variables",
".",
"items",
"(",
")",
":",
"self",
".",
"scoped_data",
"[",
"str",
"(",
"scoped_var",
".",
"data_port... | Add the scoped variables default values to the scoped_data dictionary | [
"Add",
"the",
"scoped",
"variables",
"default",
"values",
"to",
"the",
"scoped_data",
"dictionary"
] | python | train |
niolabs/python-xbee | examples/alarm.py | https://github.com/niolabs/python-xbee/blob/b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7/examples/alarm.py#L122-L132 | def _set_LED(self, status):
"""
_set_LED: boolean -> None
Sets the status of the remote LED
"""
# DIO pin 1 (LED), active low
self.hw.remote_at(
dest_addr=self.remote_addr,
command='D1',
parameter='\x04' if status else '\x05') | [
"def",
"_set_LED",
"(",
"self",
",",
"status",
")",
":",
"# DIO pin 1 (LED), active low",
"self",
".",
"hw",
".",
"remote_at",
"(",
"dest_addr",
"=",
"self",
".",
"remote_addr",
",",
"command",
"=",
"'D1'",
",",
"parameter",
"=",
"'\\x04'",
"if",
"status",
... | _set_LED: boolean -> None
Sets the status of the remote LED | [
"_set_LED",
":",
"boolean",
"-",
">",
"None"
] | python | train |
rosenbrockc/ci | pyci/server.py | https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L540-L565 | def fields_general(self, event):
"""Appends any additional fields to the common ones and returns the fields
dictionary.
"""
result = self._fields_common()
basic = {
"__test_html__": self.repo.testing.html(False),
"__test_text__": self.repo.testing.text(Fal... | [
"def",
"fields_general",
"(",
"self",
",",
"event",
")",
":",
"result",
"=",
"self",
".",
"_fields_common",
"(",
")",
"basic",
"=",
"{",
"\"__test_html__\"",
":",
"self",
".",
"repo",
".",
"testing",
".",
"html",
"(",
"False",
")",
",",
"\"__test_text__\... | Appends any additional fields to the common ones and returns the fields
dictionary. | [
"Appends",
"any",
"additional",
"fields",
"to",
"the",
"common",
"ones",
"and",
"returns",
"the",
"fields",
"dictionary",
"."
] | python | train |
Geotab/mygeotab-python | mygeotab/api.py | https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L126-L144 | def get(self, type_name, **parameters):
"""Gets entities using the API. Shortcut for using call() with the 'Get' method.
:param type_name: The type of entity.
:type type_name: str
:param parameters: Additional parameters to send.
:raise MyGeotabException: Raises when an exceptio... | [
"def",
"get",
"(",
"self",
",",
"type_name",
",",
"*",
"*",
"parameters",
")",
":",
"if",
"parameters",
":",
"results_limit",
"=",
"parameters",
".",
"get",
"(",
"'resultsLimit'",
",",
"None",
")",
"if",
"results_limit",
"is",
"not",
"None",
":",
"del",
... | Gets entities using the API. Shortcut for using call() with the 'Get' method.
:param type_name: The type of entity.
:type type_name: str
:param parameters: Additional parameters to send.
:raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
:raise Tim... | [
"Gets",
"entities",
"using",
"the",
"API",
".",
"Shortcut",
"for",
"using",
"call",
"()",
"with",
"the",
"Get",
"method",
"."
] | python | train |
ronhanson/python-tbx | tbx/bytes.py | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L180-L193 | def decode_ber(ber):
"""
Decodes a ber length byte array into an integer
return: (length, bytes_read) - a tuple of values
"""
ber = bytearray(ber)
length = ber[0]
bytes_read = 1
if length > 127:
bytes_read += length & 127 # Strip off the high bit
length = 0
for i ... | [
"def",
"decode_ber",
"(",
"ber",
")",
":",
"ber",
"=",
"bytearray",
"(",
"ber",
")",
"length",
"=",
"ber",
"[",
"0",
"]",
"bytes_read",
"=",
"1",
"if",
"length",
">",
"127",
":",
"bytes_read",
"+=",
"length",
"&",
"127",
"# Strip off the high bit",
"le... | Decodes a ber length byte array into an integer
return: (length, bytes_read) - a tuple of values | [
"Decodes",
"a",
"ber",
"length",
"byte",
"array",
"into",
"an",
"integer",
"return",
":",
"(",
"length",
"bytes_read",
")",
"-",
"a",
"tuple",
"of",
"values"
] | python | train |
troeger/opensubmit | web/opensubmit/models/submission.py | https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/models/submission.py#L361-L420 | def can_modify(self, user=None):
"""Determines whether the submission can be modified.
Returns a boolean value.
The 'user' parameter is optional and additionally checks whether
the given user is authorized to perform these actions.
This function checks the submission states and ... | [
"def",
"can_modify",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"# The user must be authorized to commit these actions.",
"if",
"user",
"and",
"not",
"self",
".",
"user_can_modify",
"(",
"user",
")",
":",
"#self.log('DEBUG', \"Submission cannot be modified, user is ... | Determines whether the submission can be modified.
Returns a boolean value.
The 'user' parameter is optional and additionally checks whether
the given user is authorized to perform these actions.
This function checks the submission states and assignment deadlines. | [
"Determines",
"whether",
"the",
"submission",
"can",
"be",
"modified",
".",
"Returns",
"a",
"boolean",
"value",
".",
"The",
"user",
"parameter",
"is",
"optional",
"and",
"additionally",
"checks",
"whether",
"the",
"given",
"user",
"is",
"authorized",
"to",
"pe... | python | train |
gaqzi/gocd-cli | gocd_cli/utils.py | https://github.com/gaqzi/gocd-cli/blob/ca8df8ec2274fdc69bce0619aa3794463c4f5a6f/gocd_cli/utils.py#L62-L96 | def format_arguments(*args):
"""
Converts a list of arguments from the command line into a list of
positional arguments and a dictionary of keyword arguments.
Handled formats for keyword arguments are:
* --argument=value
* --argument value
Args:
*args (list): a list of arguments
... | [
"def",
"format_arguments",
"(",
"*",
"args",
")",
":",
"positional_args",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"split_key",
"=",
"None",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
".",
"startswith",
"(",
"'--'",
")",
":",
"arg",
"=",
"arg",
"... | Converts a list of arguments from the command line into a list of
positional arguments and a dictionary of keyword arguments.
Handled formats for keyword arguments are:
* --argument=value
* --argument value
Args:
*args (list): a list of arguments
Returns:
([positional_args], {kwar... | [
"Converts",
"a",
"list",
"of",
"arguments",
"from",
"the",
"command",
"line",
"into",
"a",
"list",
"of",
"positional",
"arguments",
"and",
"a",
"dictionary",
"of",
"keyword",
"arguments",
"."
] | python | train |
odlgroup/odl | odl/space/entry_points.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/entry_points.py#L56-L84 | def tensor_space_impl(impl):
"""Tensor space class corresponding to the given impl name.
Parameters
----------
impl : str
Name of the implementation, see `tensor_space_impl_names` for
the full list.
Returns
-------
tensor_space_impl : type
Class inheriting from `Ten... | [
"def",
"tensor_space_impl",
"(",
"impl",
")",
":",
"if",
"impl",
"!=",
"'numpy'",
":",
"# Shortcut to improve \"import odl\" times since most users do not use",
"# non-numpy backends",
"_initialize_if_needed",
"(",
")",
"try",
":",
"return",
"TENSOR_SPACE_IMPLS",
"[",
"impl... | Tensor space class corresponding to the given impl name.
Parameters
----------
impl : str
Name of the implementation, see `tensor_space_impl_names` for
the full list.
Returns
-------
tensor_space_impl : type
Class inheriting from `TensorSpace`.
Raises
------
... | [
"Tensor",
"space",
"class",
"corresponding",
"to",
"the",
"given",
"impl",
"name",
"."
] | python | train |
Stanford-Online/xblock-image-modal | imagemodal/views.py | https://github.com/Stanford-Online/xblock-image-modal/blob/bd05f99a830a44f8d1a0e6e137e507b8ff8ff028/imagemodal/views.py#L27-L53 | def student_view(self, context=None):
"""
Build the fragment for the default student view
"""
context = context or {}
context.update({
'display_name': self.display_name,
'image_url': self.image_url,
'thumbnail_url': self.thumbnail_url or self.i... | [
"def",
"student_view",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"context",
"or",
"{",
"}",
"context",
".",
"update",
"(",
"{",
"'display_name'",
":",
"self",
".",
"display_name",
",",
"'image_url'",
":",
"self",
".",
"image_url... | Build the fragment for the default student view | [
"Build",
"the",
"fragment",
"for",
"the",
"default",
"student",
"view"
] | python | train |
instaloader/instaloader | instaloader/instaloadercontext.py | https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/instaloadercontext.py#L484-L493 | def write_raw(self, resp: Union[bytes, requests.Response], filename: str) -> None:
"""Write raw response data into a file.
.. versionadded:: 4.2.1"""
self.log(filename, end=' ', flush=True)
with open(filename, 'wb') as file:
if isinstance(resp, requests.Response):
... | [
"def",
"write_raw",
"(",
"self",
",",
"resp",
":",
"Union",
"[",
"bytes",
",",
"requests",
".",
"Response",
"]",
",",
"filename",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"log",
"(",
"filename",
",",
"end",
"=",
"' '",
",",
"flush",
"=",
... | Write raw response data into a file.
.. versionadded:: 4.2.1 | [
"Write",
"raw",
"response",
"data",
"into",
"a",
"file",
"."
] | python | train |
getfleety/coralillo | coralillo/hashing.py | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/hashing.py#L49-L68 | def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first f... | [
"def",
"force_bytes",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"# Handle the common case first for performance reasons.",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"if",
... | Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects. | [
"Similar",
"to",
"smart_bytes",
"except",
"that",
"lazy",
"instances",
"are",
"resolved",
"to",
"strings",
"rather",
"than",
"kept",
"as",
"lazy",
"objects",
".",
"If",
"strings_only",
"is",
"True",
"don",
"t",
"convert",
"(",
"some",
")",
"non",
"-",
"str... | python | train |
mortada/fredapi | fredapi/fred.py | https://github.com/mortada/fredapi/blob/d3ca79efccb9525f2752a0d6da90e793e87c3fd8/fredapi/fred.py#L250-L272 | def get_series_vintage_dates(self, series_id):
"""
Get a list of vintage dates for a series. Vintage dates are the dates in history when a
series' data values were revised or new data values were released.
Parameters
----------
series_id : str
Fred series id ... | [
"def",
"get_series_vintage_dates",
"(",
"self",
",",
"series_id",
")",
":",
"url",
"=",
"\"%s/series/vintagedates?series_id=%s\"",
"%",
"(",
"self",
".",
"root_url",
",",
"series_id",
")",
"root",
"=",
"self",
".",
"__fetch_data",
"(",
"url",
")",
"if",
"root"... | Get a list of vintage dates for a series. Vintage dates are the dates in history when a
series' data values were revised or new data values were released.
Parameters
----------
series_id : str
Fred series id such as 'CPIAUCSL'
Returns
-------
dates :... | [
"Get",
"a",
"list",
"of",
"vintage",
"dates",
"for",
"a",
"series",
".",
"Vintage",
"dates",
"are",
"the",
"dates",
"in",
"history",
"when",
"a",
"series",
"data",
"values",
"were",
"revised",
"or",
"new",
"data",
"values",
"were",
"released",
"."
] | python | train |
zhanglab/psamm | psamm/lpsolver/glpk.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/lpsolver/glpk.py#L407-L414 | def status(self):
"""Return string indicating the error encountered on failure."""
self._check_valid()
if self._ret_val == swiglpk.GLP_ENOPFS:
return 'No primal feasible solution'
elif self._ret_val == swiglpk.GLP_ENODFS:
return 'No dual feasible solution'
... | [
"def",
"status",
"(",
"self",
")",
":",
"self",
".",
"_check_valid",
"(",
")",
"if",
"self",
".",
"_ret_val",
"==",
"swiglpk",
".",
"GLP_ENOPFS",
":",
"return",
"'No primal feasible solution'",
"elif",
"self",
".",
"_ret_val",
"==",
"swiglpk",
".",
"GLP_ENOD... | Return string indicating the error encountered on failure. | [
"Return",
"string",
"indicating",
"the",
"error",
"encountered",
"on",
"failure",
"."
] | python | train |
apache/airflow | airflow/contrib/sensors/aws_glue_catalog_partition_sensor.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/sensors/aws_glue_catalog_partition_sensor.py#L83-L93 | def get_hook(self):
"""
Gets the AwsGlueCatalogHook
"""
if not hasattr(self, 'hook'):
from airflow.contrib.hooks.aws_glue_catalog_hook import AwsGlueCatalogHook
self.hook = AwsGlueCatalogHook(
aws_conn_id=self.aws_conn_id,
region_na... | [
"def",
"get_hook",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'hook'",
")",
":",
"from",
"airflow",
".",
"contrib",
".",
"hooks",
".",
"aws_glue_catalog_hook",
"import",
"AwsGlueCatalogHook",
"self",
".",
"hook",
"=",
"AwsGlueCatalogHo... | Gets the AwsGlueCatalogHook | [
"Gets",
"the",
"AwsGlueCatalogHook"
] | python | test |
lincolnloop/django-dynamic-raw-id | dynamic_raw_id/filters.py | https://github.com/lincolnloop/django-dynamic-raw-id/blob/4bf234f4a9d99daf44141205c0948222442f4957/dynamic_raw_id/filters.py#L57-L65 | def queryset(self, request, queryset):
"""Filter queryset using params from the form."""
if self.form.is_valid():
# get no null params
filter_params = dict(
filter(lambda x: bool(x[1]), self.form.cleaned_data.items())
)
return queryset.filt... | [
"def",
"queryset",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"if",
"self",
".",
"form",
".",
"is_valid",
"(",
")",
":",
"# get no null params",
"filter_params",
"=",
"dict",
"(",
"filter",
"(",
"lambda",
"x",
":",
"bool",
"(",
"x",
"[",
... | Filter queryset using params from the form. | [
"Filter",
"queryset",
"using",
"params",
"from",
"the",
"form",
"."
] | python | train |
quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L110-L119 | def execution_order(self, refcounts):
"""
Return a topologically-sorted iterator over the terms in ``self`` which
need to be computed.
"""
return iter(nx.topological_sort(
self.graph.subgraph(
{term for term, refcount in refcounts.items() if refcount >... | [
"def",
"execution_order",
"(",
"self",
",",
"refcounts",
")",
":",
"return",
"iter",
"(",
"nx",
".",
"topological_sort",
"(",
"self",
".",
"graph",
".",
"subgraph",
"(",
"{",
"term",
"for",
"term",
",",
"refcount",
"in",
"refcounts",
".",
"items",
"(",
... | Return a topologically-sorted iterator over the terms in ``self`` which
need to be computed. | [
"Return",
"a",
"topologically",
"-",
"sorted",
"iterator",
"over",
"the",
"terms",
"in",
"self",
"which",
"need",
"to",
"be",
"computed",
"."
] | python | train |
pywbem/pywbem | attic/cimxml_parse.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cimxml_parse.py#L85-L88 | def _is_end(event, node, tagName): # pylint: disable=invalid-name
"""Return true if (event, node) is an end event for tagname."""
return event == pulldom.END_ELEMENT and node.tagName == tagName | [
"def",
"_is_end",
"(",
"event",
",",
"node",
",",
"tagName",
")",
":",
"# pylint: disable=invalid-name",
"return",
"event",
"==",
"pulldom",
".",
"END_ELEMENT",
"and",
"node",
".",
"tagName",
"==",
"tagName"
] | Return true if (event, node) is an end event for tagname. | [
"Return",
"true",
"if",
"(",
"event",
"node",
")",
"is",
"an",
"end",
"event",
"for",
"tagname",
"."
] | python | train |
aboSamoor/polyglot | polyglot/downloader.py | https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/downloader.py#L982-L992 | def supported_tasks(self, lang=None):
"""Languages that are covered by a specific task.
Args:
lang (string): Language code name.
"""
if lang:
collection = self.get_collection(lang=lang)
return [x.id.split('.')[0] for x in collection.packages]
else:
return [x.name.split()[0] ... | [
"def",
"supported_tasks",
"(",
"self",
",",
"lang",
"=",
"None",
")",
":",
"if",
"lang",
":",
"collection",
"=",
"self",
".",
"get_collection",
"(",
"lang",
"=",
"lang",
")",
"return",
"[",
"x",
".",
"id",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
... | Languages that are covered by a specific task.
Args:
lang (string): Language code name. | [
"Languages",
"that",
"are",
"covered",
"by",
"a",
"specific",
"task",
"."
] | python | train |
markuskiller/textblob-de | textblob_de/ext/_pattern/text/__init__.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L1300-L1366 | def find_keywords(string, parser, top=10, frequency={}, **kwargs):
""" Returns a sorted list of keywords in the given string.
The given parser (e.g., pattern.en.parser) is used to identify noun phrases.
The given frequency dictionary can be a reference corpus,
with relative document frequenc... | [
"def",
"find_keywords",
"(",
"string",
",",
"parser",
",",
"top",
"=",
"10",
",",
"frequency",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"lemmata",
"=",
"kwargs",
".",
"pop",
"(",
"\"lemmata\"",
",",
"kwargs",
".",
"pop",
"(",
"\"stem\"",
"... | Returns a sorted list of keywords in the given string.
The given parser (e.g., pattern.en.parser) is used to identify noun phrases.
The given frequency dictionary can be a reference corpus,
with relative document frequency (df, 0.0-1.0) for each lemma,
e.g., {"the": 0.8, "cat": 0.1, ...... | [
"Returns",
"a",
"sorted",
"list",
"of",
"keywords",
"in",
"the",
"given",
"string",
".",
"The",
"given",
"parser",
"(",
"e",
".",
"g",
".",
"pattern",
".",
"en",
".",
"parser",
")",
"is",
"used",
"to",
"identify",
"noun",
"phrases",
".",
"The",
"give... | python | train |
llazzaro/analyzerstrategies | analyzerstrategies/zscoreMomentumPortfolioStrategy.py | https://github.com/llazzaro/analyzerstrategies/blob/3c647802f582bf2f06c6793f282bee0d26514cd6/analyzerstrategies/zscoreMomentumPortfolioStrategy.py#L85-L99 | def __placeBuyOrder(self, tick):
''' place buy order'''
cash=self.__getCashToBuyStock()
if cash == 0:
return
share=math.floor(cash / float(tick.close))
order=Order(accountId=self.__strategy.accountId,
action=Action.BUY,
... | [
"def",
"__placeBuyOrder",
"(",
"self",
",",
"tick",
")",
":",
"cash",
"=",
"self",
".",
"__getCashToBuyStock",
"(",
")",
"if",
"cash",
"==",
"0",
":",
"return",
"share",
"=",
"math",
".",
"floor",
"(",
"cash",
"/",
"float",
"(",
"tick",
".",
"close",... | place buy order | [
"place",
"buy",
"order"
] | python | train |
HazyResearch/fonduer | src/fonduer/candidates/candidates.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/candidates.py#L131-L140 | def clear_all(self, split):
"""Delete ALL Candidates from given split the database.
:param split: Which split to clear.
:type split: int
"""
logger.info("Clearing ALL Candidates.")
self.session.query(Candidate).filter(Candidate.split == split).delete(
synchro... | [
"def",
"clear_all",
"(",
"self",
",",
"split",
")",
":",
"logger",
".",
"info",
"(",
"\"Clearing ALL Candidates.\"",
")",
"self",
".",
"session",
".",
"query",
"(",
"Candidate",
")",
".",
"filter",
"(",
"Candidate",
".",
"split",
"==",
"split",
")",
".",... | Delete ALL Candidates from given split the database.
:param split: Which split to clear.
:type split: int | [
"Delete",
"ALL",
"Candidates",
"from",
"given",
"split",
"the",
"database",
"."
] | python | train |
softlayer/softlayer-python | SoftLayer/CLI/virt/power.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L88-L99 | def pause(env, identifier):
"""Pauses an active virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm('This will pause the VS with id %s. Continue?'
... | [
"def",
"pause",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
... | Pauses an active virtual server. | [
"Pauses",
"an",
"active",
"virtual",
"server",
"."
] | python | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L987-L1012 | def _parseSelectorPseudo(self, src, selector):
"""pseudo
: ':' [ IDENT | function ]
;
"""
ctxsrc = src
if not src.startswith(':'):
raise self.ParseError('Selector Pseudo \':\' not found', src, ctxsrc)
src = re.search('^:{1,2}(.*)', src, re.M | re.S).gr... | [
"def",
"_parseSelectorPseudo",
"(",
"self",
",",
"src",
",",
"selector",
")",
":",
"ctxsrc",
"=",
"src",
"if",
"not",
"src",
".",
"startswith",
"(",
"':'",
")",
":",
"raise",
"self",
".",
"ParseError",
"(",
"'Selector Pseudo \\':\\' not found'",
",",
"src",
... | pseudo
: ':' [ IDENT | function ]
; | [
"pseudo",
":",
":",
"[",
"IDENT",
"|",
"function",
"]",
";"
] | python | train |
tgbugs/pyontutils | nifstd/nifstd_tools/ilx_utils.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/nifstd/nifstd_tools/ilx_utils.py#L154-L165 | def decodeIlxResp(resp):
""" We need this until we can get json back directly and this is SUPER nasty"""
lines = [_ for _ in resp.text.split('\n') if _] # strip empties
if 'successfull' in lines[0]:
return [(_.split('"')[1],
ilxIdFix(_.split(': ')[-1]))
for _ in li... | [
"def",
"decodeIlxResp",
"(",
"resp",
")",
":",
"lines",
"=",
"[",
"_",
"for",
"_",
"in",
"resp",
".",
"text",
".",
"split",
"(",
"'\\n'",
")",
"if",
"_",
"]",
"# strip empties",
"if",
"'successfull'",
"in",
"lines",
"[",
"0",
"]",
":",
"return",
"[... | We need this until we can get json back directly and this is SUPER nasty | [
"We",
"need",
"this",
"until",
"we",
"can",
"get",
"json",
"back",
"directly",
"and",
"this",
"is",
"SUPER",
"nasty"
] | python | train |
KE-works/pykechain | pykechain/models/part.py | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/part.py#L505-L556 | def update(self, name=None, update_dict=None, bulk=True, **kwargs):
"""
Edit part name and property values in one go.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve per... | [
"def",
"update",
"(",
"self",
",",
"name",
"=",
"None",
",",
"update_dict",
"=",
"None",
",",
"bulk",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# dict(name=name, properties=json.dumps(update_dict))) with property ids:value",
"action",
"=",
"'bulk_update_prope... | Edit part name and property values in one go.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend... | [
"Edit",
"part",
"name",
"and",
"property",
"values",
"in",
"one",
"go",
"."
] | python | train |
agoragames/leaderboard-python | leaderboard/leaderboard.py | https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L884-L918 | def members_from_rank_range_in(
self, leaderboard_name, starting_rank, ending_rank, **options):
'''
Retrieve members from the named leaderboard within a given rank range.
@param leaderboard_name [String] Name of the leaderboard.
@param starting_rank [int] Starting rank (incl... | [
"def",
"members_from_rank_range_in",
"(",
"self",
",",
"leaderboard_name",
",",
"starting_rank",
",",
"ending_rank",
",",
"*",
"*",
"options",
")",
":",
"starting_rank",
"-=",
"1",
"if",
"starting_rank",
"<",
"0",
":",
"starting_rank",
"=",
"0",
"ending_rank",
... | Retrieve members from the named leaderboard within a given rank range.
@param leaderboard_name [String] Name of the leaderboard.
@param starting_rank [int] Starting rank (inclusive).
@param ending_rank [int] Ending rank (inclusive).
@param options [Hash] Options to be used when retrievi... | [
"Retrieve",
"members",
"from",
"the",
"named",
"leaderboard",
"within",
"a",
"given",
"rank",
"range",
"."
] | python | train |
lordmauve/lepton | examples/games/bonk/game.py | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L53-L56 | def bind_objects(self, *objects):
"""Bind one or more objects"""
self.control.bind_keys(objects)
self.objects += objects | [
"def",
"bind_objects",
"(",
"self",
",",
"*",
"objects",
")",
":",
"self",
".",
"control",
".",
"bind_keys",
"(",
"objects",
")",
"self",
".",
"objects",
"+=",
"objects"
] | Bind one or more objects | [
"Bind",
"one",
"or",
"more",
"objects"
] | python | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L95-L144 | def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[]
) -> List[OutputRecord]:
"""
Upload media to birdsite,
and send status and media,
and captions if present.
:param text: tweet text.
... | [
"def",
"send_with_media",
"(",
"self",
",",
"*",
",",
"text",
":",
"str",
",",
"files",
":",
"List",
"[",
"str",
"]",
",",
"captions",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
")",
"->",
"List",
"[",
"OutputRecord",
"]",
":",
"# upload media",
... | Upload media to birdsite,
and send status and media,
and captions if present.
:param text: tweet text.
:param files: list of files to upload with post.
:param captions: list of captions to include as alt-text with files.
:returns: list of output records,
each... | [
"Upload",
"media",
"to",
"birdsite",
"and",
"send",
"status",
"and",
"media",
"and",
"captions",
"if",
"present",
"."
] | python | train |
googleapis/google-auth-library-python | google/auth/jwt.py | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/jwt.py#L730-L748 | def before_request(self, request, method, url, headers):
"""Performs credential-specific before request logic.
Args:
request (Any): Unused. JWT credentials do not need to make an
HTTP request to refresh.
method (str): The request's HTTP method.
url (s... | [
"def",
"before_request",
"(",
"self",
",",
"request",
",",
"method",
",",
"url",
",",
"headers",
")",
":",
"# pylint: disable=unused-argument",
"# (pylint doesn't correctly recognize overridden methods.)",
"parts",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"u... | Performs credential-specific before request logic.
Args:
request (Any): Unused. JWT credentials do not need to make an
HTTP request to refresh.
method (str): The request's HTTP method.
url (str): The request's URI. This is used as the audience claim
... | [
"Performs",
"credential",
"-",
"specific",
"before",
"request",
"logic",
"."
] | python | train |
HdrHistogram/HdrHistogram_py | hdrh/histogram.py | https://github.com/HdrHistogram/HdrHistogram_py/blob/cb99981b0564a62e1aa02bd764efa6445923f8f7/hdrh/histogram.py#L287-L326 | def get_percentile_to_value_dict(self, percentile_list):
'''A faster alternative to query values for a list of percentiles.
Args:
percentile_list: a list of percentiles in any order, dups will be ignored
each element in the list must be a float value in [0.0 .. 100.0]
Re... | [
"def",
"get_percentile_to_value_dict",
"(",
"self",
",",
"percentile_list",
")",
":",
"result",
"=",
"{",
"}",
"total",
"=",
"0",
"percentile_list_index",
"=",
"0",
"count_at_percentile",
"=",
"0",
"# remove dups and sort",
"percentile_list",
"=",
"list",
"(",
"se... | A faster alternative to query values for a list of percentiles.
Args:
percentile_list: a list of percentiles in any order, dups will be ignored
each element in the list must be a float value in [0.0 .. 100.0]
Returns:
a dict of percentile values indexed by the percen... | [
"A",
"faster",
"alternative",
"to",
"query",
"values",
"for",
"a",
"list",
"of",
"percentiles",
"."
] | python | train |
crypto101/arthur | arthur/auth.py | https://github.com/crypto101/arthur/blob/c32e693fb5af17eac010e3b20f7653ed6e11eb6a/arthur/auth.py#L52-L66 | def _getContextFactory(path, workbench):
"""Get a context factory.
If the client already has a credentials at path, use them.
Otherwise, generate them at path. Notifications are reported to
the given workbench.
"""
try:
return succeed(getContextFactory(path))
except IOError:
... | [
"def",
"_getContextFactory",
"(",
"path",
",",
"workbench",
")",
":",
"try",
":",
"return",
"succeed",
"(",
"getContextFactory",
"(",
"path",
")",
")",
"except",
"IOError",
":",
"d",
"=",
"prompt",
"(",
"workbench",
",",
"u\"E-mail entry\"",
",",
"u\"Enter e... | Get a context factory.
If the client already has a credentials at path, use them.
Otherwise, generate them at path. Notifications are reported to
the given workbench. | [
"Get",
"a",
"context",
"factory",
"."
] | python | train |
jesford/cluster-lensing | clusterlensing/clusters.py | https://github.com/jesford/cluster-lensing/blob/2815c1bb07d904ca91a80dae3f52090016768072/clusterlensing/clusters.py#L502-L562 | def calc_nfw(self, rbins, offsets=None, numTh=200, numRoff=200,
numRinner=20, factorRouter=3):
"""Calculates Sigma and DeltaSigma profiles.
Generates the surface mass density (sigma_nfw attribute of parent
object) and differential surface mass density (deltasigma_nfw
at... | [
"def",
"calc_nfw",
"(",
"self",
",",
"rbins",
",",
"offsets",
"=",
"None",
",",
"numTh",
"=",
"200",
",",
"numRoff",
"=",
"200",
",",
"numRinner",
"=",
"20",
",",
"factorRouter",
"=",
"3",
")",
":",
"if",
"offsets",
"is",
"None",
":",
"self",
".",
... | Calculates Sigma and DeltaSigma profiles.
Generates the surface mass density (sigma_nfw attribute of parent
object) and differential surface mass density (deltasigma_nfw
attribute of parent object) profiles of each cluster, assuming a
spherical NFW model. Optionally includes the effect ... | [
"Calculates",
"Sigma",
"and",
"DeltaSigma",
"profiles",
"."
] | python | train |
Cymmetria/honeycomb | honeycomb/servicemanager/base_service.py | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/base_service.py#L212-L226 | def on_server_start(self):
"""Service run loop function.
Run the desired docker container with parameters and start parsing the monitored file for alerts.
"""
self._container = self._docker_client.containers.run(self.docker_image_name, detach=True, **self.docker_params)
self.sig... | [
"def",
"on_server_start",
"(",
"self",
")",
":",
"self",
".",
"_container",
"=",
"self",
".",
"_docker_client",
".",
"containers",
".",
"run",
"(",
"self",
".",
"docker_image_name",
",",
"detach",
"=",
"True",
",",
"*",
"*",
"self",
".",
"docker_params",
... | Service run loop function.
Run the desired docker container with parameters and start parsing the monitored file for alerts. | [
"Service",
"run",
"loop",
"function",
"."
] | python | train |
Hackerfleet/hfos | hfos/logger.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/logger.py#L113-L117 | def set_logfile(path, instance):
"""Specify logfile path"""
global logfile
logfile = os.path.normpath(path) + '/hfos.' + instance + '.log' | [
"def",
"set_logfile",
"(",
"path",
",",
"instance",
")",
":",
"global",
"logfile",
"logfile",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"+",
"'/hfos.'",
"+",
"instance",
"+",
"'.log'"
] | Specify logfile path | [
"Specify",
"logfile",
"path"
] | python | train |
soravux/scoop | scoop/discovery/minusconf.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/discovery/minusconf.py#L623-L688 | def _compat_inet_pton(family, addr):
""" socket.inet_pton for platforms that don't have it """
if family == socket.AF_INET:
# inet_aton accepts some strange forms, so we use our own
res = _compat_bytes('')
parts = addr.split('.')
if len(parts) != 4:
raise ValueError(... | [
"def",
"_compat_inet_pton",
"(",
"family",
",",
"addr",
")",
":",
"if",
"family",
"==",
"socket",
".",
"AF_INET",
":",
"# inet_aton accepts some strange forms, so we use our own",
"res",
"=",
"_compat_bytes",
"(",
"''",
")",
"parts",
"=",
"addr",
".",
"split",
"... | socket.inet_pton for platforms that don't have it | [
"socket",
".",
"inet_pton",
"for",
"platforms",
"that",
"don",
"t",
"have",
"it"
] | python | train |
Esri/ArcREST | src/arcresthelper/common.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L490-L525 | def find_replace(obj, find, replace):
""" Searches an object and performs a find and replace.
Args:
obj (object): The object to iterate and find/replace.
find (str): The string to search for.
replace (str): The string to replace with.
Returns:
object: The object with replace... | [
"def",
"find_replace",
"(",
"obj",
",",
"find",
",",
"replace",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{",
"find_replace",
"(",
"key",
",",
"find",
",",
"replace",
")",
":",
"find_replace",
"(",
"value... | Searches an object and performs a find and replace.
Args:
obj (object): The object to iterate and find/replace.
find (str): The string to search for.
replace (str): The string to replace with.
Returns:
object: The object with replaced strings. | [
"Searches",
"an",
"object",
"and",
"performs",
"a",
"find",
"and",
"replace",
"."
] | python | train |
pyca/pyopenssl | src/OpenSSL/crypto.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1310-L1321 | def gmtime_adj_notBefore(self, amount):
"""
Adjust the timestamp on which the certificate starts being valid.
:param amount: The number of seconds by which to adjust the timestamp.
:return: ``None``
"""
if not isinstance(amount, int):
raise TypeError("amount ... | [
"def",
"gmtime_adj_notBefore",
"(",
"self",
",",
"amount",
")",
":",
"if",
"not",
"isinstance",
"(",
"amount",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"amount must be an integer\"",
")",
"notBefore",
"=",
"_lib",
".",
"X509_get_notBefore",
"(",
"sel... | Adjust the timestamp on which the certificate starts being valid.
:param amount: The number of seconds by which to adjust the timestamp.
:return: ``None`` | [
"Adjust",
"the",
"timestamp",
"on",
"which",
"the",
"certificate",
"starts",
"being",
"valid",
"."
] | python | test |
bububa/pyTOP | pyTOP/logistics.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/logistics.py#L384-L396 | def send(self, tid, out_sid, company_code, session, sender_id=None, cancel_id=None, feature=None):
'''taobao.logistics.offline.send 自己联系物流(线下物流)发货
用户调用该接口可实现自己联系发货(线下物流),使用该接口发货,交易订单状态会直接变成卖家已发货。不支持货到付款、在线下单类型的订单。'''
request = TOPRequest('taobao.logistics.offline.send')
request[... | [
"def",
"send",
"(",
"self",
",",
"tid",
",",
"out_sid",
",",
"company_code",
",",
"session",
",",
"sender_id",
"=",
"None",
",",
"cancel_id",
"=",
"None",
",",
"feature",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.logistics.offline.... | taobao.logistics.offline.send 自己联系物流(线下物流)发货
用户调用该接口可实现自己联系发货(线下物流),使用该接口发货,交易订单状态会直接变成卖家已发货。不支持货到付款、在线下单类型的订单。 | [
"taobao",
".",
"logistics",
".",
"offline",
".",
"send",
"自己联系物流(线下物流)发货",
"用户调用该接口可实现自己联系发货(线下物流),使用该接口发货,交易订单状态会直接变成卖家已发货。不支持货到付款、在线下单类型的订单。"
] | python | train |
cedricbonhomme/Stegano | stegano/tools.py | https://github.com/cedricbonhomme/Stegano/blob/502e6303791d348e479290c22108551ba3be254f/stegano/tools.py#L83-L93 | def n_at_a_time(
items: List[int], n: int, fillvalue: str
) -> Iterator[Tuple[Union[int, str]]]:
"""Returns an iterator which groups n items at a time.
Any final partial tuple will be padded with the fillvalue
>>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X'))
[(1, 2), (3, 4), (5, 'X')]
"""
it ... | [
"def",
"n_at_a_time",
"(",
"items",
":",
"List",
"[",
"int",
"]",
",",
"n",
":",
"int",
",",
"fillvalue",
":",
"str",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"Union",
"[",
"int",
",",
"str",
"]",
"]",
"]",
":",
"it",
"=",
"iter",
"(",
"items"... | Returns an iterator which groups n items at a time.
Any final partial tuple will be padded with the fillvalue
>>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X'))
[(1, 2), (3, 4), (5, 'X')] | [
"Returns",
"an",
"iterator",
"which",
"groups",
"n",
"items",
"at",
"a",
"time",
".",
"Any",
"final",
"partial",
"tuple",
"will",
"be",
"padded",
"with",
"the",
"fillvalue"
] | python | train |
dhermes/bezier | src/bezier/_clipping.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L122-L179 | def _update_parameters(s_min, s_max, start0, end0, start1, end1):
"""Update clipped parameter range.
.. note::
This is a helper for :func:`clip_range`.
Does so by intersecting one of the two fat lines with an edge
of the convex hull of the distance polynomial of the curve being
clipped.
... | [
"def",
"_update_parameters",
"(",
"s_min",
",",
"s_max",
",",
"start0",
",",
"end0",
",",
"start1",
",",
"end1",
")",
":",
"s",
",",
"t",
",",
"success",
"=",
"_geometric_intersection",
".",
"segment_intersection",
"(",
"start0",
",",
"end0",
",",
"start1"... | Update clipped parameter range.
.. note::
This is a helper for :func:`clip_range`.
Does so by intersecting one of the two fat lines with an edge
of the convex hull of the distance polynomial of the curve being
clipped.
If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s`
... | [
"Update",
"clipped",
"parameter",
"range",
"."
] | python | train |
tweepy/tweepy | tweepy/api.py | https://github.com/tweepy/tweepy/blob/cc3894073905811c4d9fd816202f93454ed932da/tweepy/api.py#L619-L635 | def set_settings(self):
""" :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings
:allowed_param:'sleep_time_enabled', 'start_sleep_time',
'end_sleep_time', 'time_zone', 'trend_location_woeid',
'allow_... | [
"def",
"set_settings",
"(",
"self",
")",
":",
"return",
"bind_api",
"(",
"api",
"=",
"self",
",",
"path",
"=",
"'/account/settings.json'",
",",
"method",
"=",
"'POST'",
",",
"payload_type",
"=",
"'json'",
",",
"allowed_param",
"=",
"[",
"'sleep_time_enabled'",... | :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings
:allowed_param:'sleep_time_enabled', 'start_sleep_time',
'end_sleep_time', 'time_zone', 'trend_location_woeid',
'allow_contributor_request', 'lang' | [
":",
"reference",
":",
"https",
":",
"//",
"developer",
".",
"twitter",
".",
"com",
"/",
"en",
"/",
"docs",
"/",
"accounts",
"-",
"and",
"-",
"users",
"/",
"manage",
"-",
"account",
"-",
"settings",
"/",
"api",
"-",
"reference",
"/",
"post",
"-",
"... | python | train |
evhub/coconut | coconut/compiler/matching.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/matching.py#L177-L181 | def insert_def(self, index, def_item):
"""Inserts a def universally."""
self.defs.insert(index, def_item)
for other in self.others:
other.insert_def(index, def_item) | [
"def",
"insert_def",
"(",
"self",
",",
"index",
",",
"def_item",
")",
":",
"self",
".",
"defs",
".",
"insert",
"(",
"index",
",",
"def_item",
")",
"for",
"other",
"in",
"self",
".",
"others",
":",
"other",
".",
"insert_def",
"(",
"index",
",",
"def_i... | Inserts a def universally. | [
"Inserts",
"a",
"def",
"universally",
"."
] | python | train |
feifangit/dj-api-auth | djapiauth/forms.py | https://github.com/feifangit/dj-api-auth/blob/9d833134fc8a6e74bf8d9fe6c98598dd5061ea9b/djapiauth/forms.py#L7-L17 | def get_api_key_form(userfilter={}):
"""
userfileter: when binding api key with user, filter some users if necessary
"""
class APIKeyForm(ModelForm):
class Meta:
model = APIKeys
exclude = ("apitree",)
user = forms.ModelChoiceField(queryset=get_user_model().objects... | [
"def",
"get_api_key_form",
"(",
"userfilter",
"=",
"{",
"}",
")",
":",
"class",
"APIKeyForm",
"(",
"ModelForm",
")",
":",
"class",
"Meta",
":",
"model",
"=",
"APIKeys",
"exclude",
"=",
"(",
"\"apitree\"",
",",
")",
"user",
"=",
"forms",
".",
"ModelChoice... | userfileter: when binding api key with user, filter some users if necessary | [
"userfileter",
":",
"when",
"binding",
"api",
"key",
"with",
"user",
"filter",
"some",
"users",
"if",
"necessary"
] | python | test |
jab/bidict | bidict/_mut.py | https://github.com/jab/bidict/blob/1a1ba9758651aed9c4f58384eff006d2e2ad6835/bidict/_mut.py#L162-L171 | def putall(self, items, on_dup_key=RAISE, on_dup_val=RAISE, on_dup_kv=None):
"""
Like a bulk :meth:`put`.
If one of the given items causes an exception to be raised,
none of the items is inserted.
"""
if items:
on_dup = self._get_on_dup((on_dup_key, on_dup_va... | [
"def",
"putall",
"(",
"self",
",",
"items",
",",
"on_dup_key",
"=",
"RAISE",
",",
"on_dup_val",
"=",
"RAISE",
",",
"on_dup_kv",
"=",
"None",
")",
":",
"if",
"items",
":",
"on_dup",
"=",
"self",
".",
"_get_on_dup",
"(",
"(",
"on_dup_key",
",",
"on_dup_v... | Like a bulk :meth:`put`.
If one of the given items causes an exception to be raised,
none of the items is inserted. | [
"Like",
"a",
"bulk",
":",
"meth",
":",
"put",
"."
] | python | test |
carlthome/python-audio-effects | pysndfx/dsp.py | https://github.com/carlthome/python-audio-effects/blob/b2d85c166720c549c6ef3c382b561edd09229722/pysndfx/dsp.py#L226-L235 | def bend(self, bends, frame_rate=None, over_sample=None):
"""TODO Add docstring."""
self.command.append("bend")
if frame_rate is not None and isinstance(frame_rate, int):
self.command.append('-f %s' % frame_rate)
if over_sample is not None and isinstance(over_sample, int):
... | [
"def",
"bend",
"(",
"self",
",",
"bends",
",",
"frame_rate",
"=",
"None",
",",
"over_sample",
"=",
"None",
")",
":",
"self",
".",
"command",
".",
"append",
"(",
"\"bend\"",
")",
"if",
"frame_rate",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"frame_... | TODO Add docstring. | [
"TODO",
"Add",
"docstring",
"."
] | python | train |
JustinLovinger/optimal | optimal/algorithms/gsa.py | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L128-L193 | def _new_population_gsa(population, fitnesses, velocities, lower_bounds,
upper_bounds, grav_initial, grav_reduction_rate,
iteration, max_iterations):
"""Generate a new population as given by GSA algorithm.
In GSA paper, grav_initial is G_i
"""
# Update th... | [
"def",
"_new_population_gsa",
"(",
"population",
",",
"fitnesses",
",",
"velocities",
",",
"lower_bounds",
",",
"upper_bounds",
",",
"grav_initial",
",",
"grav_reduction_rate",
",",
"iteration",
",",
"max_iterations",
")",
":",
"# Update the gravitational constant, and th... | Generate a new population as given by GSA algorithm.
In GSA paper, grav_initial is G_i | [
"Generate",
"a",
"new",
"population",
"as",
"given",
"by",
"GSA",
"algorithm",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/interface/ethernet/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/interface/ethernet/__init__.py#L223-L246 | def _set_long_distance_isl(self, v, load=False):
"""
Setter method for long_distance_isl, mapped from YANG variable /interface/ethernet/long_distance_isl (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_long_distance_isl is considered as a private
method... | [
"def",
"_set_long_distance_isl",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",... | Setter method for long_distance_isl, mapped from YANG variable /interface/ethernet/long_distance_isl (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_long_distance_isl is considered as a private
method. Backends looking to populate this variable should
do so... | [
"Setter",
"method",
"for",
"long_distance_isl",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"ethernet",
"/",
"long_distance_isl",
"(",
"enumeration",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
... | python | train |
utiasSTARS/pykitti | pykitti/utils.py | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L61-L65 | def transform_from_rot_trans(R, t):
"""Transforation matrix from rotation matrix and translation vector."""
R = R.reshape(3, 3)
t = t.reshape(3, 1)
return np.vstack((np.hstack([R, t]), [0, 0, 0, 1])) | [
"def",
"transform_from_rot_trans",
"(",
"R",
",",
"t",
")",
":",
"R",
"=",
"R",
".",
"reshape",
"(",
"3",
",",
"3",
")",
"t",
"=",
"t",
".",
"reshape",
"(",
"3",
",",
"1",
")",
"return",
"np",
".",
"vstack",
"(",
"(",
"np",
".",
"hstack",
"("... | Transforation matrix from rotation matrix and translation vector. | [
"Transforation",
"matrix",
"from",
"rotation",
"matrix",
"and",
"translation",
"vector",
"."
] | python | train |
WebarchivCZ/WA-KAT | src/wa_kat/analyzers/language_detector.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/analyzers/language_detector.py#L49-L87 | def get_html_tag_lang_params(index_page):
"""
Parse lang and xml:lang parameters in the ``<html>`` tag.
See
https://www.w3.org/International/questions/qa-html-language-declarations
for details.
Args:
index_page (str): HTML content of the page you wisht to analyze.
Returns:
... | [
"def",
"get_html_tag_lang_params",
"(",
"index_page",
")",
":",
"dom",
"=",
"dhtmlparser",
".",
"parseString",
"(",
"index_page",
")",
"html_tag",
"=",
"dom",
".",
"find",
"(",
"\"html\"",
")",
"if",
"not",
"html_tag",
":",
"return",
"[",
"]",
"html_tag",
... | Parse lang and xml:lang parameters in the ``<html>`` tag.
See
https://www.w3.org/International/questions/qa-html-language-declarations
for details.
Args:
index_page (str): HTML content of the page you wisht to analyze.
Returns:
list: List of :class:`.SourceString` objects. | [
"Parse",
"lang",
"and",
"xml",
":",
"lang",
"parameters",
"in",
"the",
"<html",
">",
"tag",
"."
] | python | train |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CompositeCounters.py | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L79-L89 | def end_timing(self, name, elapsed):
"""
Ends measurement of execution elapsed time and updates specified counter.
:param name: a counter name
:param elapsed: execution elapsed time in milliseconds to update the counter.
"""
for counter in self._counters:
if... | [
"def",
"end_timing",
"(",
"self",
",",
"name",
",",
"elapsed",
")",
":",
"for",
"counter",
"in",
"self",
".",
"_counters",
":",
"if",
"isinstance",
"(",
"counter",
",",
"ITimingCallback",
")",
":",
"counter",
".",
"end_timing",
"(",
"name",
",",
"elapsed... | Ends measurement of execution elapsed time and updates specified counter.
:param name: a counter name
:param elapsed: execution elapsed time in milliseconds to update the counter. | [
"Ends",
"measurement",
"of",
"execution",
"elapsed",
"time",
"and",
"updates",
"specified",
"counter",
"."
] | python | train |
saltstack/salt | salt/modules/boto_cloudtrail.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudtrail.py#L298-L342 | def update(Name,
S3BucketName, S3KeyPrefix=None,
SnsTopicName=None,
IncludeGlobalServiceEvents=None,
IsMultiRegionTrail=None,
EnableLogFileValidation=None,
CloudWatchLogsLogGroupArn=None,
CloudWatchLogsRoleArn=None,
KmsKeyId=None,
... | [
"def",
"update",
"(",
"Name",
",",
"S3BucketName",
",",
"S3KeyPrefix",
"=",
"None",
",",
"SnsTopicName",
"=",
"None",
",",
"IncludeGlobalServiceEvents",
"=",
"None",
",",
"IsMultiRegionTrail",
"=",
"None",
",",
"EnableLogFileValidation",
"=",
"None",
",",
"Cloud... | Given a valid config, update a trail.
Returns {created: true} if the trail was created and returns
{created: False} if the trail was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.update my_trail my_bucket | [
"Given",
"a",
"valid",
"config",
"update",
"a",
"trail",
"."
] | python | train |
IdentityPython/pysaml2 | example/idp2/idp.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/idp2/idp.py#L273-L313 | def verify_request(self, query, binding):
"""
:param query: The SAML query, transport encoded
:param binding: Which binding the query came in over
"""
resp_args = {}
if not query:
logger.info("Missing QUERY")
resp = Unauthorized("Unknown user")
... | [
"def",
"verify_request",
"(",
"self",
",",
"query",
",",
"binding",
")",
":",
"resp_args",
"=",
"{",
"}",
"if",
"not",
"query",
":",
"logger",
".",
"info",
"(",
"\"Missing QUERY\"",
")",
"resp",
"=",
"Unauthorized",
"(",
"\"Unknown user\"",
")",
"return",
... | :param query: The SAML query, transport encoded
:param binding: Which binding the query came in over | [
":",
"param",
"query",
":",
"The",
"SAML",
"query",
"transport",
"encoded",
":",
"param",
"binding",
":",
"Which",
"binding",
"the",
"query",
"came",
"in",
"over"
] | python | train |
Azure/msrest-for-python | msrest/serialization.py | https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/serialization.py#L240-L270 | def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer):
"""Return a dict that can be JSONify using json.dump.
Advanced usage might optionaly use a callback as parameter:
.. code::python
def my_key_transformer(key, attr_desc, value):
return key... | [
"def",
"as_dict",
"(",
"self",
",",
"keep_readonly",
"=",
"True",
",",
"key_transformer",
"=",
"attribute_transformer",
")",
":",
"serializer",
"=",
"Serializer",
"(",
"self",
".",
"_infer_class_models",
"(",
")",
")",
"return",
"serializer",
".",
"_serialize",
... | Return a dict that can be JSONify using json.dump.
Advanced usage might optionaly use a callback as parameter:
.. code::python
def my_key_transformer(key, attr_desc, value):
return key
Key is the attribute name used in Python. Attr_desc
is a dict of metada... | [
"Return",
"a",
"dict",
"that",
"can",
"be",
"JSONify",
"using",
"json",
".",
"dump",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/controllers/utils/tree_view_controller.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L808-L828 | def update_selection_self_prior(self):
"""Tree view prior update of state machine selection"""
if self._do_selection_update:
return
self._do_selection_update = True
tree_selection, selected_model_list, sm_selection, sm_selected_model_set = self.get_selections()
if isi... | [
"def",
"update_selection_self_prior",
"(",
"self",
")",
":",
"if",
"self",
".",
"_do_selection_update",
":",
"return",
"self",
".",
"_do_selection_update",
"=",
"True",
"tree_selection",
",",
"selected_model_list",
",",
"sm_selection",
",",
"sm_selected_model_set",
"=... | Tree view prior update of state machine selection | [
"Tree",
"view",
"prior",
"update",
"of",
"state",
"machine",
"selection"
] | python | train |
genepattern/genepattern-python | gp/data.py | https://github.com/genepattern/genepattern-python/blob/9478ea65362b91c72a94f7300c3de8d710bebb71/gp/data.py#L263-L270 | def _bytes_to_str(lines):
"""
Convert all lines from byte string to unicode string, if necessary
"""
if len(lines) >= 1 and hasattr(lines[0], 'decode'):
return [line.decode('utf-8') for line in lines]
else:
return lines | [
"def",
"_bytes_to_str",
"(",
"lines",
")",
":",
"if",
"len",
"(",
"lines",
")",
">=",
"1",
"and",
"hasattr",
"(",
"lines",
"[",
"0",
"]",
",",
"'decode'",
")",
":",
"return",
"[",
"line",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"line",
"in",
"... | Convert all lines from byte string to unicode string, if necessary | [
"Convert",
"all",
"lines",
"from",
"byte",
"string",
"to",
"unicode",
"string",
"if",
"necessary"
] | python | train |
duniter/duniter-python-api | duniterpy/api/endpoint.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/endpoint.py#L492-L504 | def from_inline(cls: Type[ESSubscribtionEndpointType], inline: str) -> ESSubscribtionEndpointType:
"""
Return ESSubscribtionEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = ESSubscribtionEndpoint.re_inline.match(inline)
if m ... | [
"def",
"from_inline",
"(",
"cls",
":",
"Type",
"[",
"ESSubscribtionEndpointType",
"]",
",",
"inline",
":",
"str",
")",
"->",
"ESSubscribtionEndpointType",
":",
"m",
"=",
"ESSubscribtionEndpoint",
".",
"re_inline",
".",
"match",
"(",
"inline",
")",
"if",
"m",
... | Return ESSubscribtionEndpoint instance from endpoint string
:param inline: Endpoint string
:return: | [
"Return",
"ESSubscribtionEndpoint",
"instance",
"from",
"endpoint",
"string"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.