text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def input_file(self, _container):
"""Find the input path of a uchroot container."""
p = local.path(_container)
if set_input_container(p, CFG):
return
p = find_hash(CFG["container"]["known"].value, container)
if set_input_container(p, CFG):
return
... | [
"def",
"input_file",
"(",
"self",
",",
"_container",
")",
":",
"p",
"=",
"local",
".",
"path",
"(",
"_container",
")",
"if",
"set_input_container",
"(",
"p",
",",
"CFG",
")",
":",
"return",
"p",
"=",
"find_hash",
"(",
"CFG",
"[",
"\"container\"",
"]",
... | 33.727273 | 17.454545 |
def ip_rtm_config_route_static_route_nh_vrf_static_route_next_hop(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:br... | [
"def",
"ip_rtm_config_route_static_route_nh_vrf_static_route_next_hop",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ip",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ip\"",
",",
"xmlns",... | 61.352941 | 29.764706 |
def get_markdown_files(self, dir_):
"""
Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk.
"""
md_files = OrderedSet()
for root, _, files in os.walk(dir_):
for name in files:
split = os.... | [
"def",
"get_markdown_files",
"(",
"self",
",",
"dir_",
")",
":",
"md_files",
"=",
"OrderedSet",
"(",
")",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir_",
")",
":",
"for",
"name",
"in",
"files",
":",
"split",
"=",
"os",
... | 33.375 | 12.625 |
def proj_path(*path_parts):
# type: (str) -> str
""" Return absolute path to the repo dir (root project directory).
Args:
path (str):
The path relative to the project root (pelconf.yaml).
Returns:
str: The given path converted to an absolute path.
"""
path_parts = p... | [
"def",
"proj_path",
"(",
"*",
"path_parts",
")",
":",
"# type: (str) -> str",
"path_parts",
"=",
"path_parts",
"or",
"[",
"'.'",
"]",
"# If path represented by path_parts is absolute, do not modify it.",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path_parts",... | 29.333333 | 20.238095 |
def _update_axes_color(self, color):
"""Internal helper to set the axes label color"""
prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty()
prop_y = self.axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty()
prop_z = self.axes_actor.GetZAxisCaptionActor2D().G... | [
"def",
"_update_axes_color",
"(",
"self",
",",
"color",
")",
":",
"prop_x",
"=",
"self",
".",
"axes_actor",
".",
"GetXAxisCaptionActor2D",
"(",
")",
".",
"GetCaptionTextProperty",
"(",
")",
"prop_y",
"=",
"self",
".",
"axes_actor",
".",
"GetYAxisCaptionActor2D",... | 49.166667 | 17.416667 |
def make_published(self, request, queryset):
""" Bulk action to mark selected posts as published. If
the date_published field is empty the current time is
saved as date_published.
queryset must not be empty (ensured by DjangoCMS).
"""
cnt1 = queryset.filter(
... | [
"def",
"make_published",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"cnt1",
"=",
"queryset",
".",
"filter",
"(",
"date_published__isnull",
"=",
"True",
",",
"publish",
"=",
"False",
",",
")",
".",
"update",
"(",
"date_published",
"=",
"timezon... | 41.157895 | 9.473684 |
def get_slot(self):
"""
Get the slot position of this pair.
"""
corner, edge = self.get_pair()
corner_slot, edge_slot = corner.location.replace("D", "", 1), edge.location
if "U" not in corner_slot and corner_slot not in ["FR", "RB", "BL", "LF"]:
corner_slot = ... | [
"def",
"get_slot",
"(",
"self",
")",
":",
"corner",
",",
"edge",
"=",
"self",
".",
"get_pair",
"(",
")",
"corner_slot",
",",
"edge_slot",
"=",
"corner",
".",
"location",
".",
"replace",
"(",
"\"D\"",
",",
"\"\"",
",",
"1",
")",
",",
"edge",
".",
"l... | 56.428571 | 23.47619 |
def enable_nvm():
'''add to ~/.bashrc: Export of $NVM env variable and load nvm command.'''
bash_snippet = '~/.bashrc_nvm'
install_file_legacy(path=bash_snippet)
prefix = flo('if [ -f {bash_snippet} ]; ')
enabler = flo('if [ -f {bash_snippet} ]; then source {bash_snippet}; fi')
if env.host == '... | [
"def",
"enable_nvm",
"(",
")",
":",
"bash_snippet",
"=",
"'~/.bashrc_nvm'",
"install_file_legacy",
"(",
"path",
"=",
"bash_snippet",
")",
"prefix",
"=",
"flo",
"(",
"'if [ -f {bash_snippet} ]; '",
")",
"enabler",
"=",
"flo",
"(",
"'if [ -f {bash_snippet} ]; then sourc... | 48.727273 | 21.272727 |
def process_summary(article):
"""Ensures summaries are not cut off. Also inserts
mathjax script so that math will be rendered"""
summary = article.summary
summary_parsed = BeautifulSoup(summary, 'html.parser')
math = summary_parsed.find_all(class_='math')
if len(math) > 0:
last_math_te... | [
"def",
"process_summary",
"(",
"article",
")",
":",
"summary",
"=",
"article",
".",
"summary",
"summary_parsed",
"=",
"BeautifulSoup",
"(",
"summary",
",",
"'html.parser'",
")",
"math",
"=",
"summary_parsed",
".",
"find_all",
"(",
"class_",
"=",
"'math'",
")",... | 43.521739 | 21.913043 |
def _create_variables(self, n_features, W_=None, bh_=None, bv_=None):
"""Create the TensorFlow variables for the model.
:return: self
"""
if W_:
self.W_ = tf.Variable(W_, name='enc-w')
else:
self.W_ = tf.Variable(
tf.truncated_normal(
... | [
"def",
"_create_variables",
"(",
"self",
",",
"n_features",
",",
"W_",
"=",
"None",
",",
"bh_",
"=",
"None",
",",
"bv_",
"=",
"None",
")",
":",
"if",
"W_",
":",
"self",
".",
"W_",
"=",
"tf",
".",
"Variable",
"(",
"W_",
",",
"name",
"=",
"'enc-w'"... | 33.541667 | 20.458333 |
def poke(self, session, address, width, data):
"""Writes an 8, 16, 32, or 64-bit value from the specified address.
Corresponds to viPoke* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:pa... | [
"def",
"poke",
"(",
"self",
",",
"session",
",",
"address",
",",
"width",
",",
"data",
")",
":",
"if",
"width",
"==",
"8",
":",
"return",
"self",
".",
"poke_8",
"(",
"session",
",",
"address",
",",
"data",
")",
"elif",
"width",
"==",
"16",
":",
"... | 40 | 19.130435 |
def partition_source(src):
"""Partitions source into a list of `CodePartition`s for import
refactoring.
"""
# In python2, ast.parse(text_string_with_encoding_pragma) raises
# SyntaxError: encoding declaration in Unicode string
ast_obj = ast.parse(src.encode('UTF-8'))
visitor = TopLevelImport... | [
"def",
"partition_source",
"(",
"src",
")",
":",
"# In python2, ast.parse(text_string_with_encoding_pragma) raises",
"# SyntaxError: encoding declaration in Unicode string",
"ast_obj",
"=",
"ast",
".",
"parse",
"(",
"src",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
"visitor",... | 43.5 | 18.131579 |
def port_policy_present(name, sel_type, protocol=None, port=None, sel_range=None):
'''
.. versionadded:: 2019.2.0
Makes sure an SELinux port policy for a given port, protocol and SELinux context type is present.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)... | [
"def",
"port_policy_present",
"(",
"name",
",",
"sel_type",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"sel_range",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
... | 34.45283 | 24.90566 |
def _process_sasl_challenge(self, stream, element):
"""Process incoming <sasl:challenge/> element.
[initiating entity only]
"""
if not self.authenticator:
logger.debug("Unexpected SASL challenge")
return False
content = element.text.encode("us-ascii")
... | [
"def",
"_process_sasl_challenge",
"(",
"self",
",",
"stream",
",",
"element",
")",
":",
"if",
"not",
"self",
".",
"authenticator",
":",
"logger",
".",
"debug",
"(",
"\"Unexpected SASL challenge\"",
")",
"return",
"False",
"content",
"=",
"element",
".",
"text"... | 32.166667 | 17.041667 |
def GetHasherClasses(cls, hasher_names=None):
"""Retrieves the registered hashers.
Args:
hasher_names (list[str]): names of the hashers to retrieve.
Yields:
tuple: containing:
str: parser name
type: next hasher class.
"""
for hasher_name, hasher_class in iter(cls._... | [
"def",
"GetHasherClasses",
"(",
"cls",
",",
"hasher_names",
"=",
"None",
")",
":",
"for",
"hasher_name",
",",
"hasher_class",
"in",
"iter",
"(",
"cls",
".",
"_hasher_classes",
".",
"items",
"(",
")",
")",
":",
"if",
"not",
"hasher_names",
"or",
"hasher_nam... | 28.533333 | 19.666667 |
def index(ctx, view):
"""Index the database."""
adapter = ctx.obj['adapter']
if view:
click.echo(adapter.indexes())
return
adapter.ensure_indexes() | [
"def",
"index",
"(",
"ctx",
",",
"view",
")",
":",
"adapter",
"=",
"ctx",
".",
"obj",
"[",
"'adapter'",
"]",
"if",
"view",
":",
"click",
".",
"echo",
"(",
"adapter",
".",
"indexes",
"(",
")",
")",
"return",
"adapter",
".",
"ensure_indexes",
"(",
")... | 24.714286 | 13.714286 |
def _determine_os_workload_status(
configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Determine the state of the workload status for the charm.
This function returns the new workload status for the charm based
on the state of the interfaces, the paused state and w... | [
"def",
"_determine_os_workload_status",
"(",
"configs",
",",
"required_interfaces",
",",
"charm_func",
"=",
"None",
",",
"services",
"=",
"None",
",",
"ports",
"=",
"None",
")",
":",
"state",
",",
"message",
"=",
"_ows_check_if_paused",
"(",
"services",
",",
"... | 40.693878 | 23.77551 |
def status_human(self):
"""
Human readable status
:return:
* `DOWNLOADING`: the task is downloading files
* `BEING TRANSFERRED`: the task is being transferred
* `TRANSFERRED`: the task has been transferred to downloads \
directory
... | [
"def",
"status_human",
"(",
"self",
")",
":",
"res",
"=",
"None",
"if",
"self",
".",
"_deleted",
":",
"return",
"'DELETED'",
"if",
"self",
".",
"status",
"==",
"1",
":",
"res",
"=",
"'DOWNLOADING'",
"elif",
"self",
".",
"status",
"==",
"2",
":",
"if"... | 29.675676 | 14.972973 |
def mean_abs(self):
"""return the median of absolute values"""
# XXX rename this method
if len(self.values) > 0:
return sorted(map(abs, self.values))[len(self.values) / 2]
else:
return None | [
"def",
"mean_abs",
"(",
"self",
")",
":",
"# XXX rename this method",
"if",
"len",
"(",
"self",
".",
"values",
")",
">",
"0",
":",
"return",
"sorted",
"(",
"map",
"(",
"abs",
",",
"self",
".",
"values",
")",
")",
"[",
"len",
"(",
"self",
".",
"valu... | 34.142857 | 15.857143 |
def bitfieldify(buff, count):
"""Extract a bitarray out of a bytes array.
Some hardware devices read from the LSB to the MSB, but the bit types available prefer to put pad bits on the LSB side, completely changing the data.
This function takes in bytes and the number of bits to extract
starting from t... | [
"def",
"bitfieldify",
"(",
"buff",
",",
"count",
")",
":",
"databits",
"=",
"bitarray",
"(",
")",
"databits",
".",
"frombytes",
"(",
"buff",
")",
"return",
"databits",
"[",
"len",
"(",
"databits",
")",
"-",
"count",
":",
"]"
] | 38.416667 | 26.916667 |
def namedb_get_all_namespace_ids( cur ):
"""
Get a list of all READY namespace IDs.
"""
query = "SELECT namespace_id FROM namespaces WHERE op = ?;"
args = (NAMESPACE_READY,)
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
... | [
"def",
"namedb_get_all_namespace_ids",
"(",
"cur",
")",
":",
"query",
"=",
"\"SELECT namespace_id FROM namespaces WHERE op = ?;\"",
"args",
"=",
"(",
"NAMESPACE_READY",
",",
")",
"namespace_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")"... | 26.142857 | 17.285714 |
def _add_transaction_to_canonical_chain(db: BaseDB,
transaction_hash: Hash32,
block_header: BlockHeader,
index: int) -> None:
"""
:param bytes transaction_hash: the hash of... | [
"def",
"_add_transaction_to_canonical_chain",
"(",
"db",
":",
"BaseDB",
",",
"transaction_hash",
":",
"Hash32",
",",
"block_header",
":",
"BlockHeader",
",",
"index",
":",
"int",
")",
"->",
"None",
":",
"transaction_key",
"=",
"TransactionKey",
"(",
"block_header"... | 57.25 | 27.875 |
def node_type(node: astroid.node_classes.NodeNG) -> Optional[type]:
"""Return the inferred type for `node`
If there is more than one possible type, or if inferred type is Uninferable or None,
return None
"""
# check there is only one possible type for the assign node. Else we
# don't handle it ... | [
"def",
"node_type",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"Optional",
"[",
"type",
"]",
":",
"# check there is only one possible type for the assign node. Else we",
"# don't handle it for now",
"types",
"=",
"set",
"(",
")",
"try"... | 34.526316 | 18.157895 |
def print(self, txt: str, hold: bool=False) -> None:
""" Conditionally print txt
:param txt: text to print
:param hold: If true, hang on to the text until another print comes through
:param hold: If true, drop both print statements if another hasn't intervened
:return:
"... | [
"def",
"print",
"(",
"self",
",",
"txt",
":",
"str",
",",
"hold",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"hold",
":",
"self",
".",
"held_prints",
"[",
"self",
".",
"trace_depth",
"]",
"=",
"txt",
"elif",
"self",
".",
"held_prints"... | 40 | 18 |
def set_cursor_enter_callback(window, cbfun):
"""
Sets the cursor enter/exit callback.
Wrapper for:
GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER... | [
"def",
"set_cursor_enter_callback",
"(",
"window",
",",
"cbfun",
")",
":",
"window_addr",
"=",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"pointer",
"(",
"window",
")",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_long",
")",
")",
".",
"contents... | 39.666667 | 19.095238 |
def InternalRecv(self):
"""Receives a message from the device, including defragmenting it."""
first_read = self.InternalReadFrame()
first_packet = UsbHidTransport.InitPacket.FromWireFormat(self.packet_size,
first_read)
data = first_packet.pay... | [
"def",
"InternalRecv",
"(",
"self",
")",
":",
"first_read",
"=",
"self",
".",
"InternalReadFrame",
"(",
")",
"first_packet",
"=",
"UsbHidTransport",
".",
"InitPacket",
".",
"FromWireFormat",
"(",
"self",
".",
"packet_size",
",",
"first_read",
")",
"data",
"=",... | 39.4 | 21.714286 |
def set_host(ip, alias):
'''
Set the host entry in the hosts file for the given ip, this will overwrite
any previous entry for the given ip
.. versionchanged:: 2016.3.0
If ``alias`` does not include any host names (it is the empty
string or contains only whitespace), all entries for the... | [
"def",
"set_host",
"(",
"ip",
",",
"alias",
")",
":",
"hfn",
"=",
"_get_or_create_hostfile",
"(",
")",
"ovr",
"=",
"False",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"hfn",
")",
":",
"return",
"False",
"# Make sure future calls to _list_hosts() wil... | 30.892857 | 18.107143 |
def strainer(self):
"""
Determine whether it is required to run the MLST analyses
"""
# Initialise a variable to store whether the analyses need to be performed
analyse = list()
for sample in self.runmetadata.samples:
if sample.general.bestassemblyfile != 'NA'... | [
"def",
"strainer",
"(",
"self",
")",
":",
"# Initialise a variable to store whether the analyses need to be performed",
"analyse",
"=",
"list",
"(",
")",
"for",
"sample",
"in",
"self",
".",
"runmetadata",
".",
"samples",
":",
"if",
"sample",
".",
"general",
".",
"... | 56.953488 | 25.651163 |
def _get_dacl(path, objectType):
'''
Gets the DACL of a path
'''
try:
dacl = win32security.GetNamedSecurityInfo(
path, objectType, win32security.DACL_SECURITY_INFORMATION
).GetSecurityDescriptorDacl()
except Exception:
dacl = None
return dacl | [
"def",
"_get_dacl",
"(",
"path",
",",
"objectType",
")",
":",
"try",
":",
"dacl",
"=",
"win32security",
".",
"GetNamedSecurityInfo",
"(",
"path",
",",
"objectType",
",",
"win32security",
".",
"DACL_SECURITY_INFORMATION",
")",
".",
"GetSecurityDescriptorDacl",
"(",... | 26.909091 | 20.363636 |
def dict_array_bytes_required(arrays, template):
"""
Return the number of bytes required by
a dictionary of arrays.
Arguments
---------------
arrays : list
A list of dictionaries defining the arrays
template : dict
A dictionary of key-values, used to replace any
stri... | [
"def",
"dict_array_bytes_required",
"(",
"arrays",
",",
"template",
")",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"dict_array_bytes",
"(",
"ary",
",",
"template",
")",
"for",
"ary",
"in",
"arrays",
"]",
")"
] | 25.857143 | 17.47619 |
def collides(self, other):
"""Returns collision with axis aligned rect"""
angle = self.angle
width = self.width
height = self.height
if angle == 0:
return other.collides(Rect(-0.5 * width,
-0.5 * height, width, height))
... | [
"def",
"collides",
"(",
"self",
",",
"other",
")",
":",
"angle",
"=",
"self",
".",
"angle",
"width",
"=",
"self",
".",
"width",
"height",
"=",
"self",
".",
"height",
"if",
"angle",
"==",
"0",
":",
"return",
"other",
".",
"collides",
"(",
"Rect",
"(... | 32 | 22.258065 |
def calibration_plot(self, analytes=None, datarange=True, loglog=False, ncol=3, srm_group=None, save=True):
"""
Plot the calibration lines between measured and known SRM values.
Parameters
----------
analytes : optional, array_like or str
The analyte(s) to plot. Defaults to all analytes.
... | [
"def",
"calibration_plot",
"(",
"self",
",",
"analytes",
"=",
"None",
",",
"datarange",
"=",
"True",
",",
"loglog",
"=",
"False",
",",
"ncol",
"=",
"3",
",",
"srm_group",
"=",
"None",
",",
"save",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"anal... | 33.892 | 19.86 |
def append_json(
self,
obj: Any,
headers: Optional['MultiMapping[str]']=None
) -> Payload:
"""Helper to append JSON part."""
if headers is None:
headers = CIMultiDict()
return self.append_payload(JsonPayload(obj, headers=headers)) | [
"def",
"append_json",
"(",
"self",
",",
"obj",
":",
"Any",
",",
"headers",
":",
"Optional",
"[",
"'MultiMapping[str]'",
"]",
"=",
"None",
")",
"->",
"Payload",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"CIMultiDict",
"(",
")",
"return",
... | 29.8 | 19.1 |
def add_indices(self, indices, distance_matrix):
'''Adds extra indices for the combinatorial problem.
Arguments
---------
indices : tuple
distance_matrix : numpy.ndarray (M,M)
Example
-------
>>> add_indices((1,2), numpy.array((5,5)))
[(1, 2, 3),... | [
"def",
"add_indices",
"(",
"self",
",",
"indices",
",",
"distance_matrix",
")",
":",
"list_new_indices",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"distance_matrix",
")",
")",
":",
"if",
"i",
"not",
"in",
"indices",
":",
"l... | 28.263158 | 18.789474 |
def compile_dir(env, src_path, dst_path, pattern=r'^.*\.html$', encoding='utf-8', base_dir=None):
"""Compiles a directory of Jinja2 templates to python code.
:param env: a Jinja2 Environment instance.
:param src_path: path to the source directory.
:param dst_path: path to the destination directory.
:param ... | [
"def",
"compile_dir",
"(",
"env",
",",
"src_path",
",",
"dst_path",
",",
"pattern",
"=",
"r'^.*\\.html$'",
",",
"encoding",
"=",
"'utf-8'",
",",
"base_dir",
"=",
"None",
")",
":",
"from",
"os",
"import",
"path",
",",
"listdir",
",",
"mkdir",
"file_re",
"... | 39 | 19.833333 |
def more_cores(self, factor=1):
"""
Method to increase the number of MPI procs.
Return: new number of processors if success, 0 if processors cannot be increased.
"""
# TODO : find a formula that works for all max_cores
if self.max_cores > 40:
base_increase = 4 *... | [
"def",
"more_cores",
"(",
"self",
",",
"factor",
"=",
"1",
")",
":",
"# TODO : find a formula that works for all max_cores",
"if",
"self",
".",
"max_cores",
">",
"40",
":",
"base_increase",
"=",
"4",
"*",
"int",
"(",
"self",
".",
"max_cores",
"/",
"40",
")",... | 35.722222 | 20.388889 |
def get_env_pass(self,
user=None,
msg=None,
shutit_pexpect_child=None,
note=None):
"""Gets a password from the user if one is not already recorded for this environment.
@param user: username we are getting password for
@param msg: mes... | [
"def",
"get_env_pass",
"(",
"self",
",",
"user",
"=",
"None",
",",
"msg",
"=",
"None",
",",
"shutit_pexpect_child",
"=",
"None",
",",
"note",
"=",
"None",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"shutit_pexpect... | 46.75 | 17.75 |
def callback_url(self, request):
"""
the url to go back after the external service call
:param request: contains the current session
:type request: dict
:rtype: string
"""
service = self.service.split('Service')[1].lower()
return_to = '{ser... | [
"def",
"callback_url",
"(",
"self",
",",
"request",
")",
":",
"service",
"=",
"self",
".",
"service",
".",
"split",
"(",
"'Service'",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"return_to",
"=",
"'{service}_callback'",
".",
"format",
"(",
"service",
"... | 43.6 | 15.6 |
def get(self, queue_name, task_id):
"""
Pops a specific task off the queue by identifier.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:param task_id: The identifier of the task.
:type task_id:... | [
"def",
"get",
"(",
"self",
",",
"queue_name",
",",
"task_id",
")",
":",
"self",
".",
"conn",
".",
"lrem",
"(",
"queue_name",
",",
"1",
",",
"task_id",
")",
"data",
"=",
"self",
".",
"conn",
".",
"get",
"(",
"task_id",
")",
"if",
"data",
":",
"sel... | 27.5 | 16.2 |
def renders_impl(self, template_content, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING,
**kwargs):
"""
Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict... | [
"def",
"renders_impl",
"(",
"self",
",",
"template_content",
",",
"context",
",",
"at_paths",
"=",
"None",
",",
"at_encoding",
"=",
"anytemplate",
".",
"compat",
".",
"ENCODING",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer",
"=",
"self",
".",
"_make_rende... | 40.75 | 18.85 |
def write(self, data, params=None, expected_response_code=204,
protocol='json'):
"""Write data to InfluxDB.
:param data: the data to be written
:type data: (if protocol is 'json') dict
(if protocol is 'line') sequence of line protocol strings
... | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"params",
"=",
"None",
",",
"expected_response_code",
"=",
"204",
",",
"protocol",
"=",
"'json'",
")",
":",
"headers",
"=",
"self",
".",
"_headers",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/oc... | 35.333333 | 18.357143 |
def reset(self):
"""Request that host re-discovers plug-ins and re-processes selectors
A reset completely flushes the state of the GUI and reverts
back to how it was when it first got launched.
Pipeline:
______________ ____________ ______________
| ... | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"not",
"any",
"(",
"state",
"in",
"self",
".",
"states",
"for",
"state",
"in",
"(",
"\"ready\"",
",",
"\"finished\"",
")",
")",
":",
"return",
"self",
".",
"error",
".",
"emit",
"(",
"\"Not ready\"",
")",
... | 37.641379 | 21 |
def _get_default_arg(args, defaults, arg_index):
""" Method that determines if an argument has default value or not,
and if yes what is the default value for the argument
:param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']
:param defaults: array of default values, eg: (42, 'so... | [
"def",
"_get_default_arg",
"(",
"args",
",",
"defaults",
",",
"arg_index",
")",
":",
"if",
"not",
"defaults",
":",
"return",
"DefaultArgSpec",
"(",
"False",
",",
"None",
")",
"args_with_no_defaults",
"=",
"len",
"(",
"args",
")",
"-",
"len",
"(",
"defaults... | 45.208333 | 20.708333 |
def parse_output(self, s):
'''
Example output:
AVR Memory Usage
----------------
Device: atmega2561
Program: 4168 bytes (1.6% Full)
(.text + .data + .bootloader)
Data: 72 bytes (0.9% Full)
(.data + .bss + .noinit)
'''
... | [
"def",
"parse_output",
"(",
"self",
",",
"s",
")",
":",
"for",
"x",
"in",
"s",
".",
"splitlines",
"(",
")",
":",
"if",
"'%'",
"in",
"x",
":",
"name",
"=",
"x",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
".",
"lowe... | 30.214286 | 16.071429 |
def readline_completer(self, text, state):
"""
A completer for the readline library
"""
if state == 0:
# New completion, reset the list of matches and the display hook
self._readline_matches = []
try:
readline.set_completion_display_mat... | [
"def",
"readline_completer",
"(",
"self",
",",
"text",
",",
"state",
")",
":",
"if",
"state",
"==",
"0",
":",
"# New completion, reset the list of matches and the display hook",
"self",
".",
"_readline_matches",
"=",
"[",
"]",
"try",
":",
"readline",
".",
"set_com... | 35.380952 | 16.028571 |
def disambiguate_url(url, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation is localhost).
This is for zeromq urls, such as tcp://*:10101."""
try:
proto,ip,port = split_url(url)
except AssertionError:
... | [
"def",
"disambiguate_url",
"(",
"url",
",",
"location",
"=",
"None",
")",
":",
"try",
":",
"proto",
",",
"ip",
",",
"port",
"=",
"split_url",
"(",
"url",
")",
"except",
"AssertionError",
":",
"# probably not tcp url; could be ipc, etc.",
"return",
"url",
"ip",... | 33.357143 | 16.071429 |
def reclassify(layer, exposure_key=None, overwrite_input=False):
"""Reclassify a continuous raster layer.
Issue https://github.com/inasafe/inasafe/issues/3182
This function is a wrapper for the code from
https://github.com/chiatt/gdal_reclassify
For instance if you want to reclassify like this t... | [
"def",
"reclassify",
"(",
"layer",
",",
"exposure_key",
"=",
"None",
",",
"overwrite_input",
"=",
"False",
")",
":",
"output_layer_name",
"=",
"reclassify_raster_steps",
"[",
"'output_layer_name'",
"]",
"output_layer_name",
"=",
"output_layer_name",
"%",
"layer",
".... | 32.708661 | 20.291339 |
def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key):
"""Creates an AWS Chalice project for deployment to AWS Lambda."""
from canari.commands.create_aws_lambda import create_aws_lambda
create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_acce... | [
"def",
"create_aws_lambda",
"(",
"ctx",
",",
"bucket",
",",
"region_name",
",",
"aws_access_key_id",
",",
"aws_secret_access_key",
")",
":",
"from",
"canari",
".",
"commands",
".",
"create_aws_lambda",
"import",
"create_aws_lambda",
"create_aws_lambda",
"(",
"ctx",
... | 81 | 33.5 |
def create(self, resource):
"""Create a new config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.CREATE_SCHEMA
json = self.service.encode(schema,... | [
"def",
"create",
"(",
"self",
",",
"resource",
")",
":",
"schema",
"=",
"self",
".",
"CREATE_SCHEMA",
"json",
"=",
"self",
".",
"service",
".",
"encode",
"(",
"schema",
",",
"resource",
")",
"schema",
"=",
"self",
".",
"GET_SCHEMA",
"resp",
"=",
"self"... | 34.846154 | 15.615385 |
def getPorts(self):
"""acquire ports to be used by the SC2 client launched by this process"""
if self.ports: # no need to get ports if ports are al
return self.ports
if not self._gotPorts:
self.ports = [
portpicker.pick_unused_port(), # game_port
... | [
"def",
"getPorts",
"(",
"self",
")",
":",
"if",
"self",
".",
"ports",
":",
"# no need to get ports if ports are al",
"return",
"self",
".",
"ports",
"if",
"not",
"self",
".",
"_gotPorts",
":",
"self",
".",
"ports",
"=",
"[",
"portpicker",
".",
"pick_unused_p... | 42.083333 | 16.166667 |
def spd_eig(W, epsilon=1e-10, method='QR', canonical_signs=False):
""" Rank-reduced eigenvalue decomposition of symmetric positive definite matrix.
Removes all negligible eigenvalues
Parameters
----------
W : ndarray((n, n), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilo... | [
"def",
"spd_eig",
"(",
"W",
",",
"epsilon",
"=",
"1e-10",
",",
"method",
"=",
"'QR'",
",",
"canonical_signs",
"=",
"False",
")",
":",
"# check input",
"assert",
"_np",
".",
"allclose",
"(",
"W",
".",
"T",
",",
"W",
")",
",",
"'W is not a symmetric matrix... | 32.757576 | 22.560606 |
def put(self, path, value, timeout=None, event_timeout=None):
""""Puts a value to a path and returns when it completes
Args:
path (list): The path to put to
value (object): The value to set
timeout (float): time in seconds to wait for responses, wait forever
... | [
"def",
"put",
"(",
"self",
",",
"path",
",",
"value",
",",
"timeout",
"=",
"None",
",",
"event_timeout",
"=",
"None",
")",
":",
"future",
"=",
"self",
".",
"put_async",
"(",
"path",
",",
"value",
")",
"self",
".",
"wait_all_futures",
"(",
"future",
"... | 38.444444 | 17.388889 |
def mark_offer_as_clear(self, offer_id):
"""
Mark offer as clear
:param offer_id: the offer id
:return Response
"""
return self._create_put_request(
resource=OFFERS,
billomat_id=offer_id,
command=CLEAR,
) | [
"def",
"mark_offer_as_clear",
"(",
"self",
",",
"offer_id",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"OFFERS",
",",
"billomat_id",
"=",
"offer_id",
",",
"command",
"=",
"CLEAR",
",",
")"
] | 23.833333 | 11.333333 |
def clear_attributes(self):
"""
Remove the record_dict attribute from the object, as SeqRecords are not JSON-serializable. Also remove
the contig_lengths and longest_contig attributes, as they are large lists that make the .json file ugly
"""
for sample in self.metadata:
... | [
"def",
"clear_attributes",
"(",
"self",
")",
":",
"for",
"sample",
"in",
"self",
".",
"metadata",
":",
"try",
":",
"delattr",
"(",
"sample",
"[",
"self",
".",
"analysistype",
"]",
",",
"'record_dict'",
")",
"delattr",
"(",
"sample",
"[",
"self",
".",
"... | 48.083333 | 24.083333 |
def is_child_of_repository(self, id_, repository_id):
"""Tests if a node is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if the ``id`` is a child of
``repository_... | [
"def",
"is_child_of_repository",
"(",
"self",
",",
"id_",
",",
"repository_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_child_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_... | 51.75 | 20.5 |
def _bind_as(self, bind_dn, bind_password, sticky=False):
"""
Binds to the LDAP server with the given credentials. This does not trap
exceptions.
If sticky is True, then we will consider the connection to be bound for
the life of this object. If False, then the caller only wishe... | [
"def",
"_bind_as",
"(",
"self",
",",
"bind_dn",
",",
"bind_password",
",",
"sticky",
"=",
"False",
")",
":",
"self",
".",
"_get_connection",
"(",
")",
".",
"simple_bind_s",
"(",
"bind_dn",
",",
"bind_password",
")",
"self",
".",
"_connection_bound",
"=",
"... | 43.333333 | 25.166667 |
def maybe_dotted(module, throw=True):
""" If ``module`` is a dotted string pointing to the module,
imports and returns the module object.
"""
try:
return Configurator().maybe_dotted(module)
except ImportError as e:
err = '%s not found. %s' % (module, e)
if throw:
... | [
"def",
"maybe_dotted",
"(",
"module",
",",
"throw",
"=",
"True",
")",
":",
"try",
":",
"return",
"Configurator",
"(",
")",
".",
"maybe_dotted",
"(",
"module",
")",
"except",
"ImportError",
"as",
"e",
":",
"err",
"=",
"'%s not found. %s'",
"%",
"(",
"modu... | 30.384615 | 11.692308 |
def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
compression=None, mode=None):
"""
If the filepath_or_buffer is a url, translate and return the buffer.
Otherwise passthrough.
Parameters
----------
filepath_or_buffer : a url, filepath (str, py.path.local o... | [
"def",
"get_filepath_or_buffer",
"(",
"filepath_or_buffer",
",",
"encoding",
"=",
"None",
",",
"compression",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"filepath_or_buffer",
"=",
"_stringify_path",
"(",
"filepath_or_buffer",
")",
"if",
"_is_url",
"(",
"fi... | 38.636364 | 19.981818 |
def add(self, other):
"""Return the QuantumChannel self + other.
Args:
other (QuantumChannel): a quantum channel.
Returns:
SuperOp: the linear addition self + other as a SuperOp object.
Raises:
QiskitError: if other cannot be converted to a channel ... | [
"def",
"add",
"(",
"self",
",",
"other",
")",
":",
"# Convert other to SuperOp",
"if",
"not",
"isinstance",
"(",
"other",
",",
"SuperOp",
")",
":",
"other",
"=",
"SuperOp",
"(",
"other",
")",
"if",
"self",
".",
"dim",
"!=",
"other",
".",
"dim",
":",
... | 34.6 | 18.95 |
def seriesshape(self):
"""Shape of the whole time series (time being the first dimension)."""
seriesshape = [len(hydpy.pub.timegrids.init)]
seriesshape.extend(self.shape)
return tuple(seriesshape) | [
"def",
"seriesshape",
"(",
"self",
")",
":",
"seriesshape",
"=",
"[",
"len",
"(",
"hydpy",
".",
"pub",
".",
"timegrids",
".",
"init",
")",
"]",
"seriesshape",
".",
"extend",
"(",
"self",
".",
"shape",
")",
"return",
"tuple",
"(",
"seriesshape",
")"
] | 44.8 | 8 |
def confusion_matrix(exp, obs):
"""Create a confusion matrix
In each axis of the resulting confusion matrix the negative case is
0-index and the positive case 1-index. The labels get sorted, in a
True/False scenario true positives will occur at (1,1). The first dimension
(rows) of the resulting... | [
"def",
"confusion_matrix",
"(",
"exp",
",",
"obs",
")",
":",
"assert",
"len",
"(",
"exp",
")",
"==",
"len",
"(",
"obs",
")",
"# Expected in the first dimension (0;rows), observed in the second (1;cols)",
"lbls",
"=",
"sorted",
"(",
"set",
"(",
"exp",
")",
")",
... | 39.909091 | 17.772727 |
def project_inspect_template_path(cls, project, inspect_template):
"""Return a fully-qualified project_inspect_template string."""
return google.api_core.path_template.expand(
"projects/{project}/inspectTemplates/{inspect_template}",
project=project,
inspect_template=... | [
"def",
"project_inspect_template_path",
"(",
"cls",
",",
"project",
",",
"inspect_template",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/inspectTemplates/{inspect_template}\"",
",",
"project",
"=",
"proj... | 48.714286 | 16.571429 |
def renormalize(self, modelparams):
"""
Renormalizes one or more states represented as model
parameter vectors, such that each state has trace 1.
:param np.ndarray modelparams: Array of shape ``(n_states,
dim ** 2)`` representing one or more states as
model para... | [
"def",
"renormalize",
"(",
"self",
",",
"modelparams",
")",
":",
"# The 0th basis element (identity) should have",
"# a value 1 / sqrt{dim}, since the trace of that basis",
"# element is fixed to be sqrt{dim} by convention.",
"norm",
"=",
"modelparams",
"[",
":",
",",
"0",
"]",
... | 43.6875 | 13.9375 |
def numericalize(self, t:Collection[str]) -> List[int]:
"Convert a list of tokens `t` to their ids."
return [self.stoi[w] for w in t] | [
"def",
"numericalize",
"(",
"self",
",",
"t",
":",
"Collection",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"[",
"self",
".",
"stoi",
"[",
"w",
"]",
"for",
"w",
"in",
"t",
"]"
] | 49 | 9 |
def _is_broken_ref(key1, value1, key2, value2):
"""True if this is a broken reference; False otherwise."""
# A link followed by a string may represent a broken reference
if key1 != 'Link' or key2 != 'Str':
return False
# Assemble the parts
n = 0 if _PANDOCVERSION < '1.16' else 1
if isin... | [
"def",
"_is_broken_ref",
"(",
"key1",
",",
"value1",
",",
"key2",
",",
"value2",
")",
":",
"# A link followed by a string may represent a broken reference",
"if",
"key1",
"!=",
"'Link'",
"or",
"key2",
"!=",
"'Str'",
":",
"return",
"False",
"# Assemble the parts",
"n... | 37.9375 | 14.5625 |
def animate_cycle(self, colors, groups=('LEFT', 'RIGHT'), sleeptime=0.5, duration=5, block=True):
"""
Cycle ``groups`` LEDs through ``colors``. Do this in a loop where
we display each color for ``sleeptime`` seconds.
Animate for ``duration`` seconds. If ``duration`` is None animate for... | [
"def",
"animate_cycle",
"(",
"self",
",",
"colors",
",",
"groups",
"=",
"(",
"'LEFT'",
",",
"'RIGHT'",
")",
",",
"sleeptime",
"=",
"0.5",
",",
"duration",
"=",
"5",
",",
"block",
"=",
"True",
")",
":",
"def",
"_animate_cycle",
"(",
")",
":",
"index",... | 28.627907 | 23 |
def _ignore_comments(lines_enum):
"""
Strips comments and filter empty lines.
"""
for line_number, line in lines_enum:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line_number, line | [
"def",
"_ignore_comments",
"(",
"lines_enum",
")",
":",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"line",
"=",
"COMMENT_RE",
".",
"sub",
"(",
"''",
",",
"line",
")",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"y... | 27.444444 | 5.888889 |
def variance_increase_distance(cluster1, cluster2, data = None):
"""!
@brief Calculates variance increase distance between two clusters.
@details Clusters can be represented by list of coordinates (in this case data shouldn't be specified),
or by list of indexes of points from the data (rep... | [
"def",
"variance_increase_distance",
"(",
"cluster1",
",",
"cluster2",
",",
"data",
"=",
"None",
")",
":",
"# calculate local sum\r",
"if",
"data",
"is",
"None",
":",
"member_cluster1",
"=",
"[",
"0.0",
"]",
"*",
"len",
"(",
"cluster1",
"[",
"0",
"]",
")",... | 45.059701 | 30.089552 |
def options_handler(self, sock, cmd, opt):
"Negotiate options"
if cmd == NOP:
self.sendcommand(NOP)
elif cmd == WILL or cmd == WONT:
if self.WILLACK.has_key(opt):
self.sendcommand(self.WILLACK[opt], opt)
else:
self.sendcommand(D... | [
"def",
"options_handler",
"(",
"self",
",",
"sock",
",",
"cmd",
",",
"opt",
")",
":",
"if",
"cmd",
"==",
"NOP",
":",
"self",
".",
"sendcommand",
"(",
"NOP",
")",
"elif",
"cmd",
"==",
"WILL",
"or",
"cmd",
"==",
"WONT",
":",
"if",
"self",
".",
"WIL... | 37.032258 | 11.677419 |
def get_objects_in_sequence(brain_or_object, ctype, cref):
"""Return a list of items
"""
obj = api.get_object(brain_or_object)
if ctype == "backreference":
return get_backreferences(obj, cref)
if ctype == "contained":
return get_contained_items(obj, cref)
raise ValueError("Refere... | [
"def",
"get_objects_in_sequence",
"(",
"brain_or_object",
",",
"ctype",
",",
"cref",
")",
":",
"obj",
"=",
"api",
".",
"get_object",
"(",
"brain_or_object",
")",
"if",
"ctype",
"==",
"\"backreference\"",
":",
"return",
"get_backreferences",
"(",
"obj",
",",
"c... | 40.222222 | 9.555556 |
def does_not_raise(self, function, *args, **kwargs):
"""
Check if a function does not raise an exception,
*args and **kwargs are forwarded to the function
"""
try:
return function(*args, **kwargs)
except Exception as e:
self.log_error("{} d... | [
"def",
"does_not_raise",
"(",
"self",
",",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log_e... | 35.416667 | 11.75 |
def posthoc_tamhane(a, val_col=None, group_col=None, welch=True, sort=False):
'''Tamhane's T2 all-pairs comparison test for normally distributed data with
unequal variances. Tamhane's T2 test can be performed for all-pairs
comparisons in an one-factorial layout with normally distributed residuals
but u... | [
"def",
"posthoc_tamhane",
"(",
"a",
",",
"val_col",
"=",
"None",
",",
"group_col",
"=",
"None",
",",
"welch",
"=",
"True",
",",
"sort",
"=",
"False",
")",
":",
"x",
",",
"_val_col",
",",
"_group_col",
"=",
"__convert_to_df",
"(",
"a",
",",
"val_col",
... | 38.302752 | 29.220183 |
def allocate_observation_matrix(self):
"""!
@brief Allocates observation matrix in line with output dynamic of the network.
@details Matrix where state of each neuron is denoted by zero/one in line with Heaviside function on each iteration.
@return (list) Observation matrix... | [
"def",
"allocate_observation_matrix",
"(",
"self",
")",
":",
"number_neurons",
"=",
"len",
"(",
"self",
".",
"output",
"[",
"0",
"]",
")",
"observation_matrix",
"=",
"[",
"]",
"for",
"iteration",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"output",
")"... | 41.526316 | 22.526316 |
def from_passphrase(cls, passphrase=None):
""" Create keypair from a passphrase input (a brain wallet keypair)."""
if not passphrase:
# run a rejection sampling algorithm to ensure the private key is
# less than the curve order
while True:
passphrase =... | [
"def",
"from_passphrase",
"(",
"cls",
",",
"passphrase",
"=",
"None",
")",
":",
"if",
"not",
"passphrase",
":",
"# run a rejection sampling algorithm to ensure the private key is",
"# less than the curve order",
"while",
"True",
":",
"passphrase",
"=",
"create_passphrase",
... | 46.333333 | 19.055556 |
def normalize_files(files, separators=None):
"""
Normalizes the file paths to use the POSIX path separator.
*files* (:class:`~collections.abc.Iterable` of :class:`str`) contains
the file paths to be normalized.
*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
:data:`None`) optionally conta... | [
"def",
"normalize_files",
"(",
"files",
",",
"separators",
"=",
"None",
")",
":",
"norm_files",
"=",
"{",
"}",
"for",
"path",
"in",
"files",
":",
"norm_files",
"[",
"normalize_file",
"(",
"path",
",",
"separators",
"=",
"separators",
")",
"]",
"=",
"path... | 35.388889 | 20.944444 |
def configure(
cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
) -> None:
"""Configures the `AsyncHTTPClient` subclass to use.
``AsyncHTTPClient()`` actually creates an instance of a subclass.
This method may be called with either a class object or the
fully... | [
"def",
"configure",
"(",
"cls",
",",
"impl",
":",
"\"Union[None, str, Type[Configurable]]\"",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"super",
"(",
"AsyncHTTPClient",
",",
"cls",
")",
".",
"configure",
"(",
"impl",
",",
"*",
"*",
"kw... | 45.318182 | 27.636364 |
def _geoid_radius(latitude: float) -> float:
"""Calculates the GEOID radius at a given latitude
Parameters
----------
latitude : float
Latitude (degrees)
Returns
-------
R : float
GEOID Radius (meters)
"""
lat = deg2rad(latitude)
return sqrt(1/(cos(lat) ** 2 / R... | [
"def",
"_geoid_radius",
"(",
"latitude",
":",
"float",
")",
"->",
"float",
":",
"lat",
"=",
"deg2rad",
"(",
"latitude",
")",
"return",
"sqrt",
"(",
"1",
"/",
"(",
"cos",
"(",
"lat",
")",
"**",
"2",
"/",
"Rmax_WGS84",
"**",
"2",
"+",
"sin",
"(",
"... | 23.733333 | 21.666667 |
def get_change_type(self, ref, a1, a2):
"""
Given ref, allele1, and allele2, returns the type of change.
The only case of an amino acid insertion is when the ref is
represented as a '.'.
"""
if ref == '.':
return self.INSERTION
elif a1 == '.' or a2 == ... | [
"def",
"get_change_type",
"(",
"self",
",",
"ref",
",",
"a1",
",",
"a2",
")",
":",
"if",
"ref",
"==",
"'.'",
":",
"return",
"self",
".",
"INSERTION",
"elif",
"a1",
"==",
"'.'",
"or",
"a2",
"==",
"'.'",
":",
"return",
"self",
".",
"DELETION"
] | 34.8 | 10.4 |
def get_most_recent_event(self, originator_id, lt=None, lte=None):
"""
Gets a domain event from the sequence identified by `originator_id`
at the highest position.
:param originator_id: ID of a sequence of events
:param lt: get highest before this position
:param lte: ge... | [
"def",
"get_most_recent_event",
"(",
"self",
",",
"originator_id",
",",
"lt",
"=",
"None",
",",
"lte",
"=",
"None",
")",
":",
"events",
"=",
"self",
".",
"get_domain_events",
"(",
"originator_id",
"=",
"originator_id",
",",
"lt",
"=",
"lt",
",",
"lte",
"... | 38.3125 | 20.4375 |
def get_tables_and_gsis():
""" Get a set of tables and gsis and their configuration keys
:returns: set -- A set of tuples (table_name, table_conf_key)
"""
table_names = set()
configured_tables = get_configured_tables()
not_used_tables = set(configured_tables)
# Add regexp table names
f... | [
"def",
"get_tables_and_gsis",
"(",
")",
":",
"table_names",
"=",
"set",
"(",
")",
"configured_tables",
"=",
"get_configured_tables",
"(",
")",
"not_used_tables",
"=",
"set",
"(",
"configured_tables",
")",
"# Add regexp table names",
"for",
"table_instance",
"in",
"l... | 41.044444 | 19.4 |
def handle_input(self, ncode, wparam, lparam):
"""Process the key input."""
x_pos = lparam.contents.x_pos
y_pos = lparam.contents.y_pos
data = lparam.contents.mousedata
# This is how we can distinguish mouse 1 from mouse 2
# extrainfo = lparam.contents.extrainfo
... | [
"def",
"handle_input",
"(",
"self",
",",
"ncode",
",",
"wparam",
",",
"lparam",
")",
":",
"x_pos",
"=",
"lparam",
".",
"contents",
".",
"x_pos",
"y_pos",
"=",
"lparam",
".",
"contents",
".",
"y_pos",
"data",
"=",
"lparam",
".",
"contents",
".",
"moused... | 39.545455 | 16.727273 |
def loadByteArray(self, page, returnError):
"""Must be overridden. Must return a string with the loaded data."""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.")
return '' | [
"def",
"loadByteArray",
"(",
"self",
",",
"page",
",",
"returnError",
")",
":",
"returnError",
".",
"contents",
".",
"value",
"=",
"self",
".",
"IllegalStateError",
"raise",
"NotImplementedError",
"(",
"\"You must override this method.\"",
")",
"return",
"''"
] | 52.4 | 14.4 |
def add(name, function_name, cron):
""" Create an event """
lambder.add_event(name=name, function_name=function_name, cron=cron) | [
"def",
"add",
"(",
"name",
",",
"function_name",
",",
"cron",
")",
":",
"lambder",
".",
"add_event",
"(",
"name",
"=",
"name",
",",
"function_name",
"=",
"function_name",
",",
"cron",
"=",
"cron",
")"
] | 44.666667 | 12.333333 |
def find_by_typename(self, typename):
"""
List of all objects whose type has the given name.
"""
return self.find_by(lambda obj: type(obj).__name__ == typename) | [
"def",
"find_by_typename",
"(",
"self",
",",
"typename",
")",
":",
"return",
"self",
".",
"find_by",
"(",
"lambda",
"obj",
":",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"typename",
")"
] | 37.6 | 10.4 |
def filter_by(lookup_dict, grain='os_family', merge=None, default='default', base=None):
'''
.. versionadded:: 0.17.0
Look up the given grain in a given dictionary for the current OS and return
the result
Although this may occasionally be useful at the CLI, the primary intent of
this function ... | [
"def",
"filter_by",
"(",
"lookup_dict",
",",
"grain",
"=",
"'os_family'",
",",
"merge",
"=",
"None",
",",
"default",
"=",
"'default'",
",",
"base",
"=",
"None",
")",
":",
"return",
"salt",
".",
"utils",
".",
"data",
".",
"filter_by",
"(",
"lookup_dict",
... | 39.899083 | 28.743119 |
def _apply_postprocessing(marc_xml, xml, func, uuid, url):
"""
Apply `func` to all ``<mods:mods>`` tags from `xml`. Insert UUID.
Args:
marc_xml (str): Original Aleph record.
xml (str): XML which will be postprocessed.
func (fn): Function, which will be used for postprocessing.
... | [
"def",
"_apply_postprocessing",
"(",
"marc_xml",
",",
"xml",
",",
"func",
",",
"uuid",
",",
"url",
")",
":",
"dom",
"=",
"dhtmlparser",
".",
"parseString",
"(",
"xml",
")",
"return",
"[",
"func",
"(",
"marc_xml",
",",
"mods_tag",
",",
"uuid",
",",
"cnt... | 32.9 | 20.6 |
def ylim(self, low, high, index=1):
"""Set yaxis limits.
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
"""
self.layout['yaxis' + str(index)]['range'] = [low, high]
return sel... | [
"def",
"ylim",
"(",
"self",
",",
"low",
",",
"high",
",",
"index",
"=",
"1",
")",
":",
"self",
".",
"layout",
"[",
"'yaxis'",
"+",
"str",
"(",
"index",
")",
"]",
"[",
"'range'",
"]",
"=",
"[",
"low",
",",
"high",
"]",
"return",
"self"
] | 19.125 | 21.3125 |
def add_section(self, section):
"""Add a new Section object to the config. Should be a subclass of
_AbstractSection."""
if not issubclass(section.__class__, _AbstractSection):
raise TypeError("argument should be a subclass of Section")
self.sections[section.get_key_name()] = ... | [
"def",
"add_section",
"(",
"self",
",",
"section",
")",
":",
"if",
"not",
"issubclass",
"(",
"section",
".",
"__class__",
",",
"_AbstractSection",
")",
":",
"raise",
"TypeError",
"(",
"\"argument should be a subclass of Section\"",
")",
"self",
".",
"sections",
... | 49.142857 | 13.714286 |
def parse_atoms(self, pdb):
"""Parse the ATOM entries into the object"""
atomre = re.compile("ATOM")
atomlines = [line for line in pdb.lines if atomre.match(line)]
chainresnums = {}
for line in atomlines:
chain = line[21]
resname = line[17:20]
resnum = line[22:2... | [
"def",
"parse_atoms",
"(",
"self",
",",
"pdb",
")",
":",
"atomre",
"=",
"re",
".",
"compile",
"(",
"\"ATOM\"",
")",
"atomlines",
"=",
"[",
"line",
"for",
"line",
"in",
"pdb",
".",
"lines",
"if",
"atomre",
".",
"match",
"(",
"line",
")",
"]",
"chain... | 26.56 | 18.48 |
def _trigger_event(self, event, *args, **kwargs):
"""Invoke an event handler."""
run_async = kwargs.pop('run_async', False)
if event in self.handlers:
if run_async:
return self.start_background_task(self.handlers[event], *args)
else:
try:
... | [
"def",
"_trigger_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"run_async",
"=",
"kwargs",
".",
"pop",
"(",
"'run_async'",
",",
"False",
")",
"if",
"event",
"in",
"self",
".",
"handlers",
":",
"if",
"run_asyn... | 41.363636 | 16.272727 |
def parse_declaration_expressn_arrayliteral(self, values, es):
"""
Same in python. Just a square bracket enclosed array.
:param values:
:param es:
:return:
"""
es = es + '['
for ast in values:
es = es + self.parse_declaration_expressn(ast, es... | [
"def",
"parse_declaration_expressn_arrayliteral",
"(",
"self",
",",
"values",
",",
"es",
")",
":",
"es",
"=",
"es",
"+",
"'['",
"for",
"ast",
"in",
"values",
":",
"es",
"=",
"es",
"+",
"self",
".",
"parse_declaration_expressn",
"(",
"ast",
",",
"es",
"="... | 28.357143 | 18.357143 |
def getPrefilter(self,chn):
"""
Returns the prefilter of signal chn ("HP:0.1Hz", "LP:75Hz N:50Hz", etc.)
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
... | [
"def",
"getPrefilter",
"(",
"self",
",",
"chn",
")",
":",
"if",
"0",
"<=",
"chn",
"<",
"self",
".",
"signals_in_file",
":",
"return",
"self",
".",
"_convert_string",
"(",
"self",
".",
"prefilter",
"(",
"chn",
")",
".",
"rstrip",
"(",
")",
")",
"else"... | 24.565217 | 19.956522 |
def _update_loaded_modules(self):
"""
Updates the loaded modules by checking if they are still in sys.modules
"""
system_modules = sys.modules.keys()
for module in list(self.loaded_modules):
if module not in system_modules:
self.processed_filepaths.pop... | [
"def",
"_update_loaded_modules",
"(",
"self",
")",
":",
"system_modules",
"=",
"sys",
".",
"modules",
".",
"keys",
"(",
")",
"for",
"module",
"in",
"list",
"(",
"self",
".",
"loaded_modules",
")",
":",
"if",
"module",
"not",
"in",
"system_modules",
":",
... | 41.222222 | 9.222222 |
def _get_api_dependencies_of(name, version='', force=False):
'''Returns list of first level dependencies of the given dap from Dapi'''
m, d = _get_metadap_dap(name, version=version)
# We need the dependencies to install the dap,
# if the dap is unsupported, raise an exception here
if not force and n... | [
"def",
"_get_api_dependencies_of",
"(",
"name",
",",
"version",
"=",
"''",
",",
"force",
"=",
"False",
")",
":",
"m",
",",
"d",
"=",
"_get_metadap_dap",
"(",
"name",
",",
"version",
"=",
"version",
")",
"# We need the dependencies to install the dap,",
"# if the... | 52 | 18 |
def location_history(self, **params):
""" Method for `Read Device Location History <https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location-History>`_ endpoint.
:param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
... | [
"def",
"location_history",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"get",
"(",
"self",
".",
"subpath",
"(",
"'/location/waypoints'",
")",
",",
"params",
"=",
"params",
")"
] | 51.909091 | 30.636364 |
def find_connected_resources(resource, dependency_graph=None):
"""
Collects all resources connected to the given resource and returns a
dictionary mapping member resource classes to new collections containing
the members found.
"""
# Build a resource_graph.
resource_graph = \
... | [
"def",
"find_connected_resources",
"(",
"resource",
",",
"dependency_graph",
"=",
"None",
")",
":",
"# Build a resource_graph.",
"resource_graph",
"=",
"build_resource_graph",
"(",
"resource",
",",
"dependency_graph",
"=",
"dependency_graph",
")",
"entity_map",
"=",
"Or... | 37.210526 | 13.736842 |
def detect_traits(item):
""" Build traits list from attributes of the passed item. Currently,
"kind_51", "name" and "alias" are considered.
See pyrocore.util.traits:dectect_traits for more details.
"""
return traits.detect_traits(
name=item.name, alias=item.alias,
filetype=(... | [
"def",
"detect_traits",
"(",
"item",
")",
":",
"return",
"traits",
".",
"detect_traits",
"(",
"name",
"=",
"item",
".",
"name",
",",
"alias",
"=",
"item",
".",
"alias",
",",
"filetype",
"=",
"(",
"list",
"(",
"item",
".",
"fetch",
"(",
"\"kind_51\"",
... | 36.2 | 16.1 |
def is_local_import_from(node, package_name):
"""Check if a node is an import from the local package.
:param node: The node to check.
:type node: astroid.node.NodeNG
:param package_name: The name of the local package.
:type package_name: str
:returns: True if the node is an import from the lo... | [
"def",
"is_local_import_from",
"(",
"node",
",",
"package_name",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"ImportFrom",
")",
":",
"return",
"False",
"return",
"(",
"node",
".",
"level",
"or",
"node",
".",
"modname",
"==",
"p... | 26.952381 | 18.952381 |
def optimize(qs, info_dict, field_map):
"""Add either select_related or prefetch_related to fields of the qs"""
fields = collect_fields(info_dict)
for field in fields:
if field in field_map:
field_name, opt = field_map[field]
qs = (qs.prefetch_related(field_name)
... | [
"def",
"optimize",
"(",
"qs",
",",
"info_dict",
",",
"field_map",
")",
":",
"fields",
"=",
"collect_fields",
"(",
"info_dict",
")",
"for",
"field",
"in",
"fields",
":",
"if",
"field",
"in",
"field_map",
":",
"field_name",
",",
"opt",
"=",
"field_map",
"[... | 38.8 | 14.5 |
def validate(self, ip, **kwargs):
"""Check to see if this is a valid ip address."""
if ip is None:
return False
ip = stringify(ip)
if self.IPV4_REGEX.match(ip):
try:
socket.inet_pton(socket.AF_INET, ip)
return True
... | [
"def",
"validate",
"(",
"self",
",",
"ip",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ip",
"is",
"None",
":",
"return",
"False",
"ip",
"=",
"stringify",
"(",
"ip",
")",
"if",
"self",
".",
"IPV4_REGEX",
".",
"match",
"(",
"ip",
")",
":",
"try",
"... | 29.571429 | 16.607143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.