content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def add_to_final(samples, haplotypes):
"""Make final list of samples and haplotypes"""
#keep track of samples with alleles
sampled = []
for seq in haplotypes:
samples[seq[0]].append(seq[1])
sampled.append(seq[0])
#if not sequenced, add a '-9' to sample
for key in samples:
... | 8dcc988922f1354ce0ed6fc9875be2a936a2c5d7 | 651,889 |
def _check_data_pont(data_point_arr):
"""
Check whether our dp is valid return tru if it is false otherwise
"""
# Return False if any of the valuse are empty
return filter(lambda x: x==True, map(lambda x: data_point_arr[x].strip()=='',data_point_arr)) | 6b6059c7158a740c50fa1ea9d48fa762864c7afc | 651,890 |
def generate_timemap_from_timemap_data(urir, timemap_data):
"""This function generates a TimeMap for `urir` given `timemap_data`
stored in a dictionary.
"""
timemap_dict = {}
timemap_dict["original_uri"] = urir
timemap_dict["timegate_uri"] = "from-warc::timegate::{}".format(urir)
timemap_d... | 44e387e2a546e7908ca26810fcd73d4a45271e1a | 651,891 |
def import_unpaywall():
"""Import DOI list for NCBI Requests.
Returns
-------
list
List of tuples with (doi, result)
"""
# ncbi_url, pm_id, pmc_id
data = [
(
'10.1371/journal.pone.0141854',
{
'url': [
'https://jour... | 2ad0774ae849a777894ee91a5d5038ba0800deb2 | 651,892 |
def species_trunk():
""" species trunk directory name
"""
return 'SPC' | b52b10d0a0be924bacfe19c96f8e999221d1e6f0 | 651,893 |
def rescale_image(img):
"""!
@brief Rescales image to a smaller sampling size.
@param img The PIL.Image object.
@return Tuple of the new width and height of image.
"""
width, height = img.size
default_480p = [854, 480] # 480p SD resolution with 16:9 ratio.
default_360p = [640, 360] ... | 05eb40333b5d7a0262a4edfb50a63c3d59f48866 | 651,894 |
def get_max_value(array):
"""
Finds (the first occurence of) maximum value in a 1D array.
:param array: 1D array (there is no safety check on that)
:return: (index, value)
index Index of the maximum element.
value Value of the maximum element.
"""
max_val = max(array)
... | ff4103d209dfd45606404cad6226d0e3424f0670 | 651,896 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary. Structured data with the following schema:
{
"pmtu": integer,
"forward_h... | 103493dab5f9ca979d73f3d4c65642e492a36c4c | 651,897 |
def add_lowercase_context_to_sequences(seq, uc_s, uc_e,
convert_to_rna=False):
"""
Given a sequence and uppercase middle region start (uc_s) and end (uc_e),
make context region upstream + downstream lowercase.
Two coordinates should be one-based.
Return lowerca... | 8fff58cb27fb03059b4323458d5e744443f6559d | 651,898 |
from pathlib import Path
import re
def guess_file(path: Path) -> str:
"""Guess the type of a file and return the corresponding file extension."""
lines = path.read_text().splitlines()
MAX_LINES = 500 # noqa: N806
f77ish = True
f90ish = False
for i, line in enumerate(lines):
if i >=... | f23ad6217ca06730c0f7b802f3fab78f54615b02 | 651,899 |
def sigmoid_derivative(output):
"""Sigmoid激活函数求导
:param output: 激活函数的输出值
:return: 求导计算结果
"""
return output * (1.0 - output) | dc1b798daab83a55d05cc2bff45178133559e4f0 | 651,900 |
import numpy
def ackley(x):
"""
The Ackley function.
Parameters
----------
x : array_like
1-D array of points at which the Ackley function is to be computed.
Returns
-------
float
The value of the Ackley function.
"""
x = numpy.asarray(x)
ndim = x.size
... | 919b88c88226bb23f834a6056d8e0d77432c7c63 | 651,901 |
import argparse
def parse_hgt_mode(hgt_mode_req_in):
"""
parses command line height mode settings
:param hgt_mode_req_in:
:return:
"""
if type(hgt_mode_req_in) == str:
if hgt_mode_req_in == 'baro':
return [0, ]
elif hgt_mode_req_in in ['lidar', 'l']:
ret... | 85d45350fe0fda7d15a3dc74251591bfe263934e | 651,902 |
def replace_other(line, dic):
"""Заменяем всё подряд, что не попало под другие фильтры"""
for i, j in dic.items():
line = line.replace(i, j)
return line | 6153d9af15e5dac1448a40a66473385f5b658196 | 651,905 |
def candidateComponents(A,B,a):
"""
Identifies all components of B that could be the target of the Hausdorff
distance from segment a on A.
Parameters
----------
A : [(x,y),...] list of tuples
The coordinates of the main polyline.
B : [(x,y),...] list of tuples
The coordin... | c5dbdb433ce29410da9053d0cd3c14e89803e562 | 651,906 |
def format_date(date):
"""format the date of blog to correct format"""
date = date.strftime('%H:%M:%S %m/%d/%Y')
return date | f1442fee30b6b7d972db009581ccc6501f5ffb3e | 651,907 |
def check_model_termination(ClockStruct,InitCond):
"""
Function to check and declare model termination
*Arguments:*\n
`ClockStruct` : `ClockStructClass` : model time paramaters
`InitCond` : `InitCondClass` : containing current model paramaters
*Returns:*
`ClockStruct` : `ClockStructC... | 6e25a41a92b64b13f3d2db424a9fbe082d31bf24 | 651,908 |
import sys
import logging
def create_class_instance(cls):
"""
Create a class instance.
This will ensure that even if the provided class definition is outdated (because of a reload)
the latest definition (available from sys.modules) will be used.
:param cls: A class definition to inspect.
:retu... | 2442ae0840406bcf960b7d0bff6d15b647801c96 | 651,909 |
import os
import fnmatch
def get_data_files(package_dir, patterns):
"""Returns filepaths matching the given pattern."""
paths = set()
for directory, _, filenames in os.walk(package_dir):
for pattern in patterns:
for filename in fnmatch.filter(filenames, pattern):
base_p... | 4681e1d7a408bcc2215e46848cffa156d3533227 | 651,910 |
def server(start_server):
"""Starts redis-server instance."""
return start_server('A') | 2b7eecdc1bd29f76df9961ae9c08869d48d5e58c | 651,911 |
def getSNPplas(chr_numb, print_dict):
"""Check candidate SNP positions in print_dict for reports in the local PlasmoDB database. The database is available for Plasmodium falciparum
and the version 3 (_v3). All IDs in a database file have to be sorted according to the position!
The function will return ... | e4f52e1e4ea28e5dd824ee77c982296850b43a92 | 651,912 |
import argparse
def parse_command_line_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description=(
'Media Translation live subtitles demo.'))
parser.add_argument(
'--dev',
default=0,
type=int,
help='USB Microphone d... | b945d015a6d421574800b0543b5384d1e59a338a | 651,913 |
import os
def _path_split(file):
"""
Split a path in head and tail.
Args:
file (str): The file path.
Returns:
list[str], list of file tail
"""
file_dir, name = os.path.split(file)
if file_dir:
sep = file[len(file_dir) - 1]
if file_dir.startswith(sep):
... | ae17049b7b65b0a69839d7f4af00df6d4831da21 | 651,914 |
def query_schema(name, params):
"""
Query Data type Objects
:param name:
:param params:
:return:
"""
return '''
class %sItems(graphene.ObjectType):
%s
''' % (name.title(), params) | 1f2180fe090a2c6d90b6eeb3c0a756653670b181 | 651,915 |
def gtk_false(*args):
"""
GTK False default handler
"""
return False | 0d99aa7fb121e3210d1bd3401aa15b48238a7da4 | 651,916 |
from typing import List
import os
def get_all_file_paths(directory: str, extension: str = "") -> List[str]:
"""
Get all nested files from a directory with a specific extension.
usage: get_all_file_paths("packages/valory/skills")
"""
return [
os.path.join(root, file)
for root, _, ... | df2c57430320dc5d93511e60c6548a0611119e44 | 651,917 |
def int_or_none(value):
"""
Returns int or none if int could not be converted
"""
try:
return int(value)
except ValueError:
return None | 7bc702089d855fd9859dce0aca1c1e36628faf0e | 651,918 |
def tables_cleanup_order(tables):
"""
Defines order in which will be tables cleaned up on datastore reset.
"""
return tables | c751249a8ac1895c155f1c29c1cb281a47bce2ad | 651,919 |
from os import listdir
import re
def find_files_like(datapath, pattern):
"""Finds files in a folder whose name matches a pattern
This function looks for files in folder `datapath` that match a regular
expression `pattern`.
Parameters
----------
datapath : str
Path to search
patte... | 788468c82b6483a63b05803feeeea5dde8d9eb75 | 651,920 |
def avg_item_count_character(cursor):
"""Returns the average number of items per character from sqlite cursor.
Args:
cursor (sqlite3.Cursor): cursor to sqlite database
Returns:
(float) Average number of items per character
"""
return cursor.execute("""SELECT AVG(item_ct)
FROM(
... | 4d3a7ebbd07fec822fd609e6cee7ddfde79cb7e5 | 651,921 |
def parse_uri(uri):
"""Extracts the host, port and db from an uri"""
host, port, db = uri, 6379, 0
if len(host.split('/')) == 2:
host, db = host.split('/')
if len(host.split(':')) == 2:
host, port = host.split(':')
return host, int(port), int(db) | 52750de603818952530b9418441130d69ce40d1a | 651,922 |
def _request_content_to_string(content):
"""
Converts the given list of request tuples to a string.
@arguments: content, a list of request tuples (<net> <sta> <chan> <loc> <begtime> <endtime> <constr>)
@return: the string representation
"""
retstr = ""
for elem in content:
retstr = "%s%s %s %s %s %s %s\n" % ... | 3b26e662a4215a03a3f87d59d4c64426648b24d6 | 651,923 |
def distribution_to_particle(predictions, n_particles=50):
""" Convert a distribution prediction to a particle prediction
Args:
predictions (Distribution): a batch of distribution predictions.
n_particles (int): the number of particles to sample.
"""
return predictions.sample... | cc4c9dbb9d735db5e094e87c177156717bbf3a6c | 651,924 |
import socket
import struct
def _mk_mcast_sock(mcast_grp, mcast_port, all_grps=True):
"""
multicast socket setup
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket... | 21e3e6043efa828668768fbbd4220b273158c367 | 651,925 |
from typing import Any
def get_lit_link(e: Any, lit_in_brackets: Any) -> str:
"""Get a brenda url from a value of the 'literature' column."""
lit = str(lit_in_brackets).replace("[", "").replace("]", "")
url = f"https://www.brenda-enzymes.org/literature.php?e={str(e)}&r={lit}"
return f'<a href = "{url}... | 3504b562f62bb473b6b7f708da5407d81e0dbd40 | 651,928 |
def nulls(data):
"""Returns keys of values that are null (but not bool)"""
return [k for k in data.keys()
if not isinstance(data[k], bool) and not data[k]] | 0dcdd0f98467e85bc99b8d9ffb2a45e25172f82a | 651,929 |
def test_varargs_complex():
"""Complex vararg fuzzing tests."""
return """
fn main() {
{dest} = test_va(0, 1, 1::u8, 2::u2, 3::u4);
}
fn test_va(no_: u1, pe_: u8, ...) -> u8 {
var a: *u8;
var b: *u2;
var c: *u4;
var ptr := var_args::*u1;
ptr = ptr -... | 3cc241801ac1377fefa6f24e5e13854d45801d8f | 651,930 |
def _process_ratios(value):
"""Helper function to convert the GPS ratios in float format"""
return float(value[0])/float(value[1]) | 3066a891014a38954d45587ca067ec4e6a224904 | 651,931 |
def normalize_path(path):
"""
Returns a normalized path from a `path` string.
"""
return "/" + path.strip("/") | fd7e4956bb09e048b32670b6050f51fa3183431b | 651,932 |
def Canto(d,r,l,t):
""" Determina el canto donde d en mt y l y t en mm"""
return d + (0.5*l + t + r)/1000 | 9d12e99b179b163a8676db44186516413684edc4 | 651,933 |
def latex_header_package_import(*args):
"""generates the string to import the desired latex package based on
their names.
"""
typebased_op_support =\
lambda entry_o :\
{
"str": lambda entry: r"\\usepackage{%s}" % entry
, "tuple": lambda entry: r"\\usepackage[%s]... | bb40e2b7b1fa1556b466556b25759f09d16f9f7c | 651,934 |
def check_image_extension(filename):
"""Checks filename extension."""
ext = ['.jpg', '.jpeg', '.png']
for e in ext:
if filename.endswith(e):
return True
return False | 2fe6420dee1a7a04b488927c4004712a94b69ffb | 651,935 |
def get_vgci_warnings(tc):
"""
extract warnings from the parsed test case stderr
"""
warnings = []
if tc['stderr']:
for line in tc['stderr'].split('\n'):
# For each line
if "WARNING" in line and "vgci" in line:
# If it is a CI warning, keep it
... | d167c66374754e6099cb20d05e49c5ad609b472b | 651,936 |
from pathlib import Path
def get_reps_path(params, split):
"""Return path to directory where dialogue representations are stored."""
directory = Path(params.path_to_representations)
path_r = f'{params.bot}Bot_{params.bot_version}_representations_{split}.h5'
return directory / path_r | 563aa05a90fe5c45b26954ebd6775aac886f8a42 | 651,937 |
import re
def detect_other_protocol(server_handshake_bytes):
"""
Looks at the server handshake bytes to try and detect a different protocol
:param server_handshake_bytes:
A byte string of the handshake data received from the server
:return:
None, or a unicode string of "ftp", "http",... | 953feeac84c5a977b730acd7653928b9ca64f0d3 | 651,938 |
import pathlib
def _check_export_suffix(src, dest, edited):
"""Helper function for exporting photos to check file extensions of destination path.
Checks that dst file extension is appropriate for the src.
If edited=True, will use src file extension of ".jpeg" if None provided for src.
Args:
... | 70bd5d0a2afa6297fcdd998c8392ed045134a3ae | 651,939 |
import logging
def _get_logger(logger_name):
""" logging.getLogger scales very bad when using threads. Caching its result is far faster """
return logging.getLogger(logger_name) | d54068823bd26c4e59521c687214468133dffb61 | 651,940 |
import os
def get_file_list(dir, regex=None):
"""Get List of files from directory
Input: DIR, directory to retrieve content from
regex: the regex used to filter out unwanted files
Return:
filename_list, list of contents filename, sorted by sorted()
"""
if not os.pat... | 7b8cb5c5b5ad4ebd6762108eea4834f322e4fb93 | 651,941 |
import re
def _include(path, includes, excludes):
"""
:params path: The file path to check whether to include
:params includes: List of include regexs to apply
:params excludes: List of exclude regexs to apply
:returns True if the file path should be included, False
"""
if includes is No... | 0e6c8c4c883537034d6a5a53dc57bb9e0936aa55 | 651,943 |
def inverted_y(coordinate_y, height):
"""反转y坐标。
Args:
coordinate_y: y坐标。
height: 高度。
Returns:
新的y坐标
"""
return abs(coordinate_y - height) | 4d99fe184c567f3fb22c210357fbb6bec62ba4e8 | 651,944 |
def get_phi_comps_from_recfile(recfile):
"""read the phi components from a record file by iteration
Args:
recfile (`str`): pest record file name
Returns:
`dict`: nested dictionary of iteration number, {group,contribution}
Note:
It is really poor form to use the record file in... | 7c83c1853adb0d5ed17a32caf98ce2e48b8df56a | 651,946 |
import collections
def graph_inputs(name, **kwargs):
"""Creates a namedtuple of the given keys and values.
Args:
name (string): Name of the tuple.
kwargs (tf.Tensor): One or more tensor(s) to add to the
namedtuple's values. The parameter names are used as keys
in the n... | dbdafaf68d4540de8f1e10ccb71d8ae2aeb13ead | 651,947 |
def _port_in_range(value):
"""Return True if port is in expected range."""
return 49512 <= value <= 65535 | b8041e2e9c6b055577744c9ecc840ca55890c1ef | 651,948 |
import re
def encode_textfield_ncr(content):
"""
Encodes the contents for CIF textfield in Numeric Character Reference.
:param content: a string with contents
:return: encoded string
"""
def match2ncr(m):
prefix = ''
postfix = ''
if 'prefix' in m.groupdict().keys():
... | 7e231f8716b76efa22e274ee0e157aac401bccf4 | 651,949 |
import numpy
def get_random_block_from_data(data, batch_size):
"""
DOCSTRING
"""
start_index = numpy.random.randint(0, len(data) - batch_size)
return data[start_index:(start_index + batch_size)] | 3ea5e2e79d52f7d0baed044affb3c113a7fefd28 | 651,950 |
def results_summary(results_data):
"""
Return a summary of the results stored in a dataframe.
Returns a dict containing unique entities in each column
Ignores the exp_data, f_min, min_params and time columns
"""
unique_vals_dict = {}
col_list = list(results_data.columns.values)
... | 8de33c0d883d9e224a58e0316fa8109fa4f1edaa | 651,951 |
def makeIntervals(evts):
"""From evts=[a,b,c], create a list of intervals: [(0,a), (b,c)]
From evts=[a,b,c,d], create a list of intervals: [(0,a), (b,c), (d,1)].
Assumes all values in evts are in (0,1)"""
if evts == []: return [(0.0, 1.0)]
evts.sort()
left = 0.0
intervals = []
for e in evts:
if left >= 0.0:
... | 093299058904966682e9df91d96c6cc7adc430f2 | 651,952 |
def get_lone_pair():
"""
Pi donars increase the value
"""
return {'C': 0, 'H': 0, 'F': 0.5, 'N': 1, 'O': 0.8} | 731abc09b75d6de02010491f7f1851eace9badf8 | 651,953 |
import os
def yaml_to_path_helper(yaml_path):
"""
Replace forward slashes with current OS path separater.
"""
return yaml_path.replace('/', os.path.sep) | 4b0dfd48b9f8741c23b4abdc14e8d81dc66e0633 | 651,954 |
import re
import keyword
def is_valid_identifier(var, allow_unicode=False):
"""Return true if var contains a valid Python identifier
Parameters
----------
val : string
identifier to check
allow_unicode : bool (default: False)
if True, then allow Python 3 style unicode identifiers.... | 27e5f63de31d3f713395be5d0c9867cba0d62047 | 651,955 |
import mimetypes
def mimetype(file):
""" return mime type of file else a blank string"""
if file and file.url:
return mimetypes.guess_type(file.url, strict=True)[0]
return '' | d8ee82ef115325e51c1c9bb7e4f09c18e5cfcd34 | 651,956 |
def _validate_artman_config(config_pb):
""" Validate the parsed config_pb.
Currently, it checkes the uniqueness of the artifact name, and uniqieuness
of publishing target name in each artifact. Plus, it makes sure the
specified configuration or other input file or folder exists.
"""
artifacts =... | 2db3009308f66b64df79d36c72b5ae59ff5d3713 | 651,957 |
def prompt_user_approval() -> bool:
""" Asks the user if it's acceptable. """
return input("\nAccept? [y/N]").lower() in ['y', 'yes'] | b6b871a29e8b222ffb4034330da95bb8bdcd8fdf | 651,959 |
import re
def is_rgb_code(s: str) -> bool:
""" Returns True if `s` appears to be a single rgb escape code. """
pattern = '^\033\\[((38)|(48));2;\\d{1,3};\\d{1,3};\\d{1,3}m'
return re.match(pattern, s) is not None | 8e3c3e7b02c572786418cf4573ccaf9ed425a2dd | 651,960 |
import re
def backup_vault_name(name):
"""
Property: BackupVault.BackupVaultName
"""
vault_name_re = re.compile(r"^[a-zA-Z0-9\-\_\.]{1,50}$") # noqa
if vault_name_re.match(name):
return name
else:
raise ValueError("%s is not a valid backup vault name" % name) | 6444f6018d3c2f0cc6e4d76a0394ca39d9e55ec7 | 651,961 |
def props_of_this_event(event, ts_tuple, run):
"""
Find the set of propositions that correspond to an event.
Parameters
-----------
event: A tuple
An event is a tuple of the form (agent_no, run_pos). This argument
can either be a tuple of events (simultaneous events) or a tuple of
integers (single event).
... | a0abab647967e1f777aa47797af0e18f61cba6bd | 651,962 |
import site
from pathlib import Path
def find_pkg(name):
"""Find package in site-packages"""
for p in site.getsitepackages():
pkg_path = Path(p) / name
if pkg_path.exists():
return pkg_path
return None | da22728cc30f4f4e817dcf4f8f647fe1361cc7fb | 651,963 |
import json
def dump_record(record: dict) -> str:
"""
Helper method for comparing records.
"""
if "children" in record:
record["children"].sort()
if "parents" in record:
record["parents"].sort()
return json.dumps(record, sort_keys=True) | cb800ba4193a17c4987d97b3310094bf711a5df0 | 651,964 |
def function_dollar(field, variable_list):
"""
替换${变量名}的方法
:param field: 第一个参数是yaml文件里面定义的字段
:param variable_list: 第二个参数是变量列表
:return:
"""
if "${" in field:
for key, value in variable_list:
field = field.replace("${" + key + "}", value)
# replace(old, new)把字符... | ba7d1ec3696b9dde9558fc80dd0f2c86f54e2366 | 651,965 |
import collections
import json
def request_builder(commands, output, version='1.0', chunk='0', sid=None):
"""Encodes a NXAPI JSON request message
"""
output_to_command_type = {
'text': 'cli_show_ascii',
'json': 'cli_show',
'bash': 'bash',
'config': 'cli_conf'
}
may... | 5c55641a2079fb44d2f5d65d00e9b4aac00cfb99 | 651,967 |
import argparse
def get_args():
"""Are you tired of arguments yet? Cause there'll be way more"""
parser = argparse.ArgumentParser(
description="What are we bringing, boss?",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"items", metavar="item", ... | fa055c285ab104653b53815e08c1af9922a0255c | 651,968 |
import json
def readfile(filepath):
"""
reads a pipeline json file and returns the resulting dictionary
"""
with open(filepath, "r") as json_file:
json_data = json.load(json_file)
return json_data | 0bc68952023ef779afcd6541780e66fa44fb6088 | 651,969 |
def points_to_region(region_pts):
"""
Reverse Voronoi region polygon IDs to point ID assignments by returning a dict that maps each point ID to its
Voronoi region polygon ID. All IDs should be integers.
:param region_pts: dict mapping Voronoi region polygon IDs to list of point IDs
:return: dict ma... | 880a2c3fb91f41a37dcb218ad09799399ddacc8e | 651,973 |
def help_():
"""
Usage
"""
usage = ('salt-run network.get_cpu_count server=minion\n\n'
' Returns the number of cpus for a minion\n'
'\n\n'
'salt-run network.ping:\n'
'salt-run network.ping6:\n'
'salt-run network.ping ipversion="ipv6":\n... | 380be20c5cb865ded9424307dc292907c674db12 | 651,974 |
def clean_file_name(filename):
"""Clean the filename for the client.
If it has directory structure, purge it and give only the file name.
:param filename: file name to be cleaned
:return: cleaned filename
"""
if '/' in filename:
filename = filename.split('/')[-1]
return filename | 2cbb37d68e45ac76fb17ae99504bcc7bae2d41f1 | 651,975 |
def mean_normalize(x, mean_x, max_x, min_x):
"""
Mean normalization of input x, given dataset mean, max, and min.
>>> mean_normalize(10, 10, 15, 5)
0.0
>>> mean_normalize(15, 20, 30, 10)
-0.25
Formula from:
https://en.wikipedia.org/wiki/Feature_scaling
"""
# If min=max, all va... | 30e38ddb6cfb73c5326d2620e0c4b10ab7074ddb | 651,976 |
import logging
from typing import Callable
from typing import Any
from typing import Tuple
from typing import Dict
def obj_log(log: logging.Logger) -> Callable[..., Any]:
"""Represent logger for a given object."""
def decorator(original: Callable[..., Any]) -> Callable[..., Any]:
def wrapper(*args: T... | d1df63391c0f8364656ef9ee18c3bfda0f69a480 | 651,978 |
def ext_1(self):
"""Turns on extensions arrows for values before the first level"""
return self._ext_1 | 32b54fb5af587e52e345dd001952d94da867f47e | 651,979 |
def element(request, elements_endf):
"""Element ENDF data"""
return elements_endf[request.param] | 8965556a1d3549b838ec81a0f34ee3e335695d55 | 651,980 |
def calculate_centroid(gps_bounds):
"""Given a set of GPS boundaries, return lat/lon of centroid.
gps_bounds -- (lat(y) min, lat(y) max, long(x) min, long(x) max)
Returns:
Tuple of (lat, lon) representing centroid
"""
return (
gps_bounds[0] + float(gps_bounds[1] - gps_bounds[0])/2... | d6a9d99f011f64958d9a7ac74d582be18294da92 | 651,981 |
import re
def hasNewRating(filename):
"""
Checks if parameter file name already has a rating.
Movie ratings are in the format (\d.\d)
"""
pattern = re.compile('\[IMDb [0-9].[0-9]\]')
return pattern.search(filename) is not None | 0acf113d86d764fc59c949addb678e0263243394 | 651,982 |
from typing import Iterable
from typing import List
def _resplit(parts: Iterable[str]) -> List[str]:
"""
Given a list of strings, returns a list of lines, by splitting each string
into multiple lines where it contains newlines.
>>> _resplit([])
[]
>>> _resplit(['a', 'b'])
['a', 'b']
>... | b37d71f659858ad6f58bf68e679359b7e00fa65c | 651,983 |
def calc(exp):
"""Calculate given expression and return the result.
Args:
exp: Expression as string of the form a*x+b.
"""
res = 0
invalid = False
adds = exp.split("+")
for add in adds:
mults = add.split("*")
add = 1
for mult in mults:
if mult.isd... | 74bc607033bcdc8ecce843716ea91426ca4e085a | 651,984 |
def remove_empty_kps(coco_context):
"""Returns a list of valid keypoint annotations
Arguments:
coco_context: The initialized cocoapi class
Returns:
processed_idx (list): List of images with
valid keypoint annotations
"""
processed_idx = []
image_idx_list = coco_cont... | 5979c14336590ba5adc57a44af7a8d587bb74f1e | 651,985 |
def parse_sst_results(results):
"""
:param results:
:return:
"""
sentences = {}
lines = results.strip().split('\n')
for l in lines:
values = l.split('\t')
wntags = [x.split(' ')[-1].split('-')[-1] for x in values[1:]]
sentences[values[0]] = wntags
return sente... | 35a86582cfdf3bfa1a93ed8a9b8d9f3f38d3e5da | 651,986 |
from datetime import datetime
def to_embed_timestamp(timestamp: int) -> datetime:
"""
Convert UNIX timestamp to datetime object for embed timestamps.
:param timestamp: UNIX timestamp with seconds accuracy.
:return: Timezone native datetime
"""
return datetime.utcfromtimestamp(timestamp) | acebe00defb27122a770f5b54fe59e3c8f4bc8d9 | 651,989 |
def exists(path):
"""Return ``True`` if *path* refers to an existing path. Returns ``False`` for
broken symbolic links. On some platforms, this function may return ``False`` if
permission is not granted to execute :func:`os.stat` on the requested file, even
if the *path* physically exists."""
... | 0e7df4eb70bc26f2e4bcd0a9a1ec2de51fb1430f | 651,991 |
import itertools
def _check_duplicates(filelist, verbose=True):
"""
Checks for duplicate file entries in filelist (that are only different by
version number). Returns filelist with duplicates removed.
"""
for _, g in itertools.groupby(filelist, lambda f: f.split('_')[:-1]):
dups = list(g)
... | 0df8ef193940b2730fa4e743cf4b7fe7c7b8a95f | 651,994 |
import os
def parse_module_as_path(module_name):
"""Convert a path to a file to a format that it can be imported.
:param module_name: The module as a path.
:returns: `Tuple[str, str]` the module name (without a file ext) and the
absolute path of the dir the file lives in (or '' if the module_name... | ac12acd4fc5cfe08c61b2a0d872a0d2cca08bfb4 | 651,995 |
import re
def split_all_delimiters(string):
"""
This splits a string by all delimiters.
Args:
string (str): The string to split.
Returns:
string (str): The split string.
"""
return re.split(r'[^a-zA-Z0-9]', string) | 426ecad37a8292c5f580408f97f0a12bbc0ab63e | 651,996 |
def lectureListe():
""" Lit un fichier et de créer une liste d'entiers correspondant aux poids indiqués. """
fichier = open("fichiers/liste.txt", "r") # ouverture du fichier en lecture
liste = []
try:
for i in fichier.readlines(): # pour chaque ligne du fichier
poids = eval(i.st... | 807b5c143138736a0dbaf55beee82d128e8a6f81 | 651,997 |
def make_inverted(m, n):
"""
Given two integers m and n, write a function that returns a reversed list of integers between m and n.
If the difference between m and n is even, include m and n, otherwise don't include.
If m == n, return empty list
If m < n, swap between m and n and continue.
Example 1:
Input: ... | 83692c924162bb595d01c9b7e1cb8c818497faf1 | 651,998 |
def tag2ts(ts_tag_sequence):
"""
transform ts tag sequence to targeted sentiment
:param ts_tag_sequence: tag sequence for ts task
:return:
"""
n_tags = len(ts_tag_sequence)
ts_sequence, sentiments = [], []
beg, end = -1, -1
for i in range(n_tags):
ts_tag = ts_tag_sequence[i]
... | 0f0af751334304211dab766c3bbf63d2cc065a8f | 651,999 |
import re
def escape_removal(document):
"""
Function to remove the escape from the elements of the file, the function should be upgraded to eliminate all the undesired symbols
Args:
document(line): The line of the rdd to parse.
"""
return re.sub(r'\\', "", document) | c55fac8f8c8510e49c9f540e3137f9ce7be8a0d3 | 652,000 |
def visparamsListToStr(params):
""" Transform a list to a string formated as needed by
ee.data.getMapId
:param params: params to convert
:type params: list
:return: a string formated as needed by ee.data.getMapId
:rtype: str
"""
n = len(params)
if n == 1:
newbands = '{}'... | 5606c4dca858f5b58acaecdd3266ae7b26560cbe | 652,001 |
def get_asa_owners(indexer_client, asset_id, asa_min_balance=0):
"""Search for ASAs owners
Args:
indexer_client (IndexerClient): Indexer Client V2
asset_id (int): ASA Asset ID
asa_min_balance (int): Optional; ASA minimum balance expressed as
minimal int units
Returns:
... | 15fdcbfa9022eb6a0c738bcfa212a41bca40e76e | 652,002 |
def coleman_liau_index(n_chars, n_words, n_sents):
"""https://en.wikipedia.org/wiki/Coleman%E2%80%93Liau_index"""
return 5.879851 * (n_chars / n_words) - 29.587280 * (n_sents / n_words) - 15.800804 | b81afdceb58c885c3e1eb1fa17a70031e6d7a555 | 652,003 |
def _gen_possible_feet(meters_list):
"""Generate possible feet from a meters list."""
withfeet = [_["pattern"].replace(" ", "") for _ in meters_list]
poss_feet = []
for _ in withfeet:
if "*" in _:
poss_feet.append("=" + _[2:])
poss_feet.append("=" + _[2:] + "_")
... | 1354c31ed25330c748bcee94db0faad38f9e4681 | 652,004 |
def choose_box(group, plot_data):
"""Given a set of overlapping bounding boxes and predictions, just choose a closest to stem box by centroid if there are multiples"""
if group.shape[0] == 1:
return group
else:
#Find centroid
individual_id = group.individual.unique()[0]
stem... | 6550422786370683808c60f8c5c33c39fe3fb255 | 652,005 |
def get_email_queue(db):
"""Get an active queue of emails waiting to be sent."""
result = db.execute(
"SELECT * FROM emails WHERE sent IS NULL ORDER BY id LIMIT 100;")
queued_emails = []
for row in result:
queued_emails.append({
'id': row[0],
'send_to': row[1],
... | 33e5ff1e68a4d808a5978550c8edbca981390cfb | 652,006 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.