seed
stringlengths
1
14k
source
stringclasses
2 values
def expand_window(data, window_set=1): """ :param data: the original list :param window_set: int or list of int :return: a list of lists shifted by the bias which is specified by window_set """ if isinstance(window_set, int): window_set = [window_set] window_list = [] for bias in...
bigcode/self-oss-instruct-sc2-concepts
def dirname(path): """Return the directory portion of a file path.""" if path == "/": return "/" parts = path.split("/") if len(parts) > 1: return "/".join(parts[:-1]) return "."
bigcode/self-oss-instruct-sc2-concepts
import functools def drain(predicate=lambda x: True): """ Drains a generator function into a list, optionally filtering using predicate """ def wrapper(func): @functools.wraps(func) def inner(*args, **kwargs) -> list: return [x for x in func(*args, **kwargs) if predicate(x...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def sanitize_path(path): """Sanitize a path. Returns a pathlib.PurePath object. If a path string is given, a PurePath object will be returned. All relative paths will be converted to absolute paths. """ pure_path = pathlib.Path(path).resolve() return pure_path
bigcode/self-oss-instruct-sc2-concepts
import time def server_time(request): """ Includes the server time as a millisecond accuracy timestamp """ return {"server_time": int(round(time.time() * 1000))}
bigcode/self-oss-instruct-sc2-concepts
def clearsky(three_days_hourly, albuquerque): """Clearsky at `three_days_hourly` in `albuquerque`.""" return albuquerque.get_clearsky( three_days_hourly, model='simplified_solis' )
bigcode/self-oss-instruct-sc2-concepts
import requests def object_store_change_ownership(api_key, object_type, object_id, owner_id): """ Changes the ownership of an object (Extractor or Crawl Run) in the object store. NOTE: The API KEY must be from an account that has SUPPORT role :param api_key: Import.io API Key :param object_type: S...
bigcode/self-oss-instruct-sc2-concepts
def lower_clean_string(string): """ Function used to make string lowercase filter out punctuation :param string: Text string to strip clean and make lower case. :return: String in lowercase with all punctuation stripped. """ punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~[\n]' lowercase_...
bigcode/self-oss-instruct-sc2-concepts
def find_first_common_ancestor(node1, node2): """ Find the first common ancestor for two nodes in the same tree. Parameters ---------- node1 : nltk.tree.ParentedTree The first node. node2 : nltk.tree.ParentedTree The second node. Returns ------- ancestor_node : nltk...
bigcode/self-oss-instruct-sc2-concepts
async def get_hmms_referenced_in_db(db) -> set: """ Returns a set of all HMM ids referenced in NuVs analysis documents :param db: the application database object :return: set of all HMM ids referenced in analysis documents """ cursor = db.analyses.aggregate([ {"$match": { "...
bigcode/self-oss-instruct-sc2-concepts
import asyncio async def call(args, *, cwd, env=None, shell=False): """ Similar to subprocess.call but adapted for asyncio. Please add new arguments as needed. cwd is added as an explicit argument because asyncio will not work well with os.chdir, which is not bound to the context of the running corout...
bigcode/self-oss-instruct-sc2-concepts
def _pad_data(data: bytes, n: int = 16) -> bytes: """ Adds padding to the data according to the PKCS7 standard. Note that at least one byte of padding is guaranteed to be added. :param data: the data to pad :param n: the length to pad the data to, defaults to 16 :return: the padded data """ ...
bigcode/self-oss-instruct-sc2-concepts
def add_segment_final_space(segments): """ >>> segments = ['Hi there!', 'Here... ', 'My name is Peter. '] >>> add_segment_final_space(segments) ['Hi there! ', 'Here... ', 'My name is Peter.'] """ r = [] for segment in segments[:-1]: r.append(segment.rstrip()+' ') r.append(segment...
bigcode/self-oss-instruct-sc2-concepts
def construct_publish_comands(additional_steps=None): """Get the shell commands we'll use to actually build and publish a package to PyPI. Returns: List[str]: List of shell commands needed to publish a module. """ return (additional_steps or []) + [ "python setup.py sdist bdist_wheel",...
bigcode/self-oss-instruct-sc2-concepts
def n_lexemes_for_lemma(conn, language_code, lemma) -> int: """Get the number of dictionary entries with ``lemma`` as headword. :param conn: The database connection for the dictionary. :param str language_code: ISO 639-3 language code of the language of interest. :param lemma: A dictionary that con...
bigcode/self-oss-instruct-sc2-concepts
def _get_binary_op_bcast_shape(lhs_shape, rhs_shape): """Get the shape after binary broadcasting. We will strictly follow the broadcasting rule in numpy. Parameters ---------- lhs_shape : tuple rhs_shape : tuple Returns ------- ret_shape : tuple """ ret_shape = [] if l...
bigcode/self-oss-instruct-sc2-concepts
def _sort_key_max_confidence_sd(sample, labels): """Samples sort key by the maximum confidence_sd.""" max_confidence_sd = float("-inf") for inference in sample["inferences"]: if labels and inference["label"] not in labels: continue confidence_sd = inference.get("confidence_sd", f...
bigcode/self-oss-instruct-sc2-concepts
def reassemble_addresses(seq): """Takes a sequence of strings and combines any sub-sequence that looks like an IPv4 address into a single string. Example: ['listener', '0', '0', '0', '0_80', downstream_cx_total'] -> ['listener', '0.0.0.0:80', 'downstream_cx_total'] """ reassembled =...
bigcode/self-oss-instruct-sc2-concepts
import operator def best_assembly(assembly_list): """Based on assembly summaries find the one with the highest scaffold N50""" if assembly_list: return sorted(assembly_list, key=operator.itemgetter('scaffoldn50'))[-1]
bigcode/self-oss-instruct-sc2-concepts
import math def compute_distance(x1, y1, x2, y2): """Compute the distance between 2 points. Parameters ---------- x1 : float x coordinate of the first point. y1 : float y coordinate of the first point. x2 : float x coordinate of the second point. y2 : float ...
bigcode/self-oss-instruct-sc2-concepts
def get_version_integer(version): """Get an integer of the OGC version value x.y.z""" if version is not None: # split and make integer xyz = version.split('.') if len(xyz) != 3: return -1 try: return int(xyz[0]) * 10000 + int(xyz[1]) * 100 + int(xyz[2]) e...
bigcode/self-oss-instruct-sc2-concepts
import requests def download(url: str) -> bytes: """ Download a file from the internet using a GET request. If it fails for any reason, an exception is raised. For more complicated behavior, use an HttpAgent object. Returns the bytes of the downloaded object. """ resp = requests.get(url, stream=True) if not...
bigcode/self-oss-instruct-sc2-concepts
def _get_headers(data): """ get headers from data :param data: parsed message :return: headers """ headers = {} data = str(data, encoding="utf-8") header_str, body = data.split("\r\n\r\n", 1) header_list = header_str.split("\r\n") headers['method'], headers['protocol'] = header_l...
bigcode/self-oss-instruct-sc2-concepts
def convertFromRavenComment(msg): """ Converts fake comment nodes back into real comments @ In, msg, converted file contents as a string (with line seperators) @ Out, string, string contents of a file """ msg=msg.replace('<ravenTEMPcomment>','<!--') msg=msg.replace('</ravenTEMPcomment>','-->') ret...
bigcode/self-oss-instruct-sc2-concepts
def text_objects(text, font, color, pos): """Return text surface and rect""" text_surface = font.render(text, True, color) text_rect = text_surface.get_rect(center=pos) return text_surface, text_rect
bigcode/self-oss-instruct-sc2-concepts
def hms2deg(h, m, s): """Convert from hour, minutes, seconds to degrees Args: h (int) m (int) s (float) Return: float """ return h * 360 / 24 + m / 60.0 + s / 3600.0
bigcode/self-oss-instruct-sc2-concepts
def missing_char(str_: str, n: int) -> str: """Remove character at index n.""" return f'{str_[:n]}{str_[n+1:]}'
bigcode/self-oss-instruct-sc2-concepts
import math def f_slow(X): """ slow function """ a = X[0] b = X[1] c = X[2] s = 0 for i in range(10000): s += math.sin(a * i) + math.sin(b * i) + math.cos(c * i) return s
bigcode/self-oss-instruct-sc2-concepts
import json def get_pg_params(json_file): """ Takes the path to the json file specifying database connection information and returns formatted information. Parameters ---------- json_file : 'str' The path to the json file specifying database connection information. Returns...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def update_src_dict(key, item_dict, src_dict=None): """ updates existing or non existing src dict with key values of item dict @param key: search key in item dict @type key: str @param item_dict: the dictionary to search for key @type item_dict: dict @param ...
bigcode/self-oss-instruct-sc2-concepts
def str_format(text, data, enc_char): """This takes a text template, and formats the encapsulated occurences with data keys Example: if text = 'My name is $$name$$', provided data = 'Bob' and enc_char = '$$'. the returned text will be 'My name is Bob'. """ for key in data: val = data[key] text = tex...
bigcode/self-oss-instruct-sc2-concepts
def factorial(n: int) -> int: """Return n! (0! is 1).""" if n <= 1: return 1 result = 2 for x in range(3, n + 1): result *= x return result
bigcode/self-oss-instruct-sc2-concepts
def inherited_branches(bases): """Returns a dictionary of combined branches for all the given bases. Bases are evaluated in reverse order (right to left), mimicking Python's method resolution order. This means that branches defined on multiple bases will take the value from the leftmost base. """ ...
bigcode/self-oss-instruct-sc2-concepts
def massage_link(linkstring): """Don't allow html in the link string. Prepend http:// if there isn't already a protocol.""" for c in "<>'\"": linkstring = linkstring.replace(c, '') if linkstring and linkstring.find(':') == -1: linkstring = 'http://' + linkstring return linkstring
bigcode/self-oss-instruct-sc2-concepts
def construct_instance_market_options(instancemarket, spotinterruptionbehavior, spotmaxprice): """ construct the dictionary necessary to configure instance market selection (on-demand vs spot) See: https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances ...
bigcode/self-oss-instruct-sc2-concepts
def tau_column(tau, k, j): """ Determine the column index for the non-zero elements of the matrix for a particular row `k` and the value of `j` from the Dicke space. Parameters ---------- tau: str The tau function to check for this `k` and `j`. k: int The row of the matrix ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def configure_output_dir(output_dir: str): """ Create a directory (recursively) and ignore errors if they already exist. :param output_dir: path to the output directory :return: output_path """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_o...
bigcode/self-oss-instruct-sc2-concepts
def simple_transfer(type, file_path, out_path=None): """ simple_transfer [summary] Args: type (str): File's encoding type file_path (str): Path to the file out_path (str, optional): Path to the output file. Defaults to None. Returns: [bool]: whether transfer the encoding type successfully. """ with ope...
bigcode/self-oss-instruct-sc2-concepts
import plistlib import xml def read_manifest_plist(path): """Given a path to a ProfileCreator manifest plist, return the contents of the plist.""" with open(path, "rb") as openfile: try: return plistlib.load(openfile) except xml.parsers.expat.ExpatError: print("Erro...
bigcode/self-oss-instruct-sc2-concepts
import six def get_dict_from_output(output): """Parse list of dictionaries, return a dictionary. :param output: list of dictionaries """ obj = {} for item in output: obj[item['Property']] = six.text_type(item['Value']) return obj
bigcode/self-oss-instruct-sc2-concepts
import torch def pack_tensors(tensors, use_cuda=False): """ Packs a list of tensors into one 1-dimensional tensor. Args: tensors (list[torch.Tensor]): The tensors to pack use_cuda (bool): Whether the resulting tensor should be on cuda Returns: (torch.Tensor, list[int], list[(...
bigcode/self-oss-instruct-sc2-concepts
def SFR(z): """ returns the cosmic star formation rate in M_\odot/yr/Mpc^3 following Strolger+15""" A = 0.015 #M_\odot/yr/Mpc^3 B = 1.5 C = 5.0 D = 6.1 return A*(1+z)**C/( ((1+z)/B)**D + 1 )
bigcode/self-oss-instruct-sc2-concepts
def private_repo_count(self): """count of private repositories of `org`""" return len(self.get_repos('private'))
bigcode/self-oss-instruct-sc2-concepts
def dobra(x): """ Dobra o valor da entrada Parâmetros ---------- x : número O valor a ser dobrado Retorno ------- número O dobro da entrada """ return 2*x
bigcode/self-oss-instruct-sc2-concepts
def get_called_variants(var_list, cn_prob_processed, starting_index=0): """ Return called variants based on called copy number and list of variant names """ total_callset = [] if starting_index != 0: assert len(var_list) == len(cn_prob_processed) + starting_index for i, cn_called in enum...
bigcode/self-oss-instruct-sc2-concepts
def add_deviations_from_sample_mean(data): """ Adds columns in which [profitability, inv_rate] are demeaned at the firm-level and then the full-sample mean is added again. Args ---- data (pandas.DataFrame): dataframe with 4 columns: firm, year, profitability, inv_rate Returns ---...
bigcode/self-oss-instruct-sc2-concepts
def get_normal_vector(hkl, Astar): """ Get normal vector to real-space Miller plane, hkl. Note ---- The normal vector to a real-space Miller plane is collinear with the reciprocal dHKL vector. As such, we can use this simpler formula in the reciprocal lattice basis to get the c...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def get_alert_values(root): """Finds important alert info, returned in this order: 1. Alert header 2. Alert type 3. Alert status 4. Alert confidence 5. Alert latitude (of radiative center) 6. Alert longitude (of radiative center) 7. Alert date and time (da...
bigcode/self-oss-instruct-sc2-concepts
def convert_types(type_dict): """ Check dictionary on nested dictionaries, convert it into one dictionary without nested dictionaries :param type_dict: dictionary that can contain nested dictionaries :type: dict :return: dictionary contained data from type_dict without nested dictionary in it ...
bigcode/self-oss-instruct-sc2-concepts
def host_data(fqdn): """ Splits input FQDN to usable elements: domain_attr = { "fqdn": "name.example.com", "domain": "example.com", "host": "name", } Takes into account multiple subdomains (i.e., name1.name2.example.com). """ hosts = fqdn.split(".") domain_at...
bigcode/self-oss-instruct-sc2-concepts
def manhattan_distance(pos1, pos2): """Returns manhattan distance between two points in (x, y) format""" return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
bigcode/self-oss-instruct-sc2-concepts
def is_linear_perpetual(trading_pair: str) -> bool: """ Returns True if trading_pair is in USDT(Linear) Perpetual """ _, quote_asset = trading_pair.split("-") return quote_asset == "USDT"
bigcode/self-oss-instruct-sc2-concepts
def _f2r(v, depth): """\ _f2r(floatval,depth) -> (numerator, denominator) Generates a rational fraction representation of a *positive* floating point value using the continuous fractions technique to the specified depth. Used rational() in preference, to get the most optional match. This function ...
bigcode/self-oss-instruct-sc2-concepts
def tableName(line): """ Generate the name of the table. """ words = line.split() tableNum = words[1].replace(":", "") tname = "Table" + tableNum for w in words[2:]: tname += "-" + w tname += ".csv" return tname
bigcode/self-oss-instruct-sc2-concepts
def validate_parameters(params): """Validate event counter parameters and return an error, if any.""" # Sanitize input to correct numeric types for key in ('start_year', 'end_year'): if params.get(key): try: params[key] = int(params[key]) except ValueError: return "%s must be an in...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def to_datetime(datetime_str: str, sep: str = ":") -> datetime: """Convert datetime formatted string to datetime object. Arguments: --- datetime_str: datetime value in string sep: separator for time in datetime string returns: --- return datetime objec...
bigcode/self-oss-instruct-sc2-concepts
def w_binary_to_hex(word): """Converts binary word to hex (word is a list) >>> w_binary_to_hex("111") '0x7' >>> w_binary_to_hex([1,1,1,1]) '0xf' >>> w_binary_to_hex([0,0,0,0,1,1,1,1]) '0xf' >>> w_binary_to_hex([0,1,1,1,1,1,0,0]) '0x7c' """ if isinstance(word, str): ...
bigcode/self-oss-instruct-sc2-concepts
import logging import json def connect_and_get_output(device): """ Helper function which get LLDP data from specified device Positional argument: - device -- NAPALM driver object Returns: - json_output -- LLDP device data serialized to JSON """ try: device.open() outp...
bigcode/self-oss-instruct-sc2-concepts
def denormalize(features, mean, std): """ Normalizes features with the specificed mean and std """ return features * std + mean
bigcode/self-oss-instruct-sc2-concepts
def num_sections(course: tuple[str, str, set]) -> int: """Return the number of sections for the given course. Preconditions: - The input matches the format for a course described by the assignment handout. """ return len(course[2])
bigcode/self-oss-instruct-sc2-concepts
def _sort_circle(the_dict): """ Each item in the dictionary has a list. Return a new dict with each of those lists sorted by key. """ new_dict = {} for k, v in the_dict.items(): new_dict[k] = sorted(v) return new_dict
bigcode/self-oss-instruct-sc2-concepts
def make_anchor(type): """Takes a type name in CamelCase and returns the label (anchor) equivalent which is all lower case, as the labels Sphinx generates for headers. """ return type.lower()
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_data(infile): """Read data array. Args: infile (str): path to file Returns: np.ndarray: numpy arrays for features and labels """ print(f'Reading data from {infile}') with open(infile, 'rb') as f_read: obj = pickle.load(f_read) array_ordered ...
bigcode/self-oss-instruct-sc2-concepts
def load_input_data(input_path, do_lowercase): """Load input data.""" examples = [] lc = 0 with open(input_path, "r") as f: for line in f: lc += 1 line_split = line.strip().split("\t") print(line_split) if len(line_split) != 2: raise Exception("Each line is expect to only hav...
bigcode/self-oss-instruct-sc2-concepts
def get_controller_index_by_typename(net, typename, idx=[], case_sensitive=False): """ Returns controller indices of a given name of type as list. """ idx = idx if len(idx) else net.controller.index if case_sensitive: return [i for i in idx if str(net.controller.object.at[i]).split(" ")[0] =...
bigcode/self-oss-instruct-sc2-concepts
def cap(v, l): """Shortens string is above certain length.""" s = str(v) return s if len(s) <= l else s[-l:]
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 def openDatabase(file,inMemory=False): """Open SQLite db and return tuple (connection,cursor)""" if inMemory==True: conn=sqlite3.connect(':memory:') else: conn=sqlite3.connect(file) conn.row_factory = sqlite3.Row cursor=conn.cursor() return (conn,cursor)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def __wrap_boolean_value(value: Any) -> str: """ If `value` is Python's native True, returns 'true'. If `value` is Python's native False, returns 'false'. Otherwise returns 'null'. """ if value is True: return 'true' if value is False: return 'false' ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def datetime_helper( datetime_str ): """try to convert datetime for comparison Args: datetime_str (str): datetime str (%Y-%m-%d) or (%Y-%m-%dT%H:%M:S) Returns: datetime.datetime """ try: return_datetime = datetime.strptime(datetime_s...
bigcode/self-oss-instruct-sc2-concepts
def merge_lists(*lists): """Merges the given lists, ignoring duplicate entries. Args: *lists: lists of strings to merge Returns: A list of strings """ result = {} for x in lists: for elem in x: result[elem] = 1 return result.keys()
bigcode/self-oss-instruct-sc2-concepts
def sqr(x): """Return the square of x. """ return x*x
bigcode/self-oss-instruct-sc2-concepts
import asyncio async def gather_with_concurrency(n, *tasks): """ Execute tasks concurrently with a max amount of tasks running at the same time. Retrieved from https://stackoverflow.com/a/61478547/7868972. """ semaphore = asyncio.Semaphore(n) async def sem_task(task): async with semap...
bigcode/self-oss-instruct-sc2-concepts
import torch def l1norm(X, dim, eps=1e-8): """L1-normalize columns of X""" norm = torch.abs(X).sum(dim=dim, keepdim=True) + eps X = torch.div(X, norm) return X
bigcode/self-oss-instruct-sc2-concepts
def s2_index_to_band_id(band_index): """s2_index_toBand_id returns the band_id from the band index :param band_index: band index (0-12 inclusive) referencing sensors in ESA's metadata :return: band_id for the band_index """ return { 0: '1', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7', ...
bigcode/self-oss-instruct-sc2-concepts
def ppm_to_dalton(mass:float, prec_tol:int)->float: """Function to convert ppm tolerances to Dalton. Args: mass (float): Base mass. prec_tol (int): Tolerance. Returns: float: Tolerance in Dalton. """ return mass / 1e6 * prec_tol
bigcode/self-oss-instruct-sc2-concepts
def matrix_matrix_product(A, B): """Compute the matrix-matrix product AB as a list of lists.""" m, n, p = len(A), len(B), len(B[0]) return [[sum([A[i][k] * B[k][j] for k in range(n)]) for j in range(p) ] for i in range(m) ]
bigcode/self-oss-instruct-sc2-concepts
def raw_input_default(prompt, default=None): """prompts the user for a string, proposing a default value in brackets.""" if default: prompt = "%s [%s]: " % (prompt, default) res = input(prompt) if not res and default: return default return res
bigcode/self-oss-instruct-sc2-concepts
def lls_predict(A, X): """Given X and A, compute predicted value Y = A.T@X """ if X.ndim == 1: return A * X else: return A.T @ X
bigcode/self-oss-instruct-sc2-concepts
def md_headline(title, level): """ Format a markdown header line based on the level argument """ level_char_list = ['=', '-'] try: level_char = level_char_list[level] except IndexError: level_char = '=' return '\n%s\n%s\n' % (title, (level_char * len(title)))
bigcode/self-oss-instruct-sc2-concepts
def get_issue_info(payload): """Extract all information we need when handling webhooks for issues.""" # Extract the title and the body title = payload.get('issue')['title'] # Create the issue dictionary return {'action': payload.get('action'), 'number': payload.get('issue')['number'], ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Type from enum import Enum from typing import List def enum_values(enum_cls: Type[Enum]) -> List: """List enum values.""" return [v.value for v in enum_cls]
bigcode/self-oss-instruct-sc2-concepts
def get_txtfilename(ID, era): """ Return the txtfilename given by station ID and era in correct format.""" return era+'_'+ID+'.txt'
bigcode/self-oss-instruct-sc2-concepts
def popcount(n=0): """ Computes the popcount (binary Hamming weight) of integer `n`. Arguments --------- n : a base-10 integer Returns ------- int Popcount (binary Hamming weight) of `n` """ return bin(n).count('1')
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_neighbors( cell: Tuple[int, int], shape: Tuple[int, int, int], with_start_position: bool = False, ): """ :param cell: :param shape: :param with_start_position :return: The neighbor cells of the given cell, respecting the map shape """ p, q = sha...
bigcode/self-oss-instruct-sc2-concepts
import xmltodict def gen_query(search_ligand, search_protein=None, querymode=None): """ Args: search_ligand: the Chem_ID of the FDA-approved inhibitor of interest search_protein: UniProt Accession ID for the approved target for the inhibitor querymode: string indicating whether searchi...
bigcode/self-oss-instruct-sc2-concepts
def hamming_distance(str1, str2): """ Computes the number of different characters in the same position for two given strings. Typically the inputs are binary, but it needs not be the case. Parameters: ---------- str1: str str2: str Returns: ------- int: hamming distance Exampl...
bigcode/self-oss-instruct-sc2-concepts
import torch def regulate_len(durations, enc_out, pace=1.0, mel_max_len=None): """A function that takes predicted durations per encoded token, and repeats enc_out according to the duration. NOTE: durations.shape[1] == enc_out.shape[1] Args: durations (torch.tensor): A tensor of shape (batch x enc...
bigcode/self-oss-instruct-sc2-concepts
def mix_targets(preds, targets, target_name1, target_name2, weight1=0.5, weight2=0.5, skip_missing=False, new_name=None): """ Linearly combines two targets into one, optionally with custom weights, storing it under the name of the first one, unless `new_name` is given. `weight1` and `wei...
bigcode/self-oss-instruct-sc2-concepts
def ext2str(ext, compact=False, default_extver=1): """ Return a string representation of an extension specification. Parameters ---------- ext : tuple, int, str Extension specification can be a tuple of the form (str,int), e.g., ('sci',1), an integer (extension number), or a string ...
bigcode/self-oss-instruct-sc2-concepts
def way(routing, start, end): """Return the route from the start to the end as a list""" route = [] current_node = end while current_node != start: route.insert(0, current_node) current_node = routing[current_node] return route
bigcode/self-oss-instruct-sc2-concepts
def parse_info_cfg(filename): """ Extracts information contained in the Info.cfg file given as input. :param filename: path/to/patient/folder/Info.cfg :return: values for: ed, es, group, h, nf, w """ ed, es, group, h, nf, w = None, None, None, None, None, None with open(filename, 'r') as f: ...
bigcode/self-oss-instruct-sc2-concepts
import math def safe_is_nan(x): """Is the value NaN (not a number). Returns True for np.nan and nan python float. Returns False for anything else, including None and non-numeric types. Called safe because it won't raise a TypeError for non-numerics. Args: x: Object to check for NaN. ...
bigcode/self-oss-instruct-sc2-concepts
def c_to_k(temp): """ Converts Celsius to Kelvin. """ return temp + 273.15
bigcode/self-oss-instruct-sc2-concepts
def __pydonicli_declare_args__(var_dict): """ Limit a dictionary, usually `locals()` to exclude modules and functions and thus contain only key:value pairs of variables. """ vars_only = {} for k, v in var_dict.items(): dtype = v.__class__.__name__ if dtype not in ['module', 'fun...
bigcode/self-oss-instruct-sc2-concepts
def always_hold(state): """Always hold strategy.""" return 'hold'
bigcode/self-oss-instruct-sc2-concepts
def normalize(X): """ Normalizes the input between -0.5 and 0.5 """ return X / 255. - 0.5
bigcode/self-oss-instruct-sc2-concepts
def list_diff(listEE1, listEE2): """ Difference between two earth engine lists :param listEE1: one list :param listEE2: the other list :return: list with the values of the difference :rtype: ee.List """ return listEE1.removeAll(listEE2).add(listEE2.removeAll(listEE1)).flatten()
bigcode/self-oss-instruct-sc2-concepts
def iteration(printer, ast): """Prints "for (name : type) {body}".""" name_str = ast["name"] type_str = printer.ast_to_string(ast["type"]) body_str = printer.ast_to_string(ast["body"]) return f'for ({name_str} : {type_str}) {body_str}'
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def yaml_path_to_html_path(yaml_path): """Converts a yaml filepath to the corresponding html filepath. For instance: converts 'newsletters/yaml/week_032.yml' to: 'newsletters/html/week_032.html'. Args: yaml_path (pathlib.Path): the yaml path to ...
bigcode/self-oss-instruct-sc2-concepts
import time import math def run_time(t1, name="", is_print=True): """Performance test function, test run time. :param t1: Set the time of the breakpoint :param name: Set the name of the print :param is_print: True, Whether to print :return: Printed string content >>> t1 = time.time() # t...
bigcode/self-oss-instruct-sc2-concepts