seed
stringlengths
1
14k
source
stringclasses
2 values
import string def make_file_name(song): """Returns a valid file name for a song object.""" valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) fname = '{} - {}.mp3'.format(song.name.encode('utf8', 'replace'), song.artist.name.encode('utf8', 'replace')) f...
bigcode/self-oss-instruct-sc2-concepts
def planetary_temp(S, A, L=1.0): """Calculate the planetary temperature. SL(1-A) = sT**4 Arguments --------- S : float Incident solar energy. A : float Planetary albedo. Keyword Arguments ----------------- L = 1.0 : float Normalised stellar luminosity. "...
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_index_select(x, idx): """ :param x: *, n, Dim :param idx: *, k :return: *, k , Dim """ idx_ = idx.unsqueeze(-1).expand(idx.shape + (x.shape[-1],)) return torch.gather(x, -2, idx_)
bigcode/self-oss-instruct-sc2-concepts
def draw_frame(surface, rect, color_fill, color_border, border=1): """ Creates and draws a rect with a frame. Returns the inside rect object. returns a pygame.Rect() object, which is the filled area inside the frame - surface: the pygame surface to draw this on - rect: pygame.Rect() object for the o...
bigcode/self-oss-instruct-sc2-concepts
def _eval_expr(expr, ctxt, vars=None): """Evaluate the given `Expression` object. :param expr: the expression to evaluate :param ctxt: the `Context` :param vars: additional variables that should be available to the expression :return: the result of the evaluation """ if...
bigcode/self-oss-instruct-sc2-concepts
def datetime(anon, obj, field, val): """ Returns a random datetime """ return anon.faker.datetime(field=field)
bigcode/self-oss-instruct-sc2-concepts
def allMatches(source, regex): """Return a list of matches for regex in source """ pos = 0 end = len(source) rv = [] match = regex.search(source, pos) while match: rv.append(match) match = regex.search(source, match.end() ) return rv
bigcode/self-oss-instruct-sc2-concepts
import io def readReviews(path): """ Function to store reviews in a list buffer. Arguments --------- path: location of reviews Return --------- list of reviews """ # Create an empty buffer to hold all the reviews reviewBuf = [] # Open the file with io.open(path,'r') as raw: for line in raw: revi...
bigcode/self-oss-instruct-sc2-concepts
def get_fitzpatrick_type(ita): """ This function will take a ita value and return the Fitzpatrick skin tone scale https://arxiv.org/pdf/2104.14685.pdf :param ita: :return: """ if ita < -50: return "6" elif -50 <= ita < -25: return "5" elif -25 <= ita < 0: retu...
bigcode/self-oss-instruct-sc2-concepts
import requests def twitter_get_friends_json(nickname: str, token: str) -> dict: """ Get json with friends by username from twitter. """ reqest_url = "https://api.twitter.com/1.1/friends/list.json" headers = { 'Authorization': 'Bearer {}'.format(token) } params = { 'scree...
bigcode/self-oss-instruct-sc2-concepts
def get_cam_name(i, min_chars=7): """Create formatted camera name from index.""" format_str = '{:0' + str(min_chars) + 'd}' return 'cam_' + format_str.format(i)
bigcode/self-oss-instruct-sc2-concepts
def linear(x, slope=1.0, intercept=0.0): """Return a linear function. x -> slope * x + intercept """ return slope * x + intercept
bigcode/self-oss-instruct-sc2-concepts
import random def different_account(account, test_case=None): """Randomly choose a non-existant account or keep account.""" if test_case: if test_case.get("account"): return "FFFFFFFFF" else: return account else: return "FFFFFFFFF" if random.random() < 0.1 e...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha512_encode(t): """Encoder using SHA512. >>> sha512_encode("Hola mundo") '34ddb0edac59e441459e07cf33bd628f53fbbf752141125f069f32081b169f933666c71b2f1b83031da66bc905a1e72af7c6cfd779fc197513639a098f94c641' """ s = hashlib.sha512(t) return s.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def geth_to_cmd(node, datadir, verbosity): """ Transform a node configuration into a cmd-args list for `subprocess.Popen`. Args: node (dict): a node configuration datadir (str): the node's datadir Return: List[str]: cmd-args list """ node_config = [ 'nodekeyhex'...
bigcode/self-oss-instruct-sc2-concepts
import re def get_words_from_txt_file(txt_path: str) -> list: """ Return list of words from txt file at specified path """ words = [] with open(txt_path, encoding='utf-8') as file: for line in file: try: for word in line.split(): words.append(word...
bigcode/self-oss-instruct-sc2-concepts
def extract_terminal_pathname(url): """Extract the last path segment from a URL """ return list(filter(None, url.split("/"))).pop()
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle(path): """ Loads a .pickle file Parameters ---------- path : str Absolute path to the file Returns ------- Object contained in the .pickle file """ with open(path, 'rb') as f: return pickle.load(f)
bigcode/self-oss-instruct-sc2-concepts
import gzip def parse (f): """Decompress an epgdb file. :arg typing.BinaryIO f: epgdb file contents :return: Uncompressed epgdb file contents :rtype: typing.BinaryIO """ # skip epgdb-specific header f.read(12) return gzip.GzipFile(fileobj=f)
bigcode/self-oss-instruct-sc2-concepts
def build_vocab(posts): """ Given the training set of posts, constructs the vocabulary dictionary, `tok_to_ix`, that maps unique tokens to their index in the vocabulary. """ tok_to_ix = {} for post in posts: tokens = post.split(' ') for token in tokens: tok_to_ix.setd...
bigcode/self-oss-instruct-sc2-concepts
def get_feature_importance_data(data_income, column='Close_x', include_targets=False): """ :param data_income: :param column: :param include_targets: targets are 'Open_x', 'High_x', 'Low_x' and 'Close_x' :return: train and test of X and y """ data = data_income.copy() y = data[column] ...
bigcode/self-oss-instruct-sc2-concepts
def naive(data, **kwargs): """The naive forecast for the next point is the value of the previous point. In most forecasting situations, the naive model is a good baseline due to it's simplicity and low computational overhead. Args: data (np.array): Observed data, presumed to be ordered in t...
bigcode/self-oss-instruct-sc2-concepts
def str_responder(*args, **kwargs): """Responds with an empty string""" return ''
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_hash(filepath): """ Generates unique ID based on hash of the file Args: filepath (str) path to file to read Returns hash of file """ filehash = hashlib.md5() with open(filepath, 'rb') as fobj: for chunk in iter(lambda: fobj.read(2097152), b""): filehash.update...
bigcode/self-oss-instruct-sc2-concepts
def biggest(a, b): """ This function returns the biggest of the numbers (but it does checks for None). Input: a: int, first number; b: int, second number. Output: biggest: int, the biggest number of the passed numbers (the non-None number, if one of the ...
bigcode/self-oss-instruct-sc2-concepts
def unflatten(tensor, batch_size, num_rounds): """Unflatten a tensor based on batch_size(B) and num_rounds(N). Args: tensor: Size [B*N, D1, D2, D3, ...] batch_size: B num_rounds = N Returns: unflat_tensor: Size [B, N, D1, D2, ...] """ old_size = tensor.shape expected_fi...
bigcode/self-oss-instruct-sc2-concepts
def lstrip_keep(text): """ Like lstrip, but also returns the whitespace that was stripped off """ text_length = len(text) new_text = text.lstrip() prefix = text[0 : (text_length - len(new_text))] return new_text, prefix
bigcode/self-oss-instruct-sc2-concepts
import re def get_track_quirk(quirks, cro_track_id): """Return Spotify track id for given CRo track id from quirks.""" q = quirks["tracks"].get(cro_track_id) if q: m = re.search(r"(?:track.)?([0-9a-zA-Z]{22})", q) if m: return m.group(1)
bigcode/self-oss-instruct-sc2-concepts
def generate_sns_event(message, topic, subject): """ Generates a SNS Event :param str message: Message sent to the topic :param str topic: Name of the Topic :param str subject: Subject of the Topic :return dict: Dictionary representing the SNS Event """ return { "Records": [{ ...
bigcode/self-oss-instruct-sc2-concepts
import time def FunctionTimer(on_done=None): """ To check execution time of a function borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d >>> def logger(details, args, kwargs): #some function that uses the time output ... print(d...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def split_namespace(s: str) -> Tuple[str, str]: """ Splits a namespace and name into their parts Parameters ---------- s: str string to be split Returns ------- (tuple) namespace: str name: str """ split = s.spl...
bigcode/self-oss-instruct-sc2-concepts
from operator import mul def compute_mul(tree): """ Compute the Variable that is the output of a multiplication tree. This is the inverse of the operation performed by `parse_mul_tree`, i.e. compute_mul(parse_mul_tree(tree)) == tree. Parameters ---------- tree A multiplication tr...
bigcode/self-oss-instruct-sc2-concepts
def doc_string(docstring: str = "default doc"): """Set a documentation string for `function`. Helpful if several functions have the same doc""" def wrapper(function): function.__doc__ += docstring return function return wrapper
bigcode/self-oss-instruct-sc2-concepts
def local_temp(A, albedo, T, q=30): """Calculate local temperature experienced by a particular daisy type or ground cover. This is a simplified version of the original. q*(A-albedo)+T Arguments --------- A : float Planetary albedo alpha : float Albedo of daisy type T : f...
bigcode/self-oss-instruct-sc2-concepts
def to_bool(boolean: bool): """ Checks if an argument is of type bool: - If argument is type bool, simply returns argument - If argunent is type str, attempts to convert to type bool - Raises TypeError otherwise :param boolean: bool, str argument to be converted to type bool...
bigcode/self-oss-instruct-sc2-concepts
import re def _strip_blanks(table): """ Remove blank lines from table (included for "human readability" but useless to us... returns a single string joined by \n newlines Parameters ---------- table : str table to strip as a string Returns ------- single string joined ...
bigcode/self-oss-instruct-sc2-concepts
def is_parans_exp(istr): """ Determines if an expression is a valid function "call" """ fxn = istr.split('(')[0] if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')': return False plevel = 1 for c in '('.join(istr[:-1].split('(')[1:]): if c == '(': plevel += 1...
bigcode/self-oss-instruct-sc2-concepts
import inspect def inherit_docstring(c, meth): """Since Python 3.5, inspect.getdoc is supposed to return the docstring from a parent class if a class has none. However this doesn't seem to work for Cython classes. """ doc = None for ancestor in inspect.getmro(c): try: ancest...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable import importlib def get_method(pkg_path: str) -> Callable: """ Returns a method given the full package path of the method, e.g. given the string ``oedtools.schema.get_schema`` it will return the actual method ``get_schema`` from the ``oedtools.schema`` module. :param ...
bigcode/self-oss-instruct-sc2-concepts
def epsg_from_utm_zone(zone): """ Returns the WGS-84 EPSG for a given UTM zone Input: zone(int): Zone, positive values for North Output: epsg code(int). """ if zone > 0: epsg = 32600 + zone else: epsg = 32700 - zone return epsg
bigcode/self-oss-instruct-sc2-concepts
def liveobj_valid(obj): """ Check whether obj represents a valid Live API obj. This will return False both if obj represents a lost weakref or is None. It's important that Live API objects are not checked using "is None", since this would treat lost weakrefs as valid. """ return obj != None
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce import operator def prod(factors): """ The product of the given factors (iterable) :param factors: :return: """ return reduce(operator.mul, factors, 1.0)
bigcode/self-oss-instruct-sc2-concepts
import re def paragraphs(corpus): """ >>> text = 'P1\n\nP2\nP2\n \t \n\n\n \t\nP3' >>> paragraphs(text) '<p>P1</p>\n<p>P2\nP2</p>\n<p>P3</p>' """ inner_paras_added = re.sub(r'\n\s*\n', '</p>\n<p>', corpus) all_paras_added = f'<p>{inner_paras_added}</p>' return all_paras_added
bigcode/self-oss-instruct-sc2-concepts
import random import logging def get_random_route(rs_api) -> int: """Gets a random route id used for testing""" routes = rs_api.get_routes() index = random.randint(1, len(routes) - 1) route_id = routes[index]['RouteID'] logging.getLogger().info("Selecting RouteID %s", route_id) return route_id
bigcode/self-oss-instruct-sc2-concepts
def prepareDFgeneral(dfAllCancerData): """ Given that the entire PSP cancer data is passed as a dataframe, it i) separates the genes (features) from the target variables, that is: CancerStatus, Project, TumorStage, Race, and Gender ii) asks the user to chose one of them as the class variable i...
bigcode/self-oss-instruct-sc2-concepts
def _NameToIndex(name, L): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately,...
bigcode/self-oss-instruct-sc2-concepts
def rhist(ax, data, **keywords): """Creates a histogram with default style parameters to look like ggplot2 Is equivalent to calling ax.hist and accepts the same keyword parameters. If style parameters are explicitly defined, they will not be overwritten """ defaults = { 'facecol...
bigcode/self-oss-instruct-sc2-concepts
def flatten_arguments(arg_dict): """Flattens a dict of options into an argument list. Parameters ---------- arg_dict : Dict[Str, Any] Dictionary of arguments. Keys should be strings, values may be lists or tuples (for multiple values), booleans (for flags) or any other value tha...
bigcode/self-oss-instruct-sc2-concepts
import stat def file_groupreadable(path): """Check whether a given path has bad permissons.""" if not bool(stat.S_IRGRP & path.stat().mode): return 'PROB_FILE_NOT_GRPRD'
bigcode/self-oss-instruct-sc2-concepts
def GetPortStatus(chameleond, port_id): """Gets port status with port_id through chameleond proxy.""" if not chameleond.IsPhysicalPlugged(port_id): return 'Not connected\n' if chameleond.IsPlugged(port_id): return 'Connected\nPlugged\n' return 'Connected\nNot plugged\n'
bigcode/self-oss-instruct-sc2-concepts
def get_low_high_cells(methylation_df, patient, percentage): """ For the given patient calculate the percentage high and low cells, excluding normal cells. :param methylation_df: df containing the average methylation levels for each cell. :param patient: The patient to calculate cells for. :param pe...
bigcode/self-oss-instruct-sc2-concepts
def _ch(x: int, y: int, z: int): """As defined in the specification.""" return (x & y) ^ (~x & z)
bigcode/self-oss-instruct-sc2-concepts
def TransformSplit(r, sep='/', undefined=''): """Splits a string by the value of sep. Args: r: A string. sep: The separator value to use when splitting. undefined: Returns this value if the result after splitting is empty. Returns: A new array containing the split components of the resource. ...
bigcode/self-oss-instruct-sc2-concepts
import torch def MIoU(pred, gt): """ Description: Mean Intersection over Union Params: pred -- the predicted label, tensor of shape (N,H,W,C) gt -- the ground_truth label, tensor of shape (N,H,W,C) Tips: gt needs to be transformed to one_hot form """ intersectio...
bigcode/self-oss-instruct-sc2-concepts
import torch def default_orientation(num: int, device: str) -> torch.Tensor: """Returns identity rotation transform.""" quat = torch.zeros((num, 4,), dtype=torch.float, device=device) quat[..., -1] = 1.0 return quat
bigcode/self-oss-instruct-sc2-concepts
def th_flatten(x): """Flatten tensor""" return x.contiguous().view(-1)
bigcode/self-oss-instruct-sc2-concepts
import functools import string import unicodedata def unaccent(text): """Translate accented characters to their non-accented equivalents""" @functools.cache def unaccent_c(char): if char in string.printable: return char elif unicodedata.combining(char): return None else: return unicodedata.normalize...
bigcode/self-oss-instruct-sc2-concepts
import torch def sample_batch(data, length, batch_size): """ Takes the data (a single sequence of tokens) and slices out a batch of subsequences to provide as input to the model. For each input instance, it also slices out the sequence that is shofted one position to the right, to provide as a target...
bigcode/self-oss-instruct-sc2-concepts
def italic(text: str) -> str: """ Return the *text* surrounded by italic HTML tags. >>> italic("foo") '<i>foo</i>' """ return f"<i>{text}</i>"
bigcode/self-oss-instruct-sc2-concepts
def carddir(deg): """Returns the cardinal direction string from degrees (0° = N, 90° = E, ...) """ return ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'][int(((deg+11.25)%360)/22.5)]
bigcode/self-oss-instruct-sc2-concepts
def chunk_array(array, num_chunks, len_array): """ Chunk a given list into a given number of smaller lists. :param array: :param num_chunks: :return: """ # return [array[i:i + num_chunks] for i in range(0, len(array), num_chunks)] if len_array > num_chunks: if len_array % num_chu...
bigcode/self-oss-instruct-sc2-concepts
import torch def bboxes2tblr(priors, gts, normalizer=4.0, normalize_by_wh=False): """Encode ground truth boxes to tblr coordinate. It first convert the gt coordinate to tblr format, (top, bottom, left, right), relative to prior box centers. The tblr coordinate may be normalized by the side length of...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def cls_is_annotated(cls: Any) -> bool: """ Inspect if a class has annotations Args: cls (Any): Class to inspect Returns: bool: True if cls is annotated else False """ return ( hasattr(cls, "__dict__") and "__annotations__" in cls.__dict...
bigcode/self-oss-instruct-sc2-concepts
def calc_relative_density_boulanger_et_al_2014_cpt_values(q_c1n, c_dq=0.9): """ Table 4.1 in PM4Sand v3.1 manual Parameters ---------- q_c1n: array_like Normalised cone penetration resistance c_dq: float, default=0.9 (from :cite:`Idriss:2008ua`) Correlation factor, (range 0.64-1...
bigcode/self-oss-instruct-sc2-concepts
def get_row_col_matrix(row_index_set, col_index_set): """ Returns the resulting matrix when using a row and column of indices (list of tuples) row_index_set: the index set that would be taken from wells A-H (or equivalent) on that plate. Should be dim 8 or 16. col_index_set: the index set that would be...
bigcode/self-oss-instruct-sc2-concepts
def _UsingGtestJson(options): """Returns True if we're using GTest JSON summary.""" return (options.annotate == 'gtest' and not options.run_python_script and not options.run_shell_script)
bigcode/self-oss-instruct-sc2-concepts
def CSourceForArrayData(values, formatter, margin=4, width=80): """Turn an array of values into a C source array data definition. Args: values: Array of input values. formatter: Formatting function, applied to each input value to get a C-source description of the value. margin: Left-side margin /...
bigcode/self-oss-instruct-sc2-concepts
def get_binary_mask_from_raw_address(raw_address: str) -> str: """ Return binary mask from raw address. >>> get_binary_mask_from_raw_address("192.168.1.15/24") '11111111.11111111.11111111.00000000' >>> get_binary_mask_from_raw_address("91.124.230.205/30") '11111111.11111111.11111111.11111100' ...
bigcode/self-oss-instruct-sc2-concepts
def cyclic(graph): """ Return True if the directed graph has a cycle. The graph must be represented as a dictionary mapping vertices to iterables of neighbouring vertices. For example: >>> cyclic({1: (2,), 2: (3,), 3: (1,)}) True >>> cyclic({1: (2,), 2: (3,), 3: (4,)}) False """ ...
bigcode/self-oss-instruct-sc2-concepts
def high_income_amount(responses, derived): """ Return the guidelines table amount for a high income earner """ try: under = float(responses.get('child_support_amount_under_high_income', 0)) except ValueError: under = 0 try: over = float(responses.get('amount_income_over_high_i...
bigcode/self-oss-instruct-sc2-concepts
def get_col(df, key): """ Return a DataFrame column by either name or numeric index. :param df: A pandas.DataFrame :param key: A string or int :return: The indicated column from the dataframe, either by name or order. """ try: if isinstance(key, int) and (key not in df.columns): ...
bigcode/self-oss-instruct-sc2-concepts
import torch def generate_noise(max_norm, parameter, noise_multiplier, noise_type, device): """ A noise generation function that can utilize different distributions for noise generation. @param max_norm The maximum norm of the per-sample gradients. Any gradient with norm higher than this ...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def get_testdata_file_path(rel_path: str) -> pathlib.Path: """Gets the full path to a file in the testdata directory. Arguments: rel_path -- path relative to testdata/ Returns: pathlib.Path -- the full path to the file. """ return pathlib.Path(__file__).parent / "t...
bigcode/self-oss-instruct-sc2-concepts
def usage_hint(command, shell): """ Returns the usage hint and comment, for the given shell. """ if shell == "fish": return ("eval ({command})".format(command=command), "#") elif shell == "powershell": return ( "{command} | ForEach-Object {{If (-Not[string]::IsNullOrEmpty...
bigcode/self-oss-instruct-sc2-concepts
import random import string def latin(minimum=3, maximum=8, separator=' '): """ Simple function to generate fake (two parts) Latin species names. :param minimum: int, minimum number of letters in each part of the Latin name. :param maximum: int, maximum number of letters in each part of the Latin...
bigcode/self-oss-instruct-sc2-concepts
def report(sufficient_items, insufficient_items, condition, output = ".", prefix = None, **kwargs): """ Report the symbols which did not pass the condition. Parameters: sufficient_items: List of (name, object)-tuples that passed the condition insufficient_items: List of (n...
bigcode/self-oss-instruct-sc2-concepts
def squeeze_batch_dim(tt): """Converts batch size 1 TensorTrainBatch into TensorTrain. Args: tt: TensorTrain or TensorTrainBatch. Returns: TensorTrain if the input is a TensorTrainBatch with batch_size == 1 (known at compilation stage) or a TensorTrain. TensorTrainBatch otherwise. """ tr...
bigcode/self-oss-instruct-sc2-concepts
def test(test_cases, function): """Given a dictionary of test_cases containing inputs and their expected results after a function has been run on them, returns True if all passed, returns False if any fail with a print statement on each failure.""" successful = True for test_case in test_cases: ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import logging def get_most_recent_run_id(run_recovery_file: Path) -> str: """ Gets the string name of the most recently executed AzureML run. This is picked up from the `most_recent_run.txt` file. :param run_recovery_file: The path of the run recovery file :return: The r...
bigcode/self-oss-instruct-sc2-concepts
def nested_get(dic, path, delimiter='.'): """Get from dictionary by path :dic dict Source dictionaly. :path string Path withing dictionary :delimiter string Path delimiter :return: Value at path :rtype: unknown """ try: keys = path.split(delimiter) for key in keys[:-1]: ...
bigcode/self-oss-instruct-sc2-concepts
def str2num (text:str)->float: """ Convert string to number. Keyword arguments: text -- number in string format Output: number -- number converted """ assert text.isnumeric(),"Error: The string can not be converted to a number" number = float(text) retu...
bigcode/self-oss-instruct-sc2-concepts
def apply_func_to_ast_helper(ast, func, acc): """Recursive helper function for "apply_func_to_ast". Args: ast: The AST instance. func: The function applied to the AST elements. acc: A list of values accumulated during application. Returns: The adapted AST. """ if is...
bigcode/self-oss-instruct-sc2-concepts
def upper_section_score(die_value, final_dice, scorepad, ): """Evaluate dice from a roll for a given value and multiply the count by that value. E.g. for a die value of 3 and a count of two dice with that value the total score is 6 (die...
bigcode/self-oss-instruct-sc2-concepts
def letterize(bytes_): """ Canonicalize a byte sequence. Removes non-alphabetic characters and converts to lower case. """ return bytes(b for b in bytes_ if chr(b).isalpha()).lower()
bigcode/self-oss-instruct-sc2-concepts
def evalt(t): """ Evaluate tuple if unevaluated >>> from logpy.util import evalt >>> add = lambda x, y: x + y >>> evalt((add, 2, 3)) 5 >>> evalt(add(2, 3)) 5 """ if isinstance(t, tuple) and len(t) >= 1 and callable(t[0]): return t[0](*t[1:]) else: return t
bigcode/self-oss-instruct-sc2-concepts
def reverse_transcript_rna_char(base_char: str) -> str: """ A function that reverse transcripts mRNA char into DNA char returns '' when base char is not one of RNA bases :param base_char: :return rna_char: """ dict_of_rna_to_dna_base = {'A': 'T', 'U': 'A', ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def rotation_plane(xyz: Tuple[int, int, int]) -> Tuple[int, int, int]: """ Rotation des Punktes xyz um 90° im Uhrzeigersinn um eine z-parallele Achse durch den Punkt (2,2.0). :param xyz: Diesen Punkt rotieren. :return: Die Koordinaten nach der Rotation. """ return ...
bigcode/self-oss-instruct-sc2-concepts
def bond_or_stake(bond_price, ohm_price, reward_rate, n_rebase_to_fully_vested=15, claim_interval=1): """ Assumptions ----------- * Constant APY over vesting period: reward_rate == reward_yield, i.e. the amount of staked OHM doesn't change over the vesting period. * No trans...
bigcode/self-oss-instruct-sc2-concepts
def change_ext(input_fn, new_ext, no_dot=False, remove_player=False): """ Return the input path `input_fn` with `new_ext` as extension and the part after the last '-' removed. If `no_dot` is True, it will not add a dot before of the extension, otherwise it will add it if not present. `remove_pla...
bigcode/self-oss-instruct-sc2-concepts
def get_atoms_for_flow(flow, persistence_backend): """ Gets all atoms for a flow :param obj flow: A TaskFlow flow :param obj persistence_backend: A connection to the persistence backend :return iter[obj, ..] all_atoms: An iterable of atom objects """ return persistence_backend.get_atoms_for_...
bigcode/self-oss-instruct-sc2-concepts
import typing def calcNthTerm(a_1: typing.Union[float, int], r: typing.Union[float, int], n: typing.Union[float, int]) -> typing.Union[float, int]: """ Calculates the nth term of a geometric progression (an = a1 * r^(n-1)). :param a_1: First term. :param r: Common ratio. :param n: Number of desire...
bigcode/self-oss-instruct-sc2-concepts
import torch def eye(m, dtype=None, device=None): """Returns a sparse matrix with ones on the diagonal and zeros elsewhere. Args: m (int): The first dimension of corresponding dense matrix. dtype (`torch.dtype`, optional): The desired data type of returned value vector. (default i...
bigcode/self-oss-instruct-sc2-concepts
def get_tag(record, name, default=None): """ Loks in the XML tag 'record' for other tags named 'name', and returns the value of the first one. If none is found, it returns 'default'. """ tag = record.getElementsByTagName(name) if len(tag) and len(tag[0].childNodes): return tag[0].chi...
bigcode/self-oss-instruct-sc2-concepts
def BuildIdToBuildStatus(db, build_id): """Fetch a BuildStatus (with stages) from cidb from a build_id. Args: db: cidb.CIDBConnection object. build_id: build id as an integer. Returns: build status dictionary from CIDB with 'stages' field populated. """ build_status = db.GetBuildStatus(build_id)...
bigcode/self-oss-instruct-sc2-concepts
from io import StringIO def to_XML_string(Coalesce_object, indent_level = 1, pretty_print = True): """ Assigns the XML representation of a Coalesce object to a string. :param Coalesce_object: a Coalesce object with an "export" method :param level: multiply by 4 to determine the number of spaces for...
bigcode/self-oss-instruct-sc2-concepts
def average_of_factors(n): """ n (int): number Returns the average of the positive divisors of n """ # Initialize the sum total = 0 # Initialize the number of factors count = 0 for i in range(1, n+1): # Check if i is a divisor of n if n % i == 0: total += ...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_read(read): """Check if a read is properly mapped.""" if (read.mapping_quality >= 20 and read.reference_end and read.reference_start): return True return False
bigcode/self-oss-instruct-sc2-concepts
def calc_time_axis(df): """Returns the number of minutes between midnight of the earliest date and midnight of the day after the latest date in the dataset""" time_min = df.Timestamp.min() time_max = df.Timestamp.max() diff_in_days =(time_max.date() - time_min.date()) diff_in_minutes = (dif...
bigcode/self-oss-instruct-sc2-concepts
def filter_cds_utr_ncrna(df_in): """Filter regions CDS, UTR5, UTR3 and ncRNA by size and trim.""" utr5 = df_in.region == "UTR5" cds = df_in.region == "CDS" utr3 = df_in.region == "UTR3" ncrna = df_in.region == "ncRNA" size = df_in.end - df_in.start >= 100 df_out = df_in[(utr5 & size) | (cds ...
bigcode/self-oss-instruct-sc2-concepts
def url_joiner(url, path, trailing=None): """Join to sections for a URL and add proper forward slashes""" url_link = "/".join(s.strip("/") for s in [url, path]) if trailing: url_link += "/" return url_link
bigcode/self-oss-instruct-sc2-concepts