seed
stringlengths
1
14k
source
stringclasses
2 values
from typing import List from typing import Dict def get_author(author_list: List[Dict]) -> str: """Parse ChemRxiv dump entry to extract author list Args: author_list (list): List of dicts, one per author. Returns: str: ;-concatenated author list. """ return "; ".join( ["...
bigcode/self-oss-instruct-sc2-concepts
def read_conll_pos_file(path): """ Takes a path to a file and returns a list of word/tag pairs (This code is adopted from the exercises) """ sents = [] with open(path, 'r') as f: curr = [] for line in f: line = line.strip() if line == "": s...
bigcode/self-oss-instruct-sc2-concepts
def is_keymap_dir(keymap, c=True, json=True, additional_files=None): """Return True if Path object `keymap` has a keymap file inside. Args: keymap A Path() object for the keymap directory you want to check. c When true include `keymap.c` keymaps. json ...
bigcode/self-oss-instruct-sc2-concepts
import torch def recall(cm, mode='pos'): """ Recall: What fraction of ground truth labels was correct? Of all ground truth positive samples, what fraction was predicted positive? sensitivity = recall_pos = TP / (TP + FN) Similarly, of all ground truth negatives, what fraction was predicted ...
bigcode/self-oss-instruct-sc2-concepts
def concatenate_datasets(datasets): """/ concatenate single cell datasets Parameters ---------- datasets: list List of AnnData objects to be concatenate. Returns ------- :class:`~anndata.AnnData` adata """ adata = datasets[0].concatenate(datasets[1]) for i in range(2, len(datasets)): adata = adata.c...
bigcode/self-oss-instruct-sc2-concepts
import math def svp_from_t(t): """ Estimate saturation vapour pressure (*es*) from air temperature. Based on equations 11 and 12 in Allen et al (1998). :param t: Temperature [deg C] :return: Saturation vapour pressure [kPa] :rtype: float """ return 0.6108 * math.exp((17.27 * t) / (t ...
bigcode/self-oss-instruct-sc2-concepts
def formatColor3i(r,g,b): """3 ints to #rrggbb""" return '#%02x%02x%02x' % (r,g,b)
bigcode/self-oss-instruct-sc2-concepts
def read_string(file_pth): """ read in a file as a string """ with open(file_pth, encoding='utf8', errors='ignore') as file_obj: string = file_obj.read() return string
bigcode/self-oss-instruct-sc2-concepts
def _map_bins_to_labels(bins): """ Maps integers 0-99 to a label according to the distribution specified in `bins`. Example: bins = [10, 20] # implies bin sizes of 10 - 20 - 70 maps to => [0]*10 + [1]*20 + [2]*70 Note that if the integers in `bins` don't add up to 100, this function will ...
bigcode/self-oss-instruct-sc2-concepts
def get_supressed_alarms( self, ) -> dict: """Get configured supressed alarms .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - alarm - GET - /alarm/suppress :return: Returns dictionary of appliances and alarm t...
bigcode/self-oss-instruct-sc2-concepts
def _clean_roles(roles): """ Clean roles. Strips whitespace from roles, and removes empty items. Args: roles (str[]): List of role names. Returns: str[] """ roles = [role.strip() for role in roles] roles = [role for role in roles if role] return roles
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def datetime_str_to_obj(datetime_str): """ :param datetime_str: a string representation of a datetime as formatted in DICOM (YYYYMMDDHHMMSS) :return: a datetime object :rtype: datetime """ year = int(datetime_str[0:4]) month = int(datetime_str[4:6]) day =...
bigcode/self-oss-instruct-sc2-concepts
def _int_to_indices(value, length, bits): """Converts an integer value to indices in big endian order.""" mask = (1 << bits) - 1 return ((value >> (i * bits)) & mask for i in reversed(range(length)))
bigcode/self-oss-instruct-sc2-concepts
def formatdt(date, include_time=True): """Formats a date to ISO-8601 basic format, to minute accuracy with no timezone (or, if include_time is False, omit the time).""" if include_time: return date.strftime("%Y-%m-%dT%H:%M") else: return date.strftime("%Y-%m-%d")
bigcode/self-oss-instruct-sc2-concepts
import torch def calculate_wh_iou(box1, box2) -> float: """ calculate_wh_iou - Gets the Intersection over Union of the w,h values of the bboxes :param box1: :param box2: :return: IOU """ # RETURNS THE IOU OF WH1 TO WH2. WH1 IS 2, WH2 IS NX2 box2 = box2.t() # W, H = BOX...
bigcode/self-oss-instruct-sc2-concepts
import importlib def import_class(value): """Import the given class based on string. :param value: [path of the class] :type value: [str] :returns: [class object] :rtype: {[Object]} """ value, class_name = value.rsplit(".", 1) module = importlib.import_module(value) return getattr...
bigcode/self-oss-instruct-sc2-concepts
def hardness(s: str) -> float: """Get the element hardness.""" d = { 'h': 6.4299, 'he': 12.5449, 'li': 2.3746, 'be': 3.4968, 'b': 4.619, 'c': 5.7410, 'n': 6.8624, 'o': 7.9854, 'f': 9.1065, 'ne': 10.2303, 'na': 2.4441, 'mg': 3.0146, 'al': 3.5849, 'si': 4.1551, 'p': 4.7258, 's': 5.2960, 'c...
bigcode/self-oss-instruct-sc2-concepts
def database_connection_type(hostname, default_type): """ returns known DB types based on the hostname :param hostname: hostname from the URL :return: string type, or default type """ if 'rds.amazonaws' in hostname: return 'rds' if 'redshift.amazonaws' in hostname: return 're...
bigcode/self-oss-instruct-sc2-concepts
def two_fer(name=None): """Return a string with a message when given a name.""" if name==None: return "One for you, one for me." else: return f"One for {name.title()}, one for me."
bigcode/self-oss-instruct-sc2-concepts
def hyphenate(path): """Replaces underscores with hyphens""" return path.replace('_', '-')
bigcode/self-oss-instruct-sc2-concepts
def compute_score(parsed): """ If a node has no child node (len == 1), the score is the sum of the metadata, else the metadata are indexes of scores of child nodes. If an index does not exists, it is 0. """ score = 0 if len(parsed) == 1: # Only metadata score += sum(parsed['m...
bigcode/self-oss-instruct-sc2-concepts
def _read_from(file): """Read all content of the file, and return it as a string.""" with open(file, 'r') as file_h: return file_h.read()
bigcode/self-oss-instruct-sc2-concepts
def askyesno(question, default=True): """Ask a yes/no question and return True or False. The default answer is yes if default is True and no if default is False. """ if default: # yes by default question += ' [Y/n] ' else: # no by default question += ' [y/N] ' ...
bigcode/self-oss-instruct-sc2-concepts
def genomic_dup2_rel_38(genomic_dup2_seq_loc): """Create test fixture relative copy number variation""" return { "type": "RelativeCopyNumber", "_id": "ga4gh:VRC.WLuxOcKidzwkLQ4Z5AyH7bfZiSg-srFw", "subject": genomic_dup2_seq_loc, "relative_copy_class": "partial loss" }
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_iou(box1, box2): """Compute the intersection over union of two set of boxes, each box is [x1,y1,x2,y2]. Args: box1: (tensor) bounding boxes, sized [N,4]. box2: (tensor) bounding boxes, sized [M,4]. Return: (tensor) iou, sized [N,M]. """ lt = torch.max( ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def path_to_example(dataset): """ Construct a file path to an example dataset, assuming the dataset is contained in the 'example-data' directory of the abc-classroom package. Adapted from the PySAL package. Parameters ---------- dataset: string Name of a d...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Any from functools import reduce def product(it: Iterable[Any]) -> Any: """ Convolution product of iterable object Args: it: Iterable object Examples: >>> fpsm.product(range(6)) 120 """ return reduce(lambda x, y: x * y, i...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def create_copy_sql(table_name: str, stage_name: str, upload_key: str, file_format_name: str, columns: List): """Generate a CSV compatible snowflake COPY INTO command""" p_columns = ', '.join([c['name'] for...
bigcode/self-oss-instruct-sc2-concepts
import json def jsondump(data): """Return prettified JSON dump""" return json.dumps(data, sort_keys=True, indent=4)
bigcode/self-oss-instruct-sc2-concepts
def get_or_else(hashmap, key, default_value=None): """ Get value or default value Args: hashmap (dict): target key (Any): key default_value (Any): default value Returns: value of key or default_value """ value = hashmap.get(key) if value is None: return de...
bigcode/self-oss-instruct-sc2-concepts
import json def equal_list_of_dicts(obj1, obj2, exclude=[]): """Check whether two lists of dictionaries are equal, independent of the order within the list. Parameters ---------- obj1 : list of dict First object to compare obj2 : list of dict Second object to compare exclu...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random def generate_random_fill_holes(size: int) -> List[bool]: """ Generate a list of random bools of length size. :param size: length of list of random booleans to generate. """ return [bool(random.getrandbits(1)) for i in range(size)]
bigcode/self-oss-instruct-sc2-concepts
def KtoM(k): """ (number) -> number Returns miles from kilometers. >>> KtoM(5) 3.106855 >>> KtoM(9) 5.592339 """ return k * 0.621371
bigcode/self-oss-instruct-sc2-concepts
def B2s(bs): """ Switch bytes and string. """ if type(bs) == type(b''): return "".join(map(chr, bs)) else : return bytes([ord(c) for c in bs])
bigcode/self-oss-instruct-sc2-concepts
def get_flights_sorted_price(flights, reverse=False): """Return a list of flights sorted by price. Args: flights (list): list of flights, each flight is represented by a dictionary. reverse (bool, optional): defines the sorting order, by default to False - ascending, if ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def create_profile_path(input_profile_path: Path, profile_name: str, output_dir: Path) -> Path: """Create the name of the output profile by grabbing the ID of the input profile.""" profile_name = profile_name + input_profile_path.stem[len("Color LCD"):] + ".icc" return output_dir ...
bigcode/self-oss-instruct-sc2-concepts
def filterit(s): """ A functoin to filter out unnecessary characters from a sentece, helper for nBOW Args: s = Sentence returns: filtered Sentence """ s=s.lower() S='' for c in s: if c in ' abcdefghijklmnopqrstuvwxyz0123456789': if c.isdigit(): ...
bigcode/self-oss-instruct-sc2-concepts
def MaxPairwiseProduct_Better(array:list): """ Using 2 variables to store Top 2 Max Values in `array`. Single Pass O(n) """ if len(array) < 2: return 0 max1, max2 = array[0],array[1] for i in array[2:]: if i > max2: if i > max1: max1, max2 = i, max...
bigcode/self-oss-instruct-sc2-concepts
def slash_sort(fn): """Used to sort dir names by the number of slashes in them""" return fn.count("/")
bigcode/self-oss-instruct-sc2-concepts
import json def decode_workload_key(workload_key): """Decode the workload key from a string to the name and arguments. The wokrload key is expected to be a list of "[func_name/hash, args ...]" in a JSON string. If not, then simply return the workload key as the name without arguments. Parameters ...
bigcode/self-oss-instruct-sc2-concepts
def return_all_parameters_from_parameter_group(rds_client_obj, param_group): """ Returns all the parameters for a parameter group. """ parameters_to_return = [] pagination_token = None # Iterate through all parameters in parameter group and break out when appropriate. while(True): ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Tuple def get_results(conn, query: str, values: Optional[Tuple] = None): """Returns the results from a provided query at a given connection""" cursor = conn.cursor() cursor.execute(query, values) results = list(cursor) return results
bigcode/self-oss-instruct-sc2-concepts
def get_duplicates_from_cols(df, cols_to_use, what_to_keep='first'): """ Check duplicated rows by using the combination of multiple columns This is a workaround in the case where one doesn't have unique identifiers for a dataset :param pd.DataFrame df: :param list cols_to_use: columns to use to cre...
bigcode/self-oss-instruct-sc2-concepts
def HA(df, ohlc=None): """ Function to compute Heiken Ashi Candles (HA) Args : df : Pandas DataFrame which contains ['date', 'open', 'high', 'low', 'close', 'volume'] columns ohlc: List defining OHLC Column names (default ['Open', 'High', 'Low', 'Close']) Returns : df : Pandas ...
bigcode/self-oss-instruct-sc2-concepts
import functools import gc def disable_gc(f): """ Decorator to disable garbage collection during the execution of the decorated function. This can speed-up code that creates a lot of objects in a short amount of time. """ @functools.wraps(f) def wrapper(*args, **kwargs): gc.di...
bigcode/self-oss-instruct-sc2-concepts
def branch_text(branch): """ Takes and lxml tree element 'branch' and returns its text, joined to its children's tails (i.e. the content that follows childrens of 'branch'). """ texts = list(filter(lambda s: s != None, [branch.text] + [child.tail for child in branch])) if len(texts) == 0: ...
bigcode/self-oss-instruct-sc2-concepts
def splitCommas(s): """Split a string s containing items separated by commas into a list of strings. Spaces before or after each string are removed.""" items = s.split(",") return [ i.strip(" ") for i in items ]
bigcode/self-oss-instruct-sc2-concepts
def divide(a, b): """ Divides two numbers. Automatically raises ZeroDivisionError. >>> divide(3.0, 2.0) 1.5 >>> divide(1.0, 0) Traceback (most recent call last): ... ZeroDivisionError: float division by zero :param a: first number :param b: second number :return: qu...
bigcode/self-oss-instruct-sc2-concepts
def get_imperatives(tokens): """Identify, color and count imparative forms""" imperatives = [t for t in tokens if t.full_pos.endswith('IMP')] for t in imperatives: t.mode_color.append('Imperatives') return len(imperatives)
bigcode/self-oss-instruct-sc2-concepts
def get_target_rows(df): """Restrict data frame to rows for which a prediction needs to be made.""" df_target = df[ (df.action_type == "clickout item") & (df["reference"].isna()) ] return df_target
bigcode/self-oss-instruct-sc2-concepts
def row_to_dict(row, field_names): """Convert a row from bigquery into a dictionary, and convert NaN to None """ dict_row = {} for value, field_name in zip(row, field_names): if value and str(value).lower() == "nan": value = None dict_row[field_name] = value return d...
bigcode/self-oss-instruct-sc2-concepts
def parse_domains_and_ips(file_loc): """Reads the file and returns a dict with every domain we want to redirect and the respective address we want to redirect it to. Parameters: file_loc (str): the location of the file. Returns: dict: a dictionary whose keys are the domain...
bigcode/self-oss-instruct-sc2-concepts
def get_chunk(total, current, list): """ :param total: Total number of wanted chunks :param current: Current chunk position wanted :param list: List of data who will be chunked :return: The chunk """ length = len(list)//total start = current*length if current == total-1: ret...
bigcode/self-oss-instruct-sc2-concepts
def get_element(array): """ Get an element from an array of any depth. Args ---- array (Type of the element): Array we want to get an element Returns ------- Type of the element: One of the element of the array """ element = array[0] for i in...
bigcode/self-oss-instruct-sc2-concepts
import six import re def is_valid_mac(address): """Verify the format of a MAC address. Check if a MAC address is valid and contains six octets. Accepts colon-separated format only. :param address: MAC address to be validated. :returns: True if valid. False if not. """ m = "[0-9a-f]{2}(:...
bigcode/self-oss-instruct-sc2-concepts
def does_flavor_exist(nova_client, flavor_name): """ Check if flavor exists """ for flavor in nova_client.flavors.list(): if flavor.name == flavor_name: return True return False
bigcode/self-oss-instruct-sc2-concepts
def safe_value_fallback2(dict1: dict, dict2: dict, key1: str, key2: str, default_value=None): """ Search a value in dict1, return this if it's not None. Fall back to dict2 - return key2 from dict2 if it's not None. Else falls back to None. """ if key1 in dict1 and dict1[key1] is not None: ...
bigcode/self-oss-instruct-sc2-concepts
import math def Combinations(n, k): """Calculate the binomial coefficient, i.e., "n choose k" This calculates the number of ways that k items can be chosen from a set of size n. For example, if there are n blocks and k of them are bad, then this returns the number of ways that the bad blocks can be distrib...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def normalize_architecture(arch: str, variant: str) -> Tuple[str, str]: """ Normalize the passed architecture and variant. This is copying the same semantics used in https://github.com/moby/containerd/blob/ambiguous-manifest-moby-20.10/platforms/database.go """ arch, v...
bigcode/self-oss-instruct-sc2-concepts
def force2bytes(s): """ Convert the given string to bytes by encoding it. If the given argument is not a string (already bytes?), then return it verbatim. :param s: Data to encode in bytes, or any other object. :return: Bytes-encoded variant of the string, or the given argument verbatim. """ ...
bigcode/self-oss-instruct-sc2-concepts
def _get_build_data(build): """ Returns the given build model as formatted dict. Args: build (molior.model.build.Build): The build model. Returns: dict: The data dict. """ maintainer = "-" if build.maintainer: maintainer = "{} {}".format( build.maint...
bigcode/self-oss-instruct-sc2-concepts
def validate_certificateauthority_type(certificateauthority_type): """ CertificateAuthority Type validation rule. Property: CertificateAuthority.Type """ VALID_CERTIFICATEAUTHORITY_TYPE = ("ROOT", "SUBORDINATE") if certificateauthority_type not in VALID_CERTIFICATEAUTHORITY_TYPE: raise...
bigcode/self-oss-instruct-sc2-concepts
def writeweight(alloc, content_w, g_w, g_a): """Return write weighting `ww` Parameters ---------- alloc : `[batch_size, mem_size]`. content_w : `[batch_size, mem_size]`. g_w : `[batch_size, 1]`. g_a : `[batch_size, 1]`. Returns ------- ww : `[batch_size, mem_size]`. """ ...
bigcode/self-oss-instruct-sc2-concepts
def comp_joule_losses(self, out_dict, machine): """Compute the electrical Joule losses Parameters ---------- self : EEC_PMSM an EEC_PMSM object out_dict : dict Dict containing all magnetic quantities that have been calculated in comp_parameters of EEC machine : Machine a...
bigcode/self-oss-instruct-sc2-concepts
def get_fold_val(fold_test, fold_list): """ Get the validation fold given the test fold. Useful for cross-validation evaluation mode. Return the next fold in a circular way. e.g. if the fold_list is ['fold1', 'fold2',...,'fold10'] and the fold_test is 'fold1', then return 'fold2'. If the fold_...
bigcode/self-oss-instruct-sc2-concepts
def map_segs_xsens2ergowear(xsens_segs): """Map segments from xsens (23) to ergowear (9).""" return xsens_segs[..., [0, 4, 5, 8, 9, 10, 12, 13, 14], :]
bigcode/self-oss-instruct-sc2-concepts
def todep(name): """Convert a library name to an archive path or object file name.""" if name.startswith("-l"): name = name.replace("-l","",1) if name.startswith('toaru'): return (True, "%s/lib%s.so" % ('base/lib', name)) elif name.startswith('kuroko'): return (Tr...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def create_data_dir(run_dir): """ Create initial files for HADDOCK3 run. Returns ------- pathlib.Path A path referring only to 'data'. """ data_dir = Path(run_dir, 'data') data_dir.mkdir(parents=True, exist_ok=True) return data_dir
bigcode/self-oss-instruct-sc2-concepts
def split_key_value(key_value_str, delimiter='='): """ splits given string into key and value based on delimiter :param key_value_str: example string `someKey=somevalue` :param delimiter: default delimiter is `=` :return: [ key, value] """ key, value = key_value_str.split(delimiter) key...
bigcode/self-oss-instruct-sc2-concepts
def parse_labels_and_features(dataset): """Extracts labels and features. This is a good place to scale or transform the features if needed. Args: dataset: A Pandas `Dataframe`, containing the label on the first column and monochrome pixel values on the remaining columns, in row major order. Retu...
bigcode/self-oss-instruct-sc2-concepts
def gen_file_name(rank: int, file_ext: str) -> str: """ generate filename to write a DataFrame partition """ if rank < 10: numeric_ext = "000" + str(rank) elif rank < 100: numeric_ext = "00" + str(rank) elif rank < 1000: numeric_ext = "0" + str(rank) else: num...
bigcode/self-oss-instruct-sc2-concepts
def test_items_must_be_in_array_type(open_discovery_document, name, version): """ Test that all array types in disc docs have an attribute called "items". aiogoogle.validate.validate assumes all arrays has an "items" property and it will fail if it didn't find one """ disc_doc = open_discovery_document...
bigcode/self-oss-instruct-sc2-concepts
def valid_year(entry, minimum, maximum): """Validate four digit year entries.""" if len(entry) > 4: return False elif int(entry) >= minimum and int(entry) <= maximum: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def refreshAllSymbol(command, mySymbols): """ Check if command is to refresh all stock symbols. """ return (len(mySymbols) > 0 and (command.strip().lower() == "r" or command.strip().lower() == "refresh") and len(command) == 1)
bigcode/self-oss-instruct-sc2-concepts
def clamp(val, min, max): """ Clamp value between min/max values """ if val > max: return max if val < min: return min return val
bigcode/self-oss-instruct-sc2-concepts
def split_line(line): """ Converts a single input line into its elements. Result is a dict containing the keys low, high, letter and passwd. """ parts = line.split() numbers = parts[0].split("-") d = dict() d["low"] = int(numbers[0]) d["high"] = int(numbers[1]) d["letter"] =...
bigcode/self-oss-instruct-sc2-concepts
def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2...
bigcode/self-oss-instruct-sc2-concepts
def get_concordance(text, keyword, idx, window): """ For a given keyword (and its position in an article), return the concordance of words (before and after) using a window. :param text: text :type text: string :param keyword: keyword...
bigcode/self-oss-instruct-sc2-concepts
def no_op(*_, **__) -> None: """A function that does nothing, regardless of inputs""" return None
bigcode/self-oss-instruct-sc2-concepts
def synergy_rows_list(ws, signal_names): """ Params - ws: openpyxl worksheet object - signal_names: name given to the signal by the user, i.e., "CFP" Returns - rows: list of tuples, each containing ('signal', signal_row_position) """ rows = [(celda.value, celda.row) for...
bigcode/self-oss-instruct-sc2-concepts
def write(*args, **kwargs): """ Wrapper for print function or print to ensure compatibility with python 2 The arguments are used similarly as the print_function They can also be generalized to python 2 cases """ return print(*args, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
def sfl(L): """ (list) -> bool Precondition: len(L) >= 2 Return True if and only if first item of the list is same as last. >>> sfl([3, 4, 2, 8, 3]) True >>> sfl([a, b, c]) False """ return (L[0] == L[-1])
bigcode/self-oss-instruct-sc2-concepts
def flatten_dict(input_dict, parent_key='', sep='.'): """Recursive function to convert multi-level dictionary to flat dictionary. Args: input_dict (dict): Dictionary to be flattened. parent_key (str): Key under which `input_dict` is stored in the higher-level dictionary. sep (str): Sepa...
bigcode/self-oss-instruct-sc2-concepts
def mean(vals): """Calculate the mean of a list of values.""" return sum([v for v in vals])/len(vals)
bigcode/self-oss-instruct-sc2-concepts
def get_raffles_for_date_expanded(db, date, user_id, conf): """Get raffles for a specific date Args: db (psycopg2.connection): The db to generate a cursor date (datetime.date): The date to search for user_id (int): User id conf (Config): Configurations Returns: psyc...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def footprint_transpose(x: float, y: float) -> Tuple[float, float]: """A transform function to swap the coordinates of a shapely geometry Arguments: x {float} -- The original x-coordinate y {float} -- The original y-coordinate Returns: Tuple[float, float]...
bigcode/self-oss-instruct-sc2-concepts
import random def randint(start: int, end: int) -> int: """Returns a random integer""" return random.randint(start, end)
bigcode/self-oss-instruct-sc2-concepts
def helper_properties_def(properties): """ Convert properties from a Fiona datasource to a definition that is usable by `dict_reader_as_geojson` and utilizes the helper functions for better value handling. Sample input: { 'float_field': 'float:14', 'int_field': 'in...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import shutil def copy_to_tmp(origin: Path, dest: Path) -> Path: """ Copy `origin` to temp `dest` """ shutil.copy(origin.as_posix(), dest.as_posix()) return dest / origin.name
bigcode/self-oss-instruct-sc2-concepts
import random def init_neurons(count): """ Initialize the weights of the neurons :param count: number of neurons to initialize :return: list of neurons as weight vectors (x,y) """ return [[random.uniform(0.0, 1.0), random.uniform(0.0, 1.0)] for i in range(count)]
bigcode/self-oss-instruct-sc2-concepts
def custom_name_func(testcase_func, param_num, param): """Generates friendly names such as `test_syntax_while`.""" return "%s_%s" % (testcase_func.__name__, param.args[0])
bigcode/self-oss-instruct-sc2-concepts
def iodineIndex (Na2S2O3_molarity, Na2S2O3_fc, Na2S2O3_volume_spent, blank_volume, sample_weight): """ Function to calculate the iodine index in grams of iodine per 100g """ V_Na2S2O3 = blank_volume - Na2S2O3_volume_spent iodine_mols = (Na2S2O3_molarity * Na2S2O3_fc * V_Na2S2O3) / 2 iodine_mg = ...
bigcode/self-oss-instruct-sc2-concepts
def time_to_seconds(time): """Convert timestamp string of the form 'hh:mm:ss' to seconds.""" return int(sum(abs(int(x)) * 60 ** i for i, x in enumerate(reversed(time.replace(',', '').split(':')))) * (-1 if time[0] == '-' else 1))
bigcode/self-oss-instruct-sc2-concepts
def value2Tuple4(v): """Answers a tuple of 4 values. Can be used for colors and rectangles. >>> value2Tuple4(123) (123, 123, 123, 123) >>> value2Tuple4((2,3)) (2, 3, 2, 3) >>> value2Tuple4((2,3,4,5)) (2, 3, 4, 5) """ if not isinstance(v, (list, tuple)): v = [v] if len(v)...
bigcode/self-oss-instruct-sc2-concepts
import math def glow(radius=40): """Overlay a Gaussian blur with given radius (default 40)""" stdDev = math.floor(radius/2) return lambda g: f""" <filter id="glow"> <feGaussianBlur stdDeviation="{stdDev}" /> <feMerge> <feMergeNode /> <feMergeNode in="SourceGraphic" /> </feM...
bigcode/self-oss-instruct-sc2-concepts
def parked_vehicles(psvList): """ Get number of successfully parked vehicles. Args: psvList (list): List of parking search vehicle objects Returns: int: Number of parked vehicles """ return sum(1 for psv in psvList if psv.is_parked())
bigcode/self-oss-instruct-sc2-concepts
def false_discovery_rate(cm): """ false discovery rate (FDR) FDR = FP / (FP + TP) = 1 - PPV """ return cm[0][1] / float(cm[0][1] + cm[1][1])
bigcode/self-oss-instruct-sc2-concepts
def _get_iterator_device(job_name, task_id): """ Returns the iterator device to use """ if job_name != 'learner': return None return '/job:%s/task:%d' % (job_name, task_id)
bigcode/self-oss-instruct-sc2-concepts
def unicode_to_c_ustring(string): """Converts a Python unicode string to a C++ u16-string literal. >>> unicode_to_c_ustring(u'b\u00fccher.de') 'u"b\\\\u00fccher.de"' """ result = ['u"'] for c in string: if (ord(c) > 0xffff): escaped = '\\U%08x' % ord(c) elif (ord(c) > 0x7f): escap...
bigcode/self-oss-instruct-sc2-concepts
import torch def masked_mean(x, m=None, dim=-1): """ mean pooling when there're paddings input: tensor: batch x time x h mask: batch x time output: tensor: batch x h """ if m is None: return torch.mean(x, dim=dim) mask_sum = torch.sum(m, dim=-1) # ba...
bigcode/self-oss-instruct-sc2-concepts