seed
stringlengths
1
14k
source
stringclasses
2 values
from typing import Callable def _node_not_implemented(node_name: str) -> Callable[..., None]: """ Return a function that raises a NotImplementedError with a passed node name. """ def f(self, *args, **kwargs): raise NotImplementedError(f"'{node_name}' nodes are not implemented") return f
bigcode/self-oss-instruct-sc2-concepts
def sorted_options(options): """Sort a sequence of options into canonical order. Return a list with the same elements as *options* sorted using the option :attr:`number<UrOption.number>` as the key. The sort is stable: options with the same number remain in their original order. This operation is...
bigcode/self-oss-instruct-sc2-concepts
def GenerateLibraryDescription(lib_name): """Generates a library description consisting of its full name and version. Args: lib_name: The name of the library for which a description is to be generated. Returns: A string description of the given library. """ tmp_lib = __import__('adspygoo...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def term_freq(tokens) -> dict: """ Takes in a list of tokens (str) and return a dictionary of term frequency of each token (doc = a list of tokens) """ #counting occurrences of each unique token term_count = Counter(tokens) #total number of tokens n_tokens = ...
bigcode/self-oss-instruct-sc2-concepts
def inverseTransform(tran): """ An SVG transform matrix looks like [ a c e ] [ b d f ] [ 0 0 1 ] And it's inverse is [ d -c cf - de ] [ -b a be - af ] * ( ad - bc ) ** -1 [ 0 0 1 ] And, no reasonable 2d coordi...
bigcode/self-oss-instruct-sc2-concepts
def element(a): """ Return the element """ return a.GetSymbol()
bigcode/self-oss-instruct-sc2-concepts
def get_class_plural_name(cls): """Convert class name to it's plural form""" base = cls.__name__.lower() for ending in ('s', 'z', 'x', 'ch', 'sh'): if base.endswith(ending): return base + 'es' if base.endswith('y'): return base[:-1] + 'ies' else: return base + 's'
bigcode/self-oss-instruct-sc2-concepts
def drop_col(df, col): """ If a pandas.DataFrame has a particular column, drop it. args ---- df : pandas.DataFrame col : str returns ------- pandas.DataFrame, same DataFrame without column """ if col in df.columns: df = df.drop(col, axi...
bigcode/self-oss-instruct-sc2-concepts
def print_deps_stdout_arg(request): """Argument for printing deps to stdout""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def read_map_file(file_name): """ reads a map file generated by TI's ARM compiler. the function expects a file of a form similar to: . . . GLOBAL SYMBOLS: SORTED BY Symbol Address address name ------- ---- 00000000 __TI_static_base__ 00000000 g_pfnVectors 00000200 __S...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List def process_dorms(dorms: Union[str, None] = None, size: Union[int, None] = None, default_dorm: str = 'Unknown', dorm_separator: Union[str, None] = None) -> List[List[str]]: """Process the dorms. Args: ...
bigcode/self-oss-instruct-sc2-concepts
def N_bar(tree): """ Returns the $\bar{N}$ statistic: the average number of nodes above a terminal node. """ leaf_count = 0 nbar = 0 for leaf_node in tree.leaf_node_iter(): leaf_count += 1 for parent in leaf_node.ancestor_iter(inclusive=False): nbar += 1 retur...
bigcode/self-oss-instruct-sc2-concepts
def osm_area_sql(grid, osm, cat): """ Returns a sql fragment that sums the total area by category of a grid cell coverd by OSM polygon features Args: grid (string): a PostGIS table name containing the grid osm (string): a PostGIS table name containing the OSM polygon features ca...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def get_record_code(record: dict[str, Any]) -> str: """Returns the concatenated codes for a taric record.""" return f"{record['record_code']}{record['subrecord_code']}"
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def get_soup(request, element, class_value): """ Uses the BeautifulSoup library to retrieve the HTML text for a given webpage request. :param request: The webpage request for which the HTML text is to be retrieved. :param element: The element of the webpag...
bigcode/self-oss-instruct-sc2-concepts
def _write_url_file(images, separator=" "): """ ImageNet generally uses a specific format to store the URLs of images. This converts a set of images into this format. Args: images: The set of images to write. It should contain tuples with image WNIDs and URLs. separator: Default string used to separat...
bigcode/self-oss-instruct-sc2-concepts
import pathlib from typing import Union def _should_granule_be_processed( filename: str, save_dir: pathlib.Path, order_number: Union[str, int] ) -> bool: """ Return True iff the given granule should be processed (i.e. has not yet been saved) Args: filename (str): Name of the granule `.h5` fil...
bigcode/self-oss-instruct-sc2-concepts
def _merge_keys(dicts): """Return the union of the keys in the list of dicts.""" keys = [] for d in dicts: keys.extend(d.keys()) return frozenset(keys)
bigcode/self-oss-instruct-sc2-concepts
def is_list_of_dict(value): """ Check if value is a non-empty list of dictionaries """ return isinstance(value, list) and len(value) > 0 and all(isinstance(elem, dict) for elem in value)
bigcode/self-oss-instruct-sc2-concepts
def nav_active(context, item): """ Returns 'active' is item is the active nav bar item, and '' otherwise. """ default = '' try: url_name = context['request'].resolver_match.url_name except: return default if url_name == item: return 'active' return default
bigcode/self-oss-instruct-sc2-concepts
from typing import IO from typing import Any from pathlib import Path def containing_directory(file_object: IO[Any]) -> Path: """Return the directory containing the given file.""" return Path(file_object.name).parent.absolute()
bigcode/self-oss-instruct-sc2-concepts
import re def GetVersion(path): """Get the version of this python tool.""" version_str = 'XWalk packaging tool version ' file_handle = open(path, 'r') src_content = file_handle.read() version_nums = re.findall(r'\d+', src_content) version_str += ('.').join(version_nums) file_handle.close() return vers...
bigcode/self-oss-instruct-sc2-concepts
import re def find_ip(url): """ Find IP address in string (code from dusty 1.0) """ ip_pattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s') # pylint: disable=W1401 ip_value = re.findall(ip_pattern, url) return ip_value
bigcode/self-oss-instruct-sc2-concepts
from typing import List def l2s(inputs: List) -> List[str]: """ Transforms a list into list of strings. :param inputs: objects :return: list of str(object) """ return [str(inp) for inp in inputs]
bigcode/self-oss-instruct-sc2-concepts
def readIdentificationFile(infile, sep="\t"): """ read lines from a peptide identification file and store the column split version of those lines (without header) in a list. (return: list of peptide identifications as list of identification ) infile: file containing identification lines (like output of I...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def parse_node_id(node_id: str) -> Dict: """ 解析节点ID :param node_id: 节点ID "host|instance|host|123" :return: { "object_type": "HOST", "node_type": "INSTANCE", "type": "host", "id": 123, } """ object_type, node_type, _type, _id = node_id...
bigcode/self-oss-instruct-sc2-concepts
def intsqrt(x): """ Return the largest integer whose square is less than or equal to x. """ if x == 0: return 0 # invariant: l^2 <= x and x < r^2 l = 1 r = x while r-l > 1: m = l + (r-l)//2 s = m*m if s <= x: l = m else: r =...
bigcode/self-oss-instruct-sc2-concepts
def _rchild(i): """ Returns the right child node of the given node. """ return 2 * i + 2
bigcode/self-oss-instruct-sc2-concepts
def make_list(string): """Make a list of floats out of a string after removing unwanted chars.""" l1 = string.strip('[] \n') l2 = l1.split(',') return [float(c.strip()) for c in l2]
bigcode/self-oss-instruct-sc2-concepts
def vcross(self, labxr="", labyr="", labzr="", labx1="", laby1="", labz1="", labx2="", laby2="", labz2="", **kwargs): """Forms element table items from the cross product of two vectors. APDL Command: VCROSS Parameters ---------- labxr, labyr, labzr Label assigned to X, Y, and Z-...
bigcode/self-oss-instruct-sc2-concepts
def get_last_lines_from_file(file_localtion, x=50): """ returns an array of the last x lines of a file """ with open(file_localtion, "r") as the_file: lines = the_file.readlines() last_lines = lines[-x:] return last_lines
bigcode/self-oss-instruct-sc2-concepts
def memoized_triple_step(step): """Find number of step combinations for maximum of three steps at a time :param step Number of steps left :return Number of step combinations """ if step < 0: return 0 elif step == 0: return 1 return memoized_triple_step(step - 3) + \ ...
bigcode/self-oss-instruct-sc2-concepts
def get_action(mod_line): """Function to return the type of action requested by the user for a given module, using the pavilion configuration syntax. The string can be in one of three formats: 1) '[mod-name]' - The module 'mod-name' is to be loaded. 2) '[old-mod-name]->[mod-name]' - The...
bigcode/self-oss-instruct-sc2-concepts
def qualified_name_tuple(cls): """ Get the module name and the thing-name for a class. e.g. ('instakit.processors.halftone', 'FloydSteinberg') """ mod_name = getattr(cls, '__module__') cls_name = getattr(cls, '__qualname__', getattr(cls, '__name__')) return mod_name, cls_name
bigcode/self-oss-instruct-sc2-concepts
def recursive_node_count(sll): """Solution to exercise R-7.3. Describe a recursive algorithm that counts the number of nodes in a singly linked list. """ def recurse(node, count): if node is None: # Base case, found tail of linked list return count return recurse(node....
bigcode/self-oss-instruct-sc2-concepts
def with_lock(lock, fn): """ Call fn with lock acquired. Guarantee that lock is released upon the return of fn. Returns the value returned by fn, or raises the exception raised by fn. (Lock can actually be anything responding to acquire() and release().) """ lock.acquire() try...
bigcode/self-oss-instruct-sc2-concepts
def dailyLow (lowTemps, date): """Finds the low temperature for date in question. .. warning: Assumes date has been validated using dateValidation and that data exists for date in question using dataAvailable. :param list lowTemps: Low temperatures for given month :param date: Date (Mo...
bigcode/self-oss-instruct-sc2-concepts
def byte_to_gb(byte): """Convert bytes to GB""" return byte / (1024.0 * 1024 * 1024)
bigcode/self-oss-instruct-sc2-concepts
def accesskey(request): """Get the accesskey from command line. Arguments: request: Gives access to the requesting test context. Returns: A accesskey from command line. """ return request.config.getoption("--accesskey")
bigcode/self-oss-instruct-sc2-concepts
def b2b_ipv4_devices(b2b_raw_config, tx_port, rx_port): """Returns a list of ipv4 tx device and rx device objects Each device object is ipv4, ethernet and vlan """ tx_device, rx_device = b2b_raw_config.devices.device().device() tx_device.name, rx_device.name = "Tx Devices Ipv4", "Rx Devices Ipv4" ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def timestamp_as_number_formatter(row: Dict, field: str): """ Useful for JQGrids where we want to send down time as a timestamp so we can put it in the user's timezone :param row: JQGrid row object :param field: field to access row (row[field] should be a timestamp) :return...
bigcode/self-oss-instruct-sc2-concepts
def safe_union_two_by_name(df1, df2): """Combine common fields from two dataframes rowwise. Note we do not use the ``pyspark.sql.DataFrame.unionByName`` function here because we explicitly reorder columns to the order of ``take``. Parameters ---------- df1 : pyspark.sql.DataFrame f...
bigcode/self-oss-instruct-sc2-concepts
def filter_labels_by_occlusion(obj_labels, occlusion): """Filters object labels by truncation. Args: obj_labels: List of object labels occlusion: Maximum occlusion Returns: obj_labels: List of filtered labels occ_mask: Mask of labels to keep """ occ_mask = [obj_labe...
bigcode/self-oss-instruct-sc2-concepts
def _mpi_command(nprocs, mpi_exec): """ Generate a string for shell execution of MPI. If the number of processors is 1 or the executable path is empty, the returned value is simply an empty string. Args: nprocs (int): Number of processors to use. mpi_exec (str): Path to MPI executable. ...
bigcode/self-oss-instruct-sc2-concepts
def get_dimensions(partitioning_config): """Retrieve the list of partition dimension names. Args: partitioning_config (dict): Dictionary of partitioning variables. Returns: List of dimensions. """ dimensions_dict = partitioning_config.get("dimensions") dimensions = [] types...
bigcode/self-oss-instruct-sc2-concepts
def _safe_conversion(value, converter, default=None): """Pipes a value through a converter function and returns the converted value or the default value if there was an exception during the conversion. Args: value: the value to convert converter (callable): a callable that converts the valu...
bigcode/self-oss-instruct-sc2-concepts
import torch def l1_normalize(x: torch.Tensor, eps: float = 1e-12) -> torch.Tensor: """Normalizes the input tensor using L1-norm. Args: x: Tensor to be normalized. eps: Small value to avoid division by zero. Returns: Normalized tensor. """ return x / (torch.norm(x, p=1, ...
bigcode/self-oss-instruct-sc2-concepts
def _estimate_crosscovar(cweights, proppts, mean, sigpts, mpred): """See BFaS; p.88. Parameters ---------- cweights: np.ndarray, shape (2*dimension + 1,) Constant kernels weights for unscented transform. sigpts: np.ndarray, shape (2*dimension + 1, dimension) Sigma points mpred: ...
bigcode/self-oss-instruct-sc2-concepts
def _matplotlib_list(interval_list): """ Returns lists for matplotlib ``fill`` command from a list of bounding rectangular intervals """ xlist = [] ylist = [] if len(interval_list): for intervals in interval_list: intervalx = intervals[0] intervaly = intervals...
bigcode/self-oss-instruct-sc2-concepts
def fp_boyer_freqs(ups_r, ups_theta, ups_phi, gamma, aa, slr, ecc, x, M=1): """ Boyer frequency calculation Parameters: ups_r (float): radial frequency ups_theta (float): theta frequency ups_phi (float): phi frequency gamma (float): time frequency aa (float): spin pa...
bigcode/self-oss-instruct-sc2-concepts
def float_eq( a, b, err=1e-08): """ Check if floats a and b are equal within tolerance err @return boolean """ return abs(a - b) <= err
bigcode/self-oss-instruct-sc2-concepts
def _make_type (vendor, field): """ Takes an NXM vendor and field and returns the whole type field """ return (vendor << 7) | field
bigcode/self-oss-instruct-sc2-concepts
def naming_convention(dic, convert): """ Convert a nested dictionary from one convention to another. Args: dic (dict): dictionary (nested or not) to be converted. convert (func): function that takes the string in one convention and returns it in the other one. Ret...
bigcode/self-oss-instruct-sc2-concepts
def _check_filter(filter_, stix_obj): """Evaluate a single filter against a single STIX 2.0 object. Args: filter_ (Filter): filter to match against stix_obj: STIX object to apply the filter to Returns: True if the stix_obj matches the filter, False if not. """ # Fo...
bigcode/self-oss-instruct-sc2-concepts
def gen_query_filters_mock(mocker): """Mock _apply_general_query_filters""" def return_search_arg( search, *args ): # pylint: disable=missing-docstring,unused-argument return search return mocker.patch( "search.api._apply_general_query_filters", side_effect=return_search_arg ...
bigcode/self-oss-instruct-sc2-concepts
def get_etr(etr_t, R_dash_vnt_rtd, V_rtd_SA, V_rtd_RA): """定格条件における補正風量比での熱通過有効度 Args: etr_t(float): 熱交換型換気設備の温度交換効率 R_dash_vnt_rtd(float): 定格条件における補正風量比 V_rtd_SA(float): 定格条件における給気風量 V_rtd_RA(float): 定格条件における還気風量 Returns: float: 定格条件における補正風量比での熱通過有効度 """ # (12) ...
bigcode/self-oss-instruct-sc2-concepts
def botcommand(*names): """Mark function as command. (for extensions) Parameters ---------- *names : str Name/s to invoke the command. Default: name of function. """ def decorator(func): command_names = names if names != () else func.__name__ func.command...
bigcode/self-oss-instruct-sc2-concepts
def _return_slave(index, parsed_args): """Gives the slave index name.""" return index + parsed_args.suffix
bigcode/self-oss-instruct-sc2-concepts
def arch_sampling_str_to_dict(sampling_str): """ Converts string representations of architecutre sampling methodology to the dictionary format that nas_searchmanager.SearchManager uses. Example: \"1:4,2:4,3:4,4:4\" is converted to {1.0 : 4, 2.0 : 4, 3.0 : 4, 4.0 : 4}. """ # Remove ...
bigcode/self-oss-instruct-sc2-concepts
def find_max_weight(regions): """Find the maximal weight in the given regions""" mw = 0 for r in regions: mw = max(mw, r.profEntry.weight) return mw
bigcode/self-oss-instruct-sc2-concepts
import pathlib import json def load_fixture(name: str): """Load a fixture from disk.""" path = pathlib.Path(__file__).parent / "fixtures" / name content = path.read_text() if name.endswith(".json"): return json.loads(content) return content
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random def get_quote_funfact(text_list: List[str]) -> str: """ Utility to get random text from given list. """ return random.choice(text_list)
bigcode/self-oss-instruct-sc2-concepts
def float_approximates(float_a, float_b, error=1e-6): """Returns whether float a is approximately b within error tolerance""" return abs(float_a-float_b) < error
bigcode/self-oss-instruct-sc2-concepts
def crop(x, area): """ * inputs: - x (torch.Tensor, required) A torch tensor of shape (N, C, H, W) is assumed. - area (sequence, required) A sequence of length 2 ((X, Y), (W, H)) is assumed. sequence[0] (X, Y) is the left corner of an area to be cr...
bigcode/self-oss-instruct-sc2-concepts
def seqs_from_dict(seqs, Alphabet=None): """SequenceCollection from dict of {label:seq_as_str}. This is an InputHandler for SequenceCollection. It converts a dict in which the keys are the names and the values are the sequences (sequence only, no whitespace or other formatting) into a SequenceC...
bigcode/self-oss-instruct-sc2-concepts
import torch def one_hot_embedding(labels, num_classes): """ 将标签嵌入成one-hot形式 :param labels: 标签,(LongTensor)类别标签,形状[N,] :param num_classes: 类别数, :return:(tensor)被编码的标签,形状(N,类别数) """ # 返回2维张量,对角线全是1,其余全是0 y = torch.eye(num_classes) return y[labels]
bigcode/self-oss-instruct-sc2-concepts
def get_type(string): """Returns type of debit/credit card according to first number of card number""" initial_digit = string[0] card_type = { "3": "American Express", "4": "Visa", "5": "MasterCard", "6": "Discover Card"} if initial_digit not in list(card_type.keys()): ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def size2shape(size: int) -> Tuple[int, int]: """convert a plate size (number of wells) to shape (y, x)""" assert size in [384, 1536] return (16, 24) if size == 384 else (32, 48)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def prepend_timestamp(line): """Add ISO 8601 timestamp to line""" timestamp = datetime.now().replace(microsecond=0).isoformat() return "{} {}".format(timestamp, line)
bigcode/self-oss-instruct-sc2-concepts
def my_function(a: int, b: int) -> int: """Add two numbers together Parameters ---------- a: int first integer b: int second integer Raises ------ value errror if a == 0 Examples -------- >>> my_function(1, 2) 3 >>> my_function(0, 2) Tracebac...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup import re def get_links(html_page, base_url): """gets all links from html Parameters ------ html_page (str): document html base_url (str): the original URL supplied Returns ------ list: list of all the links in the html document these could be fi...
bigcode/self-oss-instruct-sc2-concepts
def sizeof_fmt(num: int, suffix: str = "o") -> str: """ Human readable version of file size. Supports: - all currently known binary prefixes (https://en.wikipedia.org/wiki/Binary_prefix) - negative and positive numbers - numbers larger than 1,000 Yobibytes - arbitrary units ...
bigcode/self-oss-instruct-sc2-concepts
def _get_total_citation_by_year(l, max_year=2015): """ Calculate the total citation by year :param l: list of (year, citation) tuple :param max_year: the maximal year :return: dict with the totatl number of citation in each year """ min_year = int(min([y for y, v in l])) total_citations...
bigcode/self-oss-instruct-sc2-concepts
def _get_env_var(repository_ctx, name): """Find an environment variable.""" if name in repository_ctx.os.environ: return repository_ctx.os.environ[name] else: return None
bigcode/self-oss-instruct-sc2-concepts
def prep_phrase(args, premise, verbose=True): """Check whether there is prepositional phrase in premise.""" # Collect prepositions preps = [t for t in premise.tokens if t.deprel == 'prep'] if preps: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def path_crawler(hm, path=['A'], paths=[]): """Given a matrix, return a list of all available paths It works similarly to Depth-First Search. Starting from a root element, it recursively iterates down a single path until it reaches the terminal. It returns the given path, and works its way back up...
bigcode/self-oss-instruct-sc2-concepts
def get_fibonacci_sequence(length: int) -> list: """Return the fibonacci sequence to the specified length.""" fibonacci_sequence = [0, 1] if length == 1: return [fibonacci_sequence[0], ] elif length == 2: return fibonacci_sequence for _ in range(0, length - 2): second_to_las...
bigcode/self-oss-instruct-sc2-concepts
import re def edit_code(row, oc4ids_codes, source): """ If the row's "Code" is in the ``oc4ids_codes`` list, adds " or project" after "contracting process" in the row's "Description" and sets the row's "Source" to ``"OC4IDS"``. Otherwise, sets the row's "Source" to ``source``. """ if row['Code'] i...
bigcode/self-oss-instruct-sc2-concepts
def coalesce(*args): """Return the first argument which is not None. If all arguments are None, return None.""" for a in args: if a is not None: return a return None
bigcode/self-oss-instruct-sc2-concepts
def get_hyphen_exp(text: str, nlp): """ Returns a list of all hyphen expressions contained in the text :param text: string :param nlp: spacy language model :return: list of hyphen expressions contained in text """ doc = nlp(text) token_list = [token.text for token in doc] hyphen_exp...
bigcode/self-oss-instruct-sc2-concepts
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if len(options) > 1: buttons = [] for i in range(min(5, len(options))): buttons.appe...
bigcode/self-oss-instruct-sc2-concepts
def sum_fuel_enduse_sectors(data_enduses, enduses): """Aggregate fuel for all sectors according to enduse Arguments -------- data_enduses : dict Fuel per enduse enduses : list Enduses nr_fueltypes : int Number of fuetlypes Returns ------- aggregated_fuel_end...
bigcode/self-oss-instruct-sc2-concepts
def split_url(url): """split a zmq url (tcp://ip:port) into ('tcp','ip','port').""" proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis return proto,a...
bigcode/self-oss-instruct-sc2-concepts
def get_A_f(A_HCZ, r_Af): """敷設面積 Args: A_HCZ(float): 暖冷房区画の床面積 (m2) r_Af(float): 床暖房パネルの敷設率 Returns: float: 敷設面積 """ return A_HCZ * r_Af
bigcode/self-oss-instruct-sc2-concepts
def is_topk_evaluator(evaluator_keys): """Are these evaluator keys from TopK evaluator?""" return (len(evaluator_keys) == 5 and evaluator_keys[0] == 'top_1' and evaluator_keys[1] == 'top_2' and evaluator_keys[2] == 'top_3' and evaluator_keys[3] == 'top_4' and evalua...
bigcode/self-oss-instruct-sc2-concepts
def get_dataset_mean_std(kind): """Get mean and std of a dataset for normalization.""" if kind == "epic": mean = [0.412773, 0.316411, 0.278039] std = [0.222826, 0.215075, 0.202924] elif kind == "gtea": mean = [0.555380, 0.430436, 0.183021] std = [0.132028, 0.139590, 0.123337]...
bigcode/self-oss-instruct-sc2-concepts
def check_for_take(string: str) -> bool: """ Helper Function that checks to see if clapperboard elements follows set of rules to be identified as a "take" element Parameters ---------- string: String (The string thay will be checked Returns ------- Boolean True if ...
bigcode/self-oss-instruct-sc2-concepts
import ast def parse_source_file(filename): """Parse source file into AST node Parameters ---------- filename : str File path Returns ------- node : AST node content : utf-8 encoded string """ # can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't ...
bigcode/self-oss-instruct-sc2-concepts
def fibonacci(n): """Returns n fibonacci numbers Args: n: number of fibonacci numbers to return Returns: List that contains n fibonacci numbers Raises: ValueError when n is not a positive integer """ if n < 1: raise ValueError("n must be a posit...
bigcode/self-oss-instruct-sc2-concepts
def to_tuple(d): """ Expects dict with single key, returns tuple. >>> to_tuple({'a': 1}) ('a', 1) """ return next(iter(d.items()))
bigcode/self-oss-instruct-sc2-concepts
def slice_list(list_a: list, start: int, end: int): """Problem 18: Extract a slice from list. Parameters ---------- list_a : list The input list start : int The start of the slice end : int The end of the slice Returns ------- list A slice of the ini...
bigcode/self-oss-instruct-sc2-concepts
def merge(d1, d2): """Merges d2 into d1 without overwriting keys.""" left = d1.copy() right = d2.copy() for key in right.keys(): if key in left: left_is_dict = isinstance(left[key], dict) right_is_dict = isinstance(right[key], dict) if left_is_dict and right...
bigcode/self-oss-instruct-sc2-concepts
def multiply(value, multiplier): """ Multiplies two values together. Usage: >>> multiply(5, 2) 10 """ return value * multiplier
bigcode/self-oss-instruct-sc2-concepts
def provider2network(provider): """ Convert a MADIS network ID to one that I use, here in IEM land""" if provider in ['KYMN']: return provider if provider == 'MesoWest': return 'VTWAC' if len(provider) == 5 or provider in ['KYTC-RWIS', 'NEDOR']: if provider[:2] == 'IA': ...
bigcode/self-oss-instruct-sc2-concepts
def match_code(code:str, raw_line:bytes)->bool: """returns True if code is met at the beginning of the line.""" line = raw_line.decode("ascii") return line.startswith(code + " ") or line.startswith(code + ";")
bigcode/self-oss-instruct-sc2-concepts
def get_linked_info(issue): """ for the given issue, if "[Dd]uplicates: <org>/<repo>#XXX exists in PR body, returns the parsed org/repo/number Else return None """ body = issue["body"].lower() if "\nduplicates" in body: _, url_string = body.split("\nduplicates ") next_newlin...
bigcode/self-oss-instruct-sc2-concepts
import functools def voice_only(fn): """A decorator that modifies a cog function command to require a sender to be in a voice channel. On failure, it'll notify the author with an error message. Note: discord.py checks would cause it to not show on the help function. So we do this instead. """ @fun...
bigcode/self-oss-instruct-sc2-concepts
def _to_string(val): """Convert to text.""" if isinstance(val, bytes): return val.decode('utf-8') assert isinstance(val, str) return val
bigcode/self-oss-instruct-sc2-concepts
def get_model_top_scope_name(model_name, problem_name): """ Returns the top scope name of all models. Args: model_name: The model string. problem_name: The problem name. Returns: A str. """ if model_name is None: model_name = "SequenceToSequence" return problem_name or ...
bigcode/self-oss-instruct-sc2-concepts
def get_wildcard_constraints(image_types): """Return a wildcard_constraints dict for snakemake to use, containing all the wildcards that are in the dynamically grabbed inputs Parameters ---------- image_types : dict Returns ------- Dict containing wildcard constraints for all wildc...
bigcode/self-oss-instruct-sc2-concepts