seed
stringlengths
1
14k
source
stringclasses
2 values
import math def euclidean_distance_native(u, v): """Computes the Euclidean distance between two vectors, represented as Python lists. Args: u (List[float]): A vector, represented as a list of floats. v (List[float]): A vector, represented as a list of floats. Returns: float: ...
bigcode/self-oss-instruct-sc2-concepts
def del_pos(s): """ Deletes part-of-speech encoding from an entity string, if present. :param s: Entity string. :return: Entity string with part-of-speech encoding removed. """ if s.endswith("/n") or s.endswith("/a") or s.endswith("/v") or s.endswith("/r"): s = s[:-2] return s
bigcode/self-oss-instruct-sc2-concepts
def _sortValue_familyName(font): """ Returns font.info.familyName. """ value = font.info.familyName if value is None: value = "" return value
bigcode/self-oss-instruct-sc2-concepts
import builtins def builtin_target(obj): """Returns mock target string of a builtin""" return f"{builtins.__name__}.{obj.__name__}"
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def bits_to_int(list_): """ Converts a big-endian bit string to its integer representation. >>> bits_to_int([1, 0, 1]) 5 """ return reduce( lambda a, x: a | (1 << x[1]) if x[0] == 1 else a, zip(list_, range(len(list_) - 1, -1, -1)), 0, ...
bigcode/self-oss-instruct-sc2-concepts
def tier_from_site_name(s): """ Splits site name by _ (underscore), and takes only the first part that represents tier. """ split = s.split('_') tier = str(split[0]) return tier
bigcode/self-oss-instruct-sc2-concepts
def _get_line_index(line_or_func, lines): """Return the appropriate line index, depending on ``line_or_func`` which can be either a function, a positive or negative int, or None. """ if hasattr(line_or_func, '__call__'): return line_or_func(lines) elif line_or_func: if line_or_func ...
bigcode/self-oss-instruct-sc2-concepts
def ToString(bval): """Convert a bytes type into a str type Args: bval: bytes value to convert Returns: Python 3: A bytes type Python 2: A string type """ return bval.decode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
def parse_image_size(image_size): """Parse "100x100" like string into a tuple.""" return tuple(map(int, image_size.split("x")))
bigcode/self-oss-instruct-sc2-concepts
def unwrap_model(model_wrapper): """Remove model's wrapper.""" model = model_wrapper.module return model
bigcode/self-oss-instruct-sc2-concepts
import torch def torch_multinomial(input, num_samples, replacement=False): """ Like `torch.multinomial()` but works with cuda tensors. Does not support keyword argument `out`. """ if input.is_cuda: return torch_multinomial(input.cpu(), num_samples, replacement).cuda() else: ret...
bigcode/self-oss-instruct-sc2-concepts
def dna_2_rna(dna_str): """ Transcribes DNA into RNA RNA differs from DNA in that it contains a base called uracil in place of thymine. An RNA string is formed by replacing all occurrences of 'T' in the DNA string with 'U'. Params: ------- dna_str: (str) DNA string. For example: "GATGGAACTTGACTACGTAAATT"...
bigcode/self-oss-instruct-sc2-concepts
def _translation_vectors(mtps, vector_table): """For a set of maximally translatable patterns, returns the set of translation vectors for the MTPs. Finds the common translation vectors for each note of a MTP, enabling finding all occurrences of the MTP. Args: mtps: All MTPs of a point set vector_table: Vecto...
bigcode/self-oss-instruct-sc2-concepts
import re def __get_auth_api_url(module, url): """ Return the parsed URL of the specific authentication API. :param AnsibleModule module: the ansible module :param str url: the initial URL of API :rtype: str """ # format the input for zmd_port if module.params['zmf_port'] is None: ...
bigcode/self-oss-instruct-sc2-concepts
def calc_temp_overlap(start_1, end_1, start_2, end_2): """ Calculate the portion of the first time span that overlaps with the second Parameters ---------- start_1: datetime start of first time span end_1: datetime end of first time span start_2: datetime start of se...
bigcode/self-oss-instruct-sc2-concepts
import socket def is_port_in_use(port: int) -> bool: """ Check if a porty is in use. """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(('localhost', port)) == 0
bigcode/self-oss-instruct-sc2-concepts
def process_fieldmap_solrf(data): """ Processes array of raw data from a rfdataX file into a dict. From the documentation: Here, the rfdataV5 file contains the Fourier coefficients for both E fields and B fields. The first half contains E fields, and the second half contains B fields. See m...
bigcode/self-oss-instruct-sc2-concepts
def utf8(s): """Convert to UTF-8.""" return s.encode("UTF-8")
bigcode/self-oss-instruct-sc2-concepts
def element_is_scrolled_to_left(element): """ Is the element scrolled to the left? :param element: :return: Boolean """ return int(element.get_property('scrollLeft')) == 0
bigcode/self-oss-instruct-sc2-concepts
import pathlib def as_uri(path): """ Converts the supplied path to file URI :param path: Path to be converted :return: Path as a fille URI """ p = pathlib.Path(path) return p.as_uri()
bigcode/self-oss-instruct-sc2-concepts
import torch def _tuple_splice_range(inputs, start, end): """ Splices each tensor element of given tuple (inputs) from range start (inclusive) to end (non-inclusive) on its first dimension. If element is not a Tensor, it is left unchanged. It is assumed that all tensor elements have the same first...
bigcode/self-oss-instruct-sc2-concepts
import uuid def is_uuid(id): """Verify if a string is an UUID""" try: v = uuid.UUID(id) except ValueError: v = None return isinstance(v, uuid.UUID)
bigcode/self-oss-instruct-sc2-concepts
import secrets def pick(s, n): """Return a string with n randomly picked characters from string s.""" return "".join(secrets.choice(s) for i in range(n))
bigcode/self-oss-instruct-sc2-concepts
import json import re def uri_twitch(bot, response, matches): """ Extract Twitch.tv channel information. """ channel = json.loads(response.text) title = channel['status'].replace('\n', ' ') title = re.sub(r'\s+', ' ', title).strip() game = channel['game'].replace('\n', ' ') game = re.sub(r'\s...
bigcode/self-oss-instruct-sc2-concepts
def delete(flavor_id, **kwargs): """Delete flavor.""" # NOTE: flavor_id can be any string, don't convert flavor name to uuid url = '/flavors/{flavor_id}'.format(flavor_id=flavor_id) return url, {}
bigcode/self-oss-instruct-sc2-concepts
def compute_denominator(log_strike, variance, deriv_1, deriv_2): """ Compute denominator in local vol equation. Args: log_strike: The log-strike. variance: The variance. deriv_1: The first derivative of variance wrt log strike. deriv_2: The second derivative of variance wrt...
bigcode/self-oss-instruct-sc2-concepts
def _LookupTargets(names, mapping): """Returns a list of the mapping[name] for each value in |names| that is in |mapping|.""" return [mapping[name] for name in names if name in mapping]
bigcode/self-oss-instruct-sc2-concepts
import requests def connect_to_endpoint(url, headers): """Fetches latest information of a Twitter handle Args: url: URL to make a GET call headers: Headers need for authentication Returns: List of tweets in json format """ response = requests.request("GET", url, headers=he...
bigcode/self-oss-instruct-sc2-concepts
def rotate(x, y, ctx, cty, ang) : """ Rotate catalog x,y against center (ctx,cty), using specified rotate angle args: x: ndarray of x, or scalar y: ndarray of y ctx: center x, scalar cty: center y ang: rotate angle, 0-7 0 keep original 1 CW 90 deg ...
bigcode/self-oss-instruct-sc2-concepts
def rank_order(df, rank_column, ascending=False): """ Given dataframe with a column of numerical values, order and rank those values. Allows for ties if a value is the same as the previous value. """ df = df.sort_values(rank_column, ascending=ascending).reset_index().drop('index', axis=1) ranki...
bigcode/self-oss-instruct-sc2-concepts
import copy def get_descendants(node, include_self=True): """ Return a flat list including `node` and all its descendants. Nodes returned are modified to remove the tree structure between them (set `children=[]`). """ results = [] if include_self: node_copy = copy.deepcopy(node) ...
bigcode/self-oss-instruct-sc2-concepts
def get_max_value(array): """ Finds (the first occurence of) maximum value in a 1D array. :param array: 1D array (there is no safety check on that) :return: (index, value) index Index of the maximum element. value Value of the maximum element. """ max_val = max(array) ...
bigcode/self-oss-instruct-sc2-concepts
def add_lowercase_context_to_sequences(seq, uc_s, uc_e, convert_to_rna=False): """ Given a sequence and uppercase middle region start (uc_s) and end (uc_e), make context region upstream + downstream lowercase. Two coordinates should be one-based. Return lowerca...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import re def guess_file(path: Path) -> str: """Guess the type of a file and return the corresponding file extension.""" lines = path.read_text().splitlines() MAX_LINES = 500 # noqa: N806 f77ish = True f90ish = False for i, line in enumerate(lines): if i >=...
bigcode/self-oss-instruct-sc2-concepts
def check_model_termination(ClockStruct,InitCond): """ Function to check and declare model termination *Arguments:*\n `ClockStruct` : `ClockStructClass` : model time paramaters `InitCond` : `InitCondClass` : containing current model paramaters *Returns:* `ClockStruct` : `ClockStructC...
bigcode/self-oss-instruct-sc2-concepts
def gtk_false(*args): """ GTK False default handler """ return False
bigcode/self-oss-instruct-sc2-concepts
def int_or_none(value): """ Returns int or none if int could not be converted """ try: return int(value) except ValueError: return None
bigcode/self-oss-instruct-sc2-concepts
def avg_item_count_character(cursor): """Returns the average number of items per character from sqlite cursor. Args: cursor (sqlite3.Cursor): cursor to sqlite database Returns: (float) Average number of items per character """ return cursor.execute("""SELECT AVG(item_ct) FROM( ...
bigcode/self-oss-instruct-sc2-concepts
def parse_uri(uri): """Extracts the host, port and db from an uri""" host, port, db = uri, 6379, 0 if len(host.split('/')) == 2: host, db = host.split('/') if len(host.split(':')) == 2: host, port = host.split(':') return host, int(port), int(db)
bigcode/self-oss-instruct-sc2-concepts
def distribution_to_particle(predictions, n_particles=50): """ Convert a distribution prediction to a particle prediction Args: predictions (Distribution): a batch of distribution predictions. n_particles (int): the number of particles to sample. """ return predictions.sample...
bigcode/self-oss-instruct-sc2-concepts
def nulls(data): """Returns keys of values that are null (but not bool)""" return [k for k in data.keys() if not isinstance(data[k], bool) and not data[k]]
bigcode/self-oss-instruct-sc2-concepts
def _process_ratios(value): """Helper function to convert the GPS ratios in float format""" return float(value[0])/float(value[1])
bigcode/self-oss-instruct-sc2-concepts
def normalize_path(path): """ Returns a normalized path from a `path` string. """ return "/" + path.strip("/")
bigcode/self-oss-instruct-sc2-concepts
def get_vgci_warnings(tc): """ extract warnings from the parsed test case stderr """ warnings = [] if tc['stderr']: for line in tc['stderr'].split('\n'): # For each line if "WARNING" in line and "vgci" in line: # If it is a CI warning, keep it ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_reps_path(params, split): """Return path to directory where dialogue representations are stored.""" directory = Path(params.path_to_representations) path_r = f'{params.bot}Bot_{params.bot_version}_representations_{split}.h5' return directory / path_r
bigcode/self-oss-instruct-sc2-concepts
import re def _include(path, includes, excludes): """ :params path: The file path to check whether to include :params includes: List of include regexs to apply :params excludes: List of exclude regexs to apply :returns True if the file path should be included, False """ if includes is No...
bigcode/self-oss-instruct-sc2-concepts
def inverted_y(coordinate_y, height): """反转y坐标。 Args: coordinate_y: y坐标。 height: 高度。 Returns: 新的y坐标 """ return abs(coordinate_y - height)
bigcode/self-oss-instruct-sc2-concepts
import collections def graph_inputs(name, **kwargs): """Creates a namedtuple of the given keys and values. Args: name (string): Name of the tuple. kwargs (tf.Tensor): One or more tensor(s) to add to the namedtuple's values. The parameter names are used as keys in the n...
bigcode/self-oss-instruct-sc2-concepts
def _port_in_range(value): """Return True if port is in expected range.""" return 49512 <= value <= 65535
bigcode/self-oss-instruct-sc2-concepts
def results_summary(results_data): """ Return a summary of the results stored in a dataframe. Returns a dict containing unique entities in each column Ignores the exp_data, f_min, min_params and time columns """ unique_vals_dict = {} col_list = list(results_data.columns.values) ...
bigcode/self-oss-instruct-sc2-concepts
import re import keyword def is_valid_identifier(var, allow_unicode=False): """Return true if var contains a valid Python identifier Parameters ---------- val : string identifier to check allow_unicode : bool (default: False) if True, then allow Python 3 style unicode identifiers....
bigcode/self-oss-instruct-sc2-concepts
import re def is_rgb_code(s: str) -> bool: """ Returns True if `s` appears to be a single rgb escape code. """ pattern = '^\033\\[((38)|(48));2;\\d{1,3};\\d{1,3};\\d{1,3}m' return re.match(pattern, s) is not None
bigcode/self-oss-instruct-sc2-concepts
def props_of_this_event(event, ts_tuple, run): """ Find the set of propositions that correspond to an event. Parameters ----------- event: A tuple An event is a tuple of the form (agent_no, run_pos). This argument can either be a tuple of events (simultaneous events) or a tuple of integers (single event). ...
bigcode/self-oss-instruct-sc2-concepts
import site from pathlib import Path def find_pkg(name): """Find package in site-packages""" for p in site.getsitepackages(): pkg_path = Path(p) / name if pkg_path.exists(): return pkg_path return None
bigcode/self-oss-instruct-sc2-concepts
import json def readfile(filepath): """ reads a pipeline json file and returns the resulting dictionary """ with open(filepath, "r") as json_file: json_data = json.load(json_file) return json_data
bigcode/self-oss-instruct-sc2-concepts
def points_to_region(region_pts): """ Reverse Voronoi region polygon IDs to point ID assignments by returning a dict that maps each point ID to its Voronoi region polygon ID. All IDs should be integers. :param region_pts: dict mapping Voronoi region polygon IDs to list of point IDs :return: dict ma...
bigcode/self-oss-instruct-sc2-concepts
def clean_file_name(filename): """Clean the filename for the client. If it has directory structure, purge it and give only the file name. :param filename: file name to be cleaned :return: cleaned filename """ if '/' in filename: filename = filename.split('/')[-1] return filename
bigcode/self-oss-instruct-sc2-concepts
def mean_normalize(x, mean_x, max_x, min_x): """ Mean normalization of input x, given dataset mean, max, and min. >>> mean_normalize(10, 10, 15, 5) 0.0 >>> mean_normalize(15, 20, 30, 10) -0.25 Formula from: https://en.wikipedia.org/wiki/Feature_scaling """ # If min=max, all va...
bigcode/self-oss-instruct-sc2-concepts
def calculate_centroid(gps_bounds): """Given a set of GPS boundaries, return lat/lon of centroid. gps_bounds -- (lat(y) min, lat(y) max, long(x) min, long(x) max) Returns: Tuple of (lat, lon) representing centroid """ return ( gps_bounds[0] + float(gps_bounds[1] - gps_bounds[0])/2...
bigcode/self-oss-instruct-sc2-concepts
import re def hasNewRating(filename): """ Checks if parameter file name already has a rating. Movie ratings are in the format (\d.\d) """ pattern = re.compile('\[IMDb [0-9].[0-9]\]') return pattern.search(filename) is not None
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import List def _resplit(parts: Iterable[str]) -> List[str]: """ Given a list of strings, returns a list of lines, by splitting each string into multiple lines where it contains newlines. >>> _resplit([]) [] >>> _resplit(['a', 'b']) ['a', 'b'] >...
bigcode/self-oss-instruct-sc2-concepts
def remove_empty_kps(coco_context): """Returns a list of valid keypoint annotations Arguments: coco_context: The initialized cocoapi class Returns: processed_idx (list): List of images with valid keypoint annotations """ processed_idx = [] image_idx_list = coco_cont...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def to_embed_timestamp(timestamp: int) -> datetime: """ Convert UNIX timestamp to datetime object for embed timestamps. :param timestamp: UNIX timestamp with seconds accuracy. :return: Timezone native datetime """ return datetime.utcfromtimestamp(timestamp)
bigcode/self-oss-instruct-sc2-concepts
def make_inverted(m, n): """ Given two integers m and n, write a function that returns a reversed list of integers between m and n. If the difference between m and n is even, include m and n, otherwise don't include. If m == n, return empty list If m < n, swap between m and n and continue. Example 1: Input: ...
bigcode/self-oss-instruct-sc2-concepts
def visparamsListToStr(params): """ Transform a list to a string formated as needed by ee.data.getMapId :param params: params to convert :type params: list :return: a string formated as needed by ee.data.getMapId :rtype: str """ n = len(params) if n == 1: newbands = '{}'...
bigcode/self-oss-instruct-sc2-concepts
def get_asa_owners(indexer_client, asset_id, asa_min_balance=0): """Search for ASAs owners Args: indexer_client (IndexerClient): Indexer Client V2 asset_id (int): ASA Asset ID asa_min_balance (int): Optional; ASA minimum balance expressed as minimal int units Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def coleman_liau_index(n_chars, n_words, n_sents): """https://en.wikipedia.org/wiki/Coleman%E2%80%93Liau_index""" return 5.879851 * (n_chars / n_words) - 29.587280 * (n_sents / n_words) - 15.800804
bigcode/self-oss-instruct-sc2-concepts
def choose_box(group, plot_data): """Given a set of overlapping bounding boxes and predictions, just choose a closest to stem box by centroid if there are multiples""" if group.shape[0] == 1: return group else: #Find centroid individual_id = group.individual.unique()[0] stem...
bigcode/self-oss-instruct-sc2-concepts
def organize_edges(edges, borders=None, default_border='land'): """ Organize edges in to various collections specified by borders. Required Arguments ------------------ * edges : List of edges of the form (node_number, node_number, ... , edge_type) The sort...
bigcode/self-oss-instruct-sc2-concepts
def isstrlessthan(string, length): """Checks if string is below length""" return len(string) < length
bigcode/self-oss-instruct-sc2-concepts
import re def _clean(text): """ Cleans the text: Lowercasing, trimming, removing non-alphanumeric""" return " ".join(re.findall(r'\w+', text, flags=re.UNICODE)).lower()
bigcode/self-oss-instruct-sc2-concepts
import json def read_config_file(filename): """ Read the json configuration file and return a map with the config entries """ with open(filename) as json_file: json_input = json.load(json_file) return json_input
bigcode/self-oss-instruct-sc2-concepts
def dim_col(d: int) -> str: """ Name of an dimension columns. Parameters ---------- d Dimension number. Returns ------- name: str Dimension name. Example ------- >>> from rle_array.testing import dim_col >>> dim_col(1) 'dim_1' """ return f"d...
bigcode/self-oss-instruct-sc2-concepts
import math def s1diff(a,b): """Angle from a to b in an anticlockwise direction.""" if b < a: b += 2*math.pi return b - a
bigcode/self-oss-instruct-sc2-concepts
def convert_length_in_minutes_to_hr_min_str(length_minutes=0): """ Convert minutes into something like 02h03m if given 123. Note that both hr and min are 0-padded """ hour = length_minutes // 60 minutes = length_minutes % 60 return "%02dh%02dm" % (hour, minutes)
bigcode/self-oss-instruct-sc2-concepts
def solve_linear_system_LU(matrix, syms): """ Solves the augmented matrix system using LUsolve and returns a dictionary in which solutions are keyed to the symbols of syms *as ordered*. The matrix must be invertible. Examples ======== >>> from sympy import Matrix >>> from sympy.abc im...
bigcode/self-oss-instruct-sc2-concepts
def PyDateTime_GET_DAY(space, w_obj): """Return the day, as an int from 1 through 31. """ return space.int_w(space.getattr(w_obj, space.newtext("day")))
bigcode/self-oss-instruct-sc2-concepts
def freeze_parameters(model): """ Freezes all parameters from a given model. Args: model (any of nff.nn.models) """ for param in model.parameters(): param.requires_grad = False return model
bigcode/self-oss-instruct-sc2-concepts
def get_stats(stat_int_list: list) -> list: """Return a list of stats in play. Argument(s): stat_int_list: list -- list of stat indices """ stat_list = [] for stat in stat_int_list: if stat == 0: stat_list.append("Hunger") elif stat == 1: stat_list.appen...
bigcode/self-oss-instruct-sc2-concepts
def convert_numeral(string: str) -> str: """ Convert a assembly numeral into a hexadecimal numeral :param string: A string representation of a simpSim numeral :return: Hexadecimal representation of the numeral """ return_num: int = 0 is_pointer: bool = string.startswith("[") and string.endsw...
bigcode/self-oss-instruct-sc2-concepts
import string import random def generateCharacters(charCount): """Generates ASCII lowercase random characters""" # https://www.educative.io/edpresso/how-to-generate-a-random-string-in-python letters = string.ascii_lowercase result = "".join(random.choice(letters) for i in range(charCount)) return ...
bigcode/self-oss-instruct-sc2-concepts
def _pair_members_to_new_node(dm, i, j, disallow_negative_branch_length): """Return the distance between a new node and decendants of that new node. Parameters ---------- dm : skbio.DistanceMatrix The input distance matrix. i, j : str Identifiers of entries in the distance matrix to...
bigcode/self-oss-instruct-sc2-concepts
def _sym_solve(Dinv, M, A, r1, r2, solve, splu=False): """ An implementation of [1] equation 8.31 and 8.32 References ---------- .. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point optimizer for linear programming: an implementation of the homogeneous a...
bigcode/self-oss-instruct-sc2-concepts
def root_app(expr): """Returns the pair (r, args) such that expr = r(*args) Arguments: - `expr`: an expression """ root = expr args = [] while root.is_app(): args.append(root.arg) root = root.fun #The arguments were collected in reverse order args.reverse...
bigcode/self-oss-instruct-sc2-concepts
def get_file_download_details(file_response): """ Return the download_link from the file_response. Used for updating the message with a download button. """ download_link = file_response['file']['url_private_download'] return download_link
bigcode/self-oss-instruct-sc2-concepts
def percentage(f): """ Return the percentage version of a float f """ return round(f * 100, 3)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def create_module_scratch(module_name): """Create a scratch that is easily found (by developers) and removed, and doesn't clutter up the working directories. """ path = Path("~").expanduser() for path_part in ".idaes", "_scratch", module_name: path = path / path_pa...
bigcode/self-oss-instruct-sc2-concepts
def recall(recs, truth, k=None): """ Compute recommendation recall. """ nrel = len(truth) if nrel == 0: return None if k is not None: nrel = min(nrel, k) recs = recs.iloc[:k] ngood = recs['item'].isin(truth.index).sum() return ngood / nrel
bigcode/self-oss-instruct-sc2-concepts
import torch def translation_error(pose_pred, pose_target): """ Angular error for rotation matrix :param pose_pred: shape (b, 3, 4), estimated pose :param pose_target: shape (b, 3, 4), target pose :return: float >>> import torch >>> pose_pred = torch.tensor([[1.0, 0, 0, 1], [0, 1, 0, 1],...
bigcode/self-oss-instruct-sc2-concepts
def _replace_match(text, match, replacement): """Expands a regexp match in the text with its replacement. Args: text: str. The text in which to perform the replacement. match: re.MatchObject. A match object that applies to "text". replacement: str. The string to replace the match wit...
bigcode/self-oss-instruct-sc2-concepts
def parse(css): """Parse a CSS style into a dict.""" result = {} for declaration in css.split(";"): if declaration: key, value = declaration.split(":") result[key] = value.strip() return result
bigcode/self-oss-instruct-sc2-concepts
def strip_whitespace(string_value): """ Return the input string without space, tab, or newline characters (for comparing strings) """ return ''.join( [c for c in string_value if c != ' ' and c != '\n' and c != '\t'] )
bigcode/self-oss-instruct-sc2-concepts
def amgxwrapper_poisson_read_runtimes(*filepaths): """Read the runtimes to solve the system for multiple runs. Parameters ---------- filepaths : tuple of strings or pathlib.Path objects Path of the files to read. Returns ------- runtimes : list of floats The runtimes. ...
bigcode/self-oss-instruct-sc2-concepts
def set_device_orientation_override(alpha: float, beta: float, gamma: float) -> dict: """Overrides the Device Orientation. Parameters ---------- alpha: float Mock alpha beta: float Mock beta gamma: float Mock gamma **Experimental** """ return { ...
bigcode/self-oss-instruct-sc2-concepts
def load_movies(path_movies='movies.csv'): """ Returns a dictionary mapping item_id to item_name and another dictionary mapping item_id to a list of genres """ data = {} genreMap = {} with open(path_movies, encoding = "utf8") as f_data: for line in f_data: parts = line.st...
bigcode/self-oss-instruct-sc2-concepts
def label_smoothing(x_onehot, epsilon=0.1): """ Label smoothing for one-hot type label. Args: x_onehot: Tensor with shape [..., depth] epsilon: float, default 0.1 The smoothing factor in range [0.0, 1.0]. Returns: Tensor with same shape as x_onehot, and its value ha...
bigcode/self-oss-instruct-sc2-concepts
def yesno(value, icaps=True): """ Return 'yes' or 'no' according to the (assumed-bool) value. """ if (value): str = 'Yes' if icaps else 'yes' else: str = 'No' if icaps else 'no' return str
bigcode/self-oss-instruct-sc2-concepts
def get_utt_id(segment): """ Gives utterance IDs in a form like: en_4156-a-36558-37113 """ return "{}-{}-{}-{}".format(segment.filename, segment.channel, int(segment.begin * 100), int(segment.end * 100),)
bigcode/self-oss-instruct-sc2-concepts
import re def GetCipdPackagePath(pkg_yaml_file): """Find CIPD package path in .yaml file. There should one line in .yaml file, e.g.: "package: chrome_internal/third_party/android_sdk/internal/q/add-ons" or "package: chromium/third_party/android_sdk/public/platforms" Args: pkg_yaml_file: The yaml file ...
bigcode/self-oss-instruct-sc2-concepts
def specific_gravity_to_gravity_points(sg, vol_gal): """Convert specific gravity to gravity points Parameters ---------- sg : float Specific gravity. vol_gal : float Wort volume, in gallons. Returns ------- gravity_points : float Gravity points. """ ...
bigcode/self-oss-instruct-sc2-concepts