text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def JP(cpu, target):
"""
Jumps short if parity.
:param cpu: current CPU.
:param target: destination operand.
"""
cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.PF, target.read(), cpu.PC) | [
"def",
"JP",
"(",
"cpu",
",",
"target",
")",
":",
"cpu",
".",
"PC",
"=",
"Operators",
".",
"ITEBV",
"(",
"cpu",
".",
"address_bit_size",
",",
"cpu",
".",
"PF",
",",
"target",
".",
"read",
"(",
")",
",",
"cpu",
".",
"PC",
")"
] | 29 | 15.75 |
def create_file(self, path, fp, force=False, update=False):
"""Store a new file at `path` in this storage.
The contents of the file descriptor `fp` (opened in 'rb' mode)
will be uploaded to `path` which is the full path at
which to store the file.
To force overwrite of an exist... | [
"def",
"create_file",
"(",
"self",
",",
"path",
",",
"fp",
",",
"force",
"=",
"False",
",",
"update",
"=",
"False",
")",
":",
"if",
"'b'",
"not",
"in",
"fp",
".",
"mode",
":",
"raise",
"ValueError",
"(",
"\"File has to be opened in binary mode.\"",
")",
... | 45.282051 | 20.987179 |
def sort(self):
"""Sort the data so that x is monotonically increasing and contains
no duplicates.
"""
if 'wavelength' in self.rsr:
# Only one detector apparently:
self.rsr['wavelength'], self.rsr['response'] = \
sort_data(self.rsr['wavelength'], s... | [
"def",
"sort",
"(",
"self",
")",
":",
"if",
"'wavelength'",
"in",
"self",
".",
"rsr",
":",
"# Only one detector apparently:",
"self",
".",
"rsr",
"[",
"'wavelength'",
"]",
",",
"self",
".",
"rsr",
"[",
"'response'",
"]",
"=",
"sort_data",
"(",
"self",
".... | 45.285714 | 15.428571 |
def namedspace(typename, required_fields=(), optional_fields=(), mutable_fields=(),
default_values=frozendict(), default_value_factories=frozendict(),
return_none=False):
"""Builds a new class that encapsulates a namespace and provides
various ways to access it.
The typename argument is re... | [
"def",
"namedspace",
"(",
"typename",
",",
"required_fields",
"=",
"(",
")",
",",
"optional_fields",
"=",
"(",
")",
",",
"mutable_fields",
"=",
"(",
")",
",",
"default_values",
"=",
"frozendict",
"(",
")",
",",
"default_value_factories",
"=",
"frozendict",
"... | 36.528646 | 27.390625 |
def _validate_dependencies_met():
"""
Verifies that PyOpenSSL's package-level dependencies have been met.
Throws `ImportError` if they are not met.
"""
# Method added in `cryptography==1.1`; not available in older versions
from cryptography.x509.extensions import Extensions
if getattr(Extens... | [
"def",
"_validate_dependencies_met",
"(",
")",
":",
"# Method added in `cryptography==1.1`; not available in older versions",
"from",
"cryptography",
".",
"x509",
".",
"extensions",
"import",
"Extensions",
"if",
"getattr",
"(",
"Extensions",
",",
"\"get_extension_for_class\"",
... | 48.333333 | 20.333333 |
def get_infobox(ptree, boxterm="box"):
"""
Returns parse tree template with title containing <boxterm> as dict:
<box> = {<name>: <value>, ...}
If simple transform fails, attempts more general assembly:
<box> = {'boxes': [{<title>: <parts>}, ...],
'count': <len(boxes)>}
... | [
"def",
"get_infobox",
"(",
"ptree",
",",
"boxterm",
"=",
"\"box\"",
")",
":",
"boxes",
"=",
"[",
"]",
"for",
"item",
"in",
"lxml",
".",
"etree",
".",
"fromstring",
"(",
"ptree",
")",
".",
"xpath",
"(",
"\"//template\"",
")",
":",
"title",
"=",
"item"... | 26.814815 | 19.185185 |
def tree(path, load_path=None):
'''
Returns recursively the complete tree of a node
CLI Example:
.. code-block:: bash
salt '*' augeas.tree /files/etc/
path
The base of the recursive listing
.. versionadded:: 2016.3.0
load_path
A colon-spearated list of directori... | [
"def",
"tree",
"(",
"path",
",",
"load_path",
"=",
"None",
")",
":",
"load_path",
"=",
"_check_load_paths",
"(",
"load_path",
")",
"aug",
"=",
"_Augeas",
"(",
"loadpath",
"=",
"load_path",
")",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"+",
... | 23.777778 | 24.222222 |
def isempty(path):
"""Returns True if the given file or directory path is empty.
**Examples**:
::
auxly.filesys.isempty("foo.txt") # Works on files...
auxly.filesys.isempty("bar") # ...or directories!
"""
if op.isdir(path):
return [] == os.listdir(path)
elif op.isfile(... | [
"def",
"isempty",
"(",
"path",
")",
":",
"if",
"op",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"[",
"]",
"==",
"os",
".",
"listdir",
"(",
"path",
")",
"elif",
"op",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"0",
"==",
"os",
".",
"s... | 28.615385 | 16.923077 |
def __skeleton_difference(graph, image, boundary_term, spacing):
"""
A skeleton for the calculation of intensity difference based boundary terms.
Iterates over the images dimensions and generates for each an array of absolute
neighbouring voxel :math:`(p, q)` intensity differences :math:`|I_p, I_q|... | [
"def",
"__skeleton_difference",
"(",
"graph",
",",
"image",
",",
"boundary_term",
",",
"spacing",
")",
":",
"def",
"intensity_difference",
"(",
"neighbour_one",
",",
"neighbour_two",
")",
":",
"\"\"\"\n Takes two voxel arrays constituting neighbours and computes the ab... | 46.468085 | 28.170213 |
def to_picard_basecalling_params(
self,
directory: Union[str, Path],
bam_prefix: Union[str, Path],
lanes: Union[int, List[int]],
) -> None:
"""Writes sample and library information to a set of files for a given
set of lanes.
**BARCODE PARAMETERS FILES**: Stor... | [
"def",
"to_picard_basecalling_params",
"(",
"self",
",",
"directory",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"bam_prefix",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"lanes",
":",
"Union",
"[",
"int",
",",
"List",
"[",
"int",
"]",
"]"... | 40.890909 | 22.266667 |
def send_to_cloudshark(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin
"""Send a capture to a CloudShark Appliance. Both
cloudshark_appliance_url and cloudshark_appliance_token must
be properly configured via system preferences.
:param id: Result ID ... | [
"def",
"send_to_cloudshark",
"(",
"self",
",",
"id",
",",
"seq",
",",
"intf",
",",
"inline",
"=",
"False",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"CloudSharkSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"pos... | 53.4 | 21 |
def put_http_meta(self, key, value):
"""
Add http related metadata.
:param str key: Currently supported keys are:
* url
* method
* user_agent
* client_ip
* status
* content_length
:param value: status and content_le... | [
"def",
"put_http_meta",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"key",
"==",
"http",
".",
"STATUS",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_... | 30.5 | 14.323529 |
def format(self, tokensource, outfile):
"""
Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
tuples and write it into ``outfile``.
"""
if self.encoding:
# wrap the outfile in a StreamWriter
outfile = codecs.lookup(self.encoding)[3](outfi... | [
"def",
"format",
"(",
"self",
",",
"tokensource",
",",
"outfile",
")",
":",
"if",
"self",
".",
"encoding",
":",
"# wrap the outfile in a StreamWriter",
"outfile",
"=",
"codecs",
".",
"lookup",
"(",
"self",
".",
"encoding",
")",
"[",
"3",
"]",
"(",
"outfile... | 41.555556 | 11.555556 |
def filter_nremoved(self, filt=True, quiet=False):
"""
Report how many data are removed by the active filters.
"""
rminfo = {}
for n in self.subsets['All_Samples']:
s = self.data[n]
rminfo[n] = s.filt_nremoved(filt)
if not quiet:
maxL =... | [
"def",
"filter_nremoved",
"(",
"self",
",",
"filt",
"=",
"True",
",",
"quiet",
"=",
"False",
")",
":",
"rminfo",
"=",
"{",
"}",
"for",
"n",
"in",
"self",
".",
"subsets",
"[",
"'All_Samples'",
"]",
":",
"s",
"=",
"self",
".",
"data",
"[",
"n",
"]"... | 44.190476 | 17.52381 |
def Start(self, Minimized=False, Nosplash=False):
"""Starts Skype application.
:Parameters:
Minimized : bool
If True, Skype is started minimized in system tray.
Nosplash : bool
If True, no splash screen is displayed upon startup.
"""
self._Sky... | [
"def",
"Start",
"(",
"self",
",",
"Minimized",
"=",
"False",
",",
"Nosplash",
"=",
"False",
")",
":",
"self",
".",
"_Skype",
".",
"_Api",
".",
"startup",
"(",
"Minimized",
",",
"Nosplash",
")"
] | 34.7 | 15.8 |
def main():
"""
Zebrafish:
1. Map ENSP to ZFIN Ids using Intermine
2. Map deprecated ENSP IDs to ensembl genes
by querying the ensembl database then use
intermine to resolve to gene IDs
Mouse: Map deprecated ENSP IDs to ensembl genes
by querying the ensembl ... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"usage",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'--config'",
",",
"'-c'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'JSON configuration file'",
"... | 34.175573 | 20.954198 |
def shutdown(self, reason = ConnectionClosed()):
"""Shutdown the socket server.
The socket server will stop accepting incoming connections.
All connections will be dropped.
"""
if self._shutdown:
raise ShutdownError()
self.stop()
se... | [
"def",
"shutdown",
"(",
"self",
",",
"reason",
"=",
"ConnectionClosed",
"(",
")",
")",
":",
"if",
"self",
".",
"_shutdown",
":",
"raise",
"ShutdownError",
"(",
")",
"self",
".",
"stop",
"(",
")",
"self",
".",
"_closing",
"=",
"True",
"for",
"connection... | 28.590909 | 16.818182 |
def add_default_module_dir(self):
"""
Add directory to store built-in plugins to `module_dir` parameter.
Default directory to store plugins is `BLACKBIRD_INSTALL_DIR/plugins`.
:rtype: None
:return: None
"""
default_module_dir = os.path.join(
os.path.ab... | [
"def",
"add_default_module_dir",
"(",
"self",
")",
":",
"default_module_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"curdir",
")",
",",
"'plugins'",
")",
"module_dir_params",
"=",
"{",
... | 31.227273 | 16.590909 |
def string_asset(class_obj: type) -> type:
"""
Decorator to annotate the StringAsset class. Registers the decorated class
as the StringAsset known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _string_asset_resource_type
_string_asset_resource_type = class_o... | [
"def",
"string_asset",
"(",
"class_obj",
":",
"type",
")",
"->",
"type",
":",
"assert",
"isinstance",
"(",
"class_obj",
",",
"type",
")",
",",
"\"class_obj is not a Class\"",
"global",
"_string_asset_resource_type",
"_string_asset_resource_type",
"=",
"class_obj",
"re... | 37.222222 | 10.777778 |
def open_channel_with_funding(
self,
registry_address_hex,
token_address_hex,
peer_address_hex,
total_deposit,
settle_timeout=None,
):
""" Convenience method to open a channel.
Args:
registry_address_hex (str): hex ... | [
"def",
"open_channel_with_funding",
"(",
"self",
",",
"registry_address_hex",
",",
"token_address_hex",
",",
"peer_address_hex",
",",
"total_deposit",
",",
"settle_timeout",
"=",
"None",
",",
")",
":",
"# Check, if peer is discoverable",
"registry_address",
"=",
"decode_h... | 35 | 21.27907 |
def patch_module_function(module, target, aspect, force_name=None, bag=BrokenBag, **options):
"""
Low-level patcher for one function from a specified module.
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object.
"""
logdebug("patch_module_function (modul... | [
"def",
"patch_module_function",
"(",
"module",
",",
"target",
",",
"aspect",
",",
"force_name",
"=",
"None",
",",
"bag",
"=",
"BrokenBag",
",",
"*",
"*",
"options",
")",
":",
"logdebug",
"(",
"\"patch_module_function (module=%s, target=%s, aspect=%s, force_name=%s, **... | 48.166667 | 27 |
def get_stdin_data():
""" Helper function that returns data send to stdin or False if nothing is send """
# STDIN can only be 3 different types of things ("modes")
# 1. An interactive terminal device (i.e. a TTY -> sys.stdin.isatty() or stat.S_ISCHR)
# 2. A (named) pipe (stat.S_ISFIFO)
# 3. A reg... | [
"def",
"get_stdin_data",
"(",
")",
":",
"# STDIN can only be 3 different types of things (\"modes\")",
"# 1. An interactive terminal device (i.e. a TTY -> sys.stdin.isatty() or stat.S_ISCHR)",
"# 2. A (named) pipe (stat.S_ISFIFO)",
"# 3. A regular file (stat.S_ISREG)",
"# Technically, STDIN can... | 56.566667 | 30.933333 |
def render(self, is_unicode=False, **kwargs):
"""Render the graph, and return the svg string"""
self.setup(**kwargs)
svg = self.svg.render(
is_unicode=is_unicode, pretty_print=self.pretty_print
)
self.teardown()
return svg | [
"def",
"render",
"(",
"self",
",",
"is_unicode",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"setup",
"(",
"*",
"*",
"kwargs",
")",
"svg",
"=",
"self",
".",
"svg",
".",
"render",
"(",
"is_unicode",
"=",
"is_unicode",
",",
"pretty_... | 34.375 | 15.25 |
def int_to_bit(self, x_int, num_bits, base=2):
"""Turn x_int representing numbers into a bitwise (lower-endian) tensor.
Args:
x_int: Tensor containing integer to be converted into base
notation.
num_bits: Number of bits in the representation.
base: Base of the representation.
... | [
"def",
"int_to_bit",
"(",
"self",
",",
"x_int",
",",
"num_bits",
",",
"base",
"=",
"2",
")",
":",
"x_l",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"expand_dims",
"(",
"x_int",
",",
"axis",
"=",
"-",
"1",
")",
")",
"# pylint: disable=g-complex-compreh... | 34 | 15.571429 |
def __update_state(self):
"""Fetches most up to date state from db."""
# Only if the job was not in a terminal state.
if self._state.active:
self._state = self.__get_state_by_id(self.job_config.job_id) | [
"def",
"__update_state",
"(",
"self",
")",
":",
"# Only if the job was not in a terminal state.",
"if",
"self",
".",
"_state",
".",
"active",
":",
"self",
".",
"_state",
"=",
"self",
".",
"__get_state_by_id",
"(",
"self",
".",
"job_config",
".",
"job_id",
")"
] | 43 | 13 |
def changeLayerSize(self, layername, newsize):
"""
Changes layer size. Newsize must be greater than zero.
"""
# for all connection from to this layer, change matrix:
if self.sharedWeights:
raise AttributeError("shared weights broken")
for connection in self.co... | [
"def",
"changeLayerSize",
"(",
"self",
",",
"layername",
",",
"newsize",
")",
":",
"# for all connection from to this layer, change matrix:",
"if",
"self",
".",
"sharedWeights",
":",
"raise",
"AttributeError",
"(",
"\"shared weights broken\"",
")",
"for",
"connection",
... | 48.214286 | 13.785714 |
def is_satisfied_by(self, candidate: Any, **kwds: Any) -> bool:
"""Return True if `candidate` satisfies the specification."""
candidate_name = self._candidate_name
context = self._context
if context:
if candidate_name in kwds:
raise ValueError(f"Candidate name... | [
"def",
"is_satisfied_by",
"(",
"self",
",",
"candidate",
":",
"Any",
",",
"*",
"*",
"kwds",
":",
"Any",
")",
"->",
"bool",
":",
"candidate_name",
"=",
"self",
".",
"_candidate_name",
"context",
"=",
"self",
".",
"_context",
"if",
"context",
":",
"if",
... | 43.8 | 14.533333 |
def _tidy2xhtml5(html):
"""Tidy up a html4/5 soup to a parsable valid XHTML5.
Requires tidy-html5 from https://github.com/w3c/tidy-html5
Installation: http://goo.gl/FG27n
"""
html = _io2string(html)
html = _pre_tidy(html) # Pre-process
xhtml5, errors =\
tidy_document(html,
... | [
"def",
"_tidy2xhtml5",
"(",
"html",
")",
":",
"html",
"=",
"_io2string",
"(",
"html",
")",
"html",
"=",
"_pre_tidy",
"(",
"html",
")",
"# Pre-process",
"xhtml5",
",",
"errors",
"=",
"tidy_document",
"(",
"html",
",",
"options",
"=",
"{",
"# do not merge ne... | 57.223529 | 22.094118 |
def opls_notation(atom_key):
"""Return element for OPLS forcefield atom key."""
# warning for Ne, He, Na types overlap
conflicts = ['ne', 'he', 'na']
if atom_key in conflicts:
raise _AtomKeyConflict((
"One of the OPLS conflicting "
"atom_keys has occured '{0}'. "
... | [
"def",
"opls_notation",
"(",
"atom_key",
")",
":",
"# warning for Ne, He, Na types overlap",
"conflicts",
"=",
"[",
"'ne'",
",",
"'he'",
",",
"'na'",
"]",
"if",
"atom_key",
"in",
"conflicts",
":",
"raise",
"_AtomKeyConflict",
"(",
"(",
"\"One of the OPLS conflicting... | 43.352941 | 13.117647 |
def intersect(self, other):
"""Constructs an unminimized DFA recognizing
the intersection of the languages of two given DFAs.
Args:
other (DFA): The other DFA that will be used
for the intersect operation
Returns:
Returns:
DFA: The... | [
"def",
"intersect",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"automaton",
"=",
"fst",
".",
"intersect",
"(",
"self",
".",
"automaton",
",",
"other",
".",
"automaton",
")",
"return",
"self"
] | 35.666667 | 16.083333 |
def find_all_mappings(
self,
other_lattice: "Lattice",
ltol: float = 1e-5,
atol: float = 1,
skip_rotation_matrix: bool = False,
) -> Iterator[Tuple["Lattice", Optional[np.ndarray], np.ndarray]]:
"""
Finds all mappings between current lattice and another lattic... | [
"def",
"find_all_mappings",
"(",
"self",
",",
"other_lattice",
":",
"\"Lattice\"",
",",
"ltol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1",
",",
"skip_rotation_matrix",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Iterator",
"[",
"Tupl... | 42.820513 | 23.333333 |
def update_model_in_repo_based_on_filename(self, model):
""" Adds a model to the repo (not initially visible)
Args:
model: the model to be added. If the model
has no filename, a name is invented
Returns: the filename of the model added to the repo
"""
if m... | [
"def",
"update_model_in_repo_based_on_filename",
"(",
"self",
",",
"model",
")",
":",
"if",
"model",
".",
"_tx_filename",
"is",
"None",
":",
"for",
"fn",
"in",
"self",
".",
"all_models",
".",
"filename_to_model",
":",
"if",
"self",
".",
"all_models",
".",
"f... | 43.809524 | 15.952381 |
def parse_variable(self, variable):
"""Method to parse an input or output variable.
**Example Variable**::
#App:1234:output!String
Args:
variable (string): The variable name to parse.
Returns:
(dictionary): Result of parsed string.
"""
... | [
"def",
"parse_variable",
"(",
"self",
",",
"variable",
")",
":",
"data",
"=",
"None",
"if",
"variable",
"is",
"not",
"None",
":",
"variable",
"=",
"variable",
".",
"strip",
"(",
")",
"if",
"re",
".",
"match",
"(",
"self",
".",
"_variable_match",
",",
... | 29.36 | 15.92 |
def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` clas... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"# Check the \"before\" file",
"if",
"not",
"args",
".",
"before",
".",
"endswith",
"(",
"\".bim\"",
")",
":",
"msg",
"=",
"\"%s: not a BIM file (extension must be .bim)\"",
"%",
"args",
".",
"before",
"raise",
"ProgramEr... | 32.193548 | 18.483871 |
def clear(self):
"""Remove all key-value pairs."""
for i in range(self.maxlevel):
self._head[2+i] = self._tail
self._tail[-1] = 0
self._level = 1 | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"maxlevel",
")",
":",
"self",
".",
"_head",
"[",
"2",
"+",
"i",
"]",
"=",
"self",
".",
"_tail",
"self",
".",
"_tail",
"[",
"-",
"1",
"]",
"=",
"0",
"self",
... | 31.333333 | 8.833333 |
def socket_reader(connection: socket, buffer_size: int = 1024):
""" read data from adb socket """
while connection is not None:
try:
buffer = connection.recv(buffer_size)
# no output
if not len(buffer):
raise ConnectionAbortedError
except Conne... | [
"def",
"socket_reader",
"(",
"connection",
":",
"socket",
",",
"buffer_size",
":",
"int",
"=",
"1024",
")",
":",
"while",
"connection",
"is",
"not",
"None",
":",
"try",
":",
"buffer",
"=",
"connection",
".",
"recv",
"(",
"buffer_size",
")",
"# no output",
... | 32.6 | 12.65 |
def runner(self, fun, **kwargs):
'''
Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>`
'''
return self.pool.fire_async(self.client_cache['runner'].low, args=(fun, kwargs)) | [
"def",
"runner",
"(",
"self",
",",
"fun",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"pool",
".",
"fire_async",
"(",
"self",
".",
"client_cache",
"[",
"'runner'",
"]",
".",
"low",
",",
"args",
"=",
"(",
"fun",
",",
"kwargs",
")",
"... | 44.4 | 30.8 |
def _compute_needed_metrics(self, instance, available_metrics):
""" Compare the available metrics for one MOR we have computed and intersect them
with the set of metrics we want to report
"""
i_key = self._instance_key(instance)
if self.in_compatibility_mode(instance):
... | [
"def",
"_compute_needed_metrics",
"(",
"self",
",",
"instance",
",",
"available_metrics",
")",
":",
"i_key",
"=",
"self",
".",
"_instance_key",
"(",
"instance",
")",
"if",
"self",
".",
"in_compatibility_mode",
"(",
"instance",
")",
":",
"if",
"instance",
".",
... | 48.966667 | 22.033333 |
def add_global_request_interceptor(self, request_interceptor):
# type: (AbstractRequestInterceptor) -> None
"""Register input to the global request interceptors list.
:param request_interceptor: Request Interceptor instance to be
registered.
:type request_interceptor: Abstra... | [
"def",
"add_global_request_interceptor",
"(",
"self",
",",
"request_interceptor",
")",
":",
"# type: (AbstractRequestInterceptor) -> None",
"if",
"request_interceptor",
"is",
"None",
":",
"raise",
"RuntimeConfigException",
"(",
"\"Valid Request Interceptor instance to be provided\"... | 42.333333 | 19.944444 |
def pygmentify(value, **kwargs):
"""Return a highlighted code block with Pygments."""
soup = BeautifulSoup(value, 'html.parser')
for pre in soup.find_all('pre'):
# Get code
code = ''.join([to_string(item) for item in pre.contents])
code = code.replace('<', '<')
code = cod... | [
"def",
"pygmentify",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"value",
",",
"'html.parser'",
")",
"for",
"pre",
"in",
"soup",
".",
"find_all",
"(",
"'pre'",
")",
":",
"# Get code",
"code",
"=",
"''",
".",
"j... | 30.732143 | 17.625 |
def get_catalog_lookup_session(self):
"""Gets the catalog lookup session.
return: (osid.cataloging.CatalogLookupSession) - a
``CatalogLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_catalog_lookup()`` is
... | [
"def",
"get_catalog_lookup_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_catalog_lookup",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"CatalogLookupSession",
"(",
... | 40.25 | 14.75 |
def prtcols(items, vpad=6):
'''
After computing the size of our rows and columns based on the terminal size
and length of the largest element, use zip to aggregate our column lists
into row lists and then iterate over the row lists and print them.
'''
from os import get_terminal_size
items =... | [
"def",
"prtcols",
"(",
"items",
",",
"vpad",
"=",
"6",
")",
":",
"from",
"os",
"import",
"get_terminal_size",
"items",
"=",
"list",
"(",
"items",
")",
"# copy list so we don't mutate it",
"width",
",",
"height",
"=",
"get_terminal_size",
"(",
")",
"height",
... | 41.941176 | 17 |
def clean_path_from_deprecated_naming(base_path):
""" Checks if the base path includes deprecated characters/format and returns corrected version
The state machine folder name should be according the universal RAFCON path format. In case the state machine path
is inside a mounted library_root_path also the... | [
"def",
"clean_path_from_deprecated_naming",
"(",
"base_path",
")",
":",
"def",
"warning_logger_message",
"(",
"insert_string",
")",
":",
"not_allowed_characters",
"=",
"\"'\"",
"+",
"\"', '\"",
".",
"join",
"(",
"REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION",
".",
"keys",
"... | 60.323529 | 31.147059 |
def _get_time_stamp(entry):
"""Return datetime object from a timex constraint start/end entry.
Example string format to convert: 2018-01-01T00:00
"""
if not entry or entry == 'Undef':
return None
try:
dt = datetime.datetime.strptime(entry, '%Y-%m-%dT%H:%M')
except Exception as e... | [
"def",
"_get_time_stamp",
"(",
"entry",
")",
":",
"if",
"not",
"entry",
"or",
"entry",
"==",
"'Undef'",
":",
"return",
"None",
"try",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"entry",
",",
"'%Y-%m-%dT%H:%M'",
")",
"except",
"Exc... | 30.846154 | 17.384615 |
def write_task_options(self, **kw):
"""
Write an options line for a task definition::
writer.write_task_options(
start_time=time(12, 34, 56),
task_time=timedelta(hours=1, minutes=45, seconds=12),
waypoint_distance=False,
dista... | [
"def",
"write_task_options",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"self",
".",
"in_task_section",
":",
"raise",
"RuntimeError",
"(",
"u'Task options have to be written in task section'",
")",
"fields",
"=",
"[",
"'Options'",
"]",
"if",
"'star... | 38.85 | 21.65 |
def camelHump(text):
"""
Converts the inputted text to camel humps by joining all
capital letters toegether (The Quick, Brown,
Fox.Tail -> TheQuickBrownFoxTail)
:param: text <str> text to be changed
:return: <str>
:usage: |import projex.text
... | [
"def",
"camelHump",
"(",
"text",
")",
":",
"# make sure the first letter is upper case",
"output",
"=",
"''",
".",
"join",
"(",
"[",
"word",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"word",
"[",
"1",
":",
"]",
"for",
"word",
"in",
"words",
"(",
"t... | 32.277778 | 18.388889 |
def __execute_from_archive(self, cmd):
"""Execute gerrit command against the archive"""
cmd = self.sanitize_for_archive(cmd)
response = self.archive.retrieve(cmd, None, None)
if isinstance(response, RuntimeError):
raise response
return response | [
"def",
"__execute_from_archive",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"self",
".",
"sanitize_for_archive",
"(",
"cmd",
")",
"response",
"=",
"self",
".",
"archive",
".",
"retrieve",
"(",
"cmd",
",",
"None",
",",
"None",
")",
"if",
"isinstance",... | 29 | 18 |
def createCertRequest(pkey, digest="sha256"):
"""
Create a certificate request.
Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is sha256
**name - The name of the subject of the request, possible
... | [
"def",
"createCertRequest",
"(",
"pkey",
",",
"digest",
"=",
"\"sha256\"",
")",
":",
"req",
"=",
"crypto",
".",
"X509Req",
"(",
")",
"req",
".",
"get_subject",
"(",
")",
".",
"C",
"=",
"\"FR\"",
"req",
".",
"get_subject",
"(",
")",
".",
"ST",
"=",
... | 37.785714 | 13.857143 |
def filter_stacks(data, sidx, hslice):
"""
Grab a chunk of loci from the HDF5 database. Apply filters and fill the
the filters boolean array.
The design of the filtering steps intentionally sacrifices some performance
for an increase in readability, and extensibility. Calling multiple filter
fu... | [
"def",
"filter_stacks",
"(",
"data",
",",
"sidx",
",",
"hslice",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Entering filter_stacks\"",
")",
"## open h5 handles",
"io5",
"=",
"h5py",
".",
"File",
"(",
"data",
".",
"clust_database",
",",
"'r'",
")",
"co5",
"="... | 39.643564 | 21.564356 |
def fromMimeData(self, data):
"""
Paste the clipboard data at the current cursor position.
This method also adds another undo-object to the undo-stack.
..note: This method forcefully interrupts the ``QsciInternal``
pasting mechnism by returning an empty MIME data elemen... | [
"def",
"fromMimeData",
"(",
"self",
",",
"data",
")",
":",
"# Only insert the element if it is available in plain text.",
"if",
"data",
".",
"hasText",
"(",
")",
":",
"self",
".",
"insert",
"(",
"data",
".",
"text",
"(",
")",
")",
"# Tell the underlying QsciScinti... | 37.842105 | 21.421053 |
def argv_to_cmdline(argv):
"""
Convert a list of arguments to a single command line string.
@type argv: list( str )
@param argv: List of argument strings.
The first element is the program to execute.
@rtype: str
@return: Command line string.
"""
... | [
"def",
"argv_to_cmdline",
"(",
"argv",
")",
":",
"cmdline",
"=",
"list",
"(",
")",
"for",
"token",
"in",
"argv",
":",
"if",
"not",
"token",
":",
"token",
"=",
"'\"\"'",
"else",
":",
"if",
"'\"'",
"in",
"token",
":",
"token",
"=",
"token",
".",
"rep... | 30.84 | 12.36 |
def xyplot(points, title="", c="b", corner=1, lines=False):
"""
Return a ``vtkXYPlotActor`` that is a plot of `x` versus `y`,
where `points` is a list of `(x,y)` points.
:param int corner: assign position:
- 1, topleft,
- 2, topright,
- 3, bottomleft,
- 4, bottomrigh... | [
"def",
"xyplot",
"(",
"points",
",",
"title",
"=",
"\"\"",
",",
"c",
"=",
"\"b\"",
",",
"corner",
"=",
"1",
",",
"lines",
"=",
"False",
")",
":",
"c",
"=",
"vc",
".",
"getColor",
"(",
"c",
")",
"# allow different codings",
"array_x",
"=",
"vtk",
".... | 30.397059 | 13.367647 |
def generate_swagger_html(swagger_static_root, swagger_json_url):
"""
given a root directory for the swagger statics, and
a swagger json path, return back a swagger html designed
to use those values.
"""
tmpl = _get_template("swagger.html")
return tmpl.render(
swagger_root=swagger_st... | [
"def",
"generate_swagger_html",
"(",
"swagger_static_root",
",",
"swagger_json_url",
")",
":",
"tmpl",
"=",
"_get_template",
"(",
"\"swagger.html\"",
")",
"return",
"tmpl",
".",
"render",
"(",
"swagger_root",
"=",
"swagger_static_root",
",",
"swagger_json_url",
"=",
... | 36.1 | 16.3 |
def _make_retry_fields(file_name, metadata, tags, project):
"""Generate fields to send to init_multipart_upload in the case that a Sample upload via
fastx-proxy fails.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
metad... | [
"def",
"_make_retry_fields",
"(",
"file_name",
",",
"metadata",
",",
"tags",
",",
"project",
")",
":",
"upload_args",
"=",
"{",
"\"filename\"",
":",
"file_name",
"}",
"if",
"metadata",
":",
"# format metadata keys as snake case",
"new_metadata",
"=",
"{",
"}",
"... | 28 | 22.081081 |
def cli(**args):
""" Shakedown is a DC/OS test-harness wrapper for the pytest tool.
"""
import shakedown
# Read configuration options from ~/.shakedown (if exists)
args = read_config(args)
# Set configuration defaults
args = set_config_defaults(args)
if args['quiet']:
shakedow... | [
"def",
"cli",
"(",
"*",
"*",
"args",
")",
":",
"import",
"shakedown",
"# Read configuration options from ~/.shakedown (if exists)",
"args",
"=",
"read_config",
"(",
"args",
")",
"# Set configuration defaults",
"args",
"=",
"set_config_defaults",
"(",
"args",
")",
"if"... | 35.659509 | 22.490798 |
def run(self, *args, **kwargs):
"""Run the command; args/kwargs are added or replace the ones given to the constructor."""
_args, _kwargs = self._combine_arglist(args, kwargs)
results, p = self._run_command(*_args, **_kwargs)
return results | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_args",
",",
"_kwargs",
"=",
"self",
".",
"_combine_arglist",
"(",
"args",
",",
"kwargs",
")",
"results",
",",
"p",
"=",
"self",
".",
"_run_command",
"(",
"*",
"_args"... | 53.6 | 12.8 |
def inrypl(vertex, direct, plane):
"""
Find the intersection of a ray and a plane.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inrypl_c.html
:param vertex: Vertex vector of ray.
:type vertex: 3-Element Array of floats
:param direct: Direction vector of ray.
:type direct: 3-Elem... | [
"def",
"inrypl",
"(",
"vertex",
",",
"direct",
",",
"plane",
")",
":",
"assert",
"(",
"isinstance",
"(",
"plane",
",",
"stypes",
".",
"Plane",
")",
")",
"vertex",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"vertex",
")",
"direct",
"=",
"stypes",
".",
... | 35.076923 | 12.923077 |
def listdir(self, directory_path=None, hidden_files=False):
"""
Return a list of files and directories in a given directory.
:param directory_path: Optional str (defaults to current directory)
:param hidden_files: Include hidden files
:return: Directory listing
"""
... | [
"def",
"listdir",
"(",
"self",
",",
"directory_path",
"=",
"None",
",",
"hidden_files",
"=",
"False",
")",
":",
"# Change current directory if a directory path is specified, otherwise use current",
"if",
"directory_path",
":",
"self",
".",
"chdir",
"(",
"directory_path",
... | 36.052632 | 20.473684 |
def contains_non_repeat_actions(self):
'''
Because repeating repeat actions can get ugly real fast
'''
for action in self.actions:
if not isinstance(action, (int, dynamic.RepeatCommand)):
return True
return False | [
"def",
"contains_non_repeat_actions",
"(",
"self",
")",
":",
"for",
"action",
"in",
"self",
".",
"actions",
":",
"if",
"not",
"isinstance",
"(",
"action",
",",
"(",
"int",
",",
"dynamic",
".",
"RepeatCommand",
")",
")",
":",
"return",
"True",
"return",
"... | 34.125 | 18.625 |
def get_3d_markers_no_label(
self, component_info=None, data=None, component_position=None
):
"""Get 3D markers without label."""
return self._get_3d_markers(
RT3DMarkerPositionNoLabel, component_info, data, component_position
) | [
"def",
"get_3d_markers_no_label",
"(",
"self",
",",
"component_info",
"=",
"None",
",",
"data",
"=",
"None",
",",
"component_position",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_3d_markers",
"(",
"RT3DMarkerPositionNoLabel",
",",
"component_info",
",",
... | 38.571429 | 21.285714 |
def create_timestamp_anti_leech_url(host, file_name, query_string, encrypt_key, deadline):
"""
创建时间戳防盗链
Args:
host: 带访问协议的域名
file_name: 原始文件名,不需要urlencode
query_string: 查询参数,不需要urlencode
encrypt_key: 时间戳防盗链密钥
deadline: 链接有效期时间... | [
"def",
"create_timestamp_anti_leech_url",
"(",
"host",
",",
"file_name",
",",
"query_string",
",",
"encrypt_key",
",",
"deadline",
")",
":",
"if",
"query_string",
":",
"url_to_sign",
"=",
"'{0}/{1}?{2}'",
".",
"format",
"(",
"host",
",",
"urlencode",
"(",
"file_... | 32.2 | 23.6 |
def p_expr_BOR_expr(p):
""" expr : expr BOR expr
"""
p[0] = make_binary(p.lineno(2), 'BOR', p[1], p[3], lambda x, y: x | y) | [
"def",
"p_expr_BOR_expr",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"make_binary",
"(",
"p",
".",
"lineno",
"(",
"2",
")",
",",
"'BOR'",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lambda",
"x",
",",
"y",
":",
"x",
"|",
"y"... | 33 | 12.75 |
def colindex_by_colname(self, colname):
"""Return column index whose name is :param:`column`
:raises: `ValueError` when no column with :param:`colname` found
"""
for i, coldef in enumerate(self): # iterate each column's definition
if coldef.name == colname:
... | [
"def",
"colindex_by_colname",
"(",
"self",
",",
"colname",
")",
":",
"for",
"i",
",",
"coldef",
"in",
"enumerate",
"(",
"self",
")",
":",
"# iterate each column's definition",
"if",
"coldef",
".",
"name",
"==",
"colname",
":",
"return",
"i",
"raise",
"ValueE... | 43.222222 | 17.333333 |
def dependents(self):
"""
:API: public
:return: targets that depend on this target
:rtype: list of Target
"""
return [self._build_graph.get_target(dep_address)
for dep_address in self._build_graph.dependents_of(self.address)] | [
"def",
"dependents",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_build_graph",
".",
"get_target",
"(",
"dep_address",
")",
"for",
"dep_address",
"in",
"self",
".",
"_build_graph",
".",
"dependents_of",
"(",
"self",
".",
"address",
")",
"]"
] | 28.222222 | 17.111111 |
def GetExtractionStatusUpdateCallback(self):
"""Retrieves the extraction status update callback function.
Returns:
function: status update callback function or None if not available.
"""
if self._mode == self.MODE_LINEAR:
return self._PrintExtractionStatusUpdateLinear
if self._mode == ... | [
"def",
"GetExtractionStatusUpdateCallback",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mode",
"==",
"self",
".",
"MODE_LINEAR",
":",
"return",
"self",
".",
"_PrintExtractionStatusUpdateLinear",
"if",
"self",
".",
"_mode",
"==",
"self",
".",
"MODE_WINDOW",
":",
... | 30.384615 | 18.307692 |
def trade(self, pair, type_, rate, amount):
"""
The basic method that can be used for creating orders and trading on the exchange.
To use this method you need an API key privilege to trade.
You can only create limit orders using this method, but you can emulate market orders using rate p... | [
"def",
"trade",
"(",
"self",
",",
"pair",
",",
"type_",
",",
"rate",
",",
"amount",
")",
":",
"return",
"self",
".",
"_trade_api_call",
"(",
"'Trade'",
",",
"pair",
"=",
"pair",
",",
"type_",
"=",
"type_",
",",
"rate",
"=",
"rate",
",",
"amount",
"... | 62.733333 | 31.933333 |
def set_bucket_notification(self, bucket_name, notifications):
"""
Set the given notifications on the bucket.
:param bucket_name: Bucket name.
:param notifications: Notifications structure
"""
is_valid_bucket_name(bucket_name)
is_valid_bucket_notification_config(... | [
"def",
"set_bucket_notification",
"(",
"self",
",",
"bucket_name",
",",
"notifications",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_valid_bucket_notification_config",
"(",
"notifications",
")",
"content",
"=",
"xml_marshal_bucket_notifications",
"(",
"... | 33.5 | 15.416667 |
def resolve_dependencies(self, to_build, depender):
"""Add any required dependencies.
"""
shutit_global.shutit_global_object.yield_to_draw()
self.log('In resolve_dependencies',level=logging.DEBUG)
cfg = self.cfg
for dependee_id in depender.depends_on:
dependee = self.shutit_map.get(dependee_id)
# Don'... | [
"def",
"resolve_dependencies",
"(",
"self",
",",
"to_build",
",",
"depender",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"self",
".",
"log",
"(",
"'In resolve_dependencies'",
",",
"level",
"=",
"logging",
".",
"DEBUG"... | 40.714286 | 12.428571 |
def _expand_paths_itr(paths, marker='*'):
"""Iterator version of :func:`expand_paths`.
"""
for path in paths:
if is_path(path):
if marker in path: # glob path pattern
for ppath in sglob(path):
yield ppath
else:
yield path ... | [
"def",
"_expand_paths_itr",
"(",
"paths",
",",
"marker",
"=",
"'*'",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"is_path",
"(",
"path",
")",
":",
"if",
"marker",
"in",
"path",
":",
"# glob path pattern",
"for",
"ppath",
"in",
"sglob",
"(",
"pat... | 34.05 | 9.2 |
def get_topics(self):
'''
Returns the topics available on unbabel
'''
result = self.api_call('topic/')
topics_json = json.loads(result.content)
topics = [Topic(name=topic_json["topic"]["name"])
for topic_json in topics_json["objects"]]
return... | [
"def",
"get_topics",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"api_call",
"(",
"'topic/'",
")",
"topics_json",
"=",
"json",
".",
"loads",
"(",
"result",
".",
"content",
")",
"topics",
"=",
"[",
"Topic",
"(",
"name",
"=",
"topic_json",
"[",
... | 35.444444 | 16.777778 |
def body(self):
"""Yields the body of the buffered file."""
for fp, need_close in self.files:
try:
name = os.path.basename(fp.name)
except AttributeError:
name = ''
for chunk in self.gen_chunks(self.envelope.file_open(name)):
... | [
"def",
"body",
"(",
"self",
")",
":",
"for",
"fp",
",",
"need_close",
"in",
"self",
".",
"files",
":",
"try",
":",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fp",
".",
"name",
")",
"except",
"AttributeError",
":",
"name",
"=",
"''",
"... | 35.705882 | 13.882353 |
def validation_step(self, Xi, yi, **fit_params):
"""Perform a forward step using batched data and return the
resulting loss.
The module is set to be in evaluation mode (e.g. dropout is
not applied).
Parameters
----------
Xi : input data
A batch of the ... | [
"def",
"validation_step",
"(",
"self",
",",
"Xi",
",",
"yi",
",",
"*",
"*",
"fit_params",
")",
":",
"self",
".",
"module_",
".",
"eval",
"(",
")",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"y_pred",
"=",
"self",
".",
"infer",
"(",
"Xi",
","... | 28.535714 | 19.607143 |
def register_logger(self, logger):
"""
Register a new logger.
"""
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]
logger.propagate = False
output = self.output
level = logging.WARNING
if ... | [
"def",
"register_logger",
"(",
"self",
",",
"logger",
")",
":",
"handler",
"=",
"CommandHandler",
"(",
"self",
")",
"handler",
".",
"setFormatter",
"(",
"CommandFormatter",
"(",
")",
")",
"logger",
".",
"handlers",
"=",
"[",
"handler",
"]",
"logger",
".",
... | 28.411765 | 11.588235 |
def analyze(qpi, r0, method="edge", model="projection", edgekw={}, imagekw={},
ret_center=False, ret_pha_offset=False, ret_qpi=False):
"""Determine refractive index and radius of a spherical object
Parameters
----------
qpi: qpimage.QPImage
Quantitative phase image data
r0: floa... | [
"def",
"analyze",
"(",
"qpi",
",",
"r0",
",",
"method",
"=",
"\"edge\"",
",",
"model",
"=",
"\"projection\"",
",",
"edgekw",
"=",
"{",
"}",
",",
"imagekw",
"=",
"{",
"}",
",",
"ret_center",
"=",
"False",
",",
"ret_pha_offset",
"=",
"False",
",",
"ret... | 37.941176 | 16.107843 |
def read_matlab_features(array_paths, number_of_nodes, dimensionality):
"""
Returns a sparse feature matrix as calculated by a Matlab routine.
"""
# Read the data array
file_row_gen = get_file_row_generator(array_paths[0], "\t")
data = list()
append_data = data.append
for file_row in fil... | [
"def",
"read_matlab_features",
"(",
"array_paths",
",",
"number_of_nodes",
",",
"dimensionality",
")",
":",
"# Read the data array",
"file_row_gen",
"=",
"get_file_row_generator",
"(",
"array_paths",
"[",
"0",
"]",
",",
"\"\\t\"",
")",
"data",
"=",
"list",
"(",
")... | 34.194444 | 20.861111 |
def send(self, sender: PytgbotApiBot):
"""
Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage
"""
return sender.send_sticker(
# receiver, self.media, disable_notificati... | [
"def",
"send",
"(",
"self",
",",
"sender",
":",
"PytgbotApiBot",
")",
":",
"return",
"sender",
".",
"send_sticker",
"(",
"# receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id",
"sticker",
"=",
"self",
".",
"sticker",
",",
"c... | 42.076923 | 26.538462 |
def vgp_calc(dataframe, tilt_correction='yes', site_lon='site_lon', site_lat='site_lat', dec_is='dec_is', inc_is='inc_is', dec_tc='dec_tc', inc_tc='inc_tc'):
"""
This function calculates paleomagnetic poles using directional data and site
location data within a pandas.DataFrame. The function adds the column... | [
"def",
"vgp_calc",
"(",
"dataframe",
",",
"tilt_correction",
"=",
"'yes'",
",",
"site_lon",
"=",
"'site_lon'",
",",
"site_lat",
"=",
"'site_lat'",
",",
"dec_is",
"=",
"'dec_is'",
",",
"inc_is",
"=",
"'inc_is'",
",",
"dec_tc",
"=",
"'dec_tc'",
",",
"inc_tc",
... | 66.166667 | 36.366667 |
def diff(config, files, metrics, changes_only=True, detail=True):
"""
Show the differences in metrics for each of the files.
:param config: The wily configuration
:type config: :namedtuple:`wily.config.WilyConfig`
:param files: The files to compare.
:type files: ``list`` of ``str``
:par... | [
"def",
"diff",
"(",
"config",
",",
"files",
",",
"metrics",
",",
"changes_only",
"=",
"True",
",",
"detail",
"=",
"True",
")",
":",
"config",
".",
"targets",
"=",
"files",
"files",
"=",
"list",
"(",
"files",
")",
"state",
"=",
"State",
"(",
"config",... | 36.190909 | 19.027273 |
def _decode_value(self, value):
""" Decodes the value by turning any binary data back into Python objects.
The method searches for ObjectId values, loads the associated binary data from
GridFS and returns the decoded Python object.
Args:
value (object): The value that shoul... | [
"def",
"_decode_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"str",
",",
"bool",
",",
"datetime",
")",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"list",... | 38.666667 | 20.272727 |
def _useful_basename(data):
"""Provide a useful file basename for outputs, referencing batch/sample and caller.
"""
names = dd.get_batches(data)
if not names:
names = [dd.get_sample_name(data)]
batch_name = names[0]
return "%s-%s" % (batch_name, data["sv"]["variantcaller"]) | [
"def",
"_useful_basename",
"(",
"data",
")",
":",
"names",
"=",
"dd",
".",
"get_batches",
"(",
"data",
")",
"if",
"not",
"names",
":",
"names",
"=",
"[",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"]",
"batch_name",
"=",
"names",
"[",
"0",
"]",
... | 37.375 | 10.375 |
def collect_variables(self, g_scope='gen', d_scope='discrim'):
"""
Assign `self.g_vars` to the parameters under scope `g_scope`,
and same with `self.d_vars`.
"""
self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope)
assert self.g_vars
self.d_v... | [
"def",
"collect_variables",
"(",
"self",
",",
"g_scope",
"=",
"'gen'",
",",
"d_scope",
"=",
"'discrim'",
")",
":",
"self",
".",
"g_vars",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
",",
"g_scope",
")",
"asser... | 45 | 18.555556 |
def get_host_node_state(self, state, problem_has_been_acknowledged, in_scheduled_downtime):
"""Get host node state, simplest case ::
* Handle not value (revert) for host and consider 1 as 2
:return: 0, 1 or 2
:rtype: int
"""
# Make DOWN look as CRITICAL (2 instead of 1)... | [
"def",
"get_host_node_state",
"(",
"self",
",",
"state",
",",
"problem_has_been_acknowledged",
",",
"in_scheduled_downtime",
")",
":",
"# Make DOWN look as CRITICAL (2 instead of 1)",
"if",
"state",
"==",
"1",
":",
"state",
"=",
"2",
"# If our node is acknowledged or in dow... | 34.35 | 23.9 |
def _get_regional_term(self, C, imt, vs30, rrup):
"""
Compute regional term for Japan. See page 1043
"""
f3 = interpolate.interp1d(
[150, 250, 350, 450, 600, 850, 1150, 2000],
[C['a36'], C['a37'], C['a38'], C['a39'], C['a40'], C['a41'],
C['a42'], C['a... | [
"def",
"_get_regional_term",
"(",
"self",
",",
"C",
",",
"imt",
",",
"vs30",
",",
"rrup",
")",
":",
"f3",
"=",
"interpolate",
".",
"interp1d",
"(",
"[",
"150",
",",
"250",
",",
"350",
",",
"450",
",",
"600",
",",
"850",
",",
"1150",
",",
"2000",
... | 38.6 | 9.8 |
def get_token_issuer(token):
"""
Issuer of a token is the identifier used to recover the secret
Need to extract this from token to ensure we can proceed to the signature validation stage
Does not check validity of the token
:param token: signed JWT token
:return issuer: iss field of the JWT toke... | [
"def",
"get_token_issuer",
"(",
"token",
")",
":",
"try",
":",
"unverified",
"=",
"decode_token",
"(",
"token",
")",
"if",
"'iss'",
"not",
"in",
"unverified",
":",
"raise",
"TokenIssuerError",
"return",
"unverified",
".",
"get",
"(",
"'iss'",
")",
"except",
... | 34.368421 | 15.526316 |
def request_object(self, object_class, address, state, object_handler,
error_handler = None, timeout_handler = None,
backup_state = None, timeout = None,
freshness_period = None, expiration_period = None, purge_period = None):
"""Request an object of given class, with given a... | [
"def",
"request_object",
"(",
"self",
",",
"object_class",
",",
"address",
",",
"state",
",",
"object_handler",
",",
"error_handler",
"=",
"None",
",",
"timeout_handler",
"=",
"None",
",",
"backup_state",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"fresh... | 54.25 | 23.544118 |
def remove_permission(self, label, callback=None):
"""
Remove a permission from a queue.
:type label: str or unicode
:param label: The unique label associated with the permission being removed.
:rtype: bool
:return: True if successful, False otherwise.
"""
... | [
"def",
"remove_permission",
"(",
"self",
",",
"label",
",",
"callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"connection",
".",
"remove_permission",
"(",
"self",
",",
"label",
",",
"callback",
"=",
"callback",
")"
] | 35 | 19.363636 |
def _all_default(d, default, seen=None):
"""
ANY VALUE NOT SET WILL BE SET BY THE default
THIS IS RECURSIVE
"""
if default is None:
return
if _get(default, CLASS) is Data:
default = object.__getattribute__(default, SLOT) # REACH IN AND GET THE dict
# Log = _late_import()... | [
"def",
"_all_default",
"(",
"d",
",",
"default",
",",
"seen",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"return",
"if",
"_get",
"(",
"default",
",",
"CLASS",
")",
"is",
"Data",
":",
"default",
"=",
"object",
".",
"__getattribute__",
... | 46.727273 | 20.045455 |
def set_color(self, color, alpha = 1):
"""set active color. You can use hex colors like "#aaa", or you can use
normalized RGB tripplets (where every value is in range 0..1), or
you can do the same thing in range 0..65535.
also consider skipping this operation and specify the color on str... | [
"def",
"set_color",
"(",
"self",
",",
"color",
",",
"alpha",
"=",
"1",
")",
":",
"color",
"=",
"self",
".",
"colors",
".",
"parse",
"(",
"color",
")",
"# parse whatever we have there into a normalized triplet",
"if",
"len",
"(",
"color",
")",
"==",
"4",
"a... | 50.166667 | 18.333333 |
def ignore(self, argument_dest, **kwargs):
""" Register an argument with type knack.arguments.ignore_type (hidden/ignored)
:param argument_dest: The destination argument to apply the ignore type to
:type argument_dest: str
"""
self._check_stale()
if not self._applicable(... | [
"def",
"ignore",
"(",
"self",
",",
"argument_dest",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_stale",
"(",
")",
"if",
"not",
"self",
".",
"_applicable",
"(",
")",
":",
"return",
"dest_option",
"=",
"[",
"'--__{}'",
".",
"format",
"(",
"... | 40.75 | 20.75 |
def interstore(self, destination, *others):
""" The same as :meth:intersection, but stores the resulting set
@destination
@destination: #str keyname or :class:RedisSet
@others: one or several #str keynames or :class:RedisSet objects
-> #int number of members in ... | [
"def",
"interstore",
"(",
"self",
",",
"destination",
",",
"*",
"others",
")",
":",
"others",
"=",
"self",
".",
"_typesafe_others",
"(",
"others",
")",
"destination",
"=",
"self",
".",
"_typesafe",
"(",
"destination",
")",
"return",
"self",
".",
"_client",... | 42.5 | 18.25 |
def read(variable):
"""
read an element from LiFePO4wered.
:param variable: the element to read.
:type variable: Lifepo4weredEnum
:return: the value of the element
:rtype: int
:raises ValueError: if parameter value is not a member of Lifepo4weredEnum
"""
if variable not in variables... | [
"def",
"read",
"(",
"variable",
")",
":",
"if",
"variable",
"not",
"in",
"variablesEnum",
":",
"raise",
"ValueError",
"(",
"'Use a lifepo4wered enum element as read parameter.'",
")",
"if",
"canRead",
"(",
"variable",
")",
":",
"return",
"lifepo4weredSO",
".",
"re... | 34.470588 | 19.529412 |
def _break_poorly_matched_fronts(fronts, threshold=0.1, threshold_overlap_samples=3):
"""
For each onset front, for each frequency in that front, break the onset front if the signals
between this frequency's onset and the next frequency's onset are not similar enough.
Specifically:
If we have the f... | [
"def",
"_break_poorly_matched_fronts",
"(",
"fronts",
",",
"threshold",
"=",
"0.1",
",",
"threshold_overlap_samples",
"=",
"3",
")",
":",
"assert",
"threshold_overlap_samples",
">",
"0",
",",
"\"Number of samples of overlap must be greater than zero\"",
"breaks_after",
"=",... | 43.848485 | 24.090909 |
def join (self, timeout=None):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all... | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"self",
".",
"all_tasks_done",
":",
"if",
"timeout",
"is",
"None",
":",
"while",
"self",
".",
"unfinished_tasks",
":",
"self",
".",
"all_tasks_done",
".",
"wait",
"(",
")",
"els... | 44.136364 | 16.363636 |
def scaled(self, scale):
"""
Return a copy of the current scene, with meshes and scene
transforms scaled to the requested factor.
Parameters
-----------
scale : float
Factor to scale meshes and transforms
Returns
-----------
scaled : tr... | [
"def",
"scaled",
"(",
"self",
",",
"scale",
")",
":",
"scale",
"=",
"float",
"(",
"scale",
")",
"# matrix for 2D scaling",
"scale_2D",
"=",
"np",
".",
"eye",
"(",
"3",
")",
"*",
"scale",
"# matrix for 3D scaling",
"scale_3D",
"=",
"np",
".",
"eye",
"(",
... | 35.33871 | 14.983871 |
def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx):
"""Merge all columns and place text string in widened cell."""
hdridxval = len(self.hdrs) - 1
worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt)
return row_idx + 1 | [
"def",
"wr_row_mergeall",
"(",
"self",
",",
"worksheet",
",",
"txtstr",
",",
"fmt",
",",
"row_idx",
")",
":",
"hdridxval",
"=",
"len",
"(",
"self",
".",
"hdrs",
")",
"-",
"1",
"worksheet",
".",
"merge_range",
"(",
"row_idx",
",",
"0",
",",
"row_idx",
... | 53.4 | 13.8 |
def entry_line_to_text(self, entry):
"""
Return the textual representation of an :class:`~taxi.timesheet.lines.Entry` instance. This method is a bit
convoluted since we don't want to completely mess up the original formatting of the entry.
"""
line = []
# The entry is ne... | [
"def",
"entry_line_to_text",
"(",
"self",
",",
"entry",
")",
":",
"line",
"=",
"[",
"]",
"# The entry is new, it didn't come from an existing line, so let's just return a simple text representation of",
"# it",
"if",
"not",
"entry",
".",
"_text",
":",
"flags_text",
"=",
"... | 47.690476 | 30.595238 |
def fix_pix_borders(image2d, nreplace, sought_value, replacement_value):
"""Replace a few pixels at the borders of each spectrum.
Set to 'replacement_value' 'nreplace' pixels at the beginning (at
the end) of each spectrum just after (before) the spectrum value
changes from (to) 'sought_value', as seen ... | [
"def",
"fix_pix_borders",
"(",
"image2d",
",",
"nreplace",
",",
"sought_value",
",",
"replacement_value",
")",
":",
"# input image size",
"naxis2",
",",
"naxis1",
"=",
"image2d",
".",
"shape",
"for",
"i",
"in",
"range",
"(",
"naxis2",
")",
":",
"# only spectra... | 29.744681 | 19.93617 |
def _roll_random(n):
"""returns a random # from 0 to N-1"""
bits = util.bit_length(n - 1)
byte_count = (bits + 7) // 8
hbyte_mask = pow(2, bits % 8) - 1
# so here's the plan:
# we fetch as many random bits as we'd need to fit N-1, and if the
# generated number is >= N, we try again. in the... | [
"def",
"_roll_random",
"(",
"n",
")",
":",
"bits",
"=",
"util",
".",
"bit_length",
"(",
"n",
"-",
"1",
")",
"byte_count",
"=",
"(",
"bits",
"+",
"7",
")",
"//",
"8",
"hbyte_mask",
"=",
"pow",
"(",
"2",
",",
"bits",
"%",
"8",
")",
"-",
"1",
"#... | 37.6 | 18.6 |
def ParseFileObject(self, parser_mediator, file_object):
"""Parses a Firefox cache file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.
Raises:
... | [
"def",
"ParseFileObject",
"(",
"self",
",",
"parser_mediator",
",",
"file_object",
")",
":",
"filename",
"=",
"parser_mediator",
".",
"GetFilename",
"(",
")",
"if",
"(",
"not",
"self",
".",
"_CACHE_FILENAME_RE",
".",
"match",
"(",
"filename",
")",
"and",
"no... | 36.575758 | 22.757576 |
def get_matching_symbols_pairs(self, cursor, opening_symbol, closing_symbol, backward=False):
"""
Returns the cursor for matching given symbols pairs.
:param cursor: Cursor to match from.
:type cursor: QTextCursor
:param opening_symbol: Opening symbol.
:type opening_symb... | [
"def",
"get_matching_symbols_pairs",
"(",
"self",
",",
"cursor",
",",
"opening_symbol",
",",
"closing_symbol",
",",
"backward",
"=",
"False",
")",
":",
"if",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"start_position",
"=",
"cursor",
".",
"selectionEnd",
"(... | 46.297297 | 25.918919 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.