content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def isuuid5(value):
"""
Return whether or not given value is a UUID version 5.
If the value is a UUID version 5, this function returns ``True``, otherwise ``False``.
Examples::
>>> isuuid5('987FBC97-4BED-5078-AF07-9141BA07C9F3')
True
>>> isuuid5('9c858901-8a57-4791... | 1e281cc2451033f8c241320f7033512816b7e74a | 670,587 |
def get_batchid_from_job(job_ads_dict):
"""
Get batchID string from condor job dict
"""
batchid = '{0}.{1}'.format(job_ads_dict['ClusterId'], job_ads_dict['ProcId'])
return batchid | fe7fd25830d9b0e5f6e963958fc3f883a9c745de | 670,588 |
import random
def random_name() -> str:
"""Generate a random account name."""
return "temp" + str(random.randint(100000, 999999)) | 3a54c44bdaf2c8fa99674c727462848a5ac9b24e | 670,590 |
def calcul_jxy(ne, k):
"""Calculer j,x,y les attributs individus de la variable k"""
y = (k - 1) % ne
x = ((k-1-y) // ne) % ne
j = (k - 1 - y - x*ne) // (ne**2)
return j, x, y | c14d3cf24cbf38b4076943ac5ac65c2488fc69f2 | 670,591 |
def sort_by_tc(events):
"""Sorts events by their rec_start_tc."""
events.sort(key=lambda e: (e.rec_start_tc.frames, e.track))
return events | 940a3700ffbd389152dd784f6580f0da970eda18 | 670,592 |
import numpy
def log2RelativeMassLimit(relativeMassLimit):
"""Converts a relative mass limit to a corresponding value, which can be
used as an absolute limit for log2 transformed mass values.
:param relativeMassLimit: float, for example the commonly used value 10ppm
(10*1e-6)
:returns: numpy... | d276bd67ca354d18eaff79c5e610043881c93a23 | 670,593 |
def _create_ha_id(name, channel, param, count):
"""Generate a unique entity id."""
# HMDevice is a simple device
if count == 1 and param is None:
return name
# Has multiple elements/channels
if count > 1 and param is None:
return "{} {}".format(name, channel)
# With multiple pa... | 97ea3beb0a3e3e7f2fb02c3a7eafc1ba8c1b19b2 | 670,594 |
from pathlib import Path
def get_immediate_directories(directory_path):
"""Gets the immediate sub-directories within a directory
Args:
directory_path (str): path to the directory
Returns:
list(str): list of sub-directories
"""
p = Path(directory_path)
return [f for f in p.ite... | 8aabf6279367733bc6b25aec2cf69fb2e8f1c0a0 | 670,595 |
def all_equal(s):
"""Return whether all elements in a list are equal."""
return len(set(s)) <= 1 | a13d0e7bed1f2051337184a6c77d57ac5c8ece23 | 670,596 |
def write_updates_to_tas(tensor_arrays, t, tensor_updates):
"""Write updates to corresponding TensorArrays at time step t."""
assert len(tensor_arrays) == len(tensor_updates)
num_updates = len(tensor_updates)
return [tensor_arrays[i].write(t, tensor_updates[i])
for i in range(num_updates)] | f86587e60b9997ff5a17c757dff9b4e9c29d0974 | 670,597 |
def get_node_ids(apic, args):
"""
Get the list of node ids from the command line arguments.
If none, get all of the node ids
:param apic: Session instance logged in to the APIC
:param args: Command line arguments
:return: List of strings containing node ids
"""
if args.switch is not None... | 4daa84c0fb6e74daacc3a184918ca59c6d1b6add | 670,598 |
def _html_tag(tag, contents, attr_string=''):
"""Wraps 'contents' in an HTML element with an open and closed 'tag', applying the 'attr_string' attributes. """
return '<' + tag + attr_string + '>' + contents + '</' + tag + '>' | d6c08b117a6ec89e8011a4e87db22fc7d1fa0ada | 670,599 |
import pathlib
def tmp_cache(config, tmpdir):
"""Move the cache to a temporary dir that is empty at the start of the test and
deleted after the test."""
config['CACHE_ROOT_DIR'] = pathlib.Path(tmpdir)
return config['CACHE_ROOT_DIR'] | f4d18fa936a19f402a68e5552c534c86426c9e0e | 670,600 |
def formatParamStr(s,generalLine,length=64):
"""
modify so that len(last_line) = length (default=72)
Add the general line pointer at the end of each line
"""
# check the remainder and append with spaces as required, divide into elements
s = s.split(',')
retStr = ''
newLine = ''
... | fb7eb5ed20e9f1e1ccfeb224d6923fea9115da92 | 670,601 |
import codecs
def read_metafile(path):
"""
Read contents from given metafile
"""
with codecs.open(path, 'rb', 'utf-8') as f:
return f.read() | 14545384e8c60174c858d4899832f8196216ba42 | 670,602 |
def getSubmissionTextAsSingleString(content):
"""
Get all submission titles as a single string
"""
items = reversed(content)
text = ''
for item in items:
#print (item.link_flair_text)
if item.is_self is not True:
#print (str(item.author) + ' ' + item.permali... | 390898f0427c15512946e5df0eb816aed60a27dd | 670,603 |
def read_content_from_file(filename):
"""Simply reads content from a file.
Used so we don't have to mock __builtin__.open()
Args:
filename (string): name of the file
"""
with open(filename, 'r') as fh:
content = fh.read()
return content | c4a6d246db590b86cba88d8d39f526422e30560f | 670,604 |
import torch
def collate_fn(data):
""" Creates mini-batch from x, ivec, jvec tensors
We should build custom collate_fn, as the ivec, and jvec have varying lengths. These should be appended
in row form
Args:
data: list of tuples contianing (x, ivec, jvec)
Returns:
x: one hot enco... | 06c25feda297aba9d000e1ffb1e2f648887ae89a | 670,605 |
from bs4 import BeautifulSoup
def extract_body_from_html(html_soup):
"""Return an XML beautiful soup object with the <body> of the input HTML file"""
body = html_soup.body.extract()
xml_soup = BeautifulSoup('', 'xml')
xml_soup.append(body)
return xml_soup | e017ceb805bd1da023201e56d633bdb6392adbc5 | 670,606 |
def zero_mean(im):
"""
ZeroMean called with the 'both' argument, as from Binghamton toolbox.
Parameters
----------
im : numpy.ndarray
Multidimensional array.
Returns
-------
numpy.ndarray
Zero mean version of input im.
"""
if im.ndim == 2:
im.shape += (... | b9dbc67410cf055c722117be07d3c36c59f5ad07 | 670,607 |
import yaml
import json
def load_config_file(config_file: str, child_name="dockerConfiguration") -> dict:
"""
Load OSDF configuration from a file -- currently only yaml/json are supported
:param config_file: path to config file (.yaml or .json).
:param child_name: if present, return only that child n... | 2814bf1e67b79a4f48fd67564e00b0f822aedd64 | 670,608 |
def make_frame(contents, title=''):
"""
Wrap `contents` in \begin{frame} ... \end{frame},
optionally setting `title`
"""
lines = [r'\begin{frame}']
if title != '':
lines.append(f'\\frametitle{{{title}}}')
lines += [
f'{contents}',
r'\end{frame}'
]
return '\n'.... | eded8f5646287a363edc22a91afda779bfbaaa15 | 670,609 |
def calculate_dot_product(vectEndX, vectEndZ, pointCoordX, pointCoordZ):
"""
Looks if the linePosition is above or below user defined point for
isolating drop.
vectEndX = list - total x range (in pixels) of droplet
vectEndZ = list - z-coordinate (in pixels) of user input for isolating droplet
... | 4fe9acff06c0c9164690a6983cc036af04829764 | 670,610 |
def gini_impurity_score_by_period(right_dict, left_dict, verbose=False):
"""
Calculate the gini impurity score by period given two dictionaries that
charactize the left and right leaf after the potential split.
"""
current_score = []
for key in right_dict.keys():
left_proba = left_dict[... | a0742fe9fbfed026e90fe017b2fa2a2f6b57ae85 | 670,611 |
def add_cluster_labels(model, ct, train_df, test_df, target):
"""Adds cluster labels as a feature"""
train_df_cluster = train_df.copy()
test_df_cluster = test_df.copy()
X_cluster = ct.fit_transform(train_df.drop(columns=[target]))
test_cluster = ct.transform(test_df)
model.fit(X_cluster)
... | 07c7a08dec098aa9f9bb23e1906e5b70fac2b18a | 670,612 |
def get_pull_request(pull_request_number=None, repo=None):
"""
get pull request from given identifier
:param pull_request_number:
:param repo:
:return:
"""
if not pull_request_number:
raise ValueError("you must provide pull request number")
if not repo:
raise ValueError(... | 0168c214cef9433d9a8445d31422f69eba9cc90d | 670,613 |
def mol_with_atom_index(mol):
"""Use this method to add RDKit's atom index (order) to the visualized graph"""
for atom in mol.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx())
return mol | 36b9906322bd2508d78909cf8c3c03a590e04cd2 | 670,614 |
def separate_words_and_numbers(strings):
"""
Separates words and numbers into two lists.
:param strings: List of strings.
:return: One list of words and one list of numbers
"""
filtered_words = []
filtered_numbers = []
for string in strings:
if string.isdigit():
... | d0846effcd81524620ed7d6c3e132a3d44f0f2ef | 670,616 |
def intersection(lst1, lst2):
"""returns the intersection between two lists"""
if (lst1 == None or lst2 == None):
return []
lst3 = [value for value in lst1 if value in lst2]
return lst3 | eb02cb1163762d6f0ccdbf85c3c7a0146febb38e | 670,617 |
import torch
def _format_faces_indices(faces_indices, max_index):
"""
Format indices and check for invalid values. Indices can refer to
values in one of the face properties: vertices, textures or normals.
See comments of the load_obj function for more details.
Args:
faces_indices: List of... | 1bbba9714a3359a0c98c5ebe1059ac0ebb035b0c | 670,618 |
import argparse
def _get_parser():
"""
Command line Parser for search
:return:
"""
parser = argparse.ArgumentParser(description='Tool for fetching photos from facebook')
parser.add_argument('-fb', '--facebook', action='store_true',
help='Fetch Facebook Photos (Default)'... | d9cc5b867fbd6be9e944e2467ef12d1102e6c023 | 670,619 |
import logging
def logger() -> logging.Logger:
"""Create logger fixture."""
return logging.getLogger("test") | dbf502d18e85abfd037d3bd7905ae19926301c69 | 670,620 |
def sum_pair(numbers, sum_to):
"""
Naive approach with double for loop over unsorted numbers array
Complexity: O(n2)
"""
for n1 in numbers:
for n2 in numbers:
if n1 + n2 == sum_to:
return True
return False | 8f8bf5640d33baeb5e984f13da5188e6abb30a27 | 670,621 |
import os
def confirm_overwrite(filepath):
"""
If config.get('output', 'overwrite')==False and the file exists, ask user
if it should be overwritten.
"""
if os.path.isfile(filepath):
overwrite = input("[WARNING] {} already exists - ".format(filepath) +
"overwrite... | cf3b9fc972c2e7558645e7b40fcc934c13d35f49 | 670,622 |
def get_coherence_pairs():
""" These are pairs that should be placed next to each other """
return [(u"(", u")"), (u"[", u"]"), (u"{", u"}"), (u"<", u">"), (u"“", u"”"), (u"‘", u"’"), (u"«", u"»"),
(u"‹", u"›")] | eac823f732110ebba2c72ed94debfb6313a96486 | 670,625 |
def remove_redefined_attributes(path):
"""
Removing any redefined 'viewBox' or 'd' attributes
path: path of file being corrected
"""
file_content = ""
file = open(path, 'r')
file = file.read()
d_attribute_found = False
view_box_attribute_found = False
end_tag_fo... | df0546859fff8fc50d9301af61c0204761b43561 | 670,626 |
def get_division_data():
"""Get league division names"""
divisions = [
{'name': 'AFC East'},
{'name': 'AFC North'},
{'name': 'AFC South'},
{'name': 'AFC West'},
{'name': 'NFC East'},
{'name': 'NFC North'},
{'name': 'NFC South'},
{'name': 'NFC West'... | ae90c8a75acc581bfccecfeb67a8897dc1169226 | 670,627 |
import os
def get_export_dir(out_dir):
"""Returns directory of exported best model"""
return os.path.join(out_dir, 'export') | d48dd9bec7f0d2b83d968b6eb4f20b01401b86f5 | 670,628 |
def wrap_function(function, args):
"""Count the number of times a function is called and close around `args`.
This function existed in scipy prior to 1.7
It must not have been considered part of the public API, as it has
disappeared without a trace.
"""
ncalls = [0]
if function is None:
... | 506e87a4da447e21f71b1444f23b917860ac0de2 | 670,629 |
import unicodedata
def _preprocess_ja(sentence: str) -> str:
"""Copied from https://github.com/rwth-i6/ExtendedEditDistance/blob/master/util.py.
Raises:
ValueError: If input sentence is not of a type `str`.
"""
if not isinstance(sentence, str):
raise ValueError(f"Only strings allowed ... | a183da92233ce737607fb7db60c769e145d7c903 | 670,630 |
import os
import glob
def find_image_subfolder(current_root):
"""Identifies the right level of a directory
that matches with torchvision.datasets.ImageFolder requirements.
In particular, if images are in current_root/foo/bar/category_X/*.jpg
we will want to feed current_root/foo/bar/ to ImageFolder.
... | 1087252808b0e129c951d05b9195a691d154d79e | 670,631 |
def _pairs(exercises):
""" Returns a list of pairs of exercises in `excercises` """
pair_list = []
for i in range(len(exercises)//2):
pair_list.append((exercises[2 * i], exercises[2 * i + 1]))
return pair_list | 81af596635cac3def4c8bdb79955fdfb4261527f | 670,632 |
def _unique_metric_name(name, existing_metrics):
"""Returns a unique name given the existing metric names."""
existing_names = set([metric.name for metric in existing_metrics])
proposed_name = name
cnt = 1 # Start incrementing with 1.
# Increment name suffix until the name is unique.
while proposed_name i... | 005fa048ec1c9d0a03f28fa0024531d74f232b56 | 670,633 |
import torch
def euclidean_distance_mean_loss(data, centroids):
"""
Calculate euclidean distance mean loss between data and centroids (also similar to kmean_loss())
# Arguments
data: input data (torch tensor)
single_value: a single value, usually the min value (torch tensor)
# Return
... | 6ec4f4a7dbafb80ae68c1eab2287eb93765fd8e5 | 670,634 |
def V(x):
"""
potential energy function
use units such that m = 1 and omega_0 = 1
"""
return 0.5 * pow(x, 2.0) | 1969edd5447657096353eda96cb281da68383e8f | 670,635 |
def dms_to_deg(deg,min,sec):
"""Convert a (deg,arcmin,arcsec) to decimal degrees"""
return deg+min/60.+sec/3600. | 9eaf74e10d80cf66990836da950b2908af6677b1 | 670,636 |
def count_ways(n):
"""
Parameters
----------
n : Dimension of chessboard (n x n)
Returns
----------
The number of ways to place n queens on the chessboard,
such that no pair of queens attack each other
"""
def backtrack(i, c, l, r):
if not i:
... | 2f37c4177c60ad3d8988671f9ca8ea1b8d49f9ce | 670,637 |
import logging
def isTie(df):
"""
Determine if the kmers count value is a tie with the second top isolate; if
so then indicate a tie was found in the results
Parameters
----------
df : pandas data frame
Returns
----------
str
string of best genus either genus or a sentenc... | 2406858b1cfd653d26fb089c49e614211e4216ec | 670,638 |
def construct_network_config_string(cfg_list):
"""
Creates the network configuration string from a list of addresses created via convert_network_address_to_list
Args:
cfg_list (List): List of lists containing all the addresses
Returns:
cfg_string (str): String containing the numbers of... | 5a2eefc6e6cb02644a75f1609432e085d04bebdc | 670,639 |
def add(x, y):
"""
Helper function to implement
adding for binary nums
"""
cur_sum = 0
carry_in = 0
temp_x = x
temp_y = y
k = 1
while temp_x or temp_y:
xk = x & k
yk = y & k
carry_out = (xk & yk) | (xk & carry_in) | (yk & carry_in)
cur_sum |= (xk ... | 6edc4ab9a24457df6efd6c6d7bf365fa4f92933c | 670,641 |
def from_pandas_contextual(df):
""" Convert contextual ``pandas.DataFrame`` to list of tuples.
Args:
df (DataFrame):
anomalies, passed as ``pandas.DataFrame``
containing two columns: start and stop.
Returns:
list:
tuple (start, end) timestamp.
Raise... | bbf47db19777a82ef9c5372cf638f95bfb1465f3 | 670,642 |
from datetime import datetime
def format_str_date(str_date):
"""
将全球每日疫情数据中的字符串转为时间
:return:
"""
return datetime.strptime(str_date, '%Y %m.%d').date().__str__() | 71dfb61c11d67987877dd0b083927a4b6f1c6d82 | 670,643 |
import math
def get_dist(x1,x2,y1,y2):
"""Find distance between two points"""
return abs(math.sqrt(pow(x1-x2,2) + pow(y1-y2,2))) | dc83c92ff12260b01ea10b90546ad475a1e83e09 | 670,644 |
def get_X_Y(**cosmo):
"""The fraction of baryonic mass in hydrogen and helium.
Assumes X_H + Y_He = 1.
You must specify either 'X_H', or 'Y_He', or both.
"""
if 'X_H' in cosmo and 'Y_He' not in cosmo:
X_H = cosmo['X_H']
Y_He = 1. - X_H
elif 'Y_He' in cosmo and 'X_H' not in cosm... | 02268d861543ba0bc7deaafa3c31d0cc50231112 | 670,645 |
from typing import List
def do_materials_match(
materials_1: List[str],
materials_2: List[str],
colors_1: List[str],
colors_2: List[str]
) -> bool:
"""Returns whether the two given material lists match, or, if either of the
given material lists are empty, returns whether the two given color li... | 2ad205c9ade63da4134c6260005db6a8bf3ee0d0 | 670,646 |
def separate_appetizers(dishes, appetizers):
"""
:param dishes: list of dish names
:param appetizers: list of appetizer names
:return: list of dish names
The function should return the list of dish names with appetizer names removed.
Either list could contain duplicates and may require de-dupin... | 2a3296751f7767143602b43ce3c07a09b6280729 | 670,647 |
def compute_loss(batch, output, loss_func):
"""Computes the loss of a given batch
Args:
batch (dict): The current batch
output (tuple): Tuple of tensors (output of `TransformerModel`)
loss_func (:obj:`nn.modules._Loss`): The loss function
Returns:
(:obj:`torch.Tensor`, int)... | 0ced525c776fb5522555fd0b584040d02736d120 | 670,648 |
def memo(f):
"""Simple memoize"""
key = "__zpretty_memo__" + f.__name__
def wrapped(obj):
if not hasattr(obj, key):
setattr(obj, key, f(obj))
return getattr(obj, key)
return wrapped | 8ccd0f7658af22b3c4114b0a0a349c1529343a41 | 670,649 |
from typing import List
import itertools
def flatten_(list_of_lists: List[List]) -> List:
"""Reduce a lists of lists to a list, functionally
>>> assert flatten_([[1, 2], [3, 4]]) == [1, 2, 3, 4]
Thanks to CTT at
https://stackoverflow.com/a/716482/500942
"""
return list(itertools.chain.fr... | c516785b429ba113953cb5183074f3de72c73e19 | 670,650 |
def clean_data(df):
"""
Clean the dataset
Args:
df: (pandas.DatFrame) containing data to be cleaned
Returns:
df: (pandas.DataFrame) containing the cleaned dataset
"""
try:
# clean target labels
categories = df.categories.str.split(";", expand=True)
cat_n... | 676f43ebdb426155ce53d3632626aefca09b3b00 | 670,652 |
import torch
def redistribute_errors(power_deltaE_hyab, cmax, pc, pt):
"""
Redistributes exponentiated HyAB errors to the [0,1] range
:param power_deltaE_hyab: float tensor (with Nx1xHxW layout) containing the exponentiated HyAb distance
:param cmax: float containing the exponentiated, maximum HyAB difference be... | 3e5ce06b0e1ef68b3c04dbc4476ad7e890d91354 | 670,653 |
def error_handler(func):
"""Makes a function in a cog an error handler"""
func._is_error_handler = True
return func | eaad3680010f57c8e8d7779affb3b0c0c2c903fb | 670,654 |
import socket
import os
def compute_environ():
"""Figure out things about our current host."""
env = {}
# get hostname
env["hostname"] = socket.gethostname()
# Get system memory in GB
env["memGB"] = (
os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / (1024**3)
)
env["T... | 9a250ff431a85016c7e207c043c96b6fc991d71d | 670,655 |
def decode_fit_par(fit_par, constraint_types):
"""
Translate the 1D array of fit parameters to individual lists.
The fit paramters are sorted into the lists segment_borders, y_at_borders
slope_at_borders based on the strings given in constraint_types. The three
lists are used as arguments in piecew... | 3fdf47c8a3cb1628accbe2f81b2e1e7a5efd41f3 | 670,656 |
import pickle
def load_transform_data_fn(data_file, **kwargs):
"""
Load and preprocess data, returning the examples and labels as numpy.
"""
# Try loading saved preprocessed data and classifier.
with open(data_file, "rb") as f:
obj = pickle.load(f)
X, y = obj["X"], obj["y"]
re... | 304707cfe9bfecec18669ba41dc38b9e1758a13e | 670,657 |
import itertools
def get_room_locations(room_top_left, room_width, room_height):
""" Returns the locations within a room, excluding walls.
This is a helper function for adding objects to a room. It returns a
list of all (x,y) coordinates that fall within the room excluding the
walls.
Parameters
... | c9a7ad43c30153b6ff0e3eaafe7adb4751f54bfb | 670,658 |
import random
def random_fill_sparse(table,K):
"""
brief : fills in a matrix randomly
args :
matrix : empty matrix
K : number of cells to be filled in
Return :
the matrix (numpy array) filled in with "X" values (char)
Raises :
K must be smaller than... | bd0834ed032623893b77c6e7e29c0125bce42c05 | 670,659 |
import re
def _build_es_query(params):
"""Builds the body of the ES search query and return it as a dict.
Args:
params: the parameters from a web query. Should at least contain a
terms and a fields parameter.
Returns:
search_body: a dict conating the body for an ES search... | 16a134543eb98359392a2537ef0fa0f2bdbc572d | 670,660 |
def validate_file_transfer(filename, file_transfer_status):
"""Validate file transfer.
Keyword arguments:
filename -- name of file being copied
file_transfer_status -- true (success) or false (failed)
:param filename: str
:param file_transfer_status: bool
"""
if not file_transfer_statu... | 275616e2c358cb2a9f820633b687b104af1fb6c0 | 670,661 |
def find_column(input_text: str, token_lexpos: int) -> int:
"""
Used for compute column in case of error.
"""
line_start = input_text.rfind('\n', 0, token_lexpos) + 1
return (token_lexpos - line_start) + 1 | 13e0aaff371a7b910273012b84903c918355dbad | 670,662 |
def calcular_longitud_cadena(cadena):
"""
Calcula la longitud de una cadena de caracteres.
"""
contador = 0
for c in cadena:
contador += 1
return contador | 93675f6c559b19e0ef01f99e96b0c6afa8cb259b | 670,663 |
def process_text(response):
"""Returns the plaintext of the reponse."""
return response.text | 65c6b8055fdcf0a86ba6985895da7b0bf2d172ec | 670,664 |
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new ha... | cf2b94ddf35100b05e2807218048c387d7a53242 | 670,665 |
def _next_rooted_tree(predecessor, p=None):
"""One iteration of the Beyer-Hedetniemi algorithm."""
if p is None:
p = len(predecessor) - 1
while predecessor[p] == 1:
p -= 1
if p == 0:
return None
q = p - 1
while predecessor[q] != predecessor[p] - 1:
q -= ... | 3214257132bf806f14c5f753090d7c882079345e | 670,667 |
def get_list_by_selected_names(set_names, set_list):
"""
@summary 通过集群名称(列表)获取集群{bk_set_id, bk_set_name}对象列表
@param set_names: aa,bb or ['aa', 'bb']
@param set_list: [{"bk_set_id":1, "bk_set_name":"bb"}]
@return: [{"bk_set_id":1, "bk_set_name":"bb"}]
"""
set_name_list = set_names
if not ... | 87199cf59d6281a91daa962ca6253bf20534d951 | 670,668 |
def input_new_values(formed_text, sample_list):
"""
formed_text: formatted text with {}
sample_list: list of new user values
formats text with user values
:@return(String) Re-formatted version of
"""
return formed_text.format(*sample_list) | 52c7b1b66b0bc8e018eec332253fdaba4f91d642 | 670,669 |
import torch
def invlogit(x, a=torch.tensor(0.0), b=torch.tensor(1.0)):
"""
sigmoid
"""
u = torch.sigmoid(x)
return (b - a) * u + a | 6b73461ac63b6d6ed680423bb8b994579dbf5eb4 | 670,670 |
def make_colorscale(scl0='rgb(255, 6, 6)', scl20='rgb(255, 153, 51)',
scl40='rgb(255, 255, 51)', scl60='rgb(128, 255, 0)',
scl80='rgb(0, 102, 0)'):
"""Generates a discrete color scale for the map graphic.
@param scl0 - color string for the minimum value
@param scl20 -... | 20bbc3071a0833668f70a13a317af98a28015b8e | 670,672 |
import os
def getfilename(val):
"""
Returns "item" from /home/adys/Item.dbc
"""
return os.path.splitext(os.path.basename(val))[0].lower() | d688a1a4351a41446c204f8dcb3b6c2d39e4adf5 | 670,673 |
import torch
def square_norm(x):
"""
Helper function returning square of the euclidean norm.
Also here we clamp it since it really likes to die to zero.
"""
norm = torch.norm(x, dim=-1, p=2) ** 2
return torch.clamp(norm, min=1e-5) | 8ac4b7c388e718c933b5ea9855d169e609671a76 | 670,674 |
def dt_tstamp(dt_obj):
"""
Args:
dt_obj (dt.datetime): datetime.datetime object
Returns:
int: timestamp
"""
return int(dt_obj.strftime('%s')) | 33a367c888a19515d8590b7094439aed933003d5 | 670,675 |
def sum_unmarked(board):
"""
Sum of the unmarked pieces on the board
:param board:
:return:
"""
counter = 0
for row in board:
for pair in row:
number, marked = pair
if not marked:
counter += number
return counter | 1d576cd21ff88978a5a032f957d81f205b0a78b2 | 670,676 |
def other_bond_index(bond, index):
"""Return the atom index for the other atom in a bond."""
if bond[0] == index:
return bond[1]
elif bond[1] == index:
return bond[0]
else:
raise ValueError("Index %s not found in bond %s" % (index, bond)) | e31bc9f490d4faead6ccfd8abe152e929a8b1961 | 670,677 |
def validate_package_name(name):
"""
Check if the given name is compliant to Keypirinha's package naming rules
and return a boolean.
**CAUTION:** this function should just serve an informational purpose as it
may not be up-to-date with current Keypirinha release.
"""
ascii_alnum = "01234567... | ba4d16dd3d2c40f90d4d51d734796fd65225d6ec | 670,678 |
def pretty_print_time(time, message=None):
"""Pretty print the given time"""
days = time.days
hours, remainder = divmod(time.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
if message is not None:
print(message)
print(f'\t {days} days, {hours} hours, {minutes} minutes, {secon... | 366caa41f110b984508376cf957d5050a04955e7 | 670,679 |
import re
def is_fc_uid(uid):
"""Validate the FC initiator format."""
return re.match(r"(\w{2}:){15}\w{2}", uid, re.I) is not None | 9e1d798cd1554a1515e2eeabcece110a02ed066a | 670,680 |
import base64
def base64_to_str(b64):
"""
>>> base64_to_str("TMOhc3psw7M=")
'László'
"""
return base64.b64decode(b64.encode()).decode() | 94387a8903ca6640e3ef51c1b4692c563d8eddcb | 670,681 |
import numpy
import os
import pandas
def calculateuncertainty(numberofsensor,numberofmodelinstance,finalpathuncertaintyinput,finalpathprediction):
"""
Calculate geotechnical uncertainties for the subsequent EDMF analysis
Developed by : WANG Ze-Zhou (ETH Singapore)
Contact : e0054... | 34f1b2d8ad8afcfb1ee3fb108213ec7fbd1c23f1 | 670,682 |
import re
def doctor(string: str) -> str:
"""Get rid of all the wacky newlines nbconvert adds to markdown output and return result."""
post_code_newlines_patt = re.compile(r'(```)(\n+)')
inter_output_newlines_patt = re.compile(r'(\s{4}\S+)(\n+)(\s{4})')
post_code_filtered = re.sub(post_code_newlines_... | b9fc3358acc2436bea6ffa6e0358d5470d781de6 | 670,683 |
import string
def get_valid_chars():
"""Get valid characters.
Valid characters are the ones which are on the following list:
-_()[] abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
Return: string
"""
return "-_()[] %s%s" % (string.ascii_letters, string.digits) | afdcce70d11b43de60664e6dafb36f39c0873749 | 670,685 |
def _make_url_args(url_args: dict):
"""
Make url parameters
Args:
url_args (Dict): Dict of url parametes
Returns:
str: The url parameters
Example:
input: {'test1': 1, 'test2': 2, 'test3': 3}
output: "&test1=1&test2=2&test3=3"
"""
url = ''
for key, v... | 0680736981aeaa755a8dc9fc280876c5b1f0f1dd | 670,686 |
def singleton(cls, *args, **kwargs):
"""构造一个单例的装饰器"""
instance = {}
def __singleton(*args, **kwargs):
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return __singleton | 339d8b82681b10997021c0826395eb35dbc6f6af | 670,687 |
def package_time(date_dict):
"""Package a time/date statement in a standardised form."""
return {"time_value": date_dict} | 6c4097e162091e3992fa6ef57e83093cf0788c46 | 670,688 |
def saffir_simpson_scale(spd):
"""Static method that returns the equivalent saffir-simpson scale rating,
based on wind-speed in knots.
This is the most-common index used to generalize tropical cyclone
intensity.
Example: saffir_simpson(100) --> 3 (implying category 3).
"""
if 34 <= spd < 6... | fd6a38a4168037e35f4354f3c297c7b676578f86 | 670,689 |
def validate_container_command(output: str, name: str) -> tuple:
"""
Validates output from one of the *_container functions, eg start_container.
:param output: output from the command line
:param name: container name or ID
:return: success boolean, message
"""
if "no such container" in outpu... | 29a48035e12ebd8d70a40a8c01ad514881aba382 | 670,690 |
def fill_list_to_len(slist, lgoal, tobefilled=""):
""" fill a list with something to a given length """
for i in range(lgoal - len(slist)):
slist.append(tobefilled)
return slist | db96830bee69960e430de84315e564c4c7a53863 | 670,692 |
from typing import Dict
from typing import Any
from typing import Tuple
from typing import List
def get_category_counts(cookie_data: Dict[str, Dict[str, Any]]) -> Dict[Tuple[str,str], List[int]]:
"""
Retrieve category counts for each cookie, to then be able to compute the majority opinion.
Cookies are ide... | c15f27c3dbef48200bf98b5665a96c08ac5c3aeb | 670,693 |
import argparse
def get_args():
"""Argument parser.
Returns:
Dictionary of arguments.
"""
parser = argparse.ArgumentParser(description='Chainer MNIST Example')
parser.add_argument(
'--batch-size',
type=int,
default=100,
metavar='N',
help='input batch size for training (defa... | df179f1d31d1c41939828f6e22894a5e5a895c5e | 670,694 |
def standardize_tabletype(tabletype):
"""
Given the user defined type of table it returns the proper 'tabletype' expected by the pipeline
Args:
tabletype, str. Allows for a flexible number of input options, but should refer to either the 'exposure',
'processing', or 'unproc... | bb715f40708ad3bd55b495167d01fb586b5e7cde | 670,695 |
def reorder_list_or_array(M, ordering):
""" Reorders a list or array like object. """
if isinstance(M, list):
return [M[i] for i in ordering]
else:
return M[ordering] | b3c215b75937f919bab1c17146e195793d2aade2 | 670,696 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.