seed
stringlengths
1
14k
source
stringclasses
2 values
def process_target(target_str): """ Extract target architecture from a string of verbose compiler invocation output. """ target_label = "Target:" target_clean = "" for line in target_str.splitlines(True): line = line.strip().split() if len(line) > 1 and line[0] == target_lab...
bigcode/self-oss-instruct-sc2-concepts
def uuid_ints_to_uuid_str(uuid: tuple[int, int, int, int]): """Return a string representation given the 4 integer UUID representation.""" usc = tuple(hex(i % 2 ** 32)[2:10].zfill(8) for i in uuid) return '-'.join([usc[0], usc[1][0:4], usc[1][4:8], usc[2][0:4], usc[2][4:8] + usc[3]])
bigcode/self-oss-instruct-sc2-concepts
def _B36Check(b36val): """ Verify that a string is a valid path base-36 integer. >>> _B36Check('Aa') 'aa' >>> _B36Check('.') Traceback (most recent call last): ... ValueError: invalid ... """ int(b36val, 36) return str(b36val).lower()
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def crawl(url): """Crawl a specific url and return the soup. """ req = requests.get(url) req.encoding = 'utf-8' # force utf-8 encoding soup = BeautifulSoup(req.text, 'html.parser') return soup
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def date(date): """DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime`` type and the format changes between DokuWiki versions ... This function convert *date* to a `datetime` object. """ date = date.value return (datetime.strptime(date[:-5], '%Y-%m-%...
bigcode/self-oss-instruct-sc2-concepts
def scanning_title_provider(body): """Get the title of a page from its content body. This implementation does not use a standard xml parser. Instead, it scans the body text looking for content between <title> and </title>. This adds the benefit of working with invalid, or non-standard, xhtml content. ...
bigcode/self-oss-instruct-sc2-concepts
def file_to_list(filename: str) -> list: """ Reads a file and returns a list with the cotent of each line. """ with open(filename, "r") as filehandler: content = [line.strip() for line in filehandler.readlines()] return content
bigcode/self-oss-instruct-sc2-concepts
def _PasswordName(user): """Returns the name of the password file for the specified user. """ return "{0}_pwd".format(user)
bigcode/self-oss-instruct-sc2-concepts
def _get_prefix(concept1, concept2): """ Build a Concept UI prefix as the combination of the UI prefixes of two concepts. :param Concept concept1: The first concept. :param Concept concept2: The second concept. :returns: New prefix :rtype: str """ # ["NMCD_NMCD", "DSLD_NHP"] pr...
bigcode/self-oss-instruct-sc2-concepts
import platform import unittest def skip_unless_has_memory_collection(cls): """Class decorator to skip tests that require memory collection. Any test that uses memory collection (such as the resource leak tests) can decorate their class with skip_unless_has_memory_collection to indicate that if the p...
bigcode/self-oss-instruct-sc2-concepts
def union(*items): """ union(*items) → Return the set-union of the contents of all non-`None` arguments """ return set().union(item for item in items if item is not None)
bigcode/self-oss-instruct-sc2-concepts
def array_reverse(a): """ Reverses an array """ # Time O(n) # Space O(n) return a[::-1]
bigcode/self-oss-instruct-sc2-concepts
def kebab_case(instr): """Convert a snake case string to kebab case.""" return instr.replace("_", "-")
bigcode/self-oss-instruct-sc2-concepts
from unittest.mock import call import re def is_release() -> bool: """Return if current branch is a release branch.""" tag_name = call("git describe --tags").replace("\n", "") return re.match(r"^v\d+\.\d+\.\d+$", tag_name) is not None
bigcode/self-oss-instruct-sc2-concepts
import base64 def decode_base64(data): """Decode base64, padding being optional. :param data: Base64 data as an ASCII byte string :returns: The decoded byte string. """ missing_padding = len(data) % 4 if missing_padding: data += b"=" * (4 - missing_padding) return base64.urlsafe_...
bigcode/self-oss-instruct-sc2-concepts
def repo_exists(github_repos, repo_slug): """Checks if a repository with a given slug exists among the public GitHub repositories. Args: - github_repos: List of GitHub repositories. - repo_slug: Repository slug (usually in a form of path with a namespace, eg: "username/reponame"). Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def get_sum(limit = 1000): """Gets the sum of the multiples of 3 or 5""" sum = 0 for n in range(1, limit): if n % 3 == 0 or n % 5 == 0: sum += n return sum
bigcode/self-oss-instruct-sc2-concepts
def _strip_suffix(service_name): """ Strip ".service" suffix from a given service name. """ return service_name[:-8]
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any import importlib import inspect def _deserialize_from_settings(mod_name: str, class_name: str, settings: Dict) -> Any: """Deserialize an object from its settings. Args: mod_name: Name of the module. class_name: Name of the class. settings...
bigcode/self-oss-instruct-sc2-concepts
def monta_lista_base(lista_ref): """A partir de uma lista_ref constrói uma nova lista de mesmo tamanho e elementos None Args: lista_ref (list): lista de referência para o tamanho da nova lista Returns: [list]: lista com elementos None com mesmo tamanho de lista_ref """ return ...
bigcode/self-oss-instruct-sc2-concepts
from textwrap import dedent def split_docstring(docstring): """ Split a docstring into a summary and a description. Arguments: docstring (str): the docstring Returns: summary (str or None): a one-line summary. description (str or None): the multi-line description. """ ...
bigcode/self-oss-instruct-sc2-concepts
def implicitConstraint(self): """ Evaluates the constraint function @ a given point ($\vec(x)$) @ In, self, object, RAVEN container @ Out, g(x1,x2), float, $g(\vec(x)) = x1 + x2 + objective - 9$ because the original constraint was x1 + x2 + objective > 9 the way the constraint is designed ...
bigcode/self-oss-instruct-sc2-concepts
def parse_extra_alignments(extra_field): """ Parse the additional alignments field of a SAM file :param extra_field: The 'XA' field of a SAM file (e.g. "XA:Z:NC_000913.3,+2729620,22M,0;NC_000913.3,+3427225,22M,0;") :return: A list of tuples representing the positions of the additional alignments ""...
bigcode/self-oss-instruct-sc2-concepts
import gzip import io def smart_open(file, mode='rt', encoding='utf-8'): """Convenience function for reading compressed or plain text files. :param file: The file to read. :param encoding: The file encoding. """ if file.endswith('.gz'): return gzip.open(file, mode=mode, encoding=encoding, newline...
bigcode/self-oss-instruct-sc2-concepts
def check_version_2(dataset): """Checks if json-stat version attribute exists and is equal or greater \ than 2.0 for a given dataset. Args: dataset (OrderedDict): data in JSON-stat format, previously \ deserialized to a python object by \ ...
bigcode/self-oss-instruct-sc2-concepts
def _train_dev_split(X, y, dev_ratio=0.25): """ This function spilts data into training set and development set. """ train_size = int(len(X) * (1 - dev_ratio)) return X[:train_size], y[:train_size], X[train_size:], y[train_size:]
bigcode/self-oss-instruct-sc2-concepts
def psi0(ctx, z): """Shortcut for psi(0,z) (the digamma function)""" return ctx.psi(0, z)
bigcode/self-oss-instruct-sc2-concepts
import logging def check_response(response): """Check the status of responses from polyswarmd Args: response: Response dict parsed from JSON from polyswarmd Returns: (bool): True if successful else False """ status = response.get('status') ret = status and status == 'OK' i...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import List def listify(item: Any) -> List: """Convert any scalar value into list.""" if not item: return [] if isinstance(item, list): return item if isinstance(item, (tuple, set)): return list(item) if isinstance(item, (int, float, str))...
bigcode/self-oss-instruct-sc2-concepts
def _ecdsa_get_pubkey(private_key) -> bytes: """ returns the associated public key of a given ECDSA private key """ return private_key.public_key()
bigcode/self-oss-instruct-sc2-concepts
def eulers_cromer_method(f, dx, y, yp, range, cromer=True): """ The Eulers method, and Eulers-Cromer method for second order differential equations. :param f: Second order differential equation to approximate the solution for. :type f: lambda :param dx: Step size. Smaller is better. :type ...
bigcode/self-oss-instruct-sc2-concepts
def amap(attr, *args): """More convenient syntax for quick data exploration. Get an attribute value for multiple objects. Name is short for "attrmap". Parameters ---------- attr: str Name of attribute to retrieve for each object. args: any Objects (usually of same type) to retri...
bigcode/self-oss-instruct-sc2-concepts
import re def _update_id(record, new_id): """ Update a record id to new_id, also modifying the ID in record.description """ old_id = record.id record.id = new_id # At least for FASTA, record ID starts the description record.description = re.sub('^' + re.escape(old_id), new_id, ...
bigcode/self-oss-instruct-sc2-concepts
import json import requests def collection_exists(collection_name): """ Check if a collection already exists on DIVAServices Arguments: collection_name {string} -- the name of the collection on DIVAServices Returns: bool -- True if the collection exists, False otherwise """ ...
bigcode/self-oss-instruct-sc2-concepts
import warnings def _get_secret_keys(config, secrets_config_key='SECRETS', secrets_list=None): """ Finds all of the configuration values that should be secret """ keys = [] if secrets_config_key is not None: configuration_keys = config.get(secrets_config_key) if configuration_keys ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def return_input(obj: Any) -> Any: """A dummy function that always returns input.""" return obj
bigcode/self-oss-instruct-sc2-concepts
def parse_error_msg(orig_msg): """ Parse "error" message received from backend Format: "error: %s\r\n" """ error = orig_msg[7:] return "error", error
bigcode/self-oss-instruct-sc2-concepts
def add_calculated_rul(df): """Calculates Remaining Useful Life (RUL) and adds it to dataset, which is returned. Parameters ----------- df : pd.DataFrame Dataframe containing time-series data. Returns pd.DataFrame dataset, inclusive of calculated RUL values. """ ...
bigcode/self-oss-instruct-sc2-concepts
def _strip_shell(cmd): """Strip a (potentially multi-line) command. For example $ foo \ > --bar baz \ > --quux 10 would becomes `foo --bar baz --quux 10`. """ parts = [] for line in cmd.strip().split("\n"): without_console = line.lstrip("$> ").rstrip("\\ ") ...
bigcode/self-oss-instruct-sc2-concepts
def list_local_tags(repo): """Return a list of the tags on the local repo.""" # A tag can point to a blob and the loop prunes blob tags from the list of tags to be sorted tag_list = [] for bar in repo.tags: try: bar.commit.committed_datetime except ValueError: pas...
bigcode/self-oss-instruct-sc2-concepts
def ask(msg, number=True): """Return valid user response to a question. Accepts: msg, str: What to display to the user number, bool: Whether to enforce entry of a number Returns: response, (str|float): User entry, either string or float """ while True: response = inp...
bigcode/self-oss-instruct-sc2-concepts
from operator import getitem from functools import reduce def dpath(dict_, path): """Dig into dictionary by string path. e.g. dpath({'a': {'b': {'c': 'd'}}}, 'a.b') -> {'c': 'd'} """ paths = path.split('.') return reduce( getitem, paths, dict_ )
bigcode/self-oss-instruct-sc2-concepts
def length(node): """ Count how many values there are in the linked list :param node: value of head node, start of list :return: int: number of list elements """ if node is not None: return 1 + length(node.next_node) # count nodes basically return 0
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import hashlib import requests def _pwned_password(passphrase: str) -> Union[int, bool]: """Check passphrase with Troy's Hunt haveibeenpwned API. Query the API to check if the passphrase has already been pwned in the past. If it has, returns the number of times it has been pwned,...
bigcode/self-oss-instruct-sc2-concepts
def vector2string(vec): """ Helper function, converts vector to one string separated by spaces :param vec: :return: """ s = "" for item in vec: s += str(item) + " " return s
bigcode/self-oss-instruct-sc2-concepts
def last_received_endswith(agent, tail): """ Check if the agent's last received message ends with `tail`. It is supposed to be executed as an agent method (in example: use it as the condition in `wait_agent_condition` or execute it with the method `execute_as_method`). Parameters ---------...
bigcode/self-oss-instruct-sc2-concepts
def version_to_str(vsn): """ Convert the given version tuple to a dot separated string representation """ return '.'.join(str(x) for x in vsn)
bigcode/self-oss-instruct-sc2-concepts
def time_to_secs(t): """Convert a datetime.time object to seconds""" return t.hour*3600 + t.minute*60 + t.second
bigcode/self-oss-instruct-sc2-concepts
def get_func_id(func): """Get a quasi-identifier of a given function.""" return func.__qualname__
bigcode/self-oss-instruct-sc2-concepts
import math def rotate(v, axis, angle): """Rotate a vector about an axis through an angle Parameters ---------- v : array with exactly 3 numeric entries The vector to be rotated. axis : one of 'x', 'z' The axis about which to rotate. Rotations about y are not supported sin...
bigcode/self-oss-instruct-sc2-concepts
def sumd(n): """ Return the sum of digits of a number. number: non-negative integer """ # Base Case if n == 0: return 0 else: # Mod (%) by 10 gives you the rightmost digit (227 % 10 == 7), # while doing integer division by 10 removes the rightmost # digit (22...
bigcode/self-oss-instruct-sc2-concepts
def filter_startswith(word, beginning=None): """Filter a word starting with specified string. :param word (str): The word. :param beginning (str, optional): The beginning string to check. :rtype: bool: The resulting check. """ return word.lower().startswith(beginning)
bigcode/self-oss-instruct-sc2-concepts
def na_usd(total_pln, rate_usd): """Calculate values in USD""" return total_pln / rate_usd
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def calculate_percentages(hour_production: Dict[str, float]) -> Dict[str, int]: """Calculate percentages from all values in the dictionary. Returns dictionary with same keys but percentage values as integers. Percentage total not always 100 due to rounding to integers """ ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def calling_source_location(skip=0): """Return source location of current call stack, skip specified levels (not include itself).""" skip += 1 # This function itself is excluded. skipped = 0 frame = inspect.currentframe() while frame: if skipped == skip: return ...
bigcode/self-oss-instruct-sc2-concepts
def killwhitespace(string): """ Merge consecutive spaces into one space. """ return " ".join(s.strip() for s in string.split())
bigcode/self-oss-instruct-sc2-concepts
def first_of(attr, match, it): """ Return the first item in a set with an attribute that matches match """ if it is not None: for i in it: try: if getattr(i, attr) == match: return i except: pass return None
bigcode/self-oss-instruct-sc2-concepts
import re def clean_filename(unclean_name: str) -> str: """ Return a valid filename where any character that is not a letter, number, dash, underscore, space, or period is replaced with an underscore """ return re.sub(r'[^\w\-_. ]', '_', unclean_name)
bigcode/self-oss-instruct-sc2-concepts
def descendants_query(node_id, node_label, edge_label="edge"): """Generate Cypher query finding descendant nodes starting at 'node_id'.""" return ( "MATCH path=(n:{} {{id: '{}'}})-[:{}*1..]->(m:{})\n".format( node_label, node_id, edge_label, node_label) + "RETURN m.id AS descendant, ...
bigcode/self-oss-instruct-sc2-concepts
def mocked_elasticsearch(mocked_elasticsearch_module_patcher): """ Fixture that resets all of the patched ElasticSearch API functions """ for mock in mocked_elasticsearch_module_patcher.patcher_mocks: mock.reset_mock() return mocked_elasticsearch_module_patcher
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def discover_controllers(entry_point='steppy.controllers'): """Discover controllers registered under given entry point In: - ``entry_point`` - The entry point under which to register controllers (default: "steppy.controllers") Return: - A dictionary {controller name: contr...
bigcode/self-oss-instruct-sc2-concepts
import collections def reorder_props(props): """ If "children" is in props, then move it to the front to respect dash convention Parameters ---------- props: dict Dictionary with {propName: propMetadata} structure Returns ------- dict Dictionary with {propName: pr...
bigcode/self-oss-instruct-sc2-concepts
def ql(fmp, fs, f0p): """Calculate qL qL = ((fmp - fs) / (fmp - f0p)) * (f0p / fs) :param fmp: Fm' :param fs: Fs :param f0p: F0' :returns: qL (float) """ return ((fmp - fs) / (fmp - f0p)) * (f0p / fs)
bigcode/self-oss-instruct-sc2-concepts
def tostr(lst): """Makes all values of a list into strings""" return [str(i) for i in list(lst)]
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def extract_entitlement(entitlement: str, text: str) -> Tuple[str, str, str, str]: """ Extracts entitlement components from an entitlement string Args: entitlement: The entitlement itself text: The actual reply text Returns: Entitlement components ...
bigcode/self-oss-instruct-sc2-concepts
def extract_number_of_pages(soup): """ Extract the number of result pages from a result page. """ pager_span = soup.find('span', class_='smallPager') return int(pager_span.string.split()[-1])
bigcode/self-oss-instruct-sc2-concepts
from typing import List def date_filter_string(column: str, comp_type: int, thresholds: List[str]): """ Generate string for date-based filters Generates a filter for filtering for specific rows based on different date comparisons. Args: column: Column to filter on ...
bigcode/self-oss-instruct-sc2-concepts
import torch def ravel_index(idx, dims) -> torch.Tensor: """ Computes the linear index in an array of shape dims. It performs the reverse functionality of unravel_index Args: idx: A LongTensor of shape (N, 3). Each row corresponds to indices into an array of dimensions dims. dims...
bigcode/self-oss-instruct-sc2-concepts
def _is_password_valid(pw): """Returns `true` if password is strong enough for Firebase Auth.""" return len(pw) >= 6
bigcode/self-oss-instruct-sc2-concepts
def get_snapping_pos_line_chart_vertical(data_objects, line_pos): """ Calculates the nearest pos of and objects from a line chart with an vertical line. :param data_objects: The nodes of the data objects in the chart. :type data_objects: dict[str, PolyLineNode] :param line_pos: The necessary positi...
bigcode/self-oss-instruct-sc2-concepts
import json def parse_json_file(distribution_json_file): """ Parse a json distribution file for a distribution id. Look for node of type 'dynamicPluginConfiguration' that contains the attribute id Note: The file should contains only one distribution. :param distribution_json_file: filepath :r...
bigcode/self-oss-instruct-sc2-concepts
def ensure_ref_position_is_valid(ref_position, num_alts, param_title): """ Ensures that `ref_position` is None or an integer that is in the interval `[0, num_alts - 1]`. If None, ensures that intercepts are not the parameters being estimated. Raises a helpful ValueError if otherwise. Parameters ...
bigcode/self-oss-instruct-sc2-concepts
def _suggest_target_postcodes(system, threshold=None): """Sort postcodes by population density (descending) - if considering threshold, filter out any with capacity above threshold """ postcodes = system.postcode_sectors.values() total_postcodes = len(postcodes) if threshold is not None: ...
bigcode/self-oss-instruct-sc2-concepts
def parse_size(root): """Parse the width and height of the image out of the root node. Args: ---- root: xml.etree.ElementTree.Element Output: ------ width: str height str """ size_node = root.find('size') width = size_node.find('width').text height = size_n...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def getResourcePath(name): """ Return the path to a resource """ return pkg_resources.resource_filename(__name__, "data/%s" % name)
bigcode/self-oss-instruct-sc2-concepts
import requests def is_darksky_quota_error(err): """Return Tre if input 'err' is a DarkSky quota error, else False""" tf = False if isinstance(err, requests.exceptions.HTTPError): resp = err.response if resp.status_code == 403 and 'darksky' in resp.url: tf = True return tf
bigcode/self-oss-instruct-sc2-concepts
def colors(graph, node_type_attr='type'): """ Utility function that generates colors for node types for drawing graph in Ipython Notebook. :param graph: networkx.Graph :returns: Dict. Nodes as keys, colors as values. """ colors_dict = {} colors = [] counter = 1 for node, attrs i...
bigcode/self-oss-instruct-sc2-concepts
def create_weighted_list(peoplex, no_showx): """ Function to create a list using weights (avoiding no shows) :param peoplex: :param no_showx: :return: """ jc_listx = [] for name in peoplex: if peoplex[name] == 0: continue if peoplex[name] in no_showx: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def get_lr_schedule_rnd( rnd: int, lr_initial: float, lr_decay: float ) -> Callable[[int], float]: """Return a schedule which decays the learning rate after each round.""" lr_rnd = lr_initial * lr_decay ** rnd # pylint: disable-msg=unused-argument def lr_schedule(epoch...
bigcode/self-oss-instruct-sc2-concepts
def thisorthat(this, that): """ If this is None takes that otherwise takes this. :param this: :param that: :return: """ if this is None: return that else: return this
bigcode/self-oss-instruct-sc2-concepts
def errfun_sae(x,y): """ Sum of absolute errors """ return sum(abs(x-y))
bigcode/self-oss-instruct-sc2-concepts
def _calculate_value_in_range(min_val, max_val, percentage): """Get the value within a range based on percentage. Example: A percentage 0.0 maps to min_val A percentage of 1.0 maps to max_val """ value_range = max_val - min_val return min_val + int(percentage * value_range)
bigcode/self-oss-instruct-sc2-concepts
def fmt_item_ipv4(entry): """Format an IPv4 range with lo and hi addresses in decimal form.""" return "%d,%d,%s\n"%(entry[0], entry[1], entry[2])
bigcode/self-oss-instruct-sc2-concepts
import torch def loss_loglik(y_mean, y_logvar, x): """ Args: y_mean of shape (batch_size, 1, 28, 28): Predictive mean of the VAE reconstruction of x. y_logvar of shape (batch_size, 1, 28, 28): Predictive log-variance of the VAE reconstruction of x. x of shape (batch_size, 1, 28, 28): Trainin...
bigcode/self-oss-instruct-sc2-concepts
def find_shift(p, row, test_col): """Find how many cells to shift up when encountering possible merged cells.""" max_shift = 4 for shift in range(max_shift): test_val = p[test_col + str(row - shift)].value # If None,the cells were merged vertically; look up. if test_val is not None:...
bigcode/self-oss-instruct-sc2-concepts
def selective_title(str): """ Convert string to Title Case except for key initialisms Splits input string by space character, applies Title Case to each element except for ["NHS", "PCN", "CCG", "BNF", "std"], then joins elements back together with space Parameters ---------- str : str ...
bigcode/self-oss-instruct-sc2-concepts
def CLSID(MyClass): """Return CLSID of MyClass as string""" return str(MyClass._reg_clsid_)
bigcode/self-oss-instruct-sc2-concepts
import re def spec_add_spaces(text: str) -> str: """Add spaces around / and # in `text`. \n (code from `fastai`)""" return re.sub(r"([/#\n])", r" \1 ", text)
bigcode/self-oss-instruct-sc2-concepts
def bubble_sort(lst: list) -> list: """Sort a list in ascending order. The original list is mutated and returned. The sort is stable. Design idea: Swap adjacent out-of-order elements until the list is sorted. Complexity: O(n^2) time, O(1) space. Stable and in-place. See quicksort, merge sort and ...
bigcode/self-oss-instruct-sc2-concepts
def datetime2hr(dtime): """ Calculate hours of day from datetime Parameters ---------- dtime : (dt.datetime) Universal time as a timestamp Returns ------- uth : (float) Hours of day, includes fractional hours """ uth = dtime.hour + dtime.minute / 60.0 \ + ...
bigcode/self-oss-instruct-sc2-concepts
def get_indeces(a, b): """ Extracts the indices multiple items in a list. Parameters: a: list. where we want to get the index of the items. b: list. the items we want to get index of. #example: x = ['SBS1', 'SBS2', 'SBS3', 'SBS5', 'SBS8', 'SBS13', 'SBS40'] y = ['SBS1...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha256(x): """ Simple wrapper of hashlib sha256. """ return hashlib.sha256(x).digest()
bigcode/self-oss-instruct-sc2-concepts
import yaml def load(filename): """Load a dictionary from a yaml file. Expects the file at filename to be a yaml file. Returns the parsed configuration as a dictionary. :param filename: Name of the file :type filename: String :return: Loaded configuration :rtype: Dict """ with open...
bigcode/self-oss-instruct-sc2-concepts
def unique_family(data): """A list of unique families in the USDA data provided Iterates through the DictReader for the family names, and returns a list of names Args: A DictReader instance of the usda plant checklist Returns: A list of strings containing all the unique family...
bigcode/self-oss-instruct-sc2-concepts
def raw(s): """ Coverts ScholarOne MS_ID into its base form (i.e. removes revision number if present) """ if '.R' in s: s = s.split('.R')[0] return s
bigcode/self-oss-instruct-sc2-concepts
def is_inverted(c): """Returns True if the ordering of the candidates in the sentence is inverted.""" if len(c) != 2: raise ValueError("Only applicable to binary Candidates") return c[0].get_word_start() > c[1].get_word_start()
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def remove_non_ascii(words): """Remove non-ASCII characters from list of tokenized words""" # replaces non-ascii tokens with "" # example £ § new_words = [] for word in words: new_word = unicodedata.normalize('NFKD', word).encode('ascii', 'ignore').decode('utf-8', 'ignor...
bigcode/self-oss-instruct-sc2-concepts
def allsame(xs): """ Returns whether all elements of sequence are the same """ assert len(xs) > 0 return all(x == xs[0] for x in xs[1:])
bigcode/self-oss-instruct-sc2-concepts
def bytes_to_gb(bytes_val): """ Convert bytes to GB, rounded to 2 decimal places """ BYTES_IN_GB = 1024 * 1024 * 1024 gbytes = bytes_val / BYTES_IN_GB return round(gbytes, 2)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def generate_object_key(lookup_key, resolution, time_sample, morton_id): """ Generates an object key assumes iso=False. Based on spdb.spatialdb.object.AWSObject.generate_object_key() Args: lookup_key (str): lookup key collection_id&experiment_id&channel_id resolution (int ...
bigcode/self-oss-instruct-sc2-concepts