content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def writedict():
""" return the dictionnary """
col = ["♠", "♥", "♦", "♣"]
d = {}
for i in range(0, 4):
for j in range(1, 15):
if j <= 10:
d[i*14+j] = col[i] + str(j)
else:
a = ""
if j == 11:
a = "V"
... | d572a71f2a7c05cc668b39c35713fbaf773a19d5 | 696,410 |
from typing import List
def get_connectors_with_release_stage(definitions_yaml: List, stages: List[str]) -> List[str]:
"""returns e.g: ['airbyte/source-salesforce', ...] when given 'generally_available' as input"""
return [definition["dockerRepository"] for definition in definitions_yaml if definition.get("re... | 804acfc7ef01909cc74493e4b102444afaa24f34 | 696,411 |
def likelihood(numSamples, target, numRequests=1): # This can return > 1.0
"""Returns a likelyhood of sampling the next request based on
"""
try:
currentRate= numSamples/float(numRequests)
# The 100 in the next line was found empiricially, and is needed to
# force the two rates to converge re... | bc15c7ae5741c7924a5dba91ea8f58d3493661e1 | 696,413 |
def get_lon_lat_dims(dataarray):
"""
Get the name of lon and lat corresponding to an dataarray (based on the dimensions of the dataarray).
"""
# get correct grid
dims = dataarray.dims
lon_name = 'lon_rho'
lat_name = 'lat_rho'
for dim in dims:
if dim.startswith('eta') or dim.startswith('lon'):
lon_name = di... | 1716feffea50a1963de1425e537ab7f39e0da0a8 | 696,415 |
import collections
def get_first_negative_floor(text):
"""Returns the position where # of ) > # of ("""
negative_floor = None
floor = 0
counter = collections.Counter('')
for char in text:
if char in '()':
floor += 1
counter.update(char)
if counter.get('... | fef5bef98e70a297a68759987e5e93d816a746d3 | 696,416 |
def rs_is_puiseux(p, x):
"""
Test if ``p`` is Puiseux series in ``x``.
Raise an exception if it has a negative power in ``x``.
Examples
========
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import rs_is_puiseux
>>> ... | a93ff5797d8e3b845099f9c8da2a5fd88c288ff6 | 696,417 |
def resultToString(result, white):
"""
The function returns if the game was won based on result and color of figures
Input:
result(str): result in format '1-0','1/2-1/2', '0-1'
white(bool): True if white, False if black
Output:
str: result of a game: 'won', 'lost', 'tie' or 'unknown'
""... | 9294ca5fc67c9f33d263b977bd35847cef2f56cc | 696,418 |
def list_of_depths(bst):
"""Create a linked list for every depth of the bst."""
previous_level = [bst.root]
current_level = [bst.root]
list_of_levels = [[bst.root.val]]
while current_level:
current_node = current_level.pop(0)
if previous_level:
if previous_level[-1] no... | 675d617ecd8a3e40f1d98e0e28389f425a695ee6 | 696,419 |
def read(r):
"""
读取redis数据
:param r: redis对象
:return:
keys:返回需要处理的数据
"""
result = r.hgetall('xhs')
keys = []
for each in result.keys():
if result[each] == b'':
keys.append(each.decode('utf-8'))
return keys | 56d198efbb57e098ea8e4a8bdc4b7695c0715867 | 696,420 |
def get_next_page(response, previous_page_params):
"""
See specification at:
https://digital.nhs.uk/services/data-security-centre/cyber-alerts-api/get-cyber-alerts
"""
next_page = response["currentPage"] + 1
if next_page > response["totalPages"]:
return {}
return {
"page": ne... | 72f35cbec47d0e7fe14854b549f52382721bdd06 | 696,421 |
def check_uniprot(alias):
"""
Return True if the protein has UniProt identifier
"""
return len(alias) == 1 or alias.split(':')[0] == 'uniprotkb' | 90fab83a02595ea5808ae8b9dcbec1993eb81404 | 696,422 |
import torch
def label_smoothing(true_labels: torch.Tensor, classes: int, smoothing=0.1):
"""
if smoothing == 0, it's one-hot method
if 0 < smoothing < 1, it's smooth method
"""
assert 0 <= smoothing < 1
confidence = 1.0 - smoothing
label_shape = torch.Size((true_labels.size(0), classes))
... | 837a7cb5167db9d65dab25b25737e43753fb7693 | 696,423 |
def to_c_string(text):
"""
Make 'text' agreeable as C/C++ string literal
:return: str
"""
text = text.replace("\\", "\\\\")
text = text.replace("\n", "\\n")
text = text.replace("\r", "")
text = text.replace('"', '\\"')
return text | 7081d03d4be30cee135d52393cef481329232050 | 696,424 |
def is_flush(suits):
"""Return True if hand is a flush.
Compare if card suit values are all equal.
"""
return suits[0] == suits[1] == suits[2] == suits[3] == suits[4] | 33b7ef74af5856d87d81ad53513a0ab448de7de9 | 696,425 |
import os
def validate_path(current_dir: str, folder: str = '') -> bool:
"""
Validates file directories
@params:
current_dir - Required : current directory path (Str)
folder - Optional : folder path (Str)
"""
if current_dir and folder:
return bool(os.path.exists(cu... | 94c080370c81a96ec8221038c1f71f56f7fa8553 | 696,426 |
def date_str(year, month, day, hour=0, minute=0, second=0., microsecond=None):
"""
Creates an ISO 8601 string.
"""
# Get microsecond if not provided
if microsecond is None:
if type(second) is float:
microsecond = int((second - int(second)) * 1000000)
else:
mic... | a08bc5aee24f500ff3b4f18ba3bee6d808374136 | 696,429 |
import re
import sys
def parse_tasks_str(task_str, dataset_names, interpolate_coordinates):
""" Parser for task string. '+' will split the string and will parse each part for a dataset. It will return a list
with dictionaries. The length of the list is equal to the number of datasets in the multidataset trai... | a91710b6bb65a9dce3ff3c162358d5dae5fa0bf3 | 696,430 |
def confirm_action(desc='Really execute?') -> bool:
"""
Return True if user confirms with 'Y' input
"""
inp = ''
while inp.lower() not in ['y', 'n']:
inp = input(desc + ' Y/N: ')
return inp == 'y' | 4dd485e76e36c579b16c91d57edbde18ba52d3db | 696,431 |
import re
def clean_sentence(sentence, disambiguations):
"""
Clean a sentence from some useless stuff (brackets, quotation marks etc.)
:param sentence: a list of tokens (string), representing a sentence.
:param disambiguations: a list of Disambiguation objects, wrt each word in the sentence.
:return: the same pa... | acb31ebcc662abba39cdfa8b3dd22a08ae3e347d | 696,433 |
def remove(text, removeValue):
"""
Return a string where all remove value are removed from the text.
"""
return text.replace(removeValue, '') | cfc7f5f5ab212bea6e02423fd0fb1fc2947be7a2 | 696,434 |
def clean_tweet(x):
"""
Cleans a tweet by removing unnecessary material
"""
# things we want to do:
# - remove links
# - remove @users
# - remove RT :
# - remove [CLS] (we add it anyway)
tokens = x.split(' ')
result = []
i = 1
while i < len(tokens) - 1: # ignore... | f0c5ee9311637ba1fbce25340640505baeba937d | 696,435 |
def _tuple_replace(s, Lindices, Lreplace):
"""
Replace slices of a string with new substrings.
Given a list of slice tuples in C{Lindices}, replace each slice
in C{s} with the corresponding replacement substring from
C{Lreplace}.
Example:
>>> _tuple_replace('0123456789',[(4,5),(6,9)],['a... | 2942023bac0ac81031f9c17ac421d13b872466d4 | 696,436 |
def get_node(conn, name):
"""
Return a node for the named VM
"""
for node in conn.list_servers(per_page=1000):
if node["name"] == name:
return node | d43988ef6a55d58eae1957d219e846e3d4e36227 | 696,437 |
import torch
def logsumexp(pred, keepdim=True, verbose=False):
"""
compute <logsumexp(y)>
"""
lse = torch.logsumexp(pred.mean, dim=-1, keepdim=keepdim) # [b, 1]
if verbose:
print(lse.mean().item())
p = torch.exp(pred.mean - lse) # softmax # [b, y]
di... | 893b910e27de27ae4aace51e8d70fe8b6066653b | 696,438 |
from datetime import datetime
def timestamp_seconds() -> str:
"""
Return a timestamp in 15-char string format: {YYYYMMDD}'T'{HHMMSS}
"""
now = str(datetime.now().isoformat(sep="T", timespec="seconds"))
ts: str = ""
for i in now:
if i not in (" ", "-", ":"):
ts += i
retu... | d4c03925949795e6f9993cc4a79cb088619e0527 | 696,439 |
import gzip
import bz2
import lzma
import io
def open_cnf_file(filename, mode):
"""
Opens a CNF file (this is badly guarded, by file-extension only)
"""
obj = None
if filename.endswith('.cnf.gz'):
obj = gzip.open(filename, mode)
elif filename.endswith('.cnf.bz2'):
obj = bz2.ope... | e5c431cbc1f2711a4e1cbd21bf1771452b2b2fce | 696,440 |
def count_spaces(docstring):
"""
Hacky function to figure out the minimum indentation
level of a docstring.
"""
lines = docstring.split("\n")
for line in lines:
if line.startswith(" "):
for t in range(len(line)):
if line[t] != " ":
return ... | a6b102cc7ccebcfba7047c284d9db6ede3389a15 | 696,441 |
def AAPIExitVehicle(idveh, idsection):
""" called when a vehicle reaches its destination """
return 0 | 503370ec9376a04d38e43af8f017105ec7b93ac9 | 696,442 |
def get_files_priorities(torrent_data):
"""Returns a dictionary with files priorities, where
filepaths are keys, and priority identifiers are values."""
files = {}
walk_counter = 0
for a_file in torrent_data['files']:
files[a_file['path']] = torrent_data['file_priorities'][walk_counter]
... | c142f73ef1087cee72bbca317e3ea07ebcc5bf8c | 696,443 |
def _make_update_dict(update):
"""
Return course update item as a dictionary with required keys ('id', "date" and "content").
"""
return {
"id": update["id"],
"date": update["date"],
"content": update["content"],
} | f20efac269ad67b9f46f4994bf61e2397fb91d98 | 696,444 |
def is_resource(url):
"""
:param url: url to check;
:return: return boolean;
This function checks if a url is a downloadable resource. This is defined by the list of resources;
"""
if url:
resources = ['mod/resource', 'mod/assign', 'pluginfile']
for resource in resource... | 39496ff5bb170746645d40d954a96c76b4c36a87 | 696,446 |
import re
def group_lines(lines, delimiter):
"""
Group a list of lines into sub-lists. The list is split at line matching the
`delimiter` pattern.
:param lines: Lines of string.
:parma delimiter: Regex matching the delimiting line pattern.
:returns: A list of lists.
"""
if not lines:... | f77e643aa711b160dda97acf35c8be1cec7d703a | 696,447 |
def rows_with_missing_squares(squares):
"""This searches for the squares with 0 value and returns the list of corresponding rows.
"""
rows = []
for i, square in enumerate(squares):
if 0 in square:
rows.append(i)
return list(set(rows)) | 408ec98c14b000d91607cfc8b6939b50be931118 | 696,448 |
import os
def is_ec2_linux():
"""Detect if we are running on an EC2 Linux Instance
See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html
"""
if os.path.isfile("/sys/hypervisor/uuid"):
with open("/sys/hypervisor/uuid") as f:
uuid = f.read()
... | e9e01ccb59197839f453ca6dd3b56ddb085d046f | 696,449 |
def _build_params(dt):
"""Takes a date and builds the parameters needed to scrape the dgm website.
:param dt: the `datetime` object
:returns: the `params` that contain the needed api information
"""
params = (('yr', dt.year),
('month', dt.month),
('dy', dt.day),
... | 477f763d81407f047ada9d4d16c0207ed0b5ad67 | 696,450 |
def clear_item_intent_handler(handler_input):
"""
Handler for YesIntent when clear item.
"""
speech_text = ""
reprompt = ""
# 多言語応答データを取得
lang = handler_input.attributes_manager.request_attributes["_"]
# セッションアトリビュートから対象の品目,日時を指定
s_attrs = handler_input.attributes_manager.s... | b454f1b646bd8696d34610ce0d9dfa3d4e2eaf85 | 696,451 |
def _round_to_multiple_of(val: float, divisor: int, round_up_bias: float = 0.9) -> int:
""" Asymmetric rounding to make `val` divisible by `divisor`. With default
bias, will round up, unless the number is no more than 10% greater than the
smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88. """
... | fdc644b8d4bd5d3fdf49c5d9892eaf67640fb61b | 696,452 |
import random
def add_extra_particles(beads, protons, atom, particle_list, random_vecs, prot_name):
"""
Select a random vector and add each necessary particle to either the protons or
beads object.
Parameters
----------
beads : Particles object
protons : Particles object
atom : MDAn... | caed038bf602a1632455d5e4c14cad03c77568ac | 696,453 |
import random
def random_choice(array, probs=None):
"""
This function takes in an array of values to make a choice from,
and an pdf corresponding to those values. It returns a random choice
from that array, using the probs as weights.
"""
# If no pdf provided, assume uniform dist:
if probs == None:
index = i... | 2fc692773b50d7b940f72bf4deebede6ffd063f0 | 696,454 |
def parse_requirements(r):
"""Determine which characters are required and the number of them that
are required."""
req = {'d': 0, 'l': 0, 'u': 0, 's': 0}
for c in r:
if c == 'd':
req['d'] += 1
elif c == 'l':
req['l'] += 1
elif c == 'u':
re... | 8c1f82a7136aec08471e672e4b676d725854f2d6 | 696,455 |
def peek(file, length=1):
"""Helper function for reading *length* bytes from *file* without advancing
the current position."""
pos = file.tell()
data = file.read(length)
file.seek(pos)
return data | fe901c4001320c9498b09a1d7caa6b4598a0386a | 696,456 |
def sub_account_universal_transfer_history(self, **kwargs):
"""Query Universal Transfer History (For Master Account)
GET /sapi/v1/sub-account/universalTransfer
https://binance-docs.github.io/apidocs/spot/en/#query-universal-transfer-history-for-master-account
fromEmail and toEmail cannot be sent at t... | c552c4eeea8be9eeb0a662cbaa546085d7c5999a | 696,457 |
def computeTauPerTstep(epsilon, mindt=0.000001):
"""Read in epsilon, output tauBrownian per timestep"""
kBT = 1.0
tstepPerTau = float(epsilon / (kBT * mindt))
return 1. / tstepPerTau | f495b5358e1fd102075d8d47d1f838b9a83e8c3c | 696,458 |
def replace_del_alt(var):
"""
Issues occur with deletions hear the ends of the genome.
Currently - is used to represent an entire string of bases
being deleted. Here we replace the ALT with "N" the length
of REF.
"""
ref_length = len(var.REF)
if var.ALT[0] == '-':
fixed_alt ... | f3d081a8dd12b8ca81bd8d5a8aca6bf6dbccc839 | 696,459 |
import spwd
import crypt
def check_pw(user, password):
"""Check the password matches local unix password on file"""
try:
hashed_pw = spwd.getspnam(user)[1]
except:
return False
return crypt.crypt(password, hashed_pw) == hashed_pw | 8bfc5ac9bfef4e44c9b11bef694cb675888868a7 | 696,460 |
def get_tokenizer_result(blob):
"""
get the tokenizer results
:param blob:
:return:
"""
return list(blob.words) | 4c9d5ca975d0f670ca7fa55fd626650ca624e685 | 696,461 |
def pop_comments_gte(reply_stack, level_lte=0):
"""
Helper filter used to list comments in the <comments/list.html> template.
"""
comments_lte = []
try:
for index in range(len(reply_stack) - 1, -1, -1):
if reply_stack[index].level < level_lte:
break
co... | 7c78afa100519794badaa1d0464b9f7796824f3c | 696,462 |
def pad(value: int, length: int = 2) -> str:
"""
Adds leading and trailing zeros to value ("pads" the value).
>>> pad(5)
05
>>> pad(9, 3)
009
:param value: integer value to pad
:param length: Length to pad to
:return: string of padded value"""
return "{0:0>{width}}".format(valu... | 0ac5c5cebf3cc97f25d0e21fdef9c45f06ce635d | 696,463 |
import json
def CompilePatternsV2(pattern_json_path):
"""Converts the pattern json to ranked pattern list.
Args:
pattern_json_path: str, Path of the json file containing the patterns.
"""
keys = ['c', 'g', 'i', 'o', 's', 'u']
key_strings = []
print("Generating patterns v2...")
with open(pattern_jso... | 221a8c22203c59f1e12f86b3f8a4e52137a3d111 | 696,464 |
import os
def setup_reg_paths(paths: dict, settings: dict) -> tuple[dict, dict]:
"""
This function sets up the appropriate paths for the
MRI coregistration module. It gets run even if the module
is skipped to ensure all paths are properly stored.
"""
# Define appropriate directory
mr_regi... | f6290754807ab8ab50f7479b8abcadd3ad8b8619 | 696,465 |
import os
def fileExist(file):
"""
Checks if a file exists AND is a file
"""
return os.path.exists(file) and os.path.isfile(file) | bfb6ea70da0b1d4cca87141544fbf804d3e98a07 | 696,466 |
from typing import List
import csv
def create_list_of_selected_jc() -> List:
"""
Return the "SelectedJournalsAndConferences.csv" as a list
"""
selected_jc = []
with open("SelectedJournalsAndConferences.csv", mode="r") as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in cs... | abe0f023ba77a4c8d22d6132ee029b104ceb8466 | 696,467 |
def lower_first_letter(sentence):
"""Lowercase the first letter of a sentence."""
return sentence[:1].lower() + sentence[1:] if sentence else "" | de0f79548d42983093f65970464ca84eed032300 | 696,468 |
def prefix_hash(s, p, P=53):
"""
Compute hashes for every prefix. Only [a-zA-Z] symbols are supported
Parameters
-------------
s : str
input string
p : List[int]
all powers of P. p[i] = P ** i
Returns
----------
h : List[int]
h[i] = hash(s[:i + 1])
"""
... | c9d7d4054c580257fab9336fa7881af3c9c074f4 | 696,469 |
def 최대공약수(a, b):
"""
최대공약수를 반환하는 함수입니다.
>>> 최대공약수(18,30)
6
>>> 최대공약수(1.3, 19)
Traceback (most recent call last):
...
ValueError: params should be an integer
"""
return 0 | 4be50f7fcb1e27f1bf4cc041f45a387a103d67cf | 696,470 |
def _IsPositional(arg):
"""Returns True if arg is a positional or group that contains a positional."""
if arg.is_hidden:
return False
if arg.is_positional:
return True
if arg.is_group:
for a in arg.arguments:
if _IsPositional(a):
return True
return False | 34147b29533ba9a535ba363c264625222763fb72 | 696,471 |
import socket
def publisher_udp_main(json_file_data):
"""
The following two lines show what is json_file_data
json_file = open('mocap_config.json')
json_file_data = json.load(json_file)
"""
# IP for publisher
HOST_UDP = json_file_data['HOST_UDP']
# Port for publisher
PORT... | 518d3636cf9641892734b0cefa13166346beff51 | 696,472 |
import re
def extract_metadata_string(str):
"""Extract the metadata contents from a string, from any file format"""
meta_pat_01 = '^META01;name="(.*?)(?<!\\\\)";(.*)$'
extractor = re.compile(meta_pat_01, flags=re.DOTALL)
res = extractor.match(str)
if res is None:
return None
filenam... | f92b039914dd4a7f1d8a6806121f88c9bfc11a78 | 696,473 |
def is_potential(obj):
"""Identifies if an object is a potential-form or potential-function"""
return hasattr(obj, "is_potential") and obj.is_potential | e84ad5fb59b8a6575eab6821e1b4bcedc1ddb0ab | 696,474 |
def get_default_value(key):
""" Gives default values according to the given key """
default_values = {
"coordinates": 2,
"obabel_path": "obabel",
"obminimize_path": "obminimize",
"criteria": 1e-6,
"method": "cg",
"hydrogens": False,
"steps": 2500,
"cutoff": False,
"rvdw": 6.0,
"rele": ... | 89a12cbb20499a85fc7c6c092fc2ee90aff31ae3 | 696,475 |
def find_longest_common_substring(x: str, y: str) -> str:
"""
Finds the longest common substring between the given two strings in a
bottom-up way.
:param x: str
:param y: str
:return: str
"""
# Check whether the input strings are None or empty
if not x or not y:
return ''
... | 878f41ead963a8171ec7d07509a8dae5aef7fb4b | 696,476 |
def replace_with_prev_invalid(eye_x, eye_y, pupil_diameter, eye_valid):
"""
A Function to remove invalid eye data, careful there is no machanism to synchronise left and right eye afterwards
:param eye_x: an indexable datastructure with the x eye coordinates
:param eye_y: an indexabl... | 1dcb0936a0c8d443aed24cd0451e048ef216fc91 | 696,477 |
def model_includes_pretrained(model):
"""
Checks if a model-class includes the methods to load pretrained models.
Arguments:
model Model-class to check.
Returns:
True if it includes the functionality.
"""
return hasattr(model, "has_pretrained_state_dict") and hasattr(
m... | f19460c4a0ce731d4642ad7092f80910605278a8 | 696,478 |
def _get_other_dims(ds, dim):
"""Return all dimensions other than the given dimension."""
all_dims = list(ds.dims)
return [d for d in all_dims if d != dim] | 4c8fc614442cbf4ee1a22aa8113532dcd2905e3c | 696,479 |
import argparse
def get_user_args_group(parser):
"""
Return the user group arguments for any command.
User group arguments are composed of the user script and the user args
"""
usergroup = parser.add_argument_group(
"User script related arguments",
description="These arguments dete... | 6940a076712734c3be3974c5ee7ce99dbb0d11e8 | 696,480 |
def stag_pressure_ratio(M, gamma):
"""Stagnation pressure / static pressure ratio.
Arguments:
M (scalar): Mach number [units: dimensionless].
gamma (scalar): Heat capacity ratio [units: dimensionless].
Returns:
scalar: the stagnation pressure ratio :math:`p_0 / p` [units: dimension... | 351b14716077386eadea04a4717ea9afec8fdcaf | 696,481 |
def split_target_decoys(df_psms, frac=1, random_state=42):
"""
Shuffle and return TTs only.
Parameters
----------
df_psms : TYPE
DESCRIPTION.
frac : TYPE, optional
DESCRIPTION. The default is 1.
random_state : TYPE, optional
DESCRIPTION. The default is 42.
Retur... | b115847995b8c1a4990887db86a21b4ba19fb71c | 696,482 |
def str_to_bool(possible_bool):
"""
Attempts to coerce various strings to bool.
Fails to None
"""
if possible_bool:
if possible_bool.lower() in ['t', '1', 'yes', 'true']:
return True
if possible_bool.lower() in ['f', '0', 'no', 'false']:
return False
ret... | b1011db09b948bd22c77f844d1e045e253d377ec | 696,483 |
import torch
def shift_v(im, shift_amount):
"""Shift the image vertically by shift_amount pixels,
use positive number to shift the image down,
use negative numbers to shift the image up"""
im = torch.tensor(im)
if shift_amount == 0:
return im
else:
if len(im.shape) == 3: # fo... | cbd0eab7b3a0a64e7402e5eb14d0464ab7ba9ac5 | 696,484 |
import os
def get_version():
"""
Return the lcinvestor version number
"""
this_path = os.path.dirname(os.path.realpath(__file__))
version_file = os.path.join(this_path, 'VERSION')
return open(version_file).read().strip() | 5e3331ba167c3e86f3d38c8b81dbbf9d10e263e8 | 696,485 |
def compose(last, *fn):
"""Compose functions."""
fn = (last,) + fn
def composed(*args):
for f in reversed(fn):
args = (f(*args), )
return args[0]
return composed | 949448c1ccb101ab706a85b4efb276dedf83d549 | 696,486 |
def getPath(parent_map, start, goal):
"""
Definition
---
Method to generate path using backtracking
Parameters
---
parent_map : dict of nodes mapped to parent node_cost
start : starting node
goal : goal node
Returns
---
path: list of all the points from starting to goal... | 8a23ab5462b064744973f75c294e0814099961c7 | 696,489 |
def arrRotation(x: list,d: int):
"""
The given function is first is first appending the elements to another array
till which the index is given, then removing those element from the given array
then appending the elements of the another array to the given array.
"""
arr = []
for i in range(0... | b99e4e50931c61ed94be712c1b8881caf559bdcd | 696,490 |
from typing import List
def input_assert(message: str, choices: List[str]) -> str:
"""
Adds functionality to the python function `input` to limit the choices that can be returned
Args:
message: message to user
choices: list containing possible choices that can be returned
Returns:
... | 062b88356a977cdd119f7ee0c54b7e6a611f76f2 | 696,491 |
import bisect
def get_closest_model_from_pride_of_models(pride_of_models_dict,
time_point):
"""
returns the RegistrationTargets from the "closest" initial model in the
pride_of_models_dict. If the exact time point is not present in the
pride_of_models_dict, a... | 4f39b0e535486bad1d9fdabfa993728c8f59be07 | 696,492 |
def rate(hit, num):
"""Return the fraction of `hit`/`num`."""
return hit / (num or 1.0) | b055fa6995f85ab223747dd369a464644046f7d7 | 696,493 |
import os
def get_file_size(file_name: str, human_readable: bool = True):
"""
Get file in size in given unit like KB, MB or GB
:param file_name:
:param human_readable:
:return:
"""
size = os.path.getsize(file_name)
if human_readable is False:
return size
elif size > (1024*... | f78225cb4ac99a5f277642a7c5368b451064be4d | 696,494 |
import os
def compute_relative_path(d1, d2):
"""
Compute relative path from directory d1 to directory d2.
"""
assert os.path.isabs(d1)
assert os.path.isabs(d2)
d1 = os.path.normpath(d1)
d2 = os.path.normpath(d2)
list1 = d1.split( os.sep )
list2 = d2.split( os.sep )
while Tru... | 668addf4dc8ed97c037d73b180e34fd09459e40c | 696,495 |
def get_function_handle(method, var):
"""
Return a function handle to a given calculation method.
Parameters
----------
method : str
Identifier of the calculation method to return a handle to.
var : dict
Local variables needed in the threshold method.
Returns
-------
... | 1e8dacfeaaa32a93fbfaad8507c976c4f2e126fb | 696,496 |
import os
def options(opts=None):
""" return options as dict from env vars """
if opts is None:
opts = {}
def _opt(optkey, key, default):
if optkey not in opts:
opts[optkey] = os.environ.get(key, default)
_opt('pg-host', 'POSTGRES_HOST', '127.0.0.1')
_opt('pg-usernam... | dd91e3cd094e4e91f5169ccdda4812dc7c660f9c | 696,497 |
def is_iterable(var):
""" Return True if the given is list or tuple.
"""
return (isinstance(var, (list, tuple)) or
issubclass(var.__class__, (list, tuple))) | f4c1d60d2e62688aedb776fb90d90049d93ad5e2 | 696,498 |
from unittest.mock import Mock
def patch_mock_conn():
"""
A mock for simulating a patching session where the table:
- Starts and ends with 100 rows
- Has 50 unchanged rows
- Has 15 deleted rows, 15 inserted rows, and 35 updated rows.
"""
mock = Mock()
mock.sql_queries = []
def ex... | c3dbb85667ac671debdffe5581a2f33d70e5a4df | 696,499 |
from datetime import datetime
def _python_type_to_charts_type(type_value):
"""Convert bigquery type to charts type."""
if type_value == int or type_value == float or type_value == float:
return "number"
if type_value == datetime.date:
return "date"
return "string" | a30f821e2c83914d1a933418305b37e15dd640db | 696,501 |
def fill():
"""Fill empty space."""
return "{0:~^10}! or {0:010}".format(-666) | 601ff943bf2423da7474202d31ad08b1bb02432f | 696,502 |
def relperm_parts_in_model(model,
phase_combo = None,
low_sal = None,
table_index = None,
title = None,
related_uuid = None):
"""Returns list of part names within model that are rep... | 7d4d5d8ac7a2c763f3a0fe2589d6ff0713d0125b | 696,503 |
def paired_xml_documents(request):
"""Pair input and expected XML documents."""
document = request.param
return document | af56f2d9cc5deab0c9f114976fa00e9b35d61ab0 | 696,504 |
from typing import List
import struct
def pack_float(data: List[float]):
"""
打包单精度浮点数
"""
return struct.pack(f"{len(data)}f", *data) | 594c7b39ba25e4ed2254528382c7c00993abb366 | 696,505 |
def tagged_members(obj, meta=None, meta_value=None):
""" Utility function to retrieve tagged members from an object
Parameters
----------
obj : Atom
Object from which the tagged members should be retrieved.
meta : str, optional
The tag to look for, only member which has this tag wi... | 7b1077e774a98bd59b6cb9a59c9745fbfa0b4168 | 696,506 |
def getMatrixMinor(m,i,j):
"""
returns minors of a mtrix
"""
return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])] | 32925adb6b1b0fb751a57d6f10cbdfaf1fd626a9 | 696,508 |
def and_operator(x: bool, y: bool) -> float:
"""
Poses the AND operator as an optimization problem.
Useful only for testing that the genetic algorithm
doesn't choke on a discrete function.
"""
return 1.0 if x and y else 0.0 | 950412ec8dd50385f5d7389e1454f34cdef4f704 | 696,509 |
def loadTick(self, days):
"""载入Tick"""
return [] | 44e82c5f6c81548d90c0eeb6cb57a7e5da2268e7 | 696,510 |
def unauthenticated_userid(request):
"""
A function that returns the value of the property
:attr:`pyramid.request.Request.unauthenticated_userid`.
.. deprecated:: 1.5
Use :attr:`pyramid.request.Request.unauthenticated_userid` instead.
"""
return request.unauthenticated_user... | b6394ba84f15e4934aafadacfe16ab52867d6077 | 696,511 |
import os
def LEM(model, script='scripts/LEM.tao'):
"""
Sets Linac fudge factors.
"""
path = model.path
verbose=model.verbose
epics = model.epics
cmd = 'call '+os.path.join(path, script)
model.vprint(cmd)
res = model.cmd(cmd)
return res | aa3967236746f60a76537360034b5d4439a02938 | 696,512 |
import math
def ReactiveCFinder(PDBfilename):
""" Take a PDB file and store the reactive C on a dictionary
RETURNS
-------
Results : dict
dictionary of ester C, which are the reactive ones
"""
def ComputeDistance(atom1,atom2):
"""Computes the module or distance between ... | b9ba59ffcceda8f40ec71d4c3abd5e4bddcf2148 | 696,513 |
import os
def is_exist(_path) -> bool:
"""Return True if file exists, otherwise False."""
if os.path.exists(_path): # in os.listdir(_path):
return True
else:
return False | bdd98b0a62667001326eab5dfc60f10d3b8bc44c | 696,514 |
def remove_irrelevant_labels(labels):
"""
Filters an array of labels, removing non "CAT" labels
:param labels: array of labels
:return: an array of labels containing only the top-level "CAT" labels
"""
filtered = filter(lambda x: "CAT" in x.upper(), labels)
return list(filtered) | bedeaa6b2dd1adfcef2eb7f1d4c7b34d9e7254f8 | 696,515 |
def lookup_ec2_to_cluster(session):
"""
Takes a session argument and will return a map of instanceid to clusterarn
:param session: boto 3 session for the account to query
:return: map of ec2 instance id to cluster arn
"""
ecs = session.client('ecs')
result = dict()
for cluster in ecs.lis... | 0b148264397e5e598675dfdcd6ac4528888ce107 | 696,517 |
from typing import Reversible
def remove_list_redundancies(lst: Reversible) -> list:
"""Used instead of ``list(set(l))`` to maintain order.
Keeps the last occurrence of each element.
"""
reversed_result = []
used = set()
for x in reversed(lst):
if x not in used:
reversed_re... | 5d14f88f809ecb8a4313591b99f212c78f897dd1 | 696,518 |
def floyd_warshall(graph):
"""Find pairwise shortest paths in weighted directed graph.
Args:
graph: n x n table of distances between nodes (0 for main diagonal, -1 if no connection).
Returns:
table with pairwise shortest distances between nodes.
"""
dist = [[999999 for x in range(l... | a24095d3137e232fee77f33661177def4e44a22a | 696,520 |
def padded_hex(num, n=2):
"""
Convert a number to a #xx hex string (zero padded to n digits)
"""
return ("%x" % num).zfill(n) | 2a9e401a824cdb856d29591ae282bdbbc64b79e5 | 696,522 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.