content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import MutableMapping
from typing import Callable
from typing import Any
def _create_before_send_filter(tags: MutableMapping[str, str]) -> Callable[[Any, Any], Any]:
"""Create a filter that adds tags to every events."""
def do_filter(event: Any, hint: Any) -> Any:
event.setdefault("tags",... | 84f0ba6757cef10e39f447baeefb305b00e976bc | 219,118 |
def tpc_h17(con, BRAND="Brand#23", CONTAINER="MED BOX"):
"""Small-Quantity-Order Revenue Query (Q17)
This query determines how much average yearly revenue would be lost if
orders were no longer filled for small quantities of certain parts. This
may reduce overhead expenses by concentrating sales on larg... | 4f2214192ea084c05a257dd9dac7785fc54ad8ec | 66,674 |
def string_list(s):
"""Convert a string to a list of strings using .split()."""
return s.split() | 7a1882fc3ca6264929e80f14d3d88f156fe9143d | 507,725 |
def sanitize(extracted_df):
"""
Drops all rows that have invalid values
:param extracted_df: The dataframe generated from the data extracted from the loaded file
:return: A dataframe with no invalid values
"""
columns = extracted_df.columns
cleaned_df = extracted_df.copy()
print('Removi... | ecdbe067b94e3836421e51df823383d9566e0bcf | 403,526 |
def get_dimentions_factors(strides_schedule):
"""
Method calculates how much height and width will be increased/decreased basen on given stride schedule
Args:
strides_schedule: A list of stride tuples(heigh, width)
Returns:
Two numbers that tells how many times height and width will be in... | 9905936f6c06dc243009dc5af2d8191c8ee6a9e7 | 537,547 |
import itertools
def _group_by_key(in_file, sep='\t'):
"""Turn this:
['x\ta', 'x\tb', 'y\tc']
into this:
[('x', ['a', 'b']), ('y', ['c'])]
"""
group_key = lambda line: line.split(sep, 1)[0]
return itertools.groupby(in_file, key=group_key) | 94ad37296e356993257808382f7a16123d0e2c90 | 157,926 |
import copy
import collections
def stringify_keys(dictionary: dict):
"""
This helper function will stringify all keys in the given
dictionary.
For example:
> from apps.authentication.models.user import Jobs
> data = { Jobs.PTA: True }
> stringify_keys(data)
{ "PTA": Tr... | db5a08fc106ce01ef90d37e896a24db2d143ce13 | 635,207 |
import secrets
def generate_token_urlsafe(unique=False, nbytes=32):
"""Generate an URL-safe random token."""
return secrets.token_urlsafe(nbytes=nbytes) | 5bdab6879f241a7459653e5ec363110263f0c171 | 702,380 |
import zipfile
def unzipper(zip_file, outdir):
"""
Unzip a given 'zip_file' into the output directory 'outdir'.
Return the names of files in the archive.
"""
zf = zipfile.ZipFile(zip_file, "r",
allowZip64=True)
filenames = zf.namelist()
zf.extractall(outdir)
... | 515224a3f1880977979a27c0e9aef199c12abe64 | 350,816 |
import re
def get_table_dividers(table):
"""
Receives a results table
Returns a list of divider rows (------)
"""
return [len(re.findall(r"^-{3,}$", line)) for line in table.split("\n")] | da3f971fd81207ab8d1a78605c31affb105ad968 | 669,514 |
import re
def findExtendedCode(message):
"""get extended codes, which give more information than standard 3 digit codes
Args:
message: message from email server
Returns:
Extended code if found, None otherwise
"""
#references:
#https://www.iana.org/assignments/smtp-enh... | 751390084521234412fa313c5e2bc1e985a7f812 | 435,157 |
def as_snake_case_prefix(name):
""" Convert PascalCase name into snake_case name"""
outname = ""
for c in name:
if c.isupper() and len(outname) > 0:
outname += '_'
outname += c.lower()
return outname + ('_' if name else '') | 6a06dcc0b1cc4423c026f880005f2e3f9827ae46 | 151,561 |
import math
def gc_distance(point1, point2):
"""returns distance between point1 and point2 using great circle equation"""
lon1, lat1 = point1[0], point1[1]
lon2, lat2 = point2[0], point2[1]
lat1, lat2, lon1, lon2 = map(math.radians, [lat1, lat2, lon1, lon2])
radius = 6378 # WGS84 equatorial radius in km
trig =... | 0e6afd485f9150e673a618657b8ac486e4146647 | 169,001 |
from typing import Any
from typing import Optional
def parse_int(string: Any, base: int = 10) -> Optional[int]:
""" safely convert an object to int if possible, else return None """
if isinstance(string, int):
return string
try:
return int(string, base=base)
except Exception:
... | 3078a2ea8c259ca72706dbef4d223559e01f557a | 232,270 |
import re
def extract_redundancy_factor(oclass):
"""Extract the redundancy factor from an object class.
Args:
oclass (str): the object class.
Returns:
int: the redundancy factor.
"""
match = re.search("EC_[0-9]+P([0-9])+", oclass)
if match:
return int(match.group(1))... | 5b619d9d9d4194f5926b9ec65861053c1152ae48 | 87,604 |
def make_alignment_line(strand, kmer, prob, event):
"""Convert strand, kmer, probability and event to a correctly formatted alignment file line
:param strand: 't' or 'c' representing template or complement strand of read
:param kmer: nucleotide kmer
:param prob: probability of kmer coming from certain e... | 551f3739bc46aae88d266605604ec12a0f5a1e4f | 443,757 |
def get_domain_label(domain):
"""
"." is not a valid character in a prometheus label and the recommended
practice is to replace it with an "_".
"""
return domain.replace('.', '_') | 7ca6d78852294c9c2d35e250114f647bbac3829e | 307,839 |
def sanitize(str, strip=[" "], remove=["\r", "\n"]):
"""Return a whitespace-stripped, newline-stripped string.
Args:
str (str): The string to be sanitized.
strip (str[], optional) Additional things to be stripped.
remove (str[], optional) Additional things to be removed.
Returns:
(str) ... | d84d0f021cbaa283ee0cfe4128c362188e4dbef2 | 616,041 |
def fetchone(cursor):
"""
Fetch one row from the given cursor
Params:
cursor (Cursor) : Cursor of previously executed statement
Returns:
dict : Dict representing the records selected indexed by column name
"""
if cursor:
return dict(zip((d.name for d in cursor.description... | 1bff5e467c25db6f1d3a3d63af456812b93db676 | 237,019 |
from typing import List
def read_files(file_paths: List[str]) -> List[str]:
"""Read all of the files in the list of files provided, returning a list of strings.
Args:
file_paths List[str]: List of files to be read.
Returns:
List[str]: List of documents as strings.
"""
documents ... | 073e2976736ceed988c503d2347db5528392713c | 346,929 |
import inspect
def _wrap_asgi_coroutine_func(asgi_impl):
"""Wrap an ASGI application in another coroutine.
This utility is used to wrap the cythonized ``App.__call__`` in order to
masquerade it as a pure-Python coroutine function.
Conversely, if the ASGI callable is not detected as a coroutine funct... | fe54d656ba65615fbbb090666b29d63e5c70bc28 | 247,525 |
def get_genres(anilist):
"""
Get the genres for the search.
:param anilist: The anilist search result.
:return: the genres for the search.
"""
lst = anilist.get('genres', [])
if not lst:
return
return [s for s in lst if s] | 18bb3a9643e38ec3b34f709bc8c08950991e3112 | 550,364 |
import torch
def log_interpolate(log_a, log_b, alpha_logit):
"""Numerically stable implementation of log(alpha * a + (1-alpha) * b)."""
log_alpha = -torch.nn.functional.softplus(torch.tensor(-alpha_logit))
log_1_minus_alpha = -torch.nn.functional.softplus(torch.tensor(alpha_logit))
y = torch.logsumexp... | b07d8e9fdfc6a002d46dd84551408aef863c3867 | 618,012 |
def train_matrix_info_from_model_id(db_engine, model_id):
"""Get original train matrix information from model_id
Args:
db_engine (sqlalchemy.db.engine)
model_id (int) The id of a given model in the database
Returns: (str, dict) matrix uuid and matrix metadata
"""
get_train_... | 0b5aab871c84a0af769c11ec5981e850bd14fb22 | 528,613 |
import re
def trim_whitespaces(string: str) -> str:
"""Replaces all multiple whitespaces with one and calls default strip function on a result
Example:
>>> trim_whitespaces('hello friend')
hello friend
>>> trim_whitespaces(' hello old friend ')
hello old friend
... | cc57741b498951d80191c2920942df519d0cb521 | 608,855 |
def _cast_safe(self, value, cast_type = str, default_value = None):
"""
Casts the given value to the given type.
The cast is made in safe mode, if an exception
occurs the default value is returned.
:type value: Object
:param value: The value to be casted.
:type cast_type: Type
:param ca... | f89300e21a1758c892eb42ad35696a56f77313b5 | 71,584 |
def compute_f1(precision, recall):
"""
Compute F1 score.
F1 = 2 * P * R / (P + R)
"""
try:
f1 = 2 * precision * recall / (precision + recall)
except ZeroDivisionError:
f1 = 0.
return f1 | 08531e4a98f052c3fe57587edf4823b864f1780e | 496,209 |
def add_token_to_headers(token, headers=None):
"""Add bearer token to header dict."""
if headers is None:
headers = {}
return {**headers, **{"Authorization": "Bearer " + token["access_token"]}} | fbf122618881f5235551eaefd47c14c78092394b | 144,555 |
def getTranslation(m):
"""
get the translation vector of a homogeneous 4x4 row-major transformation matrix
"""
return [m[3], m[7], m[11]] | 6aba45f7c922a2b3be45b043e1b6c83095564feb | 228,048 |
def _is_string_or_bytes(s):
"""Returns True if input argument is string (unicode or not) or bytes.
"""
return isinstance(s, str) or isinstance(s, bytes) | d7b098424d695d3c510fd859b9bf354a262527e3 | 299,497 |
import shutil
def get_program_path(aliases):
"""Get programs path given a list of program names.
Parameters:
aliases (list): Program aliases, e.g. ["diamond", "diamond-aligner"]
Raises:
ValueError: Could not find any of the given aliases on system $PATH.
Returns:
Path to progr... | 270a572928b3e95a6c6b46277659f86441f542a4 | 432,686 |
def map_element(element):
"""Convert an XML element to a map"""
# if sys.version_info >= (2, 7):
# return {e.tag: e.text.strip() for e in list(element)}
# return dict((e.tag, e.text and e.text.strip() or "")
# for e in list(element))
return dict((e.tag, e.text) for e in list(element)... | b8a84be91f28757f28622a5909a569d35e38282f | 35,627 |
def truncate(message, from_start, from_end=None):
"""
Truncate the string *message* until at max *from_start* characters and
insert an ellipsis (`...`) in place of the additional content. If *from_end*
is specified, the same will be applied to the end of the string.
"""
if len(message) <= (from_start + (fr... | 44e37164aff5912d37a3dc27217e498b1c14efff | 20,112 |
def full_model_name(model, sep='.'):
"""Returns the "full name" of the given model, e.g. "contacts.Person" etc.
"""
return model._meta.app_label + sep + model._meta.object_name | 508ba659124a50d7b0c2e7a4c976e2091cb50974 | 157,769 |
import requests
from bs4 import BeautifulSoup
def get_holdings(base_url, mms_id, api_key):
"""
Get the holdings id(s) for the bib record via the Alma API.
"""
holdings_list = []
query = 'bibs/{}/holdings?apikey={}'
r = requests.get(''.join([base_url, query.format(mms_id, api_key)]))
soup =... | 8ff8790043b9fc9ea50c7521bc27a8314e8033be | 346,954 |
from typing import Dict
from typing import Any
def recursive_merge_dict(dict1: Dict[str, Any],
dict2: Dict[str, Any]) -> Dict[str, Any]:
"""Merge two dictionaries into a third dictionary recursively.
Args:
dict1: First dictionary to be merged.
dict2: Second dictionary to be merge... | ce659569baa270a577e190d7572f5758e62e45cd | 364,368 |
def date_index(start_year, date):
"""Returns the number of months that have passed since January of start_year"""
return (date.year - start_year) * 12 + (date.month - 1) | 1dafa11fff2e696e0bd293e880df2f02cca38460 | 587,935 |
from typing import List
def load_tokens(path: str) -> List[str]:
"""Loads the current tokens from file"""
with open(path, 'r') as f:
res = [x.strip() for x in f.readlines()]
return res | 13f1ffb5e462d2360ea6dbea4354141d7e21db64 | 546,852 |
import ipaddress
def ip_version(value):
"""
Returns version of passed IP address.
"""
return ipaddress.ip_address(value).version | 15e2a32b477918d6722ddd65d574d71236d34699 | 458,348 |
import math
def example_function(x):
"""Compute the square root of x and return it."""
return math.sqrt(x) | 0c9fa02b3ef478dd6493b5ebb6a47f68477a10f8 | 563,891 |
def get_report_from_trajectory(traject_path, report_base):
"""
The format is usually <name>_<number>.pdb
"""
name_number = traject_path.split(".")
_, number = name_number[0].split("_")
return report_base+"_"+number | 0fa1218740de8567d3cdfc09beb1b551941944e2 | 98,383 |
def parse_config_list(s):
"""util to convert X = A,B,C config entry into ['A', 'B', 'C']"""
return [x.strip() for x in s.split(',') if x.strip()] | 7286a6038d28a52cb870b22195a958be09e031cd | 492,483 |
def toint2(i):
""" Convert a number to a binary string of length 8 """
return f'{i:08b}' | 6b5abb4409349db3ec13b26f64a3c27fc4e4c470 | 584,804 |
def motp(df, num_detections):
"""Multiple object tracker precision."""
return df['D'].sum() / num_detections | 51d1f0ef3b2353ff8a008642eeacbe0d6fe5a0ff | 204,835 |
def get_message(tweet):
"""
Get the message attribute on a Tweet object.
The attribute available depends on the parameters on the query to Twitter.
"""
try:
message = tweet.full_text
except AttributeError:
message = tweet.text
return message | 7cffb76ee7795095857a48c7780f4362d37869e3 | 649,631 |
def calc_tcv(signal, threshold=2.0):
"""
Calculate the count of threshold crossings for positive and negative threshold.
:param signal: input signal
:param threshold: threshold used for counting
:return: number of times the threshold was crossed
"""
tcv = 0
prev = 0.0
tm = -threshol... | cc2c46b114d43321349098a663fe7d0328879672 | 242,901 |
def InstanceOverlap_OLD(instance1,instance2):
"""Returns True if given instances share a vertex."""
for vertex1 in instance1.vertices:
if vertex1 in instance2.vertices:
return True
return False | 0bbc42cc09ea0f67b8a04772eb0581b081dbb6dd | 689,653 |
def add_offset_to_target(example_strings, targets, offset):
"""Adds offset to the targets.
This function is intented to be passed to tf.data.Dataset.map.
Args:
example_strings: 1-D Tensor of dtype str, Example protocol buffers.
targets: 1-D Tensor of dtype int, targets representing the absolute class
... | e6659a2c22bf5e9a4d73e614ce3b67d859047a39 | 236,135 |
import re
def safe_name(name):
"""
Converts IAM user names to UNIX user names
1) Illegal IAM username characters are removed
2) +/=/,/@ are converted to plus/equals/comma/at
"""
# IAM users only allow [\w+=,.@-]
name = re.sub(r'[^\w+=,.@-]+', '', name)
name = re.sub(r'[+]', 'plus', na... | 077cb576f3c8cb6b4da905ba9c6f6410fbf691fe | 59,456 |
def _sortValue_weightValue(font):
"""
Returns font.info.openTypeOS2WeightClass.
"""
value = font.info.openTypeOS2WeightClass
if value is None:
value = -1
return value | 7cb5d9d44f1ee434e7da09d8c5503f48b822ef3a | 276,575 |
import hashlib
def hash_zipfile_contents(zf):
"""Returns a hash of a zipfile's file contents.
Ignores things like file mode, modtime
"""
h = hashlib.blake2b()
for name in zf.namelist():
h.update(name.encode("utf-8"))
h.update(zf.read(name))
return h.hexdigest() | 9530f28abbff3ffc88cf3e097c474836e42f067c | 546,641 |
def flatten_sub(sub, game_id):
"""Flatten the schema of a sub"""
sub_id = sub[0]
sub_data = sub[1]
return {'game_id': game_id,
'sub_id': sub_id,
'sub_type': sub_data['type'],
'time_of_event(min)': (sub_data['t']['m'] + (sub_data['t']['s'] / 60 )),
'team_i... | d6557b01f6f2f11c829e1094b318bf2587c74977 | 687,257 |
import jinja2
def create_main_protocol_hoc(
template_path, protocol_definitions, rin_exp_voltage_base, mtype
):
"""Create main_protocol.hoc file.
Args:
template_path (str): path to the template to fill in
protocol_definitions (dict): dictionary defining the protocols
rin_exp_volta... | 8374b01151f8e624f10f4ad2f2e9db7266e88bf1 | 604,415 |
import requests
def search_onda_catalog(search, fmt='json') -> dict:
"""Search on ONDA Catalog."""
base_uri = 'https://catalogue.onda-dias.eu/dias-catalogue/Products'
query = {
'$search': search,
'$format': fmt
}
req = requests.get(base_uri, params=query, timeout=90)
req.rai... | f3a50006ddaff236b2f989f5b41834ff41cb448a | 388,693 |
def default_func(entity, attribute, value):
"""
Look in the entity for an attribute with the
provided value. First proper attributes are
checked, then extended fields. If neither of
these are present, return False.
"""
try:
return getattr(entity, attribute) == value
except Attrib... | 0ec6636c20d3f5eedb7a7c1f2457f72ecddb7545 | 20,852 |
def get_handcrafted_feature_names(platform):
"""
Returns a set of feature names to be calculated.
Output: - names: A set of strings, corresponding to the features to be calculated.
"""
names = set()
###############################################################################################... | ccdf430b0403c1152f40c9c0bdf5fbb380d8f0c1 | 681,137 |
def eCF(i):
"""
Returns the first i terms of the (aperiodic) continued fraction
representation of e.
"""
return [2] + [int((a+1) / 3 * 2) if a % 3 == 2 else 1 for a in range(1, i)] | 4a16c01332ccb72923c8062440f928269a0e8dda | 176,194 |
def path_to_image_name(path, class_name):
"""
for paths of the following structure:
E:\ILSVRC2017\images\original\n01531178\n01531178_2421.JPEG
returns the image name, e.g. n01531178_2421
"""
t1 = path.split(class_name, 1)[1]
t2 = t1.split('.', 1)[0]
t3 = t2.split('\\', 1)[1]
ret... | b5e306b7d2a2c516b5f304375f793fd966843e5c | 58,651 |
def convert_8_int_to_tuple(int_date):
""" Converts an 8-digit integer date (e.g. 20161231) to a date tuple (Y,M,D).
"""
return (int(str(int_date)[0:4]), int(str(int_date)[4:6]), int(str(int_date)[6:8])) | 733982c2de2c74c5116c15a1a91adf03c3bd6871 | 21,325 |
def normalize_data_raw(data_tbl):
"""Return the data table without normalization."""
return data_tbl | 18fc7f93cf41d671e5fcb61d3f5be44c85c6161c | 166,216 |
def lane_lead(csd10: float, xpd10: float, total_cs: float, total_xp: float, team_prox: float) -> float:
"""
Returns the lead a player has in lane in terms of cs and xp relative to total cs and xp between the two laners
Formula: (team_prox * (csd10 + xpd10)) / (total_xp + total_cs)
:param csd10: Differ... | 639e9c0e2cde9a24662e581fc842fb3f5a6006ff | 200,390 |
def arg_name(name):
"""Get the name an argument should have based on its Python name."""
return name.rstrip('_').replace('_', '-') | b0f2ff12efa2685f914be95b816a7109d75df173 | 351,992 |
from datetime import datetime
def find_age_band(birth_date: str, end_date: datetime) -> str:
"""Given the birth date, finds the age_band for PEPFAR disaggregation."""
birth = datetime.strptime(birth_date, '%Y-%m-%d')
age = int((end_date - birth).days / 365.25)
if age < 1:
return '0-1'
if age <= 4:
r... | 92e8e37b898b873f5b254de5dc1c9ff2d2909420 | 196,566 |
import pickle
def load_class_ids(class_info_file_path):
"""
Load class ids from class_info.pickle file
"""
with open(class_info_file_path, 'rb') as f:
class_ids = pickle.load(f, encoding='latin1')
return class_ids | 65025910226a2d0391108e5dde8cee5c67f4ef39 | 487,820 |
def binary_dominates(a, b):
"""Returns whether a binary dominates b"""
for ai, bi in zip(a, b):
if bi > ai:
return False
if a == b:
return False
return True | c48e0b4712d958b52cb3a4c53232a131ceefc986 | 592,160 |
def central_credible_interval(samples, alpha=0.05):
"""The equal-tailed interval containing a (1-alpha) fraction of the posterior samples.
Parameter samples: The posterior samples (array like)
Parameter alpha: The total size of the tails (Float between 0 and 1)
Returns: Left and right interval bounds... | cb9d9379234d5cb2db8a3015ef66ef7d4a384e90 | 613,395 |
def findFront(start):
"""
start: a Frob that is part of a doubly linked list
returns: the Frob at the beginning of the linked list
"""
if start.getBefore() == None:
return start
return findFront(start.getBefore()) | c91ce2b4ee1ec638bb8e0b9db3ad7075ce436f35 | 486,257 |
def parse_sections(lines):
"""Parse the input document into sections, separated by blank lines.
A list of lists is returned. Each item is the list of lines for a section.
"""
secid = 0
section = []
for line in lines:
if not line.strip():
secid += 1
continue
... | 6127f8bfbec56e77e475684d626e44cb75ac8daa | 39,386 |
from pathlib import Path
import base64
def pdf_preprocess(pdf):
"""
Load pdfs from local filepath if not already b64 encoded
"""
path = Path(pdf)
if path.exists():
# a filepath is provided, read and encode
with path.open("rb") as f:
return base64.b64encode(f.read()).dec... | 17b2642bc90b4e7da01246a2f94c3c5f029e05d7 | 386,507 |
def numToLetter(N, ABC=u'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ):
"""
Converts a number in to a letter, or set of letters, based on the contents of
ABC. If ABC contains the alphabet (which is the default behaviour) then for a
number n this will result in the same string as the name of the nth column in
a normal spreads... | 9737918897606ef642a1747016f07a4e72cb5157 | 376,198 |
def _safe_divide(a: int, b: int):
"""Divides a and b as a/b if 0 < a <= b. Otherwise, raises ValueError.
Args:
a: Numerator.
b: Denominator.
Returns:
Float of division result.
"""
if a < 0:
raise ValueError('a ({}) < 0'.format(a))
elif a > b:
raise ValueError('a ({}) > b ({})'.format(... | 5747ebf93e33c9e09141f4512ab2e1192230d0e0 | 343,474 |
def get_lock_name(file_path):
"""
Returns lock file of the given file
:param file_path: str
:return: str
"""
return '{}.lock'.format(file_path) | 5796f5ecab4570355f8985ebb7e41b14d0d46ac0 | 284,176 |
import math
def directions(o, t):
"""Compute a list of directions o -> t unit length."""
assert len(o) == len(t)
result = []
for j in range(len(o)):
dx = t[j][0] - o[j][0]
dy = t[j][1] - o[j][1]
l = math.sqrt(dx * dx + dy * dy)
result.append((dx / l, dy / l))
re... | 4a85f552197668948864d58ca1fab8563d957a00 | 315,153 |
def device_properties() -> dict:
"""
Fixture that returns device_properties to be provided to the device under test.
This is a default implementation that provides no properties.
:return: properties of the device under test
"""
return {} | 6e400fcce6efc7ef850ab7db57de9fb034480321 | 381,192 |
def fuel_name_matching(name, blacks, browns, petcoke):
"""
Harmonize fuel names
:param name: Original name
:param blacks: Hard coal name map
:param browns: Lignite and brown coal name map
:param petcoke: Other fuels map
:return: Harmonized name
"""
if name in blacks:
return "... | 72a49b2a17d58ff76d24672eb6eba09de235ebb5 | 316,042 |
from pathlib import Path
def data_files(data_dir, data_types):
"""Recursively return a list of data files."""
data_dir = Path(data_dir)
data_files = []
for d in data_types:
files = [p.relative_to(Path("embers")) for p in data_dir.rglob(d)]
data_files.extend(files)
return [p.as_posi... | ec12921efa84266013b46176bc79cc35b7f0f400 | 268,276 |
def GetColor(status):
"""Given a job status string, returns appropriate color string."""
if status.strip() == 'pass':
color = 'green '
elif status.strip() == 'fail':
color = ' red '
elif status.strip() == 'warning':
color = 'orange'
else:
color = ' '
return color | 168e1015a8b2cc17fd3f5fb60d1da7951746d0fa | 187,453 |
def n_params(model):
"""Return the number of parameters in a pytorch model.
Args:
model (nn.Module): The model to analyze.
Returns:
int: The number of parameters in the model.
"""
pp = 0
for p in list(model.parameters()):
nn = 1
for s in list(p.size()):
... | 02bf6c5cf4c3a8cbbfce2bdf1525bcdc73aac686 | 644,754 |
def get_formatted_name(first, last, middle=''):
"""Return a full name, neatly formatted."""
if middle:
return first.title() + ' ' + middle.title() + ' ' + last.title()
return first.title() + ' ' + last.title() | 0ba3adc54bf71067c0cc66ec74d34fa40a29c799 | 537,983 |
import random
def generate_random_integers(number_values, min_val, max_val):
"""Generate a list with `n` random integers between a `minimum` and a `maximum`.
Args:
number_values (int): Number of values to generate.
min_val (int): Minimum value.
max_val (int): Maximum value.
Returns... | c1eb1482b559d5e9a38c38b07cb4b868ca902d9a | 457,857 |
def square_a_list(a_list):
"""Return a list with every item squared."""
return [item * item for item in a_list] | 2f8ea43549909e90ef8f2873987371c20bd67fa9 | 130,058 |
import re
def no_to_be(f, e):
"""
Removes 'to' or 'be' or both of those tokens in the beginning of phrases
For example:
be known -> known
to drink -> drink
:param f:
:param e:
:return:
"""
e_ = re.sub('^(to\s)?(be\s)?', '', e)
if e != e_:
print('> NO_TO_BE: %... | 4e71510b0643e478c9d973458f19b98803d6ba02 | 360,589 |
def get_max_message_size(form):
"""Get max message size (in bytes)."""
size = form.get('max_message_size')
try:
size = int(size)
except:
size = 0
return size | 413eeaacf91ff9ea7b3082fcc2f9986fa940f9a3 | 181,244 |
def tb(tb):
"""Transform the tb dataset according to what was found in the explaratory
analyses, available on sp_np.ipynb
1. Select only 'journal' and 'year' columns
2. Rename these two columns to 'Journal' and 'Year', with capitalization
3. Add a column named 'Source', with all rows = 'TreatmentBa... | dcb4f6a69033e4ef779129d7c0b58715a254536d | 576,148 |
from typing import Iterable
def to_abs_coord(v, mat):
"""
Change the local vertices coordinate to absolute coordinate
:param v: vector or a list of vertices
:param mat: matrix_world
:return: the Absolute vertices
"""
if isinstance(v, Iterable):
list_verts = []
for i in v:
... | dea20a5e0e980beb41c5b4efc358958895336b20 | 623,120 |
def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):
""" Format the error message for when __array_ufunc__ gives up. """
args_string = ', '.join(['{!r}'.format(arg) for arg in inputs] +
['{}={!r}'.format(k, v)
for k, v in kwargs.item... | 4620772f4521325e66798c57e501ffd88ab991d1 | 692,705 |
def get_es_master(es_algorithm, logger, log_dir,
stubs, bucket, experiment_name, credential):
"""Instantiate an evolution strategic algorithm master.
Return an ES algorithm master from the algorithms package.
Args:
es_algorithm: algorithms.*. ES algorithm.
logger: logging... | 9191ec1a6433206c93091423d32af35081ac7e39 | 309,184 |
def conseq(cond, true, false):
"""
Behaves like the tenary operator.
"""
if cond:
return true
else:
return false | 9ed23d6d9aa6cc93c902247dd7842f4a86675b23 | 692,196 |
import time
def compose_query_sql(measurement, limit, start_date, end_date, condition=None):
"""
根据条件构建查询metric db的sql语句
:param measurement: 表
:param limit: 条数限制
:param start_date: 查询起始日期
:param end_date: 查询结束日期
:param condition: 查询附带条件
:return: 查询的sql语句
"""
# 将年月日转换为时间戳,便于查询
... | a8e8f87e90e86be4eff55dc013ad7bbad97250de | 135,759 |
def _remove_addtl_whtspace(text: str) -> str:
"""Removes addtl. whitespace, newlines, etc. from a string."""
return " ".join(text.split()) | d201114d55700108037c4760a7fdf4f2a8faaf73 | 512,531 |
def check_nmap_file(file_path):
"""
Checks if file is oX xml output nmap file
"""
with open(file_path,'r') as check:
data = check.readlines()
if r"<?xml" in data[0] and r"<!DOCTYPE nmaprun" in data[1]:
return True
else:
return False | 7272e31032339ac8a11047e8e47873ff76d782e9 | 174,932 |
import torch
def get_mask(tensor, lengths):
"""
Generates the masks for batches of sequences.
Time should be the first axis.
input:
tensor: the tensor for which to generate the mask [N x T x ...]
lengths: lengths of the seq. [N]
"""
mask = torch.zeros_like(tensor)
for i in... | 75b82fe3554eb838c0ab041e258f0a1b973d3dd9 | 183,875 |
def _count_worker(cluster_spec):
"""Counts the number of workers in cluster_spec.
Workers with TaskType.WORKER and TaskType.MASTER are included in the return
value.
Args:
cluster_spec: a ClusterSpec instance that describes current deployment.
Returns:
The total number of eligible workers.
If '... | bb31ea27c624ba93c3d6c33795fea1ca59d5256a | 382,208 |
def __randomize(items, random_state):
"""Returns a List containing a random permutation of items"""
randomized_items = list(items)
random_state.shuffle(randomized_items)
return randomized_items | 4671d051c29fabc0cd36bfbddacdd02e6f7a4056 | 293,960 |
def _hand_copy_line_to_line(original_object, new_object):
"""Copies one class object attributes to another class object"""
new_object.action_amount = original_object.action_amount
new_object.action_from_player = original_object.action_from_player
new_object.all_in = original_object.all_in
new_object... | 485249f04243051e3607c94728b9b84318f242ab | 576,128 |
def get_dictvals(mydict):
"""This function recursively gets all non-dict items in a hierarchical dict data structure. The order of the items have no intended meaning.
e.g.
myheir = {
0: '0.0',
1: '0.1',
2: {0: '1.0', 1: '1.1'},
3: {0: '1.2', 1: {0: '2.0', 1: '2.1', 2: {0: '3.0'}, 3:'2.2'}},
4: {0: '... | 2d94b21224090a49f60ae3ca89c06458ae29e896 | 581,030 |
def panel_to_multiindex(panel, filter_observations=False):
"""Convert a panel to a MultiIndex DataFrame with the minor_axis of the
panel as the columns and the items and major_axis as the MultiIndex (levels
0 and 1, respectively).
Parameters
----------
panel : a pandas Panel
filter_observa... | 37a90ba6f7e9f1b022dc87c0d3b9524509a6742a | 665,064 |
def percentage(df, new_column, column, group_cols=None):
"""
Add a column to the dataframe according to the groupby logic on group_cols
:param df: Dataframe
:param new_column: name of the new column
:param column: name of the desired column you need percentage on
:param group_cols: (str | list o... | 6c6a8f7f890431eee70b1ba0e5da152e48f190d4 | 434,786 |
import math
def sqrt(x):
"""Returns square root of x value"""
return math.sqrt(x) | 4252f3d464250cd8f63412473f5707ccdfcec95b | 625,978 |
def command_result_processor_parameter_extra(parameter_values):
"""
Command result message processor if received extra parameter(s).
Parameters
----------
parameter_values : `str`
Extra parameters.
Returns
-------
message : `str`
"""
message_parts = []
... | a135e54617e30189cef66bf0c6ee6404ec9dbf7e | 294,098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.