seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def download_file(s, url, data_dir):
"""
Download the provided file and place it in data_dir
"""
local_filename = data_dir + url.split('/')[-1]
# NOTE the stream=True parameter
req = s.get(url, stream=True)
with open(local_filename, 'wb') as local_f:
for chunk in req.iter_content(chu... | bigcode/self-oss-instruct-sc2-concepts |
def vsstd(a, s=0.1):
"""Normalize the image range for visualization."""
return (a - a.mean()) / max(a.std(), 1e-4) * s + 0.5 | bigcode/self-oss-instruct-sc2-concepts |
def has_file(conn, path, mirror_id):
"""check if file 'path' exists on mirror 'mirror_id'
by looking at the database.
path can contain wildcards, which will result in a LIKE match.
"""
if path.find('*') >= 0 or path.find('%') >= 0:
oprtr = 'like'
path = path.replace('*', '%')
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def get_random_block_from_data(data, batch_size):
"""Randomly select batch_size number of contiguous samples."""
start_index = random.randint(0, data.shape[0] - batch_size)
return data[start_index:(start_index + batch_size)] | bigcode/self-oss-instruct-sc2-concepts |
def GetNextQtnodeBounds(qtnode, x, y, size):
"""Calculate next level boundary for qtnode.
If the qtnode has further precision, call this routine
recursively.
Args:
qtnode: The remaining string of the qtnode.
x: Current left of the qtnode (degrees).
y: Current bottom of the qtnode (degrees).
si... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Dict
from typing import List
def get_data_list_from_timeseries(data: Any) -> Dict[str, List[float]]:
"""Constructs a Dict as keys are the container names and
values are a list of data taken from given timeseries data."""
if data['status'] != 'success':
rai... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def find_overlaps(orfs_found):
"""Associates overlapping ORFs based on their start-stop intervals"""
# initialize dictionary to store associations for each ORF
overlaps_found = { i : [] for i in range(1, len(orfs_found)+1) }
processed_orfs = []
# sort ORFs by asce... | bigcode/self-oss-instruct-sc2-concepts |
def getDate(year, month, day):
""" Get date string from year month and day"""
return str(year)+'%02d' %month+'%02d' %day | bigcode/self-oss-instruct-sc2-concepts |
def mutate_individual(logger, ind):
"""
Simply calls the mutate function of the given individual.
Args:
logger (:obj:`logging.Logger`): A logger to log with
ind (:obj:`actions.strategy.Strategy`): A strategy individual to mutate
Returns:
:obj:`actions.strategy.Strategy`: Mutate... | bigcode/self-oss-instruct-sc2-concepts |
def boolean_bitarray_get(integer, index):
"""The index-th-lowest bit of the integer, as a boolean."""
return bool((integer >> index) & 0x01) | bigcode/self-oss-instruct-sc2-concepts |
def ExtractUnits(hf,k):
"""
Returns all the data for a single key (column) in a given HDF5 file.
Parameters
----------
hf : File
The HDF5 where the data is stored.
Example:
HDF5_File = h5py.File(filename, 'r')
k : str
the name of the column that is to be extr... | bigcode/self-oss-instruct-sc2-concepts |
def _get_columns(x):
""" retrieve the columns of something if it exists """
if hasattr(x, "columns"):
return list(x.columns)
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def branch_hash_worktree_path_builder(branch):
"""Returns a relative path for a worktree based on the hash of the branch
name.
"""
return hashlib.md5(branch.encode("utf-8")).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def from_gca_linestring(gca_obj):
"""
Converts LineString GCA to an EGF string.
Returns
-------
egf_str : str
LineString GCA as an EGF string
"""
if gca_obj.geometry_type != "LS":
raise ValueError(f"Expected geometry type to be 'LS' and got '{gca_obj.geometry_type}' instea... | bigcode/self-oss-instruct-sc2-concepts |
def rm_additional_rots_and_trans(results):
"""
Removes the first 6 rotations and translations, to leave
the required 3N vibrations.
"""
for key, value in results.items():
results[key] = value[6:]
return results | bigcode/self-oss-instruct-sc2-concepts |
def get_tableau_values(data):
"""
Tableau's data lists all the values used throughout the view in a single
place, and the display information about each chart references these values
by data type (int, cstring, etc.) and index.
Return a simplified version of this: a dict mapping data types to lists... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def generate_command_parameters(command: str) -> Tuple[str, int]:
"""Helper function to generate parameters from commands passed as string.
A command string is converted to a (action: str, step: int) tuple.
Pattern is:
command is an "action step" string than we can split ... | bigcode/self-oss-instruct-sc2-concepts |
def get_adjusted_price(price, currency, currency_data):
"""Return adjusted price and name of company the label is referring to.
If a user wants the price value in a currency different from the dollar
this function computes the stock value in such currency.
:param price: The price of the stock of the c... | bigcode/self-oss-instruct-sc2-concepts |
def wrapTex(tex):
""" Wrap string in the Tex delimeter `$` """
return r"$ %s $" % tex | bigcode/self-oss-instruct-sc2-concepts |
def split_geolocation_string(config, geolocation_string):
"""Fields of type 'geolocation' are represented in the CSV file using a
structured string, specifically lat,lng, e.g. "49.16667, -123.93333".
This function takes one of those strings (optionally with a multivalue
subdelimiter) and return... | bigcode/self-oss-instruct-sc2-concepts |
import random
def raffle(tickets, lots):
"""Run a raffle, producing a list of randomly selected winners.
Arguments:
tickets -- a list containing (name, number of tickets purchased) tuples
lots -- a list of lots available to be won
Each ticket can only win once, but people purchasing multiple tic... | bigcode/self-oss-instruct-sc2-concepts |
def fix_projection(shape, axes, limits):
"""Fix the axes and limits for data with dimension sizes of 1.
If the shape contains dimensions of size 1, they need to be added
back to the list of axis dimensions and slice limits before calling
the original NXdata 'project' function.
Parameters
... | bigcode/self-oss-instruct-sc2-concepts |
def macaddr_pack(data, bytes = bytes):
"""
Pack a MAC address
Format found in PGSQL src/backend/utils/adt/mac.c, and PGSQL Manual types
"""
# Accept all possible PGSQL Macaddr formats as in manual
# Oh for sscanf() as we could just copy PGSQL C in src/util/adt/mac.c
colon_parts = data.split(':')
dash_parts = d... | bigcode/self-oss-instruct-sc2-concepts |
def constraint_class(kind):
"""
The convention is that name of the class implementing the constraint
has a simple relationship to the constraint kind, namely that
a constraint whose kind is 'this_kind' is implemented by a class
called ThisKindConstraint.
So:
``min`` --> ``MinConst... | bigcode/self-oss-instruct-sc2-concepts |
def coerce_int(obj):
"""Return string converted to integer.
.. Usage::
>>> coerce_int(49)
49
>>> coerce_int('49')
49
>>> coerce_int(43.22)
43
"""
try:
return int(obj) if obj else obj
except ValueError:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Optional
def split_module(path: str) -> Tuple[Optional[str], Optional[str]]:
"""Split module and system path."""
if not path.startswith('@'):
return None, path
index = path.find('/')
if index == -1:
return path[1:], None
else:
re... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def vertex_color_qubo(G, colors):
"""Return the QUBO with ground states corresponding to a vertex coloring.
If `V` is the set of nodes, `E` is the set of edges and `C` is the set of
colors the resulting qubo will have:
* :math:`|V|*|C|` variables/nodes
* :math:`|V|*|C|*(|C| - 1)... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def correct(output, target, tokens):
"""Computes the number of correct predictions.
Args:
output (torch.tensor): output of the model
target (torch.tensor): masked labels
tokens (int): vocabulary size
Returns:
int: number of correct predictions
"""
wit... | bigcode/self-oss-instruct-sc2-concepts |
def parse_event_description(in_event):
"""Find and make nice the gig description from a single event from bar 303 website
Args:
in_event (scrapy.http.response.html.HtmlResponse): The html response for the single event from bar 303 website
Returns:
str: Event Description, maybe an e... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_order(ugraph):
"""
returns a list of random node order
"""
nodes = ugraph.keys()
random.shuffle(nodes)
return nodes | bigcode/self-oss-instruct-sc2-concepts |
import torch
def is_autocast_enabled() -> bool:
"""Similar to torch.is_autocast_enabled, but compatible with torch 1.5.1"""
if hasattr(torch, "is_autocast_enabled"):
return torch.is_autocast_enabled()
return False | bigcode/self-oss-instruct-sc2-concepts |
def _split_input_slice(input_shape, num_split):
"""Get input slice from the input shape.
Parameters
----------
input_shape : tuple
The input shape of the net.
num_split : int
The number of split we want to have.
Returns
-------
slices : list of slice
The split ... | bigcode/self-oss-instruct-sc2-concepts |
def get_DIB_data(Dataset):
"""Function that modifies a pytorch dataset so that the target contains the example index."""
class DIBData(Dataset):
def __getitem__(self, index):
img, target = super().__getitem__(index)
return img, (target, index) # append the index
return DIB... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def datetime_to_iso(timestamp):
"""Parse a datatime string and returns a datetime in iso format.
@param timestamp: timestamp string
@return: ISO datetime
"""
return datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").isoformat() | bigcode/self-oss-instruct-sc2-concepts |
def is_good_response(response):
"""Helper method to check if boto3 call was a success."""
code = response["ResponseMetadata"]['HTTPStatusCode']
# get response code 201 on EFS creation
return 200 <= code < 300 | bigcode/self-oss-instruct-sc2-concepts |
def vips_image_new_from_array(cls, array, scale = 1, offset = 0):
"""Create a new image from an array.
The array argument can be a 1D array to create a height == 1 image, or a 2D
array to make a 2D image. Use scale and offset to set the scale factor,
handy for integer convolutions.
"""
# we ac... | bigcode/self-oss-instruct-sc2-concepts |
def svc_ids(svc):
"""
Returns the account ID and service ID of a given service.
"""
return svc['accountId'], svc['id'] | bigcode/self-oss-instruct-sc2-concepts |
def split_train_test_val(X, y, threshold=0.1): # Tested [N]
"""
Creates and compiles a fully-connected feed forward neural network model using Keras
Args:
X (DataFrame):
y (ndarray): Labels
threshold (float): The proportion to split the data
Returns:
Xval (Dat... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def soft_step(x, temperature):
"""Differentiable relaxation of the Heaviside step function."""
return torch.sigmoid(x / temperature) | bigcode/self-oss-instruct-sc2-concepts |
def pmul(p, n):
"""Return the multiple of the given probabilty."""
return 1.0 - (1.0 - p) ** n | bigcode/self-oss-instruct-sc2-concepts |
def is_medium_truck(df):
"""Return if vehicle is a medium truck, per NHTSA convention."""
yr = df['YEAR']
body = df['BODY_TYP']
return ((yr.between(1975, 1981) & body.isin([53, 54, 56])) |
(yr.between(1982, 1990) & body.isin([70, 71, 75, 78])) |
((1991 <= yr) & body.isin([60, 61... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Any
def make_create_json(
summary: str,
project_key: str,
type_name: str,
description: Optional[str],
assignee: Optional[str],
priority_name: Optional[str],
labels: Optional[str],
due_date: Optional[str],
) -> Any:
"""Makes a JSON stri... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_pixel_values(pixels):
""" Normalize pixel values to be in the range [0, 1] """
pixels = pixels.astype("float32")
pixels /= 255.0
return pixels | bigcode/self-oss-instruct-sc2-concepts |
def clean_meta_data(meta_data_frame):
"""
Clean the meta data we have. Remove an unnamed column, rename some other columns, drop some columns
:param meta_data_frame: pd dataframe
:return: cleaned pd dataframe
"""
meta = meta_data_frame.loc[:, ~meta_data_frame.columns.str.contains("^Unnamed")]
... | bigcode/self-oss-instruct-sc2-concepts |
def to_iamc_layout(df):
"""Transform *df* to a standard IAMC layout.
The returned object has:
- Any (Multi)Index levels reset as columns.
- Lower-case column names 'region', 'variable', 'subannual', and 'unit'.
- If not present in *df*, the value 'Year' in the 'subannual' column.
Parameters
... | bigcode/self-oss-instruct-sc2-concepts |
def multi_match_aware_interval(k, delta, i, s, pi, li):
"""
Function returning the interval of relevant substrings to lookup using the
multi-match-aware substring selection scheme described in the paper.
Args:
k (int): Levenshtein distance threshold.
delta (int): Signed length differenc... | bigcode/self-oss-instruct-sc2-concepts |
def delete_files_template(get_s3_client_func, get_bucket_func, delete_keys_func, key_list, s3_bucket):
"""
Curried template function for deleting files from an S3 bucket
:param get_s3_client_func: A function that returns an S3 client
:param get_bucket_func: A function that returns an object representi... | bigcode/self-oss-instruct-sc2-concepts |
def hashable(raw):
"""If `raw` contains nested lists, convert them to tuples
>>> hashable(('a', 'b', 'c'))
('a', 'b', 'c')
>>> hashable(('a', ['b', 'c'], 'd'))
('a', ('b', 'c'), 'd')
"""
result = tuple(hashable(itm) if isinstance(itm, list) else itm
for itm in raw)
r... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_float_encoding(
token: str, embedding_size: int, vmax: float = 1.0
) -> torch.Tensor:
"""Convert a token representing a float into a _fixed_ embedding vector.
NOTE: This can be used for *any* range of numbers > 0.
Args:
token (str): A token representing a float. NOTE: Nee... | bigcode/self-oss-instruct-sc2-concepts |
def catch_erroneous_destination(destination):
"""
Catch instructions that are not valid and throw an error.
"""
error_msg = "Available instructions are: 'any', or '#', where '#' "\
"is an integer."
if destination not in ["any"]:
try:
integer_destination = int(destination)... | bigcode/self-oss-instruct-sc2-concepts |
def paragraphs(linelist):
"""
Break a list of lines at blank lines into a list of line-lists.
"""
plist = []
newlinelist = []
for line in linelist:
line = line.strip()
if line:
newlinelist.append(line)
elif newlinelist:
plist.append(newlinelist)
... | bigcode/self-oss-instruct-sc2-concepts |
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
"""
Format a number as friendly text, using common suffixes.
>>> friendly_number(102)
'102'
>>> friendly_number(10240)
'10k'
>>> friendly_number(12341234, ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def list_truncated_nums(n: int) -> List[int]:
"""
Returns a list of all left and right truncated numbers of n
>>> list_truncated_nums(927628)
[927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9]
>>> list_truncated_nums(467)
[467, 67, 46, 7, 4]
>>> list_truncat... | bigcode/self-oss-instruct-sc2-concepts |
def judge_checksum(content: bytes) -> bool:
"""
Judge if the checksum is right or not.
:param content: the content of segment
:return: A bool
"""
even_sum = 0x0
odd_sum = 0x0
for i in range(len(content)):
b = content[i]
if i % 2:
odd_sum += b
odd... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def factors(n, ordered=True):
"""Get factors of a number in a list.
Parameters:
n (int): The number that you want to get the factors of.
ordered (bool): Whether you want the output to be ordered from smallest to largest. Setting this value to false will marginally increas... | bigcode/self-oss-instruct-sc2-concepts |
import re
def regex_password(password):
"""
Regex
Password includes at least one digit, one uppercase letter, one lowercase letter, and one special character.
"""
# The {8,} means "at least 8".
# print(re.match(r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[@#$%^&*?!+-_=])[\w\d@#$]{8,}", password))
... | bigcode/self-oss-instruct-sc2-concepts |
def px2hc(xpx, ypx, dx, dy, xc, yc, sz):
"""
Given positions in pixel coordinates (x = [0->nx-1]; y = [0->ny-1]),
determine the HC x and y coordinates in arcseconds.
- xpx, ypx = pixel coordinates of AR positions
- dx, dy = arcsec/px
- xc, yc = FOV center in arcsec from solar disk center
- x... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_birthday(soup):
"""
Utility function to get the Birthday of an actor from his wikipedia page.
:param soup: Beautiful Soup object
:return: String containing the actor's birth date in yyyy-mm-dd format.
"""
logging.info("getBirthday called.")
# Isolate the info box ta... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _2d_rotate(position, angle_degrees):
"""rotate a 2d vector around an angle (in degrees)"""
radians = math.radians(angle_degrees)
# take the negative of the angle because the orientation circle works clockwise in this world
cos = math.cos(-radians)
sin = math.sin(-radians)
x, y ... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def product_no_consecutives(iterables, repeat=2):
""" Returns Cartesian product of input iterable excluding those contaning
equal consecutives elements.
See: `itertools.product`
"""
def has_no_equal_consecutives(sequence):
it, it_shifted = itertools.tee(sequence)
next... | bigcode/self-oss-instruct-sc2-concepts |
def is_scoped_package(name):
"""
Return True if name contains a namespace.
For example::
>>> is_scoped_package('@angular')
True
>>> is_scoped_package('some@angular')
False
>>> is_scoped_package('linq')
False
>>> is_scoped_package('%40angular')
True
"""
return name.st... | bigcode/self-oss-instruct-sc2-concepts |
def quotify(text: str) -> str:
"""
Turn a string into a discord quote.
:param text: Text to put into quote
:return: Discord quote
"""
return "> " + text.replace("\n", "\n> ") | bigcode/self-oss-instruct-sc2-concepts |
def AddRepositoryTags(prefix='', rid=True, date=True, revision=True,
wrap=False):
"""Add repository tagging into the output.
Args:
prefix: comment delimiter, if needed, to appear before tags
rid: bool; True includes the revision Id: repository tag.
date: bool; True includes the Da... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_json(filename):
""" load external json file """
with open(filename) as data_file:
json_data = json.load(data_file)
return json_data | bigcode/self-oss-instruct-sc2-concepts |
import math
def euclid(onsets, pulses):
"""returns a list of ones and zeros for a give euclidean rhythm
>>> euclid(3,8)
[1, 0, 0, 1, 0, 0, 1, 0]
"""
slope = float(onsets) / float(pulses)
result = []
previous = None
for i in range(pulses):
current = int(math.floor(float(i) * sl... | bigcode/self-oss-instruct-sc2-concepts |
def class_to_dict(inst, ignore_list=[], attr_prefix=''):
""" Writes state of class instance as a dict
Includes both attributes and properties (i.e. those methods labeled with @property)
Note: because this capture properties, it should be viewed as a snapshot of instance state
:param inst: insta... | bigcode/self-oss-instruct-sc2-concepts |
def generate_id(text):
"""Deterministically generates an ID from a given text.
NOT guaranteed to be unique, but the alternative was to
either drop some data for not having IDs, or
generating uniquely on the fly: which is hard to do on
a batch system.
A negative integer is returned to avoid... | bigcode/self-oss-instruct-sc2-concepts |
import re
def hasMainFunc( filename ):
"""
Returns True if file contains something that looks like a main() or
main( int argc, char argv ) function.
"""
main_regex = re.compile('.*main(.*argc.*argv).*')
f = open(filename)
for line in f.readlines():
if main_regex.search( line ):
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import time
def get_from_bgg(api_url, parameters):
"""Successively attempts to get data from BGG given an API"""
response = requests.get(api_url, params=parameters)
# Retry if return codes indicate "too many requests"
while response.status_code == 202 or response.status_code == 429:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
import itertools
def extract_param_list(params, prefix=''):
"""Extract a list-of-dicts based on parameters containing AWS style list.
MetricData.member.1.MetricName=buffers
MetricData.member.1.Unit=Bytes
MetricData.member.1.Value=231434333
MetricData.member.2.MetricName=buffers2
Met... | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(num):
""" Returns true if a number is a palindrome """
reverse, forward = 0, num
while (num > 0):
reverse = reverse*10 + num%10
num /= 10
return forward == reverse | bigcode/self-oss-instruct-sc2-concepts |
def privilege_check(user, *required_privileges):
"""Tests if the user has one of the required_privileges to view the
requested component.
"""
for perm in required_privileges:
if user.has_property(perm):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def pages_endash(record):
""" Convert pages to use an html en dash
"""
try:
# Convert to list of page numbers
pages = [p.strip() for p in record['pages'].split('-')
if p.strip()]
record['pages'] = '–'.join(pages)
except KeyError:
pass
return reco... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def status_crawler(LEETCODE_SESSION: str, question_name: str) -> bool:
"""Check if question solved
Args:
LEETCODE_SESSION (str): User's LeetCode session.
question_name (str): LeetCode question name.
Returns:
bool: Solved or not.
"""
cookies = {"LEETCODE_SE... | bigcode/self-oss-instruct-sc2-concepts |
def add_special_tokens(tokenizer):
""" Returns GPT2 tokenizer after adding separator and padding tokens """
#tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
special_tokens = {'bos_token':'<|startoftext|>','eos_token':'<|endoftext|>', 'pad_token':'<|pad|>','sep_token':'<|summarize|>'}
num_add_toks = tokenizer.add_... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def sub_seq(s1: Sequence, s2: Sequence) -> bool:
"""
Checks if sequence s1 is subsequence of s2,
:param s1: First sequence.
:type s1: Sequence
:param s2: Second sequence.
:type s2: Sequence
:return: True if s1 is subsequence of s2.
:rtype: bool
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def drop_null_rows(df):
"""Drop all rows containing null values"""
return df.dropna().reset_index(drop=True) | bigcode/self-oss-instruct-sc2-concepts |
def get_error_name(error):
"""Return canonical error name as string.
For builtin errors like ValueError or Exception, will return the bare
name, like ValueError or Exception.
For all other exceptions, will return modulename.errorname, such as
arbpackage.mod.myerror
Args:
error: Except... | bigcode/self-oss-instruct-sc2-concepts |
def is_s3_path(path: str) -> bool:
"""Returns True if the path points to a S3 bucket, False otherwise."""
return path.startswith("s3://") | bigcode/self-oss-instruct-sc2-concepts |
def slug_is_available(slug, job_category_model, job_category=None):
"""
Determine whether the given slug is available for use and not a duplicate
"""
JobCategory = job_category_model
siblings = JobCategory.objects.all()
if job_category:
siblings = siblings.exclude(id=job_category.id)
... | bigcode/self-oss-instruct-sc2-concepts |
def st_fleet_details(fleet, user):
"""
Details of a sitetracker fleet.
"""
return {'fleet': fleet, 'user': user} | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_env(environment_string: str) -> str:
"""
Parses an environment string as passed from the command line and ensures that it is a JSON
object with the appropriate structure (i.e. a map of strings to strings)
Args:
environment_string
JSON string denoting a mapping of env... | bigcode/self-oss-instruct-sc2-concepts |
def toint(number):
"""
Helper to return rounded int for a float or just the int it self.
"""
if isinstance(number, float):
number = round(number, 0)
return int(number) | bigcode/self-oss-instruct-sc2-concepts |
def get_asset_url(release, quiet=False):
"""
get the assets url from the release information
:return: the assets_url
"""
return release["assets_url"] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def make_pad_mask(seq_lens):
"""Make mask for padding.
Args:
seq_lens (IntTensor): `[B]`
Returns:
mask (IntTensor): `[B, T]`
"""
bs = seq_lens.size(0)
max_time = seq_lens.max()
seq_range = torch.arange(0, max_time, dtype=torch.int32, device=seq_lens.device)
... | bigcode/self-oss-instruct-sc2-concepts |
def _data_range(data: str) -> bool:
""" Checks if a string data are a numbers in range. """
return True if data.find('-') != -1 else False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Tuple
import operator
def _ensure_index_tuple(x: Any) -> Tuple[int, ...]:
"""Convert x to a tuple of indices."""
try:
return (operator.index(x),)
except TypeError:
return tuple(map(operator.index, x)) | bigcode/self-oss-instruct-sc2-concepts |
import string
def clean_punctuation(texts):
"""Remove punctuation from strings"""
cleaned_tokens = [[word.strip(string.punctuation) for word in sentence] for sentence in texts]
return cleaned_tokens | bigcode/self-oss-instruct-sc2-concepts |
def common_chars(seq, k):
""" Returns the set of characters that appear more than k times in
the input string, along with their number of occurrences.
Example:
>>> common_chars("cat in a hat", 2)
{("a", 3), (" ", 3)}
"""
chars = set()
for i in range(len(seq)):
if seq.count(seq[... | bigcode/self-oss-instruct-sc2-concepts |
def extract_data_key(returned_data):
"""
Build and return dict containing measurement 'name', description ('text')
and unit of measurement.
"""
return {i["name"]: {"text": i["$"], "units": i["units"]} for i in returned_data["SiteRep"]["Wx"]["Param"]} | bigcode/self-oss-instruct-sc2-concepts |
def _gen_index_list_to_fifty_mbyte_increment(file_buffer_list):
"""Create a list of indexes marking the ~50 MByte increments of cumulative size
of the file_buffers provided by the streamlit.file_uploader
Parameters
----------
file_buffer_list : ``list``
list of file_buffers (derived from io... | bigcode/self-oss-instruct-sc2-concepts |
def get(execution_id, client):
"""Request a execution with certain ID."""
return client.get_execution(str(execution_id)) | bigcode/self-oss-instruct-sc2-concepts |
def push_stream(cache, user_id, stream):
"""
Push a stream onto the stream stack in cache.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:param stream: stream object to push onto stack
:return: True on successful update,
False if fa... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import re
def format_header(header: str) -> Tuple[str, int, str]:
"""Calculates the level of the header, removes leading and trailing whitespaces and creates the markdown-link.
:param header: header line from the markdown file
:return: a tuple consisting of the cleaned header, th... | bigcode/self-oss-instruct-sc2-concepts |
def load_features_list(input_path):
"""
Reads in a file of distinct feature names line-by-line and returns
these features as a list. Each feature name in the file must occur
on a separate line.
Parameters
----------
input_path : str
Path to the features file. Each feature in the inp... | bigcode/self-oss-instruct-sc2-concepts |
def all_bases_valid(seq):
"""Confirm that the sequence contains only bases"""
valid_bases = ['a', 'A', 'c', 'C', 'g', 'G', 't', 'T', 'N']
for base in seq:
if base not in valid_bases:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import six
def to_float(x):
"""Convert an object to a float, unless it is None
Examples:
>>> print(to_float(12.3))
12.3
>>> print(to_float('12.3'))
12.3
>>> print(to_float(None))
None
"""
if isinstance(x, six.string_types) and x.lower() == 'none':
x = None
retu... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def len_gen(gen):
"""return length of a generator.
built-in len() does not work on generators.
Note: like iterators, generators can only iter once, so after running
len_gen() on it, you can't iter over it again.
"""
return functools.reduce(lambda x, y: x + 1, gen, 0) | bigcode/self-oss-instruct-sc2-concepts |
def matrix_transpose(matrix: list) -> list:
"""
Compute the transpose of a matrix
"""
transpose: list = []
for row in range(len(matrix[1])):
column = []
for col in range(len(matrix)):
column.append(matrix[col][row])
transpose.append(column)
return transpose | bigcode/self-oss-instruct-sc2-concepts |
import time
def my_decorator(fn):
"""my_decorator is a custom decorator that wraps any function
and prints on stdout the time for execution.
"""
def wrapper_function(*args, **kwargs):
start_time = time.time()
# invoking the wrapped function and getting the return value
value =... | 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.