content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def filter_labels_by_occlusion(obj_labels, occlusion):
"""Filters object labels by truncation.
Args:
obj_labels: List of object labels
occlusion: Maximum occlusion
Returns:
obj_labels: List of filtered labels
occ_mask: Mask of labels to keep
"""
occ_mask = [obj_labe... | 8cf7493030a6541b9045fb11ffba4a56ef0daeae | 665,332 |
def merge(prod):
"""Merges l-derived one-connected graphs at their marked vertices"""
# lhs is a bi-derived connected and rhs a derived connected.
lhs = prod.first
rhs = prod.second
if not lhs.marked_atom.is_trivial:
rhs.marked_atom.insert_all_after(lhs.marked_atom)
return lhs | d65196893aea469b14e365ca1b53557df3232950 | 665,333 |
import argparse
import os
def parseArgs():
"""Parse command line arguments and return args dict"""
parser = argparse.ArgumentParser(description='Summarize annovar annotated vcfs')
parser.add_argument('-I', '--input', type=str, nargs=1, dest='input_file')
parser.add_argument('-O', '--output', type=str,... | b018e23b9850beb8d482dad9d05d91ec53c2900c | 665,334 |
import numpy
def set_num(problem: str):
"""
give number
>>> set_num('7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098... | 17567026cf47aa960dd6416123577d4e9204e16e | 665,335 |
def get_number(target_str):
"""
gets the number of digits and letters in the target string
:param target_str: type:str
:return:
"""
number_res=0
abc_res=0
for i in target_str:
if i.ispnumeric(): #计算数字的数量
number_res+=1
if i.isalpha(): #计算字母的数量
... | bf2ec3ffa18243a84a3128b3bfacead24599ca82 | 665,336 |
import numpy
def number_of_interruptions(sample_wrapper):
"""
Returns the number of interruptions.
:param sample_wrapper: sample wrapper object
:type sample_wrapper: HandwritingSampleWrapper
:return: number of interruptions
:rtype: float
"""
# Get the pen status
pen_status = samp... | 4f15efbd5c20757174ed3a022f961491594a1d2b | 665,337 |
def diff_test(i):
"""Return the set of symbols, s, which were used in testing that
i.diff(s) agrees with i.doit().diff(s). If there is an error then
the assertion will fail, causing the test to fail."""
syms = i.free_symbols
for s in syms:
assert (i.diff(s).doit() - i.doit().diff(s)).expand(... | ea0d83659149ba62e7a9113fb42921ec025050ca | 665,338 |
def _mpi_command(nprocs, mpi_exec):
"""
Generate a string for shell execution of MPI. If the number of processors is 1 or the executable path is empty,
the returned value is simply an empty string.
Args:
nprocs (int): Number of processors to use.
mpi_exec (str): Path to MPI executable.
... | 17e0b265e5a265a90d8a112ffe635e7b2a4fc6cd | 665,339 |
def getSpecificity(similarityquality):
"""
:param similarityquality: Output of getSimilarityquality()
:return: list of specificity-values in input order.
"""
return [uospecific
for similaritythreshold, symbol, mformat, quality, fieldcount, exactf, nearf, uospecific
in similarityquali... | 7b768972ee90be77e282cd68c6f4ac286d166813 | 665,340 |
def matrixtodict(matrix):
"""
convert a word matrix(which is generated in getMatirx() method in ModelClass.py) to
the one that is used in the test() method in this file.
:param matrix: the count matrix generated by getMatrix method
:return: a Result Array(each element is a dict) that test method ca... | 1b2a440735a86aaf7c87126275e6f5af56a202e2 | 665,341 |
def get_dimensions(partitioning_config):
"""Retrieve the list of partition dimension names.
Args:
partitioning_config (dict): Dictionary of partitioning variables.
Returns:
List of dimensions.
"""
dimensions_dict = partitioning_config.get("dimensions")
dimensions = []
types... | 27cc326359194b4351bc31156e920c59bb65ce74 | 665,342 |
import re
def parse_headers(header):
"""Parse the HTTP headers
Parse the HTTP headers according to RFC 2616 section 4.2
According to the cookie spec, set-cookie headers can not
be moved, for obvious reasons. In the scope of this function
the set-cookie headers will be merged for simplicity.
... | e9fc4743a87674dd002f6b534c23b36b88cb5e47 | 665,344 |
def tostring_numba(array):
"""
1D array to string
"""
temp_string = ""
for value in array[:-1]:
if value == 0:
temp_string += "0"
else:
temp_string += "1"
temp_string += ","
if array[-1] == 0:
temp_string += "0"
else:... | a36e0a36ef59893b420bdd18c3390bd463d72d94 | 665,345 |
from pathlib import Path
import os
def list_datasets(path=''):
"""
Lists the available datasets to be used with the load_data function.
arguments:
path: path relative to phosphodisco data folder. pass 'demo' to list demo datasets.
pass nothing to get list contents of data folder.
... | 9b364a60c10173683e9080b091ac92ec8bb7667c | 665,346 |
def _safe_conversion(value, converter, default=None):
"""Pipes a value through a converter function and returns the converted
value or the default value if there was an exception during the conversion.
Args:
value: the value to convert
converter (callable): a callable that converts the valu... | 97891a0d7f1d68772428dc981d28405ceb161d08 | 665,347 |
import os
import shutil
def create_specific_manager(sm_type, name, dest_path=os.getcwd()):
"""Create a new specific manager
:param sm_type: A string, fsm or ssm
:param name: A string, the name of the specific manager
:param dest_path: A string, the target directory for the manager
:returns: a tu... | 624da944c1064ff7d437cc8b397be9905cca14d3 | 665,348 |
import torch
def l1_normalize(x: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
"""Normalizes the input tensor using L1-norm.
Args:
x: Tensor to be normalized.
eps: Small value to avoid division by zero.
Returns:
Normalized tensor.
"""
return x / (torch.norm(x, p=1, ... | a084e9776cb1b568474ebbc2211d0926269f3c94 | 665,349 |
def _estimate_crosscovar(cweights, proppts, mean, sigpts, mpred):
"""See BFaS; p.88.
Parameters
----------
cweights: np.ndarray, shape (2*dimension + 1,)
Constant kernels weights for unscented transform.
sigpts: np.ndarray, shape (2*dimension + 1, dimension)
Sigma points
mpred: ... | ab1db3cbdd59ae58458be6dc12d5c6e4d114d035 | 665,350 |
def _matplotlib_list(interval_list):
"""
Returns lists for matplotlib ``fill`` command from a list of bounding
rectangular intervals
"""
xlist = []
ylist = []
if len(interval_list):
for intervals in interval_list:
intervalx = intervals[0]
intervaly = intervals... | ae4be41634cdb2910c168cd4b6ec10433308c898 | 665,353 |
import os
def walk_logs(folder, basepath, match="sttclient.log"):
"""
Locates files within a folder matching pattern.
Returns a list of 2-tuples each containing a filepath of a file matching one of specified types,
and a path relative to the basepath.
:param folder:
:param basepath: is strippe... | 10756a26744a1d870e9e2c891e643169cabeb596 | 665,354 |
import math
def lat2y(a):
""" Converts latitude co-ordinate to its web mercator equivalent """
radius = 6378137.0 # in meters on the equator
return math.log(math.tan(math.pi / 4 + math.radians(a) / 2)) * radius | 98f42f9e55f4b5f2d2b136786a4c3bd5dd729f17 | 665,355 |
def fp_boyer_freqs(ups_r, ups_theta, ups_phi, gamma, aa, slr, ecc, x, M=1):
"""
Boyer frequency calculation
Parameters:
ups_r (float): radial frequency
ups_theta (float): theta frequency
ups_phi (float): phi frequency
gamma (float): time frequency
aa (float): spin pa... | 0c2e0ad84b0bf0211b7e7fdade0b42b05d391940 | 665,356 |
def float_eq( a, b, err=1e-08):
"""
Check if floats a and b are equal within tolerance err
@return boolean
"""
return abs(a - b) <= err | d30b6b3cbd04bd351e1d28774d2cb0d20733c19b | 665,357 |
def _make_type (vendor, field):
"""
Takes an NXM vendor and field and returns the whole type field
"""
return (vendor << 7) | field | 1ed42367e1ca4b8dcbba22f54195e99dba0e6d62 | 665,358 |
def p1_win(i, n):
""" Returns whether or not the first player to get hit wins the game
@param i (int) - number of fingers each player starts with
@param n (int) - total number of fingers on a hand
@return (boolean)
"""
(p1, p2) = (i, i)
while p1 % n != 0 and p2 % n != 0:
p1 = (p1 +... | c085e023855d82de265f4c055feb939530c3e4e0 | 665,359 |
def naming_convention(dic, convert):
"""
Convert a nested dictionary from one convention to another.
Args:
dic (dict): dictionary (nested or not) to be converted.
convert (func): function that takes the string in one convention and
returns it in the other one.
Ret... | e149528712e7e2fbc63f3ac6d835294ba638192a | 665,360 |
def _update_paths(paths, idx):
""" add new path build on idx to all paths """
if paths:
return paths + ["{}-{}".format(paths[-1], idx)]
return [str(idx)] | 8fc220ec969b354eebc8e48370a705a1d938dab9 | 665,361 |
def _make_track_ids_smallest(annotations):
"""
Adapted from motion3d:scripts/gen_pseudo_gt_tracks.py
Maps track_ids to smallest set of natural numbers
"""
tids = set(a['track_id'] for a in annotations)
tid2nat = {tid: i for i, tid in enumerate(sorted(tids))}
for a in annotations:
a[... | 5619cab33acd7f11d794314305c6fea47b6a9f2c | 665,362 |
def song_text(string_num=3, la_num=3, last_symbol=1):
"""
The method generates strings which consist of 1 same word with separator "-".
Takes 3 params:
:param string_num: - number of lines
:param la_num: - number of words
:param last_symbol: - the last symbol for the last line. 1 == !, 0 == .
... | 1a864f466eff667ac25c8941b180bf7b4ebb65d6 | 665,363 |
from typing import List
import re
def clean(raw_pgn: str) -> List:
"""
The clean method cleans the raw PGN data
and returns each tag as an element in a list
"""
str_tags = re.split(r'\]', raw_pgn, re.DOTALL)
def cleaner(x): return x.replace('\n', '').replace('[', '')
return list(map(cleane... | 855f8ac423a4dd294b8d069acd93223e250d3631 | 665,364 |
def cut_and_pad_seq(seq, max_len, pad):
"""
"""
return seq[:max_len] + [pad] * (max_len - len(seq)) | a7b2504ad71d2179379f3b081aa92126e20bfcf7 | 665,365 |
def _check_filter(filter_, stix_obj):
"""Evaluate a single filter against a single STIX 2.0 object.
Args:
filter_ (Filter): filter to match against
stix_obj: STIX object to apply the filter to
Returns:
True if the stix_obj matches the filter,
False if not.
"""
# Fo... | 737c1184ff59a723f5f5d316d9db500f2bf37235 | 665,368 |
def gen_query_filters_mock(mocker):
"""Mock _apply_general_query_filters"""
def return_search_arg(
search, *args
): # pylint: disable=missing-docstring,unused-argument
return search
return mocker.patch(
"search.api._apply_general_query_filters", side_effect=return_search_arg
... | bf72f03b19113bd0fbdb8a4b98977ddd16e8a6fb | 665,370 |
def get_etr(etr_t, R_dash_vnt_rtd, V_rtd_SA, V_rtd_RA):
"""定格条件における補正風量比での熱通過有効度
Args:
etr_t(float): 熱交換型換気設備の温度交換効率
R_dash_vnt_rtd(float): 定格条件における補正風量比
V_rtd_SA(float): 定格条件における給気風量
V_rtd_RA(float): 定格条件における還気風量
Returns:
float: 定格条件における補正風量比での熱通過有効度
"""
# (12)
... | 477f326098b4198994ac52ad72b4e5485a600b04 | 665,372 |
def botcommand(*names):
"""Mark function as command.
(for extensions)
Parameters
----------
*names : str
Name/s to invoke the command.
Default: name of function.
"""
def decorator(func):
command_names = names if names != () else func.__name__
func.command... | a8e1821daa717e4ee0327ae8a857bd1b1475cb5a | 665,373 |
def most_busy_backend(provider):
"""Return the most busy backend for the provider given.
Return the most busy available backend for those that
have a `pending_jobs` in their `status`. Backends such as
local backends that do not have this are not considered.
Args:
provider (AccountProvider)... | be58c4b637496e6705763d70f4161f1e033a5b91 | 665,375 |
def luhnCheck(card_number):
""" checks to make sure that the card passes a luhn mod-10 checksum """
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(num_digits):
digit = int(card_number[count])
if not ((count & 1) ^ oddeven):
digit *= 2... | de39e47ce3f5bf89688c78847a10f2dc4cebc8ac | 665,376 |
def del_dups(convos):
"""Delete duplicates in created convokit object.
Parameter: Dataset in Convokit format.
Returns: Deduplicated list"""
ids = set()
unique = []
for x in convos:
if x['id'] not in ids:
ids.add(x['id'])
unique.append(x)
return unique | 369d569185cdcafac15460fc3536eb42a5a9b50f | 665,377 |
def _return_slave(index, parsed_args):
"""Gives the slave index name."""
return index + parsed_args.suffix | c4780221a21c6f5d24d92381bee5310adab40b34 | 665,378 |
import math
def round(quantity, units):
"""The legacy code rounds midpoints away from zero, while Python 3 uses IEEE default mode.
:param quantity: the quantity to round
:param units: the units to convert to before rounding, and of the result
"""
number = quantity.to(units).magnitude
if numbe... | ea072ccd425535639939d74aa8c125d37e755f35 | 665,379 |
def _EBcls2QUPmatij(lib_alm, TEBcls, i, j, c=None, s=None):
"""
Turns E,B spectra into Q,U spectral matrices according to
E = cos Q + sin U
B = -sin Q + cos U
"""
assert TEBcls.ndim == 3 and TEBcls.shape[0] == 2 and TEBcls.shape[1] == 2, (TEBcls.shape)
fl = lambda alm, i, j: lib_alm.... | be949781018bea70f33d521fbf3ba6dad3ef4f3a | 665,380 |
def plus_mod_two(a,b):
""" take absolute value of a + b
and mod result with 2 """
try:
c = abs(a + b) % 2
except:
c = 1
return c | b06212f8e323f18fc161e6bfcf52ab2fb7ebffba | 665,381 |
def sort_to_match(ids, objects, attr="id"):
""" Sorts objects by one of their attributes to match order of ids. Used when order of objects is
needed to be retained and DB returns objects in "random" order.
"""
object_map = {getattr(o, attr): o for o in objects}
objects = [object_map[id] for id in id... | fbf97b3c5f8a1a87f0acdc1957c8d11637203ed8 | 665,382 |
import socket
def incoming(host, port):
"""Open specified port and return file-like object"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# set SOL_SOCKET.SO_REUSEADDR=1 to reuse the socket if
# needed later without waiting for timeout (after it is
# closed, for example)
sock.setsockopt(socke... | 5ed259a1bf502882c99bebcc0a4a458abde56c65 | 665,383 |
def arch_sampling_str_to_dict(sampling_str):
"""
Converts string representations of architecutre
sampling methodology to the dictionary format
that nas_searchmanager.SearchManager uses.
Example:
\"1:4,2:4,3:4,4:4\" is converted to
{1.0 : 4, 2.0 : 4, 3.0 : 4, 4.0 : 4}.
"""
# Remove ... | a17bccbfccc18271df0972838a7ae90940acd059 | 665,384 |
def find_max_weight(regions):
"""Find the maximal weight in the given regions"""
mw = 0
for r in regions:
mw = max(mw, r.profEntry.weight)
return mw | 7c08f3334d1ec42400509df120dde95a1a05e26d | 665,386 |
import pathlib
import json
def load_fixture(name: str):
"""Load a fixture from disk."""
path = pathlib.Path(__file__).parent / "fixtures" / name
content = path.read_text()
if name.endswith(".json"):
return json.loads(content)
return content | dfcaef65a7173037a557e45cc373e9963a7e4191 | 665,387 |
def getOneHotIndices(oneHotMaps):
# OneHotMap is array of maps to one hot reps
"""returned quantity is indices that features map to when convertedto one-hot.
E.g. if input data is features ["type", "color"]
and "type" has values that map to 3 length 1-hot arrays and
"color" has values that map to 2... | c5d7a94d529a4ba57450d7bec196058220e0e137 | 665,388 |
from typing import List
import random
def get_quote_funfact(text_list: List[str]) -> str:
"""
Utility to get random text from given list.
"""
return random.choice(text_list) | 1b2563f28603dcce799e6eb52f4421758fd1aecf | 665,389 |
def float_approximates(float_a, float_b, error=1e-6):
"""Returns whether float a is approximately b within error tolerance"""
return abs(float_a-float_b) < error | 4cd4f7a8fc90376c2e1dd5af6f122ce2b4cb1f43 | 665,390 |
def find_overlap(text, list_1, list_2):
"""
A function written to help with find_chemicals - No longer in use
It returns the elements in list_1 that does not overlap with the elements in list 2
:param text: string:
:param list_1:
:param list_2:
:return:
"""
result = list_1
for a2... | b1912f3af414c08ef393b3b94ed4222030b079b6 | 665,391 |
def decode_fn_ms(module, changed_name_list, mask_weight_list):
"""Decode function."""
for name, value in module._arch_params.items():
module_name = '.'.join(name.split('.')[:-1])
if module.name == module_name:
module_attr = name.split('.')[-1]
changed_name = module.name.s... | 588791ec6097e003fbebcafa9cae7f29cc4a7a57 | 665,392 |
def crop(x, area):
"""
* inputs:
- x (torch.Tensor, required)
A torch tensor of shape (N, C, H, W) is assumed.
- area (sequence, required)
A sequence of length 2 ((X, Y), (W, H)) is assumed.
sequence[0] (X, Y) is the left corner of an area to be cr... | 822b51b53744f0f6004343f67bf1624449a06ada | 665,393 |
def seqs_from_dict(seqs, Alphabet=None):
"""SequenceCollection from dict of {label:seq_as_str}.
This is an InputHandler for SequenceCollection. It converts a dict in
which the keys are the names and the values are the sequences
(sequence only, no whitespace or other formatting) into a
SequenceC... | 3b4fa34f83f66c023c7337d7ee127cca9d3d93c8 | 665,394 |
import torch
def one_hot_embedding(labels, num_classes):
"""
将标签嵌入成one-hot形式
:param labels: 标签,(LongTensor)类别标签,形状[N,]
:param num_classes: 类别数,
:return:(tensor)被编码的标签,形状(N,类别数)
"""
# 返回2维张量,对角线全是1,其余全是0
y = torch.eye(num_classes)
return y[labels] | 35d9b0e3afb9dc76291922b984b99ebc75bb0c90 | 665,395 |
def create_a_key_value_pair(x):
"""creating a function for creating a key value pair"""
return (x,1) | 420f65b334c26beffd686989d9b0383d54891130 | 665,396 |
def group_samples_by_metadata(metadata, data, samples):
""" Return the samples grouped by the metadata. The data and metadata
should have the same ordering of sample columns.
Args:
metadata (list): A single metadata list.
data (list): A single data set.
samples (list): The sampl... | b54106969bd5f2984983e4747fdc8dc57fa4d907 | 665,397 |
async def gather_version(device):
"""Simple function to open a connection and get some data"""
driver = device.pop("driver")
conn = driver(**device)
await conn.open()
prompt_result = await conn.get_prompt()
version_result = await conn.send_command("show version")
await conn.close()
retur... | 3d3adbfa2fd12f6909d29fcffb1356bfee2fe1d9 | 665,398 |
def get_type(string):
"""Returns type of debit/credit card according to first number of card number"""
initial_digit = string[0]
card_type = {
"3": "American Express",
"4": "Visa",
"5": "MasterCard",
"6": "Discover Card"}
if initial_digit not in list(card_type.keys()):
... | 795422d2e2f77ce93008ce028d4fa91eca3e9456 | 665,399 |
import calendar
def get_month_long_name(month):
"""for better readability returns month name (long)"""
return calendar.month_name[month] | 6c484bf54afc69037f65152e807a00203669787a | 665,400 |
from typing import Tuple
def size2shape(size: int) -> Tuple[int, int]:
"""convert a plate size (number of wells) to shape (y, x)"""
assert size in [384, 1536]
return (16, 24) if size == 384 else (32, 48) | 81795acc3992ff0d1b8b39997e8d60b19ea43db0 | 665,401 |
def w_fct(stim, color_control):
"""function for word_task, to modulate strength of word reading based on 1-strength of color_naming ControlSignal"""
# print('stim: ', stim)
# print("Color control: ", color_control)
return stim * (1 - color_control) | 524bb957f048ac25ad7708b284b4738fd0588d61 | 665,402 |
from datetime import datetime
def prepend_timestamp(line):
"""Add ISO 8601 timestamp to line"""
timestamp = datetime.now().replace(microsecond=0).isoformat()
return "{} {}".format(timestamp, line) | 926573337579084b67593204b5bb99171ab96b7c | 665,403 |
import os, fnmatch
def find(pattern, path):
"""
Generic file finder method
"""
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result | 5ba090f5b4dae8159c0af52b1ad2918abdd17f77 | 665,404 |
def my_function(a: int, b: int) -> int:
"""Add two numbers together
Parameters
----------
a: int
first integer
b: int
second integer
Raises
------
value errror if a == 0
Examples
--------
>>> my_function(1, 2)
3
>>> my_function(0, 2)
Tracebac... | d9ca51d57421569073268aad51c8f3a94f4a5dc8 | 665,405 |
def attchk(attstr):
"""Not used by user; program uses it for output and 'filling in' of
missing data"""
try:
M = attstr[0] # Measurement Flag
except:
M = ""
try:
Q = attstr[1] # Quality Flag
except:
Q = ""
try:
S = attstr[2] # Source ... | f762d3d4d9a256ba66f14b2576eeb869bf35227b | 665,406 |
def _add_needed_braces(text):
"""Add braces."""
return u'{' + text + u'}' | cb75f594ba92f481a7fbd6d734cd6f2471ff05a7 | 665,407 |
def to_html(doc, highlighted_mentions):
"""
Convert the document into a simple HTML representation with relevent
mentions highlighted for manual inspection.
"""
content = doc.tokens[:]
for mention in highlighted_mentions:
tag_begin = "<span style=\"color:red\" title=\""
tag_begi... | 8144411d17f4121f58a7d076713d93afa945a9b9 | 665,408 |
from bs4 import BeautifulSoup
import re
def get_links(html_page, base_url):
"""gets all links from html
Parameters
------
html_page (str): document html
base_url (str): the original URL supplied
Returns
------
list: list of all the links in the html document
these could be fi... | f2e97ce2934e994787f3ef79d43558f3380c6722 | 665,409 |
def sizeof_fmt(num: int, suffix: str = "o") -> str:
"""
Human readable version of file size.
Supports:
- all currently known binary prefixes (https://en.wikipedia.org/wiki/Binary_prefix)
- negative and positive numbers
- numbers larger than 1,000 Yobibytes
- arbitrary units
... | 1b1f796637da484e6d1e3a51011782f6b4278bf1 | 665,410 |
def _get_total_citation_by_year(l, max_year=2015):
"""
Calculate the total citation by year
:param l: list of (year, citation) tuple
:param max_year: the maximal year
:return: dict with the totatl number of citation in each year
"""
min_year = int(min([y for y, v in l]))
total_citations... | 84f114e0296d7ff3d83dcf2402153cdfc7787fc7 | 665,411 |
def get_zone_center(instance):
"""
This function operates on the assumption that the
instance will contain attributes called zone and center
"""
_ret = {'zone_name': '', 'center_name': ''}
try:
center = getattr(instance, "center")
_ret['center_name'] = center.center_nam... | 647df3437088976cd2844ef4c9924ffbbcd34279 | 665,412 |
import ast
def ast_attr(fields):
""" fields is string of attrs (e.g. 'self.call.me.now') or list of ast args"""
if isinstance(fields, str):
if "." in fields:
fields_list = fields.split(".")
return ast.Attribute(attr=fields_list[-1], value=ast_attr(".".join(fields_list[:-1])))
... | 4e7f2ddbcd20a9e641ed9fba1e862dd6fdf49a08 | 665,414 |
def table(labels, probs, t):
"""Return a 2x2 table using the given threshold"""
tp = tn = fp = fn = 0
for i,l in enumerate(labels):
c = 1 if (probs[i,1] >= t) else 0
if (l == 0) and (c == 0):
tn += 1
if (l == 0) and (c == 1):
fp += 1
if (l == 1) ... | db1f0e3c4736ac1759c6ff8adf1d96a499d592f5 | 665,415 |
def _get_env_var(repository_ctx, name):
"""Find an environment variable."""
if name in repository_ctx.os.environ:
return repository_ctx.os.environ[name]
else:
return None | 8cd7567ba5eb1859bf596ff9966f23db1d376fd5 | 665,416 |
def hello(name):
"""Use int, string, and other python native types."""
return "Hello " + name | 1830f329ca0ec1db6ce4a69ac445e994cc3e2c87 | 665,417 |
def prep_phrase(args, premise, verbose=True):
"""Check whether there is prepositional phrase in premise."""
# Collect prepositions
preps = [t for t in premise.tokens if t.deprel == 'prep']
if preps:
return True
else:
return False | c7d0c2dee424b84a2d035dd3df2f4edf8e36a675 | 665,419 |
def path_crawler(hm, path=['A'], paths=[]):
"""Given a matrix, return a list of all available paths
It works similarly to Depth-First Search. Starting from a
root element, it recursively iterates down a single path
until it reaches the terminal. It returns the given path,
and works its way back up... | 279485737a5732f09ff164460cf6dde7b7ce5741 | 665,420 |
def get_fibonacci_sequence(length: int) -> list:
"""Return the fibonacci sequence to the specified length."""
fibonacci_sequence = [0, 1]
if length == 1:
return [fibonacci_sequence[0], ]
elif length == 2:
return fibonacci_sequence
for _ in range(0, length - 2):
second_to_las... | f324d2d848bf1b20f054e7b3dd1aeb450d1198f9 | 665,421 |
import re
def edit_code(row, oc4ids_codes, source):
"""
If the row's "Code" is in the ``oc4ids_codes`` list, adds " or project" after "contracting process" in the row's
"Description" and sets the row's "Source" to ``"OC4IDS"``. Otherwise, sets the row's "Source" to ``source``.
"""
if row['Code'] i... | 643669c6a16e1e4f938ed142660fe98d063d1ba0 | 665,422 |
def read_headers(filepath):
"""Read Headers
Reads a header file output by `head -1 * > ~/headers.txt` at
`argosdb-vm-dev:/data/shared/argosdb/generated/datasets/reviewed/`
Parameters
----------
filepath : str
A file path for the headers file to be processed
Returns
-------
... | 6279a5577009b5392be929263a3f6b61e6e50f92 | 665,423 |
def scrub_user_tags(tagcount):
"""rebuild tag list for tags"""
rdict = {}
tagdict = dict(tagcount)
for t in tagdict:
alltags = t.split(',')
for tag in alltags:
if tag:
if not tag in rdict:
rdict[tag] = 0
rdict[tag] += tagdict[t]
rlist = []
for tag in rdict:
rlist.append([tag, rdict[tag... | 8a52fc68861cec24d081abc550a192e978e96214 | 665,424 |
def coalesce(*args):
"""Return the first argument which is not None. If all arguments are None, return None."""
for a in args:
if a is not None: return a
return None | 52ed39ff37c704579a157ef78b8330c384473c15 | 665,425 |
def format_header(line):
"""
Formats the bedpe column header line.
"""
cols = []
for n, item in enumerate(line.replace('#', '').strip().split('\t')):
if item == 'id/name':
cols.append('name')
elif item == 'brass_score':
cols.append('score')
elif item.s... | 6ac4b8f8b09f3eaef98c22075cf20cd4689ac3c5 | 665,426 |
def get_hyphen_exp(text: str, nlp):
"""
Returns a list of all hyphen expressions contained in the text
:param text: string
:param nlp: spacy language model
:return: list of hyphen expressions contained in text
"""
doc = nlp(text)
token_list = [token.text for token in doc]
hyphen_exp... | d80bc04a0cc47b5ebe4fdd8d318f607e0c353a55 | 665,427 |
def clean_lyrics(lyric):
"""
Clean lines that do not contain lyrics
"""
lines = lyric.split('\n')
lyrics_clean = []
for line in lines:
# remove headers from the file
headers = [
'เพลง ', 'คำร้อง ', 'คำร้อง/ทำนอง ', 'ศิลปิน ', 'ทำนอง ',
'เรียบเรียง ', 'เพ... | c6693878ac6d74ef6f364f5c4d3ba97740c1236b | 665,429 |
import numpy
def ccorr2D_zp(signal1, signal2, mask=None):
"""
computes the 2D cross-correlation of the input signals
Note that the binary 'mask' indicates the validity of each pixel
(the validity-mask is the same for signal1 and signal2)
The crosscovariance is computed by an FFT and with a zero ... | 1d765eaae86c7459f81a379a793bc08f4ce6b101 | 665,431 |
def build_response_card(title, subtitle, options):
"""
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
"""
buttons = None
if len(options) > 1:
buttons = []
for i in range(min(5, len(options))):
buttons.appe... | eaa86530b88bc6340940576d5dbb8369740ccbef | 665,432 |
def getDeviceManagementExtensionByInterface(cgx,site_id,element_id,interface_id):
"""
get the existing config for the interface
"""
res = cgx.get.element_extensions(site_id=site_id,element_id=element_id)
if not res.cgx_status:
print(res.cgx_content)
raise ValueError(f"Can't retrieve ... | 6cd3b09b185ff78be068cb0b25b6e6516fe62290 | 665,433 |
def load_rom_raw(filename):
"""
Loads the data from a .nes file as the nesheader and the rom data without further processing
:param filename:
:return:
"""
with open(filename, "rb") as f:
nesheader = f.read(16)
bytecode = f.read()
return bytecode, nesheader | 61c69da67a7ea4b93e1468b4c7be3a661cab78ef | 665,434 |
def sum_fuel_enduse_sectors(data_enduses, enduses):
"""Aggregate fuel for all sectors according to enduse
Arguments
--------
data_enduses : dict
Fuel per enduse
enduses : list
Enduses
nr_fueltypes : int
Number of fuetlypes
Returns
-------
aggregated_fuel_end... | d25b16f4cde787793eb3d4bfaad5698e62bc20be | 665,435 |
def objclass2dict(objclass):
"""
Meta is a objclass on python 2.7 and no have __dict__ attribute.
This method convert one objclass to one lazy dict without AttributeError
"""
class Dict(dict):
def __init__(self, data=None):
if data is None:
data = {}
... | 28c22a184ab954c9b1c9d239ba8c50eaa95349e4 | 665,436 |
def split_url(url):
"""split a zmq url (tcp://ip:port) into ('tcp','ip','port')."""
proto_addr = url.split('://')
assert len(proto_addr) == 2, 'Invalid url: %r'%url
proto, addr = proto_addr
lis = addr.split(':')
assert len(lis) == 2, 'Invalid url: %r'%url
addr,s_port = lis
return proto,a... | 0ebba51995517a0c0efc818ea8280be1b1f05591 | 665,437 |
def get_A_f(A_HCZ, r_Af):
"""敷設面積
Args:
A_HCZ(float): 暖冷房区画の床面積 (m2)
r_Af(float): 床暖房パネルの敷設率
Returns:
float: 敷設面積
"""
return A_HCZ * r_Af | 07f95b2ef3f4aab9c8f441bd21eec7e388e21ca2 | 665,438 |
def is_topk_evaluator(evaluator_keys):
"""Are these evaluator keys from TopK evaluator?"""
return (len(evaluator_keys) == 5 and
evaluator_keys[0] == 'top_1' and
evaluator_keys[1] == 'top_2' and
evaluator_keys[2] == 'top_3' and
evaluator_keys[3] == 'top_4' and
evalua... | 77b0d446118497bb1cb7be6c559f3193722eaf9c | 665,439 |
def _prepare_versions(listen_versions, supported_versions):
"""Return listen versions."""
assert supported_versions
if not listen_versions:
return supported_versions
# Check if any desired versions are unsupported.
unsupported = set(listen_versions) - set(supported_versions)
if unsupport... | 5763cea69557815f70354c8231d2814b3a932127 | 665,440 |
def flatten_series(elevation_series):
"""Return a pd.Series with no change in elevation.
Args:
elevation_series (pd.Series): elevation coordinates along a path.
Returns:
pd.Series: flat elevation coordinates located at the mean value
of the input coordinates.
"""
elevation_series.iloc[:] ... | 506768984c4a39bea50be17fe41abe5ebf3fa984 | 665,441 |
def get_dataset_mean_std(kind):
"""Get mean and std of a dataset for normalization."""
if kind == "epic":
mean = [0.412773, 0.316411, 0.278039]
std = [0.222826, 0.215075, 0.202924]
elif kind == "gtea":
mean = [0.555380, 0.430436, 0.183021]
std = [0.132028, 0.139590, 0.123337]... | e947a3776e473b36a349181c9c94d8c485492644 | 665,442 |
from pathlib import Path
def fixture_log_file_context(context: dict, tmp_log_file: Path) -> dict:
"""Return a context where the log file is specified"""
context["host_config"].log_file = str(tmp_log_file)
return context | 015f0471c707e8aacbfa3ec55341a5c92bac137b | 665,443 |
def check_for_take(string: str) -> bool:
"""
Helper Function that checks to see if clapperboard elements
follows set of rules to be identified as a "take" element
Parameters
----------
string: String
(The string thay will be checked
Returns
-------
Boolean
True if ... | 2b86829a8d1a05bcc72b1766e39bac6f7a832080 | 665,444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.