seed
stringlengths
1
14k
source
stringclasses
2 values
def _build_shift_table(grammar, item_sets, item_set_transitions): """ Returns a list of maps from terminal symbols to shift actions. A shift action is simply an index into the item_set array. """ shifts = [] for transitions in item_set_transitions: shifts.append( { ...
bigcode/self-oss-instruct-sc2-concepts
def query_tw_username(username): """ES query by Twitter's author.username Args: username (str) Returns: ES query (JSON) """ return { "query": { "bool": { "filter": [ {"term": {"doctype": "tweets2"}}, {"mat...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def worst_of_five(errors: List[float]) -> bool: """Returns true when the last error is the worst of five last ones.""" if len(errors) > 3 and (errors[-1] > max(errors[-5:-1])): return True return False
bigcode/self-oss-instruct-sc2-concepts
import math def correct_csmf_accuracy(uncorrected): """Correct Cause-Specific Mortality Fraction accuracy for chance Chance corrected metrics are derived from the general equation: .. math:: K_j = \\frac{P(observed)_j - P(expected)_j}{1 - P(expected)_j} where K\ :sub:`j` is the corrected s...
bigcode/self-oss-instruct-sc2-concepts
def eval_acer(results, is_print=False): """ :param results: np.array shape of (N, 2) [pred, label] :param is_print: print eval score :return: score """ ind_n = (results[:, 1] == 0) ind_p = (results[:, 1] == 1) fp = (results[ind_n, 0] == 1).sum() fn = (results[ind_p, 0] == 0).sum() ...
bigcode/self-oss-instruct-sc2-concepts
import codecs def read_dataset(inpath): """ Reads a generic dataset with rows separated by tabs into a list. Args: inpath (str): Path to dataset. Returns: list: List of line contents as tuples. """ with codecs.open(inpath, 'rb', 'utf-8') as infile: return [tuple(line.strip().split('\t')) for line in inf...
bigcode/self-oss-instruct-sc2-concepts
import time def dtime(t0): """time since t0.""" return round(time.perf_counter() - t0, 2)
bigcode/self-oss-instruct-sc2-concepts
def alpha_to_num(char): """Takes a single character and converts it to a number where A=1""" translator = { "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "I": 9, "J": 10, "K": 11, "L": 12, "M": 13, "N": 14, "O": 15, "P": 16, "Q": 17, "R": 18, "S"...
bigcode/self-oss-instruct-sc2-concepts
def compute_U(Sigma_sfr, Sigma_g): """ Ionizaton parameter as a function of star formation and gas surface densities. reference: Eq. 38 Ferrara et al. 2019 inputs: Sigma_sfr in Msun/yr/kpc^2 Sigma_g in Msun/kpc^2 """ out= (1.7e+14)*(Sigma_sfr/(Sigma_g*Sigma_g)) return ou...
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_function_name(count: int = 0) -> str: """ Return the name of the function calling this function, i.e., the name of the function calling `get_function_name()`. """ ptr = inspect.currentframe() # count=0 corresponds to the calling function, so we need to add an extra #...
bigcode/self-oss-instruct-sc2-concepts
import random def rand_nonce(diff): """ Returns a random int in [0, 2**diff) """ return random.randint(0,2**diff-1)
bigcode/self-oss-instruct-sc2-concepts
def decode(index, idxs, end= "\n", sep= ""): """-> str decodes `idxs : seq int` according to `index : PointedIndex`. stops at `end` and joins the results with `sep`. """ end = index(end) tgt = [] for idx in idxs: if idx == end: break tgt.append(index[idx]) return sep.j...
bigcode/self-oss-instruct-sc2-concepts
def convert_py_to_cpp_namespace(python_namespace: str) -> str: """Convert a Python namespace name to a C++ namespace. Parameters ---------- python_namespace : `str` A string describing a Python namespace. For example, ``'lsst.example'``. Returns ------- cpp_namespace : `str...
bigcode/self-oss-instruct-sc2-concepts
def h_bubble(heigth_layer, epsi_vapor): """ Calculates the heigth of bubble layer. Parameters ---------- epsi_vapor : float The vapor content of bubble layer, [dimensionless] heigth_layer : float The heigth ligth layer of the liquid, [m] Returns ------- h_bubble : fl...
bigcode/self-oss-instruct-sc2-concepts
import configparser def to_dict(cfg: configparser.ConfigParser) -> dict: """Converts ConfigParser object into dictionary""" return {s.lower(): dict(cfg[s]) for s in cfg.sections()}
bigcode/self-oss-instruct-sc2-concepts
import re def rm_quotation_marks(sent): """ Remove single quotes used as quotation marks (e.g. some 'phrase in quotes') Remove double quotes used as quotation marks (e.g. some "phrase in quotes" or ``phrase in quotes'') """ sent = re.sub(r"\s'([\w\s]+[\w])'\s", r' \1 ', sent) return re.sub(r'[...
bigcode/self-oss-instruct-sc2-concepts
def _TaskPathToId(path): """Transforms the pathname in YAML to an id for a task. Args: path: Path name. Returns: id of the task. """ return '<joiner>'.join(path)
bigcode/self-oss-instruct-sc2-concepts
import base64 def img_to_base64(path): """Converts an img to a base64 encoded string.""" with open(path, 'rb') as f: return base64.b64encode(f.read()).decode()
bigcode/self-oss-instruct-sc2-concepts
def select_from_list(tabstop, values): """Completes a partially-completed `tabstop` to one of predefined `values`.""" if tabstop: values = [value[len(tabstop):] for value in values if value.startswith(tabstop)] if len(values) == 1: return values[0] return "[" + " | ".join(values) + "]"
bigcode/self-oss-instruct-sc2-concepts
import uuid def createUUID(prefix='uid'): """Create uuid4 specific UUID which uses pseudo random generators. Further, uuid is prefixed using 3 letter acronym to visually differentiate among them Some prefix used when generating UUIDs are: ant - annotation img - image lbl - label / cat - category train ...
bigcode/self-oss-instruct-sc2-concepts
def get_positive_label(values): """ Returns the label of the positive examples. :param values: the labels :type values: collections.Iterable[float] :return: the label of the positive example :rtype: Optional[float] """ for value in values: if value > 0.0: return valu...
bigcode/self-oss-instruct-sc2-concepts
def get_config_name(arduino): """Return config filename for arduino.""" config_name = str(arduino.vid) config_name += str(arduino.pid) config_name += str(arduino.serial_number) config_name += ".yaml" return config_name
bigcode/self-oss-instruct-sc2-concepts
def completion_score_flag( df, photo_bit_binary="mhm_PhotoBitBinary", has_genus="mhm_HasGenus", sub_completeness="mhm_SubCompletenessScore", completeness="mhm_CumulativeCompletenessScore", inplace=False, ): """ Adds the following completness score flags: - `SubCompletenessScore`: The...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def _dictify(data, keys, val) -> Dict: """ Helper function to generate nested dictionary from list of keys and value. Calls itself recursively. Arguments: data (dict): dictionary to add value to with keys keys (list): list of keys to traverse along tree an...
bigcode/self-oss-instruct-sc2-concepts
def signal_1D(mu, i, key, n): """ Generate signal power consumption S values for all messages mu. Parameters: mu -- list of bool, size n x 2^n i -- integer in [0,n-1] key -- list of bool, length n n -- integer Return: S -- list of integers, length 2^n """ S = [] # For each message mu for j in rang...
bigcode/self-oss-instruct-sc2-concepts
def string_safe_list(obj): """ Turn an (iterable) object into a list. If it is a string or not iterable, put the whole object into a list of length 1. :param obj: :return list: """ if isinstance(obj, str) or not hasattr(obj, "__iter__"): return [obj] else: return list(ob...
bigcode/self-oss-instruct-sc2-concepts
def plot_bar(data, **kwargs): """ Plot bar chart.""" ax = data.plot(kind='barh', **kwargs) return ax
bigcode/self-oss-instruct-sc2-concepts
def _can_condition_be_resolved(base_conditions, extending_condition): """Determine whether an extending condition can be resolved.""" return all( condition_name in base_conditions for condition_name in extending_condition.extended_conditions )
bigcode/self-oss-instruct-sc2-concepts
def quadratic_bezier_point(p0,p1,p2,t) : """Returns the bezier point returned with p0, p1, and p2 as reference points at fraction t along curve. Reference point arguments are length 2 numpy arrays.""" return (1-t)**2*p0 + 2*(1-t)*t*p1 + t**2*p2
bigcode/self-oss-instruct-sc2-concepts
def arrow_out(value): """Convert an Arrow object to timestamp. :param Arrow value: The Arrow time or ``None``. :returns int: The timestamp, or ``None`` if the input is ``None``. """ return value.timestamp if value else None
bigcode/self-oss-instruct-sc2-concepts
def remove_ssml_tags(parm_text:str) -> str: """Remove the SSML tags from parm text. The tags are surrounded by <chevrons>.""" output_text = '' inside_chevrons = False for c in parm_text: if c == '<': inside_chevrons = True elif c == '>': inside_chevrons = False ...
bigcode/self-oss-instruct-sc2-concepts
def t_scat(t_G, f): """ Scattering timescale in seconds at f in MHz. t_G is the timescale at 1GHz, in seconds. """ return t_G*((f/1000.)**(-4))
bigcode/self-oss-instruct-sc2-concepts
def tokenise(text): """Character based tokeniser.""" return list(text)
bigcode/self-oss-instruct-sc2-concepts
import csv def _read_benchmark_numbers(benchmark_filepath): """Reads benchmark numbers from file. Args: benchmark_filepath: string, file path to benchmark result. Returns: A list of benchmark names and a list of corresponding performance number (in ns). """ with open(benchmark_filepath) as c...
bigcode/self-oss-instruct-sc2-concepts
import unittest def make_suite(tc_class, config, root_tmpdir, ports_sock): """Compose test suite based on test class names.""" testloader = unittest.TestLoader() testnames = testloader.getTestCaseNames(tc_class) suite = unittest.TestSuite() for name in testnames: suite.addTest(tc_class(nam...
bigcode/self-oss-instruct-sc2-concepts
import io import csv def roaming_channel_csv() -> io.StringIO: """ Generates a placeholder RoamingChannel.csv """ header = [ "No.", "Receive Frequency", "Transmit Frequency", "Color Code", "Slot", "Name", ] sio = io.StringIO() writer = csv....
bigcode/self-oss-instruct-sc2-concepts
def find_neighbors(pindex, tri): """ Adapted from @user2535797 at https://stackoverflow.com/questions/12374781/how-to-find-all-neighbors-of-a-given-point-\ in-a-delaunay-triangulation-using-sci Parameters ---------- pindex: integer a index of a single point tri: ...
bigcode/self-oss-instruct-sc2-concepts
def dup_quo_ground(f, c, K): """ Quotient by a constant in ``K[x]``. **Examples** >>> from sympy.polys.domains import ZZ, QQ >>> from sympy.polys.densearith import dup_quo_ground >>> f = ZZ.map([3, 0, 2]) >>> g = QQ.map([3, 0, 2]) >>> dup_quo_ground(f, ZZ(2), ZZ) [1, 0, 1] >...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def extract_communication_text(communication_url): """Pull the raw text of a SOTU communication (message or address).""" # open the communication page communication_request = requests.get(communication_url) # read the html for the communication page communicat...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_header_col(board: List[List[str]]) -> List[str]: """ Get the column header. (Note: this list should only contain alphabet.) Parameters ---------- board: List[List[str]] 2D array containing all the game detail, including column he...
bigcode/self-oss-instruct-sc2-concepts
async def get_home(): """[Get Home ] Returns: JSON Response with a small introductory message """ return {"msg": "Home Microservice"}
bigcode/self-oss-instruct-sc2-concepts
def assert_ops_in_graph(expected_ops, graph): """Assert all expected operations are found. Args: expected_ops: `dict<string, string>` of op name to op type. graph: Graph to check. Returns: `dict<string, node>` of node name to node. Raises: ValueError: If the expected ops are not present in th...
bigcode/self-oss-instruct-sc2-concepts
def read_stripped_lines(filename): """Return a list of stripped lines from a file""" with open(filename) as fobj: return [line.strip() for line in fobj.readlines()]
bigcode/self-oss-instruct-sc2-concepts
def is_hex(s): """Return whether s is a hex string.""" try: int(s, 16) except (TypeError, ValueError): return False return True
bigcode/self-oss-instruct-sc2-concepts
def flat_set_from_df(df, col, condition=None): """Flatten Series from DataFrame which contains lists and return as set, optionally after filtering the DataFrame. """ if condition is not None: df = df[condition] lists = df[col].tolist() return set([item for sublist in lists for item in su...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_axis_collision_times( distance_entry: float, distance_exit: float, v: float ) -> Tuple[float, float]: """ Gets the entry and exit times for a collision in 1 dimension. Parameters: distance_entry: float - Entry distance of first object to other. di...
bigcode/self-oss-instruct-sc2-concepts
import click def format_boolean(value): """ Format boolean with color """ if type(value) == bool: if value: return click.style(str(value), fg='green') else: return click.style(str(value), fg='red') return value
bigcode/self-oss-instruct-sc2-concepts
def line_XY_intersection(point, direction): """ Finds intersection (x,y) between XY plane and a line. point: some point on the line (e.g. camera position) direction: some vector pointing along the line Assumes numpy arrays. """ r = point[2]/direction[2] xy = point[0:2] - r*direction[0:...
bigcode/self-oss-instruct-sc2-concepts
def split_repo_name(repository): """Take a string of the form user/repo, and return the tuple (user, repo). If the string does not contain the username, then just return None for the user.""" nameparts = repository.split('/', 1) if len(nameparts) == 1: return (None, nameparts[0]) else: ...
bigcode/self-oss-instruct-sc2-concepts
import csv def dict_from_tsvfile(filename): """open a tab separated two column file, return it as a str->str dict""" d = {} with open(filename) as csvfile: reader = csv.reader(csvfile, delimiter='\t') for row in reader: d[row[0]] = row[1] return d
bigcode/self-oss-instruct-sc2-concepts
def celsius_to_fahrenheit(celsius): """ convert celsius to fahrenheit """ fahrenheit = (celsius * (9.0/5.0)) + 32.0 return fahrenheit
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def get_test_data() -> Dict[str, Any]: """ Auxiliary method to return test data args. :return: Test data. """ return { "root": { "branch1": {"number": 23, "string": "value"}, "branch2": {"object": object(), "boolean": ...
bigcode/self-oss-instruct-sc2-concepts
def transObj(object, disp): """ Translate an object """ return (object[0]+disp,object[1])
bigcode/self-oss-instruct-sc2-concepts
def by_type(blocks, slist=None): """Sort blocks into layout, internal volume, data or unknown Arguments: Obj:blocks -- List of block objects. List:slist -- (optional) List of block indexes. Returns: List:layout -- List of block indexes of blocks containing the volume t...
bigcode/self-oss-instruct-sc2-concepts
def dashes(count): """ Return the specified number of dashes as a string """ return "".join(("-" for _ in range(0, count)))
bigcode/self-oss-instruct-sc2-concepts
def min_sample_rate(st, min_sps=20.0): """ Discard records if the sample rate doers not exceed minimum. Args: st (StationStream): Stream of data. min_sps (float): Minimum samples per second. Returns: StationStream: Stream checked for sample rate criteria...
bigcode/self-oss-instruct-sc2-concepts
def column(data, key): """ get specific column Args: data (list(dict)): data object returned by csv.DictReader key (str): name of the column (header in first row) Returns: list(float): column data """ column_data = [] for row in data: column_data.append(float(row[key])) return colu...
bigcode/self-oss-instruct-sc2-concepts
def _validate_record_owner(signer_public_key, record): """Validates that the public key of the signer is the latest (i.e. current) owner of the record """ latest_owner = max(record.owners, key=lambda obj: obj.timestamp).agent_id return latest_owner == signer_public_key
bigcode/self-oss-instruct-sc2-concepts
def _CalcLutOffsets(lods, isalpha): """ Compute the offset into the lookup tables by LOD level. Return an array of offsets indexed by LOD. Also return (appended to the end of the result) the lookuop table size. The result differs depending on whether this is the alpha or brick LUT. The highe...
bigcode/self-oss-instruct-sc2-concepts
def find_max(nums, left, right): """ find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_max(nums, 0, len(nums) - 1) == max(nums) True ...
bigcode/self-oss-instruct-sc2-concepts
def sum_array(a): """ Returns the sum of the numbers. :param a: an array of integers. :return: the sum of the array. """ return sum(a)
bigcode/self-oss-instruct-sc2-concepts
def bitflags(*sequential, **named): """ Enum helper to generate bit-flag values usage: ENUM_TYPE = bitflags(VALUE, VALUE2, VALUE3) or: EnumType = bitflags(VALUE1, VALUE2, VALUE3=0x0ff) The result will be VALUE = 0x1, VALUE2 = 0x2, VALUE3 = 0x4, etc. """ values = [] base = 1 for _ ...
bigcode/self-oss-instruct-sc2-concepts
import string def is_punctuation(term): """ Check whether a string consists of a single punctuation mark Example: >>> is_punctuation(".") True >>> is_punctuation("word") False """ return len(term) == 1 and term in string.punctuation
bigcode/self-oss-instruct-sc2-concepts
import string import random def generate_random_words(nb_words, nb_character_max, nb_character_min = 3): """ Generates 'nb_words' random words composed from 1 to 'nb_character_max' ASCII characters. """ words = [] for i in range(nb_words): word = string.ascii_letters word = ''.joi...
bigcode/self-oss-instruct-sc2-concepts
def copy_func_data(source_func, dest_func): """ Copy all useful data that is not the __code__ from source to destination and return destination. """ dest_func.__name__ = source_func.__name__ dest_func.__qualname__ = source_func.__qualname__ dest_func.__doc__ = source_func.__doc__ dest_fu...
bigcode/self-oss-instruct-sc2-concepts
def not_found(request, response): """Basic controller to act as default for unmatched request paths.""" response.status_code = 404 response.write("We can't find %s\n" % request.path) return response
bigcode/self-oss-instruct-sc2-concepts
def FilenameMatchesExtension(filename, extensions): """Checks to see if a file name matches one of the given extensions. Args: filename: The full path to the file to check extensions: A list of candidate extensions. Returns: True if the filename matches one of the extensions, otherwise False. """ ...
bigcode/self-oss-instruct-sc2-concepts
def tonumpy_batch(imgs): """ Convert a batch of torch images to numpy image map :param imgs: (B, C, H, W) :return: (B, H, W, C) """ return imgs.permute(0, 2, 3, 1).cpu().detach().numpy()
bigcode/self-oss-instruct-sc2-concepts
import random import string def get_random_string(length=32, prefix_string=""): """This function returns a random alphanumeric string to use as a salt or password. :param length: The length of the string (``32`` by default) :type length: int :param prefix_string: A string to which the salt should be ...
bigcode/self-oss-instruct-sc2-concepts
def convert_by_vocab_dict(vocab_dict, items): """ Converts a sequence of [tokens|ids] according to the vocab dict. """ output = [] for item in items: if item in vocab_dict: output.append(vocab_dict[item]) else: output.append(vocab_dict["<unk>"]) return out...
bigcode/self-oss-instruct-sc2-concepts
def screen_np(a, b): """screen(A, B) 1 − (1 − A) * (1 − B)""" return 255 - (255 - a) * (255 - b)
bigcode/self-oss-instruct-sc2-concepts
def read_labels(labels_path): """ def read_labels(labels_path) function to read labels from names file Args: labels_path (str): names file path Returns: dictionary of labels, id pairs. """ with open(labels_path, 'r') as names_file: lines = names_file.read() i = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def titlecase(name): """Title-case target `name` if it looks safe to do so.""" return name if name.startswith(('1', 'C/', 'DSS-')) else name.title()
bigcode/self-oss-instruct-sc2-concepts
import torch def label_to_onehot(labels, num_classes=10): """ Converts label into a vector. Args: labels (int): Class label to convert to tensor. num_classes (int): Number of classes for the model. Returns: (torch.tensor): Torch tensor with 0's everywhere except for 1 in ...
bigcode/self-oss-instruct-sc2-concepts
def titlesplit(src='', linelen=24): """Split a string on word boundaries to try and fit into 3 fixed lines.""" ret = ['', '', ''] words = src.split() wlen = len(words) if wlen > 0: line = 0 ret[line] = words.pop(0) for word in words: pos = len(ret[line]) ...
bigcode/self-oss-instruct-sc2-concepts
def calc_bn_sparsity(L, q, K): """Calculates sparsity of Block Beighborhood scheme""" sparsity = (L/K)*(q**K - 1) +1 return sparsity
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def object_to_qualified_name(value, fail=False, default_module_name='builtins') -> Union[str, None]: """ Get the fully qualified name of a Python object. It is true that ``qualified_name_to_object(object_to_qualified_name(obj)) is obj``. >>> from unittest import TestCase ...
bigcode/self-oss-instruct-sc2-concepts
import re def shorten_url(url): """ Return a URL which is shorter but still useful, for being displayed in logs >>> shorten_url("https://www.civicboom.com/i/like/bacon") '/i/like/bacon' doesn't affect urls that are already short: >>> shorten_url("/waffo/waffo") '/waffo/waffo' a...
bigcode/self-oss-instruct-sc2-concepts
def diffs_stats(pairs): """returns the avg and the maximum difference between the given pairs and the count of cases where the first element is bigger than the second """ s = 0.0 m = 0.0 n = 0 for (old, new) in pairs: d = new - old # not using abs here on purpose s += d ...
bigcode/self-oss-instruct-sc2-concepts
def get_square(tracks, position): """Get square from tracks with position.""" row, col = position return tracks[row][col]
bigcode/self-oss-instruct-sc2-concepts
def convert_to_float(value_string, parser_info_out=None, suc_return=True): """ Tries to make a float out of a string. If it can't it logs a warning and returns True or False if convertion worked or not. :param value_string: a string :returns value: the new float or value_string: the string given ...
bigcode/self-oss-instruct-sc2-concepts
def computeContinuousStatistics(df): """computeContinuousStatistics Computes statistics for continuous features. Input: df -- DataFrame to use Output: {} -- a dictionary containing the statistics """ # returning the final statistics return { 'count': len(df), 'miss_percentage': ((len(df)-df...
bigcode/self-oss-instruct-sc2-concepts
def bezier( x1,y1, x2,y2, x3,y3, x4,y4, t ): """ Returns coordinates for t (=0.0...1.0) on curve segment. x1,y1 and x4,y4: coordinates of on-curve nodes x2,y2 and x3,y3: coordinates of BCPs """ x = x1*(1-t)**3 + x2*3*t*(1-t)**2 + x3*3*t**2*(1-t) + x4*t**3 y = y1*(1-t)**3 + y2*3*t*(1-t)**2 + y3*3*t**2*(1-t) +...
bigcode/self-oss-instruct-sc2-concepts
def getInputTimeSteps(algorithm, port=0, idx=0): """Get the timestep values for the algorithm's input Args: algorithm (vtkDataObject) : The data object (Proxy) on the pipeline (pass `self` from algorithm subclasses) port (int) : the input port idx (int) : optional : the con...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from pathlib import Path def console_script_exists(site_packages_dirs: List[Path], console_script: str) -> bool: """Return true if the console script with provided name exists in one of the site-packages directories. Console script is expected to be in the 'bin' directory of site pack...
bigcode/self-oss-instruct-sc2-concepts
import re def seqs_from_stats(statfile): """Looks in the specified file for a line "SN sequences: {\d+}" and returns the number. If the file is not found or the line is not found returns None. """ try: with open(statfile) as sfh: for line in sfh: mo = ...
bigcode/self-oss-instruct-sc2-concepts
def actionmessage(case, mass=False): """ Default way to present action confirmation in chat """ output = f"**{case}** the user" if mass: output = f"**{case}** the IDs/Users" return f"✅ Successfully {output}"
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def unicode_to_ascii(sentence): """ Converts the unicode file to ascii :param sentence: str/unicode :return: str """ return ''.join(c for c in unicodedata.normalize('NFD', sentence) if unicodedata.category(c) != 'Mn')
bigcode/self-oss-instruct-sc2-concepts
def is_WORD(c): """ :param c character to check :returns True if c is not whitespace """ return c and not c.isspace()
bigcode/self-oss-instruct-sc2-concepts
def generate_playready_object(wrmheader): """ Generate a playready object from a wrmheader """ return ((len(wrmheader) + 10).to_bytes(4, "little") + # overall length (1).to_bytes(2, "little") + # record count (1).to_bytes(2, "little") + #...
bigcode/self-oss-instruct-sc2-concepts
def identity(X, y): """Identity operation. Parameters ---------- X : torch.Tensor EEG input example or batch. y : torch.Tensor EEG labels for the example or batch. Returns ------- torch.Tensor Transformed inputs. torch.Tensor Transformed labels. ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def getframeinfo(frame, context=1): """ Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line wi...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def _compute_offsets(inputs): """ Compute offsets of real inputs into the concatenated Gaussian dims. This ignores all int inputs. :param OrderedDict inputs: A schema mapping variable name to domain. :return: a pair ``(offsets, total)``, where ``offsets`` is an Orde...
bigcode/self-oss-instruct-sc2-concepts
def str2dict(strdict): """Convert key1=value1,key2=value2,... string into dictionary. :param strdict: key1=value1,key2=value2 Note: This implementation overrides the original implementation in the neutronclient such that it is no longer required to append the key with a = to specify a corresponding...
bigcode/self-oss-instruct-sc2-concepts
def inventree_github_url(*args, **kwargs): """ Return URL for InvenTree github site """ return "https://github.com/InvenTree"
bigcode/self-oss-instruct-sc2-concepts
def always_false(value): """A function that always returns False.""" return False
bigcode/self-oss-instruct-sc2-concepts
def ls_props(thing): """List all of the properties on some object :param thing: Some object :return: The list of properties """ return [x for x in dir(thing) if isinstance(getattr(type(thing), x, None), property)]
bigcode/self-oss-instruct-sc2-concepts
def kbytes(text): """convert memory text to the corresponding value in kilobytes Args: text (str): string corresponding to an abbreviation of size. Returns: int representation of text. Examples: >>> kbytes(\'10K\') 10 >>> >>> kbytes(\'10G\') 10...
bigcode/self-oss-instruct-sc2-concepts
import re def getKeepAlive(response): """Extracts and returns the keep alive token from the response. Extracts and returns the actual keep-alive token from within the response; this token enables subsequent requests for CSV data. Args: response: The Python requests response object, typically correspon...
bigcode/self-oss-instruct-sc2-concepts
def data_checker(task_name): """ Verify if a task associated to a dataset is valid in maxsmi. Parameters ---------- task_name : str The considered physical chemical task. Returns ------- bool : True if the name is valid. Raises an error otherwise. """ if task_na...
bigcode/self-oss-instruct-sc2-concepts