text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def find_srvs_by_hostname(self, host_name):
"""Get all services from a host based on a host_name
:param host_name: the host name we want services
:type host_name: str
:return: list of services
:rtype: list[alignak.objects.service.Service]
"""
if hasattr(self, 'ho... | [
"def",
"find_srvs_by_hostname",
"(",
"self",
",",
"host_name",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'hosts'",
")",
":",
"host",
"=",
"self",
".",
"hosts",
".",
"find_by_name",
"(",
"host_name",
")",
"if",
"host",
"is",
"None",
":",
"return",
"... | 34.5 | 11.285714 |
def resource_path(relative):
"""Adjust path for executable use in executable file"""
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative) | [
"def",
"resource_path",
"(",
"relative",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"\"_MEIPASS\"",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"_MEIPASS",
",",
"relative",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",... | 40.6 | 7.6 |
def _delta_filter_command(self, infile, outfile):
'''Construct delta-filter command'''
command = 'delta-filter'
if self.min_id is not None:
command += ' -i ' + str(self.min_id)
if self.min_length is not None:
command += ' -l ' + str(self.min_length)
ret... | [
"def",
"_delta_filter_command",
"(",
"self",
",",
"infile",
",",
"outfile",
")",
":",
"command",
"=",
"'delta-filter'",
"if",
"self",
".",
"min_id",
"is",
"not",
"None",
":",
"command",
"+=",
"' -i '",
"+",
"str",
"(",
"self",
".",
"min_id",
")",
"if",
... | 32.181818 | 16.545455 |
def create_folder(name, location='\\'):
r'''
Create a folder in which to create tasks.
:param str name: The name of the folder. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the folder. Default is '\\' whi... | [
"def",
"create_folder",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing folder",
"if",
"name",
"in",
"list_folders",
"(",
"location",
")",
":",
"# Connect to an existing task definition",
"return",
"'{0} already exists'",
".",
"format",
"(... | 28.666667 | 21.846154 |
def get_cytoband_coord(chrom, pos):
"""Get the cytoband coordinate for a position
Args:
chrom(str): A chromosome
pos(int): The position
Returns:
cytoband
"""
chrom = chrom.strip('chr')
pos = int(pos)
result = None
logger.debug("Finding Cytoba... | [
"def",
"get_cytoband_coord",
"(",
"chrom",
",",
"pos",
")",
":",
"chrom",
"=",
"chrom",
".",
"strip",
"(",
"'chr'",
")",
"pos",
"=",
"int",
"(",
"pos",
")",
"result",
"=",
"None",
"logger",
".",
"debug",
"(",
"\"Finding Cytoband for chrom:{0} pos:{1}\"",
"... | 26.263158 | 18.894737 |
def perlin3(size, units=(1.,)*3, repeat=(10.,)*3, shift=0, scale=None, n_volumes=1):
"""returns a 3d perlin noise array of given size (Nx,Ny,Nz)
and units (dx,dy,dz) with given repeats (in units)
by doing the noise calculations on the gpu
The volume can be splitted into n_volumes pieces if gou memory i... | [
"def",
"perlin3",
"(",
"size",
",",
"units",
"=",
"(",
"1.",
",",
")",
"*",
"3",
",",
"repeat",
"=",
"(",
"10.",
",",
")",
"*",
"3",
",",
"shift",
"=",
"0",
",",
"scale",
"=",
"None",
",",
"n_volumes",
"=",
"1",
")",
":",
"if",
"np",
".",
... | 36.755102 | 19.857143 |
def find(self, filter=list(),
sort_field=None, sort_order=None,
page=None, rows_per_page=None,
using_name=True, data_only=True, raw=True, recovery_name=True):
"""Execute a find query.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111... | [
"def",
"find",
"(",
"self",
",",
"filter",
"=",
"list",
"(",
")",
",",
"sort_field",
"=",
"None",
",",
"sort_order",
"=",
"None",
",",
"page",
"=",
"None",
",",
"rows_per_page",
"=",
"None",
",",
"using_name",
"=",
"True",
",",
"data_only",
"=",
"Tru... | 39.022727 | 21.170455 |
async def retry_post(config, url, *args, **kwargs):
""" aiohttp wrapper for POST """
return await _retry_do(config.session.post, url, *args,
**_make_headers(config, kwargs)) | [
"async",
"def",
"retry_post",
"(",
"config",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"_retry_do",
"(",
"config",
".",
"session",
".",
"post",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"_make_headers",
... | 51.25 | 12.25 |
def syscall_direct(*events):
'''
Directly process these events. This should never be used for normal events.
'''
def _syscall(scheduler, processor):
for e in events:
processor(e)
return _syscall | [
"def",
"syscall_direct",
"(",
"*",
"events",
")",
":",
"def",
"_syscall",
"(",
"scheduler",
",",
"processor",
")",
":",
"for",
"e",
"in",
"events",
":",
"processor",
"(",
"e",
")",
"return",
"_syscall"
] | 28.375 | 21.375 |
def psd(self):
"""
A pyCBC FrequencySeries holding the appropriate PSD.
Return the PSD used in the metric calculation.
"""
if not self._psd:
errMsg = "The PSD has not been set in the metricParameters "
errMsg += "instance."
raise ValueError(err... | [
"def",
"psd",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_psd",
":",
"errMsg",
"=",
"\"The PSD has not been set in the metricParameters \"",
"errMsg",
"+=",
"\"instance.\"",
"raise",
"ValueError",
"(",
"errMsg",
")",
"return",
"self",
".",
"_psd"
] | 34 | 13.4 |
def _add_logical_methods(cls):
"""
Add in logical methods.
"""
_doc = """
%(desc)s
Parameters
----------
*args
These parameters will be passed to numpy.%(outname)s.
**kwargs
These parameters will be passed to numpy.%(outnam... | [
"def",
"_add_logical_methods",
"(",
"cls",
")",
":",
"_doc",
"=",
"\"\"\"\n %(desc)s\n\n Parameters\n ----------\n *args\n These parameters will be passed to numpy.%(outname)s.\n **kwargs\n These parameters will be passed to numpy.%(outname)s.... | 28.201923 | 21.740385 |
def execute(self, query, params=None, cursor=None):
"""Execute query in pool.
Returns future yielding closed cursor.
You can get rows, lastrowid, etc from the cursor.
:param cursor: cursor class(Cursor, DictCursor. etc.)
:return: Future of cursor
:rtype: Future
... | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"params",
"=",
"None",
",",
"cursor",
"=",
"None",
")",
":",
"conn",
"=",
"yield",
"self",
".",
"_get_conn",
"(",
")",
"try",
":",
"cur",
"=",
"conn",
".",
"cursor",
"(",
"cursor",
")",
"yield",
"... | 29 | 14.904762 |
def plot(self, columns=None, loc=None, iloc=None, **kwargs):
""""
A wrapper around plotting. Matplotlib plot arguments can be passed in, plus:
Parameters
-----------
columns: string or list-like, optional
If not empty, plot a subset of columns from the ``cumulative_haz... | [
"def",
"plot",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"loc",
"=",
"None",
",",
"iloc",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
"import",
"pyplot",
"as",
"plt",
"assert",
"loc",
"is",
"None",
"or",
"iloc",
"is",... | 38.890909 | 28.509091 |
def deepcopy_dict(data):
""" deepcopy dict data, ignore file object (_io.BufferedReader)
Args:
data (dict): dict data structure
{
'a': 1,
'b': [2, 4],
'c': lambda x: x+1,
'd': open('LICENSE'),
'f': {
... | [
"def",
"deepcopy_dict",
"(",
"data",
")",
":",
"try",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"data",
")",
"except",
"TypeError",
":",
"copied_data",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"... | 26.970588 | 17.147059 |
def get(self, key, no_cache=False):
"""Return the value of a single preference using a dotted path key
:arg no_cache: if true, the cache is bypassed
"""
section, name = self.parse_lookup(key)
preference = self.registry.get(
section=section, name=name, fallback=False)
... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"no_cache",
"=",
"False",
")",
":",
"section",
",",
"name",
"=",
"self",
".",
"parse_lookup",
"(",
"key",
")",
"preference",
"=",
"self",
".",
"registry",
".",
"get",
"(",
"section",
"=",
"section",
",",
... | 37.5 | 15.555556 |
def _insert_img(qr_img, icon_img=None, factor=4, icon_box=None, static_dir=None):
"""Inserts a small icon to QR Code image"""
img_w, img_h = qr_img.size
size_w = int(img_w) / int(factor)
size_h = int(img_h) / int(factor)
try:
# load icon from current dir
... | [
"def",
"_insert_img",
"(",
"qr_img",
",",
"icon_img",
"=",
"None",
",",
"factor",
"=",
"4",
",",
"icon_box",
"=",
"None",
",",
"static_dir",
"=",
"None",
")",
":",
"img_w",
",",
"img_h",
"=",
"qr_img",
".",
"size",
"size_w",
"=",
"int",
"(",
"img_w",... | 40.931034 | 17.172414 |
def gap_proportion(sequences, gap_chars='-'):
"""
Generates a list with the proportion of gaps by index in a set of
sequences.
"""
aln_len = None
gaps = []
for i, sequence in enumerate(sequences):
if aln_len is None:
aln_len = len(sequence)
gaps = [0] * aln_le... | [
"def",
"gap_proportion",
"(",
"sequences",
",",
"gap_chars",
"=",
"'-'",
")",
":",
"aln_len",
"=",
"None",
"gaps",
"=",
"[",
"]",
"for",
"i",
",",
"sequence",
"in",
"enumerate",
"(",
"sequences",
")",
":",
"if",
"aln_len",
"is",
"None",
":",
"aln_len",... | 32.25 | 16.166667 |
def apply_T1(word):
'''There is a syllable boundary in front of every CV-sequence.'''
WORD = _split_consonants_and_vowels(word)
for k, v in WORD.iteritems():
if k == 1 and is_consonantal_onset(v):
WORD[k] = '.' + v
elif is_consonant(v[0]) and WORD.get(k + 1, 0):
WO... | [
"def",
"apply_T1",
"(",
"word",
")",
":",
"WORD",
"=",
"_split_consonants_and_vowels",
"(",
"word",
")",
"for",
"k",
",",
"v",
"in",
"WORD",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"==",
"1",
"and",
"is_consonantal_onset",
"(",
"v",
")",
":",
"WO... | 26.2 | 21.4 |
def from_pattern(cls, pattern, filetype=None, key='filename', root=None, ignore=[]):
"""
Convenience method to directly chain a pattern processed by
FilePattern into a FileInfo instance.
Note that if a default filetype has been set on FileInfo, the
filetype argument may be omitt... | [
"def",
"from_pattern",
"(",
"cls",
",",
"pattern",
",",
"filetype",
"=",
"None",
",",
"key",
"=",
"'filename'",
",",
"root",
"=",
"None",
",",
"ignore",
"=",
"[",
"]",
")",
":",
"filepattern",
"=",
"FilePattern",
"(",
"key",
",",
"pattern",
",",
"roo... | 48.1875 | 18.0625 |
def set_auth_key_from_file(user,
source,
config='.ssh/authorized_keys',
saltenv='base',
fingerprint_hash_type=None):
'''
Add a key to the authorized_keys file, using a file as the source.
CLI Example... | [
"def",
"set_auth_key_from_file",
"(",
"user",
",",
"source",
",",
"config",
"=",
"'.ssh/authorized_keys'",
",",
"saltenv",
"=",
"'base'",
",",
"fingerprint_hash_type",
"=",
"None",
")",
":",
"# TODO: add support for pulling keys from other file sources as well",
"lfile",
... | 32.946429 | 20.339286 |
def _rewrite_paths_in_file(config_file, paths_to_replace):
"""
Rewrite paths in config files to match convention job_xxxx/symlink
Requires path to run_xxxx/input/config_file and a list of paths_to_replace
"""
lines = []
# make a copy of config
import shutil
... | [
"def",
"_rewrite_paths_in_file",
"(",
"config_file",
",",
"paths_to_replace",
")",
":",
"lines",
"=",
"[",
"]",
"# make a copy of config",
"import",
"shutil",
"shutil",
".",
"copyfile",
"(",
"config_file",
",",
"str",
"(",
"config_file",
"+",
"'_original'",
")",
... | 46.15 | 17.05 |
def _get_rescale_factors(self, reference_shape, meta_info):
""" Compute the resampling factor for height and width of the input array
:param reference_shape: Tuple specifying height and width in pixels of high-resolution array
:type reference_shape: tuple of ints
:param meta_info: Meta-... | [
"def",
"_get_rescale_factors",
"(",
"self",
",",
"reference_shape",
",",
"meta_info",
")",
":",
"# Figure out resampling size",
"height",
",",
"width",
"=",
"reference_shape",
"service_type",
"=",
"ServiceType",
"(",
"meta_info",
"[",
"'service_type'",
"]",
")",
"re... | 47.361111 | 24.805556 |
def crown(self, depth=2):
""" Returns a list of leaves, nodes connected to leaves, etc.
"""
nodes = []
for node in self.leaves: nodes += node.flatten(depth-1)
return cluster.unique(nodes) | [
"def",
"crown",
"(",
"self",
",",
"depth",
"=",
"2",
")",
":",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"leaves",
":",
"nodes",
"+=",
"node",
".",
"flatten",
"(",
"depth",
"-",
"1",
")",
"return",
"cluster",
".",
"unique",
"(",
... | 37 | 10.666667 |
def on_position_changed(self, position):
"""bind position changed signal with this"""
if not self._lyric:
return
pos = find_previous(position*1000 + 300, self._pos_list)
if pos is not None and pos != self._pos:
self.current_sentence = self._pos_s_map[pos]
... | [
"def",
"on_position_changed",
"(",
"self",
",",
"position",
")",
":",
"if",
"not",
"self",
".",
"_lyric",
":",
"return",
"pos",
"=",
"find_previous",
"(",
"position",
"*",
"1000",
"+",
"300",
",",
"self",
".",
"_pos_list",
")",
"if",
"pos",
"is",
"not"... | 36.888889 | 15.111111 |
def visit_snippet(self, node):
"""
HTML document generator visit handler
"""
lang = self.highlightlang
linenos = node.rawsource.count('\n') >= self.highlightlinenothreshold - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-... | [
"def",
"visit_snippet",
"(",
"self",
",",
"node",
")",
":",
"lang",
"=",
"self",
".",
"highlightlang",
"linenos",
"=",
"node",
".",
"rawsource",
".",
"count",
"(",
"'\\n'",
")",
">=",
"self",
".",
"highlightlinenothreshold",
"-",
"1",
"fname",
"=",
"node... | 38.965517 | 17.103448 |
def init_all_receivers():
"""
Initialize all discovered Denon AVR receivers in LAN zone.
Returns a list of created Denon AVR instances.
By default SSDP broadcasts are sent up to 3 times with a 2 seconds timeout.
"""
receivers = discover()
init_receivers = []
for receiver in receivers:
... | [
"def",
"init_all_receivers",
"(",
")",
":",
"receivers",
"=",
"discover",
"(",
")",
"init_receivers",
"=",
"[",
"]",
"for",
"receiver",
"in",
"receivers",
":",
"init_receiver",
"=",
"DenonAVR",
"(",
"receiver",
"[",
"\"host\"",
"]",
")",
"init_receivers",
".... | 30.571429 | 16.857143 |
def set_share_properties(self, share_name, quota, timeout=None):
'''
Sets service-defined properties for the specified share.
:param str share_name:
Name of existing share.
:param int quota:
Specifies the maximum size of the share, in gigabytes. Must be
... | [
"def",
"set_share_properties",
"(",
"self",
",",
"share_name",
",",
"quota",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'share_name'",
",",
"share_name",
")",
"_validate_not_none",
"(",
"'quota'",
",",
"quota",
")",
"request",
"=",
"HTT... | 36.961538 | 17.038462 |
def get_for_file( fp, hash_mode="md5" ):
r"""
Returns a hash string for the given file path.
:param fp: Path to the file.
:param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'.
Defines the algorithm used to generate the resulting h... | [
"def",
"get_for_file",
"(",
"fp",
",",
"hash_mode",
"=",
"\"md5\"",
")",
":",
"with",
"_get_file_handle",
"(",
"fp",
")",
"as",
"f",
":",
"file_hash_digest",
"=",
"get_for_handle",
"(",
"f",
",",
"hash_mode",
")",
"return",
"file_hash_digest"
] | 35.571429 | 19.357143 |
def _run_purecn(paired, work_dir):
"""Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs.
"""
segfns = {"cnvkit": _segment_normalized_cnvkit, "gatk-cnv": _segment_normalized_gatk}
out_base, out, all_files = _get_purecn_files(paired, work_dir)
failed_file = out_base + "-failed.log"
cn... | [
"def",
"_run_purecn",
"(",
"paired",
",",
"work_dir",
")",
":",
"segfns",
"=",
"{",
"\"cnvkit\"",
":",
"_segment_normalized_cnvkit",
",",
"\"gatk-cnv\"",
":",
"_segment_normalized_gatk",
"}",
"out_base",
",",
"out",
",",
"all_files",
"=",
"_get_purecn_files",
"(",... | 65.142857 | 28.928571 |
def traverse_nodes(self, node_set, depth=0):
"""BFS traversal of nodes that returns name traversal as large string.
Args:
node_set: Set of input nodes to begin traversal.
depth: Current traversal depth for child node viewing.
Returns:
type: String containing... | [
"def",
"traverse_nodes",
"(",
"self",
",",
"node_set",
",",
"depth",
"=",
"0",
")",
":",
"tab",
"=",
"\" \"",
"result",
"=",
"list",
"(",
")",
"for",
"n",
"in",
"node_set",
":",
"repr",
"=",
"(",
"n",
"if",
"self",
".",
"nodes",
"[",
"n",
"]",
... | 30.88 | 22.04 |
def stream(self, func, *args, **kwargs):
"""Watch an API resource and stream the result back via a generator.
:param func: The API function pointer. Any parameter to the function
can be passed after this parameter.
:return: Event object with these keys:
... | [
"def",
"stream",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"close",
"(",
")",
"self",
".",
"_stop",
"=",
"False",
"self",
".",
"return_type",
"=",
"self",
".",
"get_return_type",
"(",
"func",
")",
... | 42.529412 | 22.029412 |
def get_job_logs(id):
"""Get the crawl logs from the job."""
crawler_job = models.CrawlerJob.query.filter_by(id=id).one_or_none()
if crawler_job is None:
click.secho(
(
"CrawlJob %s was not found, maybe it's not a crawl job?" %
id
),
... | [
"def",
"get_job_logs",
"(",
"id",
")",
":",
"crawler_job",
"=",
"models",
".",
"CrawlerJob",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"id",
")",
".",
"one_or_none",
"(",
")",
"if",
"crawler_job",
"is",
"None",
":",
"click",
".",
"secho",
"(",
... | 25.214286 | 22.642857 |
def make_spotify_blueprint(
client_id=None,
client_secret=None,
scope=None,
redirect_url=None,
redirect_to=None,
login_url=None,
authorized_url=None,
session_class=None,
storage=None,
):
"""
Make a blueprint for authenticating with Spotify using OAuth 2. This requires
a c... | [
"def",
"make_spotify_blueprint",
"(",
"client_id",
"=",
"None",
",",
"client_secret",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"redirect_url",
"=",
"None",
",",
"redirect_to",
"=",
"None",
",",
"login_url",
"=",
"None",
",",
"authorized_url",
"=",
"None"... | 41.409091 | 22.075758 |
def parse_config(filename, header):
""" Parses the provided filename and returns ``SettingParser`` if the
parsing was successful and header matches the header defined in the
file.
Returns ``SettingParser`` instance.
* Raises a ``ParseError`` exception if header doesn't match or par... | [
"def",
"parse_config",
"(",
"filename",
",",
"header",
")",
":",
"parser",
"=",
"SettingParser",
"(",
"filename",
")",
"if",
"parser",
".",
"header",
"!=",
"header",
":",
"header_value",
"=",
"parser",
".",
"header",
"or",
"''",
"raise",
"ParseError",
"(",... | 33.944444 | 21.722222 |
def report(self, stream):
"""Displays the slowest tests"""
self.db.commit()
stream.writeln()
self.draw_header(stream, "10 SLOWEST SETUPS")
self.display_slowest_setups(stream)
stream.writeln()
self.draw_header(stream, "10 SLOWEST TESTS")
self.display_slow... | [
"def",
"report",
"(",
"self",
",",
"stream",
")",
":",
"self",
".",
"db",
".",
"commit",
"(",
")",
"stream",
".",
"writeln",
"(",
")",
"self",
".",
"draw_header",
"(",
"stream",
",",
"\"10 SLOWEST SETUPS\"",
")",
"self",
".",
"display_slowest_setups",
"(... | 29 | 16.466667 |
def get_apis(self):
"""
Parses a swagger document and returns a list of APIs configured in the document.
Swagger documents have the following structure
{
"/path1": { # path
"get": { # method
"x-amazon-apigateway-integration": { # in... | [
"def",
"get_apis",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"paths_dict",
"=",
"self",
".",
"swagger",
".",
"get",
"(",
"\"paths\"",
",",
"{",
"}",
")",
"binary_media_types",
"=",
"self",
".",
"get_binary_media_types",
"(",
")",
"for",
"full_path"... | 35.581818 | 25.727273 |
def load_library(version):
"""
Load the correct module according to the version
:type version: ``str``
:param version: the version of the library to be loaded (e.g. '2.6')
:rtype: module object
"""
check_version(version)
module_name = SUPPORTED_LIBRARIES[version]
lib = sys.modules.g... | [
"def",
"load_library",
"(",
"version",
")",
":",
"check_version",
"(",
"version",
")",
"module_name",
"=",
"SUPPORTED_LIBRARIES",
"[",
"version",
"]",
"lib",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"module_name",
")",
"if",
"lib",
"is",
"None",
":",
... | 29.142857 | 14.714286 |
def ReplaceContainer(self, collection_link, collection, options=None):
"""Replaces a collection and return it.
:param str collection_link:
The link to the collection entity.
:param dict collection:
The collection to be used.
:param dict options:
The ... | [
"def",
"ReplaceContainer",
"(",
"self",
",",
"collection_link",
",",
"collection",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"CosmosClient",
".",
"__ValidateResource",
"(",
"collection",
")",
"path",... | 31.535714 | 15.25 |
def get_mac_address_range(context, id, fields=None):
"""Retrieve a mac_address_range.
: param context: neutron api request context
: param id: UUID representing the network to fetch.
: param fields: a list of strings that are valid keys in a
network dictionary as listed in the RESOURCE_ATTRIBUT... | [
"def",
"get_mac_address_range",
"(",
"context",
",",
"id",
",",
"fields",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"(",
"\"get_mac_address_range %s for tenant %s fields %s\"",
"%",
"(",
"id",
",",
"context",
".",
"tenant_id",
",",
"fields",
")",
")",
"if",
... | 36.73913 | 16.347826 |
def get_method_sig(method):
""" Given a function, it returns a string that pretty much looks how the
function signature would be written in python.
:param method: a python method
:return: A string similar describing the pythong method signature.
eg: "my_method(first_argArg, second_arg=42, third_arg... | [
"def",
"get_method_sig",
"(",
"method",
")",
":",
"# The return value of ArgSpec is a bit weird, as the list of arguments and",
"# list of defaults are returned in separate array.",
"# eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],",
"# varargs=None, keywords=None, defaults=(42, 'somet... | 39.176471 | 17.205882 |
def FormatArtifacts(self, artifacts):
"""Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition.
"""
# TODO: improve output formatting of yaml
artifact_definitions = [artifa... | [
"def",
"FormatArtifacts",
"(",
"self",
",",
"artifacts",
")",
":",
"# TODO: improve output formatting of yaml",
"artifact_definitions",
"=",
"[",
"artifact",
".",
"AsDict",
"(",
")",
"for",
"artifact",
"in",
"artifacts",
"]",
"yaml_data",
"=",
"yaml",
".",
"safe_d... | 32.615385 | 19.307692 |
def api_class(self, resource_name=None, path=None, audiences=None,
scopes=None, allowed_client_ids=None, auth_level=None,
api_key_required=None):
"""Get a decorator for a class that implements an API.
This can be used for single-class or multi-class implementations. It's
us... | [
"def",
"api_class",
"(",
"self",
",",
"resource_name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"audiences",
"=",
"None",
",",
"scopes",
"=",
"None",
",",
"allowed_client_ids",
"=",
"None",
",",
"auth_level",
"=",
"None",
",",
"api_key_required",
"=",
... | 39.291667 | 22.166667 |
def create_header(self):
""" return header dict """
try:
self.check_valid()
_header_list = []
for k,v in self.inputs.items():
if v is None:
return {self.__class__.__name__.replace('_','-'):None}
elif k == 'value':
_header_list.insert(0,str(v))
elif isinstance(v,bool):
if v is Tr... | [
"def",
"create_header",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"check_valid",
"(",
")",
"_header_list",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"inputs",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"return"... | 27.833333 | 18.388889 |
def datetimeAt(self, x):
"""
Returns the datetime at the inputed x position.
:return <QDateTime>
"""
gantt = self.ganttWidget()
dstart = gantt.dateTimeStart()
distance = int(x / float(gantt.cellWidth()))
# calculate the time... | [
"def",
"datetimeAt",
"(",
"self",
",",
"x",
")",
":",
"gantt",
"=",
"self",
".",
"ganttWidget",
"(",
")",
"dstart",
"=",
"gantt",
".",
"dateTimeStart",
"(",
")",
"distance",
"=",
"int",
"(",
"x",
"/",
"float",
"(",
"gantt",
".",
"cellWidth",
"(",
"... | 33.925926 | 12.666667 |
def is_pep484_nonable(typ):
"""
Checks if a given type is nonable, meaning that it explicitly or implicitly declares a Union with NoneType.
Nested TypeVars and Unions are supported.
:param typ:
:return:
"""
# TODO rely on typing_inspect if there is an answer to https://github.com/ilevkivsky... | [
"def",
"is_pep484_nonable",
"(",
"typ",
")",
":",
"# TODO rely on typing_inspect if there is an answer to https://github.com/ilevkivskyi/typing_inspect/issues/14",
"if",
"typ",
"is",
"type",
"(",
"None",
")",
":",
"return",
"True",
"elif",
"is_typevar",
"(",
"typ",
")",
"... | 38.2 | 28.333333 |
def create_cutout(
self, resource, resolution, x_range, y_range, z_range, time_range, numpyVolume,
url_prefix, auth, session, send_opts):
"""Upload a cutout to the Boss data store.
Args:
resource (intern.resource.resource.Resource): Resource compatible with cutout operations... | [
"def",
"create_cutout",
"(",
"self",
",",
"resource",
",",
"resolution",
",",
"x_range",
",",
"y_range",
",",
"z_range",
",",
"time_range",
",",
"numpyVolume",
",",
"url_prefix",
",",
"auth",
",",
"session",
",",
"send_opts",
")",
":",
"if",
"numpyVolume",
... | 43.45 | 21.5625 |
def store_inputs(self, line_num, source, source_raw=None):
"""Store source and raw input in history and create input cache
variables _i*.
Parameters
----------
line_num : int
The prompt number of this input.
source : str
Python input.
source... | [
"def",
"store_inputs",
"(",
"self",
",",
"line_num",
",",
"source",
",",
"source_raw",
"=",
"None",
")",
":",
"if",
"source_raw",
"is",
"None",
":",
"source_raw",
"=",
"source",
"source",
"=",
"source",
".",
"rstrip",
"(",
"'\\n'",
")",
"source_raw",
"="... | 31.8125 | 17.145833 |
def make_param(self, name, raw_uri, disk_size):
"""Return a MountParam given a GCS bucket, disk image or local path."""
if raw_uri.startswith('https://www.googleapis.com/compute'):
# Full Image URI should look something like:
# https://www.googleapis.com/compute/v1/projects/<project>/global/images/
... | [
"def",
"make_param",
"(",
"self",
",",
"name",
",",
"raw_uri",
",",
"disk_size",
")",
":",
"if",
"raw_uri",
".",
"startswith",
"(",
"'https://www.googleapis.com/compute'",
")",
":",
"# Full Image URI should look something like:",
"# https://www.googleapis.com/compute/v1/pro... | 54.105263 | 18.157895 |
def get_aggregations(self, query, group_by, stats_field, percents=(50, 95, 99, 99.9), size=100):
"""
Returns aggregations (rows count + percentile stats) for a given query
This is basically the same as the following pseudo-SQL query:
SELECT PERCENTILE(stats_field, 75) FROM query GROUP B... | [
"def",
"get_aggregations",
"(",
"self",
",",
"query",
",",
"group_by",
",",
"stats_field",
",",
"percents",
"=",
"(",
"50",
",",
"95",
",",
"99",
",",
"99.9",
")",
",",
"size",
"=",
"100",
")",
":",
"body",
"=",
"{",
"\"query\"",
":",
"{",
"\"bool\... | 34.088889 | 23.866667 |
def headerSortAscending( self ):
"""
Sorts the column at the current header index by ascending order.
"""
self.setSortingEnabled(True)
self.sortByColumn(self._headerIndex, QtCore.Qt.AscendingOrder) | [
"def",
"headerSortAscending",
"(",
"self",
")",
":",
"self",
".",
"setSortingEnabled",
"(",
"True",
")",
"self",
".",
"sortByColumn",
"(",
"self",
".",
"_headerIndex",
",",
"QtCore",
".",
"Qt",
".",
"AscendingOrder",
")"
] | 39.5 | 12.166667 |
def stop(self):
"""Stop the timer."""
self._backend._vispy_stop()
self._running = False
self.events.stop(type='timer_stop') | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_backend",
".",
"_vispy_stop",
"(",
")",
"self",
".",
"_running",
"=",
"False",
"self",
".",
"events",
".",
"stop",
"(",
"type",
"=",
"'timer_stop'",
")"
] | 30.2 | 8.8 |
def _ensure_dependency_available_at_version(package_name, min_version):
"""Throw helpful error if required dependencies not available."""
try:
pkg = importlib.import_module(package_name)
except ImportError:
pip_name = package_name.replace('_', '-')
raise SystemError(
'Sonnet requires %s (mini... | [
"def",
"_ensure_dependency_available_at_version",
"(",
"package_name",
",",
"min_version",
")",
":",
"try",
":",
"pkg",
"=",
"importlib",
".",
"import_module",
"(",
"package_name",
")",
"except",
"ImportError",
":",
"pip_name",
"=",
"package_name",
".",
"replace",
... | 42.631579 | 19.631579 |
def check_signing_key(self):
"""
Check that repo signing key is trusted by gpg keychain
"""
user_keys = self.gpg.list_keys()
if len(user_keys) > 0:
trusted = False
for key in user_keys:
if key['fingerprint'] == self.key_info['fingerprint']:... | [
"def",
"check_signing_key",
"(",
"self",
")",
":",
"user_keys",
"=",
"self",
".",
"gpg",
".",
"list_keys",
"(",
")",
"if",
"len",
"(",
"user_keys",
")",
">",
"0",
":",
"trusted",
"=",
"False",
"for",
"key",
"in",
"user_keys",
":",
"if",
"key",
"[",
... | 44.222222 | 18.555556 |
def _handle_compound(self, node, scope, ctxt, stream):
"""Handle Compound nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling compound statement")
#scope.push()
try:
for child in n... | [
"def",
"_handle_compound",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"self",
".",
"_dlog",
"(",
"\"handling compound statement\"",
")",
"#scope.push()",
"try",
":",
"for",
"child",
"in",
"node",
".",
"children",
"(",
")"... | 25.272727 | 20.590909 |
def _process_commands(self):
""" Processes commands received and executes them accordingly.
Returns ``True`` if successful, ``False`` if connection closed or
server terminated.
"""
try:
# poll for data, so we don't block forever
if self._cmd_p... | [
"def",
"_process_commands",
"(",
"self",
")",
":",
"try",
":",
"# poll for data, so we don't block forever",
"if",
"self",
".",
"_cmd_pipe",
".",
"poll",
"(",
"1",
")",
":",
"# 1 sec timeout",
"payload",
"=",
"self",
".",
"_cmd_pipe",
".",
"recv_bytes",
"(",
"... | 33.35 | 18.625 |
def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT):
"""Derives a Modular Crypt Format hash using the scrypt KDF
Parameter space is smaller than for scrypt():
N must be a power of two larger than 1 but no larger than 2 ** 31
r and p m... | [
"def",
"scrypt_mcf",
"(",
"password",
",",
"salt",
"=",
"None",
",",
"N",
"=",
"SCRYPT_N",
",",
"r",
"=",
"SCRYPT_r",
",",
"p",
"=",
"SCRYPT_p",
",",
"prefix",
"=",
"SCRYPT_MCF_PREFIX_DEFAULT",
")",
":",
"if",
"(",
"prefix",
"!=",
"SCRYPT_MCF_PREFIX_s1",
... | 36.071429 | 19.261905 |
def plot_prof_sparse(self, mod, species, xlim1, xlim2, ylim1, ylim2,
sparse, symbol):
"""
plot one species for cycle between xlim1 and xlim2.
Parameters
----------
species : list
which species to plot.
mod : string or integer
... | [
"def",
"plot_prof_sparse",
"(",
"self",
",",
"mod",
",",
"species",
",",
"xlim1",
",",
"xlim2",
",",
"ylim1",
",",
"ylim2",
",",
"sparse",
",",
"symbol",
")",
":",
"mass",
"=",
"self",
".",
"se",
".",
"get",
"(",
"mod",
",",
"'mass'",
")",
"Xspecie... | 30.714286 | 15.142857 |
def runiform(lower, upper, size=None):
"""
Random uniform variates.
"""
return np.random.uniform(lower, upper, size) | [
"def",
"runiform",
"(",
"lower",
",",
"upper",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"uniform",
"(",
"lower",
",",
"upper",
",",
"size",
")"
] | 25.6 | 4.4 |
def request(self, scheme, url, data=None, params=None):
"""
Low-level request interface to mite. Takes a HTTP request scheme (lower
case!), a URL to request (relative), and optionally data to add to the
request. Either returns the JSON body of the request or raises a
HttpExcepti... | [
"def",
"request",
"(",
"self",
",",
"scheme",
",",
"url",
",",
"data",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"url",
".",
"format",
"(",
"self",
".",
"team",
",",
"url",
")",
"headers",
"=",
"{",
"\"X-MiteApik... | 34.322581 | 20.967742 |
def missing_requirements(self, specifiers):
""" Find what's missing
"""
for specifier in specifiers:
try:
pkg_resources.require(specifier)
except pkg_resources.DistributionNotFound:
yield specifier | [
"def",
"missing_requirements",
"(",
"self",
",",
"specifiers",
")",
":",
"for",
"specifier",
"in",
"specifiers",
":",
"try",
":",
"pkg_resources",
".",
"require",
"(",
"specifier",
")",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
"yield",
"speci... | 33.75 | 7.75 |
def diff(before, after, check_modified=False):
"""Diff two sequences of comparable objects.
The result of this function is a list of dictionaries containing
values in ``before`` or ``after`` with a ``state`` of either
'unchanged', 'added', 'deleted', or 'modified'.
>>> import pprint
>>> result... | [
"def",
"diff",
"(",
"before",
",",
"after",
",",
"check_modified",
"=",
"False",
")",
":",
"# The grid will be empty if `before` or `after` are",
"# empty; this will violate the assumptions made in the rest",
"# of this function.",
"# If this is the case, we know what the result of the... | 30.111111 | 16.922222 |
def Guo_Sun(dp, voidage, vs, rho, mu, Dt, L=1):
r'''Calculates pressure drop across a packed bed of spheres using a
correlation developed in [1]_. This is valid for highly-packed particles
at particle/tube diameter ratios between 2 and 3, where a ring packing
structure occurs. If a packing ratio is so... | [
"def",
"Guo_Sun",
"(",
"dp",
",",
"voidage",
",",
"vs",
",",
"rho",
",",
"mu",
",",
"Dt",
",",
"L",
"=",
"1",
")",
":",
"# 2 < D/d < 3, particles in contact with the wall tend to form a highly ordered ring structure. ",
"Rem",
"=",
"dp",
"*",
"rho",
"*",
"vs",
... | 31.815385 | 24.923077 |
async def i2c_read_data(self, command):
"""
This method retrieves the last value read for an i2c device identified by address.
This is a polling implementation and i2c_read_request and i2c_read_request_reply may be
a better alternative.
:param command: {"method": "i2c_read_data",... | [
"async",
"def",
"i2c_read_data",
"(",
"self",
",",
"command",
")",
":",
"address",
"=",
"int",
"(",
"command",
"[",
"0",
"]",
")",
"i2c_data",
"=",
"await",
"self",
".",
"core",
".",
"i2c_read_data",
"(",
"address",
")",
"reply",
"=",
"json",
".",
"d... | 52.75 | 20.75 |
def matchItem(self, item):
'''
[OPTIONAL] Attempts to find the specified item and returns an item
that describes the same object although it's specific properties
may be different. For example, a contact whose name is an
identical match, but whose telephone number has changed would
return the ma... | [
"def",
"matchItem",
"(",
"self",
",",
"item",
")",
":",
"for",
"match",
"in",
"self",
".",
"getAllItems",
"(",
")",
":",
"if",
"cmp",
"(",
"match",
",",
"item",
")",
"==",
"0",
":",
"return",
"match",
"return",
"None"
] | 40.59375 | 25.59375 |
def _len_lcs(x, y):
"""Returns the length of the Longest Common Subsequence between two seqs.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns
integer: Length of LCS between x and y
"""
table = _lcs(x, y)
n, m =... | [
"def",
"_len_lcs",
"(",
"x",
",",
"y",
")",
":",
"table",
"=",
"_lcs",
"(",
"x",
",",
"y",
")",
"n",
",",
"m",
"=",
"len",
"(",
"x",
")",
",",
"len",
"(",
"y",
")",
"return",
"table",
"[",
"n",
",",
"m",
"]"
] | 22.8 | 22 |
def handle_inform(self, msg):
"""Dispatch an inform message to the appropriate method.
Parameters
----------
msg : Message object
The inform message to dispatch.
"""
method = self._inform_handlers.get(
msg.name, self.__class__.unhandled_inform)
... | [
"def",
"handle_inform",
"(",
"self",
",",
"msg",
")",
":",
"method",
"=",
"self",
".",
"_inform_handlers",
".",
"get",
"(",
"msg",
".",
"name",
",",
"self",
".",
"__class__",
".",
"unhandled_inform",
")",
"try",
":",
"return",
"method",
"(",
"self",
",... | 32.578947 | 17.473684 |
def underlying_variable_ref(t):
"""Find the underlying variable ref.
Traverses through Identity, ReadVariableOp, and Enter ops.
Stops when op type has Variable or VarHandle in name.
Args:
t: a Tensor
Returns:
a Tensor that is a variable ref, or None on error.
"""
while t.op.type in ["Identity",... | [
"def",
"underlying_variable_ref",
"(",
"t",
")",
":",
"while",
"t",
".",
"op",
".",
"type",
"in",
"[",
"\"Identity\"",
",",
"\"ReadVariableOp\"",
",",
"\"Enter\"",
"]",
":",
"t",
"=",
"t",
".",
"op",
".",
"inputs",
"[",
"0",
"]",
"op_type",
"=",
"t",... | 23.3 | 23.15 |
def lonlat_point(self, lon, lat):
"""Add a latitude/longitude point to the query.
This adds a request for a (`lon`, `lat`) point. This modifies the query
in-place, but returns `self` so that multiple queries can be chained together on
one line.
This replaces any existing spatia... | [
"def",
"lonlat_point",
"(",
"self",
",",
"lon",
",",
"lat",
")",
":",
"self",
".",
"_set_query",
"(",
"self",
".",
"spatial_query",
",",
"longitude",
"=",
"lon",
",",
"latitude",
"=",
"lat",
")",
"return",
"self"
] | 28.541667 | 23.541667 |
def makeSubDir(dirName):
"""Makes a given subdirectory if it doesn't already exist, making sure it us public.
"""
if not os.path.exists(dirName):
os.mkdir(dirName)
os.chmod(dirName, 0777)
return dirName | [
"def",
"makeSubDir",
"(",
"dirName",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
")",
":",
"os",
".",
"mkdir",
"(",
"dirName",
")",
"os",
".",
"chmod",
"(",
"dirName",
",",
"0777",
")",
"return",
"dirName"
] | 32.571429 | 9.571429 |
def p_numerical_expr(self, p):
'''numerical_expr : expr PLUS expr
| expr MINUS expr
| expr TIMES expr
| expr DIV expr
| MINUS expr %prec UMINUS
| PLUS expr %prec UMINUS
... | [
"def",
"p_numerical_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"2",
"]",
",",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
")",
")",
"elif",
"len",
... | 36.866667 | 7.133333 |
def refresh():
"""Scan over all the involved directories and load configs from them."""
override_files = []
for stack in traceback.extract_stack():
f = os.path.join(os.path.dirname(stack[0]), OVERRIDE_FILE)
if f not in override_files:
override_files.insert(0, f)
if OVERRIDE_F... | [
"def",
"refresh",
"(",
")",
":",
"override_files",
"=",
"[",
"]",
"for",
"stack",
"in",
"traceback",
".",
"extract_stack",
"(",
")",
":",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"stack",
"[",
"0",
"]... | 41.384615 | 15 |
def convert(model, name=None, initial_types=None, doc_string='', target_opset=None,
targeted_onnx=onnx.__version__, custom_conversion_functions=None, custom_shape_calculators=None):
'''
This function converts the specified CoreML model into its ONNX counterpart. Some information such as the produced... | [
"def",
"convert",
"(",
"model",
",",
"name",
"=",
"None",
",",
"initial_types",
"=",
"None",
",",
"doc_string",
"=",
"''",
",",
"target_opset",
"=",
"None",
",",
"targeted_onnx",
"=",
"onnx",
".",
"__version__",
",",
"custom_conversion_functions",
"=",
"None... | 51.106061 | 32.590909 |
def _simplify_feature_value(self, name, value):
"""Return simplified and more pythonic feature values."""
if name == 'prefix':
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
# [::-1] to reverse order and go from lowest to highest pr... | [
"def",
"_simplify_feature_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"==",
"'prefix'",
":",
"channel_modes",
",",
"channel_chars",
"=",
"value",
".",
"split",
"(",
"')'",
")",
"channel_modes",
"=",
"channel_modes",
"[",
"1",
":... | 31.615385 | 18.307692 |
def go(func, *args, **kwargs):
"""
Run a function in a new tasklet, like a goroutine.
If the goroutine raises an unhandled exception (*panics*),
the :func:`goless.on_panic` will be called,
which by default logs the error and exits the process.
:param args: Positional arguments to ``func``.
... | [
"def",
"go",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"safe_wrapped",
"(",
"f",
")",
":",
"# noinspection PyBroadException",
"try",
":",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
":",
"on_panic",
... | 29.210526 | 15.736842 |
def refresh(self, force_cache=False):
"""Get all blink cameras and pulls their most recent status."""
self.network_info = api.request_network_status(self.blink,
self.network_id)
self.check_new_videos()
for camera_name in self.cameras... | [
"def",
"refresh",
"(",
"self",
",",
"force_cache",
"=",
"False",
")",
":",
"self",
".",
"network_info",
"=",
"api",
".",
"request_network_status",
"(",
"self",
".",
"blink",
",",
"self",
".",
"network_id",
")",
"self",
".",
"check_new_videos",
"(",
")",
... | 56.5 | 15.8 |
def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]:
"""Parse all dependencies out of the setup.py script."""
essential_packages: PackagesType = {}
test_packages: PackagesType = {}
essential_duplicates: Set[str] = set()
test_duplicates: Set[str] = set()
with open('setup.p... | [
"def",
"parse_setup",
"(",
")",
"->",
"Tuple",
"[",
"PackagesType",
",",
"PackagesType",
",",
"Set",
"[",
"str",
"]",
",",
"Set",
"[",
"str",
"]",
"]",
":",
"essential_packages",
":",
"PackagesType",
"=",
"{",
"}",
"test_packages",
":",
"PackagesType",
"... | 43.741935 | 13.387097 |
def get_genome_ref(genome_build, aligner, galaxy_base):
"""Retrieve the reference genome file location from galaxy configuration.
"""
ref_files = dict(
bowtie = "bowtie_indices.loc",
bwa = "bwa_index.loc",
samtools = "sam_fa_indices.loc",
maq = "bowtie_indices... | [
"def",
"get_genome_ref",
"(",
"genome_build",
",",
"aligner",
",",
"galaxy_base",
")",
":",
"ref_files",
"=",
"dict",
"(",
"bowtie",
"=",
"\"bowtie_indices.loc\"",
",",
"bwa",
"=",
"\"bwa_index.loc\"",
",",
"samtools",
"=",
"\"sam_fa_indices.loc\"",
",",
"maq",
... | 36.277778 | 13.5 |
async def _trigger_event(self, event, *args, **kwargs):
"""Invoke an event handler."""
run_async = kwargs.pop('run_async', False)
ret = None
if event in self.handlers:
if asyncio.iscoroutinefunction(self.handlers[event]) is True:
if run_async:
... | [
"async",
"def",
"_trigger_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"run_async",
"=",
"kwargs",
".",
"pop",
"(",
"'run_async'",
",",
"False",
")",
"ret",
"=",
"None",
"if",
"event",
"in",
"self",
".",
"... | 43.888889 | 17.444444 |
def _match_to_morph_parents(self, type, results):
"""
Match the results for a given type to their parent.
:param type: The parent type
:type type: str
:param results: The results to match to their parent
:type results: Collection
"""
for result in result... | [
"def",
"_match_to_morph_parents",
"(",
"self",
",",
"type",
",",
"results",
")",
":",
"for",
"result",
"in",
"results",
":",
"if",
"result",
".",
"get_key",
"(",
")",
"in",
"self",
".",
"_dictionary",
".",
"get",
"(",
"type",
",",
"[",
"]",
")",
":",... | 36.9375 | 17.8125 |
def return_max_phrase(run, idx, dictionary):
"""
Finds the maximal phrase in the run starting from the given index. It uses the dictionary to find sequences of ids
that can be merged into a phrase.
:param run: a run of ids
:param idx: the position in the run to start looking fo... | [
"def",
"return_max_phrase",
"(",
"run",
",",
"idx",
",",
"dictionary",
")",
":",
"if",
"idx",
"<",
"len",
"(",
"run",
")",
"and",
"run",
"[",
"idx",
"]",
"in",
"dictionary",
":",
"id",
"=",
"run",
"[",
"idx",
"]",
"rv",
",",
"rv_idx",
"=",
"Phras... | 53.857143 | 28.809524 |
def processConfig(self, worker_config):
"""Update the pool configuration with a worker configuration.
"""
self.config['headless'] |= worker_config.get("headless", False)
if self.config['headless']:
# Launch discovery process
if not self.discovery_thread:
... | [
"def",
"processConfig",
"(",
"self",
",",
"worker_config",
")",
":",
"self",
".",
"config",
"[",
"'headless'",
"]",
"|=",
"worker_config",
".",
"get",
"(",
"\"headless\"",
",",
"False",
")",
"if",
"self",
".",
"config",
"[",
"'headless'",
"]",
":",
"# La... | 44.8 | 11 |
def unfinished_objects(self):
'''
Leaves only versions of those objects that has some version with
`_end == None` or with `_end > right cutoff`.
'''
mask = self._end_isnull
if self._rbound is not None:
mask = mask | (self._end > self._rbound)
oids = se... | [
"def",
"unfinished_objects",
"(",
"self",
")",
":",
"mask",
"=",
"self",
".",
"_end_isnull",
"if",
"self",
".",
"_rbound",
"is",
"not",
"None",
":",
"mask",
"=",
"mask",
"|",
"(",
"self",
".",
"_end",
">",
"self",
".",
"_rbound",
")",
"oids",
"=",
... | 40 | 16.4 |
def simple_interaction_kronecker_deprecated(snps,phenos,covs=None,Acovs=None,Asnps1=None,Asnps0=None,K1r=None,K1c=None,K2r=None,K2c=None,covar_type='lowrank_diag',rank=1,searchDelta=False):
"""
I-variate fixed effects interaction test for phenotype specific SNP effects.
(Runs multiple likelihood ratio tests... | [
"def",
"simple_interaction_kronecker_deprecated",
"(",
"snps",
",",
"phenos",
",",
"covs",
"=",
"None",
",",
"Acovs",
"=",
"None",
",",
"Asnps1",
"=",
"None",
",",
"Asnps0",
"=",
"None",
",",
"K1r",
"=",
"None",
",",
"K1c",
"=",
"None",
",",
"K2r",
"="... | 50.581967 | 29.237705 |
def heatmaps_to_keypoints(maps, rois):
"""Extract predicted keypoint locations from heatmaps. Output has shape
(#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob)
for each keypoint.
"""
# This function converts a discrete image coordinate in a HEATMAP_SIZE x
# HEATMAP_SIZ... | [
"def",
"heatmaps_to_keypoints",
"(",
"maps",
",",
"rois",
")",
":",
"# This function converts a discrete image coordinate in a HEATMAP_SIZE x",
"# HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain",
"# consistency with keypoints_to_heatmap_labels by using the conversion from",
... | 42.818182 | 16.381818 |
def __write_variables_2(self, col):
"""
Use one column of data, to write one line of data in the variables section.
:return none:
"""
col = self.__convert_keys_1("Variables", col)
# Write one line for each column. One line has all metadata for one column.
for ent... | [
"def",
"__write_variables_2",
"(",
"self",
",",
"col",
")",
":",
"col",
"=",
"self",
".",
"__convert_keys_1",
"(",
"\"Variables\"",
",",
"col",
")",
"# Write one line for each column. One line has all metadata for one column.",
"for",
"entry",
"in",
"NOAA_KEYS_BY_SECTION"... | 47.84127 | 18.507937 |
def print_stdout(self):
""" This function will read the standard out of the program and print it
"""
# First we check if the file we want to print does exists
if self.wdir != '':
stdout = "%s/%s"%(self.wdir, self.stdout)
else:
stdout = self.stdout
if os.path.exists(... | [
"def",
"print_stdout",
"(",
"self",
")",
":",
"# First we check if the file we want to print does exists",
"if",
"self",
".",
"wdir",
"!=",
"''",
":",
"stdout",
"=",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"wdir",
",",
"self",
".",
"stdout",
")",
"else",
":",
"s... | 40.153846 | 13.461538 |
def MigrateInstance(r, instance, mode=None, cleanup=None):
"""
Migrates an instance.
@type instance: string
@param instance: Instance name
@type mode: string
@param mode: Migration mode
@type cleanup: bool
@param cleanup: Whether to clean up a previously failed migration
"""
bo... | [
"def",
"MigrateInstance",
"(",
"r",
",",
"instance",
",",
"mode",
"=",
"None",
",",
"cleanup",
"=",
"None",
")",
":",
"body",
"=",
"{",
"}",
"if",
"mode",
"is",
"not",
"None",
":",
"body",
"[",
"\"mode\"",
"]",
"=",
"mode",
"if",
"cleanup",
"is",
... | 23.863636 | 19.681818 |
def find_rotation_scale(im0, im1, isccs=False):
"""Compares the images and return the best guess for the rotation angle,
and scale difference.
Parameters
----------
im0: 2d array
First image
im1: 2d array
Second image
isccs: boolean, default False
Set to True if the ... | [
"def",
"find_rotation_scale",
"(",
"im0",
",",
"im1",
",",
"isccs",
"=",
"False",
")",
":",
"# sanitize input",
"im0",
"=",
"np",
".",
"asarray",
"(",
"im0",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"im1",
"=",
"np",
".",
"asarray",
"(",
"im1",
... | 31.265306 | 18.714286 |
def content_types(self):
"""
Provides access to content type management methods for content types of an environment.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types
:return: :class:`EnvironmentContentTypesProxy <cont... | [
"def",
"content_types",
"(",
"self",
")",
":",
"return",
"EnvironmentContentTypesProxy",
"(",
"self",
".",
"_client",
",",
"self",
".",
"space",
".",
"id",
",",
"self",
".",
"id",
")"
] | 46.5 | 40.375 |
def _loc(form: Union[LispForm, ISeq]) -> Optional[Tuple[int, int]]:
"""Fetch the location of the form in the original filename from the
input form, if it has metadata."""
try:
meta = form.meta # type: ignore
line = meta.get(reader.READER_LINE_KW) # type: ignore
col = meta.get(reade... | [
"def",
"_loc",
"(",
"form",
":",
"Union",
"[",
"LispForm",
",",
"ISeq",
"]",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"try",
":",
"meta",
"=",
"form",
".",
"meta",
"# type: ignore",
"line",
"=",
"meta",
".",
"ge... | 40.416667 | 17 |
def delete_calendar_event(self, calendar_id, event_id, params=None):
"""
`<>`_
:arg calendar_id: The ID of the calendar to modify
:arg event_id: The ID of the event to remove from the calendar
"""
for param in (calendar_id, event_id):
if param in SKIP_IN_PATH... | [
"def",
"delete_calendar_event",
"(",
"self",
",",
"calendar_id",
",",
"event_id",
",",
"params",
"=",
"None",
")",
":",
"for",
"param",
"in",
"(",
"calendar_id",
",",
"event_id",
")",
":",
"if",
"param",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(... | 38 | 19.733333 |
def append(self, frame_p):
"""
Add frame to the end of the message, i.e. after all other frames.
Message takes ownership of frame, will destroy it when message is sent.
Returns 0 on success. Deprecates zmsg_add, which did not nullify the
caller's frame reference.
"""
return lib.zmsg_appe... | [
"def",
"append",
"(",
"self",
",",
"frame_p",
")",
":",
"return",
"lib",
".",
"zmsg_append",
"(",
"self",
".",
"_as_parameter_",
",",
"byref",
"(",
"zframe_p",
".",
"from_param",
"(",
"frame_p",
")",
")",
")"
] | 46.625 | 21.125 |
def serialize_to_string(self, name, datas):
"""
Serialize given datas to a string.
Simply return the value from required variable``value``.
Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.
Ret... | [
"def",
"serialize_to_string",
"(",
"self",
",",
"name",
",",
"datas",
")",
":",
"value",
"=",
"datas",
".",
"get",
"(",
"'value'",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"msg",
"=",
"(",
"\"String reference '{}' lacks of required 'value' variable ... | 28.52381 | 20.047619 |
def getN21PG(rates, ver, lamb, br, reactfn):
with h5py.File(str(reactfn), 'r', libver='latest') as fid:
A = fid['/N2_1PG/A'].value
lambnew = fid['/N2_1PG/lambda'].value.ravel(order='F')
franckcondon = fid['/N2_1PG/fc'].value
tau1PG = 1 / np.nansum(A, axis=1)
"""
solve for base ... | [
"def",
"getN21PG",
"(",
"rates",
",",
"ver",
",",
"lamb",
",",
"br",
",",
"reactfn",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"str",
"(",
"reactfn",
")",
",",
"'r'",
",",
"libver",
"=",
"'latest'",
")",
"as",
"fid",
":",
"A",
"=",
"fid",
"["... | 37.916667 | 22.416667 |
def on_moved(self, event):
"""
Called when a file or a directory is moved or renamed.
Many editors don't directly change a file, instead they make a
transitional file like ``*.part`` then move it to the final filename.
Args:
event: Watchdog event, either ``watchdog.... | [
"def",
"on_moved",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"_event_error",
":",
"# We are only interested for final file, not transitional file",
"# from editors (like *.part)",
"pathtools_options",
"=",
"{",
"'included_patterns'",
":",
"self",
".",... | 44.72 | 20 |
def resample(self,N):
"""Returns a random sampling.
"""
return rand.random(size=N)*(self.maxval - self.minval) + self.minval | [
"def",
"resample",
"(",
"self",
",",
"N",
")",
":",
"return",
"rand",
".",
"random",
"(",
"size",
"=",
"N",
")",
"*",
"(",
"self",
".",
"maxval",
"-",
"self",
".",
"minval",
")",
"+",
"self",
".",
"minval"
] | 36.25 | 13.75 |
def req2frame(req, N: int=0):
"""
output has to be numpy.arange for > comparison
"""
if req is None:
frame = np.arange(N, dtype=np.int64)
elif isinstance(req, int): # the user is specifying a step size
frame = np.arange(0, N, req, dtype=np.int64)
elif len(req) == 1:
fram... | [
"def",
"req2frame",
"(",
"req",
",",
"N",
":",
"int",
"=",
"0",
")",
":",
"if",
"req",
"is",
"None",
":",
"frame",
"=",
"np",
".",
"arange",
"(",
"N",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"elif",
"isinstance",
"(",
"req",
",",
"int",
"... | 36.1 | 14.6 |
def fillna(self, value, limit=None, inplace=False, downcast=None):
""" fillna on the block with the value. If we fail, then convert to
ObjectBlock and try again
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if not self._can_hold_na:
if inplace:
... | [
"def",
"fillna",
"(",
"self",
",",
"value",
",",
"limit",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"downcast",
"=",
"None",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"not",
"self",
".",
"_can_h... | 39.530612 | 18.469388 |
def get_client(
client, profile_name, aws_access_key_id, aws_secret_access_key,
region=None,
):
"""Shortcut for getting an initialized instance of the boto3 client."""
boto3.setup_default_session(
profile_name=profile_name,
aws_access_key_id=aws_access_key_id,
aws_secret_access_... | [
"def",
"get_client",
"(",
"client",
",",
"profile_name",
",",
"aws_access_key_id",
",",
"aws_secret_access_key",
",",
"region",
"=",
"None",
",",
")",
":",
"boto3",
".",
"setup_default_session",
"(",
"profile_name",
"=",
"profile_name",
",",
"aws_access_key_id",
"... | 30.769231 | 18.538462 |
def add_properties(self):
"""
Called during post processing of result
Any properties defined in your subclass will get exposed as members of the result json from the search
"""
for property_name in [p[0] for p in inspect.getmembers(self.__class__) if isinstance(p[1], property)]:
... | [
"def",
"add_properties",
"(",
"self",
")",
":",
"for",
"property_name",
"in",
"[",
"p",
"[",
"0",
"]",
"for",
"p",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
".",
"__class__",
")",
"if",
"isinstance",
"(",
"p",
"[",
"1",
"]",
",",
"property",
... | 56.857143 | 29.428571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.