seed
stringlengths
1
14k
source
stringclasses
2 values
import re from typing import List def find_arxiv_id(string: str) -> str: """ Try to extract an arxiv id from a string. Looking for one of two forms: 1. New form -- 1603.00324 2. Old form -- hep-th/0002839 Parameters ---------- string : str String in which to perform t...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def soring_date2target(sorting_date: Union[int, float]) -> int: """Convert `sorting_date` to `target`. If `sorting_date` <= 1600 then `target` is 0. If 1600 < `sorting_date` <= 1700 then `target` is 1. If 1700 < `sorting_date` <= 1800 then `target` is 2. If 1800 < `sortin...
bigcode/self-oss-instruct-sc2-concepts
def _all_in_set_(cands, s): """ Test if all elements of 'cands' are in set 's' """ if len(cands) == 0: return False for c in cands: if not c in s: return False return True
bigcode/self-oss-instruct-sc2-concepts
def is_post(request): """Check request is a POST""" return request.method == 'POST'
bigcode/self-oss-instruct-sc2-concepts
def increment_bytes(val: bytes) -> bytes: """increment a bytes value""" length = len(val) int_val = int.from_bytes(val, byteorder="big") int_val += 1 return int_val.to_bytes(length, byteorder="big")
bigcode/self-oss-instruct-sc2-concepts
import torch def load_state(filename): """ Loads the PyTorch files saved at ``filename``, converting them to be able to run with CPU or GPU, depending on the availability on the machine. """ if torch.cuda.is_available(): return torch.load(filename) else: return torch.load(filen...
bigcode/self-oss-instruct-sc2-concepts
def butlast(thing): """ BUTLAST wordorlist BL wordorlist if the input is a word, outputs a word containing all but the last character of the input. If the input is a list, outputs a list containing all but the last member of the input. """ if isinstance(thing, str): return thin...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple import random def get_noises(trajectory_len: int, noise_magnitude: float, random_seed: int) -> List[Tuple[float, float]]: """ Get `trajectory_len` noise values where each noise value is a tuple (noise_0, noise_1), noise_i is a Gaussian white noise generated fro...
bigcode/self-oss-instruct-sc2-concepts
def bsuccessors(state): """Return a dict of {state:action} pairs. A state is a (here, there, t) tuple, where here and there are frozensets of people (indicated by their times) and/or the light, and t is a number indicating the elapsed time.""" here, there, t = state if 'light' in here: retu...
bigcode/self-oss-instruct-sc2-concepts
def chinese_leap(date): """Return 'leap' element of a Chinese date, date.""" return date[3]
bigcode/self-oss-instruct-sc2-concepts
def get_starting_model(interaction_dict, verbose=False): """Returns as a starting model one of the CustomModel of the chain with more recorded interactions""" if verbose: print("Selecting best interaction from where to start modeling...") max_len = 0 interaction_key = None for key in interac...
bigcode/self-oss-instruct-sc2-concepts
def scale(X, min=0, max=1): """Scale X to given range. Parameters ---------- X : np.array of shape=(n_samples, n_features) Data to scale. min : float, default = 0 Minimum value to scale to. max : float, default = 1 Maximum value to scale...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _get_abc_from_superclass_name(qualified_superclass_name: str) -> str: """ Get the corresponding abstract base class name """ qualified_abc_name_list: List[str] = qualified_superclass_name.split(".") qualified_abc_name_list.insert(1, "abc") return ".".join(qualified_...
bigcode/self-oss-instruct-sc2-concepts
def problem_found(status): """ Check if there is an Rfam issue. """ return str(bool(status["has_issue"]))
bigcode/self-oss-instruct-sc2-concepts
def get_bin_list(n, nmax): """ return a list of digits of the binary representation of n nmax is the maximum theoretical value of n, used to add 0 at the front of the list if necessary """ if n == 0: return [0 for _ in range(len(bin(nmax))-3)] n = bin(n) digits = [] for i in rang...
bigcode/self-oss-instruct-sc2-concepts
def _unfold_parallel(lists, n_jobs): """Internal function to unfold the results returned from the parallization Parameters ---------- lists : list The results from the parallelization operations. n_jobs : optional (default=1) The number of jobs to run in parallel for both `fit` and...
bigcode/self-oss-instruct-sc2-concepts
def low(self): """Low edge of first bin. :returns: low edge of first bin :rtype: float """ ax = self.GetXaxis() return ax.GetXmin()
bigcode/self-oss-instruct-sc2-concepts
def make_missing_swift_child(child): """ Generates a Swift call to make the raw syntax for a given Child object. """ if child.is_token(): token = child.main_token() tok_kind = token.swift_kind() if token else "unknown" if token and not token.text: tok_kind += '("")' ...
bigcode/self-oss-instruct-sc2-concepts
def is_list(klass): """ Determine whether klass is a List """ return klass.__origin__ == list
bigcode/self-oss-instruct-sc2-concepts
def findclosest(list, value): """Return (index, value) of the closest value in `list` to `value`.""" a = min((abs(x - value), x, i) for i, x in enumerate(list)) return a[2], a[1]
bigcode/self-oss-instruct-sc2-concepts
def true(*ignore, **everything): """Give True regardless of the input.""" return True
bigcode/self-oss-instruct-sc2-concepts
import socket import contextlib def find_free_port() -> int: """ :return: a free port; mind that this is not multi-process safe and can lead to race conditions. """ skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) with contextlib.closing(skt): skt.bind(('', 0)) _, port = skt...
bigcode/self-oss-instruct-sc2-concepts
def isket(state): """Checks whether a state is a ket based on its shape. Args: state (:obj:`jnp.ndarray`): input state Returns: bool: ``True`` if state is a ket and ``False`` otherwise """ return state.shape[1] == 1
bigcode/self-oss-instruct-sc2-concepts
def kmerize_orf(orf, k, t): """ Creates kmers of certain size and type from provided sequence. :param orf: nucleotide sequence :param k: size of a kmer :param t: type of a kmer, i.e. 'simple', 'all' or 'codon' :return kmers: list of kmers """ kmers = [] if t == 'simple': sto...
bigcode/self-oss-instruct-sc2-concepts
def clean_str(s: str) -> str: """ Remove characters the pronouncing library can't handle. Parameters: s (str): The string to sanitize. Returns: The sanitized string. """ DEL_CHARS = ["(", ")", "[", "]", "{", "}", ",", ":", ";", "."] SWAP_CHARS = [("-", " ")] for char in DEL_CHARS: s = s.replace(char,...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources import json def load_vocabularies(project): """Load project vocabularies from json file. Load from project json data files all accepted values for facets. Args: project (str): data project Returns: a series of lists (list): one for each facets, elements are acce...
bigcode/self-oss-instruct-sc2-concepts
def vecs2tuples(vecs): """ Convert list of vectors into set of tuples """ return set(tuple(v) for v in vecs)
bigcode/self-oss-instruct-sc2-concepts
def unliteral(lit_type): """ Get base type from Literal type. """ if hasattr(lit_type, '__unliteral__'): return lit_type.__unliteral__() return getattr(lit_type, 'literal_type', lit_type)
bigcode/self-oss-instruct-sc2-concepts
def top_basemap_layer_url(layers): """Returns the URL of the top map layer if it exists""" if layers[-1].is_basemap and len(layers) > 1: return layers[-1].url return None
bigcode/self-oss-instruct-sc2-concepts
def meters_to_user_units_scale_factor(units: str) -> float: """ Return the scale factor to convert meters to user units. Multiply the meters value by the scale factor to get user units Args: units: String containing 'english' or 'meters' Returns: Scale factor """ if units == 'e...
bigcode/self-oss-instruct-sc2-concepts
def execute_query(driver,query): """Execute the provided query using the provided Neo4j database connection and driver. Parameters: driver A Neo4j bolt driver object query A Cypher query to be executed against the Neo4j database """ with driver.session() as session: results =...
bigcode/self-oss-instruct-sc2-concepts
def _get_deploy_iso_name(node): """Returns the deploy ISO file name for a given node. :param node: the node for which ISO file name is to be provided. """ return "deploy-%s.iso" % node.name
bigcode/self-oss-instruct-sc2-concepts
def binary_to_string(input_binary: str) -> str: """Convert binary string to Ascii string. :param input_binary: An input binary encoded string. :return: The Ascii encoded equivalence of the input binary string. """ binary_from_str = int(input_binary, 2) byte_from_binary = binary_from_str.to_byte...
bigcode/self-oss-instruct-sc2-concepts
def calculate_enrichment(coverage_values): """Calculate TSS enrichment value for a dataset Parameters ---------- coverage_values iterable of tuples (tss_center_depth, flank_depth) per TSS Returns ------- float the TSS enrichment value """ tss_depth, flank_depth...
bigcode/self-oss-instruct-sc2-concepts
def get_interaction_id(question_id): """Returns the interaction_id from input question_id.""" rindex = question_id.rfind("_") if rindex == -1: return question_id return question_id[:rindex]
bigcode/self-oss-instruct-sc2-concepts
def merge_config(c1, c2): """ Merge 2 configs c1 and c2 (where c1 is the default config and c2 the user defined config). A config is a python dictionary. The result config takes key:value from c1 if key is not present in c2, and key:value from c2 otherwise (key is either present both in in c1 and c...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def read_file(loc: str | Path) -> str: """Read test from a file. :param loc: The file system location of the file. :return: A :class:str object. :rtype: str """ path = Path(loc) with open(path) as fh: contents = fh.read() return contents
bigcode/self-oss-instruct-sc2-concepts
import re def _normalise_id(raw_id): """Reddit IDs start with t1_, t2_, etc. which need to be stripped.""" return re.sub("^t[0-9]_", "", raw_id)
bigcode/self-oss-instruct-sc2-concepts
def dist(spectrum, A, B): """ Minimum number of steps along ring to get from one pitch to the next Parameters: ----------- spectrum: list user-defined spectrum A: int first pitch B: int second pitch """ length = len(spectrum) forwa...
bigcode/self-oss-instruct-sc2-concepts
def get_planet_product_type(img_path): """ return if file is scene or OrthoTile""" split = img_path.stem.split('_') # check if 4th last imagename segment is BGRN if split[-4] == 'BGRN': pl_type = 'OrthoTile' else: pl_type = 'Scene' return pl_type
bigcode/self-oss-instruct-sc2-concepts
import requests def shrink(url): """ Shrinks the given URL. """ return requests.post('http://tinyurl.com/api-create.php', data={'url': url}).text
bigcode/self-oss-instruct-sc2-concepts
def get_license(j): """ By default, the license info can be achieved from json["info"]["license"] In rare cases it doesn't work. We fall back to json["info"]["classifiers"], it looks like License :: OSI Approved :: BSD Clause """ if j["info"]["license"] != "": return j["info"]["license"]...
bigcode/self-oss-instruct-sc2-concepts
def parse_literal(x): """ return the smallest possible data type for a string or list of strings Parameters ---------- x: str or list a string to be parsed Returns ------- int, float or str the parsing result Examples -------- >>> isinstance(parse_liter...
bigcode/self-oss-instruct-sc2-concepts
def decode_params(filename): """ Decode the tlusty filenames for the model parameters """ model_params = {} slashpos = filename.rfind("/") periodpos = filename.rfind(".flux") # translation of metallicity code met_code = {"C": 2.0, "G": 1.0, "L": 0.5, "S": 0.2, "T": 0.1} met_char = ...
bigcode/self-oss-instruct-sc2-concepts
def checkpoints(period, total): """ A helpful function for individual train method. to generate checkpoint list with integers for every PERIOD time steps and TOTAL time steps in total. """ ckps = [ period * x for x in range(1, total // period) ] return ckps
bigcode/self-oss-instruct-sc2-concepts
def json_length(msg_body: str) -> str: """ The robot's JSON API requires the length of the JSON command to be specified before the JSON command. This function calculates the length of the JSON message body and formats it for the JSON API. :param msg_body: the JSON message body. :return: the length of t...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def how_many_namefellows(queue: List[str], person_name: str) -> int: """ :param queue: list - names in the queue. :param person_name: str - name you wish to count or track. :return: int - the number of times the name appears in the queue. """ return queue.count(person...
bigcode/self-oss-instruct-sc2-concepts
def extract_capabilities(text): """Extract a capabilities list from a string, if present. Args: text: String to extract from Returns: Tuple with text with capabilities removed and list of capabilities """ if b"\0" not in text: return text, [] text, capabilities = text.rstrip().spl...
bigcode/self-oss-instruct-sc2-concepts
import torch def extract_ampl_phase(fft_im): """ Extracts amplitude and phase from the image Args: fft_im (Tensor): size should be bx3xhxwx2 Returns: tuple: (amplitude, phase) """ # fft_im: size should be bx3xhxwx2 fft_amp = fft_im[:, :, :, :, 0]**2 + fft_im[:, :, :, :, 1]*...
bigcode/self-oss-instruct-sc2-concepts
def __float2str(value: float) -> str: """Convert a float into a human readable string representatoin.""" if value == 0.0: return "0.0" return "{0:.5f}".format(value)
bigcode/self-oss-instruct-sc2-concepts
def set_prior(kind = 'scale', logbeta_max=-1, logbeta_min=-6, M_max=20, r_max=30, scale_max=25, mu_ol_max=25, r_min_min=0.3, r_max_max=1.5, delta_r_min=0.2): """ Setup prior transforms for models...
bigcode/self-oss-instruct-sc2-concepts
import typing def get_word_transform(name: str) -> typing.Callable[[str], str]: """Gets a word transformation function by name.""" if name == "upper": return str.upper if name == "lower": return str.lower return lambda s: s
bigcode/self-oss-instruct-sc2-concepts
def make_query(user_id=None, tenant_id=None, resource_id=None, user_ids=None, tenant_ids=None, resource_ids=None): """Returns query built from given parameters. This query can be then used for querying resources, meters and statistics. :Parameters: - `user_id`: user_id, has a prio...
bigcode/self-oss-instruct-sc2-concepts
def get_model_pk_column(model_class): """ Get the primary key Column object from a Declarative model class :param Type[DeclarativeMeta] model_class: a Declarative class :rtype: Column """ primary_keys = model_class.__mapper__.primary_key assert len(primary_keys) == 1, "Nested object must h...
bigcode/self-oss-instruct-sc2-concepts
def lgfCoord(point, lgfOrigin, trf2lgfMatrix): """ Determines the coordinates of a point in a Local Geodetic Frame. :param point: Coordinates of the point of interest expressed in ECEF :param lgfOrigin: Coordinates of the LGF origin expressed in ECEF :param lgf2trfMatrix: Rotation matrix from :...
bigcode/self-oss-instruct-sc2-concepts
import math def poh_from_hydronium(concentration): """Returns the pOH from the hydronium ion concentration.""" return 14 + math.log(concentration)
bigcode/self-oss-instruct-sc2-concepts
def __ror__(self, x): """Allows piping input to :class:`torch.nn.Module`, to match same style as the module :mod:`k1lib.cli`. Example:: # returns torch.Size([5, 3]) torch.randn(5, 2) | nn.Linear(2, 3) | cli.shape()""" return self(x)
bigcode/self-oss-instruct-sc2-concepts
def reverse_match(seq: str, recog: list) -> (bool): """ Match the sequence with a recognition sequence in reverse. :param seq: the sequence to search in :param recogn: a list with bases that should be matched subsequently :return: True if the sequence matches the rec...
bigcode/self-oss-instruct-sc2-concepts
import base64 def encode_bytes(bytes_): """ Encodes some given bytes into base64 using utf-8. :param bytes bytes_: The bytes to encode :return: The bytes encoded base64 string :rtype: str """ return base64.encodebytes(bytes_).decode("utf-8")
bigcode/self-oss-instruct-sc2-concepts
import torch def max(dat, dim=None): """Maximum element (across an axis) for tensors and arrays""" if torch.is_tensor(dat): return dat.max() if dim is None else dat.max(dim=dim).values else: return dat.max(axis=dim)
bigcode/self-oss-instruct-sc2-concepts
def payload_to_str_base(payload): """ Converts a given payload to its str_base representation. A str_base payload is for example: "0xFF 0xFF 0xFF 0xFF". :param payload: The payload to be converted. :return: Returns the str_base representation of the payload. """ result = "" for i in ran...
bigcode/self-oss-instruct-sc2-concepts
def _next_regular(target): """ Find the next regular number greater than or equal to target. Regular numbers are composites of the prime factors 2, 3, and 5. Also known as 5-smooth numbers or Hamming numbers, these are the optimal size for inputs to FFTPACK. Target must be a positive integer. ...
bigcode/self-oss-instruct-sc2-concepts
def __decode_lens__(lens_package): """ decode the lens_package tuple into its constituents Args: lens_package: a tuple or a |ParaxialModel|. If it's a tuple: - the first element is a |ParaxialModel| - the second element is a tuple with the begining and ending ...
bigcode/self-oss-instruct-sc2-concepts
def euclidean_algorithm(a: int, b: int) -> int: """ Finds the greatest common divisor of two natural numbers. If n or k is less than or equal to 0, it raises ValueError. >>> euclidean_algorithm(6,9) 3 >>> euclidean_algorithm(8, 20) 4 >>> euclidean_algorithm(19, 17) 1 >>> euclidea...
bigcode/self-oss-instruct-sc2-concepts
def setdiff(list1, list2): """ returns list1 elements that are not in list2. preserves order of list1 Args: list1 (list): list2 (list): Returns: list: new_list Example: >>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def createLookup(B): """Process B to create a reverse lookup scheme that is appropriate for any of the libraries in pyncomb that allow for one or more base sets to be specified. Let rev(K) be the reverse lookup dictionary of a list K, i.e. if K[i] = j, then rev(K)[j] ...
bigcode/self-oss-instruct-sc2-concepts
def __makenumber(value): """ Helper function to change the poorly formatted numbers to floats Examples: > value is an integer / float data type -> float type returned > value = '1,000', then the float value is 1000 > value = '1 000 000.00' then the float value is 1000000 ...
bigcode/self-oss-instruct-sc2-concepts
def request_add_host(request, address): """ If the request has no headers field, or request['headers'] does not have a Host field, then add address to Host. :param request: a dict(request key, request name) of http request :param address: a string represents a domain name :return: request after add...
bigcode/self-oss-instruct-sc2-concepts
def classif_accuracy(labels, preds): """Gets the percentage of correct classified predictions. Parameters ---------- labels : torch.tensor The true labels. preds : torch.tensor The prediction. Returns ------- float Percentage of correct classified labels. "...
bigcode/self-oss-instruct-sc2-concepts
def indexing(pair): """ The indexing method receives a pair of user X and followed users by X. for example it receives (X, Fi) as a pair which X follows Fi. This method returns (Fi, X) and (X, -Fi). :param pair: (X, Fi) as a pair which X follows Fi. :return: is a list of pairs [(Fi, X), (X, -Fi)...
bigcode/self-oss-instruct-sc2-concepts
def sanitize_single_id(value: str | int) -> str: """ Update `value` to a sanitized sql-friendly name. Force to string and then scrub out: space, slash, dash, comma e.g. "Food/Drink" -> "fooddrink" Arguments: value (str | int): unique ID value for a POI Returns: str: POI value ...
bigcode/self-oss-instruct-sc2-concepts
def is_in(x, l): """Transforms into set and checks existence Given an element `x` and an array-like `l`, this function turns `l` into a set and checks the existence of `x` in `l`. Parameters -------- x : any l : array-like Returns -------- bool """ return x in set(l)
bigcode/self-oss-instruct-sc2-concepts
import re def termlist_to_doubleamp_query(termlist_str, field=None): """ Take a comma separated term list and change to a (double ampersand) type query term (e.g., for solr) >>> a = "tuckett, dav" >>> termlist_to_doubleamp_query(a) 'tuckett && dav' >>> termlist_to_doubleamp_query(a, f...
bigcode/self-oss-instruct-sc2-concepts
import re def tokenize_datetime(text: str) -> str: """Tokenizes datetime to make it consistent with the seaweed tokens.""" # 5.10 => 5 . 10 # 4:00 => 4 : 00 # 5/7 => 5 / 7 # 5\7 => 5 \ 7 # 3-9 => 3 - 9 text = re.sub(r"(\d)([.:/\\-])(\d)", r"\1 \2 \3", text) # 4pm => 4 pm text = re...
bigcode/self-oss-instruct-sc2-concepts
def ambitus(pitches: list) -> int: """The ambitus or range of a melody in semitones >>> ambitus([60, 62, 64, 65, 60]) 5 Parameters ---------- pitches : list List of MIDI pitches Returns ------- int The ambitus """ return max(pitches) - min(pitches)
bigcode/self-oss-instruct-sc2-concepts
def Clamp01(num): """ Returns ``num`` clamped between 0 and 1. Parameters ---------- num : float Input number """ if num < 0: return 0 if num > 1: return 1 return num
bigcode/self-oss-instruct-sc2-concepts
def get_dayseconds(dt): """Returns the number of seconds behind the most recent midnight. For example: ``get_dayseconds(datetime(2016, 9, 12, 1, 2, 3)) => 3723``. """ return dt.hour * 3600 + dt.minute * 60 + dt.second
bigcode/self-oss-instruct-sc2-concepts
def extract_encoding_and_rate_from_wav_header(wav_header): """ Attempt to extract encoding, sample rate from possible WAV header. Args: wav_header (bytes): Possible WAV file header. Returns: Union[bool, str]: False or truthy value, which may be the encoding name...
bigcode/self-oss-instruct-sc2-concepts
def wrap_in(key): """Wraps value in dict ``{key: value}``""" return lambda val: {key: val}
bigcode/self-oss-instruct-sc2-concepts
def tartaglia(n): """ Funzione per generare un triangolo di tartaglia. Parametri --------- n: int Altezza del triangolo da generare Output ------ triangolo: list of lists [[],[],[],...] Lista di liste, corrispondenti alle righe del triangolo di tartaglia. Esempio -...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def format_datetime(dt: datetime): """Format a datetime for Magento.""" # "2021-07-02 13:19:18.300700" -> "2021-07-02 13:19:18" return dt.isoformat(sep=" ").split(".", 1)[0]
bigcode/self-oss-instruct-sc2-concepts
def _normalize_path(path): """Internal helper that strips "./" on the left side of the path. """ if path.startswith("./"): return path[2:] return path
bigcode/self-oss-instruct-sc2-concepts
def add(a, b): """ Adds two numbers. >>> add(3, 2) 5 :param a: first number :param b: second number :return: sum """ return a + b
bigcode/self-oss-instruct-sc2-concepts
import json def load_dataset(data_path): """Load existing json format dataset """ datafile = open(data_path) return json.load(datafile)
bigcode/self-oss-instruct-sc2-concepts
def get_sorted_node_parents(graph, node_with_parents): """ Get the parent nodes of a WIR node sorted by argument index. """ node_parents = list(graph.predecessors(node_with_parents)) node_parents_with_arg_index = [(node_parent, graph.get_edge_data(node_parent, node_with_parents)) ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def dt_obj_to_isodt_str(dt): """ Convert datetime object to ISO 8601 string. :param datetime dt: datetime object in UTC timezone :returns: ISO 8601 string """ assert isinstance(dt, datetime) # Using naive datetime object without timezone, assumed utc retu...
bigcode/self-oss-instruct-sc2-concepts
import json def is_json_format(str): """json値判断 Args: str (str): json文字列 Returns: bool: True:json, False:not json """ try: # Exceptionで引っかかるときはすべてJson意外と判断 json.loads(str) except json.JSONDecodeError: return False except ValueError: return ...
bigcode/self-oss-instruct-sc2-concepts
def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y): """ Find control points of the Bezier curve passing through (*c1x*, *c1y*), (*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1. """ cmx = .5 * (4 * mmx - (c1x + c2x)) cmy = .5 * (4 * mmy - (c1y + c2y)) return [(c1x, c...
bigcode/self-oss-instruct-sc2-concepts
def sensitivity_calc(sign_residues_per_iter): """ | Inputs the output of ``bootstrapped_residue_analysis`` and calculates the sensitivity of each residue. | The returned sensitivity of each residue is calculated by calculating ``residue_appearances / iterations``. | A sensitivity of 1 is ideal meaning t...
bigcode/self-oss-instruct-sc2-concepts
def numpy_dtype_to_numeric_type(element): """Return a valid numeric_type value based on the dtype of numpy array.""" lst = { "<u1": "uint8", "<u2": "uint16", "<u4": "uint32", "<u8": "uint64", "<i1": "int8", "<i2": "int16", "<i4": "int32", "<i8": "i...
bigcode/self-oss-instruct-sc2-concepts
def value_check(inval): """ Check if a value is equal to None :param inval: the input value :param inval: float :return: 1 if the input value is None, 0 otherwise :return type: integer """ result = 0 if inval is None: result = 1 return result
bigcode/self-oss-instruct-sc2-concepts
def nvl(value, defval="Unknown"): """ Provide a default value for empty/NULL/None. Parameters ---------- value: obj The value to verify. defval: obj The value to return if the provide value is None or empty. Returns ------- defval if value is None or empty, othe...
bigcode/self-oss-instruct-sc2-concepts
def slope_tree_check(lines: list, dx: int, dy: int) -> int: """check how many trees would be encountered with a specific slope""" x_pos = 0 y_pos = 0 trees_encountered = 0 line_length = len(lines[0]) while y_pos < len(lines): if lines[y_pos][x_pos] == '#': trees_encountered +...
bigcode/self-oss-instruct-sc2-concepts
import math def log10_zero(x): """Return the log10 of x, map log10(0) -> 0.""" if x == 0: return 0 else: return math.log10(x)
bigcode/self-oss-instruct-sc2-concepts
def get_digit_at_pos(num, base, pos): """ Gets the integer at the given position of the number in a specific base @param num The number we wish to find the converted digit in @param base The base in which the digit is calculated @param pos The position of the digit to be found @re...
bigcode/self-oss-instruct-sc2-concepts
def bit_last(x): """ Get the last digit where 1 stands (0-indexed) x.bit_length()と同じ。 ref: https://www.slideshare.net/KMC_JP/slide-www Args: x (int): bit Returns: int: last digit >>> bit_last(1) 0 >>> bit_last(4) 2 >>> bit_last(6) 1 >>> bit_last...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_file_hash(path, block_size=8192): """Calculates the content hash for the file at the given path.""" md5 = hashlib.md5() with open(path, 'rb') as f: while True: block = f.read(block_size) if not block: break md5.update(block...
bigcode/self-oss-instruct-sc2-concepts
def create_message_subject(info, context): """ Create the message subject """ base = '%s request completed' % context['display_name'] if info['errors'] > 0: return '%s with ERRORS!' % base elif info['warnings'] > 0: return '%s with WARNINGS!' % base else: return base
bigcode/self-oss-instruct-sc2-concepts
import string def is_pangram(s): """ Detect whether or not a given string input is a pangram. :param s: a string value. :return: true if string is a pangram, otherwise false. """ return set(string.ascii_lowercase) <= set(s.lower())
bigcode/self-oss-instruct-sc2-concepts
def format_input(x): """Transforms rows of numers written as strings into a list of lists of ints""" delimiter = '\t' if '\t' in x else ' ' # test_value doesn't use \t but input does return [[int(s) for s in r.split(delimiter) if s != ''] for r in x.split('\n')]
bigcode/self-oss-instruct-sc2-concepts