seed
stringlengths
1
14k
source
stringclasses
2 values
def _vax_to_ieee_single_float(data): """Converts a float in Vax format to IEEE format. data should be a single string of chars that have been read in from a binary file. These will be processed 4 at a time into float values. Thus the total number of byte/chars in the string should be divisible by 4...
bigcode/self-oss-instruct-sc2-concepts
def getBlockNumbersForRegionFromBinPosition(regionIndices, blockBinCount, blockColumnCount, intra): """ Gets the block numbers we will need for a specific region; used when the range to extract is sent in as a parameter Args: regionIndices (array): Array of ints giving range blockBinCount (in...
bigcode/self-oss-instruct-sc2-concepts
def _find_subclasses(cls): """Find all the subclasses of a class. Args: cls (class): The parent class. Returns: list: Subclasses of the given parent class. """ results = [] for subclass in cls.__subclasses__(): results.append(subclass) return results
bigcode/self-oss-instruct-sc2-concepts
def _bop_or(obj1, obj2): """Boolean or.""" return bool(obj1) or bool(obj2)
bigcode/self-oss-instruct-sc2-concepts
def copy_tensor_list(ten_list): """ Create a copy of a list of tensors """ ten_list_cp = [None]*len(ten_list) for i in range(len(ten_list)): ten_list_cp[i] = ten_list[i].copy() return ten_list_cp
bigcode/self-oss-instruct-sc2-concepts
import json def to_json_string(my_obj): """ Function that returns the JSON representation of an object. Args: my_obj (str): Surce object Returns: JSON representation. """ return json.dumps(my_obj)
bigcode/self-oss-instruct-sc2-concepts
import toml def load_features(path): """ Loads a Cargo.toml file and extracts all features from it. :param path: The path to the Cargo.toml :return: A list of features this package has """ with open(path, 'r') as f: config = toml.load(f) if 'features' not in config: ...
bigcode/self-oss-instruct-sc2-concepts
def sum_even_fibonacci(limit: int) -> int: """ Sums even terms in the Fibonacci sequence. :param limit: Limit for the sequence, non-inclusive. :return: Sum of even terms in the Fibonacci sequence. """ term_a = 1 term_b = 2 result = 0 while term_b < limit: if not term_b % 2: ...
bigcode/self-oss-instruct-sc2-concepts
import json def get_config(config): """ convert json config file into a python dict """ with open(config, 'r') as f: config_dict = json.load(f)[0] return config_dict
bigcode/self-oss-instruct-sc2-concepts
def intFromBytes(b, signed=False): """ Decodes an integer from bytes. Args: b (bytes-like): The encoded integer. signed (bool): Whether to decode as a signed integer. Returns: int: The decoded integer. """ return int.from_bytes(b, "big", signed=signed)
bigcode/self-oss-instruct-sc2-concepts
def isNaN(num): """ Checks if a value is nan :param num: value to be checked :return: Boolean True or False """ return num != num
bigcode/self-oss-instruct-sc2-concepts
import itertools def flock(predicate, iterable): """Groups elements into subsequences after sorting:: things = [("phone", "android"), ("phone", "iphone"), ("tablet", "ipad"), ("laptop", "dell studio"), ("phone", "nokia"), ("lapto...
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_to_device(batch,target_device): """ send a pytorch batch to a device (CPU/GPU) """ for key in batch: if isinstance(batch[key], torch.Tensor): batch[key] = batch[key].to(target_device) return batch
bigcode/self-oss-instruct-sc2-concepts
def makeEvalStop(limit, timer, value=None): """Use a closure to create a heuristic function that forces the search timer to expire when a fixed number of node expansions have been perfomred during the search. This ensures that the search algorithm should always be in a predictable state regardless of no...
bigcode/self-oss-instruct-sc2-concepts
def partition(predicate, sequence): """ Takes a predicate & a sequence of items, and applies the predicate to each of them. Returns a tuple with the first item being the list of matched items, and the second being the list of not matched items. """ match, nomatch = [], [] for item i...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Union from typing import List from typing import Tuple from typing import Any from typing import cast from typing import Type def _path_param_reducer(acc: Dict[str, Union[str, List[str]]], cur: Tuple[Dict[str, Any], str]) -> Dict[str, Any]: """ Reducer function - acc...
bigcode/self-oss-instruct-sc2-concepts
def histogram(letters): """ Creates a frequency histogram of the given letters Input: letters -- word or scrambled letters Output: dictionary mapping from letters to the # of occurences of that letter """ d = dict() for letter in letters: if letter in d: d[letter] += 1 ...
bigcode/self-oss-instruct-sc2-concepts
def get_num_label_vols(md): """ Get the number of volumes used for labelling - e.g. 2 for tag-control pair data """ iaf = md.get("iaf", "tc") if iaf in ("tc", "ct"): return 2 elif iaf == "diff": return 1 elif iaf == "mp": return md.get("nphases", 8) elif iaf == "v...
bigcode/self-oss-instruct-sc2-concepts
import torch def sort_by_seq_lens(batch, sequences_lengths, descending=True): """ Sort a batch of padded variable length sequences by their length. Args: batch: A batch of padded variable length sequences. The batch should have the dimensions (batch_size x max_sequence_length x *). ...
bigcode/self-oss-instruct-sc2-concepts
def calculate_height(distance, y_max, y_min, focal_y): """ Calculate real person height in centimeters. """ px_height = y_max - y_min person_height = distance * px_height / focal_y return person_height
bigcode/self-oss-instruct-sc2-concepts
def _sub2instance(initial_condition, perturbation_index, total_perturbations): """ Converts initial condition index (ci) and perturbation index (pi) subscripts to an instance number (ii) instances use 1-based indexes and vary according to this function: ii = ci * len(PERTURBATIONS) + pi + 1 ...
bigcode/self-oss-instruct-sc2-concepts
def is_control(line, index, word): """ Return whether LINE[INDEX] is actual the start position of control statement WORD. It must be followed by an opening parantheses and only whitespace in between WORD and the '('. """ if index > 0: if not (line[index-1] in [' ', '\t', ';']): return False inde...
bigcode/self-oss-instruct-sc2-concepts
import re def cextra(string): """Length of extra color characters in a string""" return len(''.join(re.findall(r'\033[^m]*m', string)))
bigcode/self-oss-instruct-sc2-concepts
def remove_excess_whitespace(maybe_text): """Removes excess whitespace from maybe_text if this argument is a string. :param maybe_text: An object that might be a string. """ if isinstance(maybe_text, str): maybe_text = ' '.join(maybe_text.split()) maybe_text = maybe_text.strip() ...
bigcode/self-oss-instruct-sc2-concepts
def format_type_tuple(type_tuple): """Return a list of type names from tuple of types.""" return ", ".join([item.__name__ for item in type_tuple])
bigcode/self-oss-instruct-sc2-concepts
def param_row(param_keys, param_values): """ Returns a dict {param key: param value} """ values = list(param_values) return {k: values[i] for i, k in enumerate(param_keys)}
bigcode/self-oss-instruct-sc2-concepts
def get_verts(data, x_col, y_col, z_col, scaling): """ Get the (x,y,z) verticies from the given data frame using the given columns and point range scaling. """ def get_xyz(row): x = row[x_col] * scaling z = row[y_col] * scaling #SWAPPED y = row[z_col] * scaling * -1.0 #SWAPPE...
bigcode/self-oss-instruct-sc2-concepts
def linear(x): """ Performs linear function on the input elements. Linear function: f(x) = x :param x: {array}, shape {n_samples,} input to the function. :return: {array}, shape {n_samples,} output of linear function. """ return x
bigcode/self-oss-instruct-sc2-concepts
import torch def load_model(checkpoint_file,model,optimizer): """ Reloads a checkpoint, loading the model and optimizer state_dicts and setting the start epoch """ checkpoint = torch.load(checkpoint_file) model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(chec...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def extract_book_title(image_path: Path) -> str: """Extract book title from image file path.""" return image_path.parts[-1].split('_')[0].split('-')[0]
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha3_512_half(m: bytes) -> bytes: """Return the SHA3_512_half digest of the provided message.""" h = hashlib.sha3_512() h.update(m) d = h.digest() return d[:len(d) // 2]
bigcode/self-oss-instruct-sc2-concepts
def isNumber(x): """ Is the argument a python numeric type. """ return ( (type(x) == float) or (type(x) == int) )
bigcode/self-oss-instruct-sc2-concepts
import torch def quaternion_to_rotmat_vec(q): """ Converts batched quaternions of shape (batch, 4) to vectorized rotation matrices of shape (batch, 9) """ qr = q[:, 0:1] qi = q[:, 1:2] qj = q[:, 2:3] qk = q[:, 3:4] r1 = torch.cat( (1. - 2*(qj ** 2 + qk ** 2), 2*(qi*qj - qk*...
bigcode/self-oss-instruct-sc2-concepts
import re def match_in(key): """Is the key the 'in' keyword""" rx = re.compile("^_?([iI][nN])_?$") match = rx.match(key) if match: return True return False
bigcode/self-oss-instruct-sc2-concepts
import torch def cut_components_mixmvn(mixmeans, mixvars, mixweights, cutoff_limit=1e-6): """ Remove components of mixture of diagonal normal distributions whose weights are below some cutoff point Parameters ---------- mixmeans : torch.Tensor Mean matrix of mixtures of diagon...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Dict import yaml def load_yaml(yaml_config: Union[Dict, str]) -> Dict: """Load YAML Convenience function to allow for providing YAML inputs either as filename or as dictionary. Arguments: yaml_config: PEtab YAML config as filename or di...
bigcode/self-oss-instruct-sc2-concepts
import struct import codecs def hex_to_rgb(hex): """Convert a hex string to rgb.""" return struct.unpack('BBB', codecs.decode(hex[1:], 'hex'))
bigcode/self-oss-instruct-sc2-concepts
import re def tags_matching_regex(key, regex_str:str, compiled_regex = None): """ Returns a list of tags with all tags that match the regular expression """ if compiled_regex is None: compiled_regex = re.compile(regex_str) tags_list = [] for tag in key.getTags(): if compil...
bigcode/self-oss-instruct-sc2-concepts
def ParseKey(algorithm, key_length, key_type, messages): """Generate a keyspec from the given (unparsed) command line arguments. Args: algorithm: (str) String mnemonic for the DNSSEC algorithm to be specified in the keyspec; must be a value from AlgorithmValueValuesEnum. key_length: (int) The key l...
bigcode/self-oss-instruct-sc2-concepts
def comma_separated_int(s): """ Used as the 'dtype' argument to TextFileParser.add_field(), to parse integer fields which appear in text files with comma separators. """ s = s.replace(',','') return int(s)
bigcode/self-oss-instruct-sc2-concepts
def lazy_reduce(reduction, block, launches, contexts): """ Applies a reduction over a sequence of parallelizable device operations. The reduction can be something like built-in `max` or `min`. The `launches` argument is a sequence of callables which trigger the asynchronous calculation and return a...
bigcode/self-oss-instruct-sc2-concepts
def calc_longitude_shift(screen_width: int, percent_hidden: float) -> float: """Return the amount to shift longitude per column of screenshots.""" return 0.00000268 * screen_width * (1 - percent_hidden) * 2 # return 0.0000268 * screen_width * (1 - percent_hidden)
bigcode/self-oss-instruct-sc2-concepts
import csv import base64 def create_download_link( dataframe, filename: str, file_type: str = "csv", index: bool = False, header: bool = True, ): """ Generate a download link for a pandas dataframe. Args: dataframe: Pandas DataFrame filename: Name of exported file ...
bigcode/self-oss-instruct-sc2-concepts
def _format_time(elapsed_time): """ Format a number of seconds as a HHMMSS string :param elapsed_time: float, an amount of time in seconds :return time_string: a formatted string of the elapsed time """ hours = elapsed_time // 3600 minutes = (elapsed_time - hours * 3600) // 60 seconds =...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Literal from typing import List def make_ner_labels( entity_types: Iterable[str], type_: Literal["BIO", "BILUO"] = "BIO" ) -> List[str]: """Make BILUO or BIO style ner label from entity type list. Examples: >>> make_ner_labels(["PERSON"]) ["-...
bigcode/self-oss-instruct-sc2-concepts
def get_unit_concept_id_dict(df): """ Retrieve dictionary containing the unit_concept_id and its corresponding unit_concept_name :param df: dataframe :return: a dictionary containing the unit_concept_id and its corresponding unit_concept_name """ return dict(zip(df.unit_concept_id, df....
bigcode/self-oss-instruct-sc2-concepts
def _AssignTypeToRow(schema, row): """Uses a map to parse a given row's field, and assign it to obj. Args: schema (dict): Type and name of the row fields. Example: [ { 'type': 'INTEGER', 'name': 'field_name'}, ... ] row (dict): Raw row from bigquery response. {'f...
bigcode/self-oss-instruct-sc2-concepts
def real_value(value, base): """ Returns int(value) if it isn't a percentage, or applies it over base @param value The value or percentage @param base The maximum value if value is a percentage """ try: if not value.endswith('%'): return int(value) else: value = float(value[:-1]) ...
bigcode/self-oss-instruct-sc2-concepts
def modify(node): """ Modify the branch to NODE, if NODE is a terminal node and the `division_exposure` of NODE differs from the `division`. This creates an intermediate branch, with a single child, such that we have PARENT-INTERMEDIATE-NODE. """ if "children" in node: return node ...
bigcode/self-oss-instruct-sc2-concepts
def clean_up_file_name(filename): """ If FILENAME has spaces in it, replaces them with underscores. Otherwise, this function returns the filename unchanged. """ words = filename.split() if len(words) > 1: filename = "_".join(words) return filename
bigcode/self-oss-instruct-sc2-concepts
def sanitize_imagename(name: str) -> str: """ remove risky characters in a latex image filename and replace them with a non-risky one (-) :param name: the image filename to sanitize :return: the sanitized filename """ for c in "%.|_#[]@": name = name.replace(c, "-") return name
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Any from typing import Iterator def iter_nested_tuple( data_tuple: Tuple[Any], sortkey: bool = False ) -> Iterator[Tuple[Any]]: """Iterate over a tuple of nested structures. Similar to iter_nested but it iterates each of each nested data in the input tuple. For ex...
bigcode/self-oss-instruct-sc2-concepts
import re def match_mm3_vdw(mm3_label): """Matches MM3* label for bonds.""" return re.match('[\sa-z]6', mm3_label)
bigcode/self-oss-instruct-sc2-concepts
def _graph_without_edge_labels(dg, vertices): """ Expand the graph, by introducing new vertices in the middle of edges. Return the corresponding partition of the new vertices. There is one new vertex for each edge with label not equal to ``(1,-1)``. These vertices are numbered starting from the sma...
bigcode/self-oss-instruct-sc2-concepts
def tcp_received(data=None, data_length=None, id=None): """ Construct a template for TCP incoming data """ tpl = { 'tcp-event': 'received' } if data is not None: tpl['tcp-data'] = data if data_length is not None: tpl['tcp-data-length'] = data_length if id is not None: tpl['client-id'] = str(id) retu...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json(file): """Load JSON file as dict.""" with open(file, "r") as read_file: data = json.load(read_file) return data
bigcode/self-oss-instruct-sc2-concepts
def _validate_port_number(port_number): """Validate port number. Parameters ---------- port_number : int Supplied port number. Returns ------- int Valid port number. Raises ------ TypeError If `port_number` is not of type int. ValueError If ...
bigcode/self-oss-instruct-sc2-concepts
def Grab_Sequence( reader ): """ given reader is the position after a fasta header, extract a sequence return the last line read and the sequence """ #read and concatenate lines until > found or other non-sequence character found total_sequence = '' sequence = reader.readline( ) while( s...
bigcode/self-oss-instruct-sc2-concepts
def difference(dataset, interval=1): """ Differencing time series according to difference_order/interval dataset: type:list, Desc: list contaning timeseries values interval: type:integers Desc: Differencing order """ def do_diff(dataset): diff = list() ...
bigcode/self-oss-instruct-sc2-concepts
def expected_utility(a, s, U, mdp): """The expected utility of doing a in state s, according to the MDP and U.""" # print(sum([p * U[s1] for (p, s1) in mdp.T()[a][s]])) R, T, beta = mdp.R(), mdp.T(), mdp.beta return R[a][s] + beta * sum([p * U[s1] for (p, s1) in T[a][s]])
bigcode/self-oss-instruct-sc2-concepts
import math def round_power_2(value): """ Return value rounded up to the nearest power of 2. """ if value == 0: return 0 return math.pow(2, math.ceil(math.log(value, 2)))
bigcode/self-oss-instruct-sc2-concepts
def choose_height(new_width, width, height): """Return the height corresponding to 'new_width' that's proportional to the original size. """ proportion = float(height) / float(width) return int(new_width * proportion)
bigcode/self-oss-instruct-sc2-concepts
import torch def test(model, test_loader, criteria, device): """ Function to perform model validation Args: model (Net): Model instance to run validation test_loader (Dataset): Dataset used in validation device (string, cuda/cpu): Device type Values Allowed - cuda/cpu Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def valid_base(base): """Checks if cloud base is valid""" if base <= 30: return True elif base <= 50: return base % 5 == 0 else: return base % 10 == 0
bigcode/self-oss-instruct-sc2-concepts
def isinstanceinh(obj, parent_class): """ Returns True if 'obj' is is an instance of class 'parent_class', or of a subclass of 'parent_class'. :param obj: object to be tested :type obj: Any :param parent_class: class to be checked against :type parent_class: type (e.g. list, tuple, int, bool) ...
bigcode/self-oss-instruct-sc2-concepts
def distance_mean_elements(K, T1, T2): """ Compute the squared distance between mean elements of two time series Parameters ---------- K: (T1+T2) x (T1+T2) array, between frames kernel matrix T1: int, duration of time series 1 T2: int, duration of time series 2 Re...
bigcode/self-oss-instruct-sc2-concepts
def _name_orf(tfam, gcoord, AAlen): """Assign a usually unique identifier for each ORF. If not unique, a number should be appended to the end.""" return '%s_%d_%daa' % (tfam, gcoord, AAlen)
bigcode/self-oss-instruct-sc2-concepts
def getWindChill(temp, windSpeed): """ A utility function to get the human-apparent temperature in an oxygen-nitrogen atmosphere given an actual temperature and a wind speed. Wind chill is only valid for temperatures at or lower than 10C (50F) and wind speeds higher than 4.8 km/h (3 m/h). @para...
bigcode/self-oss-instruct-sc2-concepts
def check_stratification(age, stratification): """ Function check_stratification Returns 1 if all ages are consistent with stratification constraints Returns 0 if not. """ age_check = [age[i] for i in range(len(age)) if stratification[i] == 1] sorted_ages = age_check.copy() sort...
bigcode/self-oss-instruct-sc2-concepts
def PacketType(byte): """ Retrieve the message type from the first byte of the fixed header. """ if byte != None: rc = byte[0] >> 4 else: rc = None return rc
bigcode/self-oss-instruct-sc2-concepts
import re def FormatTimestamp(timestamp): """Formats a timestamp which will be presented to a user. Args: timestamp: Raw timestamp string in RFC3339 UTC "Zulu" format. Returns: Formatted timestamp string. """ return re.sub(r'(\.\d{3})\d*Z$', r'\1', timestamp.replace('T', ' '))
bigcode/self-oss-instruct-sc2-concepts
def multiple_bbox(bbox, img_height, img_width): """normalize bbox to be betwween 0, 1 Args: bbox (list): original labeled bounding box; img_width(int): image width; img_height(int): image height; Returns: norm_bbox: normolized bbox """ ...
bigcode/self-oss-instruct-sc2-concepts
import re def trim_space(s: str) -> str: """Remove leading and trailing whitespace but not newlines""" # leading and trailing whitespace causes "\n"'s in the resulting string ret = re.sub(r"(?m)[ \t]+$", "", s) ret = re.sub(r"(?m)^[ \t]+", "", ret) return ret
bigcode/self-oss-instruct-sc2-concepts
def get_lineage(taxon, tree): """Get lineage of given taxon in taxonomy tree. Parameters ---------- taxon : str Query taxon. tree : dict Taxonomy tree. Returns ------- list of str Lineage from root to query taxon. """ # if taxon is not in tree, return No...
bigcode/self-oss-instruct-sc2-concepts
def get_user_param(text: dict, machine_name_in_chat: str) -> str: """Maps text by 1/0 for it to be the person or the machine in the dialogue Parameters ---------- text: Dict[..., 'from', ...] Dict containing field 'from' with the name of the user who sent the message machine_name_in_chat: ...
bigcode/self-oss-instruct-sc2-concepts
import math def compute_distance(point1, point2): """ Computes distance between 2 points in a 2D space :param point1: :param point2: :return: distance """ return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
bigcode/self-oss-instruct-sc2-concepts
import math def monobit_frequency(bit_str: str): """Frequency (Monobit) Test Determine whether the number of ones and zeros in a sequence are approximately the same as would be expected for a truly random sequence. See section 2.1 in this NIST publication: https://tsapps.nist.gov/publication/get...
bigcode/self-oss-instruct-sc2-concepts
def state_root_hash(LIB) -> str: """Returns current state root hash @ NCTL Node 1. """ return LIB.get_state_root_hash()
bigcode/self-oss-instruct-sc2-concepts
def args_and_keywords(function): """ Return the information about the function's argument signature. Return a list of the function's positional argument names and a dictionary containing the function's keyword arguments. Example: >>> import random >>> args, kw = arg...
bigcode/self-oss-instruct-sc2-concepts
def select_line(editor): """ Select line under cursor @param editor: Editor instance @type editor: ZenEditor """ start, end = editor.get_current_line_range(); editor.create_selection(start, end) return True
bigcode/self-oss-instruct-sc2-concepts
def commonprefix(m): """Given a list of pathnames, returns the longest common leading component""" if not m: return '' s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_reference(s): """Normalize reference label. Collapse internal whitespace to single space, remove leading/trailing whitespace, case fold. """ return re.sub(r'\s+', ' ', s.strip()).upper()
bigcode/self-oss-instruct-sc2-concepts
import re def filterBlankChar(sourceStr): """filter whitespace characters in a string""" newStr = re.sub(r'[\f\n\r\t\v]+', '', sourceStr) return newStr.strip()
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 def connect_to_db(dbfile): """Create connection to sqlite DB. Args: dbfile (str): path to sqlite DB. Returns: Connection object. """ conn = sqlite3.connect(dbfile) return conn
bigcode/self-oss-instruct-sc2-concepts
def get_safe_seaborn_labels(dfr, labels): """Returns labels guaranteed to correspond to the dataframe.""" if labels is not None: return [labels.get(i, i) for i in dfr.index] return [i for i in dfr.index]
bigcode/self-oss-instruct-sc2-concepts
import codecs import json from typing import OrderedDict def load_scan(json_input): """ Return a list of scan results loaded from a json_input, either in ScanCode standard JSON format or the data.json html-app format. """ with codecs.open(json_input, 'rb', encoding='utf-8') as jsonf: scan ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def int_list_greater_than_zero(l: List[int]) -> bool: """ Return True if every element in list is >= 0, else False """ for i in l: if i < 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
def has_permission_logged_in(app, identity, model, permission): """ This permission rule matches all logged in identities. It requires the identity to have a 'role' attribute. Said role attribute is used to determine if the given permission is part of the given role. """ assert hasattr(identity, '...
bigcode/self-oss-instruct-sc2-concepts
import math def dist(p1, p2): """Finds distance between two Points""" return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Optional import types from typing import List import importlib def load_module_with_name(name: str) -> Tuple[Optional[types.ModuleType], List[str]]: """ Load the module given its name. Example identifier: some.module """ try: mod = importlib.imp...
bigcode/self-oss-instruct-sc2-concepts
from typing import Literal def sh_bool(boolean: bool) -> Literal["yes", "no"]: """ Formats a boolean to be passed to a bash script environment (eg run_job.sh) :param boolean: A boolean flag (True or False) :type boolean: bool :return: 'yes' or 'no' :rtype: str """ if boolean: ...
bigcode/self-oss-instruct-sc2-concepts
def generateListLocation(username, list_name): """ generates file placement in S3 based on standardized storage """ return username + '/' + list_name + '.txt'
bigcode/self-oss-instruct-sc2-concepts
import click def format_line_diff(base: str, other: str) -> str: """ Formats the line identifier of a change. :param base: The base line number(s). :param other: The other line number(s). :return: The formatted line numbers. """ buffer = [] if base: buffer.append(f"<{base}") ...
bigcode/self-oss-instruct-sc2-concepts
def create_points_from_polygons(gdf, method='midpoint'): """ Converts the geometry of a polygon layer to a point layer. Parameters ---------- gdf : geopandas.GeoDataFrame method : str Method to create a point from a polygon. Returns ------- geopandas.GeoDataFrame : GeoDataF...
bigcode/self-oss-instruct-sc2-concepts
def db(request): """ Returns an ODB connection (one of multiple kinds). """ connection = request.param return connection
bigcode/self-oss-instruct-sc2-concepts
from typing import List def sort_mode_autocomplete(ctx, args: List[str], incomplete: str): """ Auto-complete choices for --sort-by / -s argument """ entries = [ ('seeders', 'Sort by number of torrent seeders (default)'), ('date', 'Sort by upload date'), ('size', 'Sort by file ...
bigcode/self-oss-instruct-sc2-concepts
import re def _camel_to_snake(camel_string: str) -> str: """ Use regex to change camelCased string to snake_case Args: camel_string(str) Returns: A snake_cased string """ result = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_string) result = re.sub("(.)([0-9]+)", r"\1_\2",...
bigcode/self-oss-instruct-sc2-concepts
def gen_types(tally): """Selects the field type with the highest count. Also intelligently merges compatible types, e.g., 4 ints and 1 floats --> float. Args: tally (dict): Rows of data whose keys are the field names and whose data is a dict of types and counts. Yields: dic...
bigcode/self-oss-instruct-sc2-concepts
def _get_next_n_scores_from_prediction_reader(predictions, num_to_read): """ helper script to read a specific number of predictions from the predictions file :param RaasPredictionReader predictions: reader for raas prediction file :param num_to_read: number of answers to read :return: list of rank ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import json def load_config(app_environment) -> Dict: """Load configuration file from config.json""" with open('config.json', 'r') as config_file: config_dict = json.load(config_file) return config_dict
bigcode/self-oss-instruct-sc2-concepts