seed
stringlengths
1
14k
source
stringclasses
2 values
def _string_to_numbers(input_string) -> list: """Convert comma-separated floats in string form to relevant type. Parameters ---------- input_string : string Comma-separated floats values encoded as a string. Returns ------- list of numbers Returns converted list of floats o...
bigcode/self-oss-instruct-sc2-concepts
def hits(origin, res): """ calculate the hit number of recommend result :param origin: dict {user:[item,...]} the user click or behave items :param res: dict {user:[item,...]} the algorithm recommend result :return: int the number of res result in origin """ hitCount = {} for user, items...
bigcode/self-oss-instruct-sc2-concepts
def gf_sub_ground(f, a, p, K): """ Compute ``f - a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_sub_ground >>> gf_sub_ground([3, 2, 4], 2, 5, ZZ) [3, 2, 2] """ if not f: ...
bigcode/self-oss-instruct-sc2-concepts
def get_atari_filter(shape): """Get default model set for atari environments.""" shape = list(shape) # (out_size, kernel, stride) filters_84x84 = [ [16, 8, 4], [32, 4, 2], [256, 11, 1], ] filters_42x42 = [ [16, 4, 2], [32, 4, 2], [256, 11, 1], ...
bigcode/self-oss-instruct-sc2-concepts
import torch def interpolate_bilinear(grid, query_points, name='interpolate_bilinear', indexing='ij'): """Similar to Matlab's interp2 function. Finds values for query points on a grid using bilinear interpolation. Args: grid: a...
bigcode/self-oss-instruct-sc2-concepts
from unittest.mock import call def get_items(service, function, items='items', throw_reasons=None, retry_reasons=None, **kwargs): """Gets a single page of items from a Google service function that is paged. Args: service: A Google servic...
bigcode/self-oss-instruct-sc2-concepts
import socket def get_hostname_by_addr(addr): """return hostname for host at address""" try: (hostname, aliaslist, ipaddrlist) = socket.gethostbyaddr( socket.gethostbyname(addr) ) return hostname except: return addr
bigcode/self-oss-instruct-sc2-concepts
def img_normalize(img, val_range=None): """ Normalize the tensor into (0, 1). Args: tensor (torch.Tensor): input tensor. val_range (tuple): range in the form (min_val, max_val). Returns: torch.Tensor: normalized tensor """ t = img.clone() if val_range: mm, mx = v...
bigcode/self-oss-instruct-sc2-concepts
def vectorize(function): """ :param function: Function to be vectorized :return: Vectorized function Create new function y= vf(x), such that: y = f(x) / map(f, x) if x is list vf = \ f(x) if x is not list Example: >>> import math >>> >>> sqrt...
bigcode/self-oss-instruct-sc2-concepts
def deserialize_text(value): """ Deserialize a text value, """ return value
bigcode/self-oss-instruct-sc2-concepts
def coq_param(name, type): """Coq parameter Arguments: - `name`: name of the variable - `type`: type of the variable """ return "Parameter {0!s} : {1!s}.\n".format(name, type)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import base64 def webex_id_to_uuid(webex_id: Optional[str]) -> Optional[str]: """ Convert a webex id as used by the public APIs to a UUID :param webex_id: base 64 encoded id as used by public APIs :type webex_id: str :return: ID in uuid format """ return webex_...
bigcode/self-oss-instruct-sc2-concepts
import itertools def create_pairs(df, column_entity_list): """ df: Pandas dataframe Find all pairs of entities in any list of entities Returns list of paired tuples of the for [(A,B), (B,C)] """ # Join as lists l = [''.join(row) for row in df[column_entity_list]] # Tokenize string...
bigcode/self-oss-instruct-sc2-concepts
import base64 def to_base64(utf: str) -> str: """ Convert a string to its base 64 encoded string. """ bs: bytes = base64.b64encode(utf.encode()) return bs.decode()
bigcode/self-oss-instruct-sc2-concepts
import re def replaceCaseInsensitive(a_string, to_replace, replacement): """assumes a_string is a string assumes to_replace is a string assumes replacement is a string returns a new string, a_string with any instances of to_replace replased with replacement. case insinsitive.""" pattern = re.c...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def gen_sha256_hash(msg): """Generate SHA 256 Hash of the message.""" hash_object = hashlib.sha256(msg.encode('utf-8')) return hash_object.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def getNeighFeat(data_rna, G, neighbors, norm = False): """ Function for getting neighbourhood features. Calculates the sum of logFC across the different neighbours of the gene. To normalize for number of neighbours with change in fold change (FC), the norm parameter need to be True. ...
bigcode/self-oss-instruct-sc2-concepts
def timestamp(pkt_hdr): """ Returns the timestamp of the packet in epoch milliseconds. """ (epoch_secs, delta_micros) = pkt_hdr.getts() epoch_micros = (epoch_secs * 1000000.0) + delta_micros return epoch_micros
bigcode/self-oss-instruct-sc2-concepts
def _qualname(obj): """ Return the (non-fully-)qualified name of the given object. """ return obj.__qualname__
bigcode/self-oss-instruct-sc2-concepts
def delete_vertices(graph, dverts): """Delete the vertices indexed by dverts from graph; return the resulting graph.""" vertices, edges = graph remverts = list(filter(lambda x: x not in dverts, range(len(vertices)))) vmap = {v: n for (n, v) in enumerate(remverts)} nvertices = list(map(vertices.__get...
bigcode/self-oss-instruct-sc2-concepts
def HasPackedMethodOrdinals(interface): """Returns whether all method ordinals are packed such that indexing into a table would be efficient.""" max_ordinal = len(interface.methods) * 2 return all(method.ordinal < max_ordinal for method in interface.methods)
bigcode/self-oss-instruct-sc2-concepts
import textwrap def _format_doc(docstring, prefix): """Use textwrap to format a docstring for markdown.""" initial_indent = prefix # subsequent_indent = " " * len(prefix) subsequent_indent = " " * 2 block = docstring.split("\n") fmt_block = [] for line in block: line = textwrap.f...
bigcode/self-oss-instruct-sc2-concepts
import json def PrepareGroupORM(r, obj, mapping, objname, request, mappingattr='mapping'): """Prepare data assign to orm Examples:: try: r = PrepareGroupORM(r, obj, mapping, obj__heads__, self.args.items()) except Exception as error: return omitError(ErrorMsg=repr(erro...
bigcode/self-oss-instruct-sc2-concepts
def oc_to_vlan_range(value): """ Converts an industry standard vlan range into a list that can be interpreted by openconfig. For example: ["1", "2", "3..10"] -> "1, 2, 3-10" """ return ",".join(["{}".format(s).replace("..", "-") for s in value])
bigcode/self-oss-instruct-sc2-concepts
def get_inputs( filename ): """ The input notes consists of two lines. Line 1 - estimate of earliest timestamp of departure Line 2 - bus IDs in service, where 'x' = out of service This function returns a dict with the time, buses in service and their offsets """ with open( filename, 'r' ) a...
bigcode/self-oss-instruct-sc2-concepts
def F2K(T_F): """ Convert temperature in Fahrenheit to Kelvin """ return 5/9*(T_F+459.67)
bigcode/self-oss-instruct-sc2-concepts
def convert_to_demisto_class(was_classified: str) -> int: """ Convert was_classified to demisto classification :param was_classified: :return: """ if was_classified == 'Yes': demisto_class = 1 else: demisto_class = 0 return demisto_class
bigcode/self-oss-instruct-sc2-concepts
def get_months_in_range(startdate, enddate): """Enumerates all months from startdate to enddate Args: startdate: start of the list of dates enddate: end of the list of dates, likely today Returns: list of months in iso8601 format: yyyymm """ result = [] startmonth = [int...
bigcode/self-oss-instruct-sc2-concepts
def __rred(r_1, r_2): """ Calculate the reduced (effective) radius of two radii according to Hertzian contact theory. Parameters ---------- r_1: scalar The first radius. r_2: scalar The second radius. Returns ------- r_red: scalar The reduced (effective...
bigcode/self-oss-instruct-sc2-concepts
def negative_predictive_value(y_real, y_pred): """ Computes negative predictive value of a binary classification model: NPV = TN/(TN+FN). Args: y_real (np.array): Array of ground truth values y_pred (np.array): Array of predicted values Returns: (float): The negative predictiv...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def dtype_element_count( dtype, name = None ): """Returns the number of values that compose a dtype. If you need the number of elements of a specifically named column, pass the root dtype in with the name. Ie:: >>> a = numpy.dtype([ ... ('position...
bigcode/self-oss-instruct-sc2-concepts
def kwargs_to_string(kwargs): """ Given a set of kwargs, turns them into a string which can then be passed to a command. :param kwargs: kwargs from a function call. :return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise. """ outstr = '' for ...
bigcode/self-oss-instruct-sc2-concepts
def append_collection_links(request, response, link_dict): """ Convenience method to append to a response object document-level links. """ data = response.data if not 'collection_links' in data: data['collection_links'] = {} for (link_relation_name, url) in link_dict.items(): ...
bigcode/self-oss-instruct-sc2-concepts
def sol_format(values, n): """ Formats the size of the n biggest SCCs using the format "A,B,C". If the number of values is less than n, then the value 0 is used. """ res = [0]*n # Get first n values for i in range(min(len(values), n)): res[i] = values[i][1] # Format to string ...
bigcode/self-oss-instruct-sc2-concepts
def fatorial(num = 1, show = False): """ -> Cálculo do fatorial de um número :param num: O número a ser calculado :param show: (Opcional) mostra o calculo se True :return: Retorna o valor do fatorial do num. """ cal = 1 for c in range(num, 0, -1): cal *= c if show == True...
bigcode/self-oss-instruct-sc2-concepts
def rowswap(matlist, index1, index2, K): """ Returns the matrix with index1 row and index2 row swapped """ matlist[index1], matlist[index2] = matlist[index2], matlist[index1] return matlist
bigcode/self-oss-instruct-sc2-concepts
def check_joystick_compatibility(pg_joystick): """ Check if passed joystick is compatible for this application. Buttons, axes and hats number are checked to consider joystick as compatible or not. :param pygame.joystick.Joystick pg_joystick: joystick :return: True if :var pg_joystick: is compatible with current ...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logger(name): """Gets logger for module by it's name. :param str name: name of the module. :rtype: logging.Logger """ name = name.split(".")[-1] return logging.getLogger(name)
bigcode/self-oss-instruct-sc2-concepts
def data_to_psychomotor(dic): """ Returns a dictionary of psychomotor details of each student {name:{details}} """ final_dic = {} #will return to psychomotor dic_psymo = dic["psychomotor"][0] #the relevant sheet for key, value in dic_psymo.items(): del value["AGE"] final_d...
bigcode/self-oss-instruct-sc2-concepts
def horizontal_overlaps(rect, others, sorted=False): """Get rects that overlap horizontally with the given rect.""" overlaps = [] for other in others: # Note: can optimise to prevent # going through the rest of the # array when we hit a non match if rect.overlaps_y(other)...
bigcode/self-oss-instruct-sc2-concepts
def perm2cycles_without_fixed(perm): """ Convert permutation in one-line notation to permutation in cycle notation without fixed points :param perm: Permutation in one-line notation :type perm: list :return: Returns permutation in cycle notation without fixed points :rtype: list """ cy...
bigcode/self-oss-instruct-sc2-concepts
def merge(line): """ Helper function that merges a single row or column in 2048. """ n_elements = len(line) # Remove 0 entries and slide to the left line = [value for value in line if value != 0] index = 0 # Iterate while there are possible pairs while index < len(line)-1: # ...
bigcode/self-oss-instruct-sc2-concepts
def makeseed(a=None): """Turn a hashable value into three seed values for whrandom.seed(). None or no argument returns (0, 0, 0), to seed from current time. """ if a is None: return (0, 0, 0) a = hash(a) a, x = divmod(a, 256) a, y = divmod(a, 256) a, z = divmod(a, 256) x = (x + a) % 256 or 1 y = (y + a) %...
bigcode/self-oss-instruct-sc2-concepts
def try_cast_float(f): """Cast i to float, else return None if ValueError""" try: return float(f) except ValueError: return None
bigcode/self-oss-instruct-sc2-concepts
def matrix_indices(vector_idx, matrix_size): """ Convert from vector index to matrix indices. Args: vector_idx (int): Vector index. matrix_size (int): Size along one axis of the square matrix to output indices for. Returns: (int, int): Row index, column index. """ asse...
bigcode/self-oss-instruct-sc2-concepts
def check_node_on_pos(graph, position, resolution=1e-4): """ Function checks, if at least one node of graph has position 'position' Returns boolean value. 'position' attribute must be shapely Point object. Parameters ---------- graph : nx.Graph networkx graph object (nodes should have a...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle_file(path_to_file): """ Loads the data from a pickle file and returns that object """ ## Look up: https://docs.python.org/3/library/pickle.html ## The code should look something like this: # with open(path_to_file, 'rb') as f: # obj = pickle.... ## We wi...
bigcode/self-oss-instruct-sc2-concepts
def expand_unknown_vocab(line, vocab): """ Treat the words that are in the "line" but not in the "vocab" as unknows, and expand the characters in those words as individual words. For example, the word "Spoon" is in "line" but not in "vocab", it will be expanded as "<S> <p> <o> <o> <n>". """ ...
bigcode/self-oss-instruct-sc2-concepts
def identity(df): """Verb: No-op.""" return df
bigcode/self-oss-instruct-sc2-concepts
import requests import logging def _raise_for_status(response: requests.Response, logger: logging.Logger) -> requests.Response: """ Check the status code of the response. If the status code suggests an error, log the response as JSON and then raise an exception. Otherwise, return the response for further ...
bigcode/self-oss-instruct-sc2-concepts
def duration(first, last): """Evaluate duration Parameters ---------- first : int First timestamp last : int Last timestamp Returns ------- str Formatted string """ ret = '' diff = last - first if diff <= 0: return '' mm = divmod(di...
bigcode/self-oss-instruct-sc2-concepts
def replace_ellipsis(n, index): """Replace ... with slices, :, : ,: >>> replace_ellipsis(4, (3, Ellipsis, 2)) (3, slice(None, None, None), slice(None, None, None), 2) >>> replace_ellipsis(2, (Ellipsis, None)) (slice(None, None, None), slice(None, None, None), None) """ # Careful about usin...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def max_length(length: int) -> Callable[[str], bool]: """ Create an MAX length validator (inclusive) Args: length (int): MAX length Returns: Callable[[str], bool]: a function with the name exact_length_{length} """ def v(_field): return le...
bigcode/self-oss-instruct-sc2-concepts
def parse_field(field): """ Parse a non-meta key from the response attributes dict. The non-meta keys correspond to (sub-)question titles ((s)qid). If the field name contains no brackets ('[', ']'), a qid without subquestions is meant. Otherwise one or two sqids are within the brackets: two if ...
bigcode/self-oss-instruct-sc2-concepts
def replace_with_phrases(tokens, phrases): """Replace applicable tokens in semantically-ordered tokens with their corresponding phrase. Args: tokens (list of str): A list of semantically-ordered tokens. phrases (list of str): A list of phrases. Returns: list of str: A list o...
bigcode/self-oss-instruct-sc2-concepts
def get_fasta_size_from_faifile(infile): """ Get chromosome size from .fai file .fai format: 1 249250621 52 60 61 2 243199373 253404903 60 61 3 198022430 500657651 60 61 4 191154276 701980507 ...
bigcode/self-oss-instruct-sc2-concepts
def add_vecs_to_vocab(vocab, vectors): """Add list of vector tuples to given vocab. All vectors need to have the same length. Format: [("text", [1, 2, 3])]""" length = len(vectors[0][1]) vocab.reset_vectors(width=length) for word, vec in vectors: vocab.set_vector(word, vector=vec) return...
bigcode/self-oss-instruct-sc2-concepts
def int2str(value): """ int 转换为 str """ return str(value)
bigcode/self-oss-instruct-sc2-concepts
def extract_page_id(full_file_name: str) -> str: """ Extract page id from file_name Example: Data-loss-94d44921-0a4c-4319-8f78-60ef45267d97.md -> 94d449210a4c43198f7860ef45267d97 """ file_name, _ = full_file_name.rsplit('.', maxsplit=1) parts = file_name.rsplit('-', maxsplit=5) id_...
bigcode/self-oss-instruct-sc2-concepts
def _check_key_types(remote_values, local_values): """ Validates that the key types match regardless of the casing. E.g. 'RSA' == 'rsa' :param list[str] remote_values: :param list[str] local_values: :rtype: bool """ copy = [] for val in local_values: copy.append(val.upper()) ...
bigcode/self-oss-instruct-sc2-concepts
def sorted_components(layout_area, row_height, comps): """ Sort the components by row :param layout_area: a list [x, y] that stores the area of the layout :param comps: a list of components that need to be sorted :return: a list of rows, each containing a list of components in that row. """ ...
bigcode/self-oss-instruct-sc2-concepts
def _sorted_facet_counts(solr_counts, field): """ Convert the raw solr facet data (counts, ranges, etc.) from a flat array into a two-dimensional list sorted by the number of hits. The result will look something like this: (('field1', count1), ('field2', count2), ...) """ raw = solr_counts.get(...
bigcode/self-oss-instruct-sc2-concepts
import re def get_percent(line): """ Args: line: A progress string containing percent complete Return: integer of current percent value if found, otherwise None """ m = re.search(r'\d+', line) if m: try: return int(m.group()) except ValueE...
bigcode/self-oss-instruct-sc2-concepts
def esc(string): """ Escape strings for SQLite queries """ return string.replace("'", "''")
bigcode/self-oss-instruct-sc2-concepts
def min_length(minimum): """ Return a function that tests if values are the specified minimum length """ def callback(value): """Accept a value to validate, return validation results""" if len(value) >= minimum: return True, None return False, ('"' + str(value) + '" is not a ...
bigcode/self-oss-instruct-sc2-concepts
def get_tf_idf(doc_tf, idf_map): """ calculate the product of the term frequency and the idf :param doc_tf: term frequency map of the string :param idf_map: idf map of all the strings :return: vector map of a document """ vector = {} for word in doc_tf: if word in idf_map: ...
bigcode/self-oss-instruct-sc2-concepts
def extract_server_arguments(namespace): """Given the output of .parse() on a ArgumentParser that had add_server_arguments called with it, remove the resulting option in-place from namespace and return them in a separate namespace.""" server_arguments = type(namespace)() server_arguments.bind = nam...
bigcode/self-oss-instruct-sc2-concepts
def _IsOutsideTimeRange(timestamp, time_range = None): """Returns a boolean indicating whether a timestamp is in a given range.""" return time_range is not None and (timestamp < time_range[0] or timestamp > time_range[1])
bigcode/self-oss-instruct-sc2-concepts
def iloc(df, loc): """Get the specified dataframe row as a dict""" return dict(sorted(df.iloc[loc].items()))
bigcode/self-oss-instruct-sc2-concepts
import re def AuthorStart(s): """ To check if there is an author for the input text by performing a regex check to match the format of first name, first name and last name, first name and middle name and last name, or mobile number Parameters: s (string): The string for which we need to perform r...
bigcode/self-oss-instruct-sc2-concepts
def output_tensor(interpreter, i): """Gets a model's ith output tensor. Args: interpreter: The ``tf.lite.Interpreter`` holding the model. i (int): The index position of an output tensor. Returns: The output tensor at the specified position. """ return interpreter.tensor(interpreter.get_output_det...
bigcode/self-oss-instruct-sc2-concepts
def IsFlag(token_name): """Returns whether the passed string is a flag. Args: token_name: the string to check. Returns: True if it's a flag, False otherwise. """ return token_name.startswith('-')
bigcode/self-oss-instruct-sc2-concepts
import torch def L1_loss(pred, target): """ Calculate L1 loss """ return torch.mean(torch.abs(pred - target))
bigcode/self-oss-instruct-sc2-concepts
def get_server_name(prefix, xid, wid): """Gets unique server name for each work unit in the experiment. Args: prefix: String, the prefix of the server. xid: Integer, the experiment id. wid: Integer, the work unit id. Returns: String. """ return f'{prefix}-{xid}-{wid}'
bigcode/self-oss-instruct-sc2-concepts
def get_build_list(json_data: dict) -> list: """Return a list of build IDs for a device""" builds = [] for firmware in json_data["firmwares"]: builds.append(firmware["buildid"]) return builds
bigcode/self-oss-instruct-sc2-concepts
def _get_fake_dataset_contents() -> str: """ Build a fake dataset file and write it to a temporary folder. The dataset has "measurements" for 3 different channels 0, 8, and 12, with columns for two numerical features NUM1, NUM2 and two categorical features CAT1, CAT". Labels are attached to channel ...
bigcode/self-oss-instruct-sc2-concepts
import typing def clamp(source: typing.Tuple[int, int, int]) -> typing.Tuple[int, ...]: """Helper for clamping rgb values Args: source (Tuple[int, int, int]): values to be clamped Returns: value (Tuple[int, int, int]): clamped values """ return tuple(max(0, min(value, 255)) for v...
bigcode/self-oss-instruct-sc2-concepts
def _find_cells_with_tags(nb, tags): """ Find the first cell with any of the given tags, returns a dictionary with 'cell' (cell object) and 'index', the cell index. """ tags_to_find = list(tags) tags_found = {} for index, cell in enumerate(nb['cells']): for tag in cell['metadata'].g...
bigcode/self-oss-instruct-sc2-concepts
import itertools def nwise(iterable, n=2): """ Iterates over iterable n items at a time list(nwise('ABCDE', 3)) >>> ['ABC', 'BCD', 'CDE'] """ iterables = itertools.tee(iterable, n) [next(iterables[i]) for i in range(n) for j in range(i)] return zip(*iterables)
bigcode/self-oss-instruct-sc2-concepts
def serialize_device(device): """ Standard representation for a device as returned by various tasks:: { 'id': 'device_id' 'hostname': 'device_hostname', 'tags': [], 'locked': false, 'state': 'provisioning', 'ip_addresses': [ ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def validate_date(date_text): """Validates that the date is in ISO 8601 format: YYYY-MM-DD""" try: if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'): return False return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
import types def _get_synthesizer_name(synthesizer): """Get the name of the synthesizer function or class. If the given synthesizer is a function, return its name. If it is a method, return the name of the class to which the method belongs. Args: synthesizer (function or method): ...
bigcode/self-oss-instruct-sc2-concepts
def solution(n): """ Determines the maximal 'binary gap' in an integer :param n: a positive integer (between 1 and 2147483647) :return: a count of the longest sequence of zeros in the binary representation of the integer """ bin_limit = 2147483647 if not isinstance(n, int): ...
bigcode/self-oss-instruct-sc2-concepts
import struct def _parseMCCDHeader(header): """ Parse experimental metadata from MCCD header. Byte-offsets of experimental parameters are based on this `reference <http://www.sb.fsu.edu/~xray/Manuals/marCCD165header.html>`_ Parameters ---------- header : bytes MCCD header ""...
bigcode/self-oss-instruct-sc2-concepts
def _add_solr_language_info(res, obj): """ :param res: Solr document, i.e. a dict to which new keys will be added. :param obj: object which is searched for language information. :return: mutated dict res """ if getattr(obj, 'language', None): res['language_t'] = obj.language.name ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List def sieve_of_eratosthenes(n: int = 2) -> Union[List[int], None]: """ Returns a list of prime numbers up to and including n. For n<2 returns None. >>> sieve_of_eratosthenes() [2] >>> sieve_of_eratosthenes(5) [2, 3, 5] >>> sieve_of_eratos...
bigcode/self-oss-instruct-sc2-concepts
def winner(player): """ Check if the player won (has no pieces left in his hand) :param player: Player whose turn it is :return: True, if Player won, otherwise False """ if len(player.hand) == 0: return True return False
bigcode/self-oss-instruct-sc2-concepts
def is_prime(num): """ This function checks whether the input natural number larger than 1 is a prime number. :param num: :return: boolean """ i = 2 while i ** 2 <= num: if num % i == 0: return False i += 1 return True
bigcode/self-oss-instruct-sc2-concepts
import torch def np2tensor(array, device=None): """Convert form np.ndarray to torch.Tensor. Args: array (np.ndarray): A tensor of any sizes Returns: tensor (torch.Tensor): """ tensor = torch.from_numpy(array).to(device) return tensor
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path def has_dicm_prefix(filename: Union[str, Path]) -> bool: """DICOM files have a 128 byte preamble followed by bytes 'DICM'.""" with open(filename, "rb") as f: f.seek(128) return f.read(4) == b"DICM"
bigcode/self-oss-instruct-sc2-concepts
def get_sequencing_cell_id(dataset_uuid:str, barcode:str)->str: """Takes a dataset uuid and a barcode of a cell within that dataset to produce a unique cell ID""" return "-".join([dataset_uuid, barcode])
bigcode/self-oss-instruct-sc2-concepts
def splitlines(string_with_lines): """Return a ``list`` from a string with lines.""" return string_with_lines.splitlines()
bigcode/self-oss-instruct-sc2-concepts
def _gap_difference(seq_gaps: dict, union_gaps: dict) -> tuple: """ Parameters ---------- seq_gaps {gap pos: length, } of a sequence used to generate the gap union union_gaps {gap pos: maximum length, ...} derived from the same seq aligned to different sequences Returns...
bigcode/self-oss-instruct-sc2-concepts
import random def one_chance_in (n): """ Returns True with a 1/n chance. """ return (random.randint(1,n) == 1)
bigcode/self-oss-instruct-sc2-concepts
def divide_LeftRight(img): """ Divide bi-camera image into left image and right image bi-camera image shape:(720,2560,3); left and right image shape:(720,1280,3) :param img: CV2 mat image :return: ;left_img, right_img """ divide_index = img.shape[1] // 2 right_img = img[:, 0:divide_index...
bigcode/self-oss-instruct-sc2-concepts
def extract_scores(transcript): """Extract scores of different types from a grading job's output, starting from the bottom of the output :param transcript: the grading output :type transcript: str :return: a list of (key, score) pairs """ score_lines = [] found_score = False for l...
bigcode/self-oss-instruct-sc2-concepts
def _make_fasta( num_proteins, peptides, peptides_per_protein, random_state, prefix="" ): """Create a FASTA string from a set of peptides Parameters ---------- num_proteins : int The number of proteins to generate. peptides : list of str A list of peptide sequences. peptides...
bigcode/self-oss-instruct-sc2-concepts
def extract_signal(s): """ Returns the portion of s between the (first) pair of parentheses, or the whole of s if there are no parentheses. """ loc0 = s.find("(") if loc0 >= 0: loc1 = s.find(")") if loc1 >= 0: return s[loc0 + 1 : s.find(")")] return s
bigcode/self-oss-instruct-sc2-concepts
def nice_time(sec_in): """ Pretty formatting for time stamps """ seconds = int(sec_in) % 60 minutes = int((sec_in / 60)) % 60 hours = int(sec_in / 3600) return "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds)
bigcode/self-oss-instruct-sc2-concepts
def is_tag(elm): """ True if the passed object is a HTML/XML tag * **elm**: * **return**: >>> from bs4 import BeautifulSoup as bs >>> doc = bs("<span></span><p>bubu</p>", "html.parser") >>> span = doc.span >>> is_tag(doc.span) True >>> is_tag(doc.p) True >>> is_tag(list...
bigcode/self-oss-instruct-sc2-concepts