seed
stringlengths
1
14k
source
stringclasses
2 values
def decremental_mean(mu_i, n, x): """ Calculates the mean after removing x from a vector with given mean and size. :param mu_i: Mean before removing x. :param n: Number of elements before removing x. :param x: Element to be removed. :return: New mean. """ delta = (mu_i - x) / float(n -...
bigcode/self-oss-instruct-sc2-concepts
def format_decimal_as_string(value): """ Convert a decimal.Decimal to a fixed point string. Code borrowed from Python's moneyfmt recipe. https://docs.python.org/2/library/decimal.html#recipes """ sign, digits, exp = value.as_tuple() if exp > 0: # Handle Decimals like '2.82E+3' ...
bigcode/self-oss-instruct-sc2-concepts
def _make_exact(h): """Make sure h is an exact representable number This is important when calculating numerical derivatives and is accomplished by adding 1 and then subtracting 1.. """ return (h + 1.0) - 1.0
bigcode/self-oss-instruct-sc2-concepts
def subword_tokenizer(text, dictionary): """ The MaxMatch algorithm, also known as the greedy longest-match-first algorithm, matches a token with the appropriate sub-word tokens. It's used in BERT's wordpiece tokenizer. It takes in a string, and a dictionary of sub-words Reference: https://githu...
bigcode/self-oss-instruct-sc2-concepts
def isfloat(value: str) -> bool: """ Check if the given string is a float. :param value: String to check :return: True if float """ try: float(value) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def insert(tup, loc, val): """ >>> insert(('a', 'b', 'c'), 0, 'x') ('x', 'b', 'c') """ L = list(tup) L[loc] = val return tuple(L)
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(jsonfile): """ Opens and loads a .json file. """ with open(jsonfile) as f: j = json.load(f) return j
bigcode/self-oss-instruct-sc2-concepts
def dict_get(d, key, default=None): """Return non-None value for key from dict. Use default if necessary.""" val = d.get(key, default) return default if val is None else val
bigcode/self-oss-instruct-sc2-concepts
def _convert_bytes_to_megabytes(b): """Converts bytes to megabytes""" return b / 1000 ** 2
bigcode/self-oss-instruct-sc2-concepts
def round_key(matrix, key_block): """ This function is used for both AES encryption and AES decryption. The function will divide the matrix into four 4 bytes blocks (each column as a block), and perform XOR operation between block and key which contained in the key_block. At last, create and return the...
bigcode/self-oss-instruct-sc2-concepts
def _get_layer_from_layermap(layermap, layerid): """ Get corresponding layer name and purpose from layermap Parameters ---------- layermap : dict() layermap dictionary layerid : [int, int] layermap id Returns ------- [str, str] layer name and purpose """ ...
bigcode/self-oss-instruct-sc2-concepts
def linear(a, x): """ Simple linear fit function. :param a: Coefficients array of length 2 :param x: free parameter :return: float """ return a[0] + a[1] * x
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any import yaml def read_config(path: str) -> Dict[str, Any]: """ Reads the config dictionary from the yaml file. Args: path (str): Path to the .yaml file. Returns: Dict[str, Any]: Configuration. """ with open(path, 'r', encoding='...
bigcode/self-oss-instruct-sc2-concepts
def remove_out_of_range(df, range_list): """Set any values out of range to NAN. Args: - df: a wide format df (e.g. the result of data_loader) - range_list: a list of dictionaries. Each dictionary has three keys 'variable', 'high' and 'low'. e.g. {'variable': 'aao2', 'hig...
bigcode/self-oss-instruct-sc2-concepts
import re def humanize_placeholders(msgid): """Convert placeholders to the (google translate) service friendly form. %(name)s -> __name__ %s -> __item__ %d -> __number__ """ return re.sub( r'%(?:\((\w+)\))?([sd])', lambda match: r'__{0}__'.format( match...
bigcode/self-oss-instruct-sc2-concepts
def format_data(shapelet, offset=0.0): """ Prints a shapelet in a formatted way so that it can be visualized with other tools afterwards. The formatted shapelet is returned as a string by this function. """ data = "" for x,y in enumerate(shapelet): data += "{}\t{}\n".format(x+offset,y) data += "\n...
bigcode/self-oss-instruct-sc2-concepts
def serialized_time(time): """ Return a serialized version of a datetime instance in the format of a ``DateTimeField`` from Django Rest Framework. Logic taken from: https://github.com/encode/django-rest-framework/blob/6ea7d05979695cfb9db6ec3946d031b02a82952c/rest_framework/fields.py#L1217-L1221 ...
bigcode/self-oss-instruct-sc2-concepts
def _get_nn_layers(spec): """ Returns a list of neural network layers if the model contains any. Parameters ---------- spec: Model_pb A model protobuf specification. Returns ------- [NN layer] list of all layers (including layers from elements of a pipeline """ ...
bigcode/self-oss-instruct-sc2-concepts
import re def _get_indent(t): """Returns the indentation in the first line of t""" search = re.search(r"^(\s*)\S", t) return "" if search is None else search.groups()[0]
bigcode/self-oss-instruct-sc2-concepts
def get_value(key, attrs): """ Find the key and return it's value """ for attr in attrs: if attr[0] == key: return attr[1]
bigcode/self-oss-instruct-sc2-concepts
def should_suspend(partial_result) -> bool: """Check the state of the result to determine if the orchestration should suspend.""" return bool(partial_result is not None and hasattr(partial_result, "is_completed") and not partial_result.is_completed)
bigcode/self-oss-instruct-sc2-concepts
import re def find_attribute_idx(newline_split_docs): """Finds the possible split between the header and Attribute annotations Args: newline_split_docs: new line split text Returns: idx: -1 if none or the idx of Attributes """ for idx, val in enumerate(newline_split_docs): ...
bigcode/self-oss-instruct-sc2-concepts
def parse_s3_uri(s3_uri): """ Given a URI of the form s3://<bucket>/<key> parse into bucket, key tuple For a trivial parse this is faster than using urlparse(s3_uri) """ return s3_uri.replace("s3://", "").split("/", 1)
bigcode/self-oss-instruct-sc2-concepts
def norm(value_string): """ Normalize the string value in an RTE pair's ``value`` or ``entailment`` attribute as an integer (1, 0). :param value_string: the label used to classify a text/hypothesis pair :type value_string: str :rtype: int """ valdict = {"TRUE": 1, ...
bigcode/self-oss-instruct-sc2-concepts
def linear_search(lst: list, value: object) -> int: """ Return the index <i> of the first occurance of <value> in the list <lst>, else return -1. >>> linear_search([1, 2, 3, 4], 3) 2 >>> linear_search([1, 2, 3, 4], 5) -1 >>> linear_search([1, 2, 3, 4], 4) 3 >>> linear_search([1,...
bigcode/self-oss-instruct-sc2-concepts
import tempfile import csv def write_named_temp_csv(rows): """ Write the provided rows to a named temporary file. :param rows: List of lists to be written. :return: A named temporary file containing the rows. """ ntf = tempfile.NamedTemporaryFile(suffix=".csv") with open(ntf.name, "w") as...
bigcode/self-oss-instruct-sc2-concepts
def append_lags(df, base_col, offsets, group_col='player_id'): """ Calculate "lag" of base_col (raw of previous nth row) :param df: Input DataFrame :param base_col: Name of column to "lag" :param offsets: List of integer offsets (number of rows to lag) :param group_col: Column to group on prior...
bigcode/self-oss-instruct-sc2-concepts
async def infer_type_dot(engine, a, b): """Infer the return type of dot.""" t = await engine.assert_same('type', a, b) return t
bigcode/self-oss-instruct-sc2-concepts
def image_directive(image, width=None, align=None, alt=None): """Generate an RST Image directive.""" if width is None: width = '300' if align is None: align = 'center' if alt is None: alt = image return (".. image:: %s\n :width: %s\n :align: %s\n" " :alt:...
bigcode/self-oss-instruct-sc2-concepts
import torch def rot_from_yaw(yaw): """ Get rotation matrix from yaw Args: yaw: float value representing yaw Returns: 3x3 rotation matrix """ if not isinstance(yaw, torch.Tensor): yaw = torch.Tensor([yaw]) cos = torch.cos(yaw) sin = torch.sin(yaw) z = yaw.new_tens...
bigcode/self-oss-instruct-sc2-concepts
def rcumode2band(rcumode): """ Map rcumode to band string as used in beamctl arguments Parameters ---------- rcumode: int or str The RCU mode. Returns ------- band: str The band name. """ rcumode = str(rcumode) if rcumode == "3": band = "10_90" el...
bigcode/self-oss-instruct-sc2-concepts
import copy def injected_cube_position(example_dataset_ifs_crop): """ Inject a fake companion into an example cube. Parameters ---------- example_dataset_ifs_crop : fixture Taken automatically from ``conftest.py``. Returns ------- dsi : VIP Dataset injected_position_yx : ...
bigcode/self-oss-instruct-sc2-concepts
import re def islatitude(value): """ Return whether or not given value is valid latitude. If the value is valid latitude, this function returns ``True``, otherwise ``False``. Examples:: >>> islatitude('-90.000') True >>> islatitude('+99.9') False :param value: s...
bigcode/self-oss-instruct-sc2-concepts
def check_valid(number, input_base=10): """ Checks if there is an invalid digit in the input number. Args: number: An number in the following form: (int, int, int, ... , '.' , int, int, int) (iterable container) containing positive integers of the input base input_ba...
bigcode/self-oss-instruct-sc2-concepts
def d_timeToString(dateString): """ input: string output: string description: format dateString to yyyymmddHHMM example: 2018-08-26 14:18:40 ->> 201808261418 """ return dateString.replace("-", "").replace(" ", "").replace(":", "...
bigcode/self-oss-instruct-sc2-concepts
def stetson_source_chunk(image, ix, iy, nhalf): """Extract a source image chunk.""" return image[iy-nhalf:iy+nhalf+1, ix-nhalf:ix+nhalf+1]
bigcode/self-oss-instruct-sc2-concepts
import re def convert_camel_case(operation): """ Converts ``CamelCaseOperationName`` into ``python_style_method_name``. """ return re.sub('([a-z])([A-Z])', r'\1_\2', operation).lower()
bigcode/self-oss-instruct-sc2-concepts
def extract_record_info(instances, info_needed_tuple): """ From a list of sqlalchemy class objects (records from a single table), get the instance attributes specified in the info needed tuple. :param instances: an iterable containing class instances (inst iter) :param info_needed_tuple: tuple cont...
bigcode/self-oss-instruct-sc2-concepts
def maybe_to_list(maybe_tensor): """Tries to convert an object that may be a tensor to a list. """ try: return maybe_tensor.tolist() except AttributeError: return maybe_tensor
bigcode/self-oss-instruct-sc2-concepts
import math def getZPoisson(s, b, stat, syst): """ The significance for optimisation. s: total number of signal events b: total number of background events stat: relative MC stat uncertainty for the total bkg. syst: relative syst uncertainty on background Note that the function already a...
bigcode/self-oss-instruct-sc2-concepts
def _GetEnvAsDict(arch): """Gets the saved environment from a file for a given architecture.""" # The environment is saved as an "environment block" (see CreateProcess() # for details, which is the format required for ninja). We convert to a dict # here. Drop last 2 NULs, one for list terminator, one for traili...
bigcode/self-oss-instruct-sc2-concepts
def format_configuration(name, value, nearest, path, item_type): """Helper function for formating configuration output :param str name: name of the section being set, eg. paging or log :param str value: new value of the section :param str nearest: value of the nearest set section :param str path: pa...
bigcode/self-oss-instruct-sc2-concepts
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multi...
bigcode/self-oss-instruct-sc2-concepts
import torch def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False): """Calculate overlap between two set of bboxes. If ``is_aligned`` is ``False``, then calculate the ious between each bbox of bboxes1 and bboxes2, otherwise the ious between each aligned pair of bboxes1 and bboxes2. A...
bigcode/self-oss-instruct-sc2-concepts
def still_a_dependency(dependency): """ Defines the criteria for which a dependency is deemed complete (and therefore no longer a dependency). Args: dependency, Table.Row or dict. Processing row corresponding to the required input for the job in prow. This must...
bigcode/self-oss-instruct-sc2-concepts
import random def estimate_occ_per_ap(prob_dist=[0.405, 0.345, 0.125, 0.092, 0.033]): """ Randomly generates a number of occupants between 1 and 5 Parameters ---------- prob_dist : list (of floats), optional Defines probability distribution of occupants per apartment Default: [0.4...
bigcode/self-oss-instruct-sc2-concepts
import torch def edge_clamp(B_cp, edge_idx, clamp_val=0, device='cpu', dtype=torch.float32): """ Clamp edges of each component of Bcp to clamp_val. RH 2020 Args: B_cp (list of torch.Tensor): Beta Kruskal tensor. List of tensors of shape (n_feature...
bigcode/self-oss-instruct-sc2-concepts
def return_string(input_string, replace=[], replace_with=[]): """ Return a stripped string with optional character replacements. Parameters ---------- input_string : string arbitrary string replace : list of strings strings to substitute replace_with : list of strings ...
bigcode/self-oss-instruct-sc2-concepts
import yaml def _read_config(filename): # pragma: no cover """Read YAML configuration file.""" with open(filename, "r") as reader: return yaml.safe_load(reader)
bigcode/self-oss-instruct-sc2-concepts
def mutation_type(alleles): """ Is this mutation a transition (A <-> G and C <-> T) or a transversion (everything else). """ return 'ts' if set(alleles) == {'A', 'G'} or set(alleles) == {'C', 'T'} else 'tv'
bigcode/self-oss-instruct-sc2-concepts
import io def get_parameters(file_desc: io.BufferedReader, start_index: int, end_index: int): """ Get part of file :param file_desc: file descriptor :param start_index: Index of the start reading :param end_index: Index of the end reading :return: part of the file """ file_desc.seek(s...
bigcode/self-oss-instruct-sc2-concepts
def has_common(l1, l2): """Returns truthy value if there are common elements in lists l1 and l2""" return set(l1) & set(l2)
bigcode/self-oss-instruct-sc2-concepts
def dict_merge(*dicts): """Merge dictionaries into a single dictionary. """ merged = {} for dict in dicts: merged.update(dict) return merged
bigcode/self-oss-instruct-sc2-concepts
def verMod11(cprNumbStr): """Perform modulus 11 check for validity of CPR-number. Input: cprNumbStr, str[10], holds a full CPR number Output: True/False, logical, returns failure or succes of check """ if len(cprNumbStr) != 10: raise ValueError("CPR-number to be va...
bigcode/self-oss-instruct-sc2-concepts
def findMean(num): """Find the mean of a list of numbers""" length = len(num) sumList = sum(num) return f"Mean value of {num} is {round((sumList / length) ,2)}"
bigcode/self-oss-instruct-sc2-concepts
def add(arg1,arg2): """ Add two values arg1 and arg2 """ return arg1+arg2
bigcode/self-oss-instruct-sc2-concepts
def _common_neighbors(G, u, v): """Get the set of common neighbors between two nodes.""" return set(G[u]) & set(G[v])
bigcode/self-oss-instruct-sc2-concepts
def get_Rgap_mec(self): """Returns the radius of the center of the mecanical airgap Parameters ---------- self : Machine Machine object Returns ------- Rgap_mec: float Radius of the center of the mecanical airgap [m] """ stator = self.stator rotor = self.rotor ...
bigcode/self-oss-instruct-sc2-concepts
def hex_str(an_int): """Convert an int to an hexadecimal string.""" return '{:#x}'.format(an_int)
bigcode/self-oss-instruct-sc2-concepts
def isDict(val): """Returns true if the passed value is a python dictionary type, otherwise false. **Parameters:** * val - value to test **Returns:** True if the passed value is a dictionary, otherwise false.""" return isinstance(val, dict)
bigcode/self-oss-instruct-sc2-concepts
def sanitize_df(df): """Drops empty rows and columns from the DataFrame and returns it""" # Delete empty rows for i in df.index.tolist()[-1::-1]: if df.iloc[i].isna().all(): df.drop(i, inplace=True) else: break # Delete empty columns cols = [] for column i...
bigcode/self-oss-instruct-sc2-concepts
def anchor(title): """Return an anchor '#a-title' for a title 'A title'""" return '#' + title.replace(' ', '-')
bigcode/self-oss-instruct-sc2-concepts
import base64 def base64_encode(value): """Encode the value in base64""" return base64.b64encode(value)
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Any from typing import Optional from typing import Iterator from typing import Tuple import itertools def enumerate_cycle( iterable: Iterable[Any], *, times: Optional[int] = None, ) -> Iterator[Tuple[int, Any]]: """Return iterator of tuples in...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def filter_values(d: dict, predicate: Callable) -> dict: """ Returns new subset dict of d where values pass predicate fn >>> d = {'Homer': 39, 'Marge': 36, 'Bart': 10} >>> filter_values(d, lambda x: x < 20) {'Bart': 10} """ return {k: v for k, v in d.items() if...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_content(*fps): """Return content for specified file path parts. If the file doesn't exist, return ''. Arguments: fps (List(str)): One or more path parts to be joined with current directory Returns: str: Content of the specified file, othe...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def center_coord(image_size: int, subimage_size: int) -> Tuple[int, int]: """Center a subimage in image along some axis, given image and subimage sizes.""" x0 = (image_size - subimage_size) // 2 x1 = x0 + subimage_size return x0, x1
bigcode/self-oss-instruct-sc2-concepts
import torch def bbox_iou(box1, box2): """ Returns the IoU of bounding boxes of tensor box1 vs tensor box2 IoU equals (area of rectangular overlap of the boxes / total area of both boxes combined) Params: box1: comparison box 1 - tensor box2: comparison box 2 - tensor Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import time def get_windows_timestamp_now() -> int: """ Windows Timestamp in hundreds of ns since 01.01.1601 – 00:00:00 UTC >>> assert get_windows_timestamp_now() > 10000 >>> save_time = get_windows_timestamp_now() >>> time.sleep(0.1) >>> assert get_windows_timestamp_now() > save_time ""...
bigcode/self-oss-instruct-sc2-concepts
def compose(d1, d2): """Compose two homomorphisms given by dicts.""" res = dict() for key, value in d1.items(): if value in d2.keys(): res[key] = d2[value] return res
bigcode/self-oss-instruct-sc2-concepts
def predict_sex(x_coverage, y_coverage): """Make a simple yet accurate prediction of a samples sex. The calculation is based on the average coverage across the X and Y chromosomes. Note that an extrapolation from a subsection of bases is usually quite sufficient. Args: x_coverage (float): ...
bigcode/self-oss-instruct-sc2-concepts
def multiply(x,y): """Return the result of x multiplied by y""" return x*y
bigcode/self-oss-instruct-sc2-concepts
import ssl import smtplib def configure_smtp(settings_dict): """ Configures the SMTP gateway. Args: settings_dict (dict) Returns: smtplib.SMTP: The SMTP connection. Raises: Exception: If anything goes wrong. """ # Create a SSL context ...
bigcode/self-oss-instruct-sc2-concepts
def z_score(x, df): """Calculate a z score for each x value, using estimates from a pandas data frame with the columns 'mu' and 'sd' and index coressponding to the x values""" z = (x.transpose() - df['mu'])/df['sd'] return z.transpose()
bigcode/self-oss-instruct-sc2-concepts
def convert_from_bytes(bytes): """Convert bytes to higher orders Args: bytes (int): size in bytes Returns: str: size in higher order """ for unit in ["bytes", "KB", "MB", "GB", "TB"]: if bytes < 1000: return f"{bytes:.2f} {unit}" bytes /= 1000
bigcode/self-oss-instruct-sc2-concepts
def quote_nonascii(s): """Like urllib.parse.quote, but explicitly only escaping non-ascii characters.""" return "".join(chr(c) if c <= 127 else "%%%02X" % c for c in s.encode('utf8'))
bigcode/self-oss-instruct-sc2-concepts
import torch def flip(flip, data = None, target = None, probs = None): """ Args: flip: boolean whether to apply flip augmentation data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH Returns: data, target...
bigcode/self-oss-instruct-sc2-concepts
import time def timeit(f, log=True): """ Times the execution of the function ``f`` Returns: *: result of applying ``f`` to ``args`` and ``kw`` float: time needed to execute ``f`` Usage ----- Either use it as .. code-block:: python @timeit def new_fn(): ...
bigcode/self-oss-instruct-sc2-concepts
import socket def is_port_open(port): """ Checks if the port is open on localhost by creating a socket connection to it. :param port: The port as a number :return: True if open, false otherwise """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: return sock.connect_ex((...
bigcode/self-oss-instruct-sc2-concepts
import csv def read_file(filename): """Read csv file with rows: x, y""" px = [] py = [] with open(filename) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: px.append(float(row[0])) py.append(float(row[1])) return px, py
bigcode/self-oss-instruct-sc2-concepts
import struct def structparse_ip_header_embedded_protocol(bytes_string: bytes): """Takes a given bytes string of a packet and returns information found in the IP header about the embedded protocol at the next level of encapsulation. Examples: >>> from scapy.all import *\n >>> icmp_pcap = rdpc...
bigcode/self-oss-instruct-sc2-concepts
def linear_normal(g, input, weight, bias): """Symbolic function for `linear`. PyTorch `nn.Linear` will be exported as ONNX node 'Gemm'. """ return g.op( 'Gemm', input, weight, bias, alpha_f=1.0, beta_f=1.0, transA_i=0, transB_i=1)
bigcode/self-oss-instruct-sc2-concepts
def grid_dist(cell1, cell2): """Euclidian distance between two points In particular, 1 for adjacent cells and √2 for diagonally touching square cells """ return ((cell1[0] - cell2[0]) ** 2 + (cell1[1] - cell2[1]) ** 2) ** 0.5
bigcode/self-oss-instruct-sc2-concepts
import math def percentile(data, pc): """Naive algorithm to compute the pc'th percentile of a list of (sorted) data. Linear interpolation is used when the percentile lies between two data points. It is assumed that the data contains no NaN or similar. """ if pc < 0 or pc > 100: raise Value...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import re def keys_and_input_text(obj: dict) -> Optional[bool]: """Filter input text and IDs on left side of page :param obj: pdf character :return: Whether to keep the filtered character """ if "fontname" in obj.keys(): if obj["x0"] < 50: matches ...
bigcode/self-oss-instruct-sc2-concepts
def get_N1(nvols, TR, HP): """ Get the low frequency point Parameters ---------- TR : float Temporal Resolution nvols : int Number of volumes HP : float HighPass Low Cutoff Frequency Returns ------- n1 : float Low Frequency Point """ ...
bigcode/self-oss-instruct-sc2-concepts
import uuid def generate_secret_key() -> str: """ Generate secret key. Returns: str: secret key in 32 characters uuid4 format. """ return str(uuid.uuid4().hex)
bigcode/self-oss-instruct-sc2-concepts
import torch def quaternion_multiply(quaternion1, quaternion2): """Multiply quaternion1 by quaternion2. Args: quaternion1: N x 4 quaternions quaternion2: N x 4 quaternions Returns: res: N x 4 """ x1, y1, z1, w1 = quaternion1[:, 0], quaternion1[:, 1], quaternion1[:, 2], qu...
bigcode/self-oss-instruct-sc2-concepts
def duplicate(x, rep): """Duplicate x rep times. Args: x (torch.Tensor): Tensor to replicate rep (int): Number of times to replicate Returns: torch.Tensor: Replicated Tensor """ return x.expand(rep, *x.shape).reshape(-1, *x.shape[1:])
bigcode/self-oss-instruct-sc2-concepts
import struct def turn_plink_assoc_line_into_bin(line): """ This turns a non header line from a standard plink repeated univariate association file (*.qassoc) into a byte format. The format represents in order: short (h): chromosome (only numeric chromosome allowed) int (i): position ...
bigcode/self-oss-instruct-sc2-concepts
def step(adv): """Show player's step count. Args: adv: namedtuble holding the game data Modifies: nothing Returns: string: message showing steps so far """ return adv.messages["step"].format(adv.player["step"])
bigcode/self-oss-instruct-sc2-concepts
def pyver() -> str: """ Returns string with python version number in major.minor.micro format. (e.g. 3.7.3 or 2.7.12) """ return '.'.join(str(i) for i in __import__('sys').version_info[:3])
bigcode/self-oss-instruct-sc2-concepts
def bin2dec(n): """Convert a binary number to decimal. Args: n (str): The string representation of a binary number to convert. Returns: int: The result decimal number if n is valid. """ return int(n, 2)
bigcode/self-oss-instruct-sc2-concepts
def connect(from_endpoint, to_endpoint): """Connects an upstream endpoint to a downstream endpoint. This is a convenience function only. Endpoint users may instead choose to write the 3 eq statements required to make a connection. Example uses: m.d.comb += connect(one_components_output, another_c...
bigcode/self-oss-instruct-sc2-concepts
import importlib def cfg_instantiate(cfg, *args, **kwargs): """Create a instance of a class specified in cfg.""" package_name, classname = cfg.classname.rsplit(".", 1) package = importlib.import_module(package_name) constructor = getattr(package, classname) obj = constructor(*args, **(cfg.kwargs o...
bigcode/self-oss-instruct-sc2-concepts
def flatten(values, mask): """Flatten the spatial dimensions of the input array and removed masked points """ # Flatten and mask the input array args = [-1] if values.ndim < 4 else values.shape[:2] maskflat = mask.ravel().astype(bool) valuesflat = values.reshape(*args, len(maskflat))[.....
bigcode/self-oss-instruct-sc2-concepts
import string def remove_punc(words): """Function that removes punctuation from a string Arguments --------- words -- string to have punctuation removes """ trans = {ord(c): None for c in string.punctuation} no_punc = words.translate(trans) return no_punc
bigcode/self-oss-instruct-sc2-concepts
import re def remove_numbers(words): """Remove numbers and words that start with numbers """ new_words = [] for w in words: if not re.match(r"\d+.*", w): new_words.append(w) return new_words
bigcode/self-oss-instruct-sc2-concepts
def convert_quat(q, to="xyzw"): """ Converts quaternion from one convention to another. The convention to convert TO is specified as an optional argument. If to == 'xyzw', then the input is in 'wxyz' format, and vice-versa. Args: q: a 4-dim numpy array corresponding to a quaternion ...
bigcode/self-oss-instruct-sc2-concepts
import six def to_bed12(f, db, child_type='exon', name_field='ID'): """ Given a top-level feature (e.g., transcript), construct a BED12 entry Parameters ---------- f : Feature object or string This is the top-level feature represented by one BED12 line. For a canonical GFF or GTF...
bigcode/self-oss-instruct-sc2-concepts