content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def reverse_dict_old(dikt):
"""
takes a dict and return a new dict with old values as key and old keys as values (in a list)
example
_reverse_dict({'AB04a':'b', 'AB04b': 'b', 'AB04c':'b', 'CC04x': 'c'})
will return
{'b': ['AB04a', 'AB04b', 'AB04c'], 'c': 'CC04x'}
"""
new_dikt = {... | 50155858fbbe52dc8daae66e6a94c8885b80ba05 | 5,971 |
def get_card_names(cards):
"""
:param cards: List of card JSONs
:return: List of card names (str)
"""
names = []
for card in cards:
name = card.get("name")
names.append(name)
return names | a30ad1ef7d8beaab0451d6f498254b0b5df3cf6d | 5,980 |
import re
def clean_value(value, suffix):
"""
Strip out copy suffix from a string value.
:param value: Current value e.g "Test Copy" or "test-copy" for slug fields.
:type value: `str`
:param suffix: The suffix value to be replaced with an empty string.
:type suffix: `str`
:return: Strippe... | d2ec3b3affbf71411039f234c05935132205ae16 | 5,983 |
def config_split(config):
"""
Splits a config dict into smaller chunks.
This helps to avoid sending big config files.
"""
split = []
if "actuator" in config:
for name in config["actuator"]:
split.append({"actuator": {name: config["actuator"][name]}})
del(config["actua... | 2006534ece382c55f1ba3914300f5b6960323e53 | 5,985 |
import colorsys
def hex_2_hsv(hex_col):
"""
convert hex code to colorsys style hsv
>>> hex_2_hsv('#f77f00')
(0.08569500674763834, 1.0, 0.9686274509803922)
"""
hex_col = hex_col.lstrip('#')
r, g, b = tuple(int(hex_col[i:i+2], 16) for i in (0, 2 ,4))
return colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0) | a80e9c5470dfc64c61d12bb4b823411c4a781bef | 5,987 |
def tousLesIndices(stat):
"""
Returns the indices of all the elements of the graph
"""
return stat.node2com.keys()
#s=stat.node2com.values()
global globAuthorIndex
global globTfIdfTab
#pprint(globAuthorIndex)
#pprint(stat.node2com.values())
#glob node->index
return [glo... | fa847ee3913d521778ee3462c8e946f0ff001c76 | 5,989 |
def calculate_gc(x):
"""Calculates the GC content of DNA sequence x.
x: a string composed only of A's, T's, G's, and C's."""
x = x.upper()
return float(x.count('G') + x.count('C')) / (x.count('G') + x.count('C') + x.count('A') + x.count('T')) | aae64ff550ef26e75518bdad8a12b7cda9e060d2 | 5,992 |
def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | f3a2fc308d041ed0de79e3389e30e02660a1d535 | 5,997 |
import json
def try_parse_json(json_):
"""Converts the string representation of JSON to JSON.
:param str json_: JSON in str representation.
:rtype: :class:`dict` if converted successfully, otherwise False.
"""
if not json_:
return False
try:
return json.loads(json_)
excep... | 077819cf82e307aacf3e56b11fbba26a79559968 | 5,999 |
def setup_config(quiz_name):
"""Updates the config.toml index and dataset field with the formatted
quiz_name. This directs metapy to use the correct files
Keyword arguments:
quiz_name -- the name of the quiz
Returns:
True on success, false if fials to open file
"""
try:
... | 28aba9399926f27da89953c8b0c6b41d95a12d96 | 6,003 |
from typing import Dict
def _average_latency(row: Dict):
"""
Calculate average latency for Performance Analyzer single test
"""
avg_sum_fields = [
"Client Send",
"Network+Server Send/Recv",
"Server Queue",
"Server Compute",
"Server Compute Input",
"Serve... | f321cb4d55af605298225f2f0146a9a71ee7895b | 6,006 |
def to_vsizip(zipfn, relpth):
""" Create path from zip file """
return "/vsizip/{}/{}".format(zipfn, relpth) | 6f5baf380bd7ab8a4ea92111efbc0f660b10f6f8 | 6,007 |
def requires_moderation(page):
"""Returns True if page requires moderation
"""
return bool(page.get_moderator_queryset().count()) | 8f1cfa852cbeccfae6157e94b7ddf61d9597936e | 6,011 |
def valid_parentheses(string):
"""
Takes a string of parentheses, and determines if the order of the parentheses is valid.
:param string: a string of parentheses and characters.
:return: true if the string is valid, and false if it's invalid.
"""
stack = []
for x in string:
if x == "... | e8438404c461b7a113bbbab6417190dcd1056871 | 6,013 |
def has_form_encoded_header(header_lines):
"""Return if list includes form encoded header"""
for line in header_lines:
if ":" in line:
(header, value) = line.split(":", 1)
if header.lower() == "content-type" \
and "x-www-form-urlencoded" in value:
... | e4fe797e4884161d0d935853444634443e6e25bb | 6,014 |
def attr(*args, **kwargs):
"""Decorator that adds attributes to classes or functions
for use with unit tests runner.
"""
def wrapped(element):
for name in args:
setattr(element, name, True)
for name, value in kwargs.items():
setattr(element, name, value)
r... | 77d20af87cef526441aded99bd6e24e21e5f81f9 | 6,016 |
def nn(value: int) -> int:
"""Casts value to closest non negative value"""
return 0 if value < 0 else value | 08672feaefa99881a110e3fc629d4a9256f630af | 6,017 |
def lat_long_to_idx(gt, lon, lat):
"""
Take a geotransform and calculate the array indexes for the given lat,long.
:param gt: GDAL geotransform (e.g. gdal.Open(x).GetGeoTransform()).
:type gt: GDAL Geotransform tuple.
:param lon: Longitude.
:type lon: float
:param la... | 3fafcc4750daa02beaedb330ab6273eab6abcd56 | 6,020 |
def BSMlambda(delta: float, S: float, V: float) -> float:
"""Not really a greek, but rather an expression of leverage.
Arguments
---------
delta : float
BSM delta of the option
V : float
Spot price of the option
S : float
Spot price of the underlying
Returns... | ea9bf546a7cf46b3c2be01e722409663b05248e1 | 6,021 |
import pwd
def uid_to_name(uid):
"""
Find the username associated with a user ID.
:param uid: The user ID (an integer).
:returns: The username (a string) or :data:`None` if :func:`pwd.getpwuid()`
fails to locate a user for the given ID.
"""
try:
return pwd.getpwuid(uid).... | f9054e4959a385d34c18d88704d376fb4b718e47 | 6,022 |
def adjacent_powerset(iterable):
"""
Returns every combination of elements in an iterable where elements remain ordered and adjacent.
For example, adjacent_powerset('ABCD') returns ['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D']
Args:
iterable: an iterable
Returns:
a li... | 951418b30d541e1dcdd635937ae609d429e3cd70 | 6,032 |
def end_position(variant_obj):
"""Calculate end position for a variant."""
alt_bases = len(variant_obj['alternative'])
num_bases = max(len(variant_obj['reference']), alt_bases)
return variant_obj['position'] + (num_bases - 1) | e49110a1102ea2ca53053858597247799065f8e1 | 6,034 |
import functools
def decorator_with_keywords(func=None, **dkws):
# NOTE: ONLY ACCEPTS KW ARGS
"""
A decorator that can handle optional keyword arguments.
When the decorator is called with no optional arguments like this:
@decorator
def function ...
The function is passed as the first a... | 64c4ddd26cc04a43cbf559600652113db81b79ae | 6,041 |
from datetime import datetime
def parse_line(line):
"""
Extract all the data we want from each line.
:param line: A line from our log files.
:return: The data we have extracted.
"""
time = line.split()[0].strip()
response = line.split(' :')
message = response[len(response) - 1].strip... | 72b4362b7628d31996075941be00e4ddcbd5edbc | 6,042 |
from typing import Counter
def reindex(labels):
"""
Given a list of labels, reindex them as integers from 1 to n_labels
Also orders them in nonincreasing order of prevalence
"""
old2new = {}
j = 1
for i, _ in Counter(labels).most_common():
old2new[i] = j
j += 1
old2newf... | c12afd3b6431f10ccc43cce858e71bc504088a6e | 6,044 |
import string
def is_valid_matlab_field_label(label):
""" Check that passed string is a valid MATLAB field label """
if not label.startswith(tuple(string.ascii_letters)):
return False
VALID_CHARS = set(string.ascii_letters + string.digits + "_")
return set(label).issubset(VALID_CHARS) | ea1358e94f4fc936cb12b9cad5d7285ee39dba55 | 6,053 |
def variantCombinations(items):
""" Calculates variant combinations for given list of options. Each item in the items list represents
unique value with it's variants.
:param list items: list of values to be combined
>>> c = variantCombinations([["1.1", "1.2"], ["2.1", "2.2"], ["3.1", "3.2"]])
>>> ... | 72bfdb19db3cf692e4260a5f75d10324e562f20e | 6,055 |
def fahrenheit2celsius(f: float) -> float:
"""Utility function to convert from Fahrenheit to Celsius."""
return (f - 32) * 5/9 | 5161b29998553ad6ff497e698058f330433d90b3 | 6,063 |
def pollard_brent_f(c, n, x):
"""Return f(x) = (x^2 + c)%n. Assume c < n.
"""
x1 = (x * x) % n + c
if x1 >= n:
x1 -= n
assert x1 >= 0 and x1 < n
return x1 | 5037b3feac2f131645fbe6ceb00f0d18417a7c04 | 6,064 |
def tpu_ordinal_fn(shard_index_in_host, replicas_per_worker):
"""Return the TPU ordinal associated with a shard."""
return shard_index_in_host % replicas_per_worker | 773313750ce78cf5d32776752cb75201450416ba | 6,065 |
def getObjectInfo(fluiddb, objectId):
"""
Get information about an object.
"""
return fluiddb.objects[objectId].get(showAbout=True) | baad59e6585e04a8c2a8cca1df305327b80f3768 | 6,071 |
import csv
def snp2dict(snpfile):
"""Get settings of dict from .snp file exported from save&restore app.
Parameters
----------
snpfile : str
Filename of snp file exported from save&restore app.
Returns
-------
r : dict
Dict of pairs of PV name and setpoint value.
"""
... | cb902b3f8796685ed065bfeb8ed2d6d83c0fe80b | 6,073 |
import math
def pol2cart(r,theta):
"""
Translate from polar to cartesian coordinates.
"""
return (r*math.cos(float(theta)/180*math.pi), r*math.sin(float(theta)/180*math.pi)) | 69753e1cadd36ec70da1bf2cf94641d4c7f78179 | 6,077 |
def spread(self, value="", **kwargs):
"""Turns on a dashed tolerance curve for the subsequent curve plots.
APDL Command: SPREAD
Parameters
----------
value
Amount of tolerance. For example, 0.1 is ± 10%.
"""
return self.run("SPREAD,%s" % (str(value)), **kwargs) | a92c8e230eadd4e1fde498fa5650a403f419eaeb | 6,084 |
import re
def repair_attribute_name(attr):
"""
Remove "weird" characters from attribute names
"""
return re.sub('[^a-zA-Z-_\/0-9\*]','',attr) | f653a5cb5ed5e43609bb334f631f518f73687853 | 6,085 |
def HasPositivePatterns(test_filter):
"""Returns True if test_filter contains a positive pattern, else False
Args:
test_filter: test-filter style string
"""
return bool(len(test_filter) > 0 and test_filter[0] != '-') | 9038bf799efbe4008a83d2da0aba89c0197c16a1 | 6,087 |
def module_of_callable(c):
"""Find name of module where callable is defined
Arguments:
c {Callable} -- Callable to inspect
Returns:
str -- Module name (as for x.__module__ attribute)
"""
# Ordinal function defined with def or lambda:
if type(c).__name__ == 'function':
... | 116e46a3e75fcd138e271a3413c62425a9fcec3b | 6,093 |
import json
def invocation_parameter(s) :
"""argparse parameter conversion function for invocation request
parameters, basically these parameters are JSON expressions
"""
try :
expr = json.loads(s)
return expr
except :
return str(s) | cca1a9c3514def152295b10b17ef44480ccca5a9 | 6,097 |
def dumpj(game):
"""Dump a game to json"""
return game.to_json() | bac5480ea2b3136cbd18d0690af27f94e4a2b6a3 | 6,100 |
import types
def _get_functions_names(module):
"""Get names of the functions in the current module"""
return [name for name in dir(module) if
isinstance(getattr(module, name, None), types.FunctionType)] | 581384740dc27c15ac9710d66e9b0f897c906b96 | 6,101 |
import ast
def ex_rvalue(name):
"""A variable store expression."""
return ast.Name(name, ast.Load()) | 4afff97283d96fd29740de5b7a97ef64aad66efe | 6,102 |
def stateDiff(start, end):
"""Calculate time difference between two states."""
consumed = (end.getTimestamp() - start.getTimestamp()).total_seconds()
return consumed | 1f76903e2486e2c378f338143461d1d15f7993a6 | 6,103 |
import copy
import random
def staticDepthLimit(max_depth):
"""Implement a static limit on the depth of a GP tree, as defined by Koza
in [Koza1989]. It may be used to decorate both crossover and mutation
operators. When an invalid (too high) child is generated, it is simply
replaced by one of its paren... | cdcb1e58a681b622ced58e9aa36562e1fedb6083 | 6,104 |
def replace_last(source_string, replace_what, replace_with):
""" Function that replaces the last ocurrence of a string in a word
:param source_string: the source string
:type source_string: str
:param replace_what: the substring to be replaced
:type replace_what: str
:param ... | 6fbc36824b960fb125b722101f21b5de732194c5 | 6,109 |
def unescape(text):
"""Unescapes text
>>> unescape(u'abc')
u'abc'
>>> unescape(u'\\abc')
u'abc'
>>> unescape(u'\\\\abc')
u'\\abc'
"""
# Note: We can ditch this and do it in tokenizing if tokenizing
# returned typed tokens rather than a list of strings.
new_text = []
esc... | 7db9fa5bb786ea5c1f988ee26eed07abe66a2942 | 6,110 |
def removeZeros(infile, outfile, prop=0.5, genecols=2):
"""Remove lines from `infile' in which the proportion of zeros is equal to or higher than `prop'. `genecols' is the number of columns containing gene identifiers at the beginning of each row. Writes filtered lines to `outfile'."""
nin = 0
nout = 0
... | 43feba21513be4a8292c08918e16b3e34a73c341 | 6,112 |
def getPositionPdf(i):
"""Return the position of the square on the pdf page"""
return [int(i/5), i%5] | 859fd00c1475cfcb4cd93800299181b77fdd6e93 | 6,116 |
def dur_attributes_to_dur(d_half, d_semiqvr):
"""
Convert arrays of d_hlf and d_sqv to d.
- See eq. (2) of the paper.
"""
def d_hlf_dur_sqv_to_d(d_hlf, d_sqv):
return 8 * d_hlf + d_sqv
d = d_hlf_dur_sqv_to_d(d_half, d_semiqvr)
return d | aeea74f929ef94d94178444df66a30d0d017fd4e | 6,117 |
def filter_score_grouped_pair(post_pair):
"""
Filter posts with a positive score.
:param post_pair: pair of post_id, dict with score, text blocks, and comments
:return: boolean indicating whether post has a positive score
"""
_, post_dict = post_pair
post_score = post_dict['score']
retur... | c824eacd43b44c85fc7acf102fdde2413a7c4d0e | 6,120 |
def add_upper_log_level(logger, method_name, event_dict):
"""
Add the log level to the event dict.
"""
event_dict["level"] = method_name.upper()
return event_dict | 36ccdf335473136fe8188ff99ed539920ee39fa7 | 6,126 |
def zigzag2(i, curr=.45, upper=.48, lower=.13):
"""
Generalized version of the zig-zag function.
Returns points oscillating between two bounds
linearly.
"""
if abs(i) <= (upper-curr):
return curr + i
else:
i = i - (upper-curr)
i = i%(2*(upper-lower))
if i < (u... | a51624af520121eb7285b2a8a5b4dc5ffa552147 | 6,131 |
def discriminateEvents(events, threshold):
"""
Discriminate triggers when different kind of events are on the same channel.
A time threshold is used to determine if two events are from the same trial.
Parameters
----------
events : instance of pandas.core.DataFrame
Dataframe containing ... | 0078548ea463c01d88b574185b3dcb5632e5cd13 | 6,133 |
def parse_movie(line, sep='::'):
"""
Parses a movie line
Returns: tuple of (movie_id, title)
"""
fields = line.strip().split(sep)
movie_id = int(fields[0]) # convert movie_id to int
title = fields[1]
return movie_id, title | 9d7a13ca3ddf823ff22582f648434d4b6df00207 | 6,136 |
def strip_newlines(s, nleading=0, ntrailing=0):
"""strip at most nleading and ntrailing newlines from s"""
for _ in range(nleading):
if s.lstrip(' \t')[0] == '\n':
s = s.lstrip(' \t')[1:]
elif s.lstrip(' \t')[0] == '\r\n':
s = s.lstrip(' \t')[2:]
for _ in range(ntrai... | cd9c55d4ac7828d9506567d879277a463d896c46 | 6,141 |
def xyz_to_lab(x_val, y_val, z_val):
"""
Convert XYZ color to CIE-Lab color.
:arg float x_val: XYZ value of X.
:arg float y_val: XYZ value of Y.
:arg float z_val: XYZ value of Z.
:returns: Tuple (L, a, b) representing CIE-Lab color
:rtype: tuple
D65/2° standard illuminant
"""
x... | c2478772659a5d925c4db0b6ba68ce98b6537a59 | 6,142 |
def infer(model, text_sequences, input_lengths):
"""
An inference hook for pretrained synthesizers
Arguments
---------
model: Tacotron2
the tacotron model
text_sequences: torch.Tensor
encoded text sequences
input_lengths: torch.Tensor
input lengths
Returns
-... | e7937395956e2dcd35dd86bc23599fbb63417c22 | 6,149 |
def _is_course_or_run_deleted(title):
"""
Returns True if '[delete]', 'delete ' (note the ending space character)
exists in a course's title or if the course title equals 'delete' for the
purpose of skipping the course
Args:
title (str): The course.title of the course
Returns:
... | c32c69e15fafbc899048b89ab8199f653d59e7a8 | 6,156 |
from typing import OrderedDict
def map_constructor(loader, node):
"""
Constructs a map using OrderedDict.
:param loader: YAML loader
:param node: YAML node
:return: OrderedDictionary data
"""
loader.flatten_mapping(node)
return OrderedDict(loader.construct_pairs(node)) | 21bf92d0c3975758ae434026fae3f54736b7f21d | 6,157 |
def usage_percentage(usage, limit):
"""Usage percentage."""
if limit == 0:
return ""
return "({:.0%})".format(usage / limit) | 7caf98ddb37036c79c0e323fc854cbc550eaaa60 | 6,162 |
from typing import Dict
def strip_empty_values(values: Dict) -> Dict:
"""Remove any dict items with empty or ``None`` values."""
return {k: v for k, v in values.items() if v or v in [False, 0, 0.0]} | 982814edbd73961d9afa2e2389cbd970b2bc231e | 6,164 |
def metric_wind_dict_to_beaufort(d):
"""
Converts all the wind values in a dict from meters/sec
to the corresponding Beaufort scale level (which is not an exact number but rather
represents a range of wind speeds - see: https://en.wikipedia.org/wiki/Beaufort_scale).
Conversion table: https://www.win... | b26ddb5e9c0423612a9c7086030fd77bbfa371ad | 6,170 |
def str_igrep(S, strs):
"""Returns a list of the indices of the strings wherein the substring S
is found."""
return [i for (i,s) in enumerate(strs) if s.find(S) >= 0]
#return [i for (s,i) in zip(strs,xrange(len(strs))) if s.find(S) >= 0] | bae8afdb7d0da4eb8384c06e9f0c9bc3f6a31242 | 6,171 |
import base64
def is_base64(s):
"""Return True if input string is base64, false otherwise."""
s = s.strip("'\"")
try:
if isinstance(s, str):
sb_bytes = bytes(s, 'ascii')
elif isinstance(s, bytes):
sb_bytes = s
else:
raise ValueError("Argument mus... | 6ce7bc4ddc79d5d50acce35f7995033ffb7d364a | 6,175 |
def get_mod_from_id(mod_id, mod_list):
"""
Returns the mod for given mod or None if it isn't found.
Parameters
----------
mod_id : str
The mod identifier to look for
mod_list : list[DatRecord]
List of mods to search in (or dat file)
Returns
-------
DatRecord or Non... | 1fac309e4dfadea6da34946eb695f77cbbd61f92 | 6,177 |
import math
def distance(point1, point2):
""" Return the distance between two points."""
dx = point1[0] - point2[0]
dy = point1[1] - point2[1]
return math.sqrt(dx * dx + dy * dy) | 7605d98e33989de91c49a5acf702609272cf5a68 | 6,178 |
def cumulative_sum(t):
"""
Return a new list where the ith element is the sum of all elements up to that
position in the list. Ex: [1, 2, 3] returns [1, 3, 6]
"""
res = [t[0]]
for i in range(1, len(t)):
res.append(res[-1] + t[i])
return res | 14b2ef722f72e239d05737a7bb7b3a6b3e15305f | 6,180 |
import random
def particle_movement_x(time):
"""
Generates a random movement in the X label
Parameter:
time (int): Time step
Return:
x (int): X position
"""
x = 0
directions = [1, -1]
for i in range(time):
x = x + random.choice(directions)
return x | 0dff68080dbfd56997cffb1e469390a1964a326f | 6,187 |
def _format_td(timedelt):
"""Format a timedelta object as hh:mm:ss"""
if timedelt is None:
return ''
s = int(round(timedelt.total_seconds()))
hours = s // 3600
minutes = (s % 3600) // 60
seconds = (s % 60)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds) | 071f25c3c8cfc75cacf2fedc7002527897362654 | 6,193 |
def extract_protein_from_record(record):
"""
Grab the protein sequence as a string from a SwissProt record
:param record: A Bio.SwissProt.SeqRecord instance
:return:
"""
return str(record.sequence) | a556bd4316f145bf23697d8582f66f7dcb589087 | 6,198 |
import torch
def calc_IOU(seg_omg1: torch.BoolTensor, seg_omg2: torch.BoolTensor, eps: float = 1.e-6) -> float:
"""
calculate intersection over union between 2 boolean segmentation masks
:param seg_omg1: first segmentation mask
:param seg_omg2: second segmentation mask
:param eps: eps for numerica... | 6586b1f9995858be9ab7e40edd1c3433cd1cd6f4 | 6,199 |
def td_path_join(*argv):
"""Construct TD path from args."""
assert len(argv) >= 2, "Requires at least 2 tdpath arguments"
return "/".join([str(arg_) for arg_ in argv]) | 491f1d50767a50bfbd7d3a2e79745e0446f5204c | 6,200 |
import torch
def calculate_segmentation_statistics(outputs: torch.Tensor, targets: torch.Tensor, class_dim: int = 1, threshold=None):
"""Compute calculate segmentation statistics.
Args:
outputs: torch.Tensor.
targets: torch.Tensor.
threshold: threshold for binarization of predictions.... | ccc017dd5c7197565e54c62cd83eb5cdc02d7d17 | 6,201 |
import torch
def polar2cart(r, theta):
"""
Transform polar coordinates to Cartesian.
Parameters
----------
r, theta : floats or arrays
Polar coordinates
Returns
-------
[x, y] : floats or arrays
Cartesian coordinates
"""
return torch.stack((r * theta.cos(), ... | c13225a49d6435736bf326f70af5f6d4039091d8 | 6,204 |
def backoff_linear(n):
"""
backoff_linear(n) -> float
Linear backoff implementation. This returns n.
See ReconnectingWebSocket for details.
"""
return n | a3a3b3fc0c4a56943b1d603bf7634ec50404bfb3 | 6,207 |
def check_dna_sequence(sequence):
"""Check if a given sequence contains only the allowed letters A, C, T, G."""
return len(sequence) != 0 and all(base.upper() in ['A', 'C', 'T', 'G'] for base in sequence) | 2f561c83773ddaaad2fff71a6b2e5d48c5a35f87 | 6,209 |
import random
def random_tolerance(value, tolerance):
"""Generate a value within a small tolerance.
Credit: /u/LightShadow on Reddit.
Example::
>>> time.sleep(random_tolerance(1.0, 0.01))
>>> a = random_tolerance(4.0, 0.25)
>>> assert 3.0 <= a <= 5.0
True
"""
valu... | abe631db8a520de788540f8e0973537306872bde | 6,217 |
def find_scan_info(filename, position = '__P', scan = '__S', date = '____'):
"""
Find laser position and scan number by looking at the file name
"""
try:
file = filename.split(position, 2)
file = file[1].split(scan, 2)
laser_position = file[0]
file = file[1].split(date... | f98afb440407ef7eac8ceda8e15327b5f5d32b35 | 6,218 |
import requests
def cleaned_request(request_type, *args, **kwargs):
""" Perform a cleaned requests request """
s = requests.Session()
# this removes netrc checking
s.trust_env = False
return s.request(request_type, *args, **kwargs) | b6c99c85a64e5fd78cf10cc986c9a4b1542f47d3 | 6,227 |
import yaml
def load_config_file(filename):
"""Load configuration from YAML file."""
docs = yaml.load_all(open(filename, 'r'), Loader=yaml.SafeLoader)
config_dict = dict()
for doc in docs:
for k, v in doc.items():
config_dict[k] = v
return config_dict | d61bb86e605a1e744ce3f4cc03e866c61137835d | 6,228 |
def empty_filter(item, *args, **kwargs):
"""
Placeholder function to pass along instead of filters
"""
return True | d72ac5a0f787557b78644bcedd75e71f92c38a0b | 6,231 |
import re
def remove_mentions(text):
"""Remove @-mentions from the text"""
return re.sub('@\w+', '', text) | 5cbdd40a602f24f8274369e92f9159cbb2f6a230 | 6,235 |
def _flat(l):
"""Flattens a list.
"""
f = []
for x in l:
f += x
return f | 9b2e432d79f08840d417601ff950ff9fa28073ef | 6,236 |
from typing import Union
from pathlib import Path
def find_mo(search_paths=None) -> Union[Path, None]:
"""
Args:
search_paths: paths where ModelOptimizer may be found. If None only default paths is used.
Returns:
path to the ModelOptimizer or None if it wasn't found.
"""
default_m... | 4657e15649692415dd10f2daa6527cade351d8fc | 6,241 |
import math
def point_in_wave(point_x, frequency, amplitude, offset_x, offset_y):
"""Returns the specified point x in the wave of specified parameters."""
return (math.sin((math.pi * point_x)/frequency + offset_x) * amplitude) + offset_y | 5a91c9204819492bb3bd42f0d4c9231d39e404d8 | 6,245 |
def map_to_docs(solr_response):
"""
Response mapper that only returns the list of result documents.
"""
return solr_response['response']['docs'] | 2661b9075c05a91c241342151d713702973b9c12 | 6,246 |
import json
def generate_prompt(
test_case_path, prompt_path, solutions_path, tokenizer, starter_path=None
):
"""
Generate a prompt for a given test case.
Original version from https://github.com/hendrycks/apps/blob/main/eval/generate_gpt_codes.py#L51.
"""
_input = "\nQUESTION:\n"
with ope... | ecd3218839b346741e5beea8ec7113ea2892571e | 6,252 |
def format_header(header_values):
"""
Formats a row of data with bolded values.
:param header_values: a list of values to be used as headers
:return: a string corresponding to a row in enjin table format
"""
header = '[tr][td][b]{0}[/b][/td][/tr]'
header_sep = '[/b][/td][td][b]'
return ... | 5b7cd734a486959660551a6d915fbbf52ae7ef1e | 6,258 |
import importlib
def load_attr(str_full_module):
"""
Args:
- str_full_module: (str) correspond to {module_name}.{attr}
Return: the loaded attribute from a module.
"""
if type(str_full_module) == str:
split_full = str_full_module.split(".")
str_module = ".".join(split_full[:... | f96dd56c73745e76ccc9c48dda4ba8a6592ab54b | 6,259 |
def quick_sort(seq):
"""
Реализация быстрой сортировки. Рекурсивный вариант.
:param seq: любая изменяемая коллекция с гетерогенными элементами,
которые можно сравнивать.
:return: коллекция с элементами, расположенными по возрастанию.
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3,... | 46b56b5d29ca31a872e1805b66f4529a8bf48c6b | 6,261 |
def normalize_query_result(result, sort=True):
"""
Post-process query result to generate a simple, nested list.
:param result: A QueryResult object.
:param sort: if True (default) rows will be sorted.
:return: A list of lists of RDF values.
"""
normalized = [[row[i] for i in range(len(row))... | 1df57ef889be041c41593766e1ce3cdd4ada7f66 | 6,262 |
from typing import List
def count_jobpairs(buildpairs: List) -> int:
"""
:param buildpairs: A list of build pairs.
:return: The number of job pairs in `buildpairs`.
"""
counts = [len(bp['jobpairs']) for bp in buildpairs]
return sum(counts) | 30c345698400fd134456abcf7331ca2ebbfec10f | 6,263 |
def calc_water(scenario, years, days_in_year):
"""Calculate Water costs Function
Args:
scenario (object): The farm scenario
years (int): The no. of years the simulation will analyse
days_in_year (float): The number of days in a year
Returns:
cogs_water (list): Cost of Goods So... | ed23060e64c928a545897edef008b8b020d84d3c | 6,266 |
import json
def enqueue_crawling_job(delegate_or_broadcast_svc, job_id, urls, depth):
"""
Used to enqueue a crawling job (or delegate a sub-url on a current job)
to the worker pool.
:type delegate_or_broadcast_svc: ZeroMQDelegatorService or
ZeroMQBroadcastService.
:param delegate_or_broad... | 6a211346edd6f921bf26ed08adcee98cff066764 | 6,268 |
import re
def camel_to_snake(text: str) -> str:
"""
A helper function to convert `camelCase` to `snake_case`.
- e.g. `bestBigBrawlerTime` -> `best_big_brawler_time`
### Parameters
text: `str`
The text to restructure from `camelCase` to `snake_case`.
### Returns
`str`
The ... | b9ac748bf0cc345c7cfb0bade1e4b1e9cbdf712c | 6,272 |
import ast
def extract_ast_class_def_by_name(ast_tree, class_name):
"""
Extracts class definition by name
:param ast_tree: AST tree
:param class_name: name of the class.
:return: class node found
"""
class ClassVisitor(ast.NodeVisitor):
"""
Visitor.
"""
de... | 011f1cb8d965db8e30e6f4281704a6140103946b | 6,276 |
from typing import Callable
def _scroll_screen(direction: int) -> Callable:
"""
Scroll to the next/prev group of the subset allocated to a specific screen.
This will rotate between e.g. 1->2->3->1 when the first screen is focussed.
"""
def _inner(qtile):
if len(qtile.screens) == 1:
... | e778b6ef8a07fe8609a5f3332fa7c44d1b34c17a | 6,280 |
import torch
def decorate_batch(batch, device='cpu'):
"""Decorate the input batch with a proper device
Parameters
----------
batch : {[torch.Tensor | list | dict]}
The input batch, where the list or dict can contain non-tensor objects
device: str, optional
'cpu' or 'cuda'
... | a0bd4a5dff0b5cf6e304aede678c5d56cb93d1dd | 6,286 |
import io
def read_bytes(n: int, reader: io.IOBase) -> bytes:
"""
Reads the specified number of bytes from the reader. It raises an
`EOFError` if the specified number of bytes is not available.
Parameters:
- `n`: The number of bytes to read;
- `reader`: The reader;
Returns the bytes rea... | bb3d00fc7667839864f4104a94a26e682f058fdc | 6,287 |
import json
def _format_full_payload(_json_field_name, _json_payload, _files_payload):
"""This function formats the full payload for a ``multipart/form-data`` API request including attachments.
.. versionadded:: 2.8.0
:param _json_field_name: The name of the highest-level JSON field used in the JSON pay... | feacd27be3e6fcbd33f77fa755be513a93e3cdeb | 6,288 |
def read_slug(filename):
"""
Returns the test slug found in specified filename.
"""
with open(filename, "r") as f:
slug = f.read()
return slug | e1882d856e70efa8555dab9e422a1348594ffcaf | 6,291 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.