content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Tuple
def find_lines_from_points(
p0: Tuple[float, float],
p1: Tuple[float, float]
) -> Tuple[float, float]:
"""
Function calculating the line passing throught a pair of points.
Args:
p1 (Tuple[float, float]): First point.
p2 (Tuple[float, float]): Second point.... | de1d03a3df52c1007c3ae8cbfc1087197f27d412 | 642,983 |
def create_filename(file_name: str, extension: str) -> str:
"""
Replaces white spaces of the string with '-' and
adds a '.' and the extension to the end.
:param file_name: File name
:param extension: File extension
:return: str Transformed filename
"""
return file_name.replace(' ', '-') ... | 868c8dc3375bd65b13bbb06965e267e36c6fef6e | 642,984 |
def module_fuel(mass):
"""Calculate needed fuel for mass."""
return mass // 3 - 2 | f1070cc0f94f53f7e64a519544aaa60411d1294e | 642,986 |
def compute_set_difference_one(s1, s2):
""" Computes the set difference between s1 and s2 (ie: in s1 but not in s2)
PRE: s1 and s2 differ by one element and thus their set
difference is a single element
:arg s1 (set(T)): super set
:arg s2 (set(T)): subset
:returns (T): the s... | e4a0c1fb07195d6d87252811552d91613d2dbb3d | 642,987 |
import re
def Amatch(tmpl, strn):
"""
Test for AIPS match of string
A "?" matches one of any character, "*" matches any string
all blanks matches anything
Returns True or False
* tmpl = Template string
* strng = String to search for occurance of tmpl
"""
# All blank?
... | b5755be356c25554de899dab1ae4cc2841312f8e | 642,988 |
def generate_level01():
"""Generate the bricks."""
bricks = bytearray(120)
index = 0
for row in range(27, 57, 6):
brick_color = (row - 27) // 6
for col in range(16, 112, 12):
bricks[index] = col
bricks[index + 1] = row
bricks[index + 2] = brick_color
... | 09236436f28bfda401fca6343593e43a4d38a20a | 642,989 |
def distance1(x1, y1, x2, y2):
"""Retourner la "Manhattan distance" entre (x1, y1) et (x2, y2)."""
return abs(x1 - x2) + abs(y1 - y2) | 9bd234940badcedb04ff5313d033d3af4fd27cb5 | 642,990 |
def within_ID(idx, b0, b1):
""" Tests whether an object identifer is within the
remit of the shard bounds. """
return b0 <= idx < b1 | ea1c922f5e6da31f68907d4e404e80aab0ad6746 | 642,991 |
def merge_sort(array):
"""
Sort array in ascending order by merge sort
Merge Sort is a Divide and Conquer algorithm. Conceptually,
a merge sort works as follows:
1. Divide the unsorted list into n sub-lists, each containing
one element (a list of one element is considered sorted).
2. Repe... | 7edd3aa8dd72ef44b6afd7af57041167422b6df1 | 642,992 |
def parse_responsive_length(responsive_length):
"""
Takes a string containing a length definition in pixels or percent and parses it to obtain
a computational length. It returns a tuple where the first element is the length in pixels and
the second element is its length in percent divided by 100.
No... | 220b2c593621bf056d934214a8824fc1f692d702 | 642,993 |
def Pack(flatten, nmap_list):
"""Packs the list of tensors according to `.NestedMap` in `nmap_list`.
`Pack` is loosely the inverse of `Flatten`.
Args:
flatten: A list of tensors.
nmap_list: A list of `.NestedMap`.
Returns:
A list of `.NestedMap`, say ret is the returned list. We have
1. le... | 4c0caff454f269dc91715d4dbd8a9a35fafabf86 | 642,994 |
def ptime(s: float) -> str:
"""
Pretty print a time in the format H:M:S.ms. Empty leading fields are
disgarded with the exception of times under 60 seconds which show 0
minutes.
>>> ptime(234.2)
'3:54.200'
>>> ptime(23275.24)
'6:27:55.240'
>>> ptime(51)
'0:51'
>>> ptime(325)
'5:25'
"""
h: float
m: float... | d669ed4856d1cf7777ecfc84890f85ccee549e5c | 642,995 |
def knot_vector_uniform(num_points, degree, periodic=False):
"""Computes a uniform knot vector.
Parameters
----------
num_points : int
Number of points to compute parameters for.
degree : int
The degree of the curve.
Returns
-------
list of float
The knot vector... | e053765c7142b60a6d4b8b162f2314e7af3ce373 | 642,996 |
def generate_mock_har(*args) -> dict:
"""build facility for unit tests used to generate hars with GA hits
GA hits will get values in argument
Args:
schema (list): 'dp' parameters for GA hits "A" ,"x", "B",..
Returns :
dict : har
example : generate_mock_har_ga("A","B") ->
... | e15c614e781faa947fc97b39b802e0320cc811d5 | 642,997 |
def stream_hashsum(ioobj, hasher, blocksize=65536):
"""Generate a hash sum from a filelike object using the supplied hashlib algorithm.
Example:
stream_hashsum(open('foobar.txt','rb'), hashlib.md5())
"""
while True:
block = ioobj.read(blocksize)
if len(block) > 0:
... | 95f7203992da8cb12454149456cf961c1d90508a | 642,998 |
import requests
def _fetch_seq_ensembl(ac, start_i=None, end_i=None):
"""Fetch sequence slice from Ensembl public REST interface.
Args:
ac (str): The accession of the sequence to fetch.
start_i (int, optional): The start index (interbase coordinates) of the subsequence to fetch.
D... | 407aeacd78826d13dc4634c0758baeb9f7cb4066 | 642,999 |
def get_adjective():
"""Returns an adjective from the words.txt list."""
with open("latin_adjectives.txt", "r") as words_file:
words = words_file.readlines()
count = 0
try:
count_file = open(".tweetcount", "r+")
try:
count = int(count_file.read()... | 47c3a4760b7e2159cfbc5283f12d0941ede1d27e | 643,000 |
def non_valid_devs(host):
"""Inventory Filter for Nornir for all non-valid devices.
Return True or False if a device is not valid
Args:
host(Host): Nornir Host
Returns:
bool: True if the device do not have a config, False otherwise.
"""
if host.data["has_config"]:
return... | 020b7184d138357e169f0ac19b7e0d0f7ac56f73 | 643,001 |
import requests
def get_ics(url):
"""
Gets the ICS file residing at the given url.
:param url: the url from which to download the ics file
:type url: str
:return: string containing the ical file contents
"""
req = requests.get(url)
assert req.ok, "Failed to download the file"
retur... | a723757c39d8ecb5c40ce35d06d9bfb6a039bca2 | 643,002 |
def add_units(metric_name):
"""
Given a metric name, it adds the units according to its input.
Parameters
----------
metric_name : str
The name of the metric where the units will be added
Returns
-------
label : str
The new label of the metric containing the units that
... | 03ab1407fcae8c410741e9e9fb90536e6b1c444f | 643,003 |
import re
def pathsplit(p):
"""Split a path into a WebDataset prefix and suffix.
The prefix is used for grouping files into samples,
the suffix is used as key in the output dictionary.
The suffix consists of all components after the last
"." in the filename.
In torchdata, the prefix consists... | 2d667230d330f1e36bad80ff3be4ded695319a8c | 643,004 |
def get_distance(particle):
"""Get Manhattan distance of particle."""
return sum(abs(num) for num in particle['position']) | 15d4d513d7ce61b25d247c2960df5817db3a5efc | 643,005 |
def compute_klevel(rank):
"""
assumes a frequency list of 50K words
:param rank:
:return:
"""
return (rank // 1000) + 1 | d710ff93156ef617149998b534f75e698674d4c1 | 643,006 |
import argparse
def parse_arguments():
"""
Create command-line interface
"""
desc = "Calculate the autocorrelation function of a MSM discretization"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("-l", "--lagtimes", type=int, help="Upper limit of the lagtimes to ana... | 6dd4dad62b2d42a73a46ed7a5588687576952f79 | 643,007 |
def generate_action_buttons_html(object_id, name, description, modal_id,
delete_function_name):
"""Generates HTML for action buttons.
Action button - 'Edit' and 'Delete' used in
pictures' management tab and albums' management tab
in administrator's panel.
"""
ed... | fbe66f603f084ada58abe21c6d45c5a855d1792a | 643,008 |
def color565(red, green=0, blue=0):
"""
Convert red, green and blue values (0-255) into a 16-bit 565 encoding.
"""
try:
red, green, blue = red # see if the first var is a tuple/list
except TypeError:
pass
return (red & 0xf8) << 8 | (green & 0xfc) << 3 | blue >> 3 | 4c1f2c28313c35f839fa189b45fb15abfa715cd1 | 643,010 |
def is_url(url):
"""test for HTTP and HTTPS protocol in the string"""
if len(url) > 6 and (url[0:7] == "http://" or url[0:8] == "https://"):
return True
else:
return False | d2e9c27087455b78c44b63d5f5b93955d949043a | 643,011 |
def keep_comment(text, min_ascii_fraction=0.75, min_length=1):
""" For purposes of vocabulary creation ignore non-ascii documents """
len_total = len(text)
if len_total < min_length:
return False
len_ascii = sum(c.isalpha() for c in text)
frac_ascii = float(len_ascii) / float(len_total)
if frac_ascii < ... | 17710f09cf0e8febe32659278a10ce27fcf80a6d | 643,012 |
import re
def replace_location(match: re.Match, location: str) -> str:
"""Replace location data in the warning string."""
text = match.string
start, end = match.span(2)
return text[:start] + location + text[end:] | 1260b7d42af59222bb2cc0be17f8349200f6c938 | 643,013 |
import glob
def list_cogs():
"""
Gets all modules from [cwd]/botcogs/ and puts them in a list to return in the
form of ["botcogs.module1", "botcogs.module2", "botcogs.module3", ...]
:return: list of strings where each module J.py is of form "botcogs.J"
"""
cogs = glob.glob("botcogs/*.py")
... | 536434bb4292a27574f7c71ac88be300e0ecca86 | 643,015 |
def q_learn(old_state_action_q_value, new_state_max_q_value, reward, learn_rate=0.01, discount_factor=0.9):
"""
Returns updated state-action Q_value.
:param old_state_action_q_value: Q_value of the chosen action in the previous state.
:param new_state_max_q_value: maximum Q_value of new state.
:para... | cfe2f70823dff79b43a426b2f9e0996ac5e507c1 | 643,016 |
import shutil
def prepare_fastq_folder(folder_name, tmp_path):
""""Helper function to copy a folder on the file system."""
work_path = tmp_path / "work"
input_path = work_path / "FASTQ"
input_path.mkdir(parents=True)
ingested_path = work_path / "FASTQ-INGESTED"
ingested_path.mkdir(parents=True... | 27249a67e51421e9f1ccf1e503baf4e830c859cf | 643,018 |
def format_completion(complete):
"""Returns a tuple of the string that would be visible in
the completion dialogue and the completion word
Parameters
----------
complete : jedi.api_classes.Completion
Description
Returns
-------
tuple
Description
"""
return (comp... | 8e2fab247d3561049af589ff0bb716d16710ba8d | 643,019 |
def clear_trailing_newlines(str):
"""
:param str:
deletes all trailing newlines in a string
:return:
The trailing newlines' free string
I.e: 'test\n\n' -->'test'
"""
while (len(str) > 0):
if str[-1] == '\n':
str = str[0:-1]
else:
break
return ... | bf038e8a0aca3a37422c9507a447f6128c4b0c88 | 643,020 |
def _should_add_space(prev_text, next_text):
"""Logic to determine where to add spaces to XML. Generally this is just
as matter of checking for space characters, but there are some
outliers"""
prev_text, next_text = prev_text[-1:], next_text[:1]
return (not prev_text.isspace() and not next_text.issp... | 292cf739474e7efd2c2cec745965eb3dab03471b | 643,021 |
import torch
def bilinear_interpolate_torch(im, x, y):
"""
Args:
im: (H, W, C) [y, x]
x: (N)
y: (N)
Returns:
"""
x0 = torch.floor(x).long()
x1 = x0 + 1
y0 = torch.floor(y).long()
y1 = y0 + 1
x0 = torch.clamp(x0, 0, im.shape[1] - 1)
x1 = torch.clamp(x... | a5187688014aef814346378145596e3b6d12de23 | 643,022 |
def stripLabels(testFeatures):
"""
Strips label from a test sentence feature vector
"""
return [testFeatures[i][0] for i in range(len(testFeatures))] | 24308c4e3fb0d56256b77fe0310381d8017f41ee | 643,023 |
def get_ctx_result(provides, result):
""" Function that parses data.
:param result: result
:param provides: action name
:return: response data
"""
file_attachment = []
item_attachment = []
reference_attachment = []
other_attachment = []
ctx_result = {}
param = result.get_... | bcd9b135b9e22520a91871593ffb5d59aae71e95 | 643,024 |
def find_pair_in_hits(
hits,
pair,
max_separation = None,
separation = None
):
"""Finds the locations where a pair of TFs bind in a sequence of hits
hits: The hits
pair: A tuple ( binder1, binder2, orientation1, orientation2 )
max_separation: If specified determines maxi... | bdefe55fdabff9c120b8b502e85e74abcb8ce851 | 643,025 |
import time
def get_time():
"""@rtype: float
@returns: current time as float
"""
return time.time() | 7a2be83e0633c79fdd9d279569b7ecb6b57e3541 | 643,026 |
import random
def make_act_type_data(act_tp):
"""
随机生成账号等级,提高高级别账号权重
:param act_tp: 账号类型
:return: 随机账号类别标识码,高级别账号权重较大
"""
if act_tp == "11":
act_typ = random.choice(["3", "3", "3", "2", "2", "1"])
elif act_tp == "211":
act_typ = random.choice(["1", "1", "1", "2", "2", "3"])... | 954a5e41665f9f06cf55e019be2391162c23955e | 643,027 |
def XCOMmaterial(massdic):
"""
Function to convert the mass percentages into XCOM readable input string
Parameters
----------
massdic : dict
Dictionary which stores the mass percentage for each element (which are the keys).
Returns
-------
xcomstr : str
String w... | 4fef10fe2d720c0ede53181d89e5ac26be36c56d | 643,028 |
def AskForPin(userCard):
# Method Description:
"""Asks and Checks the Pin of a Given Card in A Terminal As UI"""
# Endless Loop Till User Enters A correct PIN or cancels
while(True):
pin = int(input("Please Enter Card Pin: "))
if userCard.CheckPin(pin):
print("Welcome To PyA... | 7807eb6c75d589ea54644c3fc1caa197d0b24a7d | 643,029 |
from pathlib import Path
from typing import Tuple
def get_num_neutrinos(fpath: Path) -> Tuple[int, int]:
"""Get the number of neutrinos (both electrons and muons) from the MiniBooNE data text file
Args:
fpath: path to the text file
Returns:
Tuple of (num_electron, num_muon)
"""
... | 43df3017f2011b2d635dab937533b72948c440fa | 643,030 |
import sys
def parse_commandline_arguments():
"""Returns the arguments from the commandline as a dictionary, inserting
default values when the argument was not provided."""
if len(sys.argv) < 2:
sys.exit("Usage: python {} <root_directory> <output_directory>".format(sys.argv[0]))
args = { 'roo... | 4723c3832ceea2ec3ffed90902b2dfb5b26ebf1f | 643,031 |
import functools
def maybe_init(fun):
""" This decorator is used to initialize the Core object - provided
is was not already initialized.
We add the core command (build, upgrade, downgrade, etc) to the
oi.Program, however, we don't have access to the program configuration
until the program is act... | 99ce447a55dc7cba6b64e7d2d31fa8a6c925ac11 | 643,032 |
def factorial(num):
"""
Find the factorial of a number
:type num: integer
:param num: The number to find the factorial for.
>>> factorial(4)
24
"""
if num == 0:
return 1
return num * factorial(num - 1) | 1454262fc21e05d294e91aa3fba9182d4d23521d | 643,033 |
import base64
def decode_readme(data: str) -> str:
"""Decode the contents of old readme"""
decoded_bytes = base64.b64decode(data)
return str(decoded_bytes, "utf-8") | c33e6d9c53c4efaba58fbf03dbc3a2ac7c972d2f | 643,034 |
def validateShape(shape, name):
"""检验shape长度,超过4则截断"""
if len(shape) > 4:
newShape = shape[-4:]
print('\033[31m ' + name + ' tensor shape length > 4, 处理为丢弃头部shape \033[0m')
return newShape
return shape | 1b08a10511ef575c500198a01f473358dc200c04 | 643,035 |
def empty_config_file(tmpdir):
"""produce an empty config file
Returns:
tuple -- Tuple containing following:
1. Path to an empty config file
2. A blank dictionary
"""
cfg = tmpdir.join('empty-config.yaml')
cfg.write('')
emptydict = {}
return (... | 2a215989997878b4b6165ad21fb9dcfbf962b8d7 | 643,036 |
def feature_test_qual_value(feature, **kwargs):
"""Test qualifier values.
For every feature, check that at least one value in
feature.quailfiers(kwargs['qualifier']) is in kwargs['attribute_list']
"""
for attribute_value in feature.qualifiers.get(kwargs['qualifier'], []):
if attribute_value... | 55fb2b354a9bc8d579ce0dc0f0e241ebd6159ad4 | 643,037 |
def time_tracking(start, dest, speed):
"""Функция рассчёта времени из точки а в точку б"""
return abs((dest - start) / speed) | 8eb9f3b853b56fdcfa55b3f69c5a4227534bd7d8 | 643,039 |
from functools import reduce
def conjterm(term, mode="amp"):
"""Modify prefactor for conjugated terms, according to mode='amp|phs|real|imag'."""
f = {"amp": 1, "phs": -1, "real": 1, "imag": 1j}[
mode
] # if KeyError, mode was invalid
terms = [[f, t[:-1]] if t.endswith("_") else [t] for t in t... | e2c0dbaad32103561d5cb8adb307d2ff2f156870 | 643,040 |
import os
def fexist(fname):
""" report if file exists
"""
f = os.path.isfile(fname)
caption = None
if f:
print(' ',fname)
lines = open(fname).readlines()
if len(lines) == 1:
caption = lines[0].strip()
else:
caption = ""
for line... | 6657b0a7ddb4acbcd1a1bad196b9129e21251a65 | 643,042 |
def remove_column(table, index):
"""
Removes a column from a given table given the column index
"""
for j in table:
try:
j.pop(index)
except IndexError:
if len(j) == 0:
raise TypeError("Empty row")
else:
raise IndexError... | f491ab6610906082c2dd48c62c9d33e725a3b740 | 643,043 |
def convert_weights_to_dict(weights_list):
""" The weights are passed in as a list and we need to convert them to a dict """
db_formatted_weights = {}
for weight_details in weights_list:
weight_name = weight_details.name
weight_value = weight_details.weight
db_formatted_weights[weigh... | ba10fff9a63a10f4bf837602ccaabf9befff719d | 643,045 |
def gen_State(drone_id, battery, direction, position, status, speed):
"""Generate a State objects."""
state = {
"@type": "State",
"DroneID": drone_id,
"Battery": battery,
"Direction": direction,
"Position": position,
"Status": status,
"Speed": speed,
}... | 1a6a5e0ab629c3f6ffb4d627b7cce414476bfe59 | 643,046 |
import pickle
def predictSVM(X_test):
"""This function takes a dataset and predict the letter for each data point.
Parameters
----------
dataset: M X 128 numpy array
A dataset represented by numpy-array
Returns
-------
M x 1 numpy array
Returns a numpy array of letter that each data point represents
"""... | ce9f58301fbfdf242356b74b0c19743932d44c3b | 643,047 |
def cli(ctx):
"""Show whether the job lock is active or not. If it is active, no jobs will dispatch on the Galaxy server.
Output:
Status of the job lock
.. note::
This method is only supported by Galaxy 20.05 or later and requires
the user to be an admin.
"""
return ctx.gi... | a141030060e0429d609aa2da6a7bfce9caf915ec | 643,048 |
import torch
def logsumexp(x, dim=0):
"""log sum exp with stability trick"""
max, _ = torch.max(x, dim=dim, keepdim=True)
out = max + (x - max).exp().sum(dim=dim).log().unsqueeze(dim=dim)
return out | d5a61cc34217237a12987be3083a674ff9a84cd5 | 643,052 |
import time
def getVnanetParagragh(driver):
"""
:param driver: selenium driver
:param url:
:return:
"""
try:
xx = driver.find_element_by_id("idviewsmores")
while (True):
if xx:
button = xx.find_element_by_tag_name("a").click()
time.s... | 28fc8cd36e72fc74415bc66bd9a3ec8abff14698 | 643,053 |
import json
def build_trace_dict(f, start_time, end_time):
"""Creates a python dictionary that has trace ids as keys and the
corresponding trace objects as values.
Input: python file object that points to a file with traces, written by
htrace-c's local file span receiver.
The exact format shouldn... | 4171feeebddf2554ed052616a76f3c25b816b945 | 643,054 |
from typing import Union
from typing import List
def check_filetype(estimated_filetype: str, allowed_types: Union[str, List[str]]) -> bool:
"""
Check if a file has an expected filetype.
param: estimated_filetype: The filetype that was estimated by magic.
param: allowed_types: A string or a list of st... | 344cf29a41faadb7dd1f9131bc1cb57c12e92a6a | 643,055 |
def dup_mul_ground(f, c, K):
"""
Multiply ``f`` by a constant value in ``K[x]``.
Examples
========
>>> from sympy.polys import ring, ZZ
>>> R, x = ring("x", ZZ)
>>> R.dup_mul_ground(x**2 + 2*x - 1, ZZ(3))
3*x**2 + 6*x - 3
"""
if not c or not f:
return []
else:
... | a27c459e59e7e7b17d90038efd6204af99a1e8b2 | 643,056 |
import os
import sys
import yaml
def read_yaml(file,
is_echo=False):
"""Read in a YAML file encoded in UTF-8.
Parameters
----------
file : str
YAML file to be read in
is_echo : bool
Dump the YAML content. (default False)
Returns
-------
yaml_loaded : dic... | 837f37a4bf23913d5a2025da7eb12ddccb6c0e96 | 643,057 |
import re
def readMetaData(filepath):
"""
metadata files are txt files which contain electrode metadata needed to create
electrical and spike event series in nwb.
this function parses the metadata file to return a dictionary which is used in the main converter.
metadata includes the name... | fbdef678329486781f99ffa05ed0ba99b5351696 | 643,058 |
import torch
def correct(output, target, topk=(1,)):
"""Computes how many correct outputs with respect to targets
Does NOT compute accuracy but just a raw amount of correct
outputs given target labels. This is done for each value in
topk. A value is considered correct if target is in the topk
hig... | 8608bc5f555bdde96a021347fd32a1f0179b03cf | 643,059 |
def qs_opt_eq(qs, opt, value):
"""
Returns True if the query string option is equal to value.
"""
for opt_value in qs.get(opt, []):
if opt_value == value:
return True | 68dede185a9b1aa62e32a833db4b395ce6c4b1cd | 643,060 |
def _calc_buy_any(skus_counter, result, dict_group_offer):
"""
Function to group and update the skus_counter.
:param skus_counter:
:param result:
:param dict_group_offer:
:return:
"""
list_item = dict_group_offer['list_item']
total_price = dict_group_offer['total_price']
no_item... | f803be82f536ad0384f26b1fba5903ea68816365 | 643,061 |
import numpy as np
def binary_stdev(arr1d, sigma):
"""
calculates the probability space of each time series and checks if the minimum value falls within the
sigma interval or not
- if sigma = 1 -> 68.3%
- if sigma = 2 -> 95.5%
- if sigma = 2.5 -> 99.0%
- if sig... | 52c7e700017c8b036493355fa14233fbd5e28733 | 643,062 |
import os
def remove_prefix(path, prefix):
"""Remove a given prefix from a path
@param path: The path to clean up.
@param prefix: The prefix to remove.
@return: The string without the prefix, or, if the prefix is
not present in the path, raise a ValueError.
"""
path = os.path.abspath(... | e2e8744669d076ff6c1d5400cede14d0156daca8 | 643,063 |
def abbrev(line, ab, nchar):
"""
check for valid abbreviation
"""
# int i,nc;
if len(line) > len(ab):
return 0
nc = len(line)
if nc < nchar:
nc = nchar
for i in range(nc):
if line[i] != ab[i]:
return False
return True | a606d21333c9fd2a72470f6bece971c91437aa0b | 643,065 |
def all_input_tagged_nodes(
graph):
"""Gets all input-tagged nodes that are reachable in a graph.
An input-tagged node is considered reachable if there is a way to get to that
node by an edge of that input type.
Output will be ordered lexicographically, first by the node ordering in the
input graph's ke... | 0ac3956a3b3481f99f6461d3cda0bfc31f7ba466 | 643,066 |
import xml
def is_document_related(err):
"""Returns True for expat errors related to errors in the
document, which should not be reported as internal errors.
"""
errors = xml.parsers.expat.errors
err_str = xml.parsers.expat.ErrorString(err.code)
# All errors in the expat.errors-module in Pyt... | e435da14a7d8da0e923436260fe7aa7e0e0eb427 | 643,067 |
def my_skyline_notelists(notelist):
"""
perform a variation a the skyline algorithm by taking always the highest pitch
at each time.
*notelist* must be in the form returned by misc_tools.load_files
RETURNS :
the list of predicted labels, where 1 is for melody note and 0 is for
accom... | 9e2b261ecc7fbbcc498b1730e8935dfb2831a786 | 643,068 |
def get_blueprints(app):
"""Returns blueprints dict."""
return app.blueprints | 1cadcaca442d6f46f97d88aa4ac516defaf8f09f | 643,069 |
def capture_row_indices(materials, shape_only=False):
"""Captures the start and stop indices of an array based on the
contents of the array.
shape_only provides a method to control binary gap vs no-gap as
opposed to actual details of materials. This should provide a close
to optimal pairing of ind... | f7af85fd5798ff19fd55e59d116b104a7718cf89 | 643,070 |
def exists(path):
"""Return True if path refers to an existing path. Returns False for broken
symbolic links.
:type path: bytes | unicode | os.PathLike
:rtype: bool
"""
return False | f6d1c963205b3726b76849b179819e956f08452c | 643,072 |
def int_from_digits(digits):
"""
Returns a positive integer ``n`` which is a decimal expansion of a
sequence of digits in descending order from the most significant
digit. The input can be a sequence (list, tuple) or a generator,
e.g.
::
[1,2,3] -> 1x10^2 + 2x10^1 + 3x10^0 = ... | 16f01a0dcd9be0b44680bc3fb503790bce848f95 | 643,073 |
import os
import argparse
def check_path(path):
"""valid path argument"""
if not path or os.path.isdir(path):
return path
raise argparse.ArgumentTypeError("readable_dir:{} is not a valid path".format(path)) | 90933f30fbd4b74ce32225e65e8a8e5161a08dc8 | 643,074 |
import os
import sys
def get_fnames_under_path(path):
"""
get filename seq under path.
:param path: string
:return: filename seq
"""
if not os.path.isdir(path):
raise ValueError('In ' + sys._getframe().f_code.co_name +
'() function, path type error.')
fname... | e4b1ce725ea6f2ddf2bc2202687fd6c2542a5327 | 643,075 |
def filter_valid_tournaments(df):
"""Filter for valid tournaments
Notes:
Excluding Tour championship for 2019 and 2020
due to rule change in score totals.
Args:
df (pd.DataFrame) : espn tournaments
Returns:
valid_df (pd.Dataframe) : valid espn tournaments
"""
... | b0251b557b7ee8f2d04109d84a392ac108b9a736 | 643,076 |
from typing import List
from typing import Tuple
def get_pair(numbers: List[int], target: int) -> Tuple[int, int]:
""" get the pair from the list that adds up to the target number """
lesser_half = [x for x in numbers if x <= target/2]
for x in lesser_half:
for y in numbers:
if x + y =... | d8e496bdaa604e7274fc3d0383c6374990c10266 | 643,077 |
def global_dependencies(context):
"""
Dependencies that are loaded for all tethys gizmos (after gizmo dependencies).
"""
return('tethys_gizmos/css/tethys_gizmos.css',
'tethys_gizmos/js/tethys_gizmos.js') | 038b050a6ddbfeea3dd6208e34d08e80de8e3208 | 643,078 |
def subtract(x,y):
"""Subtract x from y and return value"""
return y-x | 708c3de6a50e7ca2fd08722133d901b79d8bac15 | 643,079 |
def calculate_points(prediction, outcome):
"""
Adjusted version of the Brier scoring function, as described at
https://fivethirtyeight.com/features/how-to-play-our-nfl-predictions-game/
"""
diff = (prediction / 100) - outcome
brier_score = diff ** 2
adjusted_score = -(brier_score - 0.25) * 2... | 575ff070100297cb7337951d48a3fc045bc18784 | 643,081 |
import functools
def rget(dict_obj, attrpath):
"""
A fancy version of `get` that allows getting dot-separated nested attributes
like `license.license_name` for use in tree comparisons attribute mappings.
This code is inspired by solution in https://stackoverflow.com/a/31174427.
"""
def _getnoe... | 67e623d8e457fe90787e18e604ef019c98918aad | 643,082 |
def integer_to_octet_string_primitive(length: int, integer: int) -> bytes:
"""Convert a nonnegative integer to an octet string."""
# https://tools.ietf.org/html/rfc8017#section-4.1
if integer >= 256 ** length:
raise ValueError(f"{integer} >= 256 ** {length}")
index = 0
digits = [0] * length
... | fca6962ff5b5208313e4bfd1d23bee626b998c7a | 643,083 |
def check_inorganic(struct):
"""
Checks if the structure contains inorganic atoms.
"""
ele = struct.geometry["element"]
metals = ['Ag', 'Al', 'As', 'Au', 'Ba', 'Be', 'Bi', 'Ca',
'Cd', 'Ce', 'Co', 'Cr', 'Cu', 'Dy', 'Er', 'Eu', 'Fe',
'Ga', 'Gd', 'Ge', 'Hf', 'Hg', 'Ho',... | 2864990a1d0c41429d663be0d56b4bdc308af74d | 643,084 |
import random
import string
import os
import hashlib
def genSeed():
"""Generates a cryptographically secure random string of numbers
which for our purposes acts as a private seed.
Then we use shake_128 to generate a secure hash of the seed
Both are returned
"""
seed_length = int(''.join(random.SystemRa... | 3f6b3c4714e587333d2449b4062c3859a61c40f3 | 643,085 |
def _errorr_input(endfin, pendfin, errorrout, mat,
ign=2, iwt=2, temp=293.6, iprint=False,
**kwargs):
"""Write acer input for fast data.
Parameters
----------
endfin : `int`
tape number for input ENDF-6 file
pendfin : `int`
tape number for inp... | 0fb45c33f3a63908dd1548d6974a498d42779659 | 643,086 |
import sys
def get_lib_extension():
"""
Return the platform-dependent extension for compiled modules.
"""
if sys.platform == "win32":
return "pyd"
elif sys.platform == "cygwin":
return "dll"
else:
return "so" | b5346221f43ef11e809b556bd01a31111941d620 | 643,088 |
import itertools
def sequence(start=0, step=1):
""":yaql:sequence
Returns an iterator to the sequence beginning from start with step.
:signature: sequence(start => 0, step => 1)
:arg start: start value of the sequence. 0 is value by default
:argType start: integer
:arg step: the next element... | 477cffac33412b0e09ab6ebcd7332cd8fe8061de | 643,089 |
import torch
def hermitify(kern, dim):
"""Enforce Hermitian symmetry.
This function takes an approximately Hermitian-symmetric kernel and
enforces Hermitian symmetry by calcualting a tensor that reverses the
coordinates and conjugates the original, then averaging that tensor with
the original.
... | 362a488b5ee94b1ac26f10932be8d423b00b4cd2 | 643,090 |
def condor_bash_template():
"""Bash script that will run leopard -- designed for condor"""
bash_template = """#!/bin/tcsh
echo " > Starting CONDOR job at `date` on `hostname`"
## Copy CMSSW tarball from eos, untar it, and remove the tarball
xrdcp -s root://cmseos.fnal.gov/%(eos_path_to_tarball)s/%(cmsRelease)... | a528f283fb3ebe333d8ced994d0d9bbbd0848113 | 643,091 |
import sys
def getHostPlatform():
"""Returns the host platform running the test suite."""
# Attempts to return a platform name matching a target Triple platform.
if sys.platform.startswith('linux'):
return 'linux'
elif sys.platform.startswith('win32') or sys.platform.startswith('cygwin'):
... | 7f04f96e8dc7aa5c6cf5f5b028dee7347ea9725f | 643,092 |
import re
def namespace_for_username(username: str) -> str:
"""
Get the Kubernetes namespace for a JupyterHub user.
Not all JupyterHub usernames are validate kubernetes namespaces, so we have to
# translate it somehow. This replaces lowercases the input and replaces
non-ascii alphanumeric charact... | e1b50b3e93705ee81aa5a99ea517207dfdc1bcca | 643,093 |
def isoformat(dt):
"""Return iso-formatted timestamp
Like .isoformat(), but uses Z for UTC instead of +00:00
"""
return dt.isoformat().replace('+00:00', 'Z') | 0184465e113093d535e335fabe92067da99d4338 | 643,095 |
import random
def random_code():
"""
Generates a random 3 digit code
Returns the code as a 3 character long string
"""
x=random.randint(000,999)
if x<10:
x= '0'+str(x)+'0'
else:
if x>=10 and x<100:
x= '0'+str(x)
return x | cd0a51dd9ad0b9014224241bf2c26618cfe87b5b | 643,096 |
def get_remote_orders(connection):
"""Returns orders from a remote player.
Parameters
----------
connection: sockets to receive/send orders (tuple)
Returns
----------
player_orders: orders given by remote player (str)
Raises
------
IOError: if remote player cannot be r... | d23c3a002e5a39ef1b9549d0dce20097bb8f52c3 | 643,097 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.