seed
stringlengths
1
14k
source
stringclasses
2 values
def list_sorted(words): """ Check if a Tuple of words are Anagrams using Sorted :param words: Tuple :return: bool """ word_one, word_two = words return sorted(word_one) == sorted(word_two)
bigcode/self-oss-instruct-sc2-concepts
def select_hannover_from_metadata(metadata): """Select entries from Hannover""" return metadata.query('doi == "10.6084/m9.figshare.12275009"')
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_fd_hash(fd): """ Compute the sha256 hash of the bytes in a file-like """ BLOCKSIZE = 1 << 16 hasher = hashlib.sha256() old_pos = fd.tell() fd.seek(0) buf = fd.read(BLOCKSIZE) while buf: hasher.update(buf) buf = fd.read(BLOCKSIZE) fd.seek(o...
bigcode/self-oss-instruct-sc2-concepts
def crop(img, left=None, right=None, top=None, bottom=None): """Crop image. Automatically limits the crop if bounds are outside the image. :param numpy.ndarray img: Input image. :param int left: Left crop. :param int right: Right crop. :param int top: Top crop. :param int bottom: Bottom cr...
bigcode/self-oss-instruct-sc2-concepts
import yaml def open_yaml(path): """Open yaml file and return as a dictionary""" data = {} with open(path) as open_file: data = yaml.safe_load(open_file) return data
bigcode/self-oss-instruct-sc2-concepts
import logging def getLogger(name): """ Returns a logger. Wrapper of logging.getLogger """ logger = logging.getLogger(name) return logger
bigcode/self-oss-instruct-sc2-concepts
def find_missing_keywords(keywords, text): """ Return the subset of keywords which are missing from the given text """ found = set() for key in keywords: if key in text: found.add(key) return list(set(keywords) - found)
bigcode/self-oss-instruct-sc2-concepts
def samplesheet_headers_to_dict(samplesheet_headers: list) -> dict: """ Given a list of headers extracted with extract_samplesheet_header_fields, will parse them into a dictionary :param samplesheet_headers: List of header lines :return: Dictionary containing data that can be fed directly into the RunSa...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any from typing import List import yaml def insert_worker(worker: Dict[str, Any], workers: List[Dict[str, Any]]) -> None: """Inserts client or server into a list, without inserting duplicates.""" def dump(...
bigcode/self-oss-instruct-sc2-concepts
def solve_5bd6f4ac(x): """ - Problem : 5bd6f4ac \n *General Description* (Problem and solving it visually - intuition): I get the zoomed in grid, only containing the top right third of the original input grid.\n *Algorithm* (to guide understandiing of the code) - Fi...
bigcode/self-oss-instruct-sc2-concepts
def set_windows_slashes(directory): """ Set all the slashes in a name so they use Windows slashes (\) :param directory: str :return: str """ return directory.replace('/', '\\').replace('//', '\\')
bigcode/self-oss-instruct-sc2-concepts
def to_str(s): """Parse a string and strip the extra characters.""" return str(s).strip()
bigcode/self-oss-instruct-sc2-concepts
def remove_prefix(text: str, prefix: str) -> str: """ Removes the prefix if it is present, otherwise returns the original string. """ if text.startswith(prefix): return text[len(prefix):] return text
bigcode/self-oss-instruct-sc2-concepts
def classesByCredits (theDictionary, credits): """Lists the courses worth a specific credit value. :param dict[str, int] theDictionary: The student's class information with the class as the key and the number or credits as the value :param int credits: The credit value by which classes are queried ...
bigcode/self-oss-instruct-sc2-concepts
import base64 def _decode_string(text): """Decode value of the given string. :param text: Encoded string :return: Decoded value """ base64_bytes = text.encode('ascii') message_bytes = base64.b64decode(base64_bytes) return message_bytes.decode('ascii')
bigcode/self-oss-instruct-sc2-concepts
def create_occurence_dict(text): """Create the occurence dict of characters for a given text. :text: str, ascii text :returns: Dict[char:int], occurence dict """ result = {} for c in text: if c in result: result[c] += 1 else: result[c] = 1 return resu...
bigcode/self-oss-instruct-sc2-concepts
import torch def gaussian_smearing(distances, offset, widths, centered=False): """ Perform gaussian smearing on interatomic distances. Args: distances (torch.Tensor): Variable holding the interatomic distances (B x N_at x N_nbh) offset (torch.Tensor): torch tensor of offsets cente...
bigcode/self-oss-instruct-sc2-concepts
def search_roles_by_name(api, configuration, api_version, api_exception, role_name): """ Searches for a role by name and returns the ID. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the api client. :param api_version: The version of the API to use. ...
bigcode/self-oss-instruct-sc2-concepts
def get_relevant_features(features, diff_threshold = 0.05, active_threshold = 0.1, inactive_threshold = 0.1): """ -- DESCRIPTION -- Extract "relevant" features from a set of given features. Relevant in this case means that th...
bigcode/self-oss-instruct-sc2-concepts
def group_weights(weights): """ Group each layer weights together, initially all weights are dict of 'layer_name/layer_var': np.array Example: input: { ...: ... 'conv2d/kernel': <np.array>, 'conv2d/bias': <np.array>, ....
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List def dict2args(data: Dict) -> List[str]: """Convert a dictionary of options to command like arguments.""" result = [] # keep sorting in order to achieve a predictable behavior for k, v in sorted(data.items()): if v is not False: prefix...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def _hash(example_with_id) -> str: """Hashes a single example.""" key = example_with_id[0], example_with_id[1]["text"] key_bytes = str(key).encode("utf8") return hashlib.sha256(key_bytes).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
import pickle def reference(infile): """ Load the given reference profile file. :params infile: The input filename or file object :returns: The reference list """ # If the input is a string then open and read from that file if isinstance(infile, str): with open(infile, "rb") as i...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def _text_compare(t1: Optional[str], t2: Optional[str]) -> bool: """Compare two text strings, ignoring wrapping whitespaces. Args: t1: First text. t2: Second text. Returns: True if they are equal, False otherwise. """ ...
bigcode/self-oss-instruct-sc2-concepts
def invert_y_and_z_axis(input_matrix_or_vector): """ This Function inverts the y and the z coordinates in the corresponding matrix and vector entries (invert y and z axis <==> rotation by 180 degree around the x axis) For the matrix multiplication holds: |m11 m12 m13| |x| |m11 x + m12 y + ...
bigcode/self-oss-instruct-sc2-concepts
import ast def binop(x, op, y, lineno=None, col=None): """Creates the AST node for a binary operation.""" lineno = x.lineno if lineno is None else lineno col = x.col_offset if col is None else col return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col)
bigcode/self-oss-instruct-sc2-concepts
def strtobool(value): """ This method convert string to bool. Return False for values of the keywords "false" "f" "no" "n" "off" "0" or 0. Or, return True for values of the keywords "true" "t" "yes" "y" "on" "1" or 1. Or, othres return None. Args: value : string value Return: Return False for va...
bigcode/self-oss-instruct-sc2-concepts
def toStringVer(version): """Converts a semantic version string to a string with leading zeros""" split = version.split(".") fullversion = "" for i, v in enumerate(split, start=0): fullversion += v.rjust(2, "0") return fullversion
bigcode/self-oss-instruct-sc2-concepts
def ranges_overlap(x1, x2, y1, y2): """Returns true if the ranges `[x1, x2]` and `[y1, y2]` overlap, where `x1 <= x2` and `y1 <= y2`. Raises: AssertionError : If `x1 > x2` or `y1 > y2`. """ assert x1 <= x2 assert y1 <= y2 return x1 <= y2 and y1 <= x2
bigcode/self-oss-instruct-sc2-concepts
import re def initialize_record(fields, shape_record): """Initializes a dictionary that stores a shapefile record. Args: fields: List that stores the shapefile record names shape_record: Object that contains a shapefile record and associated shape Returns: ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def collect_filepaths(main_path, format="png"): """ Collect a set of files using a determined location on disk and a known list of file formats. This is useful to get the full path of files encountered on a disk folder. Parameters ---------- main_path : str ...
bigcode/self-oss-instruct-sc2-concepts
import re def natural_sort(values, case_sensitive=False): """ Returns a human readable list with integers accounted for in the sort. items = ['xyz.1001.exr', 'xyz.1000.exr', 'abc11.txt', 'xyz.0999.exr', 'abc10.txt', 'abc9.txt'] natural_sort(items) = ['abc9.txt', 'abc10.txt', 'abc11.txt', 'xyz.0999.exr...
bigcode/self-oss-instruct-sc2-concepts
def python_name(cmd_name): """Convert ``-`` to ``_`` in command name, to make a valid identifier.""" return cmd_name.replace("-", "_")
bigcode/self-oss-instruct-sc2-concepts
def name(name): """Give a command a alternate name.""" def _decorator(func): func.__dict__['_cmd_name'] = name return func return _decorator
bigcode/self-oss-instruct-sc2-concepts
import inspect def params(func): """Shorthand to get the parameter spec for a function.""" return list(inspect.signature(func).parameters.values())
bigcode/self-oss-instruct-sc2-concepts
import random def random_class_ids(lower, upper): """ Get two random integers that are not equal. Note: In some cases (such as there being only one sample of a class) there may be an endless loop here. This will only happen on fairly exotic datasets though. May have to address in future. :param lo...
bigcode/self-oss-instruct-sc2-concepts
import torch def blur_with_zeros(image, blur): """Blur an image ignoring zeros. """ # Create binary weight image with 1s where valid data exists. mask = torch.ones(image.shape, device=image.device) mask[image <= 0] = 0 # Compute blurred image that ignores zeros using ratio of blurred images. ...
bigcode/self-oss-instruct-sc2-concepts
import re def cleanhtml(raw_html): """ This function is for creating filenames from the HTML returned from the API call. It takes in a string containing HTML tags as an argument, and returns a string without HTML tags or any characters that can't be used in a filename. """ # Created a regular...
bigcode/self-oss-instruct-sc2-concepts
def endfSENDLineNumber( ) : """Indicates the end of an ENDF data section for one (MF, MT) pair.""" return( 99999 )
bigcode/self-oss-instruct-sc2-concepts
def partition_at_level(dendrogram, level) : """Return the partition of the nodes at the given level A dendrogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendrogram) - 1. The higher the level...
bigcode/self-oss-instruct-sc2-concepts
def _extract_data(spark, input_fname, app_config): """ Read the input data in the form of csv file. :param spark : Active spark session :param input_fname : Input filename as in the storage directory :param app_config : loaded json object with app configuration :returns : spark dataframe of inp...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_details_page_notes(details_page_notes): """ Clean up a details page notes section. The purpose of this function is to attempt to extract the sentences about the crash with some level of fidelity, but does not always return a perfectly parsed sentence as the HTML syntax varies ...
bigcode/self-oss-instruct-sc2-concepts
def get_prob_current(psi, psi_diff): """ Calculates the probability current Im{psi d/dx psi^*}. """ print("Calculating probability current") curr = psi*psi_diff return -curr.imag
bigcode/self-oss-instruct-sc2-concepts
def get_urls(info): """Return list of SLC URLs with preference for S3 URLs.""" urls = list() for id in info: h = info[id] fields = h['_source'] prod_url = fields['urls'][0] if len(fields['urls']) > 1: for u in fields['urls']: if u.startswith('s3:/...
bigcode/self-oss-instruct-sc2-concepts
def get_provider(ns, type, backend): """ Returns SSSD provider for given backend. :type type: string :param type: Type of the provider (= value of its LMI_SSSDProvider.Type property). :type backend: LMIInstance of LMI_SSSDBackend :param backed: SSSD backend to inspect. :rtype: strin...
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def is_mapping(obj): """Check if object is mapping.""" return isinstance(obj, Mapping)
bigcode/self-oss-instruct-sc2-concepts
import torch def full_pose_3d(pose): """Expand (B, 12) pose to (B, 4, 4) transformation matrix.""" shape = list(pose.shape[:-1]) shape += [3, 4] pose = torch.reshape(pose, shape) zeros = torch.zeros_like(pose[..., :1, 0]) last = torch.stack([zeros, zeros, zeros, zeros + 1], -1) full_pose = torch.ca...
bigcode/self-oss-instruct-sc2-concepts
import six def unpack_dd(buf, offset=0): """ unpack up to 32-bits using the IDA-specific data packing format. Args: buf (bytes): the region to parse. offset (int): the offset into the region from which to unpack. default: 0. Returns: (int, int): the parsed dword, and the number of ...
bigcode/self-oss-instruct-sc2-concepts
import shlex def shell_split(st): """ Split a string correctly according to the quotes around the elements. :param str st: The string to split. :return: A list of the different of the string. :rtype: :py:class:`list` >>> shell_split('"sdf 1" "toto 2"') ['sdf 1', 'toto 2'] """ ...
bigcode/self-oss-instruct-sc2-concepts
def to_millis(secs, nanos): """Combine seconds and nanoseconds and convert them to milliseconds.""" return 1000 * secs + nanos / 1000000
bigcode/self-oss-instruct-sc2-concepts
def split_by_label(data, targets, labels): """ Given a data matrix and the targets for the data, the method splits the data by class :return: a dict with the data separeted by label, each label is a key of the dict """ d = dict() for cl in labels: d[cl] = data[targets == cl] return d
bigcode/self-oss-instruct-sc2-concepts
def expected_count(af, effective_mutation_rate): """Calculate the expected number of somatic variants greater than a given allele frequency given an effective mutation rate, according to the model of Williams et al. Nature Genetics 2016""" return effective_mutation_rate * (1.0 / af - 1.0)
bigcode/self-oss-instruct-sc2-concepts
def add_to_existing_groups(no_people, existing_groups, max_size): """ Attempts to add the given number of people to the list of existing groups without exceeding the maximum group size. Modifies the list of existing groups. Returns the number of people remaining after the attempt. ...
bigcode/self-oss-instruct-sc2-concepts
def stci(ds): """Calculate the Subtropical Cell Index (STCI) according to Duteil et al. 2014 Parameters ---------- ds : xr.Dataset Input dataset. Needs to have a variable `psi` which represents the meridional mass overturning streamfunction Returns ------- xr.Dataset The ST...
bigcode/self-oss-instruct-sc2-concepts
def applyOrderList(order, aList): """ Apply order to aList. An order of the form [2,0,1] means that the first element should be the 3rd element of aList, and so on. """ if order==[]: return aList else: return map(lambda v:aList[v], order)
bigcode/self-oss-instruct-sc2-concepts
def rec_repr(record): """Return the string representation of the consumer record. :param record: Record fetched from the Kafka topic. :type record: kafka.consumer.fetcher.ConsumerRecord :return: String representation of the consumer record. :rtype: str | unicode """ return 'Record(topic={},...
bigcode/self-oss-instruct-sc2-concepts
def standard_rb(x, baseline, amplitude, decay): """ Fitting function for randomized benchmarking. :param numpy.ndarray x: Independent variable :param float baseline: Offset value :param float amplitude: Amplitude of exponential decay :param float decay: Decay parameter :return: Fit function...
bigcode/self-oss-instruct-sc2-concepts
import math def num_buses(n): """ (int) -> int Precondition: n >= 0 Return the minimum number of buses required to transport n people. Each bus can hold 50 people. >>> num_buses(75) 2 >>> num_buses(100) 2 >>> num_buses(101) 3 >>> num_buses(1) 1 >>> num_buses(0) ...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def list_images(directory): """Generates a list of all .tif and/or .tiff files in a directory. Parameters ---------- directory : str The directory in which the function will recursively search for .tif and .tiff files. Returns ------- list A list of pathlib...
bigcode/self-oss-instruct-sc2-concepts
def d2dms(d, delimiter=':', precision=6): """ Convert decimal degrees to dd:mm:ss """ inverse = '' if d < 0: inverse = '-' minutes, seconds = divmod(abs(d) * 3600, 60) degrees, minutes = divmod(minutes, 60) return '{0:s}{1:.0f}{4}{2:02.0f}{4}{3:0{5:d}.{6:d}f}'\ .format(i...
bigcode/self-oss-instruct-sc2-concepts
def lookup(collection, key): """ Lookup a key in a dictionary or list. Returns None if dictionary is None or key is not found. Arguments: dictionary (dict|list) key (str|int) Returns: object """ if collection: try: return collection[key] except ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def _find_mark(instrumented_config: dict, path: str) -> Optional[dict]: """ Find mark in instrumented config by path :param instrumented_config: { field1: 'a', field2: 'b', '__line__': 0, '__field1__': { 'start': {'line': 1, 'column': 1}, 'end': {...} }} :param ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any from typing import Dict def transformUserIDs(userID: str, args: List[Any]) -> str: """Transform user IDs.""" userIDMap: Dict[str, str] = args[0] return userIDMap[userID]
bigcode/self-oss-instruct-sc2-concepts
def abbrev_timestr(s): """Chop milliseconds off of a time string, if present.""" arr = s.split("s") if len(arr) < 3: return "0s" return arr[0]+"s"
bigcode/self-oss-instruct-sc2-concepts
import json def read_template(template): """ Read and return template file as JSON Parameters ------------ template: string template name returns: dictionary JSON parsed as dictionary """ data = None with open(template) as data_file: data = json.load(data...
bigcode/self-oss-instruct-sc2-concepts
def _check_empty_script(filename, message, expect_fail): """Returns a script check that checks for empty diagnostics in a file. Args: filename: name of file containing diagnostic output. message: message to print when there are unexpected findings. message may be multiline. expect_fai...
bigcode/self-oss-instruct-sc2-concepts
def project(position_current, velocity_current, acceleration_current, use_acceleration, delta_t): """ This module estimates the projected position of a particle. :param position_current: The position of the particle at time "t". It must be a numpy array. :param velocity_current: The velocity of the par...
bigcode/self-oss-instruct-sc2-concepts
def calc_salary(s_from, s_to): """Calc salary. First modify salary to get 'from', 'to' :param s_from: int, salary from :param s_to: int, salary to :return: int or None, size of salary by 'from' and 'to' """ if (s_from is not None and s_to is not None): return (s_from + s_to) / 2 ...
bigcode/self-oss-instruct-sc2-concepts
def upsert_record(client, zoneid, record_name, value, record_type='A', ttl=300): """Updates or Creates the specified AWS Route 53 domain resource record Parameters ---------- client: boto3.client The boto3 'route53' client to utilize for the update request zoneid: str The Route 53 H...
bigcode/self-oss-instruct-sc2-concepts
def check_for_age_range(child_age, age_range): """ check if input child age is in the query's age range :param child_age: the age to check (int) :param age_range: the age range (list) :return: True if the age is in the range, else False """ return True if min(age_range) <= child_age <= max(a...
bigcode/self-oss-instruct-sc2-concepts
def get_padded_filename(num_pad, idx): """ Get the filename padded with 0. """ file_len = len("%d" % (idx)) filename = "0" * (num_pad - file_len) + "%d" % (idx) return filename
bigcode/self-oss-instruct-sc2-concepts
def decSinglVal(v): """Return first item in list v.""" return v[0]
bigcode/self-oss-instruct-sc2-concepts
import re def get_variable(config_text, variable): """ Get the value of a variable in config text :param config_text: str :param variable: str :return: value """ pat = re.compile(variable) for line in config_text.splitlines(): altered_line = line if pat.match(line): ...
bigcode/self-oss-instruct-sc2-concepts
def dummy_dataset_paths_no_valid(tmpdir_factory): """Creates and returns the path to a temporary dataset folder, and train, and test files. """ # create a dummy dataset folder dummy_dir = tmpdir_factory.mktemp('dummy_dataset') # create train, valid and train partitions in this folder train_file ...
bigcode/self-oss-instruct-sc2-concepts
def _vector_neg(x): """Take the negation of a vector over Z_2, i.e. swap 1 and 0.""" return [1-a for a in x]
bigcode/self-oss-instruct-sc2-concepts
def get_children(self): """ Creates a ``QuerySet`` containing the immediate children of this model instance, in tree order. The benefit of using this method over the reverse relation provided by the ORM to the instance's children is that a database query can be avoided in the case where the ins...
bigcode/self-oss-instruct-sc2-concepts
def _grad_j(q_j, A_j, b_j, b_j_norm, a_1_j, a_2_j, m): """Compute the gradient with respect to one of the coefficients.""" return (A_j.t() @ q_j / (-m)) + (b_j * (a_1_j / b_j_norm + a_2_j))
bigcode/self-oss-instruct-sc2-concepts
def perimeter_square(length): """ .. math:: perimeter = 4 * length Parameters ---------- length: float length of one side of a square Returns ------- perimeter: float perimeter of the square """ return length * 4
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def game_of_life_rule(cell: bool, neighbors: int) -> Union[bool, None]: """Classic rule of John Conway's Game of Life.\n Common notation: `B3/S23`. """ # A low cell switches to high state if is has 3 neighbors if not cell and neighbors == 3: return True # A hig...
bigcode/self-oss-instruct-sc2-concepts
import csv def write_dataset(dataset, dataset_file: str) -> bool: """ Writes a dataset to a csv file. Args: dataset: the data in list[dict] format dataset_file: str, the path to the csv file Returns: bool: True if succeeds. """ assert len(dataset) > 0, "The anonymized dat...
bigcode/self-oss-instruct-sc2-concepts
import random def modify_rate(rate, change): """ Calculate a random value within change of the given rate Args: rate: the initial rate to change from change: the maximum amount to add or subtract from the rate Returns: random value within change of the given rate Explanati...
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def _preprocess_text(inputs, lower=False, remove_space=True, keep_accents=False): """Remove space, convert to lower case, keep accents. Parameters ---------- inputs: str input string lower: bool If convert the input string to lower case. remove_space: bool ...
bigcode/self-oss-instruct-sc2-concepts
def make_ordinal(n): """ Convert an integer into its ordinal representation:: make_ordinal(0) => '0th' make_ordinal(3) => '3rd' make_ordinal(122) => '122nd' make_ordinal(213) => '213th' """ n = int(n) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)] if...
bigcode/self-oss-instruct-sc2-concepts
def generate_data(function, xdata, func_params): """Create a data set using a given function and independent variable(s). Parameters ---------- function : callable A function to use to generate data points from input values. xdata : array_like An array of values of shape (N, M) wher...
bigcode/self-oss-instruct-sc2-concepts
def to_camel_case(input_string): """ Based on https://stackoverflow.com/a/19053800 Args: input_string (str): Returns: (str): """ if "-" in input_string: components = input_string.split('-') elif "_" in input_string: components = input_string.split('_') e...
bigcode/self-oss-instruct-sc2-concepts
def compare_graphs(before, after): """ Compare two (sub)graphs. Note: a == b != b == a! :param before: A networkx (sub)graph. :param after: A networkx (sub)graph. :returns: A dict with changes. """ res = {'added': [], 'removed': [], 'added_edge': [], 'r...
bigcode/self-oss-instruct-sc2-concepts
import re from typing import Counter def extract(text_list, regex, key_name, extracted=None, **kwargs): """Return a summary dictionary about arbitrary matches in ``text_list``. This function is used by other specialized functions to extract certain elements (hashtags, mentions, emojis, etc.). It can ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_sha512(*indata): """Create SHA512 hash for input arguments.""" hasher = hashlib.sha512() for data in indata: if isinstance(data, str): hasher.update(data.encode('utf-8')) elif isinstance(data, bytes): hasher.update(data) else: ...
bigcode/self-oss-instruct-sc2-concepts
import typing def read_exact(stream: typing.BinaryIO, byte_count: int) -> bytes: """Read byte_count bytes from the stream and raise an exception if too few bytes are read (i. e. if EOF was hit prematurely). :param stream: The stream to read from. :param byte_count: The number of bytes to read. :return: The read...
bigcode/self-oss-instruct-sc2-concepts
def CEN_misclassification_calc( table, TOP, P, i, j, subject_class, modified=False): """ Calculate misclassification probability of classifying. :param table: input matrix :type table : dict :param TOP: test outcome positive :type TOP : in...
bigcode/self-oss-instruct-sc2-concepts
def _transpose(mat): """ Transpose matrice made of lists INPUTS ------ mat: iterable 2d list like OUTPUTS ------- r: list of list, 2d list like transposed matrice """ r = [ [x[i] for x in mat] for i in range(len(mat[0])) ] return r
bigcode/self-oss-instruct-sc2-concepts
def getFileData(fileName): """ Open a file, and read the contents. The with..open operation will auto-close the file as well. """ with open(fileName) as handle: data = handle.read() return data
bigcode/self-oss-instruct-sc2-concepts
def scale_to(x, from_max, to_min, to_max): """Scale a value from range [0, from_max] to range [to_min, to_max].""" return x / from_max * (to_max - to_min) + to_min
bigcode/self-oss-instruct-sc2-concepts
def int_to_bits_indexes(n): """Return the list of bits indexes set to 1. :param n: the int to convert :type n: int :return: a list of the indexes of bites sets to 1 :rtype: list """ L = [] i = 0 while n: if n % 2: L.append(i) n //= 2 i += 1 ...
bigcode/self-oss-instruct-sc2-concepts
def getDistances(digraph, path): """Returns total & outdoor distances for given path.""" total_dist = 0 outdoor_dist = 0 for i in range(len(path) - 1): for node, edge in digraph.edges[path[i]]: if node == path[i + 1]: total_dist += edge.getTotalDistance() ...
bigcode/self-oss-instruct-sc2-concepts
def header_format(morsels): """Convert list of morsels to a header string.""" return '; '.join(f'{m["name"]}={m["value"]}' for m in morsels)
bigcode/self-oss-instruct-sc2-concepts
def app_name_from_ini_parser(ini_parser): """ Returns the name of the main application from the given ini file parser. The name is found as follows: * If the ini file contains only one app:<app name> section, return this app name; * Else, if the ini file contains a pipeline:main section, us...
bigcode/self-oss-instruct-sc2-concepts
def smoothbknpo_n(x, p): """ Generalised smooth broken power law. Note: for p[4] == 2 the function is the same as 'smoothbknpo' Args: x: (non-zero) frequencies. p[0]: Normalization. p[1]: power law index for f--> 0. p[2]: power law index for f--> oo. ...
bigcode/self-oss-instruct-sc2-concepts
def rep0(s): """REGEX: build repeat 0 or more.""" return s + '*'
bigcode/self-oss-instruct-sc2-concepts
def get_axes(self): """Return axes list. Parameters ---------- self: DataND a DataND object Returns ------- axes_list """ return self.axes
bigcode/self-oss-instruct-sc2-concepts