seed
stringlengths
1
14k
source
stringclasses
2 values
import logging def set_log_level(config): """ Sets the default log level in the config dict. (logging.INFO) """ config['logger_level'] = logging.INFO return config
bigcode/self-oss-instruct-sc2-concepts
def find_idx_in_co(idx,co): """ Find the index such that co[index,0]==idx. """ for i in range(len(co)): if co[i,0] == idx: return i return None
bigcode/self-oss-instruct-sc2-concepts
def attr(obj, *path, **kwargs): """Safely get a nested attribute from an dictionary""" default = kwargs.get('default') if obj is None: return default res = obj for p in path: if p not in res: return default res = res[p] return res
bigcode/self-oss-instruct-sc2-concepts
def boolean_integer(string_or_bool): """ Converter to convert a boolean or "0"/"1" string to a boolean. """ if isinstance(string_or_bool, bool): return string_or_bool if string_or_bool.strip() == "1": return True return False
bigcode/self-oss-instruct-sc2-concepts
def distance_between_nodes(graph, node_1_id, node_2_id): """Calculate the distance between two nodes in a given graph. Args: graph: A Map object representing the graph containing the nodes to find the distance between node_1_id: An int representing the id of the first node in the pa...
bigcode/self-oss-instruct-sc2-concepts
import re def load(stream): """Load the parameter keys, values and descriptions from a SOG infile into a Python data structure. Comments (lines starting with !) and empty lines are ignored. :arg stream: An iterable (tyically a file object) containing SOG infile formatted lines separ...
bigcode/self-oss-instruct-sc2-concepts
def io(func): """ @io decorator for blocking io operations. In pycsp.parallel it has no effect, other than compatibility >>> @io ... def sleep(n): ... import time ... time.sleep(n) >>> sleep(0.01) """ return func
bigcode/self-oss-instruct-sc2-concepts
def read_string_file(file): """ Read a file as a string. Args: file: File name Returns: File content as a string """ with open(file, "r") as f: str = f.read() return str
bigcode/self-oss-instruct-sc2-concepts
def fwhm_dict(fwhm): """Convert a list of FWHM into a dictionary""" fwhm = [float(f) for f in fwhm] return {'fwhm_x': fwhm[0], 'fwhm_y': fwhm[1], 'fwhm_z': fwhm[2], 'fwhm_avg': fwhm[3]}
bigcode/self-oss-instruct-sc2-concepts
def create_query(languages, min_stars): """ Create the query string for the GitHub search API, based on the minimum amount of stars for a project, and the provided programming languages. """ # Notice we are calling .strip() on each language, to clear it of leading # and trailing whitespace...
bigcode/self-oss-instruct-sc2-concepts
def uppercase_first_letter(string): """Converts the first letter of a string to uppercase. >>> uppercase_first_letter('createHandler') 'CreateHandler' >>> uppercase_first_letter('CreateHandler') 'CreateHandler' >>> uppercase_first_letter('') '' """ return string[0].upper() + string[...
bigcode/self-oss-instruct-sc2-concepts
import re def make_container_name(image: str, suffix: str = "") -> str: """ Make default container name for the given Docker image. Args: image: Docker image tag. suffix: Suffix to append to the container name. Returns: Docker container name. """ name = re.sub(r"[^a-z...
bigcode/self-oss-instruct-sc2-concepts
def midi_to_pitch(midi: int) -> float: """Returns the absolute pitch in Hz for the given MIDI note value.""" return 440 * (2 ** ((midi - 69) / 12))
bigcode/self-oss-instruct-sc2-concepts
import copy def to_list(value): """ Takes a value and wraps it into a list if it is not already one. The result is returned. If None is passed, None is returned. Parameters ---------- value : object value to convert Returns ------- list or None A list that wraps t...
bigcode/self-oss-instruct-sc2-concepts
def remove_troublesome_chars(string: str): """Remove chars that cause trouble when pushed into postgres.""" if type(string) is not str: return string troublesome_chars = {'"': "", "'": "", "\n": " "} for k, v in troublesome_chars.items(): string = string.replace(k, v) return string
bigcode/self-oss-instruct-sc2-concepts
def _check_hospital_unhappy(resident, hospital): """Determine whether a hospital is unhappy because they are under-subscribed, or they prefer the resident to at least one of their current matches.""" return len(hospital.matching) < hospital.capacity or any( [hospital.prefers(resident, match) fo...
bigcode/self-oss-instruct-sc2-concepts
def escape_special_characters(input_string): """ Escape special characters to avoid unwanted behavior. Note that they are not stored in the index so you cannot search for them. Args: input_string (str): String to escape special characters of Returns: str: Input string that has its spe...
bigcode/self-oss-instruct-sc2-concepts
import typing def _normalize_sample_plan(sample, plan) -> typing.Tuple[list, list]: """Normalize samples and plans to list of samples and plans Parameters ---------- sample : Sample metadata. If a beamtime object is linked, an integer will be interpreted as the index appears in the `...
bigcode/self-oss-instruct-sc2-concepts
def clean_up_spacing(sentence: str) -> str: """Clean up leading and trailing space characters from the string. :param sentence: str - a sentence to clean of leading and trailing space characters. :return: str - a sentence that has been cleaned of leading and trailing space characters. """ return s...
bigcode/self-oss-instruct-sc2-concepts
def find_features(extent, df): """ given an extent and a dataframe, return a new dataframe containing only features that fall within the extent Parameters ---------- extent: list -- geographic extent in lon (deg E)/lat (deg N) df: the geopandas dataframe to slice """ xleft, xrigh...
bigcode/self-oss-instruct-sc2-concepts
def create_geometry_string(geometry): """This function converts MolecularData geometry to Dirac geometry. This function is taken from Openfermion-Psi4 interface. Args: geometry: A list of tuples giving the coordinates of each atom. example is [('H', (0, 0, 0)), ('H', (0, 0, 0.7414))]...
bigcode/self-oss-instruct-sc2-concepts
def update_firm(bac, firm): """Update the Firmicutes slider.""" return 100 - bac
bigcode/self-oss-instruct-sc2-concepts
def float_if_not_none(value): """ Returns an float(value) if the value is not None. :param value: None or a value that can be converted to an float. :return: None or float(value) """ return None if value is None else float(value)
bigcode/self-oss-instruct-sc2-concepts
def influxdb_config(influxdb): """ Returns the InfluxDB relation data as dict to use in config. :param influxdb: InfluxDB relation data object :type influxdb: InfluxdbClient :returns: dict with InfluxDB configuration options """ return { "host": influxdb.hostname(), "port": ...
bigcode/self-oss-instruct-sc2-concepts
def get_clipped_freq(records_l, records_r, records_s, minclip=4): """ Get the number of reads that are clipped over the breakpoints in a meaningful way. For the left and right breakpoints, look for clipping in the SV. For the single breakpoint, look for clipping on either side of the read. :param recor...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Any def convert_list_to_comma_separated_string(values: List[Dict[str, Any]], key: str) -> str: """ Retrieve values of an attribute in comma separated manner from response to populate human readable output :param: values: list of attribute...
bigcode/self-oss-instruct-sc2-concepts
def decrement_items(inventory, items): """Decrement items in inventory using elements from the `items` list. :param inventory: dict - inventory dictionary. :param items: list - list of items to decrement from the inventory. :return: dict - updated inventory with items decremented. """ for item...
bigcode/self-oss-instruct-sc2-concepts
def verse(bottle): """ Sing a verse """ current_bottle = '1 bottle' if bottle == 1 else f'{bottle} bottles' next_bottle = 'No more bottles' if bottle == 1 else f'{bottle - 1} bottle' if bottle == 2 else f'{bottle - 1} bottles' return '\n'.join([ f'{current_bottle} of beer on the wall,', ...
bigcode/self-oss-instruct-sc2-concepts
import calendar def utc_to_ts(y, m, d, hrs_utc): """Converts from a UTC tuple-time to unix epoch time. y,m,d: The year, month, day for which the conversion is desired. hrs_tc: Floating point number with the number of hours since midnight in UTC. Returns: The unix epoch time. >>...
bigcode/self-oss-instruct-sc2-concepts
def argmin(iterable): """Return index of minimum value.""" lowest_val = iterable[0] lowest_i = 0 for i, val in enumerate(iterable): if val < lowest_val: lowest_val = val lowest_i = i return lowest_i
bigcode/self-oss-instruct-sc2-concepts
def normalize_state(state): """Convert state into standardized (slurm style) state.""" state = state.lower() if state == 'queued': state = 'pending' return state
bigcode/self-oss-instruct-sc2-concepts
def set_file_content(file, content): """ write content to file :param file: the file to rewrite its content :param content: content to write to the given file """ nchar_written = 0 with open(file, 'w') as f: nchar_written = f.write(content) return nchar_written
bigcode/self-oss-instruct-sc2-concepts
def ensure_list(var): """Makes sure that `var` is a list. Parameters ---------- var List like object Returns ------- list `var` as list """ return var if type(var) is list else [var]
bigcode/self-oss-instruct-sc2-concepts
def get_entry_by_filename(entries, fn, key=None): """Search for an entry in entries where key(entry['file']) matches key(fn) and returns it. If key is None than file names are compared directly. Returns None if none is found.""" if key is None: key = lambda x: x for e in entries: i...
bigcode/self-oss-instruct-sc2-concepts
import uuid def CreateBudget(client): """Adds a new budget. Args: client: an AdWordsClient instance. Returns: A budget ID. """ budget_service = client.GetService('BudgetService', version='v201809') budget = { 'name': 'Interplanetary budget #%s' % uuid.uuid4(), 'amount': { '...
bigcode/self-oss-instruct-sc2-concepts
def _job_id_from_worker_name(name): """ utility to parse the job ID from the worker name template: 'prefix--jobid--suffix' """ _, job_id, _ = name.split("--") return job_id
bigcode/self-oss-instruct-sc2-concepts
def transpose_board(board): """Transpose the board --> change row to column""" return [list(col) for col in zip(*board)]
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def sqrt(num: Union[int, float]) -> float: """ Get square root of num or negative square root of positive num if num is negative. :param num: int, float :return: float >>> sqrt(0) 0.0 >>> sqrt(1) 1.0 >>> sqrt(81) 9.0 With negative number. >>>...
bigcode/self-oss-instruct-sc2-concepts
def count_data(data, code = None): """Helper function that counts the number of data points in an arbitrary list of lists""" if isinstance(data,list): sum = 0 for d in data: sum += count_data(d, code=code) return sum if data != '' and data != 'NA': if code == None or data == code: return 1 return 0
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Set def unique_answers(group: List[str]) -> Set[str]: """Finds the unique answers in a given group, that anyone gave.""" answers = set() for member in group: answers.update(answer for answer in member) return answers
bigcode/self-oss-instruct-sc2-concepts
import re def natural_keys(text): """Sort list of string with number in human order. Examples ---------- >>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg'] >>> l.sort(key=tl.files.natural_keys) ... ['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg'...
bigcode/self-oss-instruct-sc2-concepts
def get_cam_location_by_id(cam_id): """Get the location of the camera by its ID""" lat = None # latitude lng = None # longitude if cam_id == 0: # clairton1 lat = 40.305062 lng = -79.876692 elif cam_id == 1: # braddock1 lat = 40.392967 lng = -79.855709 elif cam_id ...
bigcode/self-oss-instruct-sc2-concepts
def _simplify_features(df): """ Remove 'standard error' columns from the breast cancer dataset for simplicity and replace spaces with underscores. """ simple = [col for col in df.columns if 'error' not in col] simple_df = df[simple] simple_df.columns = [col.replace(' ', '_') for col in simpl...
bigcode/self-oss-instruct-sc2-concepts
import requests import string def count_capital_words_in_website(url: str) -> int: """ Given a URL, count the number of words which start with a capital letter """ text = requests.get(url).text count = 0 for text_word in text.split(): if text_word[0] in string.ascii_uppercase: ...
bigcode/self-oss-instruct-sc2-concepts
import struct def unpack_linkmsg(data): """For *LINK RTNETLINK messages, unpack the body Discards a number of uninteresting parts. Returns if type, flags and remainder of message """ if_family, _, if_type, index, flags, change = struct.unpack("=BBHiII", ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def uniq_tokens_css(thresh, *collection_vals): """ Extract unique tokens in comma separated strings, contained in a collection, return list of unique tokens that occur more than a threshold value. Apply sorted to output for reproducible output. """ temp_lists = [...
bigcode/self-oss-instruct-sc2-concepts
def valid_gain(gain): """ Use this parse an argument as if it were a float and get back a valid gain as a float. Raises ValueError if passed an un-parse-able value. """ try: my_gain = round(float(gain), 1) except TypeError: raise ValueError("Could not parse value as into a valid ...
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize_query(query): """Remove special characters from a given query. Args: query: str: String to sanitize Returns: A sanitized string without special characters. """ return re.sub(r"[^a-zA-Z0-9_]+", " ", query)
bigcode/self-oss-instruct-sc2-concepts
import re def containsURL(line: str): """ Checks if the line contains any URLs Parameters ---------- line : str\n The string that needs to be checked if it countains URLs Returns ------- bool\n True if it contains URL and False if no URL in 'line' """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_tbl_struct_info(content_tbl): """ get the structural information of a table, including: - the number of columns - the difference between the number of actual cells and the estimated cells """ tbl_struct = content_tbl[0].split(',') tbl_struct = [int(val) for val in tbl_struct[1:]] tbl_struct...
bigcode/self-oss-instruct-sc2-concepts
def time_std(xr_da, time_name="time"): """ Calculate standard deviation along the time axis of an `xarray.DataArray`. Parameters ---------- xr_da: xarray.DataArray Data array with a time coordinate. time_name: str, optional Name of t-coordinate Returns ------- xarra...
bigcode/self-oss-instruct-sc2-concepts
def QLineEdit_parseVectors(lineedit): """ Return one or more component real vector as list from comma separated text in QLineEdit widget or None if invalid. """ try: text = lineedit.text() values = [ float(value) for value in text.split(",") ] return values except: ...
bigcode/self-oss-instruct-sc2-concepts
def find_below(target, valid_data): """ Finds the nearest valid cell below the target. Parameters ---------- target: tuple Indices of target cell valid_data: np.array(logical) Returns ------- below_idx: tuple Indices of valid cell immediately below target """ #...
bigcode/self-oss-instruct-sc2-concepts
def _join_dictable_with_defaults(tbl_def1, tbl_def2): """ performs a join while allowing for a default :Example: -------------- >>> from pyg import * >>> tbl_def1 = dictable(a = [1,2,3], b = [4,5,6]), dict(b=0) >>> tbl_def2 = dictable(a = [2,3,4], c = [5,6,7]), dict(c=1) >>> res = _...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import copy def get_flow_keys(results: dict) -> List[str]: """Get keys of optical flow in results. Args: results (dict): The data that includes data and meta information and used in data augmentation pipeline. Returns: List: keys of optical flow in res...
bigcode/self-oss-instruct-sc2-concepts
def has_units(qty, units): """ Test quantity (`qty`) for compatibility with given `units`. .. note:: The following two expressions are equivalent: 1. ``chemtk.units.has_units(qty, units)`` 2. ``qty.has_units(units)`` Parameters ---------- qty : :class:`Quantity...
bigcode/self-oss-instruct-sc2-concepts
import torch def _multiclass_accuracy(prediction, ground_truth): """ Computes metrics for multiclass classification Arguments: prediction, np array of int (num_samples) - model predictions ground_truth, np array of int (num_samples) - true labels Returns: accuracy - ratio of accurate pre...
bigcode/self-oss-instruct-sc2-concepts
def is_tls_record_magic(d): """ Returns: True, if the passed bytes start with the TLS record magic bytes. False, otherwise. """ d = d[:3] # TLS ClientHello magic, works for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2 # http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html#c...
bigcode/self-oss-instruct-sc2-concepts
def fix_kwds(kwds_dict, **kwargs): """ Given a dictionary of plot parameters (kwds_dict) and a dict of kwds, merge the parameters into a single consolidated dictionary to avoid argument duplication errors. If kwds_dict an kwargs have the same key, only the value in kwds_dict is kept. Parameter...
bigcode/self-oss-instruct-sc2-concepts
def percentage_of_num(percent, whole): """returns percent of a number. e.g. what is 5% of 20 """ return (percent * whole) / 100.0
bigcode/self-oss-instruct-sc2-concepts
def addExposures(exposureList): """Add a set of exposures together. Parameters ---------- exposureList : `list` of `lsst.afw.image.Exposure` Sequence of exposures to add. Returns ------- addedExposure : `lsst.afw.image.Exposure` An exposure of the same size as each exposure...
bigcode/self-oss-instruct-sc2-concepts
def spyOn(layers, names, verbose=False): """Add hooks to the specified layers to capture their outputs. The outputs are stored in a dict(), with the names given as keys. Args: -layers : Array containing the model layers to spy on. -names : Array containing the names of the layer, to be used as k...
bigcode/self-oss-instruct-sc2-concepts
def filter_entry(node): """Filters on nodes of type entry""" return node.type == "Entry"
bigcode/self-oss-instruct-sc2-concepts
import json def get_course_urls(dept): """ Returns a list of all the course urls in the given department """ with open(f"data\{dept}_dict.json", 'r') as fp: dept_dict = json.load(fp) dept_urls = [k['url'] for k in list(dept_dict.values())] return dept_urls
bigcode/self-oss-instruct-sc2-concepts
def get_emailids_query(conn_, query_='', qtype_='from', qexplicit_=False, **kwargs): """ Get all email ids from the emails after a simple query. Accepts explicit queries or one structures through query_ and qtype_ (Dev note: should be created more robust for future use!) """ assert qtype_.upper() ...
bigcode/self-oss-instruct-sc2-concepts
def age_check(df): """ Checks age is within permitted bounds If age is missing or outside bounds, replaces age with median age Parameters ---------- df : main dataset Returns ------- df : main dataset adds age_admit column """ df.loc[df['age_admit'] > 110, 'age...
bigcode/self-oss-instruct-sc2-concepts
def keys_from_hash(hexdigest): """ Return a cache keys triple for a hash hexdigest string. NOTE: since we use the first character and next two characters as directories, we create at most 16 dir at the first level and 16 dir at the second level for each first level directory for a maximum total of ...
bigcode/self-oss-instruct-sc2-concepts
def _convert_img_to_str(img): """ Convert an image in numpy array format, shape (1, height, width, depth), to a string. Depth is 1 for grayscale, 3 for RGB. Returns: img_string height width depth """ # height, width, and depth are all going to be features in the seri...
bigcode/self-oss-instruct-sc2-concepts
def read_algin(filepath: str) -> str: """read word or phone alignment file. <start-sample> <end-sample> <token><newline> Args: filepath (str): [description] Returns: str: token sepearte by <space> """ aligns = [] # (start, end, token) with open(filepath, 'r') as f: ...
bigcode/self-oss-instruct-sc2-concepts
def list_instances(compute, resource_group): """Returns list of Azure instance resources for specified resource_group :param compute: Azure object using ComputeManagementClient :param resource_group: string, name of Azure resource group :return: list of Azure VMs in resource_group :rtype: list ...
bigcode/self-oss-instruct-sc2-concepts
import json def read_dict(path): """ Reads a dictionary from a file using JSON. This file should have been written by write_dict. :param path: complete path including file name for output file :return: output dictionary from file """ with open(path) as file: out_dict = json.load(f...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_yaml_header(content: str) -> str: """删除 site 用的 md 文档中的 yaml 头 这些头信息,在简书或博客园中是多余信息,没有意义,所以需要去除 Args: content (str): 带 yaml 的文章内容 Returns: str: 删除 yaml 头的文章内容 """ return re.sub(r"---\n.+?\n---\n{1,2}", "", content, flags=re.MULTILINE | re.DOTALL)
bigcode/self-oss-instruct-sc2-concepts
def get_chars_hashed_by_yoffset(csv_reader, precision, pages=None): """ Hash the characters by the y-offset height rounded to [precision] decimals. """ line_hash = {} for i, row in enumerate(csv_reader): if pages: if int(row['pageid']) not in pages: continue ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def to_isoformat(date_str: str) -> str: """ Last-modified to isoformat Sat, 27 Jun 2020 02:00:18 GMT => 2020-06-27T02:00:18 """ return datetime.strptime(date_str, "%a, %d %b %Y %H:%M:%S %Z").isoformat()
bigcode/self-oss-instruct-sc2-concepts
def calc_combined_lens(f1, f2, d): """Calculate focal length and principal planes of a compound lens. Args: f1: focal length of first lens f2: focal length of second lens d: distance Returns: f: effective focal length of combined lens pp1: distance from first lens t...
bigcode/self-oss-instruct-sc2-concepts
def bit_not(a: int) -> int: """ ~ 取反 :param a: :return: """ return ~a
bigcode/self-oss-instruct-sc2-concepts
import typing def check_key_type(key: typing.Union[str, bytes]): """ Enforce the type of the key to bytes. Parameters ---------- key: str | bytes The key to check Returns ------- str The key as bytes """ if isinstance(key, bytes): return key return...
bigcode/self-oss-instruct-sc2-concepts
def obj_index(obj, key): """Get a key from an object""" return (getattr(obj, "__getitem__", None) or getattr(obj, "__getattribute__"))(key)
bigcode/self-oss-instruct-sc2-concepts
import math def r2d(r): """Convert radians into degrees.""" return math.degrees(r)
bigcode/self-oss-instruct-sc2-concepts
def utilSameType(agent, otherAgent, cutoff=1): """ matchUtilFct overload utility = 1 if same type, 0 otherwise """ return cutoff * (agent.type == otherAgent.type)
bigcode/self-oss-instruct-sc2-concepts
import types def writer_checkout_only(wrapped, instance, args, kwargs) -> types.MethodType: """Only allow a method to be called in a write-enable checkout. Parameters ---------- wrapped bound method which is being called instance class object being operated on ie. ``instance is se...
bigcode/self-oss-instruct-sc2-concepts
def expected(A, B): """ Calculate expected score of A in a match against B :param A: Elo rating for player A :param B: Elo rating for player B """ return 1 / (1 + 10 ** ((B - A) / 400))
bigcode/self-oss-instruct-sc2-concepts
def _TestPath(test_name, chart_name, trace_name): """Get the slash-separated test path to send. Args: test: Test name. Typically, this will be a top-level 'test suite' name. chart_name: Name of a chart where multiple trace lines are grouped. If the chart name is the same as the trace name, that sig...
bigcode/self-oss-instruct-sc2-concepts
def notas(* num, sit=False): """notas Parâmetros: num (array): É a lista de notas que será recebido para calcular os dados do aluno sit (bool, optional): É o parâmetro para mostrar ou não a situação do aluno. Defaults to False. Returns: dados (dict): Dicionário com as informações d...
bigcode/self-oss-instruct-sc2-concepts
def int_to_ordinal(num: int) -> str: """ Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc. """ n = int(num) if 4 <= n <= 20: return f"{n}th" elif n == 1 or (n % 10) == 1: return f"{n}st" elif n == 2 or (n % 10) == 2: return f"{n}nd" ...
bigcode/self-oss-instruct-sc2-concepts
def get_parametrize_markers_args(node): """In pytest 3.6 new API to access markers has been introduced and it deprecated MarkInfo objects. This function uses that API if it is available otherwise it uses MarkInfo objects. """ return tuple(arg for mark in node.iter_markers("parametrize") for arg in ...
bigcode/self-oss-instruct-sc2-concepts
def update_vertex_properties(g, v, prop_dict): """ Helper method for updating several vertex properties at once in a graph-tool graph. Args: g (gt.Graph): a graph-tool Graph object. v (gt.Vertex or int): a graph-tool Vertex object (or its index) for a vertex in the provided ...
bigcode/self-oss-instruct-sc2-concepts
import torch def smape(y, y_): """ Symmetric mean absolute percentage error. :param y: target :param y_: prediction :return: SMAPE """ return torch.mean( torch.sum(torch.abs(y_ - y) / (torch.abs(y) + torch.abs(y_)), dim=1) * (1.0 / y.shape[1]), dim=0, )
bigcode/self-oss-instruct-sc2-concepts
def invert_dict_mapping_all(mapping_dictionary): """ Args: mapping_dictionary: mapping from keys to values which is not necessarily injective, e.g., node_id to community_id mapping Returns: inverted mapping with unique values as keys and lists of former keys as values, e.g., com...
bigcode/self-oss-instruct-sc2-concepts
import wave def wavfile_duration(wavfile): """Return the duration of a wav file in seconds.""" wave_fp = wave.open(wavfile, 'rb') sample_rate = wave_fp.getframerate() nframes = wave_fp.getnframes() return nframes/sample_rate
bigcode/self-oss-instruct-sc2-concepts
def ht_cm_sqm(ht): """Converts height from centimeter to squared meter Parameters ---------- ht: double height in cms Returns ------- double height in squared meter. Examples -------- >>> ht_cm_sqm(175) 1.75 """ return (ht / 100) ** 2
bigcode/self-oss-instruct-sc2-concepts
def expand(fluid, p_final, eta): """Adiabatically expand a fluid to pressure p_final, using a turbine with isentropic efficiency eta.""" h0 = fluid.h s0 = fluid.s fluid.SP =s0, p_final h1s = fluid.h isentropic_work = h0 - h1s actual_work = isentropic_work * eta h1 = h0 - actual_work ...
bigcode/self-oss-instruct-sc2-concepts
def to_hex(v, nb_bits=16): """ Convert the value 'v' into a hexadecimal string (without the prefix 0x)""" try: v_hex = v.hex() except AttributeError: v_hex = hex(v)[2:] return '0'*(nb_bits//4-len(v_hex)) + v_hex
bigcode/self-oss-instruct-sc2-concepts
def xywh_to_xyminmax(x, y, w, h): """convert box coordinates from (x, y, w , h) form to (xmin, ymin, xmax, ymax) form""" return [x, y, x + w, y + h]
bigcode/self-oss-instruct-sc2-concepts
def format_with_braces(*vars: str): """This is a demo exercise of using format() with positional {} in order to insert variables into the string. Examples: >>> format_with_braces('hi','there','fella')\n hi there fella\n ['hi', 'there', 'fella']\n 'blah hi blah there blah fella' ...
bigcode/self-oss-instruct-sc2-concepts
def _static_framework_transition_impl(_settings, _attr): """Attribute transition for static frameworks to enable swiftinterface generation.""" return { "@build_bazel_rules_swift//swift:emit_swiftinterface": True, }
bigcode/self-oss-instruct-sc2-concepts
def _get_sequential_table( seqType ): """ Generates the table to fill sequence data in order to create a :class:`.SequenceFrame` :param seqType: Type of sequence: ``protein``, ``protein_sse``, ``dna``, ``rna``. :type seqType: :class:`str` :return: :class:`dict` :raise: :Va...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def is_expanded_digital_asset_dir(path: pathlib.Path) -> bool: """Check if a folder is an expanded digital asset. We say a folder is an expanded digital asset if it has a "Sections.list" file inside. :param path: The folder to check. :return: Whether the folder is an expanded digital ...
bigcode/self-oss-instruct-sc2-concepts
def to_boolean(value): """ Convert a string to boolean, case insensitively, where true values are: true, t, and 1 and false values are: false, f, 0. Raise a ValueError for all other values. """ if isinstance(value, bool): return value if isinstance(value, str): lower_value =...
bigcode/self-oss-instruct-sc2-concepts
async def cmd_rename(ctx): """ Usage``: rename <groupname> Description: Set the name of your current group to `groupname`. Arguments:: groupname: The new name for your group, less than `20` charachters long. Related: join, status, groups """ timer = ctx.client...
bigcode/self-oss-instruct-sc2-concepts