text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _add_vector(self, hash_name, bucket_key, v, data, redis_object):
'''
Store vector and JSON-serializable data in bucket with specified key.
'''
redis_key = self._format_redis_key(hash_name, bucket_key)
val_dict = {}
# Depending on type (sparse or not) fill value dict... | [
"def",
"_add_vector",
"(",
"self",
",",
"hash_name",
",",
"bucket_key",
",",
"v",
",",
"data",
",",
"redis_object",
")",
":",
"redis_key",
"=",
"self",
".",
"_format_redis_key",
"(",
"hash_name",
",",
"bucket_key",
")",
"val_dict",
"=",
"{",
"}",
"# Depend... | 35.076923 | 0.001422 |
def remove_child(self, idx=None, *, name=None, node=None):
"""Remove a child node from the current node instance.
:param idx: Index of child node to be removed.
:type idx: int
:param name: The first child node found with «name» will be removed.
:type name: str
:param n... | [
"def",
"remove_child",
"(",
"self",
",",
"idx",
"=",
"None",
",",
"*",
",",
"name",
"=",
"None",
",",
"node",
"=",
"None",
")",
":",
"if",
"(",
"idx",
"and",
"isinstance",
"(",
"idx",
",",
"int",
")",
"and",
"-",
"len",
"(",
"self",
".",
"child... | 37.714286 | 0.009234 |
def compare_password(expected, actual):
"""Compare two 64byte encoded passwords."""
if expected == actual:
return True, "OK"
msg = []
ver_exp = expected[-8:].rstrip()
ver_act = actual[-8:].rstrip()
if expected[:-8] != actual[:-8]:
msg.append("Password mismatch")
if ver_exp !... | [
"def",
"compare_password",
"(",
"expected",
",",
"actual",
")",
":",
"if",
"expected",
"==",
"actual",
":",
"return",
"True",
",",
"\"OK\"",
"msg",
"=",
"[",
"]",
"ver_exp",
"=",
"expected",
"[",
"-",
"8",
":",
"]",
".",
"rstrip",
"(",
")",
"ver_act"... | 34.142857 | 0.002037 |
def parse_include(self, node):
"""
Parses <Include>
@param node: Node containing the <Include> element
@type node: xml.etree.Element
@raise ParseError: Raised when the file to be included is not specified.
"""
if not self.include_includes:
if self.m... | [
"def",
"parse_include",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"self",
".",
"include_includes",
":",
"if",
"self",
".",
"model",
".",
"debug",
":",
"print",
"(",
"\"Ignoring included LEMS file: %s\"",
"%",
"node",
".",
"lattrib",
"[",
"'file'",
"... | 38.545455 | 0.011507 |
def server_systems(self):
"""
Retrieve a list of available systems.
"""
response = self._post(self.apiurl + "/v2/server/systems", data={'apikey': self.apikey})
return self._raise_or_extract(response) | [
"def",
"server_systems",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_post",
"(",
"self",
".",
"apiurl",
"+",
"\"/v2/server/systems\"",
",",
"data",
"=",
"{",
"'apikey'",
":",
"self",
".",
"apikey",
"}",
")",
"return",
"self",
".",
"_raise_or_e... | 33.428571 | 0.0125 |
def _check_region_for_parsing(number, default_region):
"""Checks to see that the region code used is valid, or if it is not
valid, that the number to parse starts with a + symbol so that we can
attempt to infer the region from the number. Returns False if it cannot
use the region provided and the regio... | [
"def",
"_check_region_for_parsing",
"(",
"number",
",",
"default_region",
")",
":",
"if",
"not",
"_is_valid_region_code",
"(",
"default_region",
")",
":",
"# If the number is None or empty, we can't infer the region.",
"if",
"number",
"is",
"None",
"or",
"len",
"(",
"nu... | 46 | 0.001522 |
def add_symbol(self, name, string=None):
"""
Add a symbol with key `name` to `scipy_data_fitting.Model.symbols`.
Optionally, specify an alternative `string` to pass to [`sympy.Symbol`][1],
otherwise `name` is used.
[1]: http://docs.sympy.org/dev/modules/core.html#id4
"""... | [
"def",
"add_symbol",
"(",
"self",
",",
"name",
",",
"string",
"=",
"None",
")",
":",
"if",
"not",
"string",
":",
"string",
"=",
"name",
"self",
".",
"symbols",
"[",
"name",
"]",
"=",
"sympy",
".",
"Symbol",
"(",
"string",
")"
] | 39.8 | 0.009828 |
def tfmer_clas_split(model:nn.Module) -> List[nn.Module]:
"Split a RNN `model` in groups for differential learning rates."
encoder = model[0].module
n = len(encoder.layers)//3
groups = [[encoder.encoder], list(encoder.layers[:n]), list(encoder.layers[n:2*n]), list(encoder.layers[2*n:])]
return group... | [
"def",
"tfmer_clas_split",
"(",
"model",
":",
"nn",
".",
"Module",
")",
"->",
"List",
"[",
"nn",
".",
"Module",
"]",
":",
"encoder",
"=",
"model",
"[",
"0",
"]",
".",
"module",
"n",
"=",
"len",
"(",
"encoder",
".",
"layers",
")",
"//",
"3",
"grou... | 55.166667 | 0.008929 |
def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **k... | [
"def",
"dispatch_hook",
"(",
"key",
",",
"hooks",
",",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
":",
"hooks",
"=",
"hooks",
"or",
"{",
"}",
"hooks",
"=",
"hooks",
".",
"get",
"(",
"key",
")",
"if",
"hooks",
":",
"if",
"hasattr",
"(",
"hooks",
"... | 34.5 | 0.002353 |
def run_cli_options(args):
"""
Quick implementation of Python interpreter's -m, -c and file execution.
The resulting dictionary is imported into global namespace, just in case
someone is using interactive mode.
We try to keep argument order as to pass them correctly to the subcommands.
"""
... | [
"def",
"run_cli_options",
"(",
"args",
")",
":",
"if",
"_interactive_mode",
"(",
"args",
".",
"interactive",
")",
":",
"os",
".",
"environ",
"[",
"'PYTHONINSPECT'",
"]",
"=",
"'1'",
"if",
"in_ipython",
"(",
")",
":",
"return",
"exclusive_choices",
"=",
"["... | 38.25 | 0.001912 |
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults... | [
"def",
"_validate_file_roots",
"(",
"file_roots",
")",
":",
"if",
"not",
"isinstance",
"(",
"file_roots",
",",
"dict",
")",
":",
"log",
".",
"warning",
"(",
"'The file_roots parameter is not properly formatted,'",
"' using defaults'",
")",
"return",
"{",
"'base'",
"... | 43.3 | 0.002262 |
def get_args(get_item):
"""Parse env, key, default out of input dict.
Args:
get_item: dict. contains keys env/key/default
Returns:
(env, key, has_default, default) tuple, where
env: str. env var name.
key: str. save env value to this context key.
has_def... | [
"def",
"get_args",
"(",
"get_item",
")",
":",
"if",
"not",
"isinstance",
"(",
"get_item",
",",
"dict",
")",
":",
"raise",
"ContextError",
"(",
"'envGet must contain a list of dicts.'",
")",
"env",
"=",
"get_item",
".",
"get",
"(",
"'env'",
",",
"None",
")",
... | 27.926829 | 0.000844 |
def rsem_calculate_expression(bam_file, rsem_genome_dir, samplename,
build, out_dir, cores=1):
"""
works only in unstranded mode for now (--forward-prob 0.5)
"""
if not utils.which("rsem-calculate-expression"):
logger.info("Skipping RSEM because rsem-calculate-expre... | [
"def",
"rsem_calculate_expression",
"(",
"bam_file",
",",
"rsem_genome_dir",
",",
"samplename",
",",
"build",
",",
"out_dir",
",",
"cores",
"=",
"1",
")",
":",
"if",
"not",
"utils",
".",
"which",
"(",
"\"rsem-calculate-expression\"",
")",
":",
"logger",
".",
... | 42.5 | 0.000885 |
def authenticated_request(self, endpoint, method='GET', params=None, data=None):
'''
Send a request to the given Wunderlist API with 'X-Access-Token' and 'X-Client-ID' headers and ensure the response code is as expected given the request type
Params:
endpoint -- API endpoint to send req... | [
"def",
"authenticated_request",
"(",
"self",
",",
"endpoint",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'X-Access-Token'",
":",
"self",
".",
"access_token",
",",
"'X-Client-ID'",
":",... | 43.117647 | 0.009346 |
def calc_zscale(self, data, contrast=0.25,
num_points=1000, num_per_row=None):
"""
From the IRAF documentation:
The zscale algorithm is designed to display the image values
near the median image value without the time consuming process of
computing a ful... | [
"def",
"calc_zscale",
"(",
"self",
",",
"data",
",",
"contrast",
"=",
"0.25",
",",
"num_points",
"=",
"1000",
",",
"num_per_row",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"data",
".",
"shape",
")",
">=",
"2",
",",
"AutoCutsError",
"(",
"\"input dat... | 40.502959 | 0.001996 |
def limits(self,x1,x2,y1,y2):
"""Set the coordinate boundaries of plot"""
import math
self.x1=x1
self.x2=x2
self.y1=y1
self.y2=y2
self.xscale=(self.cx2-self.cx1)/(self.x2-self.x1)
self.yscale=(self.cy2-self.cy1)/(self.y2-self.y1)
ra1=self.x1
ra2=self.x2... | [
"def",
"limits",
"(",
"self",
",",
"x1",
",",
"x2",
",",
"y1",
",",
"y2",
")",
":",
"import",
"math",
"self",
".",
"x1",
"=",
"x1",
"self",
".",
"x2",
"=",
"x2",
"self",
".",
"y1",
"=",
"y1",
"self",
".",
"y2",
"=",
"y2",
"self",
".",
"xsca... | 27.526316 | 0.07024 |
def backup_location(src, loc=None):
'''
Writes Backups of locations
:param src:
The source file/folder to backup
:param loc:
The target folder to backup into
The backup will be called `src` + :func:`util.system.get_timestamp`.
* If `loc` left to none, the backup gets wr... | [
"def",
"backup_location",
"(",
"src",
",",
"loc",
"=",
"None",
")",
":",
"from",
"photon",
".",
"util",
".",
"system",
"import",
"get_timestamp",
"src",
"=",
"_path",
".",
"realpath",
"(",
"src",
")",
"if",
"not",
"loc",
"or",
"not",
"loc",
".",
"sta... | 29.384615 | 0.001267 |
def all_equal(left, right, cache=None):
"""Check whether two objects `left` and `right` are equal.
Parameters
----------
left : Union[object, Expr, Node]
right : Union[object, Expr, Node]
cache : Optional[Dict[Tuple[Node, Node], bool]]
A dictionary indicating whether two Nodes are equal... | [
"def",
"all_equal",
"(",
"left",
",",
"right",
",",
"cache",
"=",
"None",
")",
":",
"if",
"cache",
"is",
"None",
":",
"cache",
"=",
"{",
"}",
"if",
"util",
".",
"is_iterable",
"(",
"left",
")",
":",
"# check that left and right are equal length iterables and... | 29.758621 | 0.001122 |
def sentence_texts(self):
"""The list of texts representing ``sentences`` layer elements."""
if not self.is_tagged(SENTENCES):
self.tokenize_sentences()
return self.texts(SENTENCES) | [
"def",
"sentence_texts",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"SENTENCES",
")",
":",
"self",
".",
"tokenize_sentences",
"(",
")",
"return",
"self",
".",
"texts",
"(",
"SENTENCES",
")"
] | 42.6 | 0.009217 |
def max(self):
"""
The maximum integer value of a value-set. It is only defined when there is exactly one region.
:return: A integer that represents the maximum integer value of this value-set.
:rtype: int
"""
if len(self.regions) != 1:
raise ClaripyVSAOper... | [
"def",
"max",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"regions",
")",
"!=",
"1",
":",
"raise",
"ClaripyVSAOperationError",
"(",
"\"'max()' onlly works on single-region value-sets.\"",
")",
"return",
"self",
".",
"get_si",
"(",
"next",
"(",
"iter"... | 35.75 | 0.011364 |
def _get_baremetal_switches(self, port):
"""Get switch ip addresses from baremetal transaction.
This method is used to extract switch information
from the transaction where VNIC_TYPE is baremetal.
:param port: Received port transaction
:returns: list of all switches
:re... | [
"def",
"_get_baremetal_switches",
"(",
"self",
",",
"port",
")",
":",
"all_switches",
"=",
"set",
"(",
")",
"active_switches",
"=",
"set",
"(",
")",
"all_link_info",
"=",
"port",
"[",
"bc",
".",
"portbindings",
".",
"PROFILE",
"]",
"[",
"'local_link_informat... | 34.827586 | 0.001927 |
def check_permission(self, identifiers, permission_s, logical_operator):
"""
like Yosai's authentication process, the authorization process will
raise an Exception to halt further authz checking once Yosai determines
that a Subject is unauthorized to receive the requested permission
... | [
"def",
"check_permission",
"(",
"self",
",",
"identifiers",
",",
"permission_s",
",",
"logical_operator",
")",
":",
"self",
".",
"assert_realms_configured",
"(",
")",
"permitted",
"=",
"self",
".",
"is_permitted_collective",
"(",
"identifiers",
",",
"permission_s",
... | 48 | 0.001634 |
def adsb_vehicle_encode(self, ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, callsign, emitter_type, tslc, flags, squawk):
'''
The location and information of an ADSB vehicle
ICAO_address : ICAO address (uint32_t)
... | [
"def",
"adsb_vehicle_encode",
"(",
"self",
",",
"ICAO_address",
",",
"lat",
",",
"lon",
",",
"altitude_type",
",",
"altitude",
",",
"heading",
",",
"hor_velocity",
",",
"ver_velocity",
",",
"callsign",
",",
"emitter_type",
",",
"tslc",
",",
"flags",
",",
"sq... | 79.85 | 0.008663 |
def inode(self):
"""Return the inode number of the entry."""
if self._inode is None:
self.stat(follow_symlinks=False)
return self._inode | [
"def",
"inode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_inode",
"is",
"None",
":",
"self",
".",
"stat",
"(",
"follow_symlinks",
"=",
"False",
")",
"return",
"self",
".",
"_inode"
] | 33.6 | 0.011628 |
def fetch_withdrawals(self, limit: int) -> List[Withdrawal]:
"""Fetch latest withdrawals, must provide a limit."""
return self._transactions(self._withdrawals, 'withdrawals', limit) | [
"def",
"fetch_withdrawals",
"(",
"self",
",",
"limit",
":",
"int",
")",
"->",
"List",
"[",
"Withdrawal",
"]",
":",
"return",
"self",
".",
"_transactions",
"(",
"self",
".",
"_withdrawals",
",",
"'withdrawals'",
",",
"limit",
")"
] | 65 | 0.010152 |
def match_bitap(self, text, pattern, loc):
"""Locate the best instance of 'pattern' in 'text' near 'loc' using the
Bitap algorithm.
Args:
text: The text to search.
pattern: The pattern to search for.
loc: The location to search around.
Returns:
Best match index or -1.
"""
... | [
"def",
"match_bitap",
"(",
"self",
",",
"text",
",",
"pattern",
",",
"loc",
")",
":",
"# Python doesn't have a maxint limit, so ignore this check.",
"#if self.Match_MaxBits != 0 and len(pattern) > self.Match_MaxBits:",
"# raise ValueError(\"Pattern too long for this application.\")",
... | 35.342857 | 0.011009 |
def _sprite_map(g, **kwargs):
"""
Generates a sprite map from the files matching the glob pattern.
Uses the keyword-style arguments passed in to control the placement.
"""
g = StringValue(g).value
if not Image:
raise Exception("Images manipulation require PIL")
if g in sprite_maps:... | [
"def",
"_sprite_map",
"(",
"g",
",",
"*",
"*",
"kwargs",
")",
":",
"g",
"=",
"StringValue",
"(",
"g",
")",
".",
"value",
"if",
"not",
"Image",
":",
"raise",
"Exception",
"(",
"\"Images manipulation require PIL\"",
")",
"if",
"g",
"in",
"sprite_maps",
":"... | 43.248705 | 0.000703 |
def get_cluster_health(
self, nodes_health_state_filter=0, applications_health_state_filter=0, events_health_state_filter=0, exclude_health_statistics=False, include_system_application_health_statistics=False, timeout=60, custom_headers=None, raw=False, **operation_config):
"""Gets the health of a S... | [
"def",
"get_cluster_health",
"(",
"self",
",",
"nodes_health_state_filter",
"=",
"0",
",",
"applications_health_state_filter",
"=",
"0",
",",
"events_health_state_filter",
"=",
"0",
",",
"exclude_health_statistics",
"=",
"False",
",",
"include_system_application_health_stat... | 56.306748 | 0.001071 |
def export_data_json(self, return_response_object,
chunk_size=1024,
path=None,
data_type_name=None, date_range=None,
delimiter=None, start_date_time=None,
end_date_time=None, omit_fields=None,
only_fields=None, campaign_id=None):
"""
Custom Keyword arguments:
1. return_resp... | [
"def",
"export_data_json",
"(",
"self",
",",
"return_response_object",
",",
"chunk_size",
"=",
"1024",
",",
"path",
"=",
"None",
",",
"data_type_name",
"=",
"None",
",",
"date_range",
"=",
"None",
",",
"delimiter",
"=",
"None",
",",
"start_date_time",
"=",
"... | 33.045455 | 0.036509 |
def add_zone(self, spatial_unit, container_id, name='', description='', visible=True, reuse=0, drop_behavior_type=None):
"""container_id is a targetId that the zone belongs to
"""
if not isinstance(spatial_unit, abc_mapping_primitives.SpatialUnit):
raise InvalidArgument('zone is not ... | [
"def",
"add_zone",
"(",
"self",
",",
"spatial_unit",
",",
"container_id",
",",
"name",
"=",
"''",
",",
"description",
"=",
"''",
",",
"visible",
"=",
"True",
",",
"reuse",
"=",
"0",
",",
"drop_behavior_type",
"=",
"None",
")",
":",
"if",
"not",
"isinst... | 46.862069 | 0.002163 |
def sectionWalker(section,callback,*args,walkTrace=tuple(),**kwargs):
"""
callback needs to be a function that handles different
Section elements appropriately
walkTrace needs to be a tuple, indicate the route to the section, e.g. (1,2,0)
"""
callback(section,*args,walkT... | [
"def",
"sectionWalker",
"(",
"section",
",",
"callback",
",",
"*",
"args",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"callback",
"(",
"section",
",",
"*",
"args",
",",
"walkTrace",
"=",
"walkTrace",
",",
"case",
"="... | 49.3125 | 0.03607 |
def initialize():
"""IMPORTANT: Call this function at the beginning of your program."""
try:
requests.get('http://localhost:4242/poll')
state['connected_to_bot'] = True
except requests.exceptions.ConnectionError:
state['connected_to_bot'] = False
# set up turtle
state['windo... | [
"def",
"initialize",
"(",
")",
":",
"try",
":",
"requests",
".",
"get",
"(",
"'http://localhost:4242/poll'",
")",
"state",
"[",
"'connected_to_bot'",
"]",
"=",
"True",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
":",
"state",
"[",
"'connec... | 30.764706 | 0.001855 |
def _get_children_path_interval(cls, path):
""":returns: An interval of all possible children paths for a node."""
return (path + cls.alphabet[0] * cls.steplen,
path + cls.alphabet[-1] * cls.steplen) | [
"def",
"_get_children_path_interval",
"(",
"cls",
",",
"path",
")",
":",
"return",
"(",
"path",
"+",
"cls",
".",
"alphabet",
"[",
"0",
"]",
"*",
"cls",
".",
"steplen",
",",
"path",
"+",
"cls",
".",
"alphabet",
"[",
"-",
"1",
"]",
"*",
"cls",
".",
... | 57 | 0.008658 |
def com_google_fonts_check_metadata_valid_copyright(font_metadata):
"""Copyright notices match canonical pattern in METADATA.pb"""
import re
string = font_metadata.copyright
does_match = re.search(r'Copyright [0-9]{4} The .* Project Authors \([^\@]*\)',
string)
if does_match:
yi... | [
"def",
"com_google_fonts_check_metadata_valid_copyright",
"(",
"font_metadata",
")",
":",
"import",
"re",
"string",
"=",
"font_metadata",
".",
"copyright",
"does_match",
"=",
"re",
".",
"search",
"(",
"r'Copyright [0-9]{4} The .* Project Authors \\([^\\@]*\\)'",
",",
"strin... | 43.466667 | 0.013514 |
def segment_allocation_find(context, lock_mode=False, **filters):
"""Query for segment allocations."""
range_ids = filters.pop("segment_allocation_range_ids", None)
query = context.session.query(models.SegmentAllocation)
if lock_mode:
query = query.with_lockmode("update")
query = query.fil... | [
"def",
"segment_allocation_find",
"(",
"context",
",",
"lock_mode",
"=",
"False",
",",
"*",
"*",
"filters",
")",
":",
"range_ids",
"=",
"filters",
".",
"pop",
"(",
"\"segment_allocation_range_ids\"",
",",
"None",
")",
"query",
"=",
"context",
".",
"session",
... | 33.0625 | 0.001838 |
def add_node(self, node):
""" Add a node to this network, let the node know which network it's on. """
if _debug: Network._debug("add_node %r", node)
self.nodes.append(node)
node.lan = self
# update the node name
if not node.name:
node.name = '%s:%s' % (self... | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"_debug",
":",
"Network",
".",
"_debug",
"(",
"\"add_node %r\"",
",",
"node",
")",
"self",
".",
"nodes",
".",
"append",
"(",
"node",
")",
"node",
".",
"lan",
"=",
"self",
"# update the node n... | 33.1 | 0.011765 |
def expect_regex(self, pattern, timeout=3, regex_options=0):
"""Wait for a match to the regex in *pattern* to appear on the stream.
Waits for input matching the regex *pattern* for up to *timeout*
seconds. If a match is found, a :class:`RegexMatch` result is returned.
If no match is fou... | [
"def",
"expect_regex",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"3",
",",
"regex_options",
"=",
"0",
")",
":",
"return",
"self",
".",
"expect",
"(",
"RegexSearcher",
"(",
"pattern",
",",
"regex_options",
")",
",",
"timeout",
")"
] | 53.533333 | 0.002448 |
def delete(self, id=None, q=None, commit=None, softCommit=False, waitFlush=None, waitSearcher=None, handler='update'): # NOQA: A002
"""
Deletes documents.
Requires *either* ``id`` or ``query``. ``id`` is if you know the
specific document id to remove. Note that ``id`` can also be a lis... | [
"def",
"delete",
"(",
"self",
",",
"id",
"=",
"None",
",",
"q",
"=",
"None",
",",
"commit",
"=",
"None",
",",
"softCommit",
"=",
"False",
",",
"waitFlush",
"=",
"None",
",",
"waitSearcher",
"=",
"None",
",",
"handler",
"=",
"'update'",
")",
":",
"#... | 40.146341 | 0.002372 |
def add_row_group(self, tables, collapsed=True):
"""
Adds a group over all the given tables (will include any rows between the first row over all
tables, and the last row over all tables)
Initially collapsed if collapsed is True (True by default)
"""
self.__groups.append(... | [
"def",
"add_row_group",
"(",
"self",
",",
"tables",
",",
"collapsed",
"=",
"True",
")",
":",
"self",
".",
"__groups",
".",
"append",
"(",
"(",
"tables",
",",
"collapsed",
")",
")"
] | 47.714286 | 0.008824 |
def sine(x):
'''
sine(x) is equivalent to sin(x) except that it also works on sparse arrays.
'''
if sps.issparse(x):
x = x.copy()
x.data = np.sine(x.data)
return x
else: return np.sin(x) | [
"def",
"sine",
"(",
"x",
")",
":",
"if",
"sps",
".",
"issparse",
"(",
"x",
")",
":",
"x",
"=",
"x",
".",
"copy",
"(",
")",
"x",
".",
"data",
"=",
"np",
".",
"sine",
"(",
"x",
".",
"data",
")",
"return",
"x",
"else",
":",
"return",
"np",
"... | 24.666667 | 0.008696 |
def trans(ele, standard=False):
"""Translates esprima syntax tree to python by delegating to appropriate translating node"""
try:
node = globals().get(ele['type'])
if not node:
raise NotImplementedError('%s is not supported!' % ele['type'])
if standard:
node = nod... | [
"def",
"trans",
"(",
"ele",
",",
"standard",
"=",
"False",
")",
":",
"try",
":",
"node",
"=",
"globals",
"(",
")",
".",
"get",
"(",
"ele",
"[",
"'type'",
"]",
")",
"if",
"not",
"node",
":",
"raise",
"NotImplementedError",
"(",
"'%s is not supported!'",... | 35.384615 | 0.008475 |
def macshim():
"""Shim to run 32-bit on 64-bit mac as a sub-process"""
import subprocess, sys
subprocess.call([
sys.argv[0] + '32'
]+sys.argv[1:],
env={"VERSIONER_PYTHON_PREFER_32_BIT":"yes"}
) | [
"def",
"macshim",
"(",
")",
":",
"import",
"subprocess",
",",
"sys",
"subprocess",
".",
"call",
"(",
"[",
"sys",
".",
"argv",
"[",
"0",
"]",
"+",
"'32'",
"]",
"+",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"env",
"=",
"{",
"\"VERSIONER_PYTHON_... | 27.875 | 0.017391 |
def generate_timestamped_string(subject="test", number_of_random_chars=4):
"""
Generate time-stamped string. Format as follows...
`2013-01-31_14:12:23_SubjectString_a3Zg`
Kwargs:
subject (str): String to use as subject.
number_of_random_chars (int) : Number of random characters to app... | [
"def",
"generate_timestamped_string",
"(",
"subject",
"=",
"\"test\"",
",",
"number_of_random_chars",
"=",
"4",
")",
":",
"random_str",
"=",
"generate_random_string",
"(",
"number_of_random_chars",
")",
"timestamp",
"=",
"generate_timestamp",
"(",
")",
"return",
"u\"{... | 38.291667 | 0.002123 |
def cardinality(self):
'''
Obtain the cardinality string.
Example: '1C' for a conditional link with a single instance [0..1]
'MC' for a link with any number of instances [0..*]
'M' for a more than one instance [1..*]
'M' for a link wi... | [
"def",
"cardinality",
"(",
"self",
")",
":",
"if",
"self",
".",
"many",
":",
"s",
"=",
"'M'",
"else",
":",
"s",
"=",
"'1'",
"if",
"self",
".",
"conditional",
":",
"s",
"+=",
"'C'",
"return",
"s"
] | 28.388889 | 0.00947 |
def normalize_name(s):
"""Convert a string into a valid python attribute name.
This function is called to convert ASCII strings to something that can pass as
python attribute name, to be used with namedtuples.
>>> str(normalize_name('class'))
'class_'
>>> str(normalize_name('a-name'))
'a_na... | [
"def",
"normalize_name",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"replace",
"(",
"'.'",
",",
"'_'",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"if",
"s",
"in",
"keyword",
".",
"kwlist",
":",
... | 28.962963 | 0.002475 |
def validate(self, result, spec): # noqa Yes, it's too complex.
"""Validate that the result has the correct structure."""
if spec is None:
# None matches anything.
return
if isinstance(spec, dict):
if not isinstance(result, dict):
raise ValueE... | [
"def",
"validate",
"(",
"self",
",",
"result",
",",
"spec",
")",
":",
"# noqa Yes, it's too complex.",
"if",
"spec",
"is",
"None",
":",
"# None matches anything.",
"return",
"if",
"isinstance",
"(",
"spec",
",",
"dict",
")",
":",
"if",
"not",
"isinstance",
"... | 48.026316 | 0.001074 |
def rnow(
format='%Y-%m-%d %H:%M:%S',
in_utc=False):
"""rnow
Get right now as a string formatted datetime
:param format: string output format for datetime
:param in_utc: bool timezone in utc or local time
"""
if in_utc:
return datetime.datetime.utcnow().strftime(
... | [
"def",
"rnow",
"(",
"format",
"=",
"'%Y-%m-%d %H:%M:%S'",
",",
"in_utc",
"=",
"False",
")",
":",
"if",
"in_utc",
":",
"return",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"format",
")",
"else",
":",
"return",
"datetime",
... | 23.352941 | 0.002421 |
def log_trial(args):
''''get trial log path'''
trial_id_path_dict = {}
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not runn... | [
"def",
"log_trial",
"(",
"args",
")",
":",
"trial_id_path_dict",
"=",
"{",
"}",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"rest_pid",
"=",
... | 38.65625 | 0.001577 |
async def pong(self, message: bytes=b'') -> None:
"""Send pong message."""
if isinstance(message, str):
message = message.encode('utf-8')
await self._send_frame(message, WSMsgType.PONG) | [
"async",
"def",
"pong",
"(",
"self",
",",
"message",
":",
"bytes",
"=",
"b''",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"message",
",",
"str",
")",
":",
"message",
"=",
"message",
".",
"encode",
"(",
"'utf-8'",
")",
"await",
"self",
".",
"_... | 43.4 | 0.0181 |
def write_json(json_obj, filename, mode="w", print_pretty=True):
'''write_json will (optionally,pretty print) a json object to file
Parameters
==========
json_obj: the dict to print to json
filename: the output file to write to
pretty_print: if True, will use nicer formatting
... | [
"def",
"write_json",
"(",
"json_obj",
",",
"filename",
",",
"mode",
"=",
"\"w\"",
",",
"print_pretty",
"=",
"True",
")",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"filey",
":",
"if",
"print_pretty",
":",
"filey",
".",
"writelines",
... | 34.066667 | 0.001905 |
def query(self, query):
'''Returns objects matching criteria expressed in `query`. Follows links.'''
results = super(SymlinkDatastore, self).query(query)
return self._follow_link_gen(results) | [
"def",
"query",
"(",
"self",
",",
"query",
")",
":",
"results",
"=",
"super",
"(",
"SymlinkDatastore",
",",
"self",
")",
".",
"query",
"(",
"query",
")",
"return",
"self",
".",
"_follow_link_gen",
"(",
"results",
")"
] | 50 | 0.009852 |
def Fold(seglist1, seglist2):
"""
An iterator that generates the results of taking the intersection
of seglist1 with each segment in seglist2 in turn. In each result,
the segment start and stop values are adjusted to be with respect
to the start of the corresponding segment in seglist2. See also
the segmentlist... | [
"def",
"Fold",
"(",
"seglist1",
",",
"seglist2",
")",
":",
"for",
"seg",
"in",
"seglist2",
":",
"yield",
"(",
"seglist1",
"&",
"segments",
".",
"segmentlist",
"(",
"[",
"seg",
"]",
")",
")",
".",
"shift",
"(",
"-",
"seg",
"[",
"0",
"]",
")"
] | 37.666667 | 0.022654 |
def FindUniqueId(dic):
"""Return a string not used as a key in the dictionary dic"""
name = str(len(dic))
while name in dic:
# Use bigger numbers so it is obvious when an id is picked randomly.
name = str(random.randint(1000000, 999999999))
return name | [
"def",
"FindUniqueId",
"(",
"dic",
")",
":",
"name",
"=",
"str",
"(",
"len",
"(",
"dic",
")",
")",
"while",
"name",
"in",
"dic",
":",
"# Use bigger numbers so it is obvious when an id is picked randomly.",
"name",
"=",
"str",
"(",
"random",
".",
"randint",
"("... | 37.428571 | 0.018657 |
def hicpro_capture_chart (self):
""" Generate Capture Hi-C plot"""
keys = OrderedDict()
keys['valid_pairs_on_target_cap_cap'] = { 'color': '#0039e6', 'name': 'Capture-Capture interactions' }
keys['valid_pairs_on_target_cap_rep'] = { 'color': '#809fff', 'name': 'Capture-Reporter interac... | [
"def",
"hicpro_capture_chart",
"(",
"self",
")",
":",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'valid_pairs_on_target_cap_cap'",
"]",
"=",
"{",
"'color'",
":",
"'#0039e6'",
",",
"'name'",
":",
"'Capture-Capture interactions'",
"}",
"keys",
"[",
"'vali... | 38.8 | 0.014085 |
def deprecated(use_instead=None):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
def wrapped(func):
@wraps(func)
def new_func(*args, **kwargs):
message = "Call to deprecated fu... | [
"def",
"deprecated",
"(",
"use_instead",
"=",
"None",
")",
":",
"def",
"wrapped",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"\"Call to deprecated funct... | 36.5625 | 0.001667 |
def iterargs(self):
""" uses the singular name as key """
iterargs = OrderedDict()
for name in self._iterargs:
plural = self._profile.iterargs[name]
iterargs[name] = tuple(self._values[plural])
return iterargs | [
"def",
"iterargs",
"(",
"self",
")",
":",
"iterargs",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
"in",
"self",
".",
"_iterargs",
":",
"plural",
"=",
"self",
".",
"_profile",
".",
"iterargs",
"[",
"name",
"]",
"iterargs",
"[",
"name",
"]",
"=",
"tup... | 33 | 0.012658 |
def get(self, default=None, callback=None):
u"""Returns leaf's value."""
value = self._xml.text if self._xml.text else default
return callback(value) if callback else value | [
"def",
"get",
"(",
"self",
",",
"default",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_xml",
".",
"text",
"if",
"self",
".",
"_xml",
".",
"text",
"else",
"default",
"return",
"callback",
"(",
"value",
")",
"if"... | 48.25 | 0.010204 |
def get_charset(content_type):
"""Function used to retrieve the charset from a content-type.If there is no
charset in the content type then the charset defined on DEFAULT_CHARSET
will be returned
:param content_type: A string containing a Content-Type header
:returns: A string cont... | [
"def",
"get_charset",
"(",
"content_type",
")",
":",
"if",
"not",
"content_type",
":",
"return",
"DEFAULT_CHARSET",
"matched",
"=",
"_get_charset_re",
".",
"search",
"(",
"content_type",
")",
"if",
"matched",
":",
"# Extract the charset and strip its double quotes",
"... | 37.3125 | 0.001634 |
def generate_form(model, form=None, fields=False, exclude=False):
"""
Generate a form from a model.
:param model: A Django model.
:param form: A Django form.
:param fields: A list of fields to include in this form.
:param exclude: A list of fields to exclude in this form.
"""
_model, _f... | [
"def",
"generate_form",
"(",
"model",
",",
"form",
"=",
"None",
",",
"fields",
"=",
"False",
",",
"exclude",
"=",
"False",
")",
":",
"_model",
",",
"_fields",
",",
"_exclude",
"=",
"model",
",",
"fields",
",",
"exclude",
"class",
"Form",
"(",
"form",
... | 26.818182 | 0.001637 |
def get_sequence_rules_for_assessment_part(self, assessment_part_id):
"""Gets a ``SequenceRuleList`` for the given source assessment part.
arg: assessment_part_id (osid.id.Id): an assessment part
``Id``
return: (osid.assessment.authoring.SequenceRuleList) - the
... | [
"def",
"get_sequence_rules_for_assessment_part",
"(",
"self",
",",
"assessment_part_id",
")",
":",
"# Implemented from template for",
"# osid.learning.ActivityLookupSession.get_activities_for_objective_template",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"="... | 51.869565 | 0.001646 |
def flatten_list(lobj):
"""
Recursively flattens a list.
:param lobj: List to flatten
:type lobj: list
:rtype: list
For example:
>>> import pmisc
>>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7]
"""
ret = []
for item in lobj:
... | [
"def",
"flatten_list",
"(",
"lobj",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"item",
"in",
"lobj",
":",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"for",
"sub_item",
"in",
"flatten_list",
"(",
"item",
")",
":",
"ret",
".",
"append",
"(",... | 20.391304 | 0.002037 |
def write_catalog(filename, catalog, fmt=None, meta=None, prefix=None):
"""
Write a catalog (list of sources) to a file with format determined by extension.
Sources must be of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSo... | [
"def",
"write_catalog",
"(",
"filename",
",",
"catalog",
",",
"fmt",
"=",
"None",
",",
"meta",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"meta",
"is",
"None",
":",
"meta",
"=",
"{",
"}",
"if",
"prefix",
"is",
"None",
":",
"pre",
"=... | 34.589474 | 0.002367 |
def encode(data: Union[str, bytes]) -> str:
"""
Return Base58 string from data
:param data: Bytes or string data
"""
return ensure_str(base58.b58encode(ensure_bytes(data))) | [
"def",
"encode",
"(",
"data",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"str",
":",
"return",
"ensure_str",
"(",
"base58",
".",
"b58encode",
"(",
"ensure_bytes",
"(",
"data",
")",
")",
")"
] | 29.571429 | 0.00939 |
def install_integration(self, id, **kwargs): # noqa: E501
"""Installs a Wavefront integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.install_integrat... | [
"def",
"install_integration",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"install_... | 42.190476 | 0.002208 |
def create_big_thumbnail(self, token, bitstream_id, item_id, width=575):
"""
Create a big thumbnail for the given bitstream with the given width.
It is used as the main image of the given item and shown in the item
view page.
:param token: A valid token for the user in question.... | [
"def",
"create_big_thumbnail",
"(",
"self",
",",
"token",
",",
"bitstream_id",
",",
"item_id",
",",
"width",
"=",
"575",
")",
":",
"parameters",
"=",
"dict",
"(",
")",
"parameters",
"[",
"'token'",
"]",
"=",
"token",
"parameters",
"[",
"'bitstreamId'",
"]"... | 43.769231 | 0.00172 |
def stop(name, lbn, target, profile='default', tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Stop the named worker from the lbn load balancers at the targeted minions
The worker wo... | [
"def",
"stop",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"return",
"_talk2modjk",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"'worker_stop'",
",",
"profile",
",",
"tgt_type",
"... | 31.238095 | 0.001479 |
def containsSettingsGroup(groupName, settings=None):
""" Returns True if the settings contain a group with the name groupName.
Works recursively when the groupName is a slash separated path.
"""
def _containsPath(path, settings):
"Aux function for containsSettingsGroup. Does the actual recur... | [
"def",
"containsSettingsGroup",
"(",
"groupName",
",",
"settings",
"=",
"None",
")",
":",
"def",
"_containsPath",
"(",
"path",
",",
"settings",
")",
":",
"\"Aux function for containsSettingsGroup. Does the actual recursive search.\"",
"if",
"len",
"(",
"path",
")",
"=... | 37.4 | 0.002086 |
def read_pot_status(self):
"""Read the status of the digital pot. Firmware v18+ only.
The return value is a dictionary containing the following as
unsigned 8-bit integers: FanON, LaserON, FanDACVal, LaserDACVal.
:rtype: dict
:Example:
>>> alpha.read_pot_status()
... | [
"def",
"read_pot_status",
"(",
"self",
")",
":",
"# Send the command byte and wait 10 ms",
"a",
"=",
"self",
".",
"cnxn",
".",
"xfer",
"(",
"[",
"0x13",
"]",
")",
"[",
"0",
"]",
"sleep",
"(",
"10e-3",
")",
"# Build an array of the results",
"res",
"=",
"[",
... | 24.542857 | 0.00224 |
def _fit_RSA_marginalized_null(self, Y, X_base,
scan_onsets):
""" The marginalized version of the null model for Bayesian RSA.
The null model assumes no task-related response to the
design matrix.
Note that there is a naming change of variab... | [
"def",
"_fit_RSA_marginalized_null",
"(",
"self",
",",
"Y",
",",
"X_base",
",",
"scan_onsets",
")",
":",
"# Because there is nothing to learn that is shared across",
"# participants, we can run each subject in serial.",
"# The only fitting required is to re-estimate X0 after",
"# each ... | 50.829787 | 0.000411 |
def ConsultarPuerto(self, sep="||"):
"Consulta de Puertos habilitados"
ret = self.client.puertoConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['puertoReturn']
... | [
"def",
"ConsultarPuerto",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"puertoConsultar",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",
",",
"'cuit'"... | 45.230769 | 0.01 |
def register(style, func=None):
"""注册一个拼音风格实现
::
@register('echo')
def echo(pinyin, **kwargs):
return pinyin
# or
register('echo', echo)
"""
if func is not None:
_registry[style] = func
return
def decorator(func):
_registry[styl... | [
"def",
"register",
"(",
"style",
",",
"func",
"=",
"None",
")",
":",
"if",
"func",
"is",
"not",
"None",
":",
"_registry",
"[",
"style",
"]",
"=",
"func",
"return",
"def",
"decorator",
"(",
"func",
")",
":",
"_registry",
"[",
"style",
"]",
"=",
"fun... | 18.12 | 0.002096 |
def get_loglevel(level):
""" return logging level object
corresponding to a given level passed as
a string
@str level: name of a syslog log level
@rtype: logging, logging level from logging module
"""
if level == 'debug':
return logging.DEBUG
elif level == 'notice':
retur... | [
"def",
"get_loglevel",
"(",
"level",
")",
":",
"if",
"level",
"==",
"'debug'",
":",
"return",
"logging",
".",
"DEBUG",
"elif",
"level",
"==",
"'notice'",
":",
"return",
"logging",
".",
"INFO",
"elif",
"level",
"==",
"'info'",
":",
"return",
"logging",
".... | 31.12 | 0.001247 |
def minter(record_uuid, data, pid_type, key):
"""Mint PIDs for a record."""
pid = PersistentIdentifier.create(
pid_type,
data[key],
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.REGISTERED
)
for scheme, identifier in data['identifiers'].items():
... | [
"def",
"minter",
"(",
"record_uuid",
",",
"data",
",",
"pid_type",
",",
"key",
")",
":",
"pid",
"=",
"PersistentIdentifier",
".",
"create",
"(",
"pid_type",
",",
"data",
"[",
"key",
"]",
",",
"object_type",
"=",
"'rec'",
",",
"object_uuid",
"=",
"record_... | 29.631579 | 0.001721 |
def subcellular_locations(self):
"""Distinct subcellular locations (``location`` in :class:`.models.SubcellularLocation`)
:return: all distinct subcellular locations
:rtype: list[str]
"""
return [x[0] for x in self.session.query(models.SubcellularLocation.location).all()] | [
"def",
"subcellular_locations",
"(",
"self",
")",
":",
"return",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"self",
".",
"session",
".",
"query",
"(",
"models",
".",
"SubcellularLocation",
".",
"location",
")",
".",
"all",
"(",
")",
"]"
] | 43.857143 | 0.01278 |
def get_short_annotations(annotations):
"""
Converts full GATK annotation name to the shortened version
:param annotations:
:return:
"""
# Annotations need to match VCF header
short_name = {'QualByDepth': 'QD',
'FisherStrand': 'FS',
'StrandOddsRatio': 'SOR... | [
"def",
"get_short_annotations",
"(",
"annotations",
")",
":",
"# Annotations need to match VCF header",
"short_name",
"=",
"{",
"'QualByDepth'",
":",
"'QD'",
",",
"'FisherStrand'",
":",
"'FS'",
",",
"'StrandOddsRatio'",
":",
"'SOR'",
",",
"'ReadPosRankSumTest'",
":",
... | 34.761905 | 0.001333 |
def fetch_ticker(self) -> Ticker:
"""Fetch the market ticker."""
return self._fetch('ticker', self.market.code)(self._ticker)() | [
"def",
"fetch_ticker",
"(",
"self",
")",
"->",
"Ticker",
":",
"return",
"self",
".",
"_fetch",
"(",
"'ticker'",
",",
"self",
".",
"market",
".",
"code",
")",
"(",
"self",
".",
"_ticker",
")",
"(",
")"
] | 47 | 0.013986 |
def QPSK_rx(fc,N_symb,Rs,EsN0=100,fs=125,lfsr_len=10,phase=0,pulse='src'):
"""
This function generates
"""
Ns = int(np.round(fs/Rs))
print('Ns = ', Ns)
print('Rs = ', fs/float(Ns))
print('EsN0 = ', EsN0, 'dB')
print('phase = ', phase, 'degrees')
print('pulse = ', pulse)
x, b, dat... | [
"def",
"QPSK_rx",
"(",
"fc",
",",
"N_symb",
",",
"Rs",
",",
"EsN0",
"=",
"100",
",",
"fs",
"=",
"125",
",",
"lfsr_len",
"=",
"10",
",",
"phase",
"=",
"0",
",",
"pulse",
"=",
"'src'",
")",
":",
"Ns",
"=",
"int",
"(",
"np",
".",
"round",
"(",
... | 31.4375 | 0.025097 |
async def send_animation(self,
chat_id: typing.Union[base.Integer, base.String],
animation: typing.Union[base.InputFile, base.String],
duration: typing.Union[base.Integer, None] = None,
width: typing.Unio... | [
"async",
"def",
"send_animation",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
",",
"animation",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"InputFile",
",",
"base",
".",
... | 68.046154 | 0.008469 |
def insert_json(table=None,
bulk_size=1000,
concurrency=25,
hosts=None,
output_fmt=None):
"""Insert JSON lines fed into stdin into a Crate cluster.
If no hosts are specified the statements will be printed.
Args:
table: Target table na... | [
"def",
"insert_json",
"(",
"table",
"=",
"None",
",",
"bulk_size",
"=",
"1000",
",",
"concurrency",
"=",
"25",
",",
"hosts",
"=",
"None",
",",
"output_fmt",
"=",
"None",
")",
":",
"if",
"not",
"hosts",
":",
"return",
"print_only",
"(",
"table",
")",
... | 34.583333 | 0.000781 |
def _cmp_by_asn(local_asn, path1, path2):
"""Select the path based on source (iBGP/eBGP) peer.
eBGP path is preferred over iBGP. If both paths are from same kind of
peers, return None.
"""
def get_path_source_asn(path):
asn = None
if path.source is None:
asn = local_asn
... | [
"def",
"_cmp_by_asn",
"(",
"local_asn",
",",
"path1",
",",
"path2",
")",
":",
"def",
"get_path_source_asn",
"(",
"path",
")",
":",
"asn",
"=",
"None",
"if",
"path",
".",
"source",
"is",
"None",
":",
"asn",
"=",
"local_asn",
"else",
":",
"asn",
"=",
"... | 31.192308 | 0.001196 |
def c_handle_array(objs):
"""Create ctypes const void ** from a list of MXNet objects with handles.
Parameters
----------
objs : list of NDArray/Symbol.
MXNet objects.
Returns
-------
(ctypes.c_void_p * len(objs))
A void ** pointer that can be passed to C API.
"""
a... | [
"def",
"c_handle_array",
"(",
"objs",
")",
":",
"arr",
"=",
"(",
"ctypes",
".",
"c_void_p",
"*",
"len",
"(",
"objs",
")",
")",
"(",
")",
"arr",
"[",
":",
"]",
"=",
"[",
"o",
".",
"handle",
"for",
"o",
"in",
"objs",
"]",
"return",
"arr"
] | 24.625 | 0.002445 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'language') and self.language is not None:
_dict['language'] = self.language
if hasattr(self, 'analyzed_text') and self.analyzed_text is not None:
_dict['analyz... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'language'",
")",
"and",
"self",
".",
"language",
"is",
"not",
"None",
":",
"_dict",
"[",
"'language'",
"]",
"=",
"self",
".",
"language",
"if",
"... | 57.970588 | 0.000998 |
def fit_quantile(self, X, y, quantile, max_iter=20, tol=0.01, weights=None):
"""fit ExpectileGAM to a desired quantile via binary search
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors, where n_samples is the number of samples
... | [
"def",
"fit_quantile",
"(",
"self",
",",
"X",
",",
"y",
",",
"quantile",
",",
"max_iter",
"=",
"20",
",",
"tol",
"=",
"0.01",
",",
"weights",
"=",
"None",
")",
":",
"def",
"_within_tol",
"(",
"a",
",",
"b",
",",
"tol",
")",
":",
"return",
"np",
... | 33.028986 | 0.001278 |
def get_content_html(request):
"""Retrieve content as HTML using the ident-hash (uuid@version)."""
result = _get_content_json()
media_type = result['mediaType']
if media_type == COLLECTION_MIMETYPE:
content = tree_to_html(result['tree'])
else:
content = result['content']
resp =... | [
"def",
"get_content_html",
"(",
"request",
")",
":",
"result",
"=",
"_get_content_json",
"(",
")",
"media_type",
"=",
"result",
"[",
"'mediaType'",
"]",
"if",
"media_type",
"==",
"COLLECTION_MIMETYPE",
":",
"content",
"=",
"tree_to_html",
"(",
"result",
"[",
"... | 29.733333 | 0.002174 |
def action_set(method_name):
"""
Creates a setter that will call the action method with the context's
key as first parameter and the value as second parameter.
@param method_name: the name of a method belonging to the action.
@type method_name: str
"""
def action_set(value, context, **_para... | [
"def",
"action_set",
"(",
"method_name",
")",
":",
"def",
"action_set",
"(",
"value",
",",
"context",
",",
"*",
"*",
"_params",
")",
":",
"method",
"=",
"getattr",
"(",
"context",
"[",
"\"action\"",
"]",
",",
"method_name",
")",
"return",
"_set",
"(",
... | 34.692308 | 0.00216 |
def resource_for_link(link, includes, resources=None, locale=None):
"""Returns the resource that matches the link"""
if resources is not None:
cache_key = "{0}:{1}:{2}".format(
link['sys']['linkType'],
link['sys']['id'],
locale
)
if cache_key in resou... | [
"def",
"resource_for_link",
"(",
"link",
",",
"includes",
",",
"resources",
"=",
"None",
",",
"locale",
"=",
"None",
")",
":",
"if",
"resources",
"is",
"not",
"None",
":",
"cache_key",
"=",
"\"{0}:{1}:{2}\"",
".",
"format",
"(",
"link",
"[",
"'sys'",
"]"... | 30.823529 | 0.001852 |
def _calc(self, y, w):
'''Helper to estimate spatial lag conditioned Markov transition
probability matrices based on maximum likelihood techniques.
'''
if self.discrete:
self.lclass_ids = weights.lag_categorical(w, self.class_ids,
... | [
"def",
"_calc",
"(",
"self",
",",
"y",
",",
"w",
")",
":",
"if",
"self",
".",
"discrete",
":",
"self",
".",
"lclass_ids",
"=",
"weights",
".",
"lag_categorical",
"(",
"w",
",",
"self",
".",
"class_ids",
",",
"ties",
"=",
"\"tryself\"",
")",
"else",
... | 37.137931 | 0.00181 |
def relation(self, table, origin_field, search_field,
destination_field=None, id_field="id"):
"""
Add a column to the main dataframe from a relation foreign key
"""
df = self._relation(table, origin_field,
search_field, destination_field, id_... | [
"def",
"relation",
"(",
"self",
",",
"table",
",",
"origin_field",
",",
"search_field",
",",
"destination_field",
"=",
"None",
",",
"id_field",
"=",
"\"id\"",
")",
":",
"df",
"=",
"self",
".",
"_relation",
"(",
"table",
",",
"origin_field",
",",
"search_fi... | 42.5 | 0.011527 |
def modify(self, dn: str, mod_list: dict) -> None:
"""
Modify a DN in the LDAP database; See ldap module. Doesn't return a
result if transactions enabled.
"""
_debug("modify", self, dn, mod_list)
# need to work out how to reverse changes in mod_list; result in revlist
... | [
"def",
"modify",
"(",
"self",
",",
"dn",
":",
"str",
",",
"mod_list",
":",
"dict",
")",
"->",
"None",
":",
"_debug",
"(",
"\"modify\"",
",",
"self",
",",
"dn",
",",
"mod_list",
")",
"# need to work out how to reverse changes in mod_list; result in revlist",
"rev... | 37.7875 | 0.000967 |
def grep(prev, pattern, *args, **kw):
"""The pipe greps the data passed from previous generator according to
given regular expression.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The pattern which used to filter out data.
:type pattern: str|unicode|re pattern ob... | [
"def",
"grep",
"(",
"prev",
",",
"pattern",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"inv",
"=",
"False",
"if",
"'inv'",
"not",
"in",
"kw",
"else",
"kw",
".",
"pop",
"(",
"'inv'",
")",
"pattern_obj",
"=",
"re",
".",
"compile",
"(",
"pat... | 32.6 | 0.00149 |
def sequence_quality_plot (self):
""" Create the HTML for the phred quality score plot """
data = dict()
for s_name in self.fastqc_data:
try:
data[s_name] = {self.avg_bp_from_range(d['base']): d['mean'] for d in self.fastqc_data[s_name]['per_base_sequence_quality']}
... | [
"def",
"sequence_quality_plot",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
")",
"for",
"s_name",
"in",
"self",
".",
"fastqc_data",
":",
"try",
":",
"data",
"[",
"s_name",
"]",
"=",
"{",
"self",
".",
"avg_bp_from_range",
"(",
"d",
"[",
"'base'",
... | 48.369565 | 0.010132 |
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file mus... | [
"def",
"create_jail",
"(",
"name",
",",
"arch",
",",
"version",
"=",
"\"9.0-RELEASE\"",
")",
":",
"# Config file must be on system to create a poudriere jail",
"_check_config_exists",
"(",
")",
"# Check if the jail is there",
"if",
"is_jail",
"(",
"name",
")",
":",
"ret... | 26.266667 | 0.001224 |
def create_virtualenv(venv=VENV):
"""Creates the virtual environment and installs PIP only into the
virtual environment
"""
print 'Creating venv...',
run_command(['virtualenv', '-q', '--no-site-packages', VENV])
print 'done.'
print 'Installing pip in virtualenv...',
if not run_command([W... | [
"def",
"create_virtualenv",
"(",
"venv",
"=",
"VENV",
")",
":",
"print",
"'Creating venv...'",
",",
"run_command",
"(",
"[",
"'virtualenv'",
",",
"'-q'",
",",
"'--no-site-packages'",
",",
"VENV",
"]",
")",
"print",
"'done.'",
"print",
"'Installing pip in virtualen... | 36.571429 | 0.001905 |
def tag(self, tagname, message=None, force=True):
"""Create an annotated tag."""
return git_tag(self.repo_dir, tagname, message=message, force=force) | [
"def",
"tag",
"(",
"self",
",",
"tagname",
",",
"message",
"=",
"None",
",",
"force",
"=",
"True",
")",
":",
"return",
"git_tag",
"(",
"self",
".",
"repo_dir",
",",
"tagname",
",",
"message",
"=",
"message",
",",
"force",
"=",
"force",
")"
] | 54.333333 | 0.012121 |
def insert_sequences_into_tree(aln, moltype, params={},
write_log=True):
"""Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
params: dict of parameters ... | [
"def",
"insert_sequences_into_tree",
"(",
"aln",
",",
"moltype",
",",
"params",
"=",
"{",
"}",
",",
"write_log",
"=",
"True",
")",
":",
"# convert aln to phy since seq_names need fixed to run through pplacer",
"new_aln",
"=",
"get_align_for_phylip",
"(",
"StringIO",
"("... | 31.959184 | 0.010533 |
def filter(array, predicates, ty=None):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
ty (W... | [
"def",
"filter",
"(",
"array",
",",
"predicates",
",",
"ty",
"=",
"None",
")",
":",
"weld_obj",
"=",
"WeldObject",
"(",
"encoder_",
",",
"decoder_",
")",
"array_var",
"=",
"weld_obj",
".",
"update",
"(",
"array",
")",
"if",
"isinstance",
"(",
"array",
... | 29 | 0.000855 |
def from_dict(document):
"""Create data type definition form Json-like object represenation.
Parameters
----------
document : dict
Json-like object represenation
Returns
-------
AttributeType
"""
# Get the type name from the document
... | [
"def",
"from_dict",
"(",
"document",
")",
":",
"# Get the type name from the document",
"type_name",
"=",
"document",
"[",
"'name'",
"]",
"if",
"type_name",
"==",
"ATTR_TYPE_INT",
":",
"return",
"IntType",
"(",
")",
"elif",
"type_name",
"==",
"ATTR_TYPE_FLOAT",
":... | 30.576923 | 0.002439 |
def create_order(email,
request,
addresses=None,
shipping_address=None,
billing_address=None,
shipping_option=None,
capture_payment=False):
"""
Create an order from a basket and customer infomation
"""
... | [
"def",
"create_order",
"(",
"email",
",",
"request",
",",
"addresses",
"=",
"None",
",",
"shipping_address",
"=",
"None",
",",
"billing_address",
"=",
"None",
",",
"shipping_option",
"=",
"None",
",",
"capture_payment",
"=",
"False",
")",
":",
"basket_items",
... | 40.75 | 0.002496 |
def parse_URL(cls, url, timeout=None, resolve=True, required=False, unresolved_value=DEFAULT_SUBSTITUTION):
"""Parse URL
:param url: url to parse
:type url: basestring
:param resolve: if true, resolve substitutions
:type resolve: boolean
:param unresolved_value: assigned... | [
"def",
"parse_URL",
"(",
"cls",
",",
"url",
",",
"timeout",
"=",
"None",
",",
"resolve",
"=",
"True",
",",
"required",
"=",
"False",
",",
"unresolved_value",
"=",
"DEFAULT_SUBSTITUTION",
")",
":",
"socket_timeout",
"=",
"socket",
".",
"_GLOBAL_DEFAULT_TIMEOUT"... | 48.846154 | 0.008494 |
def dashboard(request):
"""Dashboard page"""
user = None
if request.user.is_authenticated():
user = User.objects.get(username=request.user)
latest_results, count_types = get_collaboration_data(user)
latest_results.sort(key=lambda elem: elem.modified, reverse=True)
context = {
... | [
"def",
"dashboard",
"(",
"request",
")",
":",
"user",
"=",
"None",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"request",
".",
"user",
")",
"latest_results... | 28.866667 | 0.002237 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.