seed
stringlengths
1
14k
source
stringclasses
2 values
import math def length (v): """ Length of a vector in 2-space. Params: v (2-tuple) vector in 2-space Returns: (float) length """ # INSERT CODE HERE, replacing 'pass' x,y = v[0],v[1] return math.sqrt ((x**2) + (y**2))
bigcode/self-oss-instruct-sc2-concepts
def descending_coin(coin): """Returns the next descending coin in order. >>> descending_coin(25) 10 >>> descending_coin(10) 5 >>> descending_coin(5) 1 >>> descending_coin(2) # Other values return None """ if coin == 25: return 10 elif coin == 10: return 5 ...
bigcode/self-oss-instruct-sc2-concepts
def _ds_or_none(ds): """return none if ds is empty""" if any(ds.coords) or any(ds.variables) or any(ds.attrs): return ds return None
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Any def assert_and_pass(func: Callable, arg: Any): """Call ``func``` with ``arg`` and return ``arg``. Additionally allow arg to be ``None``. Args: func: Test function. arg: Function argument. Returns: Result of ``func(arg)``...
bigcode/self-oss-instruct-sc2-concepts
def type_name(obj): """Fetch the type name of an object. This is a cosmetic shortcut. I find the normal method very ugly. :param any obj: The object you want the type name of :returns str: The type name """ return type(obj).__name__
bigcode/self-oss-instruct-sc2-concepts
from typing import Generic from re import T def filter_by_organization(model: Generic[T], organization_id: str) -> QuerySet: # type: ignore """ Filters active resources that belong to an organization. Args: model (Generic[T]): Model that is going to be queried. organization_id (str): ID ...
bigcode/self-oss-instruct-sc2-concepts
import torch def pad_feature_map(feature_map: torch.Tensor, padding_size: int): """Zero-pad feature map by a constant padding margin. Args: feature_map: The map to extract features from. padding_size: The padding size. """ return torch.nn.ConstantPad2d(padding_size, 0.0)(feature_map)
bigcode/self-oss-instruct-sc2-concepts
def is_identity_matrix(L): """ Returns True if the input matrix is an identity matrix, False otherwise. """ result = len(L) == len(L[0]) for i in range(len(L)): for j in range(len(L)): if i == j: result *= (L[i][j] == 1) else: result *=...
bigcode/self-oss-instruct-sc2-concepts
def has_value(value): """ We want values like 0 and False to be considered values, but values like None or blank strings to not be considered values """ return value or value == 0 or value is False
bigcode/self-oss-instruct-sc2-concepts
def create_container(swift_connection, name, storage_policy=None): """ Create a container with an optional storage policy. :param swift_connection: connection to Swift :type swift_connection: :py:class:`swiftclient.client.Connection` :param name: container name :type name: string :param sto...
bigcode/self-oss-instruct-sc2-concepts
import pprint def block_indent(text, spaces=4): """ Given a multi-line string, indent every line of it by the given number of spaces. If `text` is not a string it is formatted using pprint.pformat. """ return '\n'.join([(' ' * spaces) + l for l in pprint.pformat(text).splitlines()])
bigcode/self-oss-instruct-sc2-concepts
def get_single_company_identifiers(data: dict, identifier: str) -> dict: """Retrieves the three identifiers (CIK, ticker, title) of a single company. :param data: The dictionary mapping CIKs with tickers and title from the SEC. :type data: dict. :param identifier: The identifier passed by the user when...
bigcode/self-oss-instruct-sc2-concepts
def remove_overlap(ranges): """ Simplify a list of ranges; I got it from https://codereview.stackexchange.com/questions/21307/consolidate-list-of-ranges-that-overlap """ result = [] current_start = -1 current_stop = -1 for start, stop in sorted(ranges): if start > current_stop: # this segment starts after t...
bigcode/self-oss-instruct-sc2-concepts
def get_supported_os(scheduler): """ Return a tuple of the os supported by parallelcluster for the specific scheduler. :param scheduler: the scheduler for which we want to know the supported os :return: a tuple of strings of the supported os """ return "alinux" if scheduler == "awsbatch" else "...
bigcode/self-oss-instruct-sc2-concepts
def get_strand(read): """Get the strand of the mapped read""" if read.is_reverse: return '-' return '+'
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import List def get_home_and_node_id_from_device_id(device_id: Tuple[str, str]) -> List[str]: """ Get home ID and node ID for Z-Wave device registry entry. Returns [home_id, node_id] """ return device_id[1].split("-")
bigcode/self-oss-instruct-sc2-concepts
def get_tag(td, tag, o1, o2): """Return the tag between offsets o1 and o2 if there is one, return None if there is no such tag.""" tags = td.tags.find_tags(tag) for t in tags: if t.begin == o1 and t.end == o2: return t return None
bigcode/self-oss-instruct-sc2-concepts
def enum(*values, **kwargs): """Generates an enum function that only accepts particular values. Other values will raise a ValueError. Parameters ---------- values : list These are the acceptable values. type : type The acceptable types of values. Values will be converted befor...
bigcode/self-oss-instruct-sc2-concepts
import codecs import yaml def load_yaml_file(file_path: str): """Load a YAML file from path""" with codecs.open(file_path, 'r') as f: return yaml.safe_load(f)
bigcode/self-oss-instruct-sc2-concepts
def remove_underscores(value): """ Removes the underscores from a given string """ return value.replace("_", " ").title()
bigcode/self-oss-instruct-sc2-concepts
def _getView(syn, view_id, clause=None): """ Based on a user-defined query calls to synapse's tableQuery function and returns the entity-view generator object. :param syn: A Synapse object: syn = synapseclient.login(username, password) - Must be logged into synapse :param view_id: A Synapse ID of...
bigcode/self-oss-instruct-sc2-concepts
def _dms2dd(d: float, m: float, s: float) -> float: """ Converts a DMS coordinate to DD :param d: degrees :param m: minutes :param s: seconds :return: equivalent in decimal degrees """ return d + m / 60 + s / 3600
bigcode/self-oss-instruct-sc2-concepts
import struct import socket def _ConvertMaskToCIDR(mask): """Convert a netmask like 255.255.255.0 to a CIDR length like /24.""" bits = int(struct.unpack('!I', socket.inet_pton(socket.AF_INET, mask))[0]) found_one_bit = False maskbits = 0 for i in range(32): if (bits >> i) & 1 == 1: found_one_bit =...
bigcode/self-oss-instruct-sc2-concepts
import jinja2 def invite_form(event, context): """Get response for invite code page. Invoked by AWS Lambda.""" template = jinja2.Environment( loader=jinja2.FileSystemLoader('./') ).get_template('public/tmpl/enter_invite.html') return { "statusCode": 200, "headers": {"Content-Ty...
bigcode/self-oss-instruct-sc2-concepts
def mean(iterable): """Returns the average of the list of items.""" return sum(iterable) / len(iterable)
bigcode/self-oss-instruct-sc2-concepts
def strip_prefix(prefix, string): """Strip prefix from a string if it exists. :param prefix: The prefix to strip. :param string: The string to process. """ if string.startswith(prefix): return string[len(prefix):] return string
bigcode/self-oss-instruct-sc2-concepts
def parse_problems(lines): """ Given a list of lines, parses them and returns a list of problems. """ res = [list(map(int, ln.split(" "))) for ln in lines] return res
bigcode/self-oss-instruct-sc2-concepts
def skip_names(mol_list): """ Check if a list of molecules contains nomenclature that suggests it can be skipped. i.e. lignin implies polymeric species. """ # lignin - a polymeric species that can form under oxidative # polymerisation # many forms exist. HRP produces some. ...
bigcode/self-oss-instruct-sc2-concepts
def get_morsel_cookie(info, name, default=None): """Gets the value of the cookie with the given name, else default.""" if info.cookies is not None and name in info.cookies: return info.cookies[name].value return default
bigcode/self-oss-instruct-sc2-concepts
def readId2Name(fin): """ Reconstruct a global id=>username dictionary from an open csv file Reads the globalId2Name file (or equivalent) and constructs an id=>username dictionary. Input is an open csv.reader file such as the one constructed by the main method of this module. Returns a dictiona...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_filetypes(format: str = 'json') -> List[str]: """Get filetypes based on specified format.""" return ['yml', 'yaml'] if format == 'yaml' else [format]
bigcode/self-oss-instruct-sc2-concepts
def min_x_pt(pt_dict): """Returns the key of the point at minimum x (with minimum y) in the XY plane (Z is ignored) pt_dict is a collection of 'pt_ID: (x, y, z)' key-value pairs""" nmin = (9.9E12, 9.9E12) the_node = None for k,v in pt_dict.items(): if v[0] == nmin[0]: if...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import random def get_wav_files(data_dir: Path): """ Get all *.wav files in the data directory. """ files = sorted(data_dir.glob("*.wav")) random.Random(42).shuffle(files) return files
bigcode/self-oss-instruct-sc2-concepts
def get_z_prop(p, pi, n): """ Function to get the Z value (standard deviations number under or over the average) correspondent of the x value (parameter) in the standard normal distribution. Applied in proportions. Parameters: -------------------------- p : double, float "Succes...
bigcode/self-oss-instruct-sc2-concepts
def compress_indexes(indexes): """Compress a list of indexes. The list is assumed to be sorted in ascending order, and this function will remove the all the consecutives numbers and only keep the first and the number of the consecutives in a dict. eg : [0, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 18, 19, 2...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_wbgene_string(string): """ Receives a string that contains WBGene indices. Parses the string into a set of WBGene indices. \ The format of a WBGene index is 'WBGene' and exactly 8 digits. :type string: str :param string: The string to be parsed. Can be any format of string. ...
bigcode/self-oss-instruct-sc2-concepts
import math def rotate(vec, degrees): """ Rotates a 2D vector x, y counter-clockwise by degrees degrees """ x, y = vec sin = math.sin(math.radians(degrees)) cos = math.cos(math.radians(degrees)) rot_x = cos * x + -sin * y rot_y = sin * x + cos * y return rot_x, rot_y
bigcode/self-oss-instruct-sc2-concepts
import torch def topk_accuracy(k, logits: torch.Tensor, labels: torch.Tensor, unk_id=None, pad_id=None): """ Averaged per sample: 1, if one of the k predictions with highest confidence was the correct one for all sub tokens 0, else if `unk_id` is given, the best non <unk> prediction will b...
bigcode/self-oss-instruct-sc2-concepts
import re def _parse_host(id): """ This helper function parses the host from `id` in scope nodes. Returns the host name if it is a host, else return None. """ host_name = None r = re.match(r"^(.*);<host>$", id) if r: host_name = r.group(1) return host_name
bigcode/self-oss-instruct-sc2-concepts
def retrieve_row_values(row, field_names, index_dict): """This function will take a given list of field names, cursor row, and an index dictionary provide a tuple of passed row values. :param - row - cursor row :param - field_names -list of fields and their order to retrieve :param - index_dict - cu...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Union from typing import Any from typing import List def hash_dict( item_dict: Dict[str, Union[Dict[str, Any], List[Any], str]] ) -> Dict[str, Any]: """ Hash dictionary values. Parameters ---------- item_dict : Dict[str, Union[Dict[str, Any], List[An...
bigcode/self-oss-instruct-sc2-concepts
def ant_2_containing_baslines(ant, antennas): """ Given antenna returns list of all baselines among given list with that antenna. """ baselines = list() for antenna in antennas: if antenna < ant: baselines.append(256 * antenna + ant) elif antenna > ant: b...
bigcode/self-oss-instruct-sc2-concepts
def count_commas(s: str) -> int: """ count commas: - english comma [,](\u002c) - Chinese full-width comma [,](\uff0c) - Chinese seperator / Japanese comma [、](\u3001) """ count = 0 for c in s: if c in "\u002c\uff0c\u3001": count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def list_to_dict(node_list: list): """ Convert the list to a dictionary, Create a dictionary, key is a element in the list, value is a element which next the key, if no exists, the value is None. Args: node_list (list): normal, list of node Returns: schema (dict): a dictionary ...
bigcode/self-oss-instruct-sc2-concepts
def clipAlpha(aj, H, L): """ 调整aj的值,使L<=aj<=H Args: aj 目标值 H 最大值 L 最小值 Returns: aj 目标值 """ aj = min(aj, H) aj = max(L, aj) return aj
bigcode/self-oss-instruct-sc2-concepts
def safe_cast(val, to_type, default=None): """A helper for safe casts between types""" try: return to_type(val) except (ValueError, TypeError): return default
bigcode/self-oss-instruct-sc2-concepts
import re def _replace_labels(html: str) -> str: """ Replace Django's question-level labels with legend elements """ return re.sub( "<fieldset><label [^>]+>(.*?)</label>", lambda m: f'<fieldset><legend class="tdp-question-legend">{m[1]}</legend>', # noqa: B950 html, )
bigcode/self-oss-instruct-sc2-concepts
import math def tanh(value): """ This function calculates the hyperbolic tangent function. """ return math.tanh(value)
bigcode/self-oss-instruct-sc2-concepts
import warnings def center_roi_around(center_rc, size_hw): """ Return a rectangular region of interest (ROI) of size `size_hw` around the given center coordinates. The returned ROI is defined as (start_row, start_column, end_row, end_column) where the start_row/column are ment to be *include...
bigcode/self-oss-instruct-sc2-concepts
def conv_lin(a, b=1.0, c=0.0, inverse=False): """Simple linear transform will I think store parameters against each sensor then they are handy >>> conv_lin(4,2,3) 11 >>> conv_lin(11,2,3.0,True) 4.0 >>>""" if inverse is False: return a * b + c else: ...
bigcode/self-oss-instruct-sc2-concepts
def get_param_dict(self): """Get the parameters dict for the ELUT of PMSM at the operationnal temperature and frequency Parameters ---------- self : ELUT an ELUT_PMSM object Returns ---------- param_dict : dict a Dict object """ # getting parameters of the abstract ...
bigcode/self-oss-instruct-sc2-concepts
def train_batch(model, x, target, optimizer, criterion): """Train a model for one iteration Args: model (torch.nn.Module): model to train x (torch.Tensor): input sample target (torch.Tensor): output target optimizer (torch.optim.Optimizer): parameter optimizer criterion (...
bigcode/self-oss-instruct-sc2-concepts
def patch_init(mocker): """ Makes patching a class' constructor slightly easier """ def patch_init(*args, **kwargs): for item in args: mocker.patch.object(item, '__init__', return_value=None, **kwargs) return patch_init
bigcode/self-oss-instruct-sc2-concepts
import json def getCommandsFromLog(inFile,filterList,coverage): """ Get commands from a log Parameters ---------- inFile : str path to pyrpipe log file. filterList : str list of commands to ignore. coverage : char type of commands to report all, passed or failed: a...
bigcode/self-oss-instruct-sc2-concepts
def get_panel_groups_at_depth(group, depth=0): """Return a list of the panel groups at a certain depth below the node group""" assert depth >= 0 if depth == 0: return [group] else: assert group.is_group() return [ p for gp in group.children() f...
bigcode/self-oss-instruct-sc2-concepts
def get_class(name, defmod=None): """Finds a class. Search a class from its fully qualified name, e.g. 'pyconstruct.domains.predefined.Class'. If the class name is not fully qualified, e.g. 'Class', it is searched inside the default module. Parameters ---------- name : str The ful...
bigcode/self-oss-instruct-sc2-concepts
def max_endtime(graph): """ A method to calculate the maximum endtime of a network. Parameter(s): ------------- graph : TemporalDiGraph A directed, temporal graph. Returns: -------- maxEndtime : int the maximum endtime of a networ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_jobdesc_config(job): """Function for extracting job description config file.""" job_desc_url = '%s/job_description.json' % job['job_url'] r = requests.get(job_desc_url, verify=False) r.raise_for_status() return job_desc_url
bigcode/self-oss-instruct-sc2-concepts
def ReadableSize(num): """Get a human-readable size.""" for unit in ['B', 'KB', 'MB', 'GB']: if abs(num) <= 1024.0: return '%3.2f%s' % (num, unit) num /= 1024.0 return '%.1f TB' % (num,)
bigcode/self-oss-instruct-sc2-concepts
def convert_to_tuples(examples): """ Convert a list of Example objects to tuples of the form: (source, translation, language, author, reference). """ convert1 = lambda e: e.to_simple_tuple() return list(filter(bool, map(convert1, examples)))
bigcode/self-oss-instruct-sc2-concepts
def prop_get_nyquistsampling(wf, lamx = 0.0): """Funtion determines the Nyquist sampling interval for the current beam, which is focal_ratio * wavelength / 2. Parameters ---------- wf : obj Wavefront class object lamx : float Wavelength to use for computing sampling...
bigcode/self-oss-instruct-sc2-concepts
def _len_arg(typ): """Returns the length of the arguments to the given type.""" try: return len(typ.__args__) except AttributeError: # For Any type, which takes no arguments. return 0
bigcode/self-oss-instruct-sc2-concepts
def gen_cppcheck_enables(enables): """生成cppcheck的enable参数 格式:enable1, enable2, ... """ # 每个enable参数用逗号隔开 return '--enable={}'.format(','.join(enables))
bigcode/self-oss-instruct-sc2-concepts
def get_file_text(path, encoding): """Returns all text contents of a file at the given path in the form of a string.""" with open(path, mode='r', encoding=encoding) as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
import importlib def call_module_function(*arguments): """ Dynamically calls specified function from specified package and module, on the given image. The three arguments of the function represent, in order: the input image, any extra input images (necessary in the case of many-to- operations, empty other...
bigcode/self-oss-instruct-sc2-concepts
def get_dict_from_list(smu_info_list): """ Given a SMUInfo array, returns a dictionary keyed by the SMU name with SMUInfo as the value. """ smu_info_dict = {} for smu_info in smu_info_list: smu_info_dict[smu_info.name] = smu_info return smu_info_dict
bigcode/self-oss-instruct-sc2-concepts
def _c_null_pointer(p): """Returns true if ctypes pointer is null.""" return (not bool(p))
bigcode/self-oss-instruct-sc2-concepts
def get_rev_recon(tree, recon, stree): """ Returns a reverse reconciliation A reverse reconciliation is a mapping from nodes in the species tree to lists of nodes in the gene tree. """ rev_recon = {} nodes = set(tree.postorder()) for node, snode in recon.iteritems(): if node not...
bigcode/self-oss-instruct-sc2-concepts
def _unshaped_initializer(fn, **kwargs): """Build a flax-style initializer that ignores shapes. Args: fn: Callable that takes a random number generator and some keyword arguments, and returns an initial parameter value. **kwargs: Arguments to pass to fn. Returns: Call...
bigcode/self-oss-instruct-sc2-concepts
def get_consecutive_num(arr): """ Method to get indices of second number in a pair of consecutive numbers Note: solve_90f3ed37 uses this function """ rows = [] for i in range(len(arr) - 1): if (arr[i] + 1) == arr[i + 1]: rows.append(arr[i + 1]) return rows
bigcode/self-oss-instruct-sc2-concepts
def getFileId(fname): """ Extract the id from a filename """ return '_'.join(fname.split('_')[:4])
bigcode/self-oss-instruct-sc2-concepts
def station_name(f): """ From the file name (f), extract the station name. Gets the data from the file name directly and assumes the file name is formatted as Data/Station_info.csv. """ return f.split('/')[1].split('_')[0]
bigcode/self-oss-instruct-sc2-concepts
def string_to_values(input_string): """Method that takes a string of '|'-delimited values and converts them to a list of values.""" value_list = [] for token in input_string.split('|'): value_list.append(float(token)) return value_list
bigcode/self-oss-instruct-sc2-concepts
def generate_reference(model, gen, field='reference', prefix='', max_retries=10): """ Generate a unique reference given: :param model: the class of the django model :param gen: a function without arguments that returns part or all the reference :param field: reference field of the model that needs ...
bigcode/self-oss-instruct-sc2-concepts
def _has_eval_results_call(cls): """Return True if cls has a __call__ decorated with @eval_results """ return getattr(getattr(cls, '__call__', None), '_eval_results', False)
bigcode/self-oss-instruct-sc2-concepts
def CommonSymbolsToOrder(symbols, common_symbols): """Returns s -> index for all s in common_symbols.""" result = {} index = 0 for s in symbols: if s not in common_symbols: continue result[s] = index index += 1 return result
bigcode/self-oss-instruct-sc2-concepts
import torch def sdd_bmm_diag_torch(t1, t2): """ Perform bmm and diagonal for sparse x dense -> dense. The diagonalized result is returned in vector tensor. With s_t1.shape = (b, x, s), d_t2.shape = (b, s, x), the output shape is (b, x). This method avoids a temporal (b, x, x) for memory efficiency. ...
bigcode/self-oss-instruct-sc2-concepts
def ip_pool_to_dict(ipp): """Convert an IPPool object to a dict""" return { 'input': ipp.input[0], 'unused': [str(x) for x in ipp.pool.iter_cidrs()], }
bigcode/self-oss-instruct-sc2-concepts
def flat_list(l): """ Convert a nested list to a flat list """ try: return [item for sublist in l for item in sublist] except: return l
bigcode/self-oss-instruct-sc2-concepts
import re import itertools def _java_hex(uuid): """Java Mongo Driver transfers byte representation of UUIDs in little endian format. See also https://jira.mongodb.org/browse/JAVA-403 :param uuid: :return: reordered hex sequence """ _hex = re.sub(r'[{}-]', '', uuid) bytes = list(zip(_hex[0:...
bigcode/self-oss-instruct-sc2-concepts
def fibonacci(n): """フィボナッチ数を求める関数 :param n: ``n`` 番目のフィボナッチ数を求める :returns: n番目のフィボナッチ数 :raises: ``ValueError`` when ``n`` is less than 0 """ if n < 0: raise ValueError('nは0以上を指定してください') if n in (0, 1): return n return fibonacci(n - 1) + fibonacci(n - 2)
bigcode/self-oss-instruct-sc2-concepts
def clean_github_repository(repo): """ get the username/repository from a Github url :param repo:str the Github url of the repository :return: username/repository """ if repo is None: return None repo = repo.replace("http://github.com/", "") \ .replace("https://github.com/", ...
bigcode/self-oss-instruct-sc2-concepts
def str2bool(value): """Returns a boolean reflecting a human-entered string.""" return value.lower() in (u'yes', u'1', u'true', u't', u'y')
bigcode/self-oss-instruct-sc2-concepts
def filter_low_swh(ds): """Remove all records with low significant wave heights.""" return ds['sea_state_30m_significant_wave_height_spectral'] > 1.0
bigcode/self-oss-instruct-sc2-concepts
def _unique_retrieval(element_list, elem_identifier, search_identifier): """ Get the text from a ResultSet that is expected to have a length of 1. Parameters ---------- element_list : bs4.element.ResultSet Result of a `findAll` elem_identifier : str An identifier for the element...
bigcode/self-oss-instruct-sc2-concepts
def time_to_knx(timeval, dow=0): """Converts a time and day-of-week to a KNX time object""" knxdata = [0, 0, 0] knxdata[0] = ((dow & 0x07) << 5) + timeval.hour knxdata[1] = timeval.minute knxdata[2] = timeval.second return knxdata
bigcode/self-oss-instruct-sc2-concepts
def prepare_cell_align_type(in_cell_align): """ Basic function that renames the cell alignment string from the ArcGIS Pro UI and makes it dea aws stac query compatible. Parameters ------------- in_cell_align : str The ArcGIS Pro UI string for stac cell alignment. Exampl...
bigcode/self-oss-instruct-sc2-concepts
def get_pretrain_stop_metric(early_stopping_method, pretrain_tasks): """ Get stop_metric, which is used for early stopping. Parameters ------------------- early_stopping_method: str, pretrain_tasks: List[Task] Returns ------------------- stop_metric: str """ if early_s...
bigcode/self-oss-instruct-sc2-concepts
def read_D(filename): """reads an upper triangular matrix with phylogentic distances between species. Returns a dictionary with distances for species names.""" D = {} f = open(filename) cols = f.readline().rstrip().split('\t') for line in f: elems = line.strip().split('\t') ...
bigcode/self-oss-instruct-sc2-concepts
import torch def corn_labels_from_logits(logits): """ Returns the predicted rank label from logits for a network trained via the CORN loss. Parameters ---------- logits : torch.tensor, shape=(n_examples, n_classes) Torch tensor consisting of logits returned by the neural net. ...
bigcode/self-oss-instruct-sc2-concepts
import yaml def read_yml(filepath: str) -> dict: """Load a yml file to memory as dict.""" with open(filepath, 'r') as ymlfile: return dict(yaml.load(ymlfile, Loader=yaml.FullLoader))
bigcode/self-oss-instruct-sc2-concepts
import json def load_json_file(filename): """Load data from a json file.""" data = {} print('Loading file "{}"'.format(filename)) with open(filename, 'r') as infile: data = json.load(infile) return data
bigcode/self-oss-instruct-sc2-concepts
def num_nodes_with_name (root,name,recurse=True): ############################################################################### """ Count nodes with certain name in an XML tree >>> xml = ''' ... <root> ... <a/> ... <sub> ... <a/> ... </sub> ... </root> ... ...
bigcode/self-oss-instruct-sc2-concepts
def binary_freq(data, expression, feature_name=str, analyze=True): """Search data for occurrences of a binary feature as a regex. Args: data (pd.Series): a series with text instances. expression (re.compile): a regex or string to search for. feature_name (str, optional): a name for the...
bigcode/self-oss-instruct-sc2-concepts
def confirm_mirror(uri): """Check if line follows correct sources.list URI""" deb = ('deb', 'deb-src') proto = ('http://', 'ftp://') if (uri and (uri[0] in deb) and (proto[0] in uri[1] or proto[1] in uri[1])): return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def sum_of_integers_in_string(s: str) -> int: """ This function calculates the sum of the integers inside a string """ return sum([int(i) for i in re.findall(r'\d+', s)])
bigcode/self-oss-instruct-sc2-concepts
def add_nonN_count(df, nonN_count_file): """Count number of nonambiguous nucleotides per sequence and add counts to dataframe""" count_dict = {} with open(nonN_count_file, 'r') as f: for line in f: id, count = line.rstrip('\n').split('\t') count_dict[id] = int(count) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence import re def list_to_patt(lst: Sequence[str], name: str) -> str: """ Create a regex pattern in string form capable of matching each element in a list. Beware of having empty string in lst! Arguments: lst: list of strings for which a regex pattern is to be deter...
bigcode/self-oss-instruct-sc2-concepts
import struct def parse_linkidandlinkedbehavior(number): """ Returns a link ID index and behavior tuple for the given number. """ number = int(number) byteval = struct.pack('>i', number) (linkid, junk, behavior) = struct.unpack('>bbH', byteval) return (linkid, behavior)
bigcode/self-oss-instruct-sc2-concepts
def echo(text): """create job that just prints text""" return ['echo', text]
bigcode/self-oss-instruct-sc2-concepts