seed
stringlengths
1
14k
source
stringclasses
2 values
def _key_in_string(string, string_formatting_dict): """Checks which formatting keys are present in a given string""" key_in_string = False if isinstance(string, str): for key, value in string_formatting_dict.items(): if "{" + key + "}" in string: key_in_string = True ...
bigcode/self-oss-instruct-sc2-concepts
def compare_two_model_index(index_1, index_2): """ If the two input index's row and column and their parent is equal, then they are equal for test. """ return (index_1.row() == index_2.row()) \ and (index_1.column() == index_2.column()) \ and (index_1.parent() == index_2.parent())
bigcode/self-oss-instruct-sc2-concepts
import json def get_json_from_file_path(path): """ Get the content of the json file and convert it into an object """ f = None result = None # noinspection PyBroadException try: f = open(path, "r", encoding="utf-8") json_str = f.read().strip() result = json.loads(js...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def connect( graph: List[List[int]], next_ver: int, current_ind: int, path: List[int] ) -> bool: """ Memeriksa apakah mungkin untuk menambahkan berikutnya ke jalur dengan memvalidasi 2 pernyataan 1. Harus ada jalan antara titik saat ini dan berikutnya 2. Vertex berikutn...
bigcode/self-oss-instruct-sc2-concepts
def addr_alignment(addr): """Compute the maximum alignment of a specified address, up to 4.""" return addr & 1 or addr & 2 or 4
bigcode/self-oss-instruct-sc2-concepts
def get_entry_ids(entry): """Creates a trakt ids dict from id fields on an entry. Prefers already populated info over lazy lookups.""" ids = {} for lazy in [False, True]: if entry.get('trakt_movie_id', eval_lazy=lazy): ids['trakt'] = entry['trakt_movie_id'] elif entry.get('trakt_...
bigcode/self-oss-instruct-sc2-concepts
def add(number_x: int, number_y: int): """Adds two numbers.""" return number_x + number_y
bigcode/self-oss-instruct-sc2-concepts
def get_instances_for_service(service_id: str, client) -> list: """ Returns list of registered instance for service with id <service_id>""" return client.list_instances(ServiceId=service_id).get('Instances', [])
bigcode/self-oss-instruct-sc2-concepts
def check_insertion_order(metadict_inst, expected): """ Ensure that the keys of `metadict_inst` are in the same order as the keys in `expected`. The keys case is ignored. """ def normalise_keys(lst_pairs): return [key.lower() for key, _ in lst_pairs] assert normalise_keys(metadict_...
bigcode/self-oss-instruct-sc2-concepts
def diagonal(matrix, reverse=False): """ Return matrix' diagonal (count from the the back if reverse = True). """ diag = 0 if not reverse: for i in range(len(matrix)): diag += matrix[i][i] else: for i in range(len(matrix)): diag += matrix[i][(len(matrix) - 1) - i]...
bigcode/self-oss-instruct-sc2-concepts
def flatten_whois(whois_record): """ Flattens a whois record result Args: whois_record (dict): A WHOIS record Returns: dict: A flattened WHOIS result """ flat_whois = dict() flat_whois["domainName"] = whois_record["domainName"] if "createdDate" in whois_record: f...
bigcode/self-oss-instruct-sc2-concepts
def rc_prescription_from_pm_and_imc(efl, f_pm, pm_vertex_to_focus): """Design a Ritchey-Chrétien telescope from information about its primary mirror. Parameters ---------- efl : float system effective focal length f_pm : float focal length of the primary mirror (should be negative) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path import csv def _preprocess_csv(file_path: Union[str, Path], delimiter: str): """Validates a CSV file and returns the data as a list of lists""" if isinstance(file_path, str): file_path = Path(file_path) if not file_path.exists(): raise Val...
bigcode/self-oss-instruct-sc2-concepts
def remove_comment(line): """ 与えられた文字列の"::"以降(右)を除去する Args: line: コメントを取り除きたい文字列 Return: 先頭がコメントだった場合(コメントのみの行だった場合): 空文字 それ以外: コメント部分を取り除いた文字列 """ return "" if line.index("::") == 0 else line.split("::")[0]
bigcode/self-oss-instruct-sc2-concepts
def _getitem_from_frame(f_locals, key, default=None): """ f_locals is not guaranteed to have .get(), but it will always support __getitem__. Even if it doesnt, we return ``default``. """ try: return f_locals[key] except Exception: return default
bigcode/self-oss-instruct-sc2-concepts
def get_edges(graph: dict) -> set: """ Return a set of couples that represents all of the edges. @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]} >>> get_edges(graph)...
bigcode/self-oss-instruct-sc2-concepts
import random def SampleNegativeEdges(graph, num_edges): """Samples `num_edges` edges from compliment of `graph`.""" random_negatives = set() nodes = list(graph.nodes()) while len(random_negatives) < num_edges: i1 = random.randint(0, len(nodes) - 1) i2 = random.randint(0, len(nodes) - 1) if i1 == ...
bigcode/self-oss-instruct-sc2-concepts
def split_train_test(data, test_data_size: int): """Splits data into train and test. Args: data: All data. test_data_size: Size of the `test` data. Size of the `train` will be `len(data) - test_data_size`. """ train_data = data[:-test_data_size] test_data = d...
bigcode/self-oss-instruct-sc2-concepts
def _is_dictionary(arg): """Check if argument is an dictionary (or 'object' in JS).""" return isinstance(arg, dict)
bigcode/self-oss-instruct-sc2-concepts
def _weight(entry): """ Sum a power of frequency. Word frequencies have a skew with a long tail toward infrequent. """ weight = 500 * entry[0] ** 0.25 for i in range(3, len(entry), 2): weight -= (entry[i] / 100.0) ** 4 * 100 return weight
bigcode/self-oss-instruct-sc2-concepts
def split_nums_chars(str_: str) -> tuple[str, str]: """Splits the numbers and characters from a string Args: str_: The string to split Returns: A tuple containing the characters and the numbers """ nums = "".join([i for i in str_ if i.isnumeric()]) chars = "".join([i for i in s...
bigcode/self-oss-instruct-sc2-concepts
def capitalize(text: str) -> str: """ Capitalize the first letter only. >>> capitalize("") '' >>> capitalize("alice") 'Alice' >>> capitalize("BOB") 'BOB' >>> capitalize("alice and bob") 'Alice and bob' """ if not text: return "" ...
bigcode/self-oss-instruct-sc2-concepts
def TestSuiteName(test_key): """Returns the test suite name for a given TestMetadata key.""" assert test_key.kind() == 'TestMetadata' parts = test_key.id().split('/') return parts[2]
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import pickle def deserialize(input_file: str) -> Any: """ Load data stored by ``serialize()``. :param input_file: path to file when data was stored by serialize() :return: list of objects """ with open(input_file, "rb") as f: return pickle.load(f)
bigcode/self-oss-instruct-sc2-concepts
def _make_compound_key(table, key): """Returns a list of columns from `column_key` for `table` representing potentially a compound key. The `column_key` can be a name of a single column or list of column names.""" if not isinstance(key, (list, tuple)): key = [key] return [table.columns[nam...
bigcode/self-oss-instruct-sc2-concepts
def get_region(regions, cluster): """ Gets the region name from the cluster ID Args: regions (dictionary): dictionary of regions where shortname is the key to the long name value. cluster (str): the OCI ID of the cluster in question. Returns a string of the region long name. """ re...
bigcode/self-oss-instruct-sc2-concepts
def convert_lanes_to_edges(lanes): """ Convert lanes (iterable) to edges (iterable). Remove lane index from the end and then remove duplicates while retaining order. Also works with single lane str. >>> lanes >>> ['1175109_0', '1175109_1', '1175109_2', '1183934_0', '1183934_1', '1183934_2']...
bigcode/self-oss-instruct-sc2-concepts
def load_blob(reader): """Given a reader object, such as returned by ExtBoar.get_blob(), fetches all the blocks and returns the reconstructed data. Warning: this means the whole blob will be loaded into RAM.""" return "".join(reader)
bigcode/self-oss-instruct-sc2-concepts
def window_landmark(region, flank_upstream=50, flank_downstream=50, ref_delta=0, landmark=0): """Define a window surrounding a landmark in a region, if the region has such a landmark, (e.g. a start codon in a transcript), accounting for splicing of the region, if the region is discontinuous Paramet...
bigcode/self-oss-instruct-sc2-concepts
def hex2rgb(hexstring): """ convert #RRGGBB to an (R, G, B) tuple """ hexstring = hexstring.strip() if hexstring[0] == '#': hexstring = hexstring[1:] if len(hexstring) != 6: raise ValueError("input #%s is not in #RRGGBB format" % hexstring) r, g, b = hexstring[:2], hexstring[2:4], hexstring[...
bigcode/self-oss-instruct-sc2-concepts
def error(msg, value=None) -> str: """Formats msg as the message for an argument that failed to parse.""" if value is None: return '<[{}]>'.format(msg) return '<[{} ({})]>'.format(msg, value)
bigcode/self-oss-instruct-sc2-concepts
def get_python_module_names(file_list, file_suffix='.py'): """ Return a list of module names from a filename list. """ module_names = [m[:m.rfind(file_suffix)] for m in file_list if m.endswith(file_suffix)] return module_names
bigcode/self-oss-instruct-sc2-concepts
def _symplectic_euler_step(state, force, dt): """Compute one step of the symplectic euler approximation. Parameters ---------- state : array-like, shape=[2, dim] variables a time t force : callable dt : float time-step Returns ------- point_new : array-like, shape=[...
bigcode/self-oss-instruct-sc2-concepts
def early_stop(patience, max_factor, vae_loss_val, em_loss_val): """ Manual implementation of https://keras.io/api/callbacks/early_stopping/. :param patience: max number of epochs loss has not decreased :param max_factor: max_factor * current loss is the max acceptable loss :param vae_loss_val: list...
bigcode/self-oss-instruct-sc2-concepts
def combinations(n, k): """ Given two integers n and k, return all possible combinations of k numbers out of 1 2 3 ... n. n = 4 k = 2 [ [1,2], [1,3], [1,4], [2,3], [2,4], [3,4], ] """ def find_c...
bigcode/self-oss-instruct-sc2-concepts
import re def humansort(l): """Sort in place a given list the way humans expect. NB: input list is modified E.g. ['file11', 'file1'] -> ['file1', 'file11'] """ def alphanum_key(s): # Turn a string into a list of string and number chunks. # e.g. "z23a" -> ["z", 23, "a"] d...
bigcode/self-oss-instruct-sc2-concepts
def fix_ecm_move_conflicts(conflict_ecm_list, move_order_text): """Get user input to sort out ECMs moved in both directions It is possible that with a given set of active and inactive ECMs and some sets of keywords given by the user to move ECMs in bulk from one list to the other, there wil...
bigcode/self-oss-instruct-sc2-concepts
def extract_value_other_gdf(x,gdf,col_name): """ Function to extract value from column from other GeoDataFrame Arguments: *x* : row of main GeoDataFrame. *gdf* : geopandas GeoDataFrame from which we want to extract values. *col_name* : the column name from whic...
bigcode/self-oss-instruct-sc2-concepts
def get_dimensions6(o_dim, ri_dim): """ Get the orientation, real/imag, height and width dimensions for the full tensor (6 dimensions).""" # Calculate which dimension to put the real and imaginary parts and the # orientations. Also work out where the rows and columns in the original # image were ...
bigcode/self-oss-instruct-sc2-concepts
import torch def voxel_box_decode(box_encodings, anchors): """ box decode for pillar-net in lidar :param box_encodings: [N, 7] Tensor, normal boxes: x, y, z, w, l, h, r :param anchors: [N, 7] Tensor, anchors :param encode_angle_to_vector: whether encoding angle to vector :param smooth_dim: whe...
bigcode/self-oss-instruct-sc2-concepts
def bboxes_to_pixels(bbox, im_width, im_height): """ Convert bounding box coordinates to pixels. (It is common that bboxes are parametrized as percentage of image size instead of pixels.) Args: bboxes (tuple): (xmin, xmax, ymin, ymax) im_width (int): image width in pixels im_heigh...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_file(f): """Finds the MD5 hash of a file. File must be opened in bytes mode. """ h = hashlib.md5() chunk_size = 65536 # 64 KiB for chunk in iter(lambda: f.read(chunk_size), b''): h.update(chunk) return h.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def kev2ang(energy): """ Convert energy [keV] to wavelength [Å] """ wlen = 12.398/energy return wlen
bigcode/self-oss-instruct-sc2-concepts
def listify(x): """If x is already a list, do nothing. Otherwise, wrap x in a list.""" if isinstance(x, list): return x else: return [x]
bigcode/self-oss-instruct-sc2-concepts
def em_complete(job): """Verify that energy minimization has completed""" return job.isfile('em.gro')
bigcode/self-oss-instruct-sc2-concepts
def world_to_index(x, y, origin, resolution, width): """ Convert World coordinates to index """ x = (x - origin[0]) / resolution y = (y - origin[1]) / resolution return y * width + x
bigcode/self-oss-instruct-sc2-concepts
def wait_for_button_press(button): """ Wait for a button to be pressed and released. Parameter: - `button` (Button): an instance of the EV3 Button() class return the Button name that was pressed. """ pressed = None while True: allpressed = button.buttons_pressed if bool(a...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_field_content(s: str) -> bool: """ Returns True if string s can be stored in a SubStation field. Fields are written in CSV-like manner, thus commas and/or newlines are not acceptable in the string. """ return "\n" not in s and "," not in s
bigcode/self-oss-instruct-sc2-concepts
import builtins def is_a_builtin(word) -> bool: """ Returns True if a word is a builtin python object Args: word: word to check Returns: True if word is builtin python object """ return str(word) in dir(builtins)
bigcode/self-oss-instruct-sc2-concepts
def invalidate_cols(platemap, cols, valid=False): """Returns updated plate map with specified columns invalidated. :param platemap: Plate map to use :type platemap: pandas dataframe :param wells: Columns to invalidate, e.g. [1, 2, 3] :type wells: int or list of ints :param valid: Sets the s...
bigcode/self-oss-instruct-sc2-concepts
import getpass def get_current_user() -> str: """Return the name of the current user""" return getpass.getuser()
bigcode/self-oss-instruct-sc2-concepts
def increase_threshold(thresh, thresh_inc): """ Increase the threshold based on a string Inputs: - thresh Initial threshold - thresh_inc How the threshold should be increased. "xN": multiply by N "+N": increase by N ...
bigcode/self-oss-instruct-sc2-concepts
import math def hd(inc, sd): """ Calculate horizontal distance. :param inc: (float) inclination angle in degrees :param sd: (float) slope distance in any units """ return sd * math.cos(math.radians(inc))
bigcode/self-oss-instruct-sc2-concepts
def get_symbol_name(*args): """Return fully-qualified symbol name given path args. Example usage: >>> get_symbol_name('ZenPacks.example.Name') 'ZenPacks.example.Name' >>> get_symbol_name('ZenPacks.example.Name', 'schema') 'ZenPacks.example.Name.schema' >>> get_symbol_...
bigcode/self-oss-instruct-sc2-concepts
from typing import Set import re def solidity_unresolved_symbols(hex_code: str) -> Set[str]: """ Return the unresolved symbols contained in the `hex_code`. Note: The binary representation should not be provided since this function relies on the fact that the '_' is invalid in hex encoding. ...
bigcode/self-oss-instruct-sc2-concepts
def remove_comment(content): """Remove comment from the content.""" lines = content.split('\n') return '\n'.join([line for line in lines if not line.startswith('#')]).strip()
bigcode/self-oss-instruct-sc2-concepts
def person(request): """ A dummy fixture, parametrized so that it has two instances """ if request.param == 0: return "world" elif request.param == 1: return "self"
bigcode/self-oss-instruct-sc2-concepts
import re def clean_tag(tag, allow_none=False, mytype='string', default=None, max_len=254): """ Clean the given `tag` instance depending of its `mytype`.""" if default is None and allow_none is False: if mytype == 'string': default = 'unknown' elif mytype == 'integer': ...
bigcode/self-oss-instruct-sc2-concepts
def calculate_square(num): """ Returns the square of a given number """ return num * num
bigcode/self-oss-instruct-sc2-concepts
def fmt_color(text: str, color: str) -> str: """Format a string in a certain color (`<span>`). Args: text: The text to format. color: Any valid CSS color. Returns: A `<span>` that contains the colored text. """ return u'<span style="color:{color}">{text}</span>'.format( ...
bigcode/self-oss-instruct-sc2-concepts
def RIGHT(text, n): """Slices string(s) a specified number of characters from right. Parameters ---------- text : list or string string(s) to be sliced from right. n : integer number of characters to slice from right. Must be greater than zero. Returns ------- list or s...
bigcode/self-oss-instruct-sc2-concepts
def _stringify_int(integer): """Convert an integer into a string formatted with thousand separators. Parameters ---------- integer : int The integer. Returns ------- str The integer turned into a string. """ return "{:,}".format(integer)
bigcode/self-oss-instruct-sc2-concepts
def calc_percent(per, cent): """Takes the parameters "per" and "cent" and returns the calculated percent.""" return (per / cent) * 100
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List from typing import Tuple def edge_has_empty_node( edge: Union[List[str], Tuple[str, str]], node_ids_with_labels ) -> bool: """Check if edge contains an empty node.""" return not str(node_ids_with_labels[edge[0]]) or not str( node_ids_with_labels[edg...
bigcode/self-oss-instruct-sc2-concepts
def cli(ctx, state="", history_id="", invocation_id="", tool_id="", workflow_id="", user_id="", date_range_min="", date_range_max="", limit=500, offset=0, user_details=False): """Get all jobs, or select a subset by specifying optional arguments for filtering (e.g. a state). Output: Summary information for eac...
bigcode/self-oss-instruct-sc2-concepts
def build_table(x, perceiver, cache, cache_emb, topk, return_images=False, index_dir=None): """ Maps each image to a linearized row in a table. Each entry in a row is delimited by "|". Each entry comes from the t...
bigcode/self-oss-instruct-sc2-concepts
def match_pattern(resource: bytes, pattern: bytes, mask: bytes, ignored: bytes): """ Implementation of algorithm in:x https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern True if pattern matches the resource. False otherwise. """ resource = bytearray(resource) pattern = bytearray(...
bigcode/self-oss-instruct-sc2-concepts
import torch def mse(target, predicted): """Mean Squared Error""" return torch.mean((target - predicted)**2)
bigcode/self-oss-instruct-sc2-concepts
def min_scalar_type(a): """ min_scalar_type(a) For scalar ``a``, returns the data type with the smallest size and smallest scalar kind which can hold its value. For non-scalar array ``a``, returns the vector's dtype unmodified. Floating point values are not demoted to integers, and comple...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def force_list(value: Any) -> list: """ Convert `value` to list or return `value` if it is already a list. :param value: Value to convert to list. """ return list(value) if isinstance(value, (list, tuple)) else [value]
bigcode/self-oss-instruct-sc2-concepts
def get_frameshift_lengths(num_bins): """Simple function that returns the lengths for each frameshift category if `num_bins` number of frameshift categories are requested. """ fs_len = [] i = 1 tmp_bins = 0 while(tmp_bins<num_bins): if i%3: fs_len.append(i) tm...
bigcode/self-oss-instruct-sc2-concepts
def set_appliance_discovery_emails( self, email_list: list[str], ) -> bool: """Update email addresses configured to be notified for discovery of new appliances. .. warning:: Replaces the current configured list with the new list. To add an email, first retrieve the current emails an...
bigcode/self-oss-instruct-sc2-concepts
def _check_not_none(value, name): """Checks that value is not None.""" if value is None: raise ValueError(f"`{name}` must be specified.") return value
bigcode/self-oss-instruct-sc2-concepts
def fill_point(x, y, z, _): """ Returns a string defining a set of minecraft fill coordinates relative to the actor. In minecraft, the y axis denotes the vertical (non-intuitively). """ return f'~{int(x)} ~{int(z)} ~{int(y)}'
bigcode/self-oss-instruct-sc2-concepts
import operator def advance_permutation(a, increasing=True, forward=True): """ Advance a list of unique, ordered elements in-place, lexicographically increasing or backward, by rightmost or leftmost digit. Returns False if the permutation wrapped around - i.e. went from lexicographically greatest...
bigcode/self-oss-instruct-sc2-concepts
def prompt(msg): """Prompt the user for input.""" value = "" while not value: value = input(msg+" ").strip() return value
bigcode/self-oss-instruct-sc2-concepts
import math def p_sequence(expected_value, days_a_week, upper_bound, step): """Calcualtes the capacity values to test.""" lower_p = math.ceil(days_a_week*expected_value/0.99) # PSEQ per week, pseq per day PSEQ = sorted(list(set([int(lower_p + step*i) for i in range(upper_bound)]))) pseq = [round(i...
bigcode/self-oss-instruct-sc2-concepts
import torch def jitter(X, ox, oy): """ Helper function to randomly jitter an image. Inputs - X: PyTorch Tensor of shape (N, C, H, W) - ox, oy: Integers giving number of pixels to jitter along W and H axes Returns: A new PyTorch Tensor of shape (N, C, H, W) """ if ox != 0: left = X[:, :, :, ...
bigcode/self-oss-instruct-sc2-concepts
import time def add_timer(func_name): """Decorator to add timing to run commands """ def decorator(func): def wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) end = time.time() line_len = 88 print("") print...
bigcode/self-oss-instruct-sc2-concepts
import re def to_slug(value): """ Convert a string to a URL slug. """ value = value.lower() # Space to dashes value = re.sub(r'[\s_]+', '-', value) # Special characters value = re.sub(r'[^a-z0-9\-]+', '', value, flags=re.I) # Extra dashes value = re.sub(r'\-{2,}', '-', value) va...
bigcode/self-oss-instruct-sc2-concepts
def get_digits_by_length(patterns, length): """Find all digits of a given length.""" return [pattern for pattern in patterns if len(pattern) == length]
bigcode/self-oss-instruct-sc2-concepts
def calculate_fantasy_points(player) -> float: """ Calculate the fantasy points this player earned from the formula Kill = 0.3 Death = -0.3 Assist = 0.15 Last Hit = 0.003 Gold per minute = 0.002 EXP per minute = 0.002 Seconds of enemy stuns = 0.07 Every 1000 allied healing done ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from functools import reduce from operator import mul def multiples_of(numbers: List[int]): """ Calculate the number of numbers multiples in the range being their product. Eg for 3, 5 compute amount of 3 & 5 multiples in frame size 3 * 5 """ frame_size = reduce(mul, numbers...
bigcode/self-oss-instruct-sc2-concepts
def positive_percent(df): """ compute the percentage of positive Tweets: 2 is positive :param df: a tweet dataframe :return: percentage of positive tweets """ assert 'sentiment_vader_percent' in df, "The pandas dataframe should contain the sentiment of each tweet" positive = 0 for sentim...
bigcode/self-oss-instruct-sc2-concepts
def gcd(a, b): """ Find the greatest common divisor of two integers a, b. This uses Euclid's algorithm. For integer a, b, it holds that a * b = LCM(a, b) * GCD(a, b). Starting from range(1, 21), we replace two head elements x, y to LCM(x, y). """ dividend = max(a, b) divisor = min(a, b)...
bigcode/self-oss-instruct-sc2-concepts
def rot(c, n): """ This function rotates a single character c forward by n spots in the alphabet. """ # check to ensure that c is a single character assert(type(c) == str and len(c) == 1) if 'a' <= c <= 'z': new_ord = ord(c) + n if new_ord > ord('z'): new_ord = ord(c) + ...
bigcode/self-oss-instruct-sc2-concepts
def format_headers(headers): """ Return a list of column names formatted as headers :param headers: :return list: """ new_headers = [] for h in headers: h: str = h if '_' in h: h = h.replace('_', ' ') # if 'id' in h: # h = h.replace('id', '') ...
bigcode/self-oss-instruct-sc2-concepts
import yaml def build_content(csvdict): """ Construct a new dictionary that will be used to populate the template. """ yamlkeys = ['title', 'excerpt', 'tags', 'mentors', 'badge', 'level'] #yamlkeys = ['title', 'excerpt', 'tags'] yamldict = {} content = csvdict.copy() #sidekeys = ['me...
bigcode/self-oss-instruct-sc2-concepts
def _kern_class(class_definition, coverage_glyphs): """Transpose a ttx classDef {glyph_name: idx, glyph_name: idx} --> {idx: [glyph_name, glyph_name]} Classdef 0 is not defined in the font. It is created by subtracting the glyphs found in the lookup coverage against all the glyphs used to define t...
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Union def normalize( data: torch.Tensor, mean: Union[float, torch.Tensor], stddev: Union[float, torch.Tensor], eps: Union[float, torch.Tensor] = 0.0, ) -> torch.Tensor: """ Normalize the given tensor. Applies the formula (data - mean) / (stddev + eps). ...
bigcode/self-oss-instruct-sc2-concepts
def get_xarray_subset( dataset, variable_name, time_step_indices, xy_slice_indices ): """ Returns a subset of the provided dataset. The source dataset is restricted to the variable and indices supplied. When contiguous time step and XY slice indices are supplied, the resulting DataArray is a view of t...
bigcode/self-oss-instruct-sc2-concepts
def encrypt_letter(letter): """Encrypt a single letter Arguments: letter {char} -- The character to encrypt Returns: char -- The encrypted character """ inc_ord_char = ord(letter) + 3 if letter.isupper(): if inc_ord_char > 90: inc_ord_char = inc_ord_c...
bigcode/self-oss-instruct-sc2-concepts
def float_to_pcnt(x): """Convert a float to a percentage string, e.g. 0.4 -> '40%'.""" return '{}%'.format(round(x * 100))
bigcode/self-oss-instruct-sc2-concepts
def resolve_integer_or_float(*numbers): """Cast float values as integers if their fractional parts are close to zero. Parameters ---------- numbers : sequence Number(s) to process. Returns ------- A number or list of numbers, appropriately transformed. """ if len(number...
bigcode/self-oss-instruct-sc2-concepts
def test_module(client): """ Returning 'ok' indicates that the integration works like it suppose to. Connection to the service is successful. Args: client: HelloWorld client Returns: 'ok' if test passed, anything else will fail the test """ result = client.say_hello('DBot') ...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def groupby_name(bindings, tier=0): """ Groups bindings by the name fragment specified by tier. Input bindings can be not sorted. The order of the bindings remains initial in scope of its group. Yields: (name, [binding(s)...]) tuples. """ res = Order...
bigcode/self-oss-instruct-sc2-concepts
def get_location(datetime, position_df): """Create a tuple of the date_time, latitude and longitude of a location in a dataframe from a given date_time.""" latitude = position_df[position_df.date_time == datetime].latitude.item() longitude = position_df[position_df.date_time == datetime].longitude.item() ...
bigcode/self-oss-instruct-sc2-concepts
import math def gen_abd_params(N, f, dummy=None): """ Generate possible values of n, q1, q2 """ quorum_params = [] quorum_params_append = quorum_params.append for n in range(2*f+1, N+1): for q1 in range(math.ceil((N-1)/2), n-f+1): for q2 in range(math.ceil((N-1)/2), n-f+1): ...
bigcode/self-oss-instruct-sc2-concepts
def is_close(a, b, rel_tol=1e-09, abs_tol=0): """Determines whether two numbers are nearly equal. The maximum of the relative-based and absolute tolerances is used to test equality. This function is taken from `math.isclose` in Python 3 but is explicitly implemented here for Python 2 compatibility...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle_file(file_name, encoding='latin1'): """Loads a pickle file. :param file_name: File name (extension included). :type file_name: pathlib.Path :param encoding: Encoding of the file. :type encoding: str :return: Loaded object. :rtype: object | list | dict | numpy....
bigcode/self-oss-instruct-sc2-concepts