content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_doc_tf(doc_name):
"""获取指定文档的词频字典.
:param doc_name: 文档名称
:return:
"""
word_tf = dict()
with open(doc_name, 'r', encoding='utf-8') as f:
for line in f:
for word in line.split():
word_cnt = word_tf.get(word, 0)
word_tf[word] = word_cnt + ... | 0cbb8414bccdb64c5d27255e9b96449cf7955bf7 | 670,697 |
def standardise(x,l1,l2):
"""standardise data x to [0,1]
Parameters
x: original data
l1: lower bound
l2: upper bound
----------
Returns
-------
standardised data
"""
return (x-l1)/float(l2-l1) | e4e76f1b9e5b1f4d46fcc56864069f7f87db60b2 | 670,698 |
def full_product_to_l3_product(full_product: str):
"""Returns l3 product name."""
return full_product.split("-")[1] | e644c565badf0e06645d4645f928dbfe87b3fc71 | 670,699 |
def strip_string(value):
"""Remove all blank spaces from the ends of a given value."""
return value.strip() | 0f66367ffc2c651488875ace33e6a44b453c3262 | 670,700 |
import click
def role_selection_is_valid(selection, account_roles):
"""Checks that the user input is a valid selection
Args:
selection: Value the user entered.
account_roles: List of valid roles to check against.
Returns:
Boolean reflecting the validity of given choice.
"""
... | 63eb49eba68264de43d39fce89010b99b1410895 | 670,701 |
from typing import List
def largest_element(arr: List[int]) -> int:
"""
Find the largest element in the array
>>> largest_element([1,2,3,4,5])
5
"""
mx = arr[0]
for i in arr:
mx = max(i, mx)
return mx | 05c0390dd0b4be3298e771ce29e0f7723e8b71b7 | 670,702 |
from typing import List
import os
import shutil
async def remove_model_files(list_file_system_entries: List):
"""Remove files and directories in data/. Files or directories which do not exist are ignored"""
for file_system_entry in list_file_system_entries:
path_to_file_system_entry = os.path.join('da... | dc1c320a36388e661e805b42c7ce79bce53ca786 | 670,703 |
def remove_dollar_sign(xx):
"""
remove $ and return float
"""
for i in range(len(xx)):
x = str(xx[i])
if '$' in x and len(x) < 25:
#print('x = ' + str(x))
x = x.replace('$','')
x = x.replace(',','')
xx[i] = float(x)
try:
... | b64f1fe40769065b7c00c437703d3f2d0c526196 | 670,704 |
import uuid
def initialize_params():
"""Fixture for providing parameters for initialize InitializeParams."""
return {
"parameters": {"param1": "foo", "param2": "bar"},
"session_id": str(uuid.uuid4()),
"test_id": "CONDDA.9.90001.2100554",
} | 7c3e1479ed60af25863db08f3da30079f496adac | 670,705 |
import string
def hst_paths(data_product):
"""
Given an HST data product in the form of an `~astropy.table.Row` returns the
associated possible cloud data paths.
Parameters
----------
data_product : `~astropy.table.Row`
HST product to determine the S3 paths.
Returns
-------... | a626a5cff348cc1bf7a34c4063e6ac867d60dee9 | 670,706 |
import binascii
def calc_crc32(memview):
""" Calculate simple CRC-32 checksum over a memoryview of data
"""
crc = binascii.crc32(memview) & 0xffffffff
return crc | b96bbf2019be3ab91c4ba1da0f0931cd908ed422 | 670,707 |
import requests
import json
import os
def analyze_descriptions(articles):
"""
Adds political bias to each article
"""
for article in articles:
text_to_analyze = article['title']
if article['description'] is not None:
text_to_analyze = text_to_analyze + '. ' + article['descr... | 14a68edebd5552a78c13f568292bc52467bbcacc | 670,708 |
async def result_processor(tasks):
"""An async result aggregator that combines all the results
This gets executed in unsync.loop and unsync.thread"""
output = {}
for task in tasks:
num, res = await task
output[num] = res
return output | d1aee3affdcd0ca11b2ac10992e265e61e23dfaf | 670,709 |
import time
import pandas as pd
def clean_dataset_table(df, msg_flag=True):
"""
Accepts the raw dataset table (a DataFrame object) and returns a cleaned up version removing entries with unknown number of samples and attributes
Also creates a 'Task' category column indicating the main machine learning task... | d21026998846a52a5b89cfd2c422762f613d19ab | 670,710 |
from typing import Iterable
def calculate_large_sum(number_strings: Iterable[str]) -> str:
"""Calculate sum of large numbers.
Args:
number_strings: iterable of numbers as strings to sum up.
Returns:
The sum of the numbers as string.
"""
number_strings = list(number_strings)
la... | 90a2771dec149d37e9957d7cc721da57a9d2b6f7 | 670,711 |
def p2i(p):
""" position to index: vim's getpos into index """
return p - 1 | 6e36eb98ba3abfec4967beae74627ddb37781ce9 | 670,712 |
import re
def _get_cadd_scores(var, labels, hit):
"""
get cadd scores
"""
raw = hit[3].split(",")
scaled = hit[4].split(",")
p = re.compile(str(var.ALT[0]))
for m in p.finditer(str(labels[hit[2]])):
pos = m.start()
return raw[pos], scaled[pos] | 9a2cc94fc9785960801bcc376661aa5bb85e5579 | 670,713 |
import struct
def i16(c, o = 0):
"""
Converts a 2-bytes (16 bits) string to an integer.
:param c: string containing bytes to convert
:param o: offset of bytes to convert in string
"""
return struct.unpack("<H", c[o:o+2])[0] | efabfd5e6aeef593a551c33d477b22b15996a715 | 670,714 |
from typing import Any
def torch_to_jax(value: Any) -> Any:
"""Converts values to JAX tensors."""
# Don't do anything by default, and when a handler is registered for this type of
# value, it gets used to convert it to a Jax DeviceArray.
# NOTE: The alternative would be to raise an error when an unsup... | 043491316868ce1252434856c3adf5176d2cac9a | 670,715 |
def mapl(function, array):
"""
Map a function to an array
(equivalent to python2 map)
:param function: Function to be mapped
:param array: List of values
:return: List of returns values
f = function
array = [x0, x1, x2, ... xn]
[f(x0), f(x1), f(x2) ... f(xn)] = mapl(f, a... | 75c4873bc48a1e949a0b51d0bc0332b6b061e628 | 670,716 |
def connect_(pairs, n=1):
"""connect_
Connects two adjacent clusters if their distance is <= n
:param pairs: Clusters of iterateables e.g., [(1,5),(7,10)]
:param n: distance between two clusters
"""
if len(pairs) == 0:
return []
start_, end_ = pairs[0]
new_pairs = []
for i, ... | 5348556c3f7c54d790b49525fce6b502b3e62a9f | 670,717 |
def _distance(p1, p2):
""" Returns distance between p1 point and p2 """
return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5 | 3e8f3327c295764875b36d5837432c1c03bf3aa7 | 670,718 |
import logging
import re
def filterBySeason(torrentTitles, name, relevantSeason):
"""
filterBySeason applies a regex that matches a torrent for a specific season of a show
:testedWith: None yet
:param torrentTitles: a list of torrent titles to be filtered
:param name: name of tv show
:param relevantSeason: rele... | aaafcdc72032c3cb5d303cb4fc5924a0876c9721 | 670,719 |
def launch_server_config():
"""
Return an array of valid launch config examples
"""
return [
{
"type": "launch_server",
"args": {
"server": {
"flavorRef": 3,
"name": "webhead",
"imageRef": "0d5894... | 5c02b1440d3cf83fd414fb317fe2c9e00d50c94f | 670,720 |
def read_text_file(file_path):
"""Read a txt file"""
with open(file_path, 'r') as f:
return f.readlines() | 4da902efcf3a1747152471128a8706f1b8742ed8 | 670,721 |
import math
def cmap(pc, p_tc, p_lc):
"""
Classification rule
:param pc:
:param p_tc:
:param p_lc:
:return:
"""
return math.log10(pc) + sum(p_tc) + p_lc | 020babe33d61c42011b1a464c6a2511a6f67a4f2 | 670,722 |
def git_pull(repo):
"""
Return the git command to update an existing repo
Args:
repo: string representing a git repo.
Returns:
cmd: list containing the command line arguments to clone a git repo.
"""
cmd = ['git', 'pull']
return cmd | c3cb046e1a17b1624ccf09719b17b86690d4fea9 | 670,724 |
def created_by_external_idp_and_unconfirmed(user):
"""Check if the user is created by external IdP and unconfirmed.
There are only three possible values that indicates the status of a user's external identity:
'LINK', 'CREATE' and 'VERIFIED'. Only 'CREATE' indicates that the user is newly created by an
... | 67e9228e7fdb0e06e1c41d97f0b4ebc13bde1f10 | 670,725 |
def is_growth(name):
""" Test if name is a growth rate-like variable"""
return name in ["gam_leq_GB", "gam_great_GB"] | 493e058d1f3f3eb03563e4f6f91bafdf978f77ee | 670,726 |
def encodingToUse(encoding):
"""Tests whether the given encoding is known in the python runtime, or returns utf-8.
This function is used to ensure that a valid encoding is always used."""
if encoding == "CHARSET" or encoding == None:
return 'utf-8'
return encoding | 4dd7b33a2e296d292814acbc6812fa951b422532 | 670,727 |
def getCouplesInteraction(couples:list, interaction_type:bool):
"""
| Get couples according to their interaction.
:param couple: list of couples
:param interaction: type of the interaction (True or False)
:type couple: CoupleJson
:type interaction_type: bool
:return: list of couples
:... | a87db8fc027f53f49ff608baffe934f966e73fea | 670,728 |
def page_test():
""" Sanity check for flask application (used in automated tests)
"""
# get user-name and access rights from IAM
html = "<h3>Hello world! 3</h3>"
return html | 60ce56d2c8245d48660f4537135e6ab760fe93e2 | 670,729 |
import torch
def reset_params(args, net, dtype):
""" Resets DeepZ slope parameters to the original values. """
relu_params = []
for param_name, param_value in net.named_parameters():
if 'deepz' in param_name:
relu_params.append(param_value)
if args.test_domain == 'zono_iter... | 8d9fa86d0e7e8750d99f22654d60e16a5c4c3244 | 670,730 |
def _adjust_component(component: int) -> int:
"""Return the midpoint of the quadrant of the range 0-255 that the given
component belongs to. Each quadrant spans 63 integers, and the midpoints
are: 31, 95, 159, 223.
>>> _adjust_component(25)
31
>>> _adjust_component(115)
95
"""
if c... | 444baac61f20dc32d05c60900f6fe7dbf7374d51 | 670,731 |
import torch
import math
def perspective(aspect_ratio, fov_y, near_clip, far_clip):
"""Computes perspective transformation matrices.
Functionality mimes gluPerspective (external/GL/glu/include/GLU/glu.h).
See:
https://unspecified.wordpress.com/2012/06/21/calculating-the-gluperspective-matrix-and-othe... | d00430eb971f0b3c4edbfd3cc145a6da1fe02d99 | 670,732 |
from datetime import datetime
def timestamp_zip(string: str) -> str:
"""
Adds the current date and a .zip ending to the given string.
Example:
> timestamp("foo")
"foo-1997-09-14-1253.zip"
"""
timestamp = datetime.today().strftime("%Y-%m-%d-%H%M")
return f"{string}-{timestamp}.zip" | ceb20c46b0620d5f98714634f74d4b6759d7a274 | 670,733 |
def probability_distribution(fd: dict):
"""
Takes a frequency distribution and converts it to a probability distribution.
fd (dict): frequency distribution of characters in a text
"""
total = sum(fd[x] for x in fd)
return {x: fd[x] / total for x in fd} | 95c912c64060c678e33e77804a2a98c6186f26ed | 670,736 |
def _in_text(adict):
"""
Wrapper to add .* around matches so pattern can be found in words.
Parameters
----------
adict : dict
Dictonary with key = `pattern`
Returns
-------
wrapped_dict : dict
Dictonary with key = `.*pattern.*`
"""
return dict((".*{}.*".forma... | 0628c51a5fc03cc11ee1a5923b7f89ba2302cc58 | 670,738 |
def get_digit_c(number, digit):
""" Given a number, returns the digit in the specified position, does not accept out of range digits """
return int(str(number)[-digit]) | 6e38e80fa6f2714cd6fd83ae01b208848dd55e2b | 670,739 |
import os
def is_cross_compiling():
"""Returns True if using GOOS or GOARCH env vars.
We also check at the start of the script that if one of them is used, then
the other is specified as well.
"""
return bool(os.environ.get('GOOS')) or bool(os.environ.get('GOARCH')) | 14e0d30835d1ac7cc1f37e4b31cb3f74e7e04ada | 670,740 |
def kth_to_last_alt(lst, k):
"""This solution implies that the singly linked list is implemented
without the size variable.
"""
node = lst.head
size = 0
while node is not None:
node = node.next
size += 1
if k < 0 or k > lst.size - 1:
return None
n = size - k - 1
... | e1c95074c6975f759dd46477654333ec36d24fa6 | 670,741 |
def move_telescope_north():
"""Return Lx200 protocol command for "move_telescope_north".
"""
command = b'#:Mn#'
return command | 95994b3b37eb6e74f0ad86d95199540a32f36583 | 670,742 |
import mpmath
def cdf(x, c, beta, scale):
"""
Cumulative distribution function of the Gamma-Gompertz distribution.
"""
with mpmath.extradps(5):
if x < 0:
return mpmath.mp.zero
x = mpmath.mpf(x)
beta = mpmath.mpf(beta)
c = mpmath.mpf(c)
scale = mpmath... | 30ea5ad2b8366fb0d5b8373e70f44c2f571d9aa0 | 670,743 |
def calculate_temperature_rise_power_loss_weight(
power_operating: float,
weight: float,
) -> float:
"""Calculate the temperature rise based on the power loss and xfmr weight.
:param power_operating: the power loss in W.
:param weight: the weight of the device in lbf.
:return: _temperature_rise... | 38800f7c093720561cf266f5450679abef4e71fe | 670,744 |
def offspring_calculation(go_tree, go_term):
"""
Calculate the total number of nodes under a term by using a recursive
depth-first tree traversal approach.
:type go_tree: dict
:param go_tree: The GO table containing all terms.
:type go_term: str
:param go_term: The GO node to calculate the... | 46a477e48ce424ecd3c8439e1dca1931f4069122 | 670,745 |
import struct
def make_msg(text) -> bytes:
""" adds the length prefix """
msg = struct.pack("!I%ds" % len(text), len(text), str.encode(text))
return msg | 14cc4f4ffb49bdef608d5678f4ad527035d86d66 | 670,746 |
def _cast(x):
"""
Auxiliary function used to cast strings read from the config file to more useful types. For example, it will
convert any of the strings true, TRUE, True, etc, to True (bool).
:param x:
:return:
"""
# -- At the moment, it is guaranteed that x is a string, however we may wa... | 4499028492d76015623efa9e697907ad9abaedaa | 670,747 |
def get_success_prob(n, pa):
"""
Calculate the probability of successful transmission
input:
n: number of nodes in the same communication range
pa: the attempt probability (pa)
return: the probability of successful transmission
"""
return (n - 1) * pa * (1 - pa) ** (n - 2) | 1324a2364b99273eb38edc56bbd3753bf01b7943 | 670,748 |
def map_category_id(category_map):
""" Assign an ID to each category """
category_id = {}
id_category = {}
counter = 0
for category in category_map:
category_id[category['name']] = counter
id_category[counter] = category['name']
counter += 1
return category_id, id_categor... | 9d48427aeb0e8ae2ac53ec02768d3081f641fcb6 | 670,749 |
def largestElementOfAList(a_list):
"""assumes a_list is a list of numbers
returns a number, the maximum element of a_list
"""
return max(a_list) | 9eb11c894813ba0aba8866ecd262bcb1d930bb98 | 670,750 |
def lamson_setting(func, key):
"""Simple way to get the lamson setting off the function, or None."""
return func._lamson_settings.get(key) | 8f6e04cbd197b1a4d3a7442a6c9edec4fbf69287 | 670,752 |
import random
import string
def generate_password(length=8):
"""パスワードを作成
英文字と数字の組み合わせ
:param length: パスワードの長さ
:return:
"""
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length)) | cec485827f9202069ea258d8e4364faeadefad37 | 670,753 |
def getSquareDistanceOriginal(p1, p2):
"""
Square distance between two points
"""
dx = p1['x'] - p2['x']
dy = p1['y'] - p2['y']
return dx * dx + dy * dy | 8650bcd719fc758dfd969a61f1a57c6f3a385bee | 670,754 |
def _regroup_indexes(idx_transition, idx_seg):
"""Regroup transitions and segmentations lists (regroup the last
part to supress signatures etc)"""
if len(idx_seg) == 0:
return idx_transition
indexes = []
for i_tran in idx_transition:
last_i_seg = (0, 0)
for i_seg in idx_seg:... | d57f53c8c3b42e51d3cb45b75dfe3e097071a3f7 | 670,755 |
def url_search_parameter_update(context, key, value):
"""Inspects the current url parameters with the context of a web request,
and updates them based on the key and value passed in so that the return
value of this method can be used as a url in tags.html or similar links.
"""
request = context['req... | 65a7885e07358e850c2dfe8da13eaef5a49dadfc | 670,756 |
def unpack_libraries(libraries):
""" Given a list of libraries returns url """
if libraries:
return libraries[0].get('url') | 49bde15bef3b3cbb65b1d2a26958fded2acec9fd | 670,757 |
def BitofWord(tag):
"""
Test if the user is trying to write to a bit of a word
ex. Tag.1 returns True (Tag = DINT)
"""
s = tag.split('.')
if s[len(s)-1].isdigit():
return True
else:
return False | 696a8290acbff14134f9f4a0852836975022aa57 | 670,758 |
def lines_intersect(p0, p1, p2, p3):
"""
Returns
-------
bool
Boolean indicating whether the two lines defined by p0->p1 and p2->p3
intersect.
"""
x_1, y_1 = p0
x_2, y_2 = p1
x_3, y_3 = p2
x_4, y_4 = p3
return (x_1 - x_2) * (y_3 - y_4) - (y_1 - y_2) * (x_3 - x_4)... | b51dd21f6d0b6e633e95ab95da3cd5b09489a3ca | 670,759 |
import os
import glob
def find_all_local_file_names(source_folder_name):
"""
Returns a list of all files that exist in the current working directory,
filtered by source_folder_name if provided.
"""
cwd = os.getcwd()
cwd_extension = os.path.normpath(f'{cwd}/{source_folder_name}/**')
file_na... | 6bf07940068650690e06aadcf5418f2e00d80404 | 670,760 |
def dna_to_binary_string(seq):
"""Encodes the given DNA sequence to binary encoding (2 bits per nt).
The last letter of the sequence is encoded in the 2 least significant bits.
"""
DNA_CODES = {
ord(b'A'): 0b00,
ord(b'C'): 0b01,
ord(b'G'): 0b10,
ord(b'T'): 0b11
}
... | 0abe30397e5856654a861b1a4a1ae49e11199491 | 670,761 |
def is_not_false_str(string):
"""
Returns true if the given string contains a non-falsey value.
"""
return string is not None and string != '' and string != 'false' | 49969a2899e3e2ca35ada15ff8d4b482dd3abe80 | 670,762 |
from pathlib import Path
from typing import List
import gzip
def save_metadata_files(path: Path, contents: str) -> List[Path]:
"""Saves the metadata file and the corresponding compressed version of the
file.
:param path: The path to save the uncompressed metadata file at
:param contents: The data to ... | d6bd3c74abe88cb3cbd4c22d6492bc117cb47e09 | 670,763 |
import shutil
import os
def clean_up(tmp_dir="./static/assets/db/"):
"""
Cleans up any auxiliary file generated by invoice
"""
if not os.path.exists(tmp_dir):
return True
try:
shutil.rmtree(tmp_dir)
return True
except shutil.Error:
return False | 165ffae39ba1a9d4e105e9b1e25890fec30f8a0d | 670,764 |
def generate_crossings(points, n_rings):
""" Generate a rings crossing dictionary from crossings points.
:param list points:
Points is a list of rings from 0 to N-1. Each list
specifies the LED number of each point on the ring that
is crossed by another ring.
:r... | 6aa39dd7fbf3002783167059336fe4aebf03d28d | 670,766 |
def create_random_files(tmpdirname, num_of_files=10):
"""
Create random files in dir given
"""
_files_created = []
# Create random files
for i in range(1, num_of_files + 1):
_object_key = f"{i}{i}{i}.txt"
_test_file = tmpdirname.join(_object_key)
_test_file.write("XXXXXX... | 506d6aebeb92940d68a79810cf493994db0c8aad | 670,767 |
def match_bag(context, bags):
"""Matches bag to the file for which an event is triggered and returns bag
or list of all bags to run Fixity against.
Args:
context (obj): Object that contains event context information
bags (set): List of bags to match against
"""
filename = context.res... | 10296c29ef8d2cb9e813f395b7efaaa52aae170b | 670,768 |
def rebin(im, binning=2):
"""
rebin an image by the number of pixels in x and y direction given by binning
Parameter
---------
image: numpy array in 2 dimensions
Returns
-------
binned image as numpy array
"""
if len(im.shape) == 2:
return im.reshape((im.shape[0]//binni... | 4a14309d2ed752bf1fc8c3f3e2d9d39645316b82 | 670,769 |
import sys
def class_module (c) :
"""Return the module defining the class `c`."""
return sys.modules [c.__module__] | 1cb8c72835bc42eedbeacf6334a8ea355d61959f | 670,770 |
def validate_numeric(window):
"""
Validates the contents of a window (usually a text control), to make sure it is numeric.
The window's contents are altered if the user entered any non-numeric input. 0 is returned if only a minus sign
is present in the control, to allow the user to enter negative numbe... | 164329aba33c86787b65788a1c68eab15edc5165 | 670,771 |
import operator
def get_freq_tuples(my_list, print_total_threshold):
""" Turn a list of errors into frequency-sorted tuples thresholded by a certain total number """
d = {}
for token in my_list:
d.setdefault(token, 0)
d[token] += 1
return sorted(d.items(), key=operator.itemgetter(1), r... | 486e6e81159b9430b2e4be167039c0a4f3c595be | 670,772 |
import torch
def model_to(on_gpu, model):
"""Transfers model to cpu/gpu.
Args:
on_gpu (bool): Transfers model to gpu if True otherwise to cpu
model (torch.nn.Module): PyTorch defined model.
Returns:
torch.nn.Module:
The model after being moved to cpu/gpu.
"""
... | c8731f84448cf6fccc387fe50b359e118cc2ce5e | 670,773 |
import torch
def BCEWithLogitsLoss(feat, target, weight=1.):
"""
binary cross entropy loss with sgmoid
"""
pos_coords_ids = target.nonzero()[:,0]
neg_coords_ids = (~target).nonzero()[:0]
pos_feats = torch.clamp(torch.sigmoid(feat[pos_coords_ids]), 1e-7, 1.0 - 1e-7)
neg_feats = torch.clam... | 63f0263a25b5588e86af9060587d86bbc2bf4df1 | 670,774 |
def format_movie_year_min(pick_movie_year_min):
"""
Ensures that the minimum movie year is properly formatted (parameter is the minimum movie year)
"""
if bool(pick_movie_year_min) == True:
movie_year_min = str(pick_movie_year_min) + "-01-01"
else:
movie_year_min = None
retur... | 5a97a1f059d5dfb445042ea0a31bb8aed6342a0f | 670,775 |
def id_has_been_provided(entity_id):
"""
Simple function returning true or false
if id has been provided. Created for
readability purposes.
"""
return True if entity_id else False | 51cfdf6f4d88d5ce7c38e5d4cdc066753155d4d7 | 670,776 |
import os
import requests
import json
def get_hotfix(store, hotfix_url, cache_file):
"""
Routine to grab hotfixes in the format we want, given a hotfix URL. Returns
a tuple containing the store name, hotfix data, and a boolean specifying
whether or not the new hotfix data should be written out to the... | 7723aeedef56bdf6b60900ef51c9320bfa7de751 | 670,777 |
def width0diameter(b, d):
"""Calculate rate width over diameter.
:param b (float): impeller width [m]
:param d (float): diameter [m]
:return bd (float): width over diameter
"""
bd = b / d
return bd | ace9712133f7b9b28f8fb755d57dc28fc4fc52ae | 670,778 |
import pathlib
import os
def safe_path(story, path):
"""
safe_path resolves a path completely (../../a/../b) completely
and returns an absolute path which can be used safely by prepending
the story's tmp dir. This ensures that the story cannot abuse the system
and write elsewhere, for example, sto... | fbdbc3b0bc37b2b52aacac3d9d722b6e5750dbca | 670,779 |
def remap_values(values, target_min=0.0, target_max=1.0, original_min=None, original_max=None):
"""
Maps a list of numbers from one domain to another.
If you do not specify a target domain 0.0-1.0 will be used.
Parameters
----------
val : list of int, list of long, list of float
The val... | f9f9d2ceb02c1ac6e68330f8600dbc212105b7da | 670,780 |
def match_gamma(value, gamma, gamma_mask):
"""Do a bitwise check of value with gamma using only the bits from gamma_mask"""
return not (value & gamma_mask) ^ (gamma & gamma_mask) | 16c1fda48964d7fc5a81b30081ddeb716869a7c6 | 670,781 |
def generate_sample(M, model, num_chains=4, warmup=5000, num_samples=500):
"""Run sampling for data matrix M."""
# Prepare the data dictionary
data = dict()
data = {"n_p": M.shape[0],
"n_a": M.shape[1],
"M": M}
samples = model.sampling(data=data,
... | 69a8637dd2df60d9d9fc492cf59406c6da79aad8 | 670,782 |
import select
def _select_for(fd, readable, writable, error, timeout):
"""Select polling backend.
@param fd: File descriptor
@type fd: int
@param readable: Whether to wait for readability
@type readable: bool
@param writable: Whether to wait for writability
@type writable: bool
@param ... | 23a3906a5146357ca1fc9b96cf5550cb56b6152c | 670,783 |
import requests
def get_tags(url, headers):
"""
Get dictionary existing tags
"""
api_url = f"{url}/api/extras/tags/"
response = requests.request("GET", api_url, headers=headers)
all_tags = response.json()["results"]
tags = []
for tag in all_tags:
tag_info = dict()
tag_... | 2f7e1e090659dec8a7519cad48904d052e15bd2b | 670,784 |
def compare(song1, song2):
"""
Compares two songs and returns which is prefferec (1 or 2) or returns
0 if it's a tie. Numbers are returned as strings
"""
print("1:", song1.name, "by", song1.artist, "or,")
print("2:", song2.name, "by", song2.artist, "?")
# x is evaluated as a string and acts ... | fc2996b0e214b77932a540b89d2feacb276f5b0f | 670,785 |
def convert_from_cammel_case_to_spaces(text):
"""
>>> convert_from_cammel_case_to_spaces('HelloWorld')
'Hello world'
>>> convert_from_cammel_case_to_spaces('helloMotto')
'hello motto'
"""
spaced_text = text[0]
for char in text[1:]:
if char == char.capitalize():
... | 37f9a551f3bb39218a3de9d67b5774fe31f1e6d4 | 670,786 |
def jmap(s, f, *l):
"""Shorthand for the join+map operation"""
return s.join(map(f, *l)) | aaf28df451bccf52ece3ca0eb6a96ecd737bc9e3 | 670,787 |
def get_neigbor_data(data, t, size):
"""
get the neigbor data of t
:param data:
:param t:
:param size:
:return: nbdata
"""
t_index = data.index[data['EventTime'] == t].tolist()[0]
data_point_index = range(t_index - int(size / 2), t_index + int(size / 2)+1)
nbddata = data.iloc[dat... | 1013c5eaba71e85a7adfbd960d7a48371f4c573e | 670,788 |
def get_variants(intervals, horizon):
"""gets all possible variants of the intervals within the horizon"""
results = []
for interval in intervals:
min_start = interval[0]
max_start = interval[1]
dur = interval[2]
temp = []
for j in range(min_start, max_start + 1):
... | e8e61243aa7026eb442da7e94089b4c4d07e3ba4 | 670,792 |
import json
def json_recursive_size(data, level=0, maxlevel=None):
"""Get size of a JSON object recursively."""
### HELPERS
# how many levels remaining?
remaining_levels = maxlevel - level if maxlevel is not None else None
def length_now(d):
"""Get length of a json string."""
re... | 3f95cbfe438a79b5ad22ba848dd29fc376563c04 | 670,793 |
import math
def rspace_sum(rs, qs, basis, kappa, rlim):
"""
Real space part of the sum
Parameters:
rs -- list of particle positions
qs -- list of particle charges
basis -- real space basis
kappa -- splitting parameter
rlim -- size of lattice (one side of a cube of points... | 28df62c94f5503386b1fa7b3557a9acee1404588 | 670,795 |
def findCompartment(rx, blocks, aR, aP, rR, metaboliteBlock):
"""
Derive information on compartment aspects of the reaction.
Returns
-------
'type': String 'Transport','Exchange' or 'Normal' (kind of reaction).
'comp': compartment of SBML-model. arrow between compartments when reaction is 'Tran... | fe6efab25e6c69e745894dc39ca175d3b50a12e4 | 670,796 |
def threadsafe_method(func):
"""Marks a method of a ThreadSafeSingleton-derived class as inherently thread-safe.
A method so marked must either not use any singleton state, or lock it appropriately.
"""
func.is_threadsafe_method = True
return func | adb631c0314e159d5d764577df87b23db71c8460 | 670,797 |
def revert_correct_V3SciYAngle(V3SciYAngle_deg):
"""Return corrected V3SciYAngle.
Only correct if the original V3SciYAngle in [0,180) deg
Parameters
----------
V3SciYAngle_deg : float
angle in deg
Returns
-------
V3SciYAngle_deg : float
Angle in deg
"""
if V3S... | 2ef5e03bf249756fb04a05b28b04ca19bacd7cdd | 670,798 |
from typing import Counter
def get_contents(path : str) -> dict[str, dict[str, int]]:
"""Get a weighted, directed graph of bags.
No protection for the case of cycles.
"""
with open(path, "r") as f:
lines = f.readlines();
contents = {}
# Could use regex here, but hardly seems nece... | 2784f2422b3d58434038856ec06d4a8b4ad40d35 | 670,799 |
def dynamic_range_compression(db, threshold, ratio, method='downward'):
"""
Execute dynamic range compression(https://en.wikipedia.org/wiki/Dynamic_range_compression) to dB.
:param db: Decibel-scaled magnitudes
:param threshold: Threshold dB
:param ratio: Compression ratio.
:param method: Downwa... | 1c5434a4bda28959bfa4b71a594e2cf6fbd71b79 | 670,801 |
def cos():
"""
CoSINE output options
"""
return {
1: ("COS_1", "COS_1"),
2: ("COS_2", "COS_2"),
3: ("COS_3", "COS_3"),
4: ("COS_4", "COS_4"),
5: ("COS_5", "COS_5"),
6: ("COS_6", "COS_6"),
7: ("COS_7", "COS_7"),
8: ("COS_8", "COS_8"),
... | b77618b80e472a5616e755c97668eb520a8d61e8 | 670,802 |
def level_by_permission_value(value):
"""
根据权限值返回当前的等级
@param value 权限值
"""
if 0 < value <= 100:
level = int(value / 5) - 1
else:
level = 1
return level | 315586ea9945d3b7a63545cf53598c3ffc68e085 | 670,803 |
def blend_darken(a, b):
""" Helper function for darken blending.
"""
if a>b:
return b
return a | 00c58f418bc662ea8005614646dc5de2d5d48b7b | 670,805 |
import os
def add_file(context, paths):
"""This function is used inside the dockerfiles templates to
render them by using either the ADD or VOLUME instruction."""
if context['use_volume']:
paths = paths.get('common', {})
paths = ['"{}"'.format(path) for path in list(paths.keys())]
... | c05c0fa2c3dd30848e6a67d244ad9cc8ffc7de58 | 670,806 |
def fake_get_k8s_obj_always_successful(obj, _):
"""Mock of get_k8s_obj that always succeeds, returning the requested lightkube object"""
return obj | e23bfafa535a45d785f8cd6c5b9097919ce7033d | 670,807 |
import sys
def exc():
"""
"""
a, b, c = sys.exc_info()
return b | 218ea53fab1cea2e908a0b6a17177df994e07399 | 670,808 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.