content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_fouling_team_in_penalty(event):
"""Returns True if fouling team over the limit, else False"""
fouls_to_give_prior_to_foul = event.previous_event.fouls_to_give[event.team_id]
return fouls_to_give_prior_to_foul == 0 | ac1578af1092586a30b8fc9cdb3e5814da1f1544 | 707,440 |
import warnings
def lmc(wave, tau_v=1, **kwargs):
""" Pei 1992 LMC extinction curve.
:param wave:
The wavelengths at which optical depth estimates are desired.
:param tau_v: (default: 1)
The optical depth at 5500\AA, used to normalize the
attenuation curve.
:returns tau:
... | 04c89605e8ad4188c62b631e173a9c8fe714958a | 707,441 |
def minMax(xs):
"""Calcule le minimum et le maximum d'un tableau de valeur xs (non-vide !)"""
min, max = xs[0], xs[0]
for x in xs[1:]:
if x < min:
min = x
elif x > max:
max = x
return min,max | 8453b71e5b62592f38f4be84f4366fb02bd0171b | 707,442 |
def compute_prefix_function(pattern):
"""
Computes the prefix array for KMP.
:param pattern:
:type pattern: str
:return:
"""
m = len(pattern)
prefixes = [0]*(m+1)
i = 0
for q in range(2, m + 1):
while i > 0 and pattern[i] != pattern[q - 1]:
i = prefixes[... | 7933cc33eba53247e858ae40b9691d101c7030e6 | 707,443 |
import math
def sigmoid(num):
"""
Find the sigmoid of a number.
:type number: number
:param number: The number to find the sigmoid of
:return: The result of the sigmoid
:rtype: number
>>> sigmoid(1)
0.7310585786300049
"""
# Return the calculated value
return... | 73730a39627317011d5625ab85c146b6bd7793d8 | 707,444 |
def get_name_and_version(requirements_line: str) -> tuple[str, ...]:
"""Get the name a version of a package from a line in the requirement file."""
full_name, version = requirements_line.split(" ", 1)[0].split("==")
name_without_extras = full_name.split("[", 1)[0]
return name_without_extras, version | 424b3c3138ba223610fdfa1cfa6d415b8e31aff3 | 707,445 |
import locale
import itertools
def validateTextFile(fileWithPath):
"""
Test if a file is a plain text file and can be read
:param fileWithPath(str): File Path
:return:
"""
try:
file = open(fileWithPath, "r", encoding=locale.getpreferredencoding(), errors="strict")
# Read only a... | 22167a4501ca584061f1bddcc7738f00d4390085 | 707,446 |
from bs4 import BeautifulSoup
def get_title(filename="test.html"):
"""Read the specified file and load it into BeautifulSoup. Return the title tag
"""
with open(filename, "r") as my_file:
file_string = my_file.read()
file_soup = BeautifulSoup(file_string, 'html.parser')
#find all ... | 31c35588bb10132509a0d35b49a9b7eeed902018 | 707,447 |
import re
def is_valid_dump_key(dump_key):
"""
True if the `dump_key` is in the valid format of
"database_name/timestamp.dump"
"""
regexmatch = re.match(
r'^[\w-]+/\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}_\d+\.\w+\.dump$',
dump_key,
)
return regexmatch | 66fd7d465f641a96bd8b22e95918a6dcbefef658 | 707,448 |
def fill_none(pre_made_replays_list):
"""Fill none and reformat some fields in a pre-made replays list.
:param pre_made_replays_list: pre-made replays list from ballchasing.com.
:return: formatted list.
"""
for replay in pre_made_replays_list:
if replay["region"] is None:
replay... | ee900227a8afcba71e6a00ef475892da4fdc3e3b | 707,449 |
def reverse_dict2(d):
"""Reverses direction of dependence dict
>>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}
>>> reverse_dict(d) # doctest: +SKIP
{1: ('a',), 2: ('a', 'b'), 3: ('b',)}
:note: dict order are not deterministic. As we iterate on the
input dict, it make the output of this functio... | 2419538a13699015f8fefa156e89cf9b1960e358 | 707,450 |
import random
def Flip(p, y='Y', n='N'):
"""Returns y with probability p; otherwise n."""
return y if random.random() <= p else n | 072e170e3f37508a04f8bdbed22470b178f05ab9 | 707,451 |
import configparser
import os
def parse_config2(filename=None):
"""
https://docs.python.org/3.5/library/configparser.html
:param filename: filename to parse config
:return: config_parse result
"""
_config = configparser.ConfigParser(allow_no_value=True)
if filename:
# ConfigParse... | cf260f09e4c293915ab226b915aebed6cb98113f | 707,452 |
def addneq_parse_residualline(line: str) -> dict:
"""
Parse en linje med dagsløsningsresidualer fra en ADDNEQ-fil.
Udtræk stationsnavn, samt retning (N/E/U), spredning og derefter et vilkårligt
antal døgnresidualer.
En serie linjer kan se således ud:
GESR N 0.07 0.02 -0.... | 6d1556cbd01f3fe4cd66dcad231e41fa6b1b9470 | 707,453 |
def fahrenheit_to_celsius(fahrenheit):
"""Convert a Fahrenheit temperature to Celsius."""
return (fahrenheit - 32.0) / 1.8 | 4aee3dd0b54450fabf7a3a01d340b45a89caeaa3 | 707,454 |
import random
import itertools
def sample_blocks(num_layers, num_approx):
"""Generate approx block permutations by sampling w/o replacement. Leave the
first and last blocks as ReLU"""
perms = []
for _ in range(1000):
perms.append(sorted(random.sample(list(range(0,num_layers)), num_approx)))
... | b4b75e77b3749bc7766c709d86bf1f694898fc0d | 707,455 |
import os
def expand(directory: str) -> str:
"""Apply expanduser and expandvars to directory to expand '~' and env vars."""
temp1 = os.path.expanduser(directory)
return os.path.expandvars(temp1) | ffad07715d5425211304e340c084c8f134bbcb22 | 707,456 |
import sys
def gather_ensemble_info(nmme_model):
"""Gathers ensemble information based on NMME model."""
# Number of ensembles in the forecast (ens_num)
# Ensemble start index (ens_start)
# Ensemble end index (ens_end)
if nmme_model == "CFSv2":
ens_num=24
ens_start=1
ens_e... | 56516751dc87415b6a08541eadb02b67a5bc6629 | 707,457 |
import random
import string
def _random_exptname():
"""Generate randome expt name NNNNNNNN_NNNNNN, where N is any number 0..9"""
r = ''.join(random.choice(string.digits) for _ in range(8))
r = r + '_' + ''.join(random.choice(string.digits) for _ in range(6))
return r | d9c72ed4bf742adf50e1fdad4f6acb1cc0046167 | 707,458 |
from typing import Union
from pathlib import Path
import subprocess
def is_tracked_upstream(folder: Union[str, Path]) -> bool:
"""
Check if the current checked-out branch is tracked upstream.
"""
try:
command = "git rev-parse --symbolic-full-name --abbrev-ref @{u}"
subprocess.run(
... | 8c58efe0d0619aaa6517d656ba88f1e29653197a | 707,459 |
def get_directions_id(destination):
"""Get place ID for directions, which is place ID for associated destination, if an event"""
if hasattr(destination, 'destination'):
# event with a related destination; use it for directions
if destination.destination:
return destination.destinatio... | f7cd182cb5ea344c341bf9bfaa7a4389335ae353 | 707,460 |
from typing import Any
from typing import cast
def parse_year(candidate: Any) -> int:
"""Parses the given candidate as a year literal. Raises a ValueError
when the candidate is not a valid year."""
if candidate is not None and not isinstance(candidate, int):
raise TypeError("Argument year is expec... | 337cc3be16e1e1246d1d1f02b55665c655fe131f | 707,461 |
def username_in_path(username, path_):
"""Checks if a username is contained in URL"""
if username in path_:
return True
return False | 131a8fa102fd0a0f036da81030b005f92ea9aab0 | 707,463 |
def str_parse_as_utf8(content) -> str:
"""Returns the provided content decoded as utf-8."""
return content.decode('utf-8') | 75b8d5f1f8867c50b08146cc3edc1d0ab630280a | 707,464 |
def remove_start(s: str) -> str:
"""
Clear string from start '-' symbol
:param s:
:return:
"""
return s[1:] if s.startswith('-') else s | 03504a3094798f6582bcae40233f7215e8d4d780 | 707,466 |
import os
def list_dirs(path):
"""遍历文件夹下的文件夹,并返回文件夹路径列表
:param path:
:return:
"""
if not os.path.exists(path):
os.mkdir(path)
_path_list = []
for lists in os.listdir(path):
sub_path = os.path.join(path, lists)
# 如果是文件夹
if os.path.isdir(sub_path):
... | b5a8e95e45adfbb1621762a9654aa237b0325d15 | 707,467 |
import os
import unittest
def get_tests():
"""Grab all of the tests to provide them to setup.py"""
start_dir = os.path.dirname(__file__)
return unittest.TestLoader().discover(start_dir, pattern='*.py') | 68733f14ec7427705698c36ae411caaaff1c0e02 | 707,468 |
def definition():
"""
Most recent student numbers and fees by set
(i.e. by year, costcentre and set category.),
aggregated by fee, aos code, seesion and fee_category.
"""
sql = """
select s.set_id, s.acad_year, s.costc,
s.set_cat_id,
fsc.description as set_cat_description,
f... | 18ded7340bf8786a531faf76c702e682bb44e0f3 | 707,469 |
def draw_adjacency_list():
"""Solution to exercise R-14.4.
Draw an adjacency list representation of the undirected graph shown in
Figure 14.1.
---------------------------------------------------------------------------
Solution:
-----------------------------------------------------------------... | 95c02ad974f2d964596cf770708ed11aa061ea49 | 707,470 |
def dict_to_one(dp_dict):
"""Input a dictionary, return a dictionary that all items are set to one.
Used for disable dropout, dropconnect layer and so on.
Parameters
----------
dp_dict : dictionary
The dictionary contains key and number, e.g. keeping probabilities.
Examples
------... | 9d18b027a0458ca6e769a932f00705a32edcb3e7 | 707,471 |
def Dc(z, unit, cosmo):
"""
Input:
z: redshift
unit: distance unit in kpc, Mpc, ...
cosmo: dicitonary of cosmology parameters
Output:
res: comoving distance in unit as defined by variable 'unit'
"""
res = cosmo.comoving_distance(z).to_value(unit) #*cosmo.h
return... | 02985b75bd24b2a18b07f7f3e158f3c6217fdf18 | 707,472 |
import subprocess
def check_conf(conf_filepath):
"""Wrap haproxy -c -f.
Args:
conf_filepath: Str, path to an haproxy configuration file.
Returns:
valid_config: Bool, true if configuration passed parsing.
"""
try:
subprocess.check_output(['haproxy', '-c', '-f', conf_filepa... | ceb2f78bcd4a688eb17c88915ebfde3f5a142e49 | 707,474 |
def get_genome_dir(infra_id, genver=None, annver=None, key=None):
"""Return the genome directory name from infra_id and optional arguments."""
dirname = f"{infra_id}"
if genver is not None:
dirname += f".gnm{genver}"
if annver is not None:
dirname += f".ann{annver}"
if key is not Non... | ab033772575ae30ae346f96aed840c48fb01c556 | 707,475 |
def uniq(string):
"""Removes duplicate words from a string (only the second duplicates).
The sequence of the words will not be changed.
"""
words = string.split()
return ' '.join(sorted(set(words), key=words.index)) | 2e5b6c51bc90f3a2bd7a4c3e845f7ae330390a76 | 707,478 |
def coo_index_to_data(index):
"""
Converts data index (row, col) to 1-based pixel-centerd (x,y) coordinates of the center ot the pixel
index: (int, int) or int
(row,col) index of the pixel in dtatabel or single row or col index
"""
return (index[1] + 1.0, index[0] + 1.0) | 5cf3ee2cc4ea234aaeb2d9de97e92b41c5daf149 | 707,480 |
def generateListPermutations(elements, level=0):
"""Generate all possible permutations of the list 'elements'."""
#print(" " * level, "gP(", elements, ")")
if len(elements) == 0:
return [[]]
permutations = []
for e in elements:
reduced = elements[:]
reduced.remove(e)
... | 1894b6726bedaaf634e8c7ac56fc1abd9e204eef | 707,481 |
import logging
import sys
def get_logger(base_name, file_name=None):
"""
get a logger that write logs to both stdout and a file. Default logging level is info so remember to
:param base_name:
:param file_name:
:param logging_level:
:return:
"""
if (file_name is None):
file_name... | 6ac5b8d78610179118605c6918998f9314a23ec4 | 707,482 |
def _split(num):
"""split the num to a list of every bits of it"""
# xxxx.xx => xxxxxx
num = num * 100
result = []
for i in range(16):
tmp = num // 10 ** i
if tmp == 0:
return result
result.append(tmp % 10)
return result | 575068b9b52fdff08522a75d8357db1d0ab86546 | 707,483 |
def clean_up_tokenization_spaces(out_string):
"""Converts an output string (de-BPE-ed) using de-tokenization algorithm from OpenAI GPT."""
out_string = out_string.replace('<unk>', '')
out_string = out_string.replace(' .', '.').replace(' ?', '?').replace(' !', '!').replace(' ,', ','
).replace(" '... | 0bd51ca7dbaa36569c0d2f18d510f1c6a92e1822 | 707,484 |
def _is_class(s):
"""Imports from a class/object like import DefaultJsonProtocol._"""
return s.startswith('import ') and len(s) > 7 and s[7].isupper() | deee946066b5b5fc548275dd2cce7ebc7023626d | 707,486 |
def longest_substring_using_lists(s: str) -> int:
"""
find the longest substring without repeating characters
644 ms 14.3 MB
>>> longest_substring_using_lists("abac")
3
>>> longest_substring_using_lists("abcabcbb")
3
>>> longest_substring_using_lists("bbbbb")
1
>>> longest_subst... | 4292af29c59ea6210cde28745f91f1e9573b7104 | 707,487 |
def pad_sents(sents, pad_token):
""" Pad list of sentences(SMILES) according to the longest sentence in the batch.
@param sents (list[list[str]]): list of SMILES, where each sentence
is represented as a list of tokens
@param pad_token (str): padding token
@returns sen... | 8f0eabfaaa18eafa84366a2f20ed2ddd633dacc6 | 707,488 |
import typing
def residual_block(
x,
filters: int,
weight_decay: float,
*,
strides: typing.Union[int, typing.Tuple[int, int]],
dilation: typing.Union[int, typing.Tuple[int, int]],
groups: int,
base_width: int,
downsample,
use_basic_block: bool,
use_cbam: bool,
cbam_chan... | f2021a89e2d737e73bfef3fb7dc127c3bbb5d0b7 | 707,489 |
def byte_list_to_nbit_le_list(data, bitwidth, pad=0x00):
"""! @brief Convert a list of bytes to a list of n-bit integers (little endian)
If the length of the data list is not a multiple of `bitwidth` // 8, then the pad value is used
for the additional required bytes.
@param data List of bytes.... | b92bbc28cc2ffd59ae9ca2e459842d7f4b284d18 | 707,490 |
import hashlib
def create_SHA_256_hash_of_file(file):
"""
Function that returns the SHA 256 hash of 'file'.\n
Logic taken from https://www.quickprogrammingtips.com/python/how-to-calculate-sha256-hash-of-a-file-in-python.html
"""
sha256_hash = hashlib.sha256()
with open(file, "rb") as f:
... | 14f62a49ea54f5fceb719c4df601fde165f5e55c | 707,491 |
def partition_average(partition):
"""Given a partition, calculates the expected number of words sharing the same hint"""
score = 0
total = 0
for hint in partition:
score += len(partition[hint])**2
total += len(partition[hint])
return score / total | 944f514e925a86f3be431bd4d56970d92d16f570 | 707,492 |
def passstore(config, name):
"""Get password file"""
return config.passroot / name | d0ca8c71650bd98dacd7d6ff9ed061aba3f2c43a | 707,493 |
def CheckTreeIsOpen(input_api, output_api, url, closed, url_text):
"""Similar to the one in presubmit_canned_checks except it shows an helpful
status text instead.
"""
assert(input_api.is_committing)
try:
connection = input_api.urllib2.urlopen(url)
status = connection.read()
connection.close()
... | 540dd0ceb9c305907b0439b678a6444ca24c3f76 | 707,494 |
def is_catalogue_link(link):
"""check whether the specified link points to a catalogue"""
return link['type'] == 'application/atom+xml' and 'rel' not in link | bc6e2e7f5c34f6ea198036cf1404fef8f7e7b214 | 707,495 |
from typing import Sequence
from typing import Set
async def get_non_existent_ids(collection, id_list: Sequence[str]) -> Set[str]:
"""
Return the IDs that are in `id_list`, but don't exist in the specified `collection`.
:param collection: the database collection to check
:param id_list: a list of doc... | b13c61f4528c36a9d78a3687ce84c39158399142 | 707,496 |
def _ParseProjectNameMatch(project_name):
"""Process the passed project name and determine the best representation.
Args:
project_name: a string with the project name matched in a regex
Returns:
A minimal representation of the project name, None if no valid content.
"""
if not project_name:
retu... | cb9f92a26c7157a5125fbdb5dd8badd7ffd23055 | 707,497 |
def explore_validation_time_gap_threshold_segments(participant_list, time_gap_list = [100, 200, 300, 400, 500, 1000, 2000], prune_length = None,
auto_partition_low_quality_segments = False):
"""Explores different threshiold values for the invalid time gaps in the Segments ... | bd88f292a00986212ae36e383c4bb4e3cd94067c | 707,498 |
def _get_lspci_name(line):
"""Reads and returns a 'name' from a line of `lspci` output."""
hush = line.split('[')
return '['.join(hush[0:-1]).strip() | 92910d0f4d9dce1689ed22a963932fb85d8e2677 | 707,499 |
def get_child_right_position(position: int) -> int:
"""
heap helper function get the position of the right child of the current node
>>> get_child_right_position(0)
2
"""
return (2 * position) + 2 | 2a5128a89ac35fe846d296d6b92c608e50b80a45 | 707,500 |
def get_label_parts(label):
"""returns the parts of an absolute label as a list"""
return label[2:].replace(":", "/").split("/") | 44998aad262f04fdb4da9e7d96d2a2b3afb27502 | 707,502 |
def split_range(r, n):
"""
Computes the indices of segments after splitting a range of r values
into n segments.
Parameters
----------
r : int
Size of the range vector.
n : int
The number of splits.
Returns
-------
segments : list
The list of lists of fi... | 34f570933a5eb8772dc4b2e80936887280ff47a4 | 707,504 |
def _fill_three_digit_hex_color_code(*, hex_color_code: str) -> str:
"""
Fill 3 digits hexadecimal color code until it becomes 6 digits.
Parameters
----------
hex_color_code : str
One digit hexadecimal color code (not including '#').
e.g., 'aaa', 'fff'
Returns
-------
f... | d91df947fcc5f0718bbd9b3b4f69f1ad68ebeff4 | 707,505 |
import ipaddress
def ipv4_addr_check():
"""Prompt user for IPv4 address, then validate. Re-prompt if invalid."""
while True:
try:
return ipaddress.IPv4Address(input('Enter valid IPv4 address: '))
except ValueError:
print('Bad value, try again.')
raise | e85681cdcedb605f47240b27e8e2bce077a39273 | 707,507 |
def namify(idx):
"""
Helper function that pads a given file number and return it as per the dataset image name format.
"""
len_data = 6 #Ilsvr images are in the form of 000000.JPEG
len_ = len(str(idx))
need = len_data - len_
assert len_data >= len_, "Error! Image idx being fetched is incorr... | 069ff7a297f944e9e0e51e5e100276a54fa51618 | 707,508 |
def mock_environ():
"""Mock for `os.environ.copy`"""
return {"SOME_ENV_VAR": "42"} | d68d44d793847f46354a8cf2503b654a40eed92a | 707,509 |
def get_bedtools_coverage_cmd(bam_filename, gff_filename,
output_filename,
require_paired=False):
"""
Get bedtools command for getting the number of reads
from the BAM filename that are strictly contained within
each interval of the GFF.
""... | e4d6da3e3e7fe611c3bc3023bea3a76a0003a1f2 | 707,510 |
def seek_inactive(x, start, length, direction=-1, abstol=0):
""" Seek inactive region to the left of start
Example
-------
>>> # _______ |
>>> seek_inactive([3, 2, 1, 1, 1, 2, 3, 4, 2], start=7, length=3)
(1, slice(2, 4))
When no sufficiently long sequence is fou... | a0029e0c145381b2acf57f77107d75d89c909b39 | 707,511 |
def get_duration_and_elevation(table):
""""Return an array of duration and elevation gain from an html table"""
try:
hiking_duration = str(table.contents[0].text.strip()) #av.note: want this to be numeric
except:
hiking_duration = ""
try:
elevation_gain_ft = str(
ta... | d52ca3c6e5d75ff936e44b452b05790db931dc6e | 707,512 |
import os
import time
import sys
def get_config():
"""Get config from env vars.
Return:
dict: Keys are: policy_url, dane_id, policy_file_dir, crypto_path,
policy_name, ssids.
"""
config = {}
for x in ["policy_url", "policy_file_dir", "dane_id",
"crypto_path", "p... | a2c69da96e2c8ac39230e6d1b277de8951a91abe | 707,513 |
import os
def unix_only(f):
"""Only execute on unix systems"""
f.__test__ = os.name == "posix"
return f | 8f20070e75e0277341985c3d528311779aff47d1 | 707,514 |
def chunks(list_, num_items):
"""break list_ into n-sized chunks..."""
results = []
for i in range(0, len(list_), num_items):
results.append(list_[i:i+num_items])
return results | 83da5c19c357cc996fc7585533303986bea83689 | 707,515 |
def form_requires_input(form):
"""
Returns True if the form has at least one question that requires input
"""
for question in form.get_questions([]):
if question["tag"] not in ("trigger", "label", "hidden"):
return True
return False | 97072a9edc494afa731312aebd1f23dc15bf9f47 | 707,516 |
def list_extract(items, arg):
"""Extract items from a list of containers
Uses Django template lookup rules: tries list index / dict key lookup first, then
tries to getattr. If the result is callable, calls with no arguments and uses the return
value..
Usage: {{ list_of_lists|list_extract:1 }} (get... | 23fb863a7032f37d029e8b8a86b883dbfb4d5e7b | 707,517 |
def row2dict(cursor, row):
""" タプル型の行データを辞書型に変換
@param cursor: カーソルオブジェクト
@param row: 行データ(tuple)
@return: 行データ(dict)
@see: http://docs.python.jp/3.3/library/sqlite3.html
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | 60e0ebed21c35a65784fe94fe5781f61fbe0c97d | 707,518 |
def merge(left, right):
"""this is used for merging two halves """
# print('inside Merge ')
result = [];
leftIndex = 0;
rightIndex = 0;
while leftIndex < len(left) and rightIndex < len(right):
if left[leftIndex] < right[rightIndex]:
result.append(left[leftIndex])
... | 5b0012e102d72a93cf3ce47f9600b7dcef758a3b | 707,519 |
import re
def parse_query(query):
"""Parse the given query, returning a tuple of strings list (include, exclude)."""
exclude = re.compile(r'(?<=-")[^"]+?(?=")|(?<=-)\w+').findall(query)
for w in sorted(exclude, key=lambda i: len(i), reverse=True):
query = query.replace(w, '')
query = " " + que... | 4fe6aac76935af6e5acaa3aedad40d6bc635d4ff | 707,520 |
import struct
def read_plain_byte_array(file_obj, count):
"""Read `count` byte arrays using the plain encoding."""
return [file_obj.read(struct.unpack(b"<i", file_obj.read(4))[0]) for i in range(count)] | f300d205fda9b1b92ebd505f676b1f76122f994d | 707,522 |
def big_number(int_in):
"""Converts a potentially big number into a lisible string.
Example:
- big_number(10000000) returns '10 000 000'.
"""
s = str(int_in)
position = len(s)
counter = 0
out = ''
while position != 0:
counter += 1
position -= 1
out = s[posit... | 7db0dce8ffa1cbea736537efbf2fdd4d8a87c20d | 707,523 |
def test_pandigital_9(*args):
"""
Test if args together contain the digits 1 through 9 uniquely
"""
digits = set()
digit_count = 0
for a in args:
while a > 0:
digits.add(a % 10)
digit_count += 1
a //= 10
return digit_count == 9 and len(digits) == ... | ad5a738400f7b8a9bea001a13a76798633b9ac61 | 707,525 |
def _get_all_scopes(blocks):
"""Get all block-local scopes from an IR.
"""
all_scopes = []
for label, block in blocks.items():
if not (block.scope in all_scopes):
all_scopes.append(block.scope)
return all_scopes | daa13a20629dd419d08c9c6026972f666c3f9291 | 707,526 |
from datetime import datetime
def get_equinox_type(date):
"""Returns a string representing the type of equinox based on what month
the equinox occurs on. It is assumed the date being passed has been
confirmed to be a equinox.
Keyword arguments:
date -- a YYYY-MM-DD string.
"""
month = da... | 06b65a54a0ccf681d9f9b57193f5e9d83578f0eb | 707,527 |
def get_tally_sort_key(code, status):
"""
Get a tally sort key
The sort key can be used to sort candidates and other tabulation
categories, for example the status and tally collections returned by
rcv.Tabulation().tabulate().
The sort codes will sort candidates before other tabulation
categories; electe... | bd7d643300997903b84b1827174dd1f5ac515156 | 707,528 |
import difflib
def getStringSimilarity(string1:str,string2:str):
"""
This function will return a similarity of two strings.
"""
return difflib.SequenceMatcher(None,string1,string2).quick_ratio() | 292f552449569206ee83ce862c2fb49f6063dc9e | 707,530 |
import torch
def flipud(tensor):
"""
Flips a given tensor along the first dimension (up to down)
Parameters
----------
tensor
a tensor at least two-dimensional
Returns
-------
Tensor
the flipped tensor
"""
return torch.flip(tensor, dims=[0]) | b0fd62172b0055d9539b554a8c967c058e46b397 | 707,531 |
def get_file_type(filepath):
"""Returns the extension of a given filepath or url."""
return filepath.split(".")[-1] | 070a1b22508eef7ff6e6778498ba764c1858cccb | 707,532 |
import os
def get_python_list(file_path):
"""
Find all the .py files in the directory and append them to a raw_files list.
:params:
file_path = the path to the folder where the to-be read folders are.
:returns:
raw_files : list of all files ending with '.py' in the read folder.
"""
py... | b771814b86c5405d5810694ad58b7a8fe80b1885 | 707,533 |
from typing import List
from typing import Pattern
import re
from typing import Optional
from typing import Match
def _target_js_variable_is_used(
*, var_name: str, exp_lines: List[str]) -> bool:
"""
Get a boolean value whether target variable is used in
js expression or not.
Parameters
-... | be07cb1628676717b2a02723ae7c01a7ba7364d6 | 707,537 |
def zip_equalize_lists(a, b):
"""
A zip implementation which will not stop when reaching the end of the
smallest list, but will append None's to the smaller list to fill the gap
"""
a = list(a)
b = list(b)
a_len = len(a)
b_len = len(b)
diff = abs(a_len - b_len)
if a_len < b_len:... | 1cf5b9cadf4b75f6dab6c42578583585ea7abdfc | 707,538 |
def find_period(samples_second):
""" # Find Period
Args:
samples_second (int): number of samples per second
Returns:
float: samples per period divided by samples per second
"""
samples_period = 4
return samples_period / samples_second | c4a53e1d16be9e0724275034459639183d01eeb3 | 707,539 |
def sqrt(x: int) -> int:
"""
Babylonian Square root implementation
"""
z = (x + 1) // 2
y = x
while z < y:
y = z
z = ( (x // z) + z) // 2
return y | 1a91d35e5783a4984f2aca5a9b2a164296803317 | 707,540 |
def is_consecutive_list(list_of_integers):
"""
# ========================================================================
IS CONSECUTIVE LIST
PURPOSE
-------
Reports if elments in a list increase in a consecutive order.
INPUT
-----
[[List]] [list_of_integers]
- A list ... | 3b165eb8d50cc9e0f3a13b6e4d47b7a8155736b9 | 707,541 |
def parent_id_name_and_quotes_for_table(sqltable):
""" Return tuple with 2 items (nameof_field_of_parent_id, Boolean)
True - if field data type id string and must be quoted), False if else """
id_name = None
quotes = False
for colname, sqlcol in sqltable.sql_columns.iteritems():
# root table... | 6f3319dc6ae0ea70af5d2c9eda90fb1a9fb9daac | 707,542 |
def clean_profit_data(profit_data):
"""清理权益全为0的垃圾结算日"""
for i in list(range(len(profit_data)))[::-1]:
profit = profit_data[i][1] == 0
closed = profit_data[i][2] == 0
hold = profit_data[i][3] == 0
if profit and closed and hold:
profit_data.pop(i)
return profit_dat... | d1b7fe9d747a1149f04747b1b3b1e6eba363c639 | 707,544 |
def mock_interface_settings_mismatch_protocol(mock_interface_settings, invalid_usb_device_protocol):
"""
Fixture that yields mock USB interface settings that is an unsupported device protocol.
"""
mock_interface_settings.getProtocol.return_value = invalid_usb_device_protocol
return mock_interface_se... | 61958439a2869d29532e50868efb39fe3da6c8b5 | 707,545 |
def MakeLocalSsds(messages, ssd_configs):
"""Constructs the repeated local_ssd message objects."""
if ssd_configs is None:
return []
local_ssds = []
disk_msg = (
messages.
AllocationSpecificSKUAllocationAllocatedInstancePropertiesAllocatedDisk)
interface_msg = disk_msg.InterfaceValueValuesEnu... | 128e7a0358221fe3d93da4726924a7a783c65796 | 707,547 |
import base64
def _b64urldec(input: str) -> bytes:
"""
Deocde data from base64 urlsafe with stripped padding (as specified in the JWS RFC7515).
"""
# The input is stripped of padding '='. These are redundant when decoding (only relevant
# for concatenated sequences of base64 encoded data) but the ... | fb535072b560b8565916ae8ec3f32c61c41115d8 | 707,548 |
import os
def is_morepath_template_auto_reload():
""" Returns True if auto reloading should be enabled. """
auto_reload = os.environ.get("MOREPATH_TEMPLATE_AUTO_RELOAD", "")
return auto_reload.lower() in {"1", "yes", "true", "on"} | 72839bf2ab0a70cefe4627e294777533d8b0087f | 707,549 |
def relabel_prometheus(job_config):
"""Get some prometheus configuration labels."""
relabel = {
'path': '__metrics_path__',
'scheme': '__scheme__',
}
labels = {
relabel[key]: value
for key, value in job_config.items()
if key in relabel.keys()
}
# parse _... | eb08f617903fe66f462a5922f8149fd8861556ad | 707,550 |
def checkGroup(self, group, colls):
"""
Args:
group:
colls:
Returns:
"""
cut = []
for elem in group:
if elem in colls:
cut.append(elem)
if len(cut) == len(group):
return cut
else:
return [] | ca30648c536bcf26a1438d908f93a5d3dcc131c9 | 707,551 |
import sys
def _replace_sysarg(match):
"""Return the substitution for the $<n> syntax, .e.g. $1 for the
first command line parameter.
"""
return sys.argv[int(match.group(1))] | efd338c537ecf2ef9113bc71d7970563ac9e5553 | 707,552 |
def decode(rdf, hint=[]):
"""Decode ReDIF document."""
def decode(encoding):
rslt = rdf.decode(encoding)
if rslt.lower().find("template-type") == -1:
raise RuntimeError("Decoding Error")
return rslt
encodings = hint + ["windows-1252", "utf-8", "utf-16", "latin-1"]
i... | f42eed2caaba90f4d22622643885b4d87b9df98b | 707,553 |
def text(el):
"""
Helper to get the text content of a BeautifulSoup item
"""
return el.get_text().strip() | 7b34c77c79677a73cc66532fe6305635b1bdac43 | 707,554 |
def get_sha512_manifest(zfile):
"""
Get MANIFEST.MF from a bar file.
:param zfile: Open (!!!) ZipFile instance.
:type zfile: zipfile.ZipFile
"""
names = zfile.namelist()
manifest = None
for name in names:
if name.endswith("MANIFEST.MF"):
manifest = name
b... | 7ef150bb3e89f8723649ee983085a413ec8a31df | 707,555 |
def part1(data):
"""
>>> part1(read_input())
0
"""
return data | 1482c41b112a3e74775e71c4aabbd588de2b6553 | 707,556 |
import torch
def get_rectanguloid_mask(y, fat=1):
"""Get a rectanguloid mask of the data"""
M = y.nonzero().max(0)[0].tolist()
m = y.nonzero().min(0)[0].tolist()
M = [min(M[i] + fat, y.shape[i] - 1) for i in range(3)]
m = [max(v - fat, 0) for v in m]
mask = torch.zeros_like(y)
mask[m[0] : ... | 0ff3ab25f2ab109eb533c7e4fafd724718dbb986 | 707,557 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.