seed
stringlengths
1
14k
source
stringclasses
2 values
def is_valid_id(id): """Check if id is valid. """ parts = id.split(':') if len(parts) == 3: group, artifact, version = parts if group and artifact and version: return True return False
bigcode/self-oss-instruct-sc2-concepts
def STD_DEV_SAMP(*expression): """ Calculates the sample standard deviation of the input values. Use if the values encompass a sample of a population of data from which to generalize about the population. See https://docs.mongodb.com/manual/reference/operator/aggregation/stdDevSamp/ for more details...
bigcode/self-oss-instruct-sc2-concepts
def misclassification_percentage(y_true, y_pred): """ Returns misclassification percentage ( misclassified_examples / total_examples * 100.0) """ misclassified_examples = list(y_true == y_pred).count(False) * 1. total_examples = y_true.shape[0] return (misclassified_examples / total_examples) * 100.0
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def _unique(*args: Iterable) -> list: """Return a list of all unique values, in order of first appearance. Args: args: Iterables of values. Examples: >>> _unique([0, 2], (2, 1)) [0, 2, 1] >>> _unique([{'x': 0, 'y': 1}, {'y': 1, 'x': 0}], [{'z':...
bigcode/self-oss-instruct-sc2-concepts
def linear_function(m, x, b): """ A linear function of one variable x with slope m and and intercept b. """ return m * x + b
bigcode/self-oss-instruct-sc2-concepts
import functools def dgetattr(obj, name, is_dict=False): """ get deep attribute operates the same as getattr(obj, name) but can use '.' for nested attributes e.g. dgetattr(my_object, 'a.b') would return value of my_object.a.b """ atr = dict.__getitem__ if is_dict else getattr names = name....
bigcode/self-oss-instruct-sc2-concepts
import json from pathlib import Path def get_total_epochs(save_path, run, last_gen): """ Compute the total number of performed epochs. Parameters ---------- save_path: str path where the ojects needed to resume evolution are stored. run : int curre...
bigcode/self-oss-instruct-sc2-concepts
def filter_same_tokens(tokens): """ Function for filtering repetitions in tokens. :param tokens: list with str List of tokens for filtering. :return: Filtered list of tokens without repetitions. """ if not isinstance(tokens, list): raise TypeError for token in toke...
bigcode/self-oss-instruct-sc2-concepts
import json def loads(json_str): """Load an object from a JSON string""" return json.loads(json_str)
bigcode/self-oss-instruct-sc2-concepts
def tag_case(tag, uppercased, articles): """ Changes a tag to the correct title case while also removing any periods: 'U.S. bureau Of Geoinformation' -> 'US Bureau of Geoinformation'. Should properly upper-case any words or single tags that are acronyms: 'ugrc' -> 'UGRC', 'Plss Fabric' -> 'PLSS Fabr...
bigcode/self-oss-instruct-sc2-concepts
def link_album(album_id): """Generates a link to an album Args: album_id: ID of the album Returns: The link to that album on Spotify """ return "https://open.spotify.com/album/" + album_id
bigcode/self-oss-instruct-sc2-concepts
def fetch_seq_pygr(chr, start, end, strand, genome): """Fetch a genmoic sequence upon calling `pygr` `genome` is initialized and stored outside the function Parameters ---------- chr : str chromosome start : int start locus end : int end locuse strand : str ...
bigcode/self-oss-instruct-sc2-concepts
def compute_metrics(y_true, y_pred, metrics): """ Computation of a given metric Parameters ---------- y_true: True values for y y_pred: Predicted values for y. metrics: metric Chosen performance metric to measure the model capabilities. Returns ------- d...
bigcode/self-oss-instruct-sc2-concepts
def centerOfGravity( array ): """ Vypočítá ze zadaých bodů jejich těžiště. Parametry: ---------- array: list Pole s body. Vrací: ----- list Pole s X- a Y-ovou souřadnicí těžiště. """ sum_X = 0 sum_Y = 0 # Sečte X-ové a Y-ové souřadnice ...
bigcode/self-oss-instruct-sc2-concepts
def rk4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. y is the initial value for y x is the initial value for x dx is the difference in x (e.g. the time step) f is a callable function (y, x) that you supply to compute dy/dx for the specified values. """ k1 = dx * f(y...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def add_parser_options(options: Dict[str, Dict[str, Any]], parser_id: str, parser_options: Dict[str, Dict[str, Any]], overwrite: bool = False): """ Utility method to add options for a given parser, to the provided options structure :par...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def distributed_axial(w:float, L:float, l1:float, l2:float) -> List[float]: """ Case 6 from Matrix Analysis of Framed Structures [Aslam Kassimali] """ Fa = w/(2*L) * (L-l1-l2) * (L-l1+l2) Fb = w/(2*L) * (L-l1-l2) * (L+l1-l2) return [Fa, Fb]
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def parse_time(time_string): """Parse a time string from the config into a :class:`datetime.time` object.""" formats = ['%I:%M %p', '%H:%M', '%H:%M:%S'] for f in formats: try: return datetime.strptime(time_string, f).time() except ValueError: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def format_link_object(url: str, text: str) -> Dict[str, str]: """ Formats link dictionary object. """ return {"href": url, "text": text}
bigcode/self-oss-instruct-sc2-concepts
def mul(args): """ Multiply the all the numbers in the list Args(list): A list of number Return(int or float): The computing result """ result = 1 for num in args: result *= num return result
bigcode/self-oss-instruct-sc2-concepts
import base64 def ddb_to_json(ddb_item): """Convert a DDB item to a JSON-compatible format. For now, this means encoding any binary fields as base64. """ json_item = ddb_item.copy() for attribute in json_item: for value in json_item[attribute]: if value == "B": ...
bigcode/self-oss-instruct-sc2-concepts
import pwd def valid_user(username): """ Returns True if the username given is a valid username on the system """ try: if username and pwd.getpwnam(username): return True except KeyError: # getpwnam returns a key error if entry isn't present return False re...
bigcode/self-oss-instruct-sc2-concepts
import time def datetime_to_timestamp(a_date): """Transform a datetime.datetime to a timestamp microseconds are lost ! :type a_date: datetime.datetime :rtype: float """ return time.mktime(a_date.timetuple())
bigcode/self-oss-instruct-sc2-concepts
import asyncio async def check_address(host: str, port: int = 80, timeout: int = 2) -> bool: """ Async version of test if an address (IP) is reachable. Parameters: host: str host IP address or hostname port : int HTTP port number Returns ------- awaitable bool "...
bigcode/self-oss-instruct-sc2-concepts
def convert_distance(val, old_scale="meter", new_scale="centimeter"): """ Convert from a length scale to another one among meter, centimeter, inch, feet, and mile. Parameters ---------- val: float or int Value of the length to be converted expressed in the original scale. old_scale...
bigcode/self-oss-instruct-sc2-concepts
def get_cell_connection(cell, pin): """ Returns the name of the net connected to the given cell pin. Returns None if unconnected """ # Only for subckt assert cell["type"] == "subckt" # Find the connection and return it for i in range(1, len(cell["args"])): p, net = cell["args"]...
bigcode/self-oss-instruct-sc2-concepts
import re def nest(text, nest): """ Indent documentation block for nesting. Args: text (str): Documentation body. nest (int): Nesting level. For each level, the final block is indented one level. Useful for (e.g.) declaring structure members. Returns: str: Indente...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import time def time_format(seconds: float, format_='%H:%M:%S') -> Union[str, float]: """ Default format is '%H:%M:%S' >>> time_format(3600) '01:00:00' """ # this because NaN if seconds >= 0 or seconds < 0: time_ = time.strftime(format_, time.gmtime(abs(s...
bigcode/self-oss-instruct-sc2-concepts
def validate_identifier(key: str): """Check if key starts with alphabetic or underscore character.""" key = key.strip() return key[0].isalpha() or key.startswith("_")
bigcode/self-oss-instruct-sc2-concepts
import struct def _single_byte_from_hex_string(h): """Return a byte equal to the input hex string.""" try: i = int(h, 16) if i < 0: raise ValueError except ValueError: raise ValueError("Can't convert hex string to a single byte") if len(h) > 2: raise ValueEr...
bigcode/self-oss-instruct-sc2-concepts
def mean(num_list): """ Computes the mean of a list of numbers Parameters ---------- num_list : list List of number to calculate mean of Returns ------- mean : float Mean value of the num_list """ # Check that input is of type list if not isinstance(num_li...
bigcode/self-oss-instruct-sc2-concepts
import csv def get_rows(input_tsv): """Parse input CSV into list of rows Keyword arguments: input_tsv -- input TSV containing study metadata Returns _csv.reader -- content of input file """ tsv_rows = csv.reader(open(input_tsv, 'r'), delimiter='\t') return tsv_rows # see tsv2xml....
bigcode/self-oss-instruct-sc2-concepts
def get_queue(conn, queue_name): """ Create a queue with the given name, or get an existing queue with that name from the AWS connection. """ return conn.get_queue(queue_name)
bigcode/self-oss-instruct-sc2-concepts
def check_reversibility(reaction): """ Return: - *forward* if reaction is irreversible in forward direction - *backward* if reaction is irreversible in the rbackward (reverse) direction - *reversible* if the reaction is reversible - *blocked* if the reactions is blocked """ if (react...
bigcode/self-oss-instruct-sc2-concepts
def summ_nsqr(i1, i2): """Return the summation from i1 to i2 of n^2""" return ((i2 * (i2+1) * (2*i2 + 1)) / 6) - (((i1-1) * i1 * (2*(i1-1) + 1)) / 6)
bigcode/self-oss-instruct-sc2-concepts
def _cost_to_qubo(cost) -> dict: """Get the the Q matrix corresponding to the given cost. :param cost: cost :return: QUBO matrix """ model = cost.compile() Q = model.to_qubo()[0] return Q
bigcode/self-oss-instruct-sc2-concepts
def base_count(DNA): """Counts number of Nucleotides""" return DNA.count('A'), DNA.count('T'), DNA.count('G'), DNA.count('C')
bigcode/self-oss-instruct-sc2-concepts
def alphabetical_value(name): """ Returns the alphabetical value of a name as described in the problem statement. """ return sum([ord(c) - 64 for c in list(str(name))])
bigcode/self-oss-instruct-sc2-concepts
def GetFilters(user_agent_string, js_user_agent_string=None, js_user_agent_family=None, js_user_agent_v1=None, js_user_agent_v2=None, js_user_agent_v3=None): """Return the optional arguments that should be saved and used to query. js_user_agent_string...
bigcode/self-oss-instruct-sc2-concepts
def filter_api_changed(record): """Filter out LogRecords for requests that poll for changes.""" return not record.msg.endswith('api/changed/ HTTP/1.1" 200 -')
bigcode/self-oss-instruct-sc2-concepts
def apply_decorators(decorators): """Apply multiple decorators to the same function. Useful for reusing common decorators among many functions.""" def wrapper(func): for decorator in reversed(decorators): func = decorator(func) return func return wrapper
bigcode/self-oss-instruct-sc2-concepts
import string def LazyFormat(s, *args, **kwargs): """Format a string, allowing unresolved parameters to remain unresolved. Args: s: str, The string to format. *args: [str], A list of strings for numerical parameters. **kwargs: {str:str}, A dict of strings for named parameters. Returns: str, Th...
bigcode/self-oss-instruct-sc2-concepts
def find_gcd(number1: int, number2: int) -> int: """Returns the greatest common divisor of number1 and number2.""" remainder: int = number1 % number2 return number2 if remainder == 0 else find_gcd(number2, remainder)
bigcode/self-oss-instruct-sc2-concepts
def rect_area(r): """Return the area of a rectangle. Args: r: an object with attributes left, top, width, height Returns: float """ return float(r.width) * float(r.height)
bigcode/self-oss-instruct-sc2-concepts
def ascii2int(str, base=10, int=int): """ Convert a string to an integer. Works like int() except that in case of an error no exception raised but 0 is returned; this makes it useful in conjunction with map(). """ try: return int(str, base) except: ...
bigcode/self-oss-instruct-sc2-concepts
def create_chord_progression(a_train=False): """Creates a midi chord progression Args: a_train (bool, optional): Defaults at False. If True, returns chord progression for Take the A Train by Duke Ellington. Otherwise, returns standard 12-bar blues in C major. Returns: (int, int)[...
bigcode/self-oss-instruct-sc2-concepts
import itertools def subsets(parent_set, include_empty=False, include_self=False): """ Given a set of variable names, return all subsets :param parent_set: a set, or tuple, of variables :return: a set of tuples, each one denoting a subset """ s = set() n = len(parent_set) for i in rang...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Optional def _guess_crs_str(crs_spec: Any)->Optional[str]: """ Returns a string representation of the crs spec. Returns `None` if it does not understand the spec. """ if isinstance(crs_spec, str): return crs_spec if hasattr(crs_spec, 'to_epsg')...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import List def unique_by(pairs: Iterable[tuple]) -> List: """Return a list of items with distinct keys. pairs yields (item, key).""" # return a list rather than a set, because items might not be hashable return list({key: item for item, key in pairs}.values())
bigcode/self-oss-instruct-sc2-concepts
def area_of_polygon(x, y): """Calculates the area of an arbitrary polygon given its verticies""" area = 0.0 for i in range(-1, len(x)-1): area += x[i] * (y[i+1] - y[i-1]) return abs(area) / 2.0
bigcode/self-oss-instruct-sc2-concepts
def _set_default_max_rated_temperature(subcategory_id: int) -> float: """Set the default maximum rated temperature. :param subcategory_id: the subcategory ID of the inductive device with missing defaults. :return: _rated_temperature_max :rtype: float """ return 130.0 if subcategory_id =...
bigcode/self-oss-instruct-sc2-concepts
def SimpleMaxMLECheck(BasinDF): """ This function checks through the basin dataframe and returns a dict with the basin key and the best fit m/n Args: BasinDF: pandas dataframe from the basin csv file. Returns: m_over_n_dict: dictionary with the best fit m/n for each basin, the key ...
bigcode/self-oss-instruct-sc2-concepts
import re def get_pkgver(pkginfo): """Extracts the APK version from pkginfo; returns string.""" try: pkgver = re.findall("versionName=\'(.*?)\'", pkginfo)[0] pkgver = "".join(pkgver.split()).replace("/", "") except: pkgver = "None" return pkgver
bigcode/self-oss-instruct-sc2-concepts
def getBBox(df, cam_key, frame, fid): """ Returns the bounding box of a given fish in a given frame/cam view. Input: df: Dataset Pandas dataframe cam_key: String designating the camera view (cam1 or cam2) frame: int indicating the frame which should be looked up fid: int ind...
bigcode/self-oss-instruct-sc2-concepts
def constituent_copyin_subname(host_model): ############################################################################### """Return the name of the subroutine to copy constituent fields to the host model. Because this is a user interface API function, the name is fixed.""" return "{}_ccpp_gather_const...
bigcode/self-oss-instruct-sc2-concepts
import codecs def check_encoding(stream, encoding): """Test, whether the encoding of `stream` matches `encoding`. Returns :None: if `encoding` or `stream.encoding` are not a valid encoding argument (e.g. ``None``) or `stream.encoding is missing. :True: if the encoding argument resolves...
bigcode/self-oss-instruct-sc2-concepts
def _list_distance(list1, list2, metric): """ Calculate distance between two lists of the same length according to a given metric. Assumes that lists are of the same length. Args: list1 (list): first input list. list2 (list): second input list. metric (str): 'identity' coun...
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Type def count_module_instances(model: torch.nn.Module, module_class: Type[torch.nn.Module]) -> int: """ Counts the number of instances of module_class in the model. Example: >>> model = nn.Sequential([nn.Linear(16, 32), nn.Linear(32, 64), nn.ReLU]) >>> cou...
bigcode/self-oss-instruct-sc2-concepts
def get_all_layers(model): """ Get all layers of model, including ones inside a nested model """ layers = [] for l in model.layers: if hasattr(l, 'layers'): layers += get_all_layers(l) else: layers.append(l) return layers
bigcode/self-oss-instruct-sc2-concepts
def escape_markdown(raw_string: str) -> str: """Returns a new string which escapes all markdown metacharacters. Args ---- raw_string : str A string, possibly with markdown metacharacters, e.g. "1 * 2" Returns ------- A string with all metacharacters escaped. Examples -----...
bigcode/self-oss-instruct-sc2-concepts
import csv def detect_csv_sep(filename: str) -> str: """Detect the separator used in a raw source CSV file. :param filename: The name of the raw CSV in the raw/ directory :type filename: str :return: The separator string :rtype: str """ sep = '' with open(f'raw/{filename}',"r") as cs...
bigcode/self-oss-instruct-sc2-concepts
def get_restraints(contact_f): """Parse a contact file and retrieve the restraints.""" restraint_dic = {} with open(contact_f) as fh: for line in fh.readlines(): if not line: # could be empty continue data = line.split() res_i = int(data[0]) ...
bigcode/self-oss-instruct-sc2-concepts
def easy_name(s): """Remove special characters in column names""" return s.replace(':', '_')
bigcode/self-oss-instruct-sc2-concepts
def skymapweights_keys(self): """ Return the list of string names of valid weight attributes. For unpolarized weights, this list includes only TT. Otherwise, the list includes all six unique weight attributes in row major order: TT, TQ, TU, QQ, QU, UU. """ if self.polarized: return ['T...
bigcode/self-oss-instruct-sc2-concepts
def one_lvl_colnames(df,cols,tickers): """This function changes a multi-level column indexation into a one level column indexation Inputs: ------- df (pandas Dataframe): dataframe with the columns whose indexation will be flattened. tickers (list|string): list/string with the tickers (...
bigcode/self-oss-instruct-sc2-concepts
def has_imm(opcode): """Returns True if the opcode has an immediate operand.""" return bool(opcode & 0b1000)
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterator def second(itr: Iterator[float]) -> float: """Returns the second item in an iterator.""" next(itr) return next(itr)
bigcode/self-oss-instruct-sc2-concepts
def _run_subsuite(args): """ Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. This helper lives at module-level and its arguments are wrapped in a tuple because of the multiprocessing module's requirements. """ runner_class, subsuite_index, subsuite, failfast = args ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def parse_seasons(seasons: List[str]): """Parses a string of seasons into a list of seasons. Used by main and by collect_course_length main""" parsed_seasons = [] for season in seasons: if re.match("[0-9]{4}\-[0-9]{4}", season): int_range = list(map(in...
bigcode/self-oss-instruct-sc2-concepts
def _copy_dict(dct, description): """Return a copy of `dct` after overwriting the `description`""" _dct = dct.copy() _dct['description'] = description return _dct
bigcode/self-oss-instruct-sc2-concepts
def poly_from_box(W, E, N, S): """ Helper function to create a counter-clockwise polygon from the given box. N, E, S, W are the extents of the box. """ return [[W, N], [W, S], [E, S], [E, N]]
bigcode/self-oss-instruct-sc2-concepts
def valfilterfalse(predicate, d, factory=dict): """ Filter items in dictionary by values which are false. >>> iseven = lambda x: x % 2 == 0 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> valfilterfalse(iseven, d) {2: 3, 4: 5} See Also: valfilter """ rv = factory() for k, v in d.items...
bigcode/self-oss-instruct-sc2-concepts
def yxbounds(shape1, shape2): """Bounds on the relative position of two arrays such that they overlap. Given the shapes of two arrays (second array smaller) return the range of allowed center offsets such that the second array is wholly contained in the first. Parameters ---------- shape1 ...
bigcode/self-oss-instruct-sc2-concepts
def parse_spec(spec, default_module): """Parse a spec of the form module.class:kw1=val,kw2=val. Returns a triple of module, classname, arguments list and keyword dict. """ name, args = (spec.split(':', 1) + [''])[:2] if '.' not in name: if default_module: module, klass = defaul...
bigcode/self-oss-instruct-sc2-concepts
def handle_returning_date_to_string(date_obj): """Gets date object to string""" # if the returning date is a string leave it as is. if isinstance(date_obj, str): return date_obj # if event time is datetime object - convert it to string. else: return date_obj.isoformat()
bigcode/self-oss-instruct-sc2-concepts
def getAtomNames(values): """ Assign to each value an atomname, O for negatives, H for 0 and N for positives. This function is created for assign atomnames for custom pdbs :param values: Collection of numbers to assing an atom name for :type values: iterable :returns: list ...
bigcode/self-oss-instruct-sc2-concepts
def event_loop_settings(auto_launch=True): """Settings for pyMOR's MPI event loop. Parameters ---------- auto_launch If `True`, automatically execute :func:`event_loop` on all MPI ranks (except 0) when pyMOR is imported. """ return {'auto_launch': auto_launch}
bigcode/self-oss-instruct-sc2-concepts
def mate_in_region(aln, regtup): """ Check if mate is found within region Return True if mate is found within region or region is None Args: aln (:obj:`pysam.AlignedSegment`): An aligned segment regtup (:tuple: (chrom, start, end)): Region Returns: bool: True if mate is within ...
bigcode/self-oss-instruct-sc2-concepts
def format_query(query, params=None): """ Replaces "{foo}" in query with values from params. Works just like Python str.format :type query str :type params dict :rtype: str """ if params is None: return query for key, value in params.items(): query = query.replace('...
bigcode/self-oss-instruct-sc2-concepts
def rename_dupe_cols(cols): """ Renames duplicate columns in order of occurrence. columns [0, 0, 0, 0] turn into [0, 1, 2, 3] columns [name10, name10, name10, name10] turn into [name10, name11, name12, name13] :param cols: iterable of columns :return: unique columns with digits increme...
bigcode/self-oss-instruct-sc2-concepts
def find_all(soup, first, second, third): """ A simpler (sorta...) method to BeautifulSoup.find_all :param soup: A BeautifulSoup object :param first: The first item to search for. Example: div :param second: the second aspect to search for. The key in the key:value pair. Example: class :param th...
bigcode/self-oss-instruct-sc2-concepts
def add_suffix_to_parameter_set(parameters, suffix, divider='__'): """ Adds a suffix ('__suffix') to the keys of a dictionary of MyTardis parameters. Returns a copy of the dict with suffixes on keys. (eg to prevent name clashes with identical parameters at the Run Experiment level) """ s...
bigcode/self-oss-instruct-sc2-concepts
def value_to_string(ast): """Remove the quotes from around the string value""" if ast.value[:3] in ('"""', "'''"): ast.value = ast.value[3:-3] else: ast.value = ast.value[1:-1] return ast
bigcode/self-oss-instruct-sc2-concepts
def module_of (object) : """Returns the name of the module defining `object`, if possible. `module_of` works for classes, functions, and class proxies. """ try : object = object.__dict__ ["Essence"] except (AttributeError, KeyError, TypeError) : pass result = getattr (object,...
bigcode/self-oss-instruct-sc2-concepts
import itertools def nQubit_Meas(n): """ Generate a list of measurement operators correponding to the [X,Y,Z]^n Pauli group Input: n (int): Number of qubits to perform tomography over Returns: (list) list of measurement operators corresponding to all combinations ...
bigcode/self-oss-instruct-sc2-concepts
import copy def make_all_strokes_dashed(svg, unfilled=False): """ Makes all strokes in the SVG dashed :param svg: The SVG, in xml.etree.ElementTree format :param unfilled: Whether this is an unfilled symbol :return: The resulting SVG """ stroke_elements = [ele for ele in svg.findall('.//*[...
bigcode/self-oss-instruct-sc2-concepts
def iter_copy(structure): """ Returns a copy of an iterable object (also copying all embedded iterables). """ l = [] for i in structure: if hasattr(i, "__iter__"): l.append(iter_copy(i)) else: l.append(i) return l
bigcode/self-oss-instruct-sc2-concepts
def tag_predicate(p): """ Given a full URI predicate, return a tagged predicate. So, for example, given http://www.w3.org/1999/02/22-rdf-syntax-ns#type return rdf:type """ ns = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#":"rdf:", "http://www.w3.org/2000/01/r...
bigcode/self-oss-instruct-sc2-concepts
def chunk(arr:list, size:int=1) -> list: """ This function takes a list and divides it into sublists of size equal to size. Args: arr ( list ) : list to split size ( int, optional ) : chunk size. Defaults to 1 Return: list : A new list containing the chunks of the original ...
bigcode/self-oss-instruct-sc2-concepts
def listify(x): """Convert item to a `list` of items if it isn't already a `list`.""" if not isinstance(x, list): return [x] return x
bigcode/self-oss-instruct-sc2-concepts
def find_missing_number(array): """ :param array: given integer array from 1 to len(array), missing one of value :return: The missing value Method: Using sum of list plus missing number subtract the list of the given array Complexity: O(n) """ n = len(array) expected_sum = (n + 1) * (n +...
bigcode/self-oss-instruct-sc2-concepts
def prune_nones_list(data): """Remove trailing None values from list.""" return [x for i, x in enumerate(data) if any(xx is not None for xx in data[i:])]
bigcode/self-oss-instruct-sc2-concepts
def get_clean_path_option(a_string): """ Typically install flags are shown as 'flag:PATH=value', so this function splits the two, and removes the :PATH portion. This function returns a tuple consisting of the install flag and the default value that is set for it. """ option, default = a_string....
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import List import re def parse_command(input: str) -> Tuple[str, List[str]]: """ Parse the command. :param input: The input to parse. :returns: Tuple of command, and a list of parameters to the command. """ input = input.strip() # Strip whitespace at sta...
bigcode/self-oss-instruct-sc2-concepts
def id_2_addr(hue_id): """ Convert a Phillips Hue ID to ISY Address """ return hue_id.replace(':', '').replace('-', '')[-14:]
bigcode/self-oss-instruct-sc2-concepts
def merge(novel_adj_dict, full_adj_dict): """ Merges adjective occurrence results from a single novel with results for each novel. :param novel_adj_dict: dictionary of adjectives/#occurrences for one novel :param full_adj_dict: dictionary of adjectives/#occurrences for multiple novels :return: full_...
bigcode/self-oss-instruct-sc2-concepts
def jinja2_lower(env, s): """Converts string `s` to lowercase letters. """ return s.lower()
bigcode/self-oss-instruct-sc2-concepts
def compute_cycle_length_with_denom(denom): """ Compute the decimal cycle length for unit fraction 1/denom (where denom>1) e.g. 1/6 has decimal representation 0.1(6) so cycle length is 1, etc """ digit_pos = 0 # Remaining fraction after subtracting away portions of earlier decimal digits fr...
bigcode/self-oss-instruct-sc2-concepts
def binary_to_ascii(binary_item): """ Convert a binary number to an ASCII char. """ str_number = str(binary_item) if str_number == '': return -1 decimal_number = int(str_number, 2) decoded = chr(decimal_number) return decoded
bigcode/self-oss-instruct-sc2-concepts
import shutil def read_binary(shared_dir, output_file): """ Read back binary file output from container into one string, not an iterable. Then remove the temporary parent directory the container mounted. :param shared_dir: temporary directory container mounted :param output_file: path to outp...
bigcode/self-oss-instruct-sc2-concepts