seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def c_to_f(temp):
"""Returns Celsius temperature as Fahrenheit"""
return temp * (9/5) + 32 | bigcode/self-oss-instruct-sc2-concepts |
def derive_bt_mac(base_mac,offset):
"""
Derives the BT_MAC from the BASE_MAC and the BT_MAC LSB offset.
"""
base_mac_lsb=int(str(base_mac[-1]), base=16)+offset
base_mac[-1]=format(base_mac_lsb, 'x')
bt_mac='-'.join(base_mac)
return bt_mac.strip() | bigcode/self-oss-instruct-sc2-concepts |
def get_logging_params(verbose):
"""
Adjusts the logging verbosity based on the `verbose` parameter
0 - No logging
1 - Strategy Level logs
2 - Transaction Level logs
3 - Periodic Logs
"""
verbosity_args = dict(
strategy_logging=False,
transaction_loggi... | bigcode/self-oss-instruct-sc2-concepts |
def calc_workload_dis_factor(target_workload_pair, workload_pair):
"""Calculate the distance factor of the workload to the target workload.
If two workloads are not compatible at all (i.e., different compute DAG or function),
then the distance factor is "inf". Otherwise, we calculate the factor by traversin... | bigcode/self-oss-instruct-sc2-concepts |
import re
import six
def rex(expr):
""" Regular expression matcher to use together with transform functions """
r = re.compile(expr)
return lambda key: isinstance(key, six.string_types) and r.match(key) | bigcode/self-oss-instruct-sc2-concepts |
def sheet_as_dict(worksheet):
"""
Take an xsrd worksheet and convert it to a dict, using the first
row as a header (to create keys for the subsequent rows).
"""
keys = worksheet.row_values(0)
value_range = range(1, worksheet.nrows)
def to_dict(values):
return dict(zip(keys, values))... | bigcode/self-oss-instruct-sc2-concepts |
def check_value_above_filter(value, threshold):
"""
Returns a boolean to indicate value at or above threshold.
:param value: integer from a column "*read count".
:param threshold: threshold for the filtering of these read counts.
:return: boolean whether integer is equal or greater than threshold.
... | bigcode/self-oss-instruct-sc2-concepts |
def lazyproperty(func):
"""A decorator for lazy evaluation of properties
"""
cache = {}
def _get(self):
try:
return cache[self]
except KeyError:
cache[self] = value = func(self)
return value
return property(_get) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Tuple
import pathlib
import click
def validate_paths(ctx, param, value: Iterable[str]) -> Tuple[pathlib.Path]:
"""Return a list of git directories in the given paths."""
git_dirs = []
for path in value:
for d in pathlib.Path(path).iterdir():
... | bigcode/self-oss-instruct-sc2-concepts |
def sorting_rivers(station):
"""sorting function for stations_by_rivers"""
river = station[1]
return river | bigcode/self-oss-instruct-sc2-concepts |
import re
def delete_mentions(string):
"""Delete at marks from input string
Args:
string (str): string to delete at marks
Returns:
str: string without at marks.
"""
return re.sub(r'@\S+', '', string) | bigcode/self-oss-instruct-sc2-concepts |
def quote(lst: list) -> list:
"""Put quotation marks around every list element, which is assumed to be a str."""
return [f"\"{element}\"" for element in lst] | bigcode/self-oss-instruct-sc2-concepts |
def get_name_from_path(path):
"""
Return just the filename from its full path.
:param path: (str), directory path.
:return: (str), name of file.
"""
filename = path.split("/")[-1]
return filename.split(".")[0] | bigcode/self-oss-instruct-sc2-concepts |
def _user_in_groups(user, group_names):
"""
Function to verify if a user belongs to any of the groups given.
"""
# If the use is staff (admin, root) we dont need to verify the groups
if user.is_staff:
return True
return set(group.name
for group in user.groups.all()).intersec... | bigcode/self-oss-instruct-sc2-concepts |
def point_inside_circle(x,y,center_x,center_y,radius):
"""Check if a point is inside a circle.
Args:
x (float): x coordinate of the point.
y (float): y coordinate of the point.
center_x (float): x coordinate of the center of the circle.
center_y (float): y coordinate of the cent... | bigcode/self-oss-instruct-sc2-concepts |
import click
def valid_api_key(ctx, param, value):
"""Ensure an API has valid length (this is a click callback)."""
if value is not None and len(value) != 32:
raise click.BadParameter(
"API Key must be 32 characters long, not {}".format(str(len(value)))
)
else:
return v... | bigcode/self-oss-instruct-sc2-concepts |
def escapeForXML(s):
"""Replace special characters '&', "'", '<', '>' and '"' by XML entities."""
s = s.replace("&", "&") # Must be done first!
s = s.replace("'", "'")
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace('"', """)
return s | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def load_object(target, namespace=None):
"""This helper function loads an object identified by a dotted-notation string.
For example:
# Load class Foo from example.objects
load_object('example.objects:Foo')
If a plugin namespace is provided simple name references ar... | bigcode/self-oss-instruct-sc2-concepts |
def reconstruct_path(came_from, current):
"""
Helper method for astar to determine path\n
@param came_from -> Cells searched while finding path\n
@param current -> Current node where snake head is\n
@returns total_path -> Reversed list of coordinates to goal
"""
total_path = [current]
w... | bigcode/self-oss-instruct-sc2-concepts |
def url_filter(url_list: list) -> list:
"""Filters out URLs that are to be queried, skipping URLs that responded with 204 HTTP code.
Args:
url_list: List of URL with metadata dict object.
Returns:
List of URL with metadata dict object that need to be queried.
""... | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate_random_between(min, max):
""" Return a random int between min and max """
return random.randint(min, max) | bigcode/self-oss-instruct-sc2-concepts |
def parse_sentences(name,data):
"""
Returns a list of natural language sentence in a dataset file
Parameters
----------
name : str
string key that contains sentences in the dataset file
data : list of dict
list of dictionaries where each dictionary contains a sentence and its an... | bigcode/self-oss-instruct-sc2-concepts |
def iqr_score(x, q = .25):
"""Inner Quantile Range Score
The IQR score, the median centered data, scaled by the IQR. The inner quantile range can
be flexibly set with the q parameter. A q further from .5 implies a larger range, and
therefore a smaller IQR Score.
Parameters
----------... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def accuracy(predictions, labels):
"""
Compute the average accuracy of the given predictions.
Inspired on
https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
Args:
predictions (torch.Tensor): Tensor containing the output of the linear
output layer of... | bigcode/self-oss-instruct-sc2-concepts |
def find_leaf(nodes, xi):
"""Find the leaf index containing the given features vector.
Parameters
----------
nodes : ndarray
Array of nodes with shape (n_nodes,) with node_dtype dtype
xi : ndarray
Input features vector of shape (n_features,) with uint8 dtype
Returns
------... | bigcode/self-oss-instruct-sc2-concepts |
def get_pos(da):
"""
Takes an xarray DataArray containing veg_index values and calculates the vegetation
value and time (day of year) at peak of season (pos) for each timeseries per-pixel.
The peak of season is the maximum value in the timeseries, per-pixel.
Parameters
----------
ds: ... | bigcode/self-oss-instruct-sc2-concepts |
def get_enabled_vhost_path(version, domain):
"""
Get the path for an enabled PHP vhost file regardless of wether or not it exists.
Args:
version - The PHP version used in the file path
domain - The domain used in the file path
"""
return '/opt/php-' + version + '/etc/php-fpm.d/' + d... | bigcode/self-oss-instruct-sc2-concepts |
def dot(v, u):
"""Compute dot product of vectors *v* and *u*."""
return sum(u[i] * v[i] for i in range(len(v))) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def download_http(url):
"""
Makes an http request for the contents at the given url and returns the response body.
"""
response = requests.get(url)
response.raise_for_status()
# Encoding here prevents a UnicodeDecodeError later in make_zip_in_memory in Python 2.
response_s... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
from typing import Tuple
def confusion_matrix(pred: Set, gold: Set) -> Tuple[Set, Set, Set]:
"""Return a confusion matrix.
This can be used for both entity-level and mention-level
:param pred: a set of predicted entities/candidates
:type pred: set
:param gold: a set of gol... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def parse_changed_files(changed_files: str) -> List[str]:
"""
Get the list of strings specified in CSV format under change_files query parameter.
:param changed_files: The CSV string.
:return: The parsed list of strings.
"""
return changed_files.split(",") | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_task_path_and_exc(file_path):
"""Get the task path and exception from the file by using its file path"""
with open(file_path, 'r') as f:
for line in f:
reg = re.search('Task (.*) with id (?:[0-9a-f\-]+) raised '
'exception:', line)
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def is_holiday(day):
"""
判断是否节假日
参数:
day: 日期, 格式为 '20160404'
return: bool
"""
api = 'http://www.easybots.cn/api/holiday.php'
params = {'d': day}
rep = requests.get(api, params)
res = rep.json()[day if isinstance(day, str) else day[0]]
return True if res == "... | bigcode/self-oss-instruct-sc2-concepts |
def build_flags_string(flags):
"""Format a string of value-less flags.
Pass in a dictionary mapping flags to booleans. Those flags set to true
are included in the returned string.
Usage:
build_flags_string({
'--no-ttl': True,
'--no-name': False,
'--verbose':... | bigcode/self-oss-instruct-sc2-concepts |
def emoji_of_status(status: str) -> str:
"""Returns the emoji associated to a docker container status.
The emojis are as follows:
* ``exited``: ⏹,
* ``paused``: ⏸,
* ``restarting``: ↩,
* ``running``: ▶,
* otherwise: ❓.
"""
return {
"exited": "⏹",
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_frameshift(var):
"""
Returns a boolean if the variant is a frameshift indel
"""
if 'ANN' in var.INFO:
if re.search('frameshift', var.INFO['ANN'][0]):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import six
def encode_string(s, encoding='utf-8', errors='strict'):
"""Encode string s to bytes."""
if isinstance(s, bytes):
return s
if isinstance(s, six.text_type):
s = s.encode(encoding, errors=errors)
else:
s = str(s).encode(encoding, errors=errors)
return s | bigcode/self-oss-instruct-sc2-concepts |
import fnmatch
def _is_excluded(name, exclude):
"""
Determine if the name is to be excluded based on the exclusion list
"""
if not exclude:
return False
return any( (fnmatch.fnmatchcase(name, i) for i in exclude) ) | bigcode/self-oss-instruct-sc2-concepts |
def isnotification(request):
"""
Tests if the given request is a notification
:param request: A request dictionary
:return: True if the request is a notification
"""
if 'id' not in request:
# 2.0 notification
return True
if request['id'] is None:
# 1.0 notification
... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def decode_pair(s, pos=0):
"""
Decodes a name/value pair.
The number of bytes decoded as well as the name/value pair
are returned.
"""
nameLength = ord(s[pos])
if nameLength & 128:
nameLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff
pos += 4
el... | bigcode/self-oss-instruct-sc2-concepts |
def get_image_size(image):
"""
Returns width and height of image
"""
width = int(image.shape[1])
height = int(image.shape[0])
return width, height | bigcode/self-oss-instruct-sc2-concepts |
def getSmoothedSampledPointsOnTrackSurface(trackSurface, startProportion1, startProportion2, endProportion1,
endProportion2, elementsOut, startDerivative = None, endDerivative = None,
startDerivativeMagnitude = None, endDerivativeMagn... | bigcode/self-oss-instruct-sc2-concepts |
def sqrt_bisect(n, steps=20, epsilon=10**-5):
"""Approximate square root by the bisection method."""
assert n > 0
assert epsilon > 0
low = 0
high = n
step = 1
sqrt = (low + high) / 2
while abs(sqrt**2 - n) > epsilon and step <= steps:
if sqrt**2 < n:
low = sqrt
... | bigcode/self-oss-instruct-sc2-concepts |
def get_bond_features_shape(train_set):
"""Get the shape of the atom features from a MoleculeACE.GNN.dataloaders.*_graph_dataset"""
bond_features = 13 # this is the standard size
for item in train_set:
single_graph = item[1]
bond_features = single_graph.edata['e'].shape[1]
break
... | bigcode/self-oss-instruct-sc2-concepts |
def split_snake(text, fix=True):
"""
Split a string in snake case format into a tuple of its component words
By default the result is guaranteed to be all lowercase
:param text: Text to split
:param fix: Whether to lowercase the result, or leave capitalization as-is
:return: Tuple of str... | bigcode/self-oss-instruct-sc2-concepts |
def set_bit(number, site, N, bit):
"""
Change the bit value of number at a single site.
:param number: the number to be changed
:param site: the index of the site starting from left
:param bit: the bit value to be changed
:returns: the changed number
"""
if bit:
return number | ... | bigcode/self-oss-instruct-sc2-concepts |
def robot_pick_mug(agents, self_state, self_name, mug):
"""
Checks if the 'mug' is reachable by the agent (robot) and if the agent does not carry anything.
Then updates the beliefs of all the agents in the same room as the robot as for the robot having picked the 'mug'
"""
if self_name in self_state... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def function_param_order(func):
"""get names of args infunction signature"""
return list(inspect.signature(func).parameters.keys()) | bigcode/self-oss-instruct-sc2-concepts |
def is_wikidata_entity(entity: str) -> bool:
"""Assert that a string is a wikidata entity"""
wrong_entity_format = entity and (entity[0] != "Q" or any([j not in "0123456789" for j in entity[1:]]))
return not wrong_entity_format | bigcode/self-oss-instruct-sc2-concepts |
def overlap_common_cnvs(all_bt, common_cnvs, cnv, min_cov):
"""
Overlap regions with a BED of common CNVs, and return list of IDs ≥ min_cov
"""
if common_cnvs is not None:
bt_cov = all_bt.coverage(common_cnvs)
ids = [x[3] for x in bt_cov if x[4] == cnv and float(x[-1]) >= min_cov]
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_total_audio_duration(info_file):
"""
Get duration and total clips from info JSON.
Parameters
----------
info_file : str
Path to info JSON
Returns
-------
float
Total duration of all clips
int
Total number of clips
"""
with open(... | bigcode/self-oss-instruct-sc2-concepts |
def group_objects_by_model(objects):
""" Group objects by their models
Args:
objects (:obj:`list` of :obj:`Model`): list of model objects
Returns:
:obj:`dict`: dictionary with object grouped by their class
"""
grouped_objects = {}
for obj in objects:
if obj.__class__ no... | bigcode/self-oss-instruct-sc2-concepts |
def cwum_2d(x,c=0.):
"""
Correlated density with uniform marginals (CWUM)
x in [0,1], 0<=c<2
c = 1. is tensor product uniform
c = 0. # if c=0 max pdf(x) = 2. min= 0.
"""
normalization = (13.*c+3)/16.
return (c-2.*(c-1.)*((x[0,:]+1)/2.+(x[1,:]+1)/2.-2.*(x[0,:]+1)/2.*(x[1,:]+1)/2.)/4.)/nor... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_version(version):
"""Parse a version string, discarding any suffix and returning a
3-tuple of the major, minor and patch version numbers."""
match = re.search(r'^([0-9]+)\.([0-9]+)(\.([0-9]+))?', version)
if match:
major = int(match.group(1))
minor = int(match.grou... | bigcode/self-oss-instruct-sc2-concepts |
def _getName(geo):
"""Given a GeoInfo object, return the value of its 'name' attribute. If there is no such attribute, return None."""
attrCtx = geo.attribContext('name', 3, 7) # 3 = per-object attribute, 7 = std::string type
if attrCtx is None:
attrCtx = geo.attribContext('name', 3, 6) # 3 = per-object attri... | bigcode/self-oss-instruct-sc2-concepts |
def fetch_logs_by_id(logs_df, conversation_id):
"""fetch logs by conversation id
"""
return logs_df[logs_df['conversation_id'] == conversation_id] | bigcode/self-oss-instruct-sc2-concepts |
def add_variable_mod(peps:list, mods_variable_dict:dict)->list:
"""
Function to add variable modification to a list of peptides.
Args:
peps (list): List of peptides.
mods_variable_dict (dict): Dicitionary with modifications. The key is AA, and value is the modified form (e.g. oxM).
Retur... | bigcode/self-oss-instruct-sc2-concepts |
def frange(a, b, n):
"""
Returns an equally spaced sequence of floats, in the interval [a, b], with
n elements. (Essentially emulates the linspace() function in numpy.)
@type a: number
@param a: start of interval
@type b: number
@param b: end of interval
@type n: number
@param n:... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def connect(address):
"""Connect to given address and set socket non blocking."""
try:
sock = socket.socket()
sock.connect(address)
sock.setblocking(False)
except socket.error:
return None
return sock | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from operator import add
def twos(bits: List[int]) -> List[int]:
"""
Converts a list of bits into its Two's Complement representation. The bits
are negated (flipped) and the list of bits is then added with 1.
Agrs:
bits: (List[int]) The bits to take Two's Complement of... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def parse_stringdb_interactions(this_line: str, header_items: List) -> Dict:
"""Methods processes a line of text from Drug Central.
Args:
this_line: A string containing a line of text.
header_items: A list of header items.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def format_frame_number_with_leading_zeros(frame: int) -> str:
"""
Formats the given number as a 5-digit with leading zeros
"""
return "{:05d}".format(frame) | bigcode/self-oss-instruct-sc2-concepts |
import math
def zscore_p(observed, expected, N):
"""
Computes z-score for the normal distribution
:param observed: prob.
:param expected: prob.
:param N:
:return:
"""
return (observed-expected) / math.sqrt((expected*(1.0-expected))/float(N)) | bigcode/self-oss-instruct-sc2-concepts |
def mean_dist_from_centroid(coordinates, centroid):
"""
Calculate mean distance between centroid and list of coordinates
:param coordinates: list of coordinates as Points
:param centroid: centroid as Point
:return: mean distance between centroid and coordinates in metres
"""
dist = sum(coord... | bigcode/self-oss-instruct-sc2-concepts |
def get_magnet_dict(self):
"""Return a dictionnary with all the magnets of the Hole
Parameters
----------
self : Hole
A Hole object
Returns
-------
magnet_dict : {Magnet}
Dictionnary of magnet (key = magnet_X, value= Magnet or None)
"""
if hasattr(self, "magnet_dic... | bigcode/self-oss-instruct-sc2-concepts |
def hassecret(repo):
"""utility function that check if a repo have any secret changeset."""
return bool(repo._phasecache.phaseroots[2]) | bigcode/self-oss-instruct-sc2-concepts |
def _CompareAnomalyBisectability(a1, a2):
"""Compares two Anomalies to decide which Anomaly's TestMetadata is better to
use.
Note: Potentially, this could be made more sophisticated by using
more signals:
- Bisect bot queue length
- Platform
- Test run time
- Stddev of test
Args:
a1: The ... | bigcode/self-oss-instruct-sc2-concepts |
def bbox_vert_aligned_left(box1, box2):
"""
Returns true if the left boundary of both boxes is within 2 pts
"""
if not (box1 and box2): return False
return abs(box1.left - box2.left) <= 2 | bigcode/self-oss-instruct-sc2-concepts |
def getDistinctElt(transactions):
"""
Get the distinct element in a list of transactions.
"""
distinctSet = set()
for transaction in transactions:
for elt in transaction:
if not(elt in distinctSet):
distinctSet.add(elt)
return distinctSet | bigcode/self-oss-instruct-sc2-concepts |
def histogram_from_vector(backend, data, weights, bins, mask=None):
"""Fills the weighted values in a data array to a histogram specified by a sorted one-dimensional bin array.
>>> data = numpy.array([1,1,1,2,3], dtype=numpy.float32)
>>> weights = numpy.array([1,1,1,2,1], dtype=numpy.float32)
>>> bins ... | bigcode/self-oss-instruct-sc2-concepts |
def do_one(fns, x):
""" Try each of the functions until one works. Then stop. """
for fn in fns:
result = fn(x)
if result != x:
return result
return x | bigcode/self-oss-instruct-sc2-concepts |
import json
def file_id(fqn):
"""Get the Google FileID
:param fqn: path to a json-like file which contains the key: "doc_id"
"""
with open(fqn) as json_file:
result = json.load(json_file)
return result['doc_id'] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import csv
def read_file(path: str) -> List[list]:
"""
Read the data from the file path, reconstruct the format the the data
and return a list of lines.
the shape of the output is:
[[season, home_team, away_team, full_time_performance_score],
...]
Precondition... | bigcode/self-oss-instruct-sc2-concepts |
import six
def xor(key, data):
"""
Perform cyclical exclusive or operations on ``data``.
The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If
the key is smaller than the provided ``data``, the ``key`` will be
repeated.
Args:
key(int or bytes): The key to xor ``da... | bigcode/self-oss-instruct-sc2-concepts |
def unscale_input(img):
"""Reverses scaling of image values from [-1,1] to [0,255].
Args:
img (numpy.ndarray[float]): image to scale
Returns:
numpy.ndarray[float]: unscaled image
"""
return ((img + 1) * 127.5) | bigcode/self-oss-instruct-sc2-concepts |
def get_info_str(*key):
"""
Returns a continuous string of a list of objects. Each object is transferred to a string and strings are separated
by '_' to form the final string. If a string of an object is too long or the object is a class, it will be replaced
by the class name of the object. All the stri... | bigcode/self-oss-instruct-sc2-concepts |
def get_object_from_action_name(action):
"""Return the object from the name of the action"""
if action.startswith('pick_'):
object_name = action[len('pick_'):]
else:
object_name = None
return object_name | bigcode/self-oss-instruct-sc2-concepts |
def get_hash_id(param):
"""Return the hash ID of a parameter."""
return param['_']['hash_id'] | bigcode/self-oss-instruct-sc2-concepts |
def parse_locust_stats(env):
"""
Turn the locust stats into more print-friendly data.
"""
stats = env.runner.stats
statistics = {
"requests": {},
"failures": {},
"num_requests": stats.num_requests,
"num_requests_fail": stats.num_failures,
}
for name, value in... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def _wrap_word(text: str, w: int) -> str:
"""
Wrap word
:param text: text
:param w: max line length
:return: Wrapped word
"""
return "\n".join(textwrap.wrap(text, w, replace_whitespace=False, break_long_words=False)) | bigcode/self-oss-instruct-sc2-concepts |
def action_key(action):
"""Returns string representation of action. This is also what is returned by argmax_Q. Needs a dictionary for that if the string representation is not enough."""
return action | bigcode/self-oss-instruct-sc2-concepts |
def bytes_list2bin(bl):
"""Convert list of bytes to binary string"""
return b''.join(chr(i).encode('latin-1') for i in bl) | bigcode/self-oss-instruct-sc2-concepts |
def get_answer_using_qa(nlp, question, context):
"""Get answer using a classifier trained with the QA technique
Parameters
----------
nlp: Pipeline
Trained QA Pipeline
question: String
Question that the model will answer
context: String
The Context of the question
R... | bigcode/self-oss-instruct-sc2-concepts |
def check_legendary(item):
""" Check if item is a Legendary """
if item.name == 'Sulfuras, Hand of Ragnaros':
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import requests
def submit_request(url: str, token: str, query: str) -> requests.Response:
"""Post a query to an API access point, along with an authentication token.
Retry with a progressive timeout window.
"""
MAX_REQUESTS = 3
TIMEOUT_INCREMENT = 5
response = None
req_count = 1
whi... | bigcode/self-oss-instruct-sc2-concepts |
def check_col(x, y, digits_grid):
"""
Checks if a digit in a box with coordinates y, x fits to its column.
Useful for checking if sudoku is solvable at all.
:param x:
a coordinate counted from 0
:param y:
a coordinate counted from 0
:param digits_grid:
2D numpy array that contains digits. 0 <==> there is n... | bigcode/self-oss-instruct-sc2-concepts |
def _inject_args(sig, types):
"""A function to inject arguments manually into a method signature before
it's been parsed. If using keyword arguments use 'kw=type' instead in
the types array.
sig the string signature
types a list of types to be inserted
Returns the altered... | bigcode/self-oss-instruct-sc2-concepts |
def _dirac(a, b):
"""Calculate the dirac function for labels."""
return int(a == b) | bigcode/self-oss-instruct-sc2-concepts |
def _format_gaussian_report(result):
"""Formats a `_GaussianResult` as a complete report str.
The information presented includes:
- The parameters of the Gaussian fit
- The extrapolated probability of the `assertAllMeansClose` failing,
assuming the distribution of means is Gaussian
- Suggested changes to... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def is_active(coords, active_voxels, volume_resolution):
""" compute whether coordinates belong to active voxels by two criterias:
1) a coordinate should be within the volume bound
2) it belongs to the input active voxels
Args:
coords: [b, n_pts, n_steps, 3]
active_vo... | bigcode/self-oss-instruct-sc2-concepts |
def quadrilaterals_mesh_to_centroids(x_vertices, y_vertices):
"""Find the centroids of a mesh from its vertices.
Parameters
----------
x_vertices - 2d numpy array (NxM)
y_vertices - 2d numpy array (NxM)
Returns
-------
x,y - 2d numpy array (N-1xM-1)
"""
x = (x_vertices[0:-1,0... | bigcode/self-oss-instruct-sc2-concepts |
def format_address(parts):
"""
Format a parsed email address for sending
:param parts: a tuple of the name and email
:return: a properly formatted email
"""
if parts[0] == "":
return parts[1]
return f"{parts[0]} <{parts[1]}>" | bigcode/self-oss-instruct-sc2-concepts |
def set_rpn_weights(training_model, inference_model, verbose=False):
"""
Set region proposal network (RPN) weights from training to inference graph
Args:
training_model: MaskRCNN training graph, tf.keras.Model
inference_model: MaskRCNN inference graph, tf.keras.Model
verbose: ... | bigcode/self-oss-instruct-sc2-concepts |
def bflag2str(bflag):
"""
Args:
bflag (dict): binary flag
Returns:
flag as binary string, keys
"""
l = []
#print("flag keys ", bflag.keys())
#['plankton', 'small_Z_diff', 'melting_layer', 'too_many_peaks']
keys = ['mod_calibration', 'unsecure_calibration', 'particle_influ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_relative_path(src: str):
"""Returns true if src is a relative path.
"""
assert isinstance(src, str), ValueError("relative_path must be a string")
return not (src.startswith("/") or re.match(r"[a-zA-Z]:\\", src) is not None) | bigcode/self-oss-instruct-sc2-concepts |
import re
def keep_only_letters(text, keep_cash=True):
"""
Remove from string `text` all characters that are not letters (letters include those
with portuguese accents). If `keep_cash` is true, do not remove the dollar sign
'$'.
"""
if keep_cash == True:
extra_chars = '$'
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def mean(data):
"""Compute the mean of the provided data."""
n = len(data)
try:
return [float(sum(l))/len(l) for l in zip(*data)]
except TypeError:
return sum(data)/n | bigcode/self-oss-instruct-sc2-concepts |
def rounder(x, ndigits):
"""Round a number, or sequence of numbers, to a specified number of decimal digits
Args:
x (None, float, complex, list): The number or sequence of numbers to be rounded. If the
argument is None, then None will be returned.
ndigits (int): The number of decima... | bigcode/self-oss-instruct-sc2-concepts |
def str2bool(value):
""" Type to convert strings to Boolean (returns input if not boolean) """
if not isinstance(value, str):
return value
if value.lower() in ('yes', 'true', 'y', '1'):
return True
elif value.lower() in ('no', 'false', 'n', '0'):
return False
else:
re... | bigcode/self-oss-instruct-sc2-concepts |
def prlimit_command(command_list, virtual_memory_limit):
"""
Prepend memory limiting arguments to a command list to be run with subprocess.
This method uses the `prlimit` program to set the memory limit.
The `virtual_memory_limit` size is in bytes.
prlimit arguments:
-v, --as[=limits]
... | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.