seed
stringlengths
1
14k
source
stringclasses
2 values
def _choose_num_bootstraps(sample_size, mean_size, fuel): """Choose how many bootstraps to do. The fuel is the total number floats we get to draw from `np.random.choice`, which is a proxy for the amount of time we're allowed to spend bootstrapping. We choose how many bootstraps to do to make sure we fit in ...
bigcode/self-oss-instruct-sc2-concepts
def add_totals_to_dataframe(df, row_name="Row total", col_name="Column total"): """Add row and column totals to dataframe""" df.loc[row_name]= df.sum(numeric_only=True, axis=0) df.loc[:,col_name] = df.sum(numeric_only=True, axis=1) return df
bigcode/self-oss-instruct-sc2-concepts
import torch def segment2distance(points, segment, max_dis=None, eps=0.1): """Encode segment based on distances. Args: points (Tensor): Shape (n,), [center]. segment (Tensor): Shape (n, 2), "start, end" format max_dis (float): Upper bound of the distance. eps (float): a small ...
bigcode/self-oss-instruct-sc2-concepts
def CreateOnHostMaintenanceMessage(messages, maintenance_policy): """Create on-host-maintenance message for VM.""" if maintenance_policy: on_host_maintenance = messages.Scheduling.OnHostMaintenanceValueValuesEnum( maintenance_policy) else: on_host_maintenance = None return on_host_maintenance
bigcode/self-oss-instruct-sc2-concepts
import posixpath def ls(session, path): # pylint: disable=invalid-name """ List files on an iRODS server. Args: session (iRODS.session.iRODSSession): iRODS session path (String): path on iRODS server to list. Must be absolute. """ coll = session.collections.get(po...
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping from typing import Optional from typing import Any from functools import reduce def get_value_by_dot_notation(dict_obj: Mapping, key: str, default: Optional[Any] = ...) -> Any: """ Return the value of a key in dot notation in a arbitrarily nested Mapping. dict_obj: Mapping k...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_md5_checksum_of_file(file_path): """ Get the md5 checksum of the local file. """ return hashlib.md5(open(file_path, 'rb').read()).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def lF_value (ER,EF,dfnum,dfden): """ Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees o...
bigcode/self-oss-instruct-sc2-concepts
def clamp(a, x, b): """ Ensures x lies in the closed interval [a, b] :param a: :param x: :param b: :return: """ if x > a: if x < b: return x else: return b else: return a
bigcode/self-oss-instruct-sc2-concepts
def calc_sidak_correction(alpha_value, num_total_tests): """ Calculates the Sidak correction for multiple hypothesis testing for a given alpha-value. See http://en.wikipedia.org/wiki/Bonferroni_correction#.C5.A0id.C3.A1k_correction for more detail. Returns the Sidak corrected p-value upon ...
bigcode/self-oss-instruct-sc2-concepts
def fuel_requirement(mass: int) -> int: """Base fuel requirements for a single module.""" return (mass // 3) - 2
bigcode/self-oss-instruct-sc2-concepts
def kph2ms(v): """ This function converts velocity from kph to m/s. """ return v / 3.6
bigcode/self-oss-instruct-sc2-concepts
import importlib def _import_func(dotted_str): """ Imports function using dot-notation string. :param dotted_str: Dotted path to function like `module.submodule.func` :return: func """ module_name, factory = dotted_str.rsplit('.', 1) module = importlib.import_module(module_name) try: ...
bigcode/self-oss-instruct-sc2-concepts
import random def weighted_choice(weight): """ Parameters ---------- weight: float Weight of choosing a chromosome Returns ------- Bool random (not uniform) choice """ # This help to don't generate individuals of the same size on average p = random.uniform(0, weig...
bigcode/self-oss-instruct-sc2-concepts
def dominant_sign(elements): """ A function to calculate the dominant sign of a set of numbers :param elements: a list of numbers :return: the dominant sign """ return sum(elements) / abs(sum(elements))
bigcode/self-oss-instruct-sc2-concepts
def generate_managed_policy(resource_name: str, permissions): """Generate an IAM Managed Policy resource""" return { resource_name: { "Type": "AWS::IAM::ManagedPolicy", "Properties": { "PolicyDocument": {"Version": "2012-10-17", "Statement": permissions} ...
bigcode/self-oss-instruct-sc2-concepts
def print_break(text): """Helper function to print clean sections to console.""" print("") print("#" * 64) print("# " + text) print("#" * 64) return None
bigcode/self-oss-instruct-sc2-concepts
import math def multiply(int1, int2): """ An implementation of the Karatsuba algorithm for integer multiplication. Returns product of int1 and int2. """ # Base case if (int1 < 10 and int1 > -10) or (int2 < 10 and int2 > -10): return int1 * int2 # Set up strInt1 = str(int1) ...
bigcode/self-oss-instruct-sc2-concepts
import re def trim_alphanum(name, length=100): """Replace non alphanum charss with '-', remove leading, trailing and double '-' chars, trim length""" return re.sub( '^-|-$', '', re.sub('[-]+', '-', re.sub('[^-a-zA-Z0-9]', '-', name[0:length])) )
bigcode/self-oss-instruct-sc2-concepts
def normalize(np_array, x_max=255, x_min=0): """ Normalize data to a scale of: [0,1] Default: normalizing pixel values [0,255]. """ return (np_array - x_min) / (x_max - x_min)
bigcode/self-oss-instruct-sc2-concepts
def generate_normalized_name(name_tuple): """ Generates a normalized name (without whitespaces and lowercase) """ name_arr = list(name_tuple) name_arr.sort() name_str = ''.join(name_arr) return name_str.lower()
bigcode/self-oss-instruct-sc2-concepts
def name_equality_check(setup_deps, pipfile_deps): """ Checks that all names present in either dependency file are present in both dependency files Args: setup_deps (dict<str, list<tuple<str, str>>>): Dictionary from setup.py dependency name keys to a list of tuples as a...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def _registered_commands(group='mupub.registered_commands'): """ Get our registered commands. Iterates the entry points and returns the registered commands as a dictionary. :param str group: The group in setup.py to iterate. :return: A table containing command-name:command p...
bigcode/self-oss-instruct-sc2-concepts
import requests def is_reachable(url: str, redirects: bool) -> bool: """ Test if a web site is reachable. This test has two different uses in the certmgr container: 1. Test if the NGINX server is up; and 2. Test if the device, e.g. the NUC, is connected to the internet. Args: url...
bigcode/self-oss-instruct-sc2-concepts
def output_formatter(value): """ Output formatter for environment variable values. Parameters ------------ value Value to format. Returns -------- :class:`str` Formatted value. """ if value is not None and not isinstance(value, bool): return str(value) ...
bigcode/self-oss-instruct-sc2-concepts
import six import json def load_config(config): """Load configuration. """ if isinstance(config, six.string_types): with open(config, "r") as f: return json.load(f) elif isinstance(config, dict): return config else: raise NotImplementedError("Config must be a js...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Any def type_match(object_: List[Dict[str, Any]], obj_type: str) -> bool: """ Checks if the object type matches for every object in list. :param object_: List of objects :param obj_type: The required object type :return: True if al...
bigcode/self-oss-instruct-sc2-concepts
def obs_filter_step(distance, view): """ Perfectly observe the agent if it is within the observing agent's view. If it is not within the view, then don't observe it at all. """ return 0 if distance > view else 1
bigcode/self-oss-instruct-sc2-concepts
def from_hex(string): """This function is the inverse of `to_hex`.""" return bytes.fromhex(string.replace(":", ""))
bigcode/self-oss-instruct-sc2-concepts
def flatten(seq): """Transforms tree lists like ['a', ['b', 'c'], 'd'] to strings like '(a, (b, c), d)', enclosing each tree level in parens.""" ret = [] for one in seq: if type(one) is list: ret.append(flatten(one)) else: ret.append(one) return "(" + ", ".join(re...
bigcode/self-oss-instruct-sc2-concepts
def dupTest(object): """Checks objects for duplicates enabled (any type) object: Blender Object. Returns: Boolean - True if object has any kind of duplicates enabled.""" if (object.is_duplicator): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def m_shape(A): """ Determines the shape of matrix A. """ rows = len(A) columns = len(A[0]) if A else 0 return rows, columns
bigcode/self-oss-instruct-sc2-concepts
def get_loco_connlines(track, loco): """ Returns a dict of lines representing each locos base connections. """ # Build loco to base connection lines loco_connlines = [] for conn in [c for c in loco.conns.values() if c.connected()]: linepath = [] linepath.append({'lat': conn.conn_to.c...
bigcode/self-oss-instruct-sc2-concepts
def _spec_arg(k, kwargs, v): """ Specify a default argument for constructors of classes created from .mat files. Used in autogenerated classes like ModelParameters. Parameters ---------- k : string Name of variable whose value will be assigned kwargs : dict Dictionary of ke...
bigcode/self-oss-instruct-sc2-concepts
import jinja2 def load_template(filename, **kwargs): """Wrapper for loading a jinja2 template from file""" templateLoader = jinja2.FileSystemLoader( searchpath="./powerhub/templates/payloads/" ) templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = filename template =...
bigcode/self-oss-instruct-sc2-concepts
def sort_by_length(arr): """Sort list of strings by length of each string.""" return sorted(arr, key=len)
bigcode/self-oss-instruct-sc2-concepts
def remove_id(iterable, obj_id): """ Removes any entry from iterable with matching ID :param iterable: list - A collection of objects (ie. Dataset, Model) :param obj_id: int - The ID matching the objects contained in iterable :return: The iterable without an entry for the filter ID """ retu...
bigcode/self-oss-instruct-sc2-concepts
def removeAlias(aname: str) -> str: """Return a query to remove a character's alias.""" return (f"DELETE FROM alias " f"WHERE aname='{aname}';" )
bigcode/self-oss-instruct-sc2-concepts
import functools def pmg_serialize(method): """ Decorator for methods that add MSON serializations keys to the dictionary. See documentation of MSON for more details """ @functools.wraps(method) def wrapper(*args, **kwargs): self = args[0] d = method(*args, **kwargs) #...
bigcode/self-oss-instruct-sc2-concepts
def init_field(height=20, width=20): """Creates a field by filling a nested list with zeros.""" field = [] for y in range(height): row = [] for x in range(width): row.append(0) field.append(row) return field
bigcode/self-oss-instruct-sc2-concepts
def _x_zip_matcher(art): """ Is this artifact the x.zip file? """ return art['name'].endswith('.zip')
bigcode/self-oss-instruct-sc2-concepts
def calc_death_rate(confirmed, deaths): """ Calculates the daily death rate in confirmed cases. :param confirmed: DataFrame of confirmed cases :param deaths: DataFrame of deaths :return: DataFrame of daily death rate """ death_rate = (deaths / confirmed) * 100 death_rate = death_rate.fil...
bigcode/self-oss-instruct-sc2-concepts
def get_users_location(data: dict) -> list: """ Get users' names and location from dictionary with information about these users. Return a list of users. >>> get_users_location(get_json("@BarackObama")) [['Bill Clinton', 'New York, NY'], ['Kamala Harris', 'California']] >>> get_users_location(...
bigcode/self-oss-instruct-sc2-concepts
import click import json def echo_event(data): """Echo a json dump of an object using click""" return click.echo(json.dumps(data, sort_keys=True, indent=2))
bigcode/self-oss-instruct-sc2-concepts
def read_txt(file_path, comment_str="#"): """Txt file reader that ignores comments and empty lines """ out = [] with open(file_path, "r", encoding="utf-8") as f: for line in f: line = line.partition(comment_str)[0] line = line.strip() if len(line) > 0: ...
bigcode/self-oss-instruct-sc2-concepts
def conform_speaker(speaker, main_character): """ Normalize speaker names using the predefined map. """ CHARACTERS_MAP = { 'a' : 'amicus', 'm' : main_character, 'unk': '?????', 'com': 'computer', 'c' : 'cassius', 'ca' : 'cato', 'al' : 'alexios'...
bigcode/self-oss-instruct-sc2-concepts
def add (x, y): """returns the sum of two vectors""" return x [0] + y [0], x [1] + y [1]
bigcode/self-oss-instruct-sc2-concepts
def poentry__cmp__( self, other, compare_obsolete=True, compare_msgstr=True, compare_occurrences=True, ): """Custom comparation ``__cmp__`` function for :py:class:`polib.POEntry`. This function acts like a workaround for https://github.com/izimobil/polib/pulls/95 and add custom entries ...
bigcode/self-oss-instruct-sc2-concepts
def _range_intersection(a, b): """ Returns the range where the two given ranges intersect. Parameters ---------- a, b: Each is a list of two coordinate values designating a min-max range. Returns ------- A range (a list of two numbers) where the two given ranges int...
bigcode/self-oss-instruct-sc2-concepts
def index_of_value(a,value): """ Get value of index that is closest to value in the array/list a. """ return min(range(len(a)),key=lambda i: abs(a[i] - value))
bigcode/self-oss-instruct-sc2-concepts
def convert_ube4b_seqid(seqid): """ convert the ube4b sequence ids in the raw data to the standard mutation format """ ube4b_wt = "IEKFKLLAEKVEEIVAKNARAEIDYSDAPDEFRDPLMDTLMTDPVRLPSGTVMDRSIILRHLLNSPTDPFNRQMLTESMLEPVPELKEQIQAWMREKQSSDH" positions, replacements = seqid.split("-") positions = [int(p) for p ...
bigcode/self-oss-instruct-sc2-concepts
import torch def gather_states(all_states, indices): """Gathers states from relevant indices given all states. Args: all_states: States for all indices (N x T x d) indices: Indices to extract states from (N) Returns: gathered_states: States gathers at given indices (N x d) ""...
bigcode/self-oss-instruct-sc2-concepts
def AddNoGlob(options): """ If the option 'no_glob' is defined, add it to the cmd string. Returns: a string containing the knob """ string = '' if hasattr(options, 'no_glob') and options.no_glob: string = ' --no_glob' return string
bigcode/self-oss-instruct-sc2-concepts
def parse_mime_type(mime_type): """Carves up a mime_type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xht...
bigcode/self-oss-instruct-sc2-concepts
import torch def check_models_have_same_weights(model_1: torch.nn.Module, model_2: torch.nn.Module): """ Checks whether two networks have the same weights @param model_1: Net to be checked @param model_2: Net to be checked @return: True iff the two networks have the same weights """ model...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def package_version(package): """Retrieve python package version.""" try: version = pkg_resources.get_distribution(package).version except pkg_resources.DistributionNotFound: version = "0.0.1.dev1" return version
bigcode/self-oss-instruct-sc2-concepts
def solve_quad_mod (a, b, c, n): """ Solve a quadratic equation modulo n. Find all solutions to the quadratic equation a*x^2 + b*x + c = 0 mod n for integer n. Here a, b, c are integers. """ solutions = [] for x in range (n): poly_val = (a*x*x + b*x + c) % n if poly...
bigcode/self-oss-instruct-sc2-concepts
def case_insensitive_header_lookup(headers, lookup_key): """Lookup the value of given key in the given headers. The key lookup is case insensitive. """ for key in headers: if key.lower() == lookup_key.lower(): return headers.get(key)
bigcode/self-oss-instruct-sc2-concepts
def key_to_idx(key): """convert a binary LMDB key to an integer index""" return int(key)
bigcode/self-oss-instruct-sc2-concepts
def wrap_markdown(text): """ Wraps text in multiline markdown quotes. """ return '```' + text + '```'
bigcode/self-oss-instruct-sc2-concepts
def image_extents(product, geotransform, step=1): """Get the corner coordinates from the opened raster. Fetches a list of latitude and longitude values for the boundary of a given satellite product with a given pixel step along the border. :param product: the opened Gdal dataset :type product:...
bigcode/self-oss-instruct-sc2-concepts
def add_boundary_ummg(ummg: dict, boundary_points: list): """ Add boundary points list to UMMG in correct format Args: ummg: existing UMMG to augment boundary_points: list of lists, each major list entry is a pair of (lon, lat) coordinates Returns: dictionary representation of u...
bigcode/self-oss-instruct-sc2-concepts
def reserved(word): """Parse for any reserved words. This is needed for words such as "class", which is used in html but reserved in Python. The convention is to use "word_" instead. """ if word == 'class_': return 'class' return word
bigcode/self-oss-instruct-sc2-concepts
def CheckExtractedInformationValid(rootGroup, verbose=False): """ **CheckExtractedInformationValid** - Checks for valid extracted information given a netCDF root node Parameters ---------- rootGroup: netCDF4.Group The root group node of a Loop Project File verbose: bool A fl...
bigcode/self-oss-instruct-sc2-concepts
def merge_pept_dicts(list_of_pept_dicts:list)->dict: """ Merge a list of peptide dict into a single dict. Args: list_of_pept_dicts (list of dict): the key of the pept_dict is peptide sequence, and the value is protein id list indicating where the peptide is from. Returns: dict: the key i...
bigcode/self-oss-instruct-sc2-concepts
def downsample(state): """Downsamples an image on the first 2 dimensions Args: state: (np array) with 3 dimensions """ return state[::2, ::2, :]
bigcode/self-oss-instruct-sc2-concepts
import string import itertools def _tokenize_by_character_class(s): """ Return a list of strings by splitting s (tokenizing) by character class. For example: _tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':', '54', ':', '52', ' ', 'M...
bigcode/self-oss-instruct-sc2-concepts
def _par_indices(names): """ Given a list of objects, returns a mapping of objects in that list to the index or indices at which that object was found in the list. """ unique = {} for idx, name in enumerate(names): # Case insensitive name = name.upper() if name in unique...
bigcode/self-oss-instruct-sc2-concepts
def offset_limit(func): """ Decorator that converts python slicing to offset and limit """ def func_wrapper(self, start, stop): offset = start limit = stop - start return func(self, offset, limit) return func_wrapper
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def readGenomeSizeFromTxt(fname) -> Dict[str, int]: """ Read genome information. Args: ----- fname: a txt file contains genome information Returns: ----- A dictionary contains SQ as key and SL as value, otherwise None """ # first check if fname...
bigcode/self-oss-instruct-sc2-concepts
def input_yesno(prompt, default=None): """ ask the user to enter Yes or No prompt: string to be shown as prompt default: True (=Yes), False (=No), or None (can not leave empty) """ while True: value = input(prompt).strip() if not value: if default is None: ...
bigcode/self-oss-instruct-sc2-concepts
def get_edge_string(edge, is_incoming_edge, to_node=True): """ Create string representing the edge. :param edge: Edge object :param is_incoming_edge: Boolean, True if edge is incoming from the perspective of a node :param to_node: Boolean, output both from and to node labels if True :return: Str...
bigcode/self-oss-instruct-sc2-concepts
import glob def get_files(root_dir): """ Get all files in the root directory. """ return list(glob.iglob(root_dir + '**/**', recursive=True))
bigcode/self-oss-instruct-sc2-concepts
def get_parm_val(parm=None,key=None): """ Return the value of a key >>> get_parm_val(parm={'test':'val'},key='test') 'val' >>> get_parm_val(parm={'test':'val'},key='foo') >>> """ if parm and key in parm.keys(): return parm[key] else: return None
bigcode/self-oss-instruct-sc2-concepts
import getpass import socket from datetime import datetime def update_header(header, comments=[], remove_keywords=[], update_keywords={}, remove_old_comments=False, write_meta=True): """Update FITS header. Parameters ---------- header : astropy.io.fits.Header FITS header. ...
bigcode/self-oss-instruct-sc2-concepts
def convert_to_list(data): """Convert input into a list for further processing.""" if data is not None: if isinstance(data, list): return data else: return [data]
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_yaml_file(filename): """Loads dictionary from yaml file. Args: filename: file to read from Returns: Dict """ with open(filename) as f: contents = yaml.load(f, Loader=yaml.FullLoader) return contents
bigcode/self-oss-instruct-sc2-concepts
import string def get_objects_list(n, np_random_state = None): """ Generates a list of (object, weight) tuples of size n :param n: list size :return: (object, weight) tuples list of size n """ alphabet_string = string.ascii_uppercase weights = list(range(1, n + 1)) if np_random_state: ...
bigcode/self-oss-instruct-sc2-concepts
def tokenize(entity, field_name): """Convert an entity and a field_name into a unique string token.""" return "%s###%s" % (entity.name, field_name)
bigcode/self-oss-instruct-sc2-concepts
def GetAllFieldInDocument(document, field_name): """Find and return all fields with the provided name in the document.""" fields = [] for f in document.field_list(): if f.name() == field_name: fields.append(f) return fields
bigcode/self-oss-instruct-sc2-concepts
def get_po_line_created_date(po_line_record): """Get created date from PO Line record or return a note that it was not found.""" if po_line_record.get("created_date") is not None: po_line_created_date = "".join( filter(str.isdigit, po_line_record["created_date"][2:]) ) else: ...
bigcode/self-oss-instruct-sc2-concepts
import json def __read_json_report(directory): """ Reads json report. :param directory: The path to store the report. :return returns json report. """ with open(directory + '/report.json', 'r') as f: json_report = json.load(f) return json_report
bigcode/self-oss-instruct-sc2-concepts
def floyd_warshall(graph): """ Takes an adjacency matrix graph of edge distances and returns a matrix of shortest distances between all pairs of vertices. Distances of -1 indicate there is no path between a pair of vertices. See: http://www.cs.cornell.edu/~wdtseng/icpc/notes/graph_part3.pdf :r...
bigcode/self-oss-instruct-sc2-concepts
def strip_from_end(s, c): """ Remove all 'c' from the end of 's' :param s: a string. :param c: character or substring to remove :return: remainder of 's' """ if c: while s.endswith(c): s = s[:-len(c)] return s
bigcode/self-oss-instruct-sc2-concepts
def path_to_DNA_read_pairs(path: list, dist: int) -> str: """Convert a path of substrings to a condensed string :param path: the ordered path of substring pairs :type path: list (of tuples (of strs)) :param dist: the distance between the read-pairs :type dist: int :returns: the overall string ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def run_unit_test(c, verbose=True): """ Runs all methods in a unit test class. Parameters ---------- c : Class Unit test class """ if verbose: print('BEGIN testing {}'.format(c.__name__)) methods = inspect.getmembers(c, predicate=inspect.isfunction) ...
bigcode/self-oss-instruct-sc2-concepts
import logging def infolog(caplog): """Sets the log capture level to ``logging.INFO``.""" caplog.set_level(logging.INFO) return caplog
bigcode/self-oss-instruct-sc2-concepts
import binascii def hex2b64(hex_string): """Convert a hex string into a base64 encoded string.""" return binascii.b2a_base64(binascii.a2b_hex(hex_string)).strip()
bigcode/self-oss-instruct-sc2-concepts
import pyarrow.parquet as pq def parquet_decoder(stream): """ Read parquet formatted files """ table = pq.read_table(stream) return table
bigcode/self-oss-instruct-sc2-concepts
import itertools def hyperparameter_combinations(hyperparameters): """ Generate all possible combinations of hyperparameters. Inputs: hyperparameters: dict containing pairs of hyperparameter names and set of values to try. Example: {"learning_rate": [0.1, 0.2], "epoch...
bigcode/self-oss-instruct-sc2-concepts
import ntpath def cleanUpPath(path): """ This function: 1) Removes extra beginning/trailing quotes, spaces and newlines. 2) Normalizes the paths. 3) Appends './' to all paths. All paths are assumed to be relative to the Makefile. Returns a clean up path. """ # Remove extra quotes and ...
bigcode/self-oss-instruct-sc2-concepts
def rotate_pitches(chord, n=1): """ Given a chord (tuple) of pitch classes, such as (1, 2, 3, 4), returns the next rotation of pitches, such as (2, 3, 4, 1), depending on what n is. Params: * chord (tuple): an ordered pitch class set * n (int): number of places to shift. A positive...
bigcode/self-oss-instruct-sc2-concepts
def blanknone(v): """ Return a value, or empty string if it's None. """ return '' if v is None else v
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_rmse(y, yhat): """ Calculates Root Mean Square Error :param y: Actual values as series :param yhat: Predicted values as series :return: RMSE value """ error_sqr = (y - yhat)**2 error_sqr_rooted = list(map(lambda x: math.sqrt(x), error_sqr)) rmse = sum(erro...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_tags(s): """Removes xml-style tags.""" return re.sub('</*.*?>', '', s)
bigcode/self-oss-instruct-sc2-concepts
import json def make_json_writer(func, *args, **kwargs): """ Return a function that receives a file-like object and writes the return value of func(*args, **kwargs) as JSON to it. """ def writer(f): json.dump(func(*args, **kwargs), f, indent=1, ensure_ascii=False) return writer
bigcode/self-oss-instruct-sc2-concepts
def dequote(string: str) -> str: """ Return string by removing surrounding double or single quotes. """ if (string[0] == string[-1]) and string.startswith(('\'', '"')): return string[1:-1] return string
bigcode/self-oss-instruct-sc2-concepts
def _ConvertOldMastersFormatToNew(masters_to_blacklisted_steps): """Converts the old masters format to the new rules dict. Args: masters_to_blacklisted_steps: A dict in the format: { 'master1': ['step1', 'step2', ...], 'master2': ['step3', 'step4', ...] } Returns: A dict in the l...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_tags(tweet): """ Takes a string and removes retweet and @user. """ tweet = re.sub('(^rt:? @[a-z]+[a-z0-9-_]+)|(\W+rt:? @[a-z]+[a-z0-9-_]+)', ' ', tweet) # remove retweeted at tweet = re.sub('(@[a-z0-9]+[a-z0-9-_]+)', ' ', tweet) # remove users return t...
bigcode/self-oss-instruct-sc2-concepts
def merge(arr1: list, arr2: list) -> list: """Merge two arrays for merge sort Args: arr1 (list): the first array arr2 (list): the second array Returns: list: the merged array """ merged = [] # Compare elements for both arrays while arr1 and arr2: if (arr1[0...
bigcode/self-oss-instruct-sc2-concepts