content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def ev(k, v):
"""ev
Get environment key and strip
:param k: environment variable key
:param v: environment variable value
"""
return os.getenv(
k,
v).strip() | f8ffbbc22e4e394e5a0a05d37b6f655cdd403d30 | 680,695 |
import os
def get_full_pathname(name):
"""
Use built-in methods to create a platform-independent file path for loading and saving of files.
:param name: This is the base name of the journal to be worked with.
:return: The full filename string.
"""
filename = os.path.abspath(os.path.join('.', ... | 2f422d07db7631cf15b92949202154da126ba1e3 | 680,697 |
import subprocess
def get_cmd_output(cmd, cwd=None):
"""Run a command and return its output as a string."""
if cwd is not None:
out = subprocess.check_output(cmd, cwd=cwd)
else:
out = subprocess.check_output(cmd)
return out.decode("utf-8").rstrip() | fa929450c85709318df5c10bdef66adef71f287e | 680,698 |
import ipaddress
def create_bgp_prefixes(radix):
"""Create a list of list of /24 prefixes."""
bgp_prefixes = list(radix)
total_prefixes = []
for bgp_prefix in bgp_prefixes:
bgp_prefix = bgp_prefix.prefix
try:
prefixes = [
p
for p in ipaddres... | a9129c34fe3a063a693b1aafea365e000fa97f22 | 680,699 |
def time_in_range(start, end, x):
"""
Return true if x is in the range [start, end]
"""
if start <= end:
return start <= x <= end
else:
return start <= x or x <= end | db8cabd7fa71ea341000cc9886181c6300996734 | 680,700 |
def get_degen_dependence_lengths2(weight_shapes, independent = False):
"""
same as above but assumes that one just wants one weight (the first weight per node) from each node in a layer
to be sorted w.r.t. corresponding weight in other nodes. This should be enough to ensure nodes aren't degenerate.
does this for we... | 8202f31d2b475dba19ead3af3347089cdb0fdfb9 | 680,701 |
def Arranjo_Repeticao(m, p):
"""
param m : número de elemetos distintos. \n
param p : número de vezes que m é repetido. \n
return : se for retornado o valor -1 quer dizer que ouve um erro.
"""
if p < 0 or m < 0:
return -1
else:
return m**p | 4f2605905d39d9ae2de845d3a30ad1861c3c5cbe | 680,702 |
import posixpath
def extract_version(module_name):
"""
extract the version number from the module name provided.
:param module_name: <str> the module to find version in.
:return: <int> version number.
"""
# module_name_v0000.py --> module_name, _v0000.py --> _v0000
return posixpath.splitex... | 64da954ee794379fd3943283c7569f1f541e8839 | 680,703 |
def indices(lst, element):
""" A function that searches for all occurrences of an element in a list """
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset + 1)
except ValueError:
return result
result.append(offset) | b415251d010db49a2823bd67fbd651193d980f38 | 680,704 |
import os
def get_self_dir() -> str:
""" Get the path to the directory where this script lives. """
return os.path.dirname(os.path.abspath(__file__)) | 30dd288630f4bee1d8597f0f3373c713001305c7 | 680,705 |
def dict_diff(dict1, dict2, by_key=False):
"""
Helper method to calculate difference of two dictionaries
"""
keys1 = set(dict1.keys() if by_key else dict1.items())
keys2 = set(dict2.keys() if by_key else dict2.items())
intersection = keys1 & keys2
return keys2 ^ intersection, intersection... | 45063cbca167b52f0b61e8c0f2f80480e568a93e | 680,706 |
def ask_yes_no(question):
"""Ask for a number within a range."""
response = None
while response not in ("y", "n"):
response = input(question)
return response | 4caff45073a4f28cd6392e5d1183bb4cedb5bcee | 680,707 |
import configparser
def get_token():
"""Get token from config.ini file."""
config = configparser.ConfigParser()
config.read("config.ini")
return config["DEFAULT"].get("github_access_token") | d2137e0e6623e2ec28b60ff1c4e4a08b192d1502 | 680,708 |
def next_greatest_letter(letters: list[str], target: str) -> str:
"""Returns the the smallest element in the list that is larger than the given target
Args:
letters:
A list of sorted characters drawn from the lowercase latin
alphabet that also wraps around. For example, if the t... | 31558470d49d124375fe4d2aee8d983f6194f007 | 680,710 |
def _se_isub_ ( self , other ) :
"""Update the counter
>>> cnt = ...
>>> cnt -= value
"""
return self.add ( -other ) | a7bb400986c7ae4ab7bf20c3e46563b01734dfb4 | 680,711 |
def usage():
"""
Return usage text so it can be used on failed human interactions
"""
usage_string = """
usage: %prog [options] -H SERVER -j JOB -w WARNING -c CRITICAL
Make sure the last job is successful
OR the current is not stuck (LastBuild)
Warning and Critical are defined... | cc03fee7e30e03d14d197ade9a5e0ccd25f9950a | 680,712 |
def same_thing(thing: object) -> object:
""" post: __old__.thing == _ """
# If `thing` isn't copyable, it won't be available in `__old__`.
# In this case, enforcement will fail with an AttributeError.
return thing | 795e80be913d272bca6acf7285470874ba949ce2 | 680,713 |
import math
def floatToJson(x):
"""Custom rule for converting non-finite numbers to JSON as quoted strings: ``"inf"``, ``"-inf"``, and ``"nan"``.
This avoids Python's bad habit of putting literal ``Infinity``, ``-Infinity``, and ``NaN``
in the JSON (without quotes)."""
if x in ("nan", "inf", "-inf"):... | dc7125ed60d8341e5e61e368b85ba34042cc5863 | 680,714 |
from typing import OrderedDict
def labels(root):
"""find label values from assets"""
asset_labels = []
name_type_map = OrderedDict(
[("fig", "fig"), ("media", "video"), ("table-wrap", "table")]
)
for tag_name in list(name_type_map):
for block_tag in root.findall(".//" + tag_name):
... | 4d80fa6c46bd74195480a6cc97375f18d376de15 | 680,715 |
def points_to_vec(pt1, pt2, flip = False):
"""
Converts the coordinate of two points (pt1 > pt2) to a vector
flip: bool, default = False
If the coordinate system should be flipped such that higher y-coords
are lower (e.g. needed when working with images in opencv).
"""
vx = pt2[0]... | 9a826a790661f1d47a4bc47991fbe16a71cfad70 | 680,716 |
import os
import imghdr
def get_images(img_dir):
"""
:param img_dir:
:return:
"""
files = []
if os.path.isfile(img_dir):
if imghdr.what(img_dir):
files.append(img_dir)
return files
for root, sub_dir, dir_files in os.walk(img_dir):
for img_file in dir_fi... | 40c92e5e75880cb44d5873f56ef8275b81375d1a | 680,718 |
import json
def monday_handshake(webhook):
"""Takes webhook information, authenticates if required, and decodes information
Args:
webhook (request): Payload received from Monday's Webhooks
Returns:
dictionary: contains various information from Monday, dependent on type of webhook sent
... | 83061e620c1bbb84311b972cc095810637278e05 | 680,719 |
def rbits_to_int(rbits):
"""Convert a list of bits (MSB first) to an int.
l[0] == MSB
l[-1] == LSB
0b10000
| |
| \\--- LSB
|
\\------ MSB
>>> rbits_to_int([1])
1
>>> rbits_to_int([0])
0
>>> bin(rbits_to_int([1, 0, 0]))
'0b100'
>>> bin(rbits_to... | 57ef269f6690511c525081d542aed0d326a71c3b | 680,720 |
def esi_Delta(Delta, q):
"""
Calculate equivalent step index (esi) Delta for a graded-index fiber.
Args:
Delta : relative refractive index [-]
Returns:
equivalent relative refractive index [-]
"""
return q * (2 + q) / (1 + q)**2 * Delta | a234c8993c59a97165f4cee6aa18e89db86ca327 | 680,721 |
import numpy
def NoRanking(robot, ik_solutions):
"""
Return IK solutions with an arbitrary ranking.
"""
return numpy.ones(ik_solutions.shape[0]) | 04132de2ca2544f850a36d2ef62370fd552e67dd | 680,722 |
def read_worksheet(worksheet_name, workbook):
"""Read worksheet table to list of dicts
"""
output = []
try:
data = workbook[worksheet_name].values
except KeyError:
print("Worksheet {} not found".format(worksheet_name))
return output
keys = next(data)
data = list(data... | c4a83ebdc617fbdfab069825fe0efa0e36e9ae2f | 680,723 |
def generate_macs_args(flags):
"""
This is a helper function that takes the sim options and outputs the start the macs_args
:param flags:
:return macs_args:
"""
macs_args = None
if '-macs_file' in flags:
macs_args = [flags['-macs_file'][0][0], flags['-length'][0][0], "-I", flags['-I... | 887d867192fbebba1f9604a724346771738f0d46 | 680,724 |
def _expand(dict_in):
""" Convert {key1: list1, key2: list2} to
{list1[0]: key1, list1[1]: key1, list2[0]: key2 etc}
"""
dict_out = {}
for key in dict_in:
for item in dict_in[key]:
dict_out[item] = key
return dict_out | 5cb4a90d424427952a2c6aafad0e8003b349c857 | 680,725 |
def reshape_by_symbol(y):
""" Deprecated helper function. Was not used in the final implementation."""
grouped_df = y.reset_index() \
.groupby('level_0') \
.apply(lambda x: x.reset_index(drop=True)) \
.drop('level_0', axis=1)
grouped_df.index = grouped_df.index.droplevel(level=1)
... | a7983e33ecaba40963b36ade8b1c2fe015fcefa8 | 680,727 |
def replacer(svgFile, toReplace, newData):
"""
Searches through SVG file until it finds a toReplace, once found, replaces it with newData
"""
for count in range(0,len(svgFile)):
found = svgFile[count].find(toReplace) #Check if the current line in the SVG file has the required string
if n... | 36cc896bb12e9e8d9539b072986ea4c255912a34 | 680,728 |
def get_delimited_string_from_list(_list, delimiter=', ', wrap_values_with_char=None, wrap_strings_with_char=None):
"""Given a list, returns a string representation of that list with specified delimiter and optional string chars
_list -- the list or tuple to stringify
delimiter -- the the character to sepe... | aa8b6923414f08db1969406bf7a0308d1da87106 | 680,729 |
def bounds():
"""
'Kf' - day-degree rate of melting (mm/(day*celsium degree))
[1, 10]
'CTG' - dimensionless weighting coefficient of the snow pack thermal state
[0, 1]
"""
bnds = ((1, 10), (0, 1))
return bnds | 6ae61f400814a73254b34fb4d01c8317b8c0c00f | 680,730 |
def tauxcontacper(beta,p,cbeta,T):
"""renvoie une fonction de contact de periode T qui vaut beta pendant une fraction p de laperiode et beta(1-cbeta) pendant le reste de la periode"""
def f(t):
if (t <= T*p):
return(beta)
else:
return(beta*(1-cbeta))
return(f) | 0dc38b2f8ef4baa19ff425423b6a0641c0b44c07 | 680,731 |
def get_yaml(path):
"""
Return the Yaml block of a post and the linenumbers of it.
"""
end = False
yaml = ""
num = 0
with open(path, 'r', encoding='utf-8') as f:
for line in f.readlines():
if line.strip() == '---':
if end:
break
... | dd443cb552cd625b7acacdc8e794dba794f9372a | 680,732 |
def convert_PBDMS_into_dict(doc_annotations):
"""Convert annotations built from PBDMS dataset into final output dict.
Args
doc_annotations (list): has format [(annotation 1), (annotation 2), ...]
Returns
output_PBDMS (dict): has format {file_id: [(annotation_str, start_pos, end_pos, mesh_... | ecd4dcc2006ea832c3cc5d05f7ef9d977a401b3f | 680,733 |
def bitcount(num):
"""
Count the number of bits in a numeric (integer or long) value. This
method is adapted from the Hamming Weight algorithm, described (among
other places) at http://en.wikipedia.org/wiki/Hamming_weight
Works for up to 64 bits.
:Parameters:
num : int
The ... | 6b71324cd3db976b86b5e56cdbb5fb086d6e3623 | 680,734 |
def _pad_binary(bin_str, req_len=8):
"""
Given a binary string (returned by bin()), pad it to a full byte length.
"""
bin_str = bin_str[2:] # Strip the 0b prefix
return max(0, req_len - len(bin_str)) * '0' + bin_str | 9be1f50e9bdc0c60daa50fe3ae1b9e4c04dff5f1 | 680,735 |
def income3(households):
"""
Dummy for for income group 3
"""
return (households['income_category'] == 'income group 3').astype(int) | 6fdd64682d3123ddc251924df027474f34ce75bd | 680,736 |
def _deep_flatten(items): # pylint: disable=invalid-name
"""Returns a list of objects, flattening sublists/subtuples along the way.
Example: _deep_flatten([1, (2, 3, (4, 5), [6, 7]), [[[8]]]]) would return
the list [1, 2, 3, 4, 5, 6, 7, 8].
Args:
items: An iterable. If elements of this iterable are lists... | b2683ddc455842d1f19ac40f021b37aeafade243 | 680,737 |
def depth2inv(depth):
"""
Invert a depth map to produce an inverse depth map
Parameters
----------
depth : torch.Tensor or list of torch.Tensor [B,1,H,W]
Depth map
Returns
-------
inv_depth : torch.Tensor or list of torch.Tensor [B,1,H,W]
Inverse depth map
"""
... | a7e2d0ccb4271bd2593f9648b0310614e0b8bb96 | 680,738 |
def get_unit_string_from_comment(comment_string):
"""return unit string from FITS comment"""
bstart = comment_string.find("[")
bstopp = comment_string.find("]")
if bstart != -1 and bstopp != -1:
return comment_string[bstart + 1: bstopp]
return None | 232c1a6446d955be172fb08c1fe0c9e7847f87da | 680,739 |
from typing import Any
import torch
def _size_repr(key: str, item: Any) -> str:
"""String containing the size / shape of an object (e.g. a tensor, array)."""
if isinstance(item, torch.Tensor) and item.dim() == 0:
out = item.item()
elif isinstance(item, torch.Tensor):
out = str(list(item.si... | 7e2b9a26070428d2f97740d37a87d1da42a4376d | 680,740 |
def _strip(json_str):
"""Strip //-prefixed comments from a JSON string."""
lines = []
for line in json_str.split('\n'):
pos = line.find('//')
if pos > -1:
line = line[:pos]
lines.append(line)
return '\n'.join(lines) | 8d0cd156c88f5d385ed1d1a4b5a22c529fd9c2fd | 680,741 |
def load_yolo_predictions(txt_path, classes=None):
"""Return a list of records from YOLO prediction file.
Each record is a list `[label, box, score]`, where the box contains
coordinates in YOLOv5 format. `score` can be None if text file does
not contain scores, and `label` is either integer, or string ... | 9e4058bbe48b8b41759fbae63fd9173e9a8dde6d | 680,742 |
def chirp_to_dict(args,curr_cfg=None):
"""Handler for `chirpCfg`"""
if curr_cfg:
cfg = curr_cfg
if 'chirps' not in cfg.keys():
cfg['chirps'] = []
else:
cfg = {'chirps': []}
chirp_dict = {}
chirp_dict['chirpStartIndex'] = int(args[0])
chirp_dict['chirpStopInde... | 33834ce721fc2328c25fd443640c89351171a866 | 680,744 |
import itertools
def dim_transform(first, second, transform):
"""Adapt `transform` dimensions following `first` to `second` rules."""
if not all(itertools.chain(first, second)):
return transform
# Compute aspect ratios.
first_ratio, second_ratio = map(lambda pair: pair[0] / pair[1],
... | b7c01b9d1b51d4c5a61f96e514720a43490fb43c | 680,745 |
def group_changes(changes):
"""Consolidate same-position insertions and deletions into single changes.
"""
insertions = [c for c in changes if c.change_type == 'insert']
deletions = [c for c in changes if c.change_type == 'delete']
mutations = [c for c in changes if c.change_type == 'mutate']
in... | e306005b1ce2d331ac5c20e573839c6f015cb61a | 680,746 |
def get_username_row_count(self):
""" Gets the number of usernames in table """
count = self.follows_db_c.execute("select count(*) from usernames").fetchone()
if count:
return count[0]
else:
return False | c0641f97e1c6dc54d322e87b6be414c8d3944846 | 680,747 |
import hashlib
def hashstring(s: str) ->str:
"""
Generating an "unique" user id from the sha224 algorithm.
"""
return hashlib.sha224(s.encode('ascii')).hexdigest() | d56e45b2f60bcd5ab096cce539bab49a7a6c96ef | 680,748 |
import os
def massage_path(file_name_path):
"""
function to massage file path and do some transformations
for different scenarios of file inputs
:param file_name_path:
:return:
"""
massaged_path = file_name_path
# pprint(massaged_path)
# convert possible windows style path to uni... | 881276c03a4e00d53b331c00d1c3c86931611a40 | 680,749 |
import re
def deNumerize(text:str) -> str:
"""Removes numbers from strings"""
regex_pattern = re.compile(pattern = r'[0-9]', flags=re.UNICODE)
return regex_pattern.sub(r'', text) | 6983cb6de3cd52fee797cd9559402d83d514a100 | 680,750 |
def parse_cfg(cfgfile):
"""
Input: cfgfile
Return: list of layer infos and net info
"""
with open(cfgfile, 'r') as f:
lines = f.read().split('\n')
lines = [x.strip() for x in lines if len(x) > 0 and x[0] != '#']
block = {} # info about a specific block
blocks = [] ... | 2b34df562cd04724a86cc9763a917dadb014291b | 680,751 |
from typing import Dict
from typing import Any
def get_schema_type(arg_schema: Dict[str, Any]) -> str:
"""Returns the schema type for an argument.
Args:
arg_schema: dict(str, *). Schema for an argument.
Returns:
str. Returns schema type by extracting it from schema.
"""
return ar... | 4f62bb591640ca2bccb0a111e7528b3ef582366e | 680,752 |
import argparse
def prepare_parser():
"""
Setup the program arguments.
Returns
-------
parser : argparse.ArgumentParser
Parser object set up with the program arguments.
"""
parser = argparse.ArgumentParser(
description='Save and restore qpdfview tab and bookmark sessions'
... | 414b34b3c83f03480e143527103185026be8a623 | 680,753 |
def extractScopeLFN(scope_lfn):
""" Extract the scope and LFN from the scope_lfn string """
# scope_lfn = scope:lfn -> scope, lfn
_dummy = scope_lfn.split(':')
return _dummy[0], _dummy[1] | 91d4672624b2b6f5df4f132f4da6d9016747cce5 | 680,754 |
def _get_liblinear_solver_type(multi_class, penalty, loss, dual):
"""Find the liblinear magic number for the solver.
This number depends on the values of the following attributes:
- multi_class
- penalty
- loss
- dual
The same number is also internally used by LibLinear to determin... | 9dbaaac9553a55b72a4c4f0cdec59e7526ed42b9 | 680,755 |
def set_style(style,
text_color='white',
highlight_hover=True,
mini_zoom=False,
th_mini_font_size=6,
enforce_size=False,
td_width=15,
td_height=15):
"""Imposes some styling options on a DataFrame.style object."""
prope... | d6b8ba059b001a0f53cc08311525b048a17f8c74 | 680,756 |
def _hasfield(model_fields, field_name):
"""
Check if field name exists in list of model fields
:param list model_fields: List of Django Model object fields
:param string field_name: attribute string, dotted or dunderscored.
example: 'user.first_name' or 'user__first_name'
:returns: Field obje... | 701099a73d2e46f686c7c353172dfe83573c72ec | 680,757 |
def m_get_mobile_m1_m5_key_seq1(mobilestr, tags, key_list):
"""
获取 mobile字符串在 tags字典中 1月到5月存在的key_list中key值的和的列表
:param mobilestr: 查询的手机字符串
:param tags: 含多种手机信息的字典
:param key_list: 查询的字段
:return: 该手机号1月到5月 在key_list中值的和 形成的列表
example:
:... | a3559e811aef1610f92e065133474648ed1444a7 | 680,758 |
def get_relationship_targets(goids, relationships, go2rec):
"""Get GO ID set of GO IDs in a relationship target set."""
# Requirements to use this function:
# 1) GO Terms must have been loaded with 'relationships'
# 2) GO IDs in 'goids' arguement must be present in go2rec
# 3) Arg, 'rela... | 68d0b1b53bcec5eafe06be672ecd5e5428989fd9 | 680,759 |
import math
def rh2ah(rh, t ):
"""[summary]
Args:
rh ([type]): rh min
t ([type]): temp max
Returns:
[type]: [description]
"""
return (6.112 * math.exp((17.67 * t) / (t + 243.5)) * rh * 2.1674) / (
273.15 + t
) | 4133f7aa24e2855ccbf8f9b9764b0d76646d69a7 | 680,760 |
def enum_solutions(node):
"""
>>> node = {'entry': {'lemma': u'EOS'}}
>>> enum_solutions(node)
[[u'EOS']]
>>> node = {
... 'entry': {'lemma': u'これ'},
... 'next': [
... {
... 'entry': {'lemma': u'は'},
... 'next': [
... {... | 5f1a6a7b9ed2c0667720fda7e65231fbe30915df | 680,761 |
import glob
import os
def find_svgs(directory):
"""Find all SVG files in the provided directory and all subdirectories.
:param directory: The directory to search for SVGs.
:returns: An enumerable of SVG file names.
"""
return glob.glob(os.path.join(directory, "**", "*.svg"), recursive=True) | 1eb24d7a74c84ebdb36480105a1ceb322bda94a4 | 680,764 |
import sys
def get_full_stack_desc():
"""Build full stack of Orion call"""
i = 1
frame = sys._getframe(i)
while (
"orion/core/worker/experiment.py" not in frame.f_code.co_filename
or frame.f_code.co_name.startswith("_")
):
i += 1
frame = sys._getframe(i)
stack ... | 2d23ee1c00fc5b6f74f3eaea85bf3161605dcd82 | 680,765 |
import re
def findErrorInSqlFile(sqlFile, output):
"""
function : Find error in the sql file
input : String,String
output : String
"""
GSQL_BIN_FILE = "gsql"
# init flag
ERROR_MSG_FLAG = "(ERROR|FATAL|PANIC)"
GSQL_ERROR_PATTERN = "^%s:%s:(\d*): %s:.*" % (
GSQL_BIN_FILE, sqlFile... | ce3939fae020d1dce33f70b07cd502289d221885 | 680,766 |
import glob
import os
def get_fastq_dir(fc_dir):
"""Retrieve the fastq directory within Solexa flowcell output.
"""
full_goat_bc = glob.glob(os.path.join(fc_dir, "Data", "*Firecrest*", "Bustard*"))
bustard_bc = glob.glob(os.path.join(fc_dir, "Data", "Intensities", "*Bustard*"))
machine_bc = os.pat... | ac0fa3287410051895f83ea607a645ae20e58799 | 680,767 |
def postprocess(var_list):
"""수집한 환자수 후처리
Args:
var_list: 후처리 할 문자열 list
Returns:
(list) var_list 순서대로 후처리된 결과
"""
result = []
for var in var_list:
var = var.replace(',', '').strip()
if '.' in var:
var = float(var)
elif var == '-':
... | 791ad52fdf9b532766aea7e6b92a2cb5b18abae3 | 680,768 |
def edit_distance(left_word: str, right_word: str) -> int:
""" The difference between same-length words in number of edits
The result is the edit distance of the two words (number of
substitutions required to tranform left_word into right_word).
Args:
left_word: One word to compare
rig... | 0db7798a95ac5934c75ab623b895e56bfba40035 | 680,769 |
def convert_to_undirected(G):
"""Return a new undirected representation of the graph G."""
return G.to_undirected() | 018e1a1a5773a025729560ad03a9eec85dd1e198 | 680,770 |
def evaluate_model(model, X_val, Y_val):
"""evaluate the model"""
scores = model.evaluate(X_val, Y_val, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[0], scores[0]*100))
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
return scores | 52b7b66717e734ff0b0c16d3330b88ca5971173c | 680,771 |
import numpy
def total_dipole_moment(vec):
""" Calculate the total dipole_moment value from the vector. Value
is simply the norm of the vector.
:param vector: dipole_moment vector in XYZ coords (Bohr)
:type vector: tuple
:rtype: float
"""
assert len(vec) == 3
return ... | 28536d73315dc45c520eb945ad59dd3cf1b5e1fa | 680,772 |
def make_tuple(input):
"""
returns the input as a tuple. if a string is
passed, returns (input, ). if a tupple is
passed, returns the tupple unmodified
"""
if not isinstance(input, (tuple, list)):
input = (input,)
return input | d5b6c69898c583c42dea70ecac56943dee97db92 | 680,773 |
def rawformat(x, pos):
"""
Generic number formatter to help log plot look nice
"""
if (x < 1000): return '%1.0f' % x
if (x < 10000): return '%1.1fK' % (x/1000.0)
if (x < 1000000): return '%1.0fK' % (x/1000.0)
if (x < 1e9): return '%1.1fM' % (x/1.0e6)
if (x < 1e12): return '%1.1fB' % (x/... | f7f91e32b614f910fb2b120df1e74c69e3de5270 | 680,774 |
def get_nested_attr(obj, attr, default=None):
"""Get nested attributes of an object."""
attrs = attr.split(".")
for a in attrs:
try:
obj = getattr(obj, a)
except AttributeError:
if default:
return default
else:
raise
ret... | 7f8dc82f6d08a763a0a083967ef524acbba8e983 | 680,775 |
import hashlib
def validate_proof(previous_proof, proof):
"""
Validates the new proof.
:param int previous_proof: Proof of the previous block
:param int proof: Potential proof of the next block
:return bool: True if the new proof is valid, False if not
"""
attempt = f'{previous_proof}{pr... | 1c02d5a07bc6476dd2c3a65ff2c4693d3e89d0cf | 680,776 |
def split_barcode(barcode, return_gg=False):
"""Splits a barcode sequence into part A, part C, and part B sequences."""
split = barcode.split("-")
if len(split) == 2:
# Remove the gem group from the barcode
barcode, gem_group = split
else:
gem_group = None
assert len(barcode)... | 44451b5d4f181bc7c0d9e065c9c0d21c3e26854d | 680,777 |
def undistort(image, pairs):
"""Undistort an image."""
arguments = []
for rdot, sdot in pairs:
arguments.extend(sdot)
arguments.extend(rdot)
image.distort('perspective', arguments)
return image | d6ed1da9851b82ee965118cd966201a9ac914ed8 | 680,778 |
def getBucketForDomain(domain):
""" get the bucket for the domain or None
if no bucket is given
"""
if not domain:
return None
if domain[0] == '/':
# no bucket specified
return None
index = domain.find('/')
if index < 0:
# invalid domain?
return No... | 118c5c7828ac7891eb76f2eef3019e515592b677 | 680,779 |
import math
def compute_idfs(documents):
"""
Given a dictionary of `documents` that maps names of documents to a list
of words, return a dictionary that maps words to their IDF values.
Any word that appears in at least one of the documents should be in the
resulting dictionary.
"""
# Slig... | ea62ca6d00c68c5b1ab7529445ea49952cdefde0 | 680,780 |
import csv
def _readcsv(file):
"""Read a CSV file into a multidimensional array of rows and columns."""
rows = []
with open(file, newline='') as csvfile:
reader = csv .reader(csvfile, delimiter=',', quotechar='"')
headers = next(reader, None) # headers
for row in reader:
... | f9248635d9b380e6862715bdde5d2345ecf31e42 | 680,781 |
import math
def solution(X, Y, D):
"""
This is deceptively simple but quite devious.
I have got to give it to the guys at codility here, the problem
description implies a solution to the problem that is much more complex
that is necessary. I am pretty sure that if implemented it using a while/for... | f0e9d73ae2aecb9cfd1d35cf51f7788581bd4da9 | 680,782 |
def create_tag(item, tag="a"):
""" some function to wrapp HTML-tag with data-attributes around a string"""
try:
item_text = item.text
except AttributeError:
item_text = "no text provided"
try:
item_lang = item.language
except AttributeError:
item_lang = "no lang provi... | e05567b532d8d54f437d749733d91e0c9fc98c16 | 680,784 |
def format_txt_desc(node):
"""
Formats a XML node into a plain text format.
"""
desc_buf = ''
for desc in node.childNodes:
if desc.nodeName == "#text":
desc_buf += desc.data + "\n"
elif desc.nodeName == "p":
desc_buf += desc.firstChild.data + "\n"
for chld in desc.childNodes:
if chld.nodeName ==... | b5f6050167f9b3df0e7f5aac47b3579fe35192ba | 680,785 |
import torch
def recid_evaluate_high_risk(bnn):
""" Recidivism prediction task: evaluate high-risk fraction of both groups """
samples, _ = bnn.all_bayes_samples[-1]
preds = (bnn.predict(samples, bnn.X_train, return_probs=True).mean(dim=0) >= 0.5).float()
eval_data = torch.stack((bnn.X_train_race, preds)).t()
a... | cd2dc9ab6630633a0d347e36d4618486ea4d008a | 680,786 |
def quickmafs(graph):
"""
:param graph: takes a graph as input and weighs each vertex
:return: maximum weight
"""
weight = {}
weight['[0, 0]'] = 1
# print(graph)
for node in graph:
# print(node)
for vertex in graph[node]:
try:
weight[str(vertex... | cc874a70dae5f4d1a0b27dcd07198065c30f1cdd | 680,787 |
def sum_attributes(triplet):
"""
return the sum of the attributes of a triplet
ie: triplet = (((2, 2, 2, 2), (3, 3, 3, 3), (1, 2, 3, 1)))
returns [6, 7, 8, 6] <- [2+3+1, 2+3+2, 2+3+3, 2+3+1]
"""
return [sum(a) for a in zip(*triplet)] | 5998240254da5fdeb169e7e9d18f106b13495f4a | 680,788 |
def get_Theta_ref_SH_H(Theta_ref_cnd_H):
"""(26)
Args:
Theta_ref_cnd_H: 暖房時の冷媒の凝縮温度(℃)
Returns:
暖房時の冷媒の過熱度(℃)
"""
return 4.49 - 0.036 * Theta_ref_cnd_H | 6df4b60fa62a22fe33a660e93941fff56a8b581c | 680,789 |
from typing import Union
from typing import Iterable
from typing import Any
def flatten_to_list(obj: Union[Iterable[Any], Any]) -> Union[list[Any], Any]:
"""
Flattens iterable to a non-nested list
Function ignores strings and treats as non-iterable
:param obj: iterable of nested iterables
:retur... | 4240b0399347f4c757301be106b2afdd7237acd0 | 680,790 |
def apply_fn(data: dict, fn):
""" Apply a function to all values in a dictionary.
:param data:
:param fn:
:return:
"""
for key, value in data.items():
data[key] = fn(value)
return data | 17a8d91b98e18eabf89fc52cc8087fbd15de4e78 | 680,791 |
def hitrate_inverse_to_hitrate(inv_dict, coverages):
"""Convert the "inverse hitrate dictionary" to a more traditional
lookup, using `coverages`."""
out = dict()
for cov in coverages:
choices = [k for k,v in inv_dict.items() if v <= cov]
out[cov] = 0 if len(choices) == 0 else max(choices... | bddf7882d52735910faf07de31d27b63318f0587 | 680,792 |
def clean_team_name(team_names):
"""Take a list of team_names, modify the names to match the format specified in br_references, and return a new list
Args:
team_names: a list of team_names to be checked for validity, and if needed, modified
"""
new_team_names = []
for team in team_names:
... | 792c06197c999e4480f64560500245d4c3b5639c | 680,793 |
def centroide(DF):
""" DataFrame -> DataFrame
Hypothèse: len(M) > 0
rend le centroïde des exemples contenus dans M
"""
return DF.mean().to_frame().transpose() | f1e8e4678eae6d5d9190688eff2ef870b30f1121 | 680,794 |
from typing import List
import subprocess
import click
def run_bitwarden_command(args: List[str]) -> str:
"""
Call `bw` with the provided arguments and return whatever it gives on
standard out. Complain if the command exits with a non-zero status code.
"""
cmd = ["bw"] + args
try:
res... | 16572a826a226d91791251937280837356e7cf83 | 680,795 |
import numpy
def smooth(v: numpy.ndarray) -> numpy.ndarray:
"""
Smooth a vector that is oscillating.
Parameters
----------
v : 1-D array
The oscillating vector you want to smooth.
Returns
-------
sv : 1-D array
The smoothed vector.
"""
dim = len(v)
smat = ... | 3b1f8f2dfe85af5ce570298d102e5d5d02b7eed4 | 680,796 |
import random
def getName():
""" allows for random human names"""
name = ""
for _ in range(5):
char = chr(random.randint(97, 122))
if char != "\n":
name += char
else:
name += " "
return name | 454a7fb45bb32288d1b2014a420eb5a23ec1a175 | 680,797 |
def _starlist_fn(request):
"""Starlist filename"""
return request.param | b68bd4ff7b702a0cd73b660432504fd6547da8e4 | 680,798 |
def datestring_to_sql_parameter(datestring):
"""
Converting date string into a dictionary suitable for the sql parameters
:param datestring (string): string that contain a start and end date in the format %Y%m%d_to_%Y%m%d
:return date_sql_param (dict): dictionary with the date parameters defined to con... | f141a317ac349b633fc57e2a5cdac06b67533a55 | 680,800 |
from typing import Iterable
from typing import Callable
def any_matches(iterable: Iterable, cond_fn: Callable = bool) -> bool:
"""
Returns `True` if `cond_fn` is `True`
for one or more elements in `iterable`.
Parameters
----------
iterable : Iterable
The iterable to be checked
con... | 902a90388a34330a2c39af35025f8e2c41426deb | 680,801 |
from typing import Set
def get_valid_name_permutations(param_name: str) -> Set[str]:
"""Get all underscore permutations for provided arg name"""
return {
"_",
param_name,
f"_{param_name}",
f"{param_name}_",
} | 0cbf5e751307ec24665ec8f0cb9657c6e17b1b75 | 680,802 |
import numpy
def _compute_strategy_coefficient(distances, strategy, labels):
"""
Creates a matrix
"""
if strategy in ('gain', 'gain_p'):
ar = numpy.arange(distances.shape[0])
dist = distances[ar, labels]
return distances - dist[:, numpy.newaxis]
raise ValueError( # pragma:... | ed77a56d3d5d78335559432b5d470cdce2206387 | 680,803 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.