content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def arg_name(name):
"""Convert snake case argument name to a command line name.
:param str name: The argument parameter name.
:returns: str
"""
return "--" + name.replace('_', '-') | e66284c3a99fe9a75799d4123ad23322089ec2ee | 8,376 |
def invert_node_predicate(node_predicate):
"""Build a node predicate that is the inverse of the given node predicate.
:param node_predicate: An edge predicate
:type node_predicate: (pybel.BELGraph, BaseEntity) -> bool
:rtype: (pybel.BELGraph, BaseEntity) -> bool
"""
def inverse_predicate(graph, node):
"""Return the inverse of the enclosed node predicate applied to the graph and node.
:type graph: pybel.BELGraph
:type node: tuple
:return: bool
"""
return not node_predicate(graph, node)
return inverse_predicate | b6132728d17d520fd9ee22f228c45b364704d5ef | 8,377 |
import random
def get_number_by_pro(number_list, pro_list):
"""
:param number_list:数字列表
:param pro_list:数字对应的概率列表
:return:按概率从数字列表中抽取的数字
"""
# 用均匀分布中的样本值来模拟概率
x = random.uniform(0, 1)
# 累积概率
cum_pro = 0.0
# 将可迭代对象打包成元组列表
for number, number_pro in zip(number_list, pro_list):
cum_pro += number_pro
if x < cum_pro:
# 返回值
return number | 34e367cb0e29df59ddf1e15deec1837d71a922f9 | 8,378 |
def gcd_fast(a: int, b: int) -> tuple:
"""
GCD using Euler's Extended Algorithm generalized for all integers of the
set Z. Including negative values.
:param a: The first number.
:param b: The second number.
:return: gcd,x,y. Where x and y are bezout's coeffecients.
"""
gcd=0
x=0
y=0
x=0
"""
if a < 0:
sign_x=-1
else:
sign_x=1
if b < 0:
sign_y=-1
else:
sign_y=1
"""
#if a or b is zero return the other value and the coeffecient's accordingly.
if a==0:
return b, 0, 1
elif b==0:
return a, 0, 1
#otherwise actually perform the calculation.
else:
#set the gcd x and y according to the outputs of the function.
# a is b (mod) a. b is just a.
gcd, x, y = gcd_fast(b % a, a)
#we're returning the gcd, x equals y - floor(b/a) * x
# y is thus x.
return gcd, y - (b // a) * x, x | d29cf59b310a7035555a04aaa358410319c3d1b3 | 8,379 |
def get_option_name(flags):
"""
Function to get option names from the user defined arguments.
Parameters
----------
flags : list
List of user defined arguments
Returns
-------
flags : list
List of option names
"""
for individualFlag in flags:
if individualFlag.startswith("--"):
return individualFlag.replace("--", "")
return flags[0].replace("--", "") | 359ab05c563aac217d8f275bb946fbafc37f3af2 | 8,380 |
def openthread_suppress_error_flags():
"""Suppress errors for openthread"""
return [
'-Wno-error=embedded-directive',
'-Wno-error=gnu-zero-variadic-macro-arguments',
'-Wno-error=overlength-strings', '-Wno-error=c++11-long-long',
'-Wno-error=c++11-extensions', '-Wno-error=variadic-macros'
] | a6379b1b6133ca24226ca996d9275e4ada8dc3eb | 8,382 |
def split_loops_into_anchors(file_name):
"""
Split loops into anchors.
"""
left = []
right = []
run = file_name.split('.')[0]
i = -1
with open(file_name, 'r') as f:
for line in f:
if '#' in line:
# Skip header
continue
i += 1
loop_id = str(i)
entry = line.strip().split()
# Left anchor
chrom_a = entry[0]
start_a = entry[1]
end_a = entry[2]
left.append(
[chrom_a, start_a, end_a, loop_id, '0', '+'])
# Right anchor
chrom_b = entry[3]
start_b = entry[4]
end_b = entry[5]
right.append(
[chrom_b, start_b, end_b, loop_id, '0', '+'])
## Write left anchors to BED file
left_file = 'temp_left_anchors.bed'
with open(left_file, 'w') as out:
for row in left:
out.write('\t'.join(row) + '\n')
## Write right anchors to BED file
right_file = 'temp_right_anchors.bed'
with open(right_file, 'w') as out:
for row in right:
out.write('\t'.join(row) + '\n')
return left_file, right_file | c5040b4c2a675d7250d0658a4e60fddd064d933a | 8,384 |
def first(*objects):
"""
Return the first non-None object in objects.
"""
for obj in objects:
if obj is not None:
return obj | 4d33225eb0348aa9b7fefa875070eb5527e67135 | 8,385 |
def init_list_with_values(list_length: int, init_value):
"""Return a pre-initialized list.
Returns a list of length list_length with each element equal to
init_value. init_value must be immutable (e.g. an int is okay; a
dictionary is not), or the resulting list will be a list of
references to same object (e.g. retlist[0] and retlist[1] would
point to the same object and manipulating
one would change it for the other).
Args:
list_length (int): The number of elements in the resulting
list.
init_value: A immutable value to initialize each list
element to.
Returns:
list: A list of length list_length with each element
initialized to init_value
Examples:
>>> init_list_with_values(3, 0)
[0, 0, 0]
>>> init_list_with_values(5, "Cookies")
['Cookies', 'Cookies', 'Cookies', 'Cookies', 'Cookies']
>>> init_list_with_values(2, (1, 2, 3))
[(1, 2, 3), (1, 2, 3)]
>>> init_list_with_values(2, {"foo": "bar"})
[{'foo': 'bar'}, {'foo': 'bar'}]
"""
return [init_value] * list_length | 85d5aa5f575b6aec54658ca6d398ded5f48f7188 | 8,387 |
import re
def decode_sigma(ds,sigma_v):
"""
ds: Dataset
sigma_v: sigma coordinate variable.
return DataArray of z coordinate implied by sigma_v
"""
formula_terms=sigma_v.attrs['formula_terms']
terms={}
for hit in re.findall(r'\s*(\w+)\s*:\s*(\w+)', formula_terms):
terms[hit[0]]=ds[hit[1]]
# this is where xarray really shines -- it will promote z to the
# correct dimensions automatically, by name
# This ordering of the multiplication puts laydim last, which is
# assumed in some other [fragile] code.
# a little shady, but its helpful to make the ordering here intentional
z=(terms['eta'] - terms['bedlevel'])*terms['sigma'] + terms['bedlevel']
return z | 3ea233f2b3acb0012166e8e002d6824845a7c043 | 8,390 |
def lowfirst(string):
"""
Make the first letter of a string lowercase (counterpart of :func:`~django.utils.text.capfirst`, see also
:templatefilter:`capfirst`).
:param string: The input text
:type string: str
:return: The lowercase text
:rtype: str
"""
return string and str(string)[0].lower() + str(string)[1:] | f877129f9225e84989fc70d096b01715a2287373 | 8,391 |
def priority(profile):
""" function : to set priority level based on certain age group
input : id, age, infection_status (0 means not infected , 1 means infected) , coordinates, residency
output : priority level : local_high(6), local_medium(5) , local_low (4), foreign(3), foreign(2) ,foreign(1) ,N/A(0)"""
priority_level=1
for i in range(len(profile)):
if profile[i][2]==1 :
priority_level=0
elif profile[i][5]== 0:
if 18<=profile[i][1]<=50:
priority_level=3
elif profile[i][1]<18:
priority_level=2
elif profile[i][1]>50:
priority_level=1
elif profile[i][5] == 1:
if 18<=profile[i][1]<=50:
priority_level=6
elif profile[i][1]<18:
priority_level=5
elif profile[i][1]>50:
priority_level=4
profile[i].append(priority_level)
return profile | dae951efb11f8988cb32910e708bb4f69d8a3ed0 | 8,393 |
def seqlib_type(cfg):
"""
Get the type of :py:class:`~enrich2.seqlib.SeqLib` derived object
specified by the configuration object.
Args:
cfg (dict): decoded JSON object
Returns:
str: The class name of the :py:class:`~seqlib.seqlib.SeqLib` derived
object specified by `cfg`.
Raises:
ValueError: If the class name cannot be determined.
"""
if "barcodes" in cfg:
if "map file" in cfg["barcodes"]:
if "variants" in cfg and "identifiers" in cfg:
raise ValueError("Unable to determine SeqLib type.")
elif "variants" in cfg:
return "BcvSeqLib"
elif "identifiers" in cfg:
return "BcidSeqLib"
else:
raise ValueError("Unable to determine SeqLib type.")
else:
return "BarcodeSeqLib"
elif "overlap" in cfg and "variants" in cfg:
return "OverlapSeqLib"
elif "variants" in cfg:
return "BasicSeqLib"
elif "identifiers" in cfg:
return "IdOnlySeqLib"
else:
raise ValueError("Unable to determine SeqLib type for configuration " "object.") | e48661f00eb6d0cb707fbb96d77b3a9ee3e798d6 | 8,394 |
import os
def parentdir(p, n=1):
"""Return the ancestor of p from n levels up."""
d = p
while n:
d = os.path.dirname(d)
if not d or d == '.':
d = os.getcwd()
n -= 1
return d | 826a52937c491404afaa254acb40827eec36f1b1 | 8,396 |
def rfactorial(n: int) -> int:
"""Recursive factorial function
:param n:
.. docstring::python
>>> from math import factorial
>>> rfactorial(1) == factorial(1)
True
>>> rfactorial(2) == factorial(2)
True
>>> rfactorial(3) == factorial(3)
True
>>> rfactorial(4) == factorial(4)
True
>>> rfactorial(5) == factorial(5)
True
>>> rfactorial(6) == factorial(6)
True
>>> rfactorial(7) == factorial(7)
True
>>> rfactorial(8) == factorial(8)
True
>>> rfactorial(9) == factorial(9)
True
"""
return 1 if n == 1 else rfactorial(n - 1) * n | c8455ce7d0e7e781c0c745287c2aef3c9a776a48 | 8,399 |
import os
import subprocess
import json
def construct_version_info():
"""Make version info using git.
Parameters
----------
None
Returns
-------
version_info : dict
Dictionary containing version information as key-value pairs.
"""
hera_opm_dir = os.path.dirname(os.path.realpath(__file__))
def get_git_output(args, capture_stderr=False):
"""Get output from Git.
This function ensures that it is of the ``str`` type, not bytes.
Parameters
----------
args : list of str
A list of arguments to be passed to `git`.
capture_stderr : bool
Whether to capture standard error as part of the call to git.
Returns
-------
data : str
The output of the git command as `str` type.
"""
argv = ["git", "-C", hera_opm_dir] + args
if capture_stderr:
data = subprocess.check_output(argv, stderr=subprocess.STDOUT)
else:
data = subprocess.check_output(argv)
data = data.strip()
return data.decode("utf-8")
def unicode_to_str(u):
return u # pragma: no cover
version_file = os.path.join(hera_opm_dir, "VERSION")
version = open(version_file).read().strip()
try:
git_origin = get_git_output(
["config", "--get", "remote.origin.url"], capture_stderr=True
)
git_hash = get_git_output(["rev-parse", "HEAD"], capture_stderr=True)
git_description = get_git_output(["describe", "--dirty", "--tag", "--always"])
git_branch = get_git_output(
["rev-parse", "--abbrev-ref", "HEAD"], capture_stderr=True
)
except subprocess.CalledProcessError: # pragma: no cover
try:
# Check if a GIT_INFO file was created when installing package
git_file = os.path.join(hera_opm_dir, "GIT_INFO")
with open(git_file) as data_file:
data = [unicode_to_str(x) for x in json.loads(data_file.read().strip())]
git_origin = data[0]
git_hash = data[1]
git_description = data[2]
git_branch = data[3]
except (IOError, OSError):
git_origin = ""
git_hash = ""
git_description = ""
git_branch = ""
version_info = {
"version": version,
"git_origin": git_origin,
"git_hash": git_hash,
"git_description": git_description,
"git_branch": git_branch,
}
return version_info | 9b56bb0e85555a6bb0989210d3d840d47cfecd42 | 8,400 |
def many2many_dicts(m2mlist):
"""
Maps objects from one list to the other list and vice versa.
Args:
m2mlist: list of 2lists [list1i, list2i] where list1i, list2i represent
a many to many mapping
Returns:
(one2two, two2one) : one2two, two2one
dictionaries from elements of list1i to list2i and vice versa
"""
one2two = {}
two2one = {}
for one, two in m2mlist:
for k in one:
one2two[k] = two
for k in two:
two2one[k] = one
return (one2two, two2one) | edce4101213941dc08d2b32f4c4624ece02bf79c | 8,401 |
import codecs
import os
def _readfile(dirpath, filename):
"""
Read a complete file and return content as a unicode string, or
empty string if file not found
"""
try:
with codecs.open(os.path.join(dirpath, filename), "r", "utf-8") as f:
return f.read()
except IOError:
return u"" | e4fb96aaccc4a3bc7837c182bf25796c724f3c5b | 8,402 |
import math
def calculate_inverse_log_density(cluster):
"""Calculate the log of inverse of Density of a cluster.
inverse of density-log = log-volume - ln(size)
Args:
cluster ():
Returns:
float: inverse of density-log
-inf if log-volume = -inf
"""
inverse_log_density = cluster['log-volume'] - math.log(cluster['size'])
return inverse_log_density | e6d6a77d078b080cd01d9fce47f9715562132864 | 8,403 |
def read_last_processed():
"""Read last processed build number."""
with open("last_processed", "r") as fin:
return int(fin.readline()) | 4362696222c0469c0150632650f07feb0f1a3273 | 8,406 |
def dirac(t, n, freq, pulse_delay):
"""
:param t: time sequence (s).
:type t: list of floats
:param n: time iteration index
:type n: int
:param freq: frequency of the sinusoid (Hz)
:type freq: float
:param pulse_delay: number of iteration for the delay of the signal defined
in the init_*.py
:type pulse_delay: int
:return: the signal magnitude of a Dirac at each time iteration
:rtype: float
"""
if n==pulse_delay:
s=1
else:
s=0
return s | 280234938eed8818666368d66b815ccb967b6dbb | 8,407 |
import torch
def DeterminePeople(tensor, classes):
""" Input: Tensor of all objects detected on screen
Output: Tensor of only 'people' detected on screen """
PersonIndexes = [] #Index of 'person' in tensor
CurrentIndex = 0
for t in tensor:
cls = int(t[-1])
ObjectDetected = "{0}".format(classes[cls]) #label
print(ObjectDetected, ' ',end =" ")
if ObjectDetected == 'person':
PersonIndexes.append(CurrentIndex)
CurrentIndex+=1
Vectors_List = []
for i in PersonIndexes:
vector = tensor[i].tolist()
Vectors_List.append(vector)
Tensor_People = torch.tensor(Vectors_List, device='cuda:0')
return Tensor_People | 37f0875fe4fbb5e636e5f63795b5634072fb80a7 | 8,409 |
def _l2t_section(label, include_section, include_marker):
"""Helper function converting section labels to text. Assumes
_l2t_subterp, _l2t_interp, and _l2t_appendix failed"""
if include_marker:
marker = u'§ '
else:
marker = ''
if include_section:
# Regulation Text with section number
if len(label) == 2: # e.g. 225-2
return marker + '.'.join(label)
else: # e.g. 225-2-b-4-i-A
return marker + '%s.%s(%s)' % (label[0], label[1],
')('.join(label[2:]))
else:
# Regulation Text without section number
if len(label) == 2: # e.g. 225-2
return marker + label[1]
else: # e.g. 225-2-b-4-i-A
return marker + '%s(%s)' % (label[1], ')('.join(label[2:])) | 01052effeba4f00fb1024d91c954aa6031153973 | 8,410 |
def extract_scores_from_outlist_file(outlist):
"""
:param outlist:
:return:
"""
scores = {'SEED': [], 'FULL': [], 'OTHER': []}
outlist_fp = open(outlist, 'r')
for line in outlist_fp:
if line[0] != '#':
line = [x for x in line.strip().split(' ') if x!='']
scores[line[2]].append(float(line[0]))
else:
# if we reached REVERSED line, we treat everything as TNs
# break and return
if line.find("BEST REVERSED") != -1:
break
outlist_fp.close()
return scores | cdaf7dca6784e6b7c5d9afd31b207d651824371e | 8,411 |
import os
def integration_url(scope="session"):
"""
returns an url
"""
test_url = os.getenv('TEST_URL_INTEGRATION', 'http://127.0.0.1')
port = os.getenv('TEST_PORT_INTEGRATION', 5000)
return f"{test_url}:{port}" | 7857f252ed82af027c93e991f0b079786ce0f6fc | 8,412 |
def is_aaai_url(url):
"""determines whether the server from url
@param url : parsed url
"""
return 'aaai.org' in url.netloc | 36a5a71de9c40ad287e44f064aa85053ed13eef9 | 8,414 |
import glob
import os
def read_batch_of_files(DIR):
"""Reads in an entire batch of text files as a list of strings"""
files = glob.glob(os.path.join(DIR,'*.txt'))
texts = []
for f in files:
with open(f,'r') as f:
texts.append(f.read())
return texts | 84068898e918cc6e4a073e6b6a11e7edc5b8cd75 | 8,415 |
def get_words_label(words_data: list) -> list:
"""
得到当前数据集下的词汇表
:param words_data: 读取到的词语数据
:return: 词汇表
"""
# 使用 set 去重
words_label = set({})
for words in words_data:
words_label.update(words[1])
res = list(words_label)
res.sort()
return res | d9ce0701c3c1baff1067d5c96a7730dc42b027f9 | 8,416 |
def hover_over(spell: str,
stopcast: bool = False,
dismount: bool = True,
) -> str:
""" Hover over target. """
macro = f'#showtooltip {spell}\n'
if stopcast:
macro += '/stopcast\n'
if dismount:
macro += '/dismount\n'
macro += f'/use [@mouseover, harm, nodead][@target, harm, nodead] {spell}'
return macro | 74586c97b971cbfab169c1777b6c82921015e8ba | 8,417 |
def read_story_file(filename):
"""read story file, return three lists, one of titles, one of keywords, one of stories"""
title_list, kw_list, story_list = [], [], []
with open(filename, 'r') as infile:
for line in infile:
title, rest = line.strip().split('<EOT>')
kw, story = rest.split('<EOL>')
title_list.append(title)
kw_list.append(kw)
story_list.append(story)
return title_list, kw_list, story_list | f354618f57eef3f8c842f2802044bc0fea0666f7 | 8,418 |
def rotate_points(points, width=600, height=300):
"""180 degree rotation of points of bbox
Parameters
----------
points: list or array
Coordinates of top-left, top-right, bottom-left and bottom-right points
width, height: int
Width/height of perspective transformed module image
Returns
-------
rotated_points: list or array
180 degree rotation
"""
return [[width - points[1][0], height - points[1][1]], [width - points[0][0], height - points[0][1]]] | ca15ebb21d9c34ba69049831395ce48de44c70a7 | 8,419 |
def inSkipTokens(start, end, skip_tokens: list) -> bool:
"""
Check if start and end index(python) is in one of skip tokens
"""
for token in skip_tokens:
if start >= token[0] and end <= token[1]:
return True
return False | a51124471eb9f1c3be84f132fc4cce3dad6ef336 | 8,420 |
def getBlock(lines, row):
"""
Parameters
----------
lines
row
Returns
-------
"""
block = []
for i in range(row, len(lines)):
if lines[i][0] == 'END':
return i, block
else:
if lines[i][0] != '#':
block.append(lines[i]) | 7c8f8e45084eb9ff92d7c68fc03bf285d98ab2d7 | 8,422 |
import os
def hasAWSEnviornmentalVariables():
"""Checks the presence of AWS Credentials in OS envoirnmental variables and returns a bool if True or False."""
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
if access_key and secret_key:
return True
return False | daaa2036d9cd50ea11e51217571d40cc37cb0e2f | 8,425 |
def shape(parameter):
"""
Get the shape of a ``Parameter``.
Parameters
----------
parameter: Parameter
``Parameter`` object to get the shape of
Returns
-------
tuple:
shape of the ``Parameter`` object
"""
return parameter.shape | ceb2b9a6199d980386b306ff329b797dc1815a29 | 8,427 |
def position_split(position_source, position_cible):
"""Prend les arguments positions_sources et position_cible et sépare la lettre et le chiffre. Les chiffres sont
transformé en entier dans l'objectif d'appliquer des opérations mathématiques. La lettre est transformé en
index dans l'objectif d'apliquer des opérations mathématiques.
Args:
position_source (str): La position source, suivant le format ci-haut. Par exemple, 'a8', 'f3', etc.
position_cible (str): La position cible, suivant le format ci-haut. Par exemple, 'b6', 'h1', etc.
Returns:
depart: Nombre entier.
arrive: Nombre entier.
index_depart: Nombre entier.
index_arrive: Nombre entier.
positon_source: Liste contenant deux chaînes de caractères.
position_cible: Liste contenant deux chaînes de caractères.
"""
position_source = position_source[0].split() + position_source[1].split()
depart = int(position_source[1])
position_cible = position_cible[0].split() + position_cible[1].split()
arrive = int(position_cible[1])
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
index_depart = list.index(position_source[0])
index_arrive = list.index(position_cible[0])
return [depart, arrive, index_depart, index_arrive, position_source, position_cible] | 51216b32614a6d9dd41216b445b9cc3036abf8f3 | 8,429 |
import os, subprocess
def get_mem_usage():
""" Get memory usage for current process """
pid = os.getpid()
process = subprocess.Popen("ps -orss= %s" % pid, shell=True, stdout=subprocess.PIPE)
out, _err = process.communicate()
return int(out) | 6b1897099c8038453eb705b76d0e63dc794dcbb7 | 8,430 |
import os
def get_last_modified(dirs):
"""Get the last modified time.
This method recursively goes through `dirs` and returns the most
recent modification time time found.
Parameters
----------
dirs : list[str]
list of directories to search
Returns
-------
int
most recent modification time found in `dirs`
"""
last_mtime = 0
for dir in dirs:
for root, dirs, files in os.walk(dir):
for f in files:
mtime = os.stat(os.path.join(root, f)).st_mtime
if mtime > last_mtime:
last_mtime = mtime
return last_mtime | 4ebc2679e8869097b8041bbe3ad893905fd94dca | 8,431 |
def get_maj_answer(votes_per_answer):
"""
:param votes_per_answer: dictionary with {'1': int, '2': int}, where the ints add up to NBR_ANNOTATORS
:return: the majority answers, i.e., number of votes at least half that of the number of annotators;
raises error if the answers are tied
"""
if (len(votes_per_answer) == 1 and '1' in votes_per_answer) or \
(len(votes_per_answer) == 2 and votes_per_answer['1'] > votes_per_answer['2']):
return '1'
elif (len(votes_per_answer) == 1 and '2' in votes_per_answer) or \
(len(votes_per_answer) == 2 and votes_per_answer['2'] > votes_per_answer['1']):
return '2'
else:
raise ValueError("The answers are equally often selected."
" This should have been impossible with the setup of the study.") | 87baeafd2ff39c4aa0ea970f501d1c195ffadecd | 8,432 |
import base64
def invoke_lambda_and_get_duration(lambda_client, payload, function_name):
"""
Invokes Lambda and return the duration.
:param lambda_client: Lambda client.
:param payload: payload to send.
:param function_name: function name.
:return: duration.
"""
response = lambda_client.invoke(
FunctionName=function_name,
InvocationType='RequestResponse',
LogType='Tail',
Payload=payload,
)
# Extract duration from Lambda log
lambda_log = base64.b64decode(response['LogResult']).decode('utf-8')
report_data = \
[line for line in lambda_log.split('\n')
if line.startswith('REPORT')
][0]
duration = \
[col for col in report_data.split('\t')
if col.startswith('Duration')
][0]
duration = float(duration.split()[1])
return duration | c8d2b77e4f7bc338efcdfd21db4f7297a625b05c | 8,433 |
import re
def reglux_list(mydict,response):
"""
遍历正则抓取数据
:param mydict: 字典类型{key:正则表达式,}
:param response: request.text需要正则匹配的字符串
:return: 字典类型
"""
temp = {}
for m,n in mydict.items():
if '' != n:
pattern = re.compile(n)
matchs = pattern.findall(response)
temp.update({m:matchs,})
else:
temp.update({m: list(n),})
return temp | f75cad96991fedc6e1ab91a17abc1b8b91be6cdd | 8,434 |
import random
def read_stat():
"""
Mocks read_stat as this is a Linux-specific operation.
"""
return [
{
"times": {
"user": random.randint(0, 999999999),
"nice": random.randint(0, 999999999),
"sys": random.randint(0, 999999999),
"idle": random.randint(0, 999999999),
"irq": random.randint(0, 999999999),
}
}
] | 06889ca31c24aa890637ac63283091b096e48443 | 8,436 |
def bfs(graph):
"""Function that recreates the Breath First Search
algorithm, using a queue as its data structure.
In this algorithm, when a node is analyzed, it is
marked as visited and all of its children are
added to the queue (if they are not in it already).
The next node to be analyzed is given both by the
queue and the 'visited' array. If a node is
dequeued and it is not in the 'visited' array, then
it is analyzed.
Args:
graph (dict): a dictionary mapping the nodes of the graph
to their connections.
Returns:
array: the array of visited nodes in order of visiting
"""
visited = []
for key in graph.keys():
queue = [key]
head = 0
if key in visited:
continue
while head < len(queue):
if queue[head] in visited:
continue
for i in range(len(graph[queue[head]])):
if graph[queue[head]][i] not in queue:
queue.append(graph[queue[head]][i])
visited.append(queue[head])
head += 1
return visited | a14671a30d0c61389378ae44641901ec8dce8ac2 | 8,437 |
from pathlib import Path
def next_job_id(output_dir: Path) -> str:
"""Return the next job id."""
# The ids are of form "0001", "0002", ...
# Such ids are used for naming log files "0001.log" etc.
# We look for the first id that haven't been used in the output directory.
def make_job_id(n: int) -> str:
return f"{n:0>4}"
n = 1
if output_dir.is_dir():
existing_job_ids = {
f.name.split(".", maxsplit=1)[0] for f in output_dir.glob("*.*")
}
while make_job_id(n) in existing_job_ids:
n += 1
return make_job_id(n) | 7fa35775e3bef8cf812b1173880c5be1ad3e6465 | 8,439 |
def POS(POSInt):
"""Returns 'F' if position indicator is present. The AllSportCG sends a * in a specific position to indicate which
team has posession, and this changes that character to an 'F'. Using font Mattbats, F is a football."""
POSText = ""
if POSInt == 42:
POSText = "F"
return(POSText) | 2f0dac3bfd0f803f1a60e740c104414bff29bf27 | 8,440 |
def is_visited(state, visited):
"""
Determines whether a State has already been visited.
Args:
state:
visited:
Returns:
"""
for visited_state in visited:
if state.shore == visited_state.shore and state.boat == visited_state.boat:
return True
return False | 567f85b63533188d58df4923e7e3a2a72da14943 | 8,441 |
def rgs_var(g, h, xoff, yoff):
"""Radiographs and variance with xoff and yoff offsets"""
gx0, hx0 = xoff, 0
if xoff < 0:
gx0, hx0 = 0, -xoff
nx = min(g.rg.shape[0]-gx0, h.rg.shape[0]-hx0)
gy0, hy0 = yoff, 0
if yoff < 0:
gy0, hy0 = 0, -yoff
ny = min(g.rg.shape[1]-gy0, h.rg.shape[1]-hy0)
mg = g.rg[gx0:gx0+nx, gy0:gy0+ny]
mh = h.rg[hx0:hx0+nx, hy0:hy0+ny]
vg = g.uncert[gx0:gx0+nx, gy0:gy0+ny]**2
vh = h.uncert[hx0:hx0+nx, hy0:hy0+ny]**2
return mg, mh, vg, vh | 17ebaecb34be1c67cb9454117097b574ce14998e | 8,442 |
def approx_match(stations, name):
"""
:param stations: dict เก็บข้อมูลพิกัดและอุณหภูมิของสถานีต่าง ๆ ในรูปแบบที่อธิบายมาก่อนนี้
:param name: เป็นสตริง
:return: คืนลิสต์ที่เก็บชื่อสถานีที่มีตัวอักษรใน name เป็นส่วนหนึ่งของชื่อสถานี โดยไม่สนใจว่าเป็นตัวพิมพ์เล็กหรือใหญ่
และไม่สนใจเว้นวรรคภายในด้วย (ชื่อในลิสต์ที่คืนเป็นผลลัพธ์เรียงอย่างไรก็ได้)
หมายเหตุ: ชื่อสถานีที่เป็นคีย์ใน stations นั้นเป็นตัวพิมพ์ใหญ่หมด ผลที่คืนจากฟังก์ชันนี้ก็จะเก็บตัวพิมพ์ใหญ่
แต่ตอนค้น name ใน stations นั้น ต้องเป็นแบบไม่สนใจว่าเป็นตัวพิมพ์เล็กหรือใหญ่
"""
# Declare a variable
result = []
# Normally, when we write this functon write search string we use 'Recursion' but I know that you are not study
# recursion because it's a programming strategy that is hard. So we are use a way that is a little bit stupid
# bur confirm that you are all know that what a program do.
# Ps. First, I think I will use Recursion with Higher-Order function (To make a recursion in this function
# and not make a code to ugly and CLEAN) but I think your teacher will say "WTF! How you know that? Holy shit"
# Convert a string to a list
# Search key
# First, our dict is all capital letters so upper it
name = name.upper()
# Convert search keyword to list and remove space out
name = name.replace(' ', '')
# Convert it to list
name_list = list(name)
# Use Typecasting to get all dict key from variable 'stations'
station_name_list = list(stations.keys())
# For loop to search
for station in station_name_list:
station_list = station.upper()
station_list = station_list.replace(' ', '')
station_list = list(station_list)
# Use all() function and for loop in one lineto check search keyword in station name
if all(item in station_list for item in name_list):
result.append(station)
return result | 42338574242c7b866917e8480bc4accd4e569133 | 8,444 |
def get_xml_schema_type():
"""
Get xml schema type.
"""
return '{http://www.w3.org/2001/XMLSchema-instance}type' | 1704b7d6227cd88836f4a55488445192bf63c9aa | 8,445 |
def to_int(value):
"""Convert to integer"""
return value & 0xFF | 9045a7857dae407a196ccb29a142a8e243476b03 | 8,447 |
def get_P_fan_rtd_C(V_fan_rtd_C):
"""(12)
Args:
V_fan_rtd_C: 定格冷房能力運転時の送風機の風量(m3/h)
Returns:
定格冷房能力運転時の送風機の消費電力(W)
"""
return 8.0 * (V_fan_rtd_C / 60) + 20.7 | 52c3d887e2c1a9daaedaacfea28207cc31a14d81 | 8,448 |
def crop_2d(pts2d, Prect, bounds):
"""
Expects 2D coordinate points and a dict of bounds of traffic signs
"""
min_x = bounds['x'] - bounds['w']
max_x = bounds['x'] + bounds['w']
min_y = bounds['y'] - bounds['h']
max_y = bounds['y'] + bounds['h']
# print(min_x)
# print(max_x)
# print(min_y)
# print(max_y)
points = []
for i, x in enumerate(pts2d[0]):
y = pts2d[1][i]
if min_x < x < max_x and min_y < y < max_y:
points.append(i)
return points | 2c218c518cd7a56bcb2c6ca87f9548d8ecc32c78 | 8,449 |
import pathlib
def get_tldname():
"""look in /etc/hosts or /etc/hostname to determine the top level domain to use
"""
basename = tldname = ''
with open('/etc/hosts') as hostsfile:
for line in hostsfile:
if not line.strip().startswith('127.0.0.1'):
continue
ipaddr, name = line.strip().split(None, 1)
if '.' in name:
tldname = name
break
if not basename:
basename = name
if not tldname:
if not basename:
basename = pathlib.Path('/etc/hostname').read_text().strip()
tldname = basename + '.nl'
return tldname | 5f1c4f7f63d0ffbd39a05d9529bffabaa2c5d216 | 8,451 |
import sys
def checkChangeLog(message):
""" Check debian changelog for given message to be present.
"""
for line in open("debian/changelog"):
if line.startswith(" --"):
return False
if message in line:
return True
sys.exit("Error, didn't find in debian/changelog: '%s'" % message) | 7801a5207549a2ba48551c760f9d2781a79ed81e | 8,453 |
import numpy
def mean_average_error(ground_truth, regression, verbose=False):
""" Computes the mean average error (MAE).
Args:
ground_truth (list or 1-dim ndarray): ground truth labels.
regression (list or 1-dim ndarray): label estimations. Must have the same length as the ground truth.
verbose (bool): verbosity parameter.
Returns:
(float): the MAE.
"""
if len(ground_truth) != len(regression):
ex = "ERROR in regression labels in mean_average_error:" + \
"len(ground_truth)=%d != len(regression)=%d" % (len(ground_truth), len(regression))
print(ex)
raise Exception(ex)
d1 = numpy.array(ground_truth).flatten()
d2 = numpy.array(regression).flatten()
if verbose:
print("ground_truth=", d1)
print("regression=", d2)
mae = numpy.abs(d2 - d1).mean()
return mae | 0bcc7fe67aa97dcf44595a6f2ef63ed242b29837 | 8,454 |
from typing import Union
from pathlib import Path
import base64
def read_as_base64(path: Union[str, Path]) -> str:
"""
Convert file contents into a base64 string
Args:
path: File path
Returns:
Base64 string
"""
content = Path(path).read_text()
return base64.b64encode(content.encode("utf-8")).decode("utf-8") | bf4071662fd335882f50e10b72e7623d5e84d855 | 8,457 |
def type_equals(e, t):
"""
Will always return true, assuming the types of
both are equal (which is checked in compare_object)
"""
return True | 7d394ab23369854476c91d85c4160cd177fa125f | 8,458 |
def set_active_design(oProject, designname):
"""
Set the active design.
Parameters
----------
oProject : pywin32 COMObject
The HFSS design upon which to operate.
designname : str
Name of the design to set as active.
Returns
-------
oDesign : pywin32 COMObject
The HFSS Design object.
"""
oEditor = oProject.SetActiveDesign(designname)
return oEditor | 825108bbfe21baa73e256d527fb982919a6b08ea | 8,461 |
def write_tags(tag, content='', attrs=None, cls_attr=None, uid=None, new_lines=False, indent=0,
**kwargs):
"""
Write an HTML element enclosed in tags.
Parameters
----------
tag : str
Name of the tag.
content : str or list(str)
This goes into the body of the element.
attrs : dict or None
Attributes of the element.
Defaults to None.
cls_attr : str or None
The "class" attribute of the element.
uid : str or None
The "id" attribute of the element.
new_lines : bool
Make new line after tags.
indent : int
Indentation expressed in spaces.
Defaults to 0.
**kwargs : dict
Alternative way to add element attributes. Use with attention, can overwrite some in-built
python names as "class" or "id" if misused.
Returns
-------
str
HTML element enclosed in tags.
"""
# Writes an HTML tag with element content and element attributes (given as a dictionary)
line_sep = '\n' if new_lines else ''
spaces = ' ' * indent
template = '{spaces}<{tag} {attributes}>{ls}{content}{ls}</{tag}>\n'
if attrs is None:
attrs = {}
attrs.update(kwargs)
if cls_attr is not None:
attrs['class'] = cls_attr
if uid is not None:
attrs['id'] = uid
attrs = ' '.join(['{}="{}"'.format(k, v) for k, v in attrs.items()])
if isinstance(content, list): # Convert iterable to string
content = '\n'.join(content)
return template.format(tag=tag, content=content, attributes=attrs, ls=line_sep, spaces=spaces) | ed0ade998b0232b8bca5cbb6083f8b60481b3ad9 | 8,462 |
def calc_BMI(w,h):
"""calculates the BMI
Arguments:
w {[float]} -- [weight]
h {[float]} -- [height]
Returns:
[float] -- [calculated BMI = w / (h*h)]
"""
return (w / (h*h)) | ee4d7b99a0bb1129d316c7031a65c465092358a3 | 8,464 |
def get_message_box_text():
"""Generates text for message boxes in HTML."""
html_begin = '<span style="font-size: 15px">'
html_end = '</span>'
shortcuts_table = "<table>" \
"<tr>" \
"<th>Shortcuts </th>" \
"<th>Description</th>" \
"</tr>" \
"<tr>" \
"<td><code>Ctrl+S</code></td>" \
"<td>Show available shortcuts</td>" \
"</tr>" \
"<tr>" \
"<td><code>Ctrl+D</code></td>" \
"<td>Show available commands</td>" \
"</tr>" \
"<tr>" \
"<td><code>Alt+G</code></td>" \
"<td>Logout from accout</td>" \
"</tr>" \
"<tr>" \
"<td><code>Alt+E</code></td>" \
"<td>Close the messenger</td>" \
"</tr>" \
"<tr>" \
"<td><code>Enter</code></td>" \
"<td>Send message</td>" \
"</tr>" \
"</table>"
message_box_text = {"close": "Are you sure to quit?",
"logout": "Are you sure to logout?",
"about": "Messenger 12.2020<br>"
"Version: 1.2"
"<br><br>",
"contacts": "Vadym Mariiechko:<br><br>"
"<a href='mailto:[email protected]'>[email protected]</a><br>"
"LinkedIn: <a href='https://www.linkedin.com/in/mariiechko/'>mariiechko</a><br>"
"GitHub: <a href='https://github.com/marik348'>marik348</a>",
"server_is_off": "The server is offline",
"shortcuts": shortcuts_table
}
message_box_text = {key: html_begin + value + html_end for key, value in message_box_text.items()}
message_box_text["about"] += "Created by Vadym Mariiechko"
return message_box_text | 29eb35e2b968fa125b77fde08669b75b5372de71 | 8,465 |
import os
import pickle
def load(filename: str) -> object:
"""
Load from pickle file
:param filename:
:return:
"""
if not os.path.exists(filename):
raise Exception(f"Unable to fine file {filename}")
with open(filename, 'rb') as fin:
obj = pickle.load(fin)
return obj | 3cda74b48c4e7d70d9b6462284e0bcafb8469f8e | 8,466 |
def get_file_content(filename):
""" Function reads the given file
@parameters
filename: Path to the file
@return
This function returns content of the file inputed"""
with open(filename, encoding='utf-8', errors='ignore') as file_data: # pragma: no mutate
return file_data.readlines() | 1396b6eae7addd329466e1e3ad597cf965360b60 | 8,467 |
def mb_to_human(num):
"""Translates float number of bytes into human readable strings."""
suffixes = ['M', 'G', 'T', 'P']
if num == 0:
return '0 B'
i = 0
while num >= 1024 and i < len(suffixes) - 1:
num /= 1024
i += 1
return "{:.2f} {}".format(num, suffixes[i]) | 95f6ae29c8031347e32f51f349afc986abe31473 | 8,470 |
def success(message, data=None, code=200):
"""Return custom success message
Args:
message(string): message to return to the user
data(dict): response data
code(number): status code of the response
Returns:
tuple: custom success REST response
"""
response = {'status': 'success', 'data': data, 'message': message}
return {key: value for key, value in response.items() if value}, code | 721542f71ad3a641efbe0a0d62723a2df23960a5 | 8,471 |
def past_days(next_day_to_be_planned):
"""
Return the past day indices.
"""
return range(1, next_day_to_be_planned) | d4b0e7387303f48bc3668f5d71b374dace6e7f44 | 8,473 |
import argparse
def parse_args(args):
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description='Run opsdroid.')
parser.add_argument('--gen-config', action="store_true",
help='prints out an example configuration file')
return parser.parse_args(args) | e4bf8f3117c5064f6dc76f257eb63233e69da3cb | 8,475 |
def import_obj(obj_path, hard=False):
"""
import_obj imports an object by uri, example::
>>> import_obj("module:main")
<function main at x>
:param obj_path: a string represents the object uri.
;param hard: a boolean value indicates whether to raise an exception on
import failures.
"""
try:
# ``__import__`` of Python 2.x could not resolve unicode, so we need
# to ensure the type of ``module`` and ``obj`` is native str.
module, obj = str(obj_path).rsplit(':', 1)
m = __import__(module, globals(), locals(), [obj], 0)
return getattr(m, obj)
except (ValueError, AttributeError, ImportError):
if hard:
raise | cceed0d6162d4ab281472c1f2c9bb58a0b9195d1 | 8,476 |
from datetime import datetime
def generate_date_now():
"""Get current timestamp date."""
return "{0}".format(datetime.utcnow().strftime('%s')) | 84489bee5b01537c273c4dc64e96586434c405e4 | 8,477 |
import random
def create_contig_and_fragments(contig, overlap_size, fragment_size):
"""
Creates a contig and overlapping fragments
:param str contig: original sequence to create test data from
:param int overlap_size: number of bases fragments should overlap
:param int fragment_size: length of bases
note:: returned contig is probably going to be smaller than the input contig so that the
last fragment isn't too short
"""
assert overlap_size < fragment_size
assert fragment_size < len(contig)
step_size = fragment_size - overlap_size
fragments = []
i = 0
while i + fragment_size <= len(contig):
fragments.append(contig[i: i + fragment_size])
i += step_size
random.shuffle(fragments)
return contig[:i - step_size + fragment_size], fragments | cb6394004f1500aefb55354cadd9788ab29749f7 | 8,479 |
def assign_road_name(x):
"""Assign road conditions as paved or unpaved to Province roads
Parameters
x - Pandas DataFrame of values
- code - Numeric code for type of asset
- level - Numeric code for level of asset
Returns
String value as paved or unpaved
"""
asset_type = str(x.road_type).lower().strip()
if str(x.road_name) != '0':
return x.road_name
else:
return 'no number' | 01bf8bccca43aa833e3d9edfcbfe0213e30d9ac0 | 8,480 |
def GetGap ( classes, gap_list ):
"""
Input
classes: {课号:{教师姓名:[完成课时,完成课时比例,完成业绩]}} (dict)
Output
availableT: available teacher list,在职教师名及其完成业绩(tuple)
unavailableT: unavailable teacher list,离职 & 管理岗教师名及其完成业绩(tuple)
gap:由离职 & 管理岗教师产生的业绩缺口(float)
"""
gap = 0
availableT = []
unavailableT = []
teacherlist = {}
# 计算教师产值列表
for c in classes.keys():
for t in classes[c].keys():
individ = classes[c][t][2] # 个人业绩
if t not in teacherlist.keys():
teacherlist[t] = round(individ,2)
else:
teacherlist[t] += round(individ,2)
# 排序教师产值
# 对teacherlist(dict)的value排序
tmp = sorted(teacherlist.items(),key = lambda item:item[1], reverse = True)
# 从availableT中找出unavailable的教师
for i in range(len(tmp)):
if tmp[i][0] in gap_list:
gap += tmp[i][1]
unavailableT.append(tmp[i])
else:
availableT.append(tmp[i])
return availableT, unavailableT, gap | 4c9bba825d4763e8c98c3f01f623b331d97a5cd4 | 8,481 |
def generateMessage(estopState, enable, right_vel, left_vel):
"""
Accepts an input of two bools for estop and enable.
Then two velocities for right and left wheels between -100 and 100
"""
# Empty list to fill with our message
messageToSend = []
# Check the directions of the motors, False = (key switch) forward, True = reverse
# Reverse direction respect to joysticks e.g. left up = right reverse
if right_vel < 0:
left_direction = True
else:
left_direction = False
if left_vel < 0:
right_direction = True
else:
right_direction = False
# Check to see if we're allowed to move. estop and enable
if estopState or not enable:
left_vel = 0
right_vel = 0
# Build the message. converting everything into positive integers
messageToSend.append(int(estopState))
messageToSend.append(int(enable))
messageToSend.append(int(left_direction))
messageToSend.append(abs(int(left_vel)))
messageToSend.append(int(right_direction))
messageToSend.append(abs(int(right_vel)))
messageToSend.append(int(left_direction))
messageToSend.append(abs(int(left_vel)))
messageToSend.append(int(right_direction))
messageToSend.append(abs(int(right_vel)))
print("Sending: %s" % str(messageToSend))
return messageToSend | 3c0d2f912ee1fca4e819b0b5813de48b7f1bb338 | 8,482 |
def cost_deriv(a, y):
"""Mean squared error derivative"""
return a - y | 15d02e49af734f9ad95e63214055f4dda58d41f4 | 8,483 |
from pathlib import Path
def read_cd_files(prefix: Path, fname: str) -> dict:
"""
result[name] = path-to-the-file
name: e.g., 08-1413.jpg
pato-to-the-file: e.g., /cifs/toor/work/2011/cyclid data/./CD9/2008-06-19/08-1413.jpg
"""
result = {}
with open(fname) as f:
for line in f:
line = line.strip()
inputf = prefix / line
assert inputf.exists()
result[inputf.name] = inputf
return result | c8b16b01819d00be0efb2f12cc25eeb7730facf9 | 8,486 |
def _generate_spaxel_list(spectrum):
"""
Generates a list wuth tuples, each one addressing the (x,y)
coordinates of a spaxel in a 3-D spectrum cube.
Parameters
----------
spectrum : :class:`specutils.spectrum.Spectrum1D`
The spectrum that stores the cube in its 'flux' attribute.
Returns
-------
:list: list with spaxels
"""
spx = [[(x, y) for x in range(spectrum.flux.shape[0])]
for y in range(spectrum.flux.shape[1])]
spaxels = [item for sublist in spx for item in sublist]
return spaxels | 9d4b5339f18022607f349c326dc83e319a690a26 | 8,488 |
import logging
import argparse
import sys
import os
def get_args():
"""
Read arguments from the command line and check they are valid.
"""
logger = logging.getLogger("stats.args")
parser = argparse.ArgumentParser(
description="Extract alignment statistics from a SAM/BAM file")
parser.add_argument("inputs",
metavar="SAM/BAM",
nargs="+",
help="Input SAM or BAM files")
parser.add_argument("-o", "--out",
help="Output file",
required=True)
parser.add_argument("-g", "--gtf",
help="GTF annotation file")
parser.add_argument("-i", "--index",
help="""Annotation index file. Required when
operating in parallel.""")
parser.add_argument("-t", "--type",
choices=["sam", "bam"],
help="Type of input file",
required=True)
parser.add_argument("-p", "--parallel",
type=int,
default=1,
help="""Number of files to process in parallel.
Requires N + 1 threads if greater than 1.""")
args = parser.parse_args()
args.is_parallel = False
if args.parallel < 1:
logger.error("Number of parallel files must be positive")
sys.exit()
elif args.parallel > 1:
args.is_parallel = True
logger.info("Running with " + str(args.parallel) + " jobs")
if args.is_parallel and not args.index:
logger.error("Index file is required when running in parallel.")
sys.exit()
if not (args.index and os.path.isfile(args.index)):
if not (args.gtf and os.path.isfile(args.gtf)):
logger.error("No GTF or index file found.")
sys.exit()
return args | c6747dea5b9579243ef538ab1fc5fb07e0ab7e70 | 8,489 |
import re
def get_frame_rate_list(fmt):
"""Get the list of supported frame rates for a video format.
This function works arround an issue with older versions of GI that does not
support the GstValueList type"""
try:
rates = fmt.get_value("framerate")
except TypeError:
# Workaround for missing GstValueList support in GI
substr = fmt.to_string()[fmt.to_string().find("framerate="):]
# try for frame rate lists
_unused_field, values, _unsued_remain = re.split("{|}", substr, maxsplit=3)
rates = [x.strip() for x in values.split(",")]
return rates | d3db15553a9bd28dc7be0754c7c8202e20aab8d2 | 8,490 |
def convert_null_to_zero(event, field_or_field_list):
""" Converts the value in a field or field list from None to 0
:param event: a dict with the event
:param field_or_field_list: A single field or list of fields to convert to 0 if null
:return: the updated event
Examples:
.. code-block:: python
# Example #1
event = {'a_field': None}
event = convert_null_to_zero(event, field_or_field_list='a_field')
event = {'a_field': 0}
# Example #2
event = {'a_field': None,
'another_field': None}
event = convert_null_to_zero(event, field_list=['a_field', 'another_field'])
event = {'a_field': 0,
'another_field': 0}
"""
if type(field_or_field_list) is str:
field_or_field_list = [field_or_field_list]
for field in field_or_field_list:
if field in event and event[field] is None:
event[field] = 0
return event | c81bf5909d13b9cb2ce759c3ab0643e03b95c203 | 8,491 |
def setBit(int_type, offset, value):
"""following 2 functions derived from https://wiki.python.org/moin/BitManipulation, this one sets a specific bit"""
if value == 1:
mask = 1 << offset
return(int_type | mask)
if value == 0:
mask = ~(1 << offset)
return(int_type & mask) | 642e8ffb41aaf3c5514038e525275c053a4cd8b1 | 8,492 |
from typing import Dict
from typing import Any
def get_xml_config_gui_settings(xml_dict: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Get the tool configuration from the config XML.
Parameters
----------
xml_dict: OrderedDictionary
Parsed XML Tool configuration
Returns
-------
OrderedDict
GUI settings extracted from the parsed XML
"""
return xml_dict["AlteryxJavaScriptPlugin"]["GuiSettings"] | a13168d8441093f8fb6ce341fd07c5e51d4169a7 | 8,493 |
def deduplicate_list(list_with_dups):
"""
Removes duplicate entries from a list.
:param list_with_dups: list to be purged
:type lost_with_dups: list
:returns: a list without duplicates
:rtype: list
"""
return list(set(list_with_dups)) | 7034f1d8533613f9478916ce7f4b18fd9f94bfe4 | 8,494 |
def adjust_factor(x, x_lims, b_lims=None):
"""
:param float x: current x value
:param float x_lims: box of x values to adjust
:param float b_lims: bathy adj at x_lims
:rtype: float
:returns: b = bathy adjustment
"""
if b_lims is None:
return 0
if x < x_lims[0] or x > x_lims[1]:
return 0
else:
value = b_lims[0]
slope = (b_lims[1]-b_lims[0]) / (x_lims[1]-x_lims[0])
value += (x-x_lims[0])*slope
return value | b0f92eef6098894fa54a3a3ed55fc01b7f6dae95 | 8,496 |
def is_empty_element_tag(tag):
"""
Determines if an element is an empty HTML element, will not have closing tag
:param tag: HTML tag
:return: True if empty element, false if not
"""
empty_elements = ['area', 'base', 'br', 'col', 'colgroup', 'command', 'embed', 'hr',
'img', 'input', 'keygen', 'link', 'meta', 'param', 'source',
'track', 'wbr', 'html']
is_empty = False
for el in empty_elements:
if tag == el:
is_empty = True
break
return is_empty | 429129246c7458f0928f22f8b99db03763c2b699 | 8,497 |
def get_outlier_definition(biomarker):
"""
Centralised definitions of biomarker outliers for filtering
"""
if biomarker == "APHalfWidth":
outlier_definition = 100.0 # ms
else:
raise ValueError(f"Biomarker {biomarker} not found.")
return outlier_definition | 27876fd83c644d7c4f751b99ab2703044e54f41d | 8,498 |
def get_incident_message_ids(client, incident_id):
"""
Returns the message ids for all the events for the input incident.
"""
detail_response = client.get_incident_details(incident_id)
message_ids = []
# loop through all the events of this incident and collect the message ids
if 'events' in detail_response.keys():
for event in detail_response['events']:
message_ids.append(event['message_id'])
if 'abuse_events' in detail_response.keys():
for event in detail_response['abuse_events']:
message_ids.append(event['message_id'])
return message_ids | 3067eb438effb2977fd3a724a284bd58f485b743 | 8,499 |
def _Dirname(path):
"""Returns the parent directory of path."""
i = path.rfind("/") + 1
head = path[:i]
if head and head != "/" * len(head):
head = head.rstrip("/")
return head | 075063a6dd29456f4adb969621d9727aa187d53b | 8,500 |
def IsLoopExit(op):
"""Return true if `op` is an Exit."""
return op.type == "Exit" or op.type == "RefExit" | dbc24fa0efa69447416963a9911c7fae3fd1f244 | 8,503 |
import os
def fasta_file_to_lists(path, marker_kw=None):
"""Reads a FASTA formatted text file to a list.
Parameters
----------
path : str
Location of FASTA file.
marker_kw : str
Keyword indicating the sample is a marker.
Returns
-------
dict
Contains list of ids, descriptions, and sequences for sample
and marker categories.
"""
_id = ''
_description = ''
_seq = ''
sample_ids = []
sample_descs = []
sample_seqs = []
marker_ids = []
marker_descs = []
marker_seqs = []
if not os.path.exists(path):
raise Exception('{} does not exist'.format(path))
with open(path, 'r') as f: # pylint: disable=invalid-name
for line in f.readlines():
line = line.rstrip()
if line.startswith('>'):
# Store sequence if _seq has contents
if _seq:
if marker_kw and (marker_kw in _id):
marker_ids.append(_id)
marker_descs.append(_description)
marker_seqs.append(_seq)
else:
sample_ids.append(_id)
sample_descs.append(_description)
sample_seqs.append(_seq)
_seq = ''
# Split id and description
try:
_id, _description = line[1:].split(' ', 1)
except ValueError:
_id, _description = line[1:], ''
else:
_seq += line
if _seq:
if marker_kw and (marker_kw in _id):
marker_ids.append(_id)
marker_descs.append(_description)
marker_seqs.append(_seq)
else:
sample_ids.append(_id)
sample_descs.append(_description)
sample_seqs.append(_seq)
return {
'sample': {
'ids': sample_ids,
'descriptions': sample_descs,
'sequences': sample_seqs,
},
'marker': {
'ids': marker_ids,
'descriptions': marker_descs,
'sequences': marker_seqs,
}
} | b8a70b6ee697fdd52d117e4a1bdfed8fe79d84d5 | 8,504 |
def islazy(f):
"""Internal. Return whether the function f is marked as lazy.
When a function is marked as lazy, its arguments won't be forced by
``lazycall``. This is the only effect the mark has.
"""
# special-case "_let" for lazify/curry combo when let[] expressions are present
return hasattr(f, "_lazy") or (hasattr(f, "__name__") and f.__name__ == "_let") | 7dd0a09f6a0e60b252ece344d62a937393598167 | 8,505 |
def _sample_ncols(col_limits, random_state):
""" Sample a valid number of columns from the column limits. """
integer_limits = []
for lim in col_limits:
try:
integer_lim = sum(lim)
except TypeError:
integer_lim = lim
integer_limits.append(integer_lim)
return random_state.randint(integer_limits[0], integer_limits[1] + 1) | e31f2e290910b9e7376750b18a6ca6436a82a0cb | 8,506 |
import string
def is_printable(s: str) -> bool:
"""
does the given string look like a very simple string?
this is just a heuristic to detect invalid strings.
it won't work perfectly, but is probably good enough for rendering here.
"""
return all(map(lambda b: b in string.printable, s)) | 78941ba7daca94274fc1b238b6f411f73fc875f6 | 8,507 |
import re
def get_index_of_tone_vowel(syllable):
"""
Returns the index of the vowel that should be marked with a tone accent in a given syllable.
The tone marks are assigned with the following priority:
- A and E first
- O is accented in OU
- otherwise, the *final* vowel
Returns -1 if no vowels found.
ARGS:
syllable (str)
"""
vowels = "AaEeIiOoUuÜü"
index = -1
if 'a' in syllable:
index = syllable.index('a')
elif 'e' in syllable:
index = syllable.index('e')
elif 'ou' in syllable:
index = syllable.index('ou')
else:
match = re.search('[{vowels}]+'.format(vowels=vowels), syllable)
if match:
index = match.end() - 1
return index | 97d4f724f56ce3270e317b4d885b3ac5730e59f5 | 8,508 |
def statement_block(evaluator, ast, state):
"""Evaluates statement block "{ ... }"."""
state.new_local_scope()
for decl in ast["decls"]:
evaluator.eval_ast(decl, state)
for stmt in ast["stmts"]:
res, do_return = evaluator.eval_ast(stmt, state)
if do_return:
state.remove_local_scope()
return res, True
state.remove_local_scope()
return None, False | e38575e5e2119cd9794ea5f0b1629cecf411a0e9 | 8,509 |
def _create_query_dict(query_text):
"""
Create a dictionary with query key:value definitions
query_text is a comma delimited key:value sequence
"""
query_dict = dict()
if query_text:
for arg_value_str in query_text.split(','):
if ':' in arg_value_str:
arg_value_list = arg_value_str.split(':')
query_dict[arg_value_list[0].strip()] = arg_value_list[1].strip()
return query_dict | 2e4478bdf110911d4ca9fcc6c409aab3504a0b8a | 8,510 |
def _getVersionString(value):
"""Encodes string for version information string tables.
Arguments:
value - string to encode
Returns:
bytes - value encoded as utf-16le
"""
return value.encode("utf-16le") | 36646a686c17f2c69d71a0cdeede56f0a1e514e2 | 8,511 |
from typing import List
from typing import Optional
def get_shift_of_one_to_one_match(matches: List[List[bool]]) -> Optional[int]:
"""
Matches is an n x n matrix representing a directed bipartite graph.
Item i is connected to item j if matches[i][j] = True
We try to find a shift k such that each item i is matched to an item j + shift
usecase:
for other_relations a shift 'shift' of the greenyellow intervals must exist such that other_relation is satisfied
for each pair {(id_from, index), (id_to, index + shift)} of greenyellow intervals of signal groups id_from and
id_to.
:param matches: n x n matrix
:return: shift or None if no such shift can be found
:raises ValueError when matches is not an nxn boolean matrix
"""
value_error_message = "matches should be an nxn boolean matrix"
n = len(matches)
if not isinstance(matches, list):
raise ValueError(value_error_message)
for row in matches:
if not isinstance(matches, list) or len(row) != n:
raise ValueError(value_error_message)
if not all(isinstance(item, bool) for item in row):
raise ValueError(value_error_message)
for shift in range(n):
# example:
# suppose matches equals:
# [[False, True, False], [False, False, True],[True, False, False]]
# then a shift of 1 to the left would give
# np.array([[True, False, False], [False, True, False],[False, False, True]])
# this has all diagonal elements
# below we do this check more efficiently for a shift of 'shift' to the left.
if all(matches[row][(row + shift) % n] for row in range(n)):
return shift
return None | f8168e72dab64acc26841a49122dcf08d473ea1f | 8,512 |
def plurality(l):
"""
Take the most common label from all labels with the same rev_id.
"""
s = l.groupby(l.index).apply(lambda x:x.value_counts().index[0])
s.name = 'y'
return s | 4e363648e79b5e9049aca2de56fd343c1efe1b93 | 8,513 |
def _handle_text_outputs(snippet: dict, results: str) -> dict:
"""
Parse the results string as a text blob into a single variable.
- name: system_info
path: /api/?type=op&cmd=<show><system><info></info></system></show>&key={{ api_key }}
output_type: text
outputs:
- name: system_info_as_xml
:param snippet: snippet definition from the Skillet
:param results: results string from the action
:return: dict of outputs, in this case a single entry
"""
snippet_name = snippet['name']
outputs = dict()
if 'outputs' not in snippet:
print('No outputs defined in this snippet')
return outputs
outputs_config = snippet.get('outputs', [])
first_output = outputs_config[0]
output_name = first_output.get('name', snippet_name)
outputs[output_name] = results
return outputs | 693a3e5cba6d72d09b2adb3745abb4fcf07f92d3 | 8,515 |
from datetime import datetime
def parse_timestamp(datetime_repr: str) -> datetime:
"""Construct a datetime object from a string."""
return datetime.strptime(datetime_repr, '%b %d %Y %I:%M%p') | ddacf877c55466354559f751eac633b5bcd7313c | 8,516 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.