seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _generate_anchor_configs(min_level, max_level, num_scales, aspect_ratios):
"""Generates mapping from output level to a list of anchor configurations.
A configuration is a tuple of (num_anchors, scale, aspect_ratio).
Args:
min_level: integer number of minimum level of the output feature pyramid.
... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def sequences_add_end_id_after_pad(sequences, end_id=888, pad_id=0):
"""Add special end token(id) in the end of each sequence.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
end_id : int
The end ID.
pad_id : int
... | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
import typing
def get_robot_types(cursor: sqlite3.Cursor) -> typing.List[dict]:
"""Gets all robot types from the db
:param cursor: [description]
:type cursor: sqlite3.Cursor
:return: [description]
:rtype: typing.List[dict]
"""
return cursor.execute(
"SELECT id, nam... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import Dict
def get_tagged_secrets(secrets_manager, secrets_tags: Sequence[str]) -> Dict[str, str]:
"""
Return a dictionary of AWS Secrets Manager names to arns
for any secret tagged with `secrets_tag`.
"""
secrets = {}
paginator = secrets_manager.get_p... | bigcode/self-oss-instruct-sc2-concepts |
def usechangesetcentricalgo(repo):
"""Checks if we should use changeset-centric copy algorithms"""
if repo.filecopiesmode == b'changeset-sidedata':
return True
readfrom = repo.ui.config(b'experimental', b'copies.read-from')
changesetsource = (b'changeset-only', b'compatibility')
return readf... | bigcode/self-oss-instruct-sc2-concepts |
def can_zip_response(headers):
"""
Check if request supports zipped response
:param headers: request headers
:return:
"""
if 'ACCEPT-ENCODING' in headers.keys():
if 'gzip' in headers.get('ACCEPT-ENCODING'):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Dict
from typing import List
def get_mock_aws_alb_event(
method,
path,
query_parameters: Optional[Dict[str, List[str]]],
headers: Optional[Dict[str, List[str]]],
body,
body_base64_encoded,
multi_value_headers: bool,
):
"""Return a mock AWS... | bigcode/self-oss-instruct-sc2-concepts |
def get_artist_names(artist_database, artist_id):
"""
Return the list of names corresponding to an artist
"""
if str(artist_id) not in artist_database:
return []
alt_names = [artist_database[str(artist_id)]["name"]]
if artist_database[str(artist_id)]["alt_names"]:
for alt_name... | bigcode/self-oss-instruct-sc2-concepts |
def containsAll(str, set):
"""
Checks if a given string contains all characters in a given set.
:param str: input string
:type: string
:param set: set if characters
:type: string
:rtype: boolean
"""
for c in set:
if c not in str: return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def format_artist_rating(__, data):
"""Returns a formatted HTML line describing the artist and its rating."""
return (
"<li><a href='{artist_tag}/index.html'>{artist}</a>" " - {rating:.1f}</li>\n"
).format(**data) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def _hash_file(fpath, algorithm="sha256", chunk_size=65535):
"""Calculates a file sha256 or md5 hash.
# Example
```python
>>> from keras.data_utils import _hash_file
>>> _hash_file('/path/to/file.zip')
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b8... | bigcode/self-oss-instruct-sc2-concepts |
def avoid_keyerror(dictionary, key):
""" Returns the value associated with key in dictionary. If key
does not exist in the dictionary, print out 'Avoid Exception' and
map it to the string 'no value'.
>>> d = {1: 'one', 3: 'three', 5: 'five'}
>>> avoid_keyerror(d, 3)
'three'
>>> avoid_keyer... | bigcode/self-oss-instruct-sc2-concepts |
def string_boolean(value):
"""Determines the boolean value for a specified string"""
if value.lower() in ('false', 'f', '0', ''):
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cosine_similarity(x, y=None, eps=1e-8):
"""Calculate cosine similarity between two matrices;
Args:
x: N*p tensor
y: M*p tensor or None; if None, set y = x
This function do not broadcast
Returns:
N*M tensor
"""
w1 = torch.norm(x, p=2, dim=1, keepdim=True)
if y is None... | bigcode/self-oss-instruct-sc2-concepts |
def all_same(L):
"""Check if all elements in list are equal.
Parameters
----------
L : array-like, shape (n,)
List of objects of any type.
Returns
-------
y : bool
True if all elements are equal.
"""
y = len(L) == 0 or all(x == L[0] for x in L)
return y | bigcode/self-oss-instruct-sc2-concepts |
def _IsDuplicateInterestedUser(url_entity, bots_user_key):
"""Checks if bots_user_key exist in interested_users.
Args:
url_entity: BotsUrl Entity to check for.
bots_user_key: bots_user entity key (db.Key).
Returns:
True if bots_user_key exist in interested_users, else False.
"""
return str(bots_... | bigcode/self-oss-instruct-sc2-concepts |
def defined_or_defaut_dir(default, directory):
"""
if given a directory it will return that directory, otherwise it returns the default
"""
if directory:
return directory
else:
return default | bigcode/self-oss-instruct-sc2-concepts |
def display_timedelta(minutes):
"""Converts timedelta in minutes to human friendly format.
Parameters
----------
minutes: int
Returns
-------
string
The timedelta in 'x days y hours z minutes' format.
Raises
------
ValueError
If the timedelta is negative.
"... | bigcode/self-oss-instruct-sc2-concepts |
def obs_model_parameter_values(values):
"""
Return a list containing all of the values for a single parameter.
:param values: The values for the parameter.
:type values: Union[List[Any], Any]
"""
if isinstance(values, list):
return values
else:
return [values] | bigcode/self-oss-instruct-sc2-concepts |
import ast
def subscript_type_to_string(subscript: ast.Subscript) -> str:
"""
Returns a string representation of a subscript.
For example, if the subscript is Optional[int] it returns "Optional[int]".
"""
return ast.unparse(subscript) | bigcode/self-oss-instruct-sc2-concepts |
import random
def makelist(random_int):
"""Creates a list of random float values of total list length
random_int (specified as function param)"""
num_list = []
for count in range(random_int):
num_list.append(random.random())
return num_list | bigcode/self-oss-instruct-sc2-concepts |
def get_table_headers(table):
"""Given a table soup, returns all the headers"""
headers = []
for th in table.find("tr").find_all("th"):
headers.append(th.text.strip())
return headers | bigcode/self-oss-instruct-sc2-concepts |
import logging
from datetime import datetime
from pathlib import Path
import requests
def download_file(url, file_location=None, overwrite=False):
"""
Purpose:
Download file from specified URL and store in a specfied location.
If no location is provided, the file is downloaded in the current
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def md(text):
"""Basic filter for escaping text in Markdown."""
return re.sub(r'([_*])', r'\\\1', text) | bigcode/self-oss-instruct-sc2-concepts |
def get_confirmation_block_from_results(*, block_identifier, results):
"""
Return the confirmation block from results list
"""
return next((i for i in results if i['message']['block_identifier'] == block_identifier), None) | bigcode/self-oss-instruct-sc2-concepts |
def add(initial: int=0, number: int=0) -> int:
"""Return sum of *intial* and *number*.
:param initial: Initial value.
:type initial: int
:param number: Value to add to initial.
:type number: int
:return: Sum of initial and number.
:rtype: int
"""
return initial + number | bigcode/self-oss-instruct-sc2-concepts |
from urllib.parse import urlencode
from typing import OrderedDict
def make_pr_link(url, project, slug, from_branch, to_branch):
"""Generates a URL that can be used to create a PR"""
if "github.com" in url:
result = "{url}/{organization}/{repo_name}/compare/{to_branch}...{from_branch}".format(
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def generate_options_for_point(x: int, y: int, z: int) -> List[Tuple[int, int, int]]:
"""
generate 24 different orientations for point presented of (x, y, z)
"""
return [(x, y, z), (z, y, -x), (-x, y, -z), (-z, y, x),
(-y, x, z), (z, x, y), ... | bigcode/self-oss-instruct-sc2-concepts |
def filter_bin(length, index_pairs):
"""
用于某些二进制标志位的场景
index_pairs: {index: value,}
返回 length 长度内第 index 位值为 value 的所有可能的 int 的 list, index 从 1 开始, e.g.
>>> filter_bin(3, {1: 1})
[1, 3, 5, 7]
>>> filter_bin(3, {1: 1, 2: 0})
[1, 5]
>>> filter_bin(3, {1: 0, 2: 1})
[2, 6]
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def switch_month(month: str):
"""
Translates an english month to a french one. For example: 'Jan' becomes '(01)Janvier'.
month : the month that will be translated
"""
return {
"Jan": "(01)Janvier",
"Feb": "(02)Fevrier",
"Mar": "(03)Mars",
"Apr": "(04)Avril",
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def extract_json(serie, k):
"""Extract a value by a key."""
return serie.map(lambda row: json.loads(row)[k]) | bigcode/self-oss-instruct-sc2-concepts |
def escape_quotes(s: str) -> str:
"""Replaces double quotes in the input string with either ' or \\".
Description:
Given a string, returns that string with double quotes escaped in one of two ways.
If the string contains single quotes, then \\" will be used to escape the double quotes.... | bigcode/self-oss-instruct-sc2-concepts |
def process_icon_emoji(inIconEmoji: str) -> str:
"""Process an 'icon_emoji' string.
Args:
inIconEmoji:
Single icon emoji string.
Returns:
Properly formatted 'icon_emoji' string
"""
tmpStr = inIconEmoji.strip(": ")
return f":{tmpStr}:" if tmpStr else "" | bigcode/self-oss-instruct-sc2-concepts |
def GetLabelsFromDict(metadata):
"""Converts a metadata dictionary to a string of labels.
Args:
metadata: a dictionary of string key value pairs.
Returns:
A string of labels in the format that Perfkit uses.
"""
return ','.join('|%s:%s|' % (k, v) for k, v in metadata.iteritems()) | bigcode/self-oss-instruct-sc2-concepts |
def generate_md_code_str(code_snippet: str, description: str = 'Snippet') -> str:
"""The normal ``` syntax doesn't seem to get picked up by mdv. It relies on indentation based code blocks.
This one liner accommodates for this by just padding a code block with 4 additional spaces.
Hacky? Sure. Effective? Yu... | bigcode/self-oss-instruct-sc2-concepts |
def subsample(data, every=5):
"""Subsample to the desired frequency. Use every `every`th sample."""
return data[::every] | bigcode/self-oss-instruct-sc2-concepts |
def get_subclasses(klass):
"""Gets the list of direct/indirect subclasses of a class"""
subclasses = klass.__subclasses__()
for derived in list(subclasses):
subclasses.extend(get_subclasses(derived))
return subclasses | bigcode/self-oss-instruct-sc2-concepts |
def is_vulnerable(source):
"""A simple boolean function that determines whether a page
is SQL Injection vulnerable from its `response`"""
errors = {
# MySQL
"you have an error in your sql syntax;",
"warning: mysql",
# SQL Server
"unclosed quotation mark after the cha... | bigcode/self-oss-instruct-sc2-concepts |
def skip_material(mtl: int) -> int:
"""Computes the next material index with respect to default avatar skin indices.
Args:
mtl (int): The current material index.
Returns:
int: The next material index to be used.
"""
if mtl == 1 or mtl == 6:
return mtl + 2
return mtl + 1 | bigcode/self-oss-instruct-sc2-concepts |
import json
import requests
def getProcedures(host, service):
"""
Get all the procedures (stations) using the WA-REST API
"""
proc_url = f"http://{host}/istsos/wa/istsos/services/{service}/procedures/operations/getlist"
# Request and Get the procedures from the response
procedures = json.loa... | bigcode/self-oss-instruct-sc2-concepts |
def agg_moy_par_pret(dataframe, group_var, prefix):
"""Aggregates the numeric values in a dataframe. This can
be used to create features for each instance of the grouping variable.
Parameters
--------
dataframe (dataframe):
the dataframe to calculate the statistics on
g... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def lowercase_and_remove_accent(text):
"""
Lowercase and strips accents from a piece of text based on
https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py
"""
text = " ".join(text)
text = text.lower()
text = unicodedata.normalize("NFD"... | bigcode/self-oss-instruct-sc2-concepts |
import random
def blood_pressure_depending_on_age(age):
"""Randomly generate a blood pressure value depending upon the given age
value.
It is assumed that for a given age value the blood pressure is normally
distributed with an average blood pressure of 75 at birth (age 0) and of
90 at age 100,... | bigcode/self-oss-instruct-sc2-concepts |
def write_content(path, content):
"""Write string content to path name."""
print(f"- writing {path}")
with open(path, 'w') as file:
file.write(content)
return path | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha1_hash(bytes):
"""
Compute the SHA-1 hash of a byte stream.
"""
sha = hashlib.sha1()
sha.update(bytes)
return sha.digest() | bigcode/self-oss-instruct-sc2-concepts |
def founder_allocation() -> float:
"""How much tokens are allocated to founders, etc."""
return 0.2 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def generate_padding_masks(data, pad_value=0):
"""
Returns a mask based on the data. For values of the padding token=0, the mask will contain 1, indicating the
model cannot attend over these positions.
:param data: The data of shape (sequence_len, batch_size)
:param pad_value: The val... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def _get_local_logging_config() -> Dict:
"""Create local logging config for running the dummy projects."""
return {
"version": 1,
"formatters": {
"simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"}
},
"root": {"level"... | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def get_mol_3d_coordinates(mol):
"""Get 3D coordinates of the molecule.
This function requires that molecular conformation has been initialized.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule instance.
Returns
-------
numpy.ndarray of shape ... | bigcode/self-oss-instruct-sc2-concepts |
def population_render_transparency(x, invert_colours=False, b=None):
"""Render image from patches with transparancy.
Renders patches with transparency using black as the transparent colour.
Args:
x: tensor of transformed RGB image patches of shape [S, B, 5, H, W].
invert_colours: Invert all RGB values.
... | bigcode/self-oss-instruct-sc2-concepts |
def youngs(vp=None, vs=None, rho=None, mu=None, lam=None, bulk=None, pr=None,
pmod=None):
"""
Computes Young's modulus given either Vp, Vs, and rho, or
any two elastic moduli (e.g. lambda and mu, or bulk and P
moduli). SI units only.
Args:
vp, vs, and rho
or any 2 from la... | bigcode/self-oss-instruct-sc2-concepts |
def initial_workload_is_ready(ops_test, app_names) -> bool:
"""Checks that the initial workload (ie. x/0) is ready.
Args:
ops_test: pytest-operator plugin
app_names: array of application names to check for
Returns:
whether the workloads are active or not
"""
return all(
... | bigcode/self-oss-instruct-sc2-concepts |
def duplication_consistency(set_one, set_two):
"""
Calculates the duplication consistency score for two sets of species
:param set_one: set/list of species
:param set_two: set/list of species
:return: float with duplication consistency score
"""
union_size = len(set(set_one).union(set(set_t... | bigcode/self-oss-instruct-sc2-concepts |
def _auto_correlations(n_states):
"""Returns list of autocorrelations
Args:
n_states: number of local states
Returns:
list of tuples for autocorrelations
>>> l = _auto_correlations(np.arange(3))
>>> assert l == [(0, 0), (1, 1), (2, 2)]
"""
local_states = n_states
retur... | bigcode/self-oss-instruct-sc2-concepts |
import re
def process_clinical_significance(clin_sig):
"""
Processes ClinVar clinical significance string into a format suitable for OT JSON schema.
Namely, splits multiple clinical significance levels into an array and normalises names (to lowercase, using only
spaces for delimiters). Multiple level... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def linear_utility(
exchange_params_by_currency_id: Dict[str, float],
balance_by_currency_id: Dict[str, int],
) -> float:
"""
Compute agent's utility given her utility function params and a good bundle.
:param exchange_params_by_currency_id: exchange params by currency
... | bigcode/self-oss-instruct-sc2-concepts |
def sum_of_square_deviations(data, c):
"""Return sum of square deviations of sequence data."""
ss = sum((float(x) - c)**2 for x in data)
return ss | bigcode/self-oss-instruct-sc2-concepts |
def DataArray_to_dictionary(da, include_data=True):
""" Convert DataArray to dictionary
Args:
da (DataArray): data to convert
include_data (bool): If True then include the .ndarray field
Returns:
dict: dictionary containing the serialized data
"""
fields = ['label', 'name',... | bigcode/self-oss-instruct-sc2-concepts |
from torch.utils.data._utils.collate import default_collate
from typing import Sequence
from typing import Dict
def multi_supervision_collate_fn(batch: Sequence[Dict]) -> Dict:
"""
Custom collate_fn for K2SpeechRecognitionDataset.
It merges the items provided by K2SpeechRecognitionDataset into the follow... | bigcode/self-oss-instruct-sc2-concepts |
def ebc_to_srm(ebc):
"""
Convert EBC to SRM Color
:param float ebc: EBC Color
:return: SRM Color
:rtype: float
"""
return ebc / 1.97 | bigcode/self-oss-instruct-sc2-concepts |
def _unique_id_to_host_id(unique_id):
"""Return the chip id unique to the daplink host procesor
Unique ID has the following fomat
Board ID - 4 bytes
Version - 4 bytes
Host ID - Everything else
"""
return unique_id[8:8 + 32] | bigcode/self-oss-instruct-sc2-concepts |
import ntpath
def pathLeaf(path):
"""
Returns the basename of the file/directory path in an _extremely_ robust way.
For example, pathLeaf('/hame/saheel/git_repos/szz/abc.c/') will return 'abc.c'.
Args
----
path: string
Path to some file or directory in the system
Returns... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def convertUnits(ww_params, pixel_size):
"""
Convert to the units currently used by the analysis pipeline. This also
adds additional zeros as needed to match the length expected by the
analysis pipeline.
"""
ww_params = copy.copy(ww_params)
ww_params[0] = ww_params[0] * pi... | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate_smallest_secret(poly_degree, crc_length, min_size=0, echo=False):
""" Helper function to generate smallest secret which is:
- divisible by 8, so that it can be encoded to bytes
- secret length + crc_length is divisible by poly_degree + 1
to be able to split s... | bigcode/self-oss-instruct-sc2-concepts |
def force_key(d, k):
"""Return a key from a dict if existing and not None, else an empty string
"""
return d[k] if d.has_key(k) and d[k] is not None else "" | bigcode/self-oss-instruct-sc2-concepts |
def foundSolution(solver_result):
"""
Check if a solution was found.
"""
return "Valid" not in solver_result and "unsat" not in solver_result | bigcode/self-oss-instruct-sc2-concepts |
import torch
def one_hotify(vec, number_of_classes, dimension):
"""
Turn a tensor of integers into a matrix of one-hot vectors.
:param vec: The vector to be converted.
:param number_of_classes: How many possible classes the one hot vectors encode.
:param dimension: Which dimension stores the ... | bigcode/self-oss-instruct-sc2-concepts |
def get_fuels(collection, country):
"""
Accumulate capacities for each fuel type for a given country
"""
result = collection.aggregate([
{
# Search country
'$search': {
'index': 'default',
'text': {
'query': country,
'path': 'coun... | bigcode/self-oss-instruct-sc2-concepts |
def extract_category(report, key):
"""
Create a dict from a classification report for a given category.
Args:
report: The report
key: The key to a category on the report
"""
result = report.get(key)
result['category'] = key
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_int_from_little_endian_bytearray(array, offset):
""" Get an int from a byte array, using little-endian representation,\
starting at the given offset
:param array: The byte array to get the int from
:type array: bytearray
:param offset: The offset at which to start looking
:type offs... | bigcode/self-oss-instruct-sc2-concepts |
def simple_dist(x1: float, x2: float) -> float:
"""Get distance between two samples for dtw distance.
Parameters
----------
x1:
first value
x2:
second value
Returns
-------
float:
distance between x1 and x2
"""
return abs(x1 - x2) | bigcode/self-oss-instruct-sc2-concepts |
def fitness_bc(agent, environment, raw_fitness, path):
""" Returns as a tuple the raw fitness and raw observation of an agent evaluation. """
if len(path) > 0:
return raw_fitness, path
return raw_fitness, [0] | bigcode/self-oss-instruct-sc2-concepts |
def accuracy(y_pred, y_truth):
"""
Accuracy: #right / #all
Parameters
-------------
y_pred : numpy array, (m, 1)
the predicted labels
y_truth : numpy array, (m, 1)
the true labels
Returns
--------
accuracy : double
larger is better
"""
re... | bigcode/self-oss-instruct-sc2-concepts |
def train_test_split(t, df):
"""
Splits time series dataset into train, validation and test set with a 60-20-20 split.
Targeted to be used in an apply function to a Series object.
:param t: current timestep (int)
:param df: pandas Dataframe containing the data
:returns: subset categorization as ... | bigcode/self-oss-instruct-sc2-concepts |
import traceback
def cut_traceback(tb, func_name):
"""
Cut off a traceback at the function with the given name.
The func_name's frame is excluded.
Args:
tb: traceback object, as returned by sys.exc_info()[2]
func_name: function name
Returns:
Reduced traceback.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def crop_2d_using_xy_boundaries(mask, boundaries):
"""
:mask: any 2D dataset
:boundaries: dict{xmin,xmax,ymin,ymax}
:return: cropped mask
"""
b = boundaries
return mask[b['ymin']:b['ymax'], b['xmin']:b['xmax']] | bigcode/self-oss-instruct-sc2-concepts |
def get_unit(a):
"""Extract the time unit from array's dtype"""
typestr = a.dtype.str
i = typestr.find('[')
if i == -1:
raise TypeError("Expected a datetime64 array, not %s", a.dtype)
return typestr[i + 1: -1] | bigcode/self-oss-instruct-sc2-concepts |
def find_dimension_contexts(instance,context,dimensions):
"""Returns a list of contexts containing the given dimension values and having the same period as the given context."""
contexts = []
for dimcontext in instance.contexts:
if dimcontext.period_aspect_value == context.period_aspect_value and di... | bigcode/self-oss-instruct-sc2-concepts |
def atoms_to_xyz_file(atoms, filename, title_line='', append=False):
"""
Print a standard .xyz file from a list of atoms
Arguments:
atoms (list(autode.atoms.Atom)): List of autode atoms to print
filename (str): Name of the file (with .xyz extension)
Keyword Arguments:
title_lin... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
import torch
def prepare_batch(batch: List) -> Dict[str, torch.Tensor]:
"""
Take a list of samples from a Dataset and collate them into a batch.
Returns:
A dictionary of tensors
"""
input_ids = torch.stack([example['input_ids'] for example in... | bigcode/self-oss-instruct-sc2-concepts |
def variants(*strings):
"""Creates three variants of each string:
- lowercase (e.g. `husky`)
- title version (e.g. `Husky`)
- uppercase (e.g. `HUSKY`)
:return: A list of all variants of all given strings.
:rtype: list
"""
result = []
for string in strings:
lowercase = strin... | bigcode/self-oss-instruct-sc2-concepts |
def get_start_end(title, print_char="-", size=150, nl_str=True, nl_end=True):
"""
:return:
start: ------------------------------- <title> -------------------------------
end: -----------------------------------------------------------------------
"""
title_len = len(title)
print_ch... | bigcode/self-oss-instruct-sc2-concepts |
def has_text(text):
"""
Return False if the text is empty or has only spaces.
A true value is returned otherwise.
"""
# This is faster than "not text.rstrip()" because no new string is
# built.
return text and not text.isspace() | bigcode/self-oss-instruct-sc2-concepts |
import torch
def jacobian(f, x):
"""Computes the Jacobian of f w.r.t x.
This is according to the reverse mode autodiff rule,
sum_i v^b_i dy^b_i / dx^b_j = sum_i x^b_j R_ji v^b_i,
where:
- b is the batch index from 0 to B - 1
- i, j are the vector indices from 0 to N-1
- v^b_i is a "test... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def mimes_to_codec(mimes: List[str]) -> str:
"""Utility function for turning mutagen's mime types into a single codec string."""
if any(["codecs=opus" in m for m in mimes]):
return "opus"
else:
return mimes[0].replace("audio/", "") | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_source_id(source_id):
"""Retrieve the source_name and version information from a source_id.
Not complex logic, but easier to have in one location.
Standard form: {source_name}_v{search_version}.{submission_version}
Arguments:
source_id (str): The source_id to split. If this is... | bigcode/self-oss-instruct-sc2-concepts |
def pruneListByIndices(lst, indices):
"""Prunes a `lst` to only keep elements at the given `indices`."""
return [l for i, l in enumerate(lst) if i in indices] | bigcode/self-oss-instruct-sc2-concepts |
def get_machine_type(cpu_cores, memory, accelerator_type):
"""Returns the GCP AI Platform machine type."""
if accelerator_type.value == "TPU_V2" or accelerator_type.value == "TPU_V3":
return "cloud_tpu"
machine_type_map = {
(4, 15): "n1-standard-4",
(8, 30): "n1-standard-8",
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def unk_init(dim):
"""
Initialize out of vocabulary words as uniform
distribution in range 0 to 1.
:param dim: word embedding dimension
:return: randomly initialized vector
"""
return torch.rand(1, dim) | bigcode/self-oss-instruct-sc2-concepts |
def convert_txt_to_inds(txt, char2ind, eos=False, sos=False):
"""
Args:
txt: Array of chars to convert to inds.
char2ind: Lookup dict from chars to inds.
Returns: The converted chars, i.e. array of ints.
"""
txt_to_inds = [char2ind[ch] for ch in txt]
if eos:
txt_to_ind... | bigcode/self-oss-instruct-sc2-concepts |
def pairwise_prefs(A,P,params,distance_bound=1):
"""
Return a dict pref that gives for each pair (i,j) of alternatives from A
the sum, over voters that prefer i to j, of how many positions higher i is than
j in the voter's ballot (but not more than "distance_bound" per ballot).
If params["missing_pr... | bigcode/self-oss-instruct-sc2-concepts |
def common_parent(a, b):
"""
Find the common parent tile of both a and b. The common parent is the tile
at the highest zoom which both a and b can be transformed into by lowering
their zoom levels.
"""
if a.zoom < b.zoom:
b = b.zoomTo(a.zoom).container()
elif a.zoom > b.zoom:
... | bigcode/self-oss-instruct-sc2-concepts |
import calendar
import random
def random_day(month):
"""Return a random int within the range of the month provided."""
dayRange = calendar.monthrange(2020, month)[1]
return random.randint(1, dayRange) | bigcode/self-oss-instruct-sc2-concepts |
def divide(dataset, target_column):
"""
Divides the dataset in X and y.
This function is called inside prepare_data function (see below) in order to prepare data.
:param dataset:
:param target_column:
:return: X and y
"""
X = dataset.drop(columns=[target_column])
y = dataset[target_... | bigcode/self-oss-instruct-sc2-concepts |
def extract_post_story(div_id_story):
"""
Extracts the post text contents, strips line breaks and whitespaces.
"""
before_keyword = "SHARE /"
post_story = div_id_story.get_text().strip().replace('\n', ' ').replace('\r', '')
return post_story[:post_story.find(before_keyword)] | bigcode/self-oss-instruct-sc2-concepts |
def mean(x):
"""Return the mean of an array across the first dimension."""
return x.mean(axis=0) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Set
def _extract_target_labels(targets_in_order: List[dict], target_name: str) -> Set[str]:
"""Collect a set of all the board names from the inherits field in each target in the hierarchy.
Args:
targets_in_order: list of targets in order of inheritance, star... | bigcode/self-oss-instruct-sc2-concepts |
def svm_predict(classifier, test_data):
"""
Predict the labels of the given test data with the given classifier pipeline.
:param sklearn.pipeline.Pipeline classifier: The classifier pipeline with which the labels of the given test data should be predicted
:param pandas.core.series.Series test_data:... | bigcode/self-oss-instruct-sc2-concepts |
def contfractbeta(
a: float, b: float, x: float, ITMAX: int = 5000, EPS: float = 1.0e-7
) -> float:
"""Continued fraction form of the incomplete Beta function.
Code translated from: Numerical Recipes in C.
Example kindly taken from blog:
https://malishoaib.wordpress.com/2014/04/15/the-beautiful-be... | bigcode/self-oss-instruct-sc2-concepts |
def readMetadata(lines):
"""
Read metadata tags and values from a TNTP file, returning a dictionary whose
keys are the tags (strings between the <> characters) and corresponding values.
The last metadata line (reading <END OF METADATA>) is stored with a value giving
the line number this tag was found in.... | 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.