content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def parseMinpts(minPts,emPair=False):
"""
Parsing command line input minPts into order minPts.
@param minPts: str
"""
if "," in str(minPts):
minPts = list(map(int, minPts.split(",")))
else:
minPts = [int(minPts)]
if emPair == False:
minPts.sort(reverse=True) #descend... | 39b3f2fe7d6e205f03b28d2a8bcdb42cf89e33eb | 630,692 |
from datetime import datetime
def add_set_time_to_state(state):
"""Annotate state the time of state creation"""
state['setTime'] = datetime.now().timestamp()
return state | 8b229d76189457b88e80505860863a04ac34da78 | 630,693 |
def fill_header(hdr, data):
""" Creates the new header for the 2D image from the header of the data
extension of the datacube.
Input:
hdr: Header from the data extension of the original datacube
data: 2D data created from the datacube
Output:
hdr: Modified header
"""... | 36293e0270976b5e84991e25758b797fad93dec3 | 630,694 |
import hashlib
def generate_hash(content: bytes):
"""
Create md5 hash from bytes
:param content: some data in bytes
:type content: bytes
:return: hash string
:rtype: str
"""
return hashlib.sha3_512(content).hexdigest() | a6d1e5c06b5aedaef31fa7376ed782ec683ceb4f | 630,696 |
def CNOT_check(function):
"""Decorator to check the arguments of calling Controlled-Not gate.
Arguments:
function {} -- The tested function
"""
def wrapper(self, control_qubit, target_qubit):
"""Method to initialize Controlled-Not gate.
Arguments:
control_qubit... | 44badfbd526f2bde7e824a7e6e41cedfee9fd935 | 630,697 |
def get_similar_coordinate(coord, sampled_coordinates, in_means, in_vars, src_means, src_vars):
"""
Get coordinate from sampled_coordinates that has the most similar stats in in_img
:param coord: (row, col) of pixel in in_img to find similar coordinate to
:param sampled_coordinates: set of (row, col) i... | ded3b1b83567a5696df312bd065598aa4396b524 | 630,698 |
def h2r(_hex):
"""
Convert a hex string to an RGB-tuple.
"""
if _hex.startswith('#'):
l = _hex[1:]
else:
l = _hex
return list(bytes.fromhex(l)) | 2cc6b758ef819b9e90b24e941e332ad610b76ecd | 630,699 |
def namedtuples2dicts(namedtuples):
"""
Convert a dict of namedtuples to a dict of dicts.
:param namedtuples: dict of namedtuples
:return: dict of dicts
"""
return {k: dict(v._asdict()) for k, v in namedtuples.items()} | b227f2ef9baf44ed543c0fca616172acbb7e069a | 630,700 |
import yaml
def load_end2end_config(config_file):
"""
Loads end-to-end test setup file
:param config_file: Name of the end-to-end config file.
"""
with open(config_file) as file:
return yaml.full_load(file) | d3aee4f513ccdaf12cb75b53d2212b90388fad20 | 630,702 |
def _printable_string(string, max_len=80):
"""
:param string: string
:param max_len: maximum length
:return: printable version of the given string adhering to the maximum length
"""
if max_len < 3:
raise ValueError("max_len is {0}, must be at least 3".format(max_len))
repred_str = re... | 06a932fb09a9da34c65fffaff557b6e9627204bb | 630,703 |
from typing import Union
from typing import Optional
def format_query_operational_data_request_template(
request_template_filename: str, message_id: str,
# timestamp can be of type 'str' in negative tests
timestamp_before_request: Union[int, None, str], timestamp_after_request: Optional[int],
... | 794eaba08d712701174e8bbca1a323d9749101d5 | 630,704 |
import re
def preHandle(formula: str) -> str:
"""对输入LTL公式的预处理"""
# 为True,False,所有原子命题(单字母)加括号
_f = formula
_f = re.sub(r'\(True\)|True', '(#)', _f)
_f = re.sub(r'\(False\)|False', '(*)', _f)
for i in range(26):
symbol = chr(i + ord('a'))
pattern = '(' + symbol + ')|' + symbol
... | f745430dd67584075b088b2dacaa6970ec4ca6b6 | 630,705 |
def set_attr_to_objList(obj_list, new_attr_name, new_value, is_attr=True, attr_by=None, attr_by_value=None, attr_exclude=None, attr_exclude_value=None):
"""
给对象添加新的属性,其值可以取对象其他的属性值,也可以由用户直接指定
:param obj_list:对象列表,数据结构如[{}, {}, {}]
:param new_attr_name:新添加的属性名
:param new_value:用户指定的新值或对象属性名(取本对象中该属性的... | 9c0d6885d969d23a324d4065809054633a168795 | 630,706 |
def get_caption(etype, cell_meta, resources):
"""return an ipypublish caption or False
captions can either be located at cell_meta.ipub.<type>.caption,
or at resources.caption[cell_meta.ipub.<type>.label]
the resources version is proritised
"""
try:
caption = cell_meta["ipub"][etype]["... | b8e08c734efb6d3f5d6204cb70930cb835800b4c | 630,707 |
def hexify(s):
"""
Used to convert message to hex integers when encrypting.
:param s: a string.
:return: a string like '0x..', decode each character as a ascii hex number.
"""
if not s: # if input is null, evcrypt the message: '!'
return '0x21' # ascii code for '!'
lst = []
fo... | e457880c713cbc8d70ba3463a6fe9331a96ba5a8 | 630,709 |
def IBA_calc(TPR, TNR, alpha=1):
"""
Calculate IBA (Index of balanced accuracy).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:param alpha : alpha coefficient
:type alpha : float
:r... | 7743df1e87791b6dcd1368f536f4e41f11ec9f45 | 630,710 |
def get_rect_even_dimensions(rect_item, even_dimensions=True):
"""
get the the graphics rectangle of the item, moved to position, with sides of even length
Args:
rect_item (QGraphicsRectItem)
even_dimensions (bool): if False even dimensions are not enforced
Returns
... | 6f4cb39964be09f143ac47e45e2ee5dfc731e55a | 630,711 |
def dictionary(input_list):
"""
To generate a dictionary.
Index: item in the array.
Value: the index of this item.
"""
return dict(zip(input_list, range(len(input_list)))) | ccf6bf7b51dfb14fc87fbbc35d3509361bc535ef | 630,712 |
def tokenize_line(line, tokenizer):
"""
Returns a tokenized line
"""
tokens = tokenizer.text_to_ids(line)
return tokens | 1fa24d1d3c380a93aebc43d7f0da80b3a7f0b2d6 | 630,714 |
import re
from datetime import datetime
def buildReportName(appName, reportName):
"""Constructs report name from app + user supplied report name"""
reportName = reportName if reportName else '{}-{}'.format(appName, datetime.now().strftime('%Y-%m-%d-%H:%M:%S'))
reportName = re.sub(r'[^\w\-:_\. ]', '_', reportNam... | 5ef945946e2491955863d0c068034074b1ce2844 | 630,715 |
def z_score_normalize(tensor, scale_to_range=None):
"""Performs z-score normalization on a tensor and scales to a range if specified."""
mean = tensor.mean()
std = tensor.std()
tensor = (tensor - mean) / std
if scale_to_range:
delta1 = tensor.max() - tensor.min()
delta2 = scale_to_... | 3f217cdd5f3322a1b030ea0fe008f52792afab0c | 630,716 |
def ami_architecture(ami_info):
"""
Finds source AMI architecture AMI tag.
Parameters
----------
ami_info : dict
AMI information.
Returns
-------
string
Architecture of source AMI.
"""
for tag in ami_info['Tags']:
if tag['Key'] == 'Architecture':
... | 4cb7e811b7c3ba550ec36f97e9259d2b7ddd1999 | 630,717 |
def makeInverseIndex(strlist):
"""
Input: a list of documents as strings
Output: a dictionary that maps each word in any document to the set consisting of the
document ids (ie, the index in the strlist) for all documents containing the word.
Note that to test your function, you are welcome ... | e4b8ee4cd8de79c8a9483e40487ba7ad7d718b28 | 630,718 |
def unmask_escape(text: str) -> str:
"""Replaces masking sequences with the original escaped characters.
Args:
text (str): masked string.
Returns:
str: unmasked string.
"""
return text.replace('ҪҪҪҪҪ', '&').replace('ҚҚҚҚ', '<').replace('ҺҺҺҺ', '>') | ddad3486703af34f6b9cf1e47ba2d2faf8210e29 | 630,719 |
def is_simple_passphrase(phrase):
"""
Checks whether a phrase contains no repeated words.
>>> is_simple_passphrase(["aa", "bb", "cc", "dd", "ee"])
True
>>> is_simple_passphrase(["aa", "bb", "cc", "dd", "aa"])
False
>>> is_simple_passphrase(["aa", "bb", "cc", "dd", "aaa"])
True
"""
... | 5045b320b6411c4f618a2ae79aa52b277a7e3e19 | 630,720 |
def _sq(x):
"""Square quickly."""
return x * x | c6f39e9ac7e1d9f9c4eed0c49bd10398ed2beb01 | 630,721 |
def get_len_of_bedtool(bed_obj, cov_col=3, cutoff=1):
"""
Get the number of rows (sites) of BedTool object
:param bed_obj:
:param cutoff:
:return:
"""
# covList = []
# for row in bed_obj:
# covList.append(int(row[cov_col]))
# covSeries = pd.Series(covList)
df = bed_obj.to... | c0efa1877ef153f1c8a6b1298cd610ce5042d1d0 | 630,723 |
def getopts(argv):
"""Parse arguments passed and add them to dictionary
:param argv: arguments must be url and threads
:return: dictionary of arguments
"""
opts = {} # Empty dictionary to store key-value pairs.
while argv: # While there are arguments left to parse...
if argv[0][0] == '... | 3ee73134582b9bf36874e30f95047096b4d4c6d6 | 630,726 |
def rreplace(s, old, new, occurrence):
"""
Function which replaces a string occurence
in a string from the end of the string.
"""
return new.join(s.rsplit(old, occurrence)) | fc1cfde420b60c9f4769c31d302272a02f708a0b | 630,727 |
import argparse
def arguments_handler():
""" Validates and parses script arguments.
Returns:
Namespace: Parsed arguments object.
"""
parser = argparse.ArgumentParser(description='Get playbook status.')
parser.add_argument('-i', '--investigation_id', help='The investigation id of the se... | 474b071710d85f032afd24e97076c567cdcfdb16 | 630,728 |
import os
def get_dir_files(path_dir):
"""
递归获取某个目录下的所有文件(单层)
:param path_dir: str, like '/home/data'
:return: list, like ['2019_12_5.txt']
"""
def get_dir_files_func(file_list, dir_list, root_path=path_dir):
"""
递归获取某个目录下的所有文件
:param root_path: str, like '/hom... | d84d317d353161d0c2fc3eac2e77712accb9c158 | 630,730 |
def generate_description(slug: str) -> str:
"""
Fungsi yang menerima input berupa string dengan kebab-case
dan mengubahnya menjadi string UPPERCASE.
Fungsi ini juga akan mengakronim input yang terlalu panjang
(lebih dari 30 karakter).
Contoh:
>>> generate_description("home")
'HOME'
... | 9fe1e270d799dc47d8a28d1c4e2eeb4c28525ef3 | 630,731 |
def find_plate_scale(dictionary):
"""
Find the plate scale determined by Astrometry.net
This value is given inside a COMMENT header, hence we have to search for it
Will return the plate scale as a float if it exists, None otherwise.
"""
try:
comment_entry = dictionary["COMMENT"]
exc... | 0e75721d929918f48b1bae674d62ecfd7e38d25c | 630,732 |
import subprocess
def runcmd(cmd):
""" Runs cmdline and returns the output """
prc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return prc.communicate()[0].decode().rstrip() | f7e318d226f0d725e24932a2006ca02ac4631e53 | 630,733 |
def get_news_tags(doc):
"""Get the list of tags containing news information"""
news_class = "Ov(h) Pend(44px) Pstart(25px)" ## class name of div tag
news_list = doc.find_all('div', {'class': news_class})
return news_list | bf3aca6df08a6b2acada80bee49708d658475a78 | 630,734 |
def _fix_snpeff_version_line(line, supported_versions):
"""Change snpEff versions to supported minor releases.
##SnpEffVersion="2.0.3 (build 2011-10-08), by Pablo Cingolani"
"""
start, rest = line.split('"', 1)
version, end = rest.split(" ", 1)
version_base = version.rsplit(".", 1)[0]
for s... | 1692310fe8f3f4658ce506e58a09f7c8b4bcbc70 | 630,735 |
def kmp(haystack, needle):
"""
Run KMP search on haystack on needle and return all matching indexes
Return empty list on no result
:param haystack:
:param needle:
:return:
"""
needle = list(needle)
len_needle = len(needle)
shifts = [1] * (len_needle + 1)
shift = 1
for... | 35aad5c8d389b13b35979875e449b3df22d541d6 | 630,736 |
def removesuffix(string, suffix):
"""
Returns <string> without the <suffix> suffix.
Copied from https://www.python.org/dev/peps/pep-0616/#specification
to support python versions < 3.9
:param str string: string from which to remove suffix
:param str suffix: suffix to remove from string
:re... | e2136ae568165fabf233a885a7b3526c3dbae5c8 | 630,737 |
def get_x(path, width):
"""Gets the x value from the image filename"""
return (float(int(path.split("_")[1])) - width/2) / (width/2) | c387ce4415b75677f2c7b4a1bc27b12cba469d22 | 630,738 |
import collections
def tree():
"""创建一颗简单树
x=tree()
x['a']['b']=1
:return: 树
"""
return collections.defaultdict(tree) | 019606266c360ddaa907b8b11a38c6d9b09270fc | 630,739 |
from typing import List
def locations(server_properties: dict) -> List[str]:
""" Yields ports locations. """
return server_properties['locations'] | 6952ca23b9873e600d920d5450add7079abee588 | 630,740 |
def convert_digits_to_chars(s):
"""
Formats edge-case characters from pypinyin (pfmt) library
"""
repl_dict = {
'1': '一',
'2': '二',
'3': '三',
'4': '四',
'5': '五',
'6': '六',
'7': '七',
'8': '八',
'9': '九',
'0': '零',
'%':... | eae469184621a31f41f44b4b6efa7a32533e1c59 | 630,742 |
def cal_iou(box1, box2):
"""
:param box1: = [xmin1, ymin1, xmax1, ymax1]
:param box2: = [xmin2, ymin2, xmax2, ymax2]
:return:
"""
xmin1, ymin1, xmax1, ymax1 = box1
xmin2, ymin2, xmax2, ymax2 = box2
# 计算每个矩形的面积
s1 = (xmax1 - xmin1) * (ymax1 - ymin1) # C的面积
s2 = (xmax2 - xmin2) * ... | c962c1588f082921f2d22c3386ec757cc06438ae | 630,743 |
import pandas as pd
def read1Result(selectfile):
"""
Loads in a bifacial_radiance results file ``.csv`` format,
and return a :py:class:`~pandas.DataFrame`
Parameters
----------
selectfile : str
File name (with path if not in working folder) that has been produced by
bifaci... | ba9b33a4820d02acba6aaf7f4d7f5ce473fd5d32 | 630,744 |
def _ReadOrder(fo):
"""Read one example from the order file."""
line = fo.readline()
if not line:
return None
line = line[:-1]
order = line.split()
order = [int(item) for item in order]
return order | fd5d1ff3e71696e2e20963444e3a70551b31e4c3 | 630,745 |
import hashlib
import random
def gen_Unique_ID(ip_adress):
"""
This function generate a unique id for the Fisher, using the ip and a random number
@param ip_adress :(string) that represent the adress of the client
@return :(hash sha256) the digest of the sha-256
"""
objhash = hashlib.sha256()
randnumb = rand... | 30e00a59ee651601a52fa4320b53463422076d09 | 630,746 |
import secrets
def bernoulli_neg_exp(gamma, rng=None):
"""Sample from Bernoulli(exp(-gamma)).
Adapted from "The Discrete Gaussian for Differential Privacy", Canonne, Kamath, Steinke, 2020.
https://arxiv.org/pdf/2004.00010v2.pdf
Parameters
----------
gamma : float
Parameter to sample ... | 36f2004607059d399ffe7bf6767e63a8fa26b82c | 630,748 |
import subprocess
from typing import Union
from typing import Sequence
import sys
from pathlib import Path
def run_cmd(cmd: "Union[str, Sequence[str]]") -> subprocess.CompletedProcess:
"""Run a command via `subprocess.run()`.
Parameters:
cmd: The command to run as a subprocess. If this is a string, i... | ee26af8091537b4595313eac02f90c25ecb2349b | 630,749 |
import os
def remove_path_prefix(pathname, prefix):
""" Return a relative path by removing prefix from pathname.
If pathname doesn't begin with prefix, no change is applied
and pathname returned as-is.
"""
prefix_len = len(prefix)
if pathname[:prefix_len] != prefix:
# pathna... | 4d03079f86773572d2115f7373ec944e36212c0c | 630,750 |
def unique(list):
""" Returns a copy of the list without duplicates.
"""
unique = []; [unique.append(x) for x in list if x not in unique]
return unique | b819d787afe247c1f0873f48f50ca5a7533a1fcd | 630,751 |
import json
import warnings
def scanimage_artist_metadata(artist):
"""Return metatata from ScanImage artist tag as dict."""
try:
return json.loads(artist)
except ValueError:
warnings.warn("invalid JSON '%s'" % artist) | f5f25b0e3f539b1a0906790f049ba66713086279 | 630,753 |
def lexicographic_permutations(seq):
"""Algorithm L for The Art of Computer Programming, Volume 4, Fascicle 2: Generating All Tuples and Permutations."""
def reverse(seq, start, end):
'''In-place reversion. Start and end denote the indexes of the last and the first element'''
while start < end:... | 34a628ffffc2a60141336788fa4a885e573824dc | 630,754 |
def trans_value(km: float, val4km: float) -> float:
"""
Função para calcular um preço sugerido para um frete.
km: distância em km;
val4km: preço cobrado por km rodado.
Retorna o valor sugerido baseado na quantia cobrado por km.
"""
return val4km*km*2 | 07431e2b734d8dd26a4630df3d76c14f32fbaf77 | 630,755 |
from typing import Optional
from typing import Tuple
def _get_validation_scope(
has_valid_abbrev: bool,
blacklist_policy: Optional[str],
) -> Tuple[str, str]:
"""Determine the validationScope for DST and abbreviations.
Returns tuple of the C++ ValidationScope and a human-readable comment.
"""
... | 8afc0f90e0179d640c0ec80434fad0170257d911 | 630,756 |
def lemmatize(lemma_dict, word):
"""Lemmatize a word.
Lemmatizes a word using a lemmatizer which is represented as a dict that
has (word, lemma) as (key, value) pair. An example of a lemma list can be
found in https://github.com/michmech/lemmatization-lists.
If the word is not found in the diction... | a035c402663ff85753ae4ede1828e0007abedb32 | 630,757 |
def next_available_row(worksheet):
"""제일 최근 기사를 가져오기 위해 제일 하단 row로 접근"""
str_list = list(filter(None, worksheet.col_values(1)))
return str(len(str_list)) | 34605c32f307196da323be4c1cd2ca93099fbd9c | 630,758 |
import torch
def allocate_tensors():
"""
init data tensors
:return: data tensors
"""
tensors = dict()
tensors['support_data'] = torch.FloatTensor()
tensors['support_label'] = torch.LongTensor()
tensors['query_data'] = torch.FloatTensor()
tensors['query_label'] = torch.LongTensor()
... | 0e088e60075399129a4ef8c51cbb006872b2b544 | 630,759 |
from typing import List
def resize_work_packages(
work_packages: List[List[List[str]]],
num_workers: int
) -> List[List[List[str]]]:
"""Updates the single work packages accordingly to the number of new workers.
When a time interval for maximum resource consumption changes the number
of ma... | e329dff88e97f71abfe39936300380323a0cc74a | 630,760 |
def str2num_disk_size(disk_size_str):
"""
smallest unit is M,all size transfer to M show in web page
:param disk_size_str: eg:'100G'
:return: eg:100 * 1024
"""
disk_size = 0
symbol = ('M', 'G', 'T', 'P', 'E', 'Z', 'Y')
if isinstance(disk_size_str, str):
level = disk_size_str[-1]... | c8dc8cfa207faae18651c3a0db63cea451632039 | 630,761 |
def filter_spikes(data):
"""In-place high-frequency spike filter
Inspired by:
Stampe, D. M. (1993). Heuristic filtering and reliable calibration
methods for video-based pupil-tracking systems. Behavior Research
Methods, Instruments, & Computers, 25(2), 137-142. doi:10.3758/bf03204486
"""... | 0ef0cf0edb3d343420075ccdbaddde98aa76073c | 630,762 |
def get_digits_matching_next(captcha, step_size=1):
"""Get digits from captcha that are matching next step_size digit."""
matching_digits = []
for index, digit in enumerate(captcha):
next_index = (index + step_size) % len(captcha)
if digit == captcha[next_index]:
matching_digits.... | c8b1c6f48ea12eb5a1ae72e3a99fda8a4f3e48a8 | 630,763 |
import pickle
def _load__catalog(path):
"""Private method."""
pklf = open(path, 'rb')
catalog = pickle.load(pklf)
pklf.close()
return catalog | fee6e4f7c9505b46309cef10f85e113fb6c73a36 | 630,764 |
import torch
def accuracy(output, target):
"""
Compute accuracy comparing the output of the model and the target.
Args:
output : [batch_size, num_classes, caps_dim] The output from the last caps layer.
target : [batch_size] Labels for dataset.
Returns:
accuracy (float): The... | efaaaf987d05d07abeb8a97dc48fd0d2d81fd8ce | 630,765 |
def c1c2c3_2_c1c3c2(m):
"""
m is hex string.
"""
aaa=bytes.fromhex(m)
C1=aaa[:64]
C3=aaa[-32:]
C2=aaa[64:-32]
b=b''.join([C1, C3, C2])
print(b.hex())
return b.hex() | 986364bd87fd4b1e4efea74eedd9a7fe725826ed | 630,766 |
def writeUndergroundarray(grounddata):
"""Finds if tile is an electric fence. If it is, it will set the underground
tile as an electric fence too. Same for fence connectors."""
tilearray = []
dic = {}
ugroundarray = []
for n in grounddata:
tilearray.append(n.strip().split('=')[1].spli... | 6cac15287cc934f9a6b2637edb913b8c698d92a4 | 630,767 |
def binary_recall(pred_y, true_y, positive=1):
"""
二类的召回率
:param pred_y: 预测结果
:param true_y: 真实结果
:param positive: 正例的索引表示
:return:
"""
corr = 0
true_corr = 0
for i in range(len(pred_y)):
if true_y[i] == positive:
true_corr += 1
if pred_y[i] == tru... | 75aba7df445491256cbef372088e9629ca099043 | 630,768 |
def formatField (Field, x, xerr):
"""
Parameters
----------
Field : The name of the field
x : Value of the field
xerr : Error in the field
Returns
-------
Str
Field: x +/- xerr
"""
return str(Field) + " " + str(x) + " +/- " + str(xerr) + "\n" | fb0c4dae3349b6fc88bb23c46bf7112546f854fe | 630,769 |
import time
def _xhj_gc_seconds_to_rmfiles(hsize, files):
"""Return age removed (the age of the *oldest* file) and list of history files to remove to get under the age limit."""
now = time.time()
oldest_ts = files[0][0]
n = 0
for ts, _, f, _ in files:
if (now - ts) < hsize:
br... | aaa03d26f8119ad57e45288ee81488a0ab3c3b85 | 630,770 |
def getAttr(argAttrName, argAttrs):
"""Extract and return the value of a particular attribute from a list
of (attributeName, attributeValue) pairs. If the attribute does
not exist in the list, return None.
"""
for attr in argAttrs:
if attr[0] == argAttrName: return attr[1]
return None | 34b24e04a186e250bca5a0c13a68e41872271300 | 630,771 |
import os
def validate_collection_path(collection_path):
"""Ensure a given path ends with 'ansible_collections'
:param collection_path: The path that should end in 'ansible_collections'
:return: collection_path ending in 'ansible_collections' if it does not already.
"""
if os.path.split(collecti... | 5cfe75111fa81479623bf8a88673dab7ac68e861 | 630,772 |
def get_search_term(request):
"""Get search term from request.
Args:
request: Django request object
Returns:
searchterm: string, search term
"""
# Get search term
searchterm = request.POST.get('search', '')
# If no POST data, try GET
if not searchterm and request.GET.get('search', ''):
s... | 98019759b3fcac959be2766751ea31c1d8d0983b | 630,773 |
def all_leaf_positions(parented_tree):
"""Return tree positions of all leaves of a ParentedTree,
even if the input is only a subtree of that ParentedTree.
"""
return parented_tree.root().treepositions('leaves') | 94d319d7d9f6d7b394f3e0d5448898a5effbe508 | 630,774 |
import requests
def site_size(url: str) -> int:
"""
Returns the page size in bytes of the given URL.
:param url: str
:return: str
"""
response = requests.get(url)
return len(response.content) | 9198ec9eed85ef396953450791abbee9429ed656 | 630,775 |
def enc_from_cons_obj(l):
"""
modulatable なオブジェクトを modulate し、01 文字列を返す。
:param l: modulatable なオブジェクト
:return: 01 文字列
"""
if type(l) == int:
res = []
if l >= 0:
res.append('01')
else:
res.append('10')
bits = '' if l == 0 else bin(abs(l))[2... | ea9da4aa1b83d1b05a666a105582a5867bc224c6 | 630,777 |
import io
def load_agg(seq):
"""
load aggregation propensity of mutations into dict
"""
tango_dict = {}
fname='data/precomputed/polio.AP.txt'
fileIN = io.open(fname, 'r')
line = fileIN.readline()
while line:
current_line = line.split()
pos = int(current_line[0])
... | acea74c45c4ef2c6762b07b2d0f4bd8b8abab0b2 | 630,778 |
def extract_package(signature):
"""Extracts the package from a signature.
Args:
signature (string): JNI signature of a method or field.
Returns:
The package name of the class containing the field/method.
"""
full_class_name = signature.split(";->")[0]
package_name = full_class_... | d0274c51337c724d1f26288c8de81426be3c3815 | 630,779 |
def get_line(s):
"""get a gui line with given char"""
return str(s)*72 | 8516e8b170679ce7b779a50323dd5684dab27e36 | 630,780 |
def find_min_gain(conflicting_ids, cm, id_to_pr):
"""Return region ID of the region with the minimum gain
conflicting_ids -- list of PairedRegion IDs
cm -- ConflictMatrix object
id_to_pr -- dict of {region ID: PairedRegion}. Result of
PairedRegions.byId() method.
This methods returns the ... | 2076241b111105f5c6264b2665b792c6259b138b | 630,781 |
def test_model(model, data):
"""Return if the dictionary `data` complies with the `model`."""
same_keys = set(model.keys()) == set(data.keys())
if not same_keys:
print(
"model_keys: {}\ndata_keys: {}".format(
sorted(model.keys()), sorted(data.keys())
)
... | 7dd229a030172649f998e750c298b37ca1025629 | 630,782 |
def get_P_Elc_rice_cooker_cook(t_rice_cooker_cook, P_Elc_rice_cooker_rtd, N_cup_of_rice):
"""炊飯時の消費電力を計算する
Parameters
----------
t_rice_cooker_cook : float
炊飯1回当たりの時間(54.19/60), h
P_Elc_rice_cooker_rtd : float
定格消費電力, W
N_cup_of_rice : float
炊飯号数, 合
Returns
--... | 3138c6cd939ced82ff15cdd7e0c52f250d036e99 | 630,783 |
def get_exception_info(exception: BaseException) -> dict:
"""
Given an Exception object, retrieves some information about it: class and message.
:param exception: An exception which inherits from the BaseException class.
:return: A dict, containing two values:
- class: Th... | 5bd8c09478e2b64ad58c857f39946bfcbfd79caa | 630,784 |
def get_count_proteins(filename):
"""
Get the number of unique proteins from unique_proteins output.
"""
with open(filename) as f:
line = f.readline()
if line.startswith("Found"):
count = int(line.split()[1])
else:
count = -1
return count | f91256571683a59138cb54e63e9ae33a159b8c3c | 630,785 |
def errors_to_angular(errors):
"""Make the errors understandable by angular
"""
for key, msg in errors.iteritems():
msg = msg.lower()
if 'is not a number' in msg:
errors[key] = 'number'
return errors | a2e16d2202c5df8d2b6045a8b2181d156d3b2fad | 630,786 |
def fits_header_value(hdu, key):
""" Take FITS hdu and a key, return value associated with key (or None if key absent).
Adapted from package photrix, class FITS.header_value.
:param hdu: astropy fits header+data unit object.
:param key: FITS header key [string] or list of keys to try [list of string... | a452a37b919a69db4faaec53925dd59670dcaa89 | 630,787 |
def input_record():
"""Minimal record data as dict coming from the external world."""
return {
"_access": {"metadata_restricted": False, "files_restricted": False},
"_owners": [1],
"_created_by": 1,
"title": "A Romans story",
"description": "A looong description full of l... | fa0dc5946b9c54b7a7a0dab6cc2fbb8312ee7139 | 630,788 |
def camelize(val):
"""Return the camel case version of a :attr:`str`
>>> camelize('this_is_a_thing')
'thisIsAThing'
"""
s = ''.join([t.title() for t in val.split('_')])
return s[0].lower()+s[1:] | a8fd3c1f273759db454589d6a8ef6ebe3e16b760 | 630,789 |
def format_menu(menu):
"""
Textually format a menu.
Args:
menu: A dictionary with as key the type of menu item and as values the menu content and the prices for students
and staff.
Returns:
The nicely format menu including emojis to indicate the menu types.
"""
me... | d8c04ee7f3b47ed604f4fa58ba8a39b60e1c5a67 | 630,790 |
def distance_between(agents_row_a, agents_row_b):
"""
calculate distance between 2 agents
"""
length = (((agents_row_a[0] - agents_row_b[0])**2) +
((agents_row_a[1] - agents_row_b[1])**2))**0.5
return(length) | a214857b0e465da43d5f4aedc703916c4a1885ab | 630,791 |
def crop_border(imgs, crop_border):
"""Crop borders of images.
Args:
imgs (list[ndarray] | ndarray): Images with shape (h, w, c).
crop_border (int): Crop border for each end of height and weight.
Returns:
list[ndarray]: Cropped images.
"""
if crop_border == 0:
retur... | 720812efc06e1a0eec0abc2dbc18554e92aa6d01 | 630,792 |
def get_module_name(path, package_name):
"""Determines the correct python module name for the given os path, relative to a particular package"""
package_index = path.rfind(package_name)
if package_index >= 0:
path = path[package_index:]
else:
raise ValueError("package_name %s not found i... | 1c841293c2abdaa2f938b296cbce94b2525ad0f4 | 630,793 |
import functools
def run_first(preceding_func):
""" Runs some function before running decorated function """
def wrapper_decorator(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
preceding_func()
returned_value = func(*args, **kwargs)
return r... | 4c8348acb12e993f15f19889344bf9d1df76f000 | 630,794 |
def outliers(trained_balanced, LSL, USL):
"""
Deals with outliers by assigning a lower or upper bound to them.
Args:
trained_balanced: The balanced data frame.
LSL: Lower Specification Limit.
USL: Upper Specification Limit.
Returns:
trained_balanced: The... | bd368e57f29beaa8754dcb0e5fb0fa6de0121870 | 630,795 |
def convert_to_strings(entities):
"""
Given a tuple of entities, return a list of strings
"""
return [e.text for e in entities] | bbf3c1edcb7e09c5a7c311eb7bc93d1a1453ef2f | 630,796 |
def constant(value=0.5):
"""Builds a constant exploration.
Args:
value: `float`. The exploratoin constant to use.
Returns:
`function` the exploration function logic.
"""
return value | c05328bdcdef9e16e24d076443d805e8e460b4e5 | 630,797 |
def populate_countries_dict(file_path):
"""
Function to populate dictionary of countries and url numbers.
"""
countries_dict = {}
with open(file_path, 'r') as f:
for line in f.readlines():
key_value = line[:-1].split(':')
countries_dict[key_value[0]] = int(k... | 49f8a00573bc3900a7c0ec9be5bf653c8115c711 | 630,798 |
def start(st_reg_number):
"""Checks the number valiaty for the Bahia state"""
weights_second_digit = range(len(st_reg_number)-1, 1, -1)
weights_first_digit = range(len(st_reg_number), 1, -1)
second_digits = st_reg_number[-1:]
number_state_registration = st_reg_number[0:len(st_reg_number) - 2]
d... | 7365281f18ed27be1a0c4dde4d364e43bf419ba1 | 630,799 |
def ggg(x, y=5):
"""
Привет, меня зовут f и я люблю пельмени
"""
z = x**2 + 2*x*y + y**2
return z | d7556c0ff314d2eca6e0aac31e1f35750dec414d | 630,800 |
import re
def remove_extra_description_terms(description):
"""
Sometimes the description contains some things we don't want to include
like trailing '.', extra spaces, the string (non-protein coding) and a typo
in the name of tmRNA's. This corrects those issues.
"""
description = re.sub(
... | 73e4ae305fc728a1ce815f040d2f4aa403df30f6 | 630,801 |
def dict_diff(first, second):
""" Return a dict of keys that differ with another config object. If a value is
not found in one fo the configs, it will be represented by KEYNOTFOUND.
@param first: Fist dictionary to diff.
@param second: Second dicationary to diff.
@return diff: ... | 163e2c7de61ad6758bcb6307c427441624c28266 | 630,802 |
def response_verify(resp):
"""
Verify if the response's status code is 200 or not.
:return: True if response code is 200
:rtype: bool
"""
if resp.status_code != 200 or resp.text == "":
return False
else:
return True | 77e01bca93b5be718a54b81f28345bf8ebc9c25e | 630,804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.