seed
stringlengths
1
14k
source
stringclasses
2 values
def set_data_types(data_types=["userAcceleration"]): """ Select the sensors and the mode to shape the final dataset. Args: data_types: A list of sensor data type from this list: [attitude, gravity, rotationRate, userAcceleration] Returns: It returns a list of columns to use for cr...
bigcode/self-oss-instruct-sc2-concepts
def false_to_none(ctx, param, value): """Convert a false value to a None""" if value: retval = True else: retval = None return retval
bigcode/self-oss-instruct-sc2-concepts
import random def face(x, y): """ Calculates points to fill in order to plot a smiley-face on a graph of x and y dimensions Parameters ---------- x: x-axis resolution (how many points desired in x-axis) y: y-axis resolution (how many points desired in y-axis) ...
bigcode/self-oss-instruct-sc2-concepts
def convert_big_str_numbers(big_num): """Convert big number written with numbers and words to int. Args: big_num (str): number, written with numbers and words. Returns: int: same number as an int. Examples: >>>print(convert_big_str_numbers('101.11 billions')) 101110000...
bigcode/self-oss-instruct-sc2-concepts
import re def read_header(ds): """Read a RAMSES output header file.""" folder = './' iout = int(str(ds)[-5:]) hname = '{0}/output_{1:05d}/header_{1:05d}.txt'.format(folder, iout) with open(hname, 'r') as hfile: htxt = hfile.read() header_re = re.compile("Total number of particles\s+(...
bigcode/self-oss-instruct-sc2-concepts
def collect_vertices(geometry): """Returns all vertices within the given geometry as a list.""" vertices = [] vertices_iter = geometry.vertices() while vertices_iter.hasNext(): vertices.append(vertices_iter.next()) return vertices
bigcode/self-oss-instruct-sc2-concepts
def convert_keys_to_variable_names(dict_): """ Change keys in dict to comply with PEP8 for variable names. Keys are converted to all lower case and spaces replaced with underscores. Parameters ---------- dict_ : :class:`dict` Dictionary the keys should be renamed in Returns --...
bigcode/self-oss-instruct-sc2-concepts
import binascii def pem_to_der(pem_str): """Convert a PEM string to DER format""" lines = pem_str.strip().splitlines() der = binascii.a2b_base64(''.join(lines[1:-1])) return der
bigcode/self-oss-instruct-sc2-concepts
def parse_requirements(filename): """Given a filename, strip empty lines and those beginning with #.""" with open(filename) as rfd: output = [] for line in rfd: line = line.strip() if line != '' and not line.startswith('#'): output.append(line) ret...
bigcode/self-oss-instruct-sc2-concepts
def get_gene_class(gene): """ Return the class of a gene. Available options are Core or Non-core. """ core_genes = ['pif-0', 'pif-1', 'pif-2', 'pif-3', 'pif-4', 'pif-5', 'pif-6', 'pif-7', 'pif-8', 'dnapol', 'desmoplakin', 'dnahe...
bigcode/self-oss-instruct-sc2-concepts
def _create_database_sql(database_name): """Return a tuple of statements to create the database with the given name. :param database_name: Database name :type: str :rtype: tuple """ tmpl = "create database {} with owner = dcc_owner template = template0 " \ "encoding = 'UTF8' lc_collat...
bigcode/self-oss-instruct-sc2-concepts
def drop_columns(cols): """Drop columns in a DataFrame.""" def dropper(data): return data.drop(columns=cols) return dropper
bigcode/self-oss-instruct-sc2-concepts
def GetModulePath(obj): """Returns the module path string for obj, None if its builtin. The module path is relative and importable by ImportModule() from any installation of the current release. Args: obj: The object to get the module path from. Returns: The module path name for obj if not builtin ...
bigcode/self-oss-instruct-sc2-concepts
import torch def uniform_sample_shape(batch_size, mean_shape, delta_betas_range): """ Uniform sampling of shape parameter deviations from the mean. """ l, h = delta_betas_range delta_betas = (h-l)*torch.rand(batch_size, mean_shape.shape[0], device= mean_shape.device) + l shape = delta_betas + ...
bigcode/self-oss-instruct-sc2-concepts
def depth(expr): """ depth(expr) finds the depth of the mathematical expr formatted as a list. depth is defined as the deepest level of nested operations within the expression. """ if not isinstance(expr, list): raise TypeError("depth() : expr must be of type list") else: exprlen...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import pkg_resources def get_current_environment_requirements() -> Dict[str, str]: """Return package requirements for current python process. Returns: A dict of package requirements for current environment """ return { distribution.key: distribution.version ...
bigcode/self-oss-instruct-sc2-concepts
def squareroot(n: int) -> str: """Return string vertion of int prepended with a unicode radical symbol. Useful for pretty printing elements of, for example, a quadratic field. Example: >>> print(squareroot(5)) √5 """ return u"\u221A"+str(n)
bigcode/self-oss-instruct-sc2-concepts
def get_maximum_telemetry_message_size(client): """ Returns the maximum message size (in bytes) the client can support """ if client.settings.language == "java" and client.settings.transport == "amqpws": # java amqpws limitation. Actual number is unknown. This just blocks 63K+ tests. #...
bigcode/self-oss-instruct-sc2-concepts
import torch def gershgorin_bounds(H): """ Given a square matrix ``H`` compute upper and lower bounds for its eigenvalues (Gregoshgorin Bounds). """ H_diag = torch.diag(H) H_diag_abs = H_diag.abs() H_row_sums = H.abs().sum(dim=1) lb = torch.min(H_diag + H_diag_abs - H_row_sums) ub ...
bigcode/self-oss-instruct-sc2-concepts
def to_bytes(s): """ Turns the string with suffix of KiB/MiB/GiB into bytes. :param s: the string (NUM SUFFIX) :type s: str :return: the number of bytes :rtype: int """ factor = 1 if s.endswith(" KiB"): factor = 1024 s = s[:-4].strip() elif s.endswith(" MiB"): ...
bigcode/self-oss-instruct-sc2-concepts
import socket def find_unused_port(base=1025, maxtries=10000): """Helper function. Finds an unused server port""" if base > 65535: base = 1025 for _ in range(maxtries): serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: serversocket.bind(("localhost",...
bigcode/self-oss-instruct-sc2-concepts
def capitalize(line): """Capitalize the first char in a string string.capitalize messes up deliberate upper cases in the strings so here's a dedicated function. Args: line (str): The string to capitalize Returns: str: The capitalized string """ return line[0].upper() + l...
bigcode/self-oss-instruct-sc2-concepts
import csv def parse_csv_data(csv_filename: str) -> list: """A function thats takes in the name of a csv file and returns a list of strings for the rows in the file""" rows = [] # a list containing the strings for the rows with open("{}".format(csv_filename)) as csv_file: csv_reader = csv.reade...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def to_factorial_base(n: int) -> List[int]: """ Convert a nonnegative integer to its representation in the `factorial number system <https://en.wikipedia.org/wiki/Factorial_number_system>`_ (represented as a list of digits in descending order of place value, not including t...
bigcode/self-oss-instruct-sc2-concepts
def normalize (bbox): """ Normalizes EPSG:4326 bbox order. Returns normalized bbox, and whether it was flipped on horizontal axis. """ flip_h = False bbox = list(bbox) while bbox[0] < -180.: bbox[0] += 360. bbox[2] += 360. if bbox[0] > bbox[2]: bbox = (bbox[0],bbox[1],bbox[2]...
bigcode/self-oss-instruct-sc2-concepts
def bandwidth_converter( number, *, from_unit, to_unit, from_time="seconds", to_time="seconds" ): """ Bandwidth Calculator. Convert data rate from one unit to another. Arguments: number (int): number to be converted Keyword arguments: from_unit (str): convert from this da...
bigcode/self-oss-instruct-sc2-concepts
def checkNull(dummy_dictionary): """Given a dictionary, checks if any of the values is null""" return None in list(dummy_dictionary.values())
bigcode/self-oss-instruct-sc2-concepts
import re def camel_case_to_snake_case(s): """Convert string in CamelCase to snake_case. Args: s (str): String in CamelCase. Returns: str: String in snake_case. """ _underscorer1 = re.compile(r"(.)([A-Z][a-z]+)") _underscorer2 = re.compile("([a-z0-9])([A-Z])") subbed = _und...
bigcode/self-oss-instruct-sc2-concepts
def get_yesno_input(text): """ Gets a yes/no input from the user. The user can type "y" for yes or "n" for no. :param text: Text to ask user (the yes-no question) :return: True for yes and False for no """ while True: user_input = input(text + " [y/n] ") if user_input[0] == 'y': ...
bigcode/self-oss-instruct-sc2-concepts
def get_accel_y(fore_veh, back_veh, ego_vy, idm_model): """ A wrapper around IDM, given a front and a back vehicle (and the absolute speed), and a longitudinal driver model, this function returns the desired acceleration of the back vehicle. Arguments fore_vehicle: A vehicle object, f...
bigcode/self-oss-instruct-sc2-concepts
def append_df_columns(dataframe1, dataframe2, dataframe2_col_name, new_appended_col_name): """Appends a column of data from one dataframe to another dataframe Args: dataframe1 (df): Dataframe to append new column on dataframe2 (df): Dataframe to pull column of data from dataframe2_col_na...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_key(key): """ Return false if key is not alphnumeric or start with letter """ if key == "": return False # check if no invalid charaters if key.isalnum(): # check if first char is letter return key[:1].isalpha() return False
bigcode/self-oss-instruct-sc2-concepts
import timeit def depthwise_conv_timer_mxnet(c, n, k, ctx): """Benchmark convolution in MXNet c : input, output channels n : input width and height k : kernel width and height """ timer = timeit.Timer( setup='import d2ltvm\n' 'import mxnet as mx\n' 'c, n, k, p, s = %d,...
bigcode/self-oss-instruct-sc2-concepts
def get_file_content(file_path): """Return content of a file.""" return open(file_path).read().strip()
bigcode/self-oss-instruct-sc2-concepts
def get_unique_instruments_in_channel(notes_in_channel): """ Utility function to get an ordered set of unique instruments in the channel """ all_instruments = [] for notes in notes_in_channel: all_instruments.append(notes.program) return sorted(set(all_instruments))
bigcode/self-oss-instruct-sc2-concepts
def attr(elem, attr): """An html attribute from an html element. E.g. <a href="">, then attr(elem, "href") will get the href or an empty string.""" try: return elem[attr] except: return ""
bigcode/self-oss-instruct-sc2-concepts
import math def vd(inc, sd): """ Calculate vertical distance. :param inc: (float) inclination angle in degrees :param sd: (float) slope distance in any units """ return abs(sd * math.sin(math.radians(inc)))
bigcode/self-oss-instruct-sc2-concepts
def module_import(app_path): """ Imports a module in a given path. :param str app_path: A string that contains the path of the module and it's name. :returns: A reference to the module in the given path. """ module = __import__(app_path) for part in app_path.split('.')[1:]: ...
bigcode/self-oss-instruct-sc2-concepts
def canonize_dtypes_and_names(a=None, t=None, y=None, w=None, X=None): """ Housekeeping method that assign names for unnamed series and canonizes their data types. Args: a (pd.Series|None): Treatment assignment of size (num_subjects,). t (pd.Series|None): Followup duration, size (num_subjec...
bigcode/self-oss-instruct-sc2-concepts
def intervalComparison(x, lowerBound, upperBound): """ classify a value relative to the interval between two bounds: returns -1 when below the lower bound returns 0 when between the bounds (inside the interval) returns +1 when above the upper bound """ if (x < lowerBound): return -1 if (x > upperBound): return...
bigcode/self-oss-instruct-sc2-concepts
import itertools def make_range(start, end): """Return a generator of the time steps to iterate over""" if end is None: return itertools.count(start=start, step=1) else: return range(start, end)
bigcode/self-oss-instruct-sc2-concepts
import inspect def deduce_protobuf_types(fn): """ Try to extract the class names that are attached as the typing annotation. :param fn: the function with the annotated parameters. :return: a list of classes or None. """ spec = inspect.getfullargspec(fn) if not spec: return None ...
bigcode/self-oss-instruct-sc2-concepts
import math def inverse_mercator(xy): """ Given coordinates in spherical mercator, return a lon,lat tuple. """ lon = (xy[0] / 20037508.34) * 180 lat = (xy[1] / 20037508.34) * 180 lat = 180 / math.pi * \ (2 * math.atan(math.exp(lat * math.pi / 180)) - math.pi / 2) return (lon, lat)
bigcode/self-oss-instruct-sc2-concepts
import collections def filter_words(line, count): """ Filter words in documents less than count. """ cnt = collections.Counter() for sentence in line: cnt.update(sentence) s = set(word for word in cnt if cnt[word] < count) l_temp = [[word for word in sentence if word not in s] for sentenc...
bigcode/self-oss-instruct-sc2-concepts
def _user_info(user): """Format a user.""" return { "id": user.id, "name": user.name, "is_owner": user.is_owner, "is_active": user.is_active, "system_generated": user.system_generated, "group_ids": [group.id for group in user.groups], "credentials": [{"typ...
bigcode/self-oss-instruct-sc2-concepts
import re def clean_name(name): """cleans a name by removing all non-alphabets""" regex = re.compile('[^a-zA-Z]') return regex.sub('', name)
bigcode/self-oss-instruct-sc2-concepts
def model(k, alpha, beta, gamma): """Returns values of alpha-beta-gamma model at given k values Parameters ---------- k : array alpha, beta, gamma : float Parameters of model """ T = (1 + (alpha * k) ** beta) ** gamma return T
bigcode/self-oss-instruct-sc2-concepts
def rgb2gray(rgb_img): """ Parameters ---------- rgb_img : numpy array with shape as (3, X, Y) image to convert in gray Returns ------- gray_img , the grayscale image """ gray_coef = [0.2989, 0.5870, 0.1140] r = rgb_img[0] / 255 g = rgb_img[1] / 255 b = rgb_img[...
bigcode/self-oss-instruct-sc2-concepts
def _map_theme(theme: str) -> str: """Maps a survey schema theme to a design system theme :param theme: A schema defined theme :returns: A design system theme """ if theme and theme not in ["census", "census-nisra"]: return "main" return "census"
bigcode/self-oss-instruct-sc2-concepts
def getFileExtension(f) : """Gets the file extension, and returns it (in all lowercase). Returns None if file has no extension. Keyword arguments: f - file name possibly with path """ i = f.rfind(".") return f[i+1:].lower() if i >= 0 and f.rfind("/") < i else None
bigcode/self-oss-instruct-sc2-concepts
def set_cat_default(available_options): """Callback to set category dropdown default value. Args: available_options: list of categories from dropdown Returns: first value from category dropdown to set as default dropdown value """ return available_op...
bigcode/self-oss-instruct-sc2-concepts
def multi_cdf(m, bound, capacity, f): """ This function computes the value of the cdf of the multivariate random variable (X1+X2+...Xn). For a given distribution it gives back the probability, if the sum of the random variables is lower or equal to a specific bound. Therefore it uses the feasible_me...
bigcode/self-oss-instruct-sc2-concepts
def update_log_level(logger, level): """Update the logging level. Args: logger (:class:`logging.Logger`): Logger to update. level (Union[str, int]): Level given either as a string corresponding to ``Logger`` levels, or their corresponding integers, ranging from 0 (``...
bigcode/self-oss-instruct-sc2-concepts
import io def tobytes(image): """Convert an image object to a PNG byte array""" data = io.BytesIO() image.save(data, format='PNG') return data.getvalue()
bigcode/self-oss-instruct-sc2-concepts
def spherocylinder_aspect_ratio(l, R): """Return the aspect ratio of a spherocylinder, Parameters ---------- l: float Length of the cylinder section. R: float Radius of the hemispheres and cylinder sections. Returns ------- ar: float Aspect ratio. This i...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def create_result_dict() -> Dict: """ Create the results dictionary """ return {"Vulnerable Library": None, "Version": None, "Language": None, "Vulnerability": None, "CVE": None, "CVSS": None, "Upgrade to Version": None}
bigcode/self-oss-instruct-sc2-concepts
def hex_color_to_tuple(hex): """ convent hex color to tuple "#ffffff" -> (255, 255, 255) "#ffff00ff" -> (255, 255, 0, 255) """ hex = hex[1:] length = len(hex) // 2 return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))
bigcode/self-oss-instruct-sc2-concepts
def reverse(pattern): """Reverse a string sequence. For example, if we reverse the string 'ACGT', we would get 'TGCA'.. Args: pattern (str): a DNA string (i.e. pattern). Returns: String, a reversed string of the given pattern. Examples: Reverse a pattern string. ...
bigcode/self-oss-instruct-sc2-concepts
def python_3000_has_key(logical_line): """ The {}.has_key() method will be removed in the future version of Python. Use the 'in' operation instead, like: d = {"a": 1, "b": 2} if "b" in d: print d["b"] """ pos = logical_line.find('.has_key(') if pos > -1: return pos, "W601...
bigcode/self-oss-instruct-sc2-concepts
def _sanitize_url(url): """ Makes sure that the URL ends with a trailing ``/`` for Pooch. Parameters ---------- url : str The URL for downloading the data, with or without a trailing ``/``. Returns ------- url : str Sanitized download URL. """ if not url.endswit...
bigcode/self-oss-instruct-sc2-concepts
def db_name() -> str: """Database name""" return 'olist_ecommerce'
bigcode/self-oss-instruct-sc2-concepts
def _fullname(o): """Return the fully-qualified name of a function.""" return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__
bigcode/self-oss-instruct-sc2-concepts
import posixpath def join_paths(a, *p): """ Joins multiple paths and ensures that the '/' is removed from the end. Any path in *p that starts with / will be have the / removed. """ return posixpath.join(a, *(i.lstrip('/') for i in p)).rstrip('/')
bigcode/self-oss-instruct-sc2-concepts
def get(obj, field): """ Extracts field value from nested object :type obj: ``dict`` :param obj: The object to extract the field from :type field: ``str`` :param field: The field to extract from the object, given in dot notation :return: The value of the extracted field :rtype: ``str`...
bigcode/self-oss-instruct-sc2-concepts
def pick_id(id, objects): """pick an object out of a list of objects using its id """ return list(filter(lambda o: o["id"] == id, objects))
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from pathlib import Path from typing import List def read_exclusion_file(path: Optional[Path] = None) -> List[str]: """Read a .exclusion file to determine which files should not be automatically re-generated in .GitIgnore format """ if path is None: path = Path("."...
bigcode/self-oss-instruct-sc2-concepts
def check_ascii(text: str) -> bool: """Check is a string is ASCII. Args: text (str): The string to check. Returns: bool: False means the text was not ASCII. """ if any(ord(c) >= 128 for c in text): return False return True
bigcode/self-oss-instruct-sc2-concepts
def create_fields(instance, **kwargs): """Return dict of fields to be used as create params.""" site = kwargs.pop("site", instance.site) creation_user = kwargs.pop("creation_user", instance.creation_user) effective_user = kwargs.pop("effective_user", instance.effective_user) update_user = kwargs.pop...
bigcode/self-oss-instruct-sc2-concepts
def get_actual_source_freqs(messages_dets, expected_source_freqs): """ Check the message sources are as expected. Note - we don't have to know what messages generated from helpers in other modules will do - just what we expect from this module. So we don't specify what sources we expect - just those...
bigcode/self-oss-instruct-sc2-concepts
from math import sqrt def distance(x1, y1, z1, x2, y2, z2, round_out=0): """ distance between two points in space for orthogonal axes. >>> distance(1, 1, 1, 2, 2, 2, 4) 1.7321 >>> distance(1, 0, 0, 2, 0, 0, 4) 1.0 """ d = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2) if ro...
bigcode/self-oss-instruct-sc2-concepts
def get_models(config): """ Get a list of the models in the source database Args: config (:obj:`dict`): configuration Returns: :obj:`list` of :obj:`dict`: models """ response = config['source_session'].get(config['source_api_endpoint'] + '/models') response.raise_for_status() ...
bigcode/self-oss-instruct-sc2-concepts
import json def from_json(value): """ Decodes a JSON string into an object. :param str value: String to decode :returns: Decoded JSON object """ return json.loads(value)
bigcode/self-oss-instruct-sc2-concepts
def scheming_field_required(field): """ Return field['required'] or guess based on validators if not present. """ if 'required' in field: return field['required'] return 'not_empty' in field.get('validators', '').split()
bigcode/self-oss-instruct-sc2-concepts
def replace_from_to(text, start_position, end_position, new_text): """ Replaces the substring within the given range against another text.""" return "{}{}{}".format(text[:start_position], new_text, text[end_position:])
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def get_flags(args: List[str]) -> Dict[str, List[str]]: """ Returns a dictionary containing the flags within the passed through command line arguments. # Example ```py # $ py ./src/main.py normal_argument -flag1 Hello, World ...
bigcode/self-oss-instruct-sc2-concepts
def len_selfies(selfies: str) -> int: """Returns the number of symbols in a given SELFIES string. :param selfies: a SELFIES string. :return: the symbol length of the SELFIES string. :Example: >>> import selfies as sf >>> sf.len_selfies("[C][=C][F].[C]") 5 """ return selfies.count...
bigcode/self-oss-instruct-sc2-concepts
def parse_log_level_names(str_log_level_names): """20:INFO,30:WARN,40:ERROR,50:FATAL""" if not str_log_level_names: return {} log_levels = str_log_level_names.split(",") log_levels = [item.split(":") for item in log_levels] level_names = {int(level): name for level, name in log_levels} ...
bigcode/self-oss-instruct-sc2-concepts
def checkXML(XML, path): """Looks for path to XML tag and pulls out the text therein.""" if XML.find(path) is not None: if XML.find(path).text is not None: return XML.find(path).text else: return "" else: return ""
bigcode/self-oss-instruct-sc2-concepts
def compute_mean(sample): """Computes sample mean""" return sum(sample) / float(len(sample) or 1)
bigcode/self-oss-instruct-sc2-concepts
def to_pascalcase(s: str) -> str: """convert a python identifier string to pascal case. Examples: >>> to_pascalcase('my_identifier') myIdentifier >>> to_pascalcase('my_long_identifier') myLongIdentifier >>> to_pascalcase('crab') crab """ first, *other = s...
bigcode/self-oss-instruct-sc2-concepts
def count_lines(input_file) -> int: """Count the lines of a given file Args: input_file (str): The file to open Returns: int: An integer that shows the line number """ with open(input_file) as f: return sum(1 for line in f)
bigcode/self-oss-instruct-sc2-concepts
def getCanonicalSvnPath(path): """Returns the supplied svn repo path *without* the trailing / character. Some pysvn methods raise exceptions if svn directory URLs end with a trailing / ("non-canonical form") and some do not. Go figure... """ if path and path.endswith('/'): path = path[:-1] return path
bigcode/self-oss-instruct-sc2-concepts
def _paths_for_iter(diff, iter_type): """ Get the set for all the files in the given diff for the specified type. :param diff: git diff to query. :param iter_type: Iter type ['M', 'A', 'R', 'D']. :return: set of changed files. """ a_path_changes = {change.a_path for change in diff.iter_chan...
bigcode/self-oss-instruct-sc2-concepts
import json def to_json(content: str) -> dict: """ deserialize the str to JSON object \n :param content: the target json str :return: the JSON object :rtype dict """ return json.loads(content)
bigcode/self-oss-instruct-sc2-concepts
def remove_white_space(input): """Remove all types of spaces from input""" input = input.replace(u"\xa0", u" ") # remove space # remove white spaces, new lines and tabs return " ".join(input.split())
bigcode/self-oss-instruct-sc2-concepts
def safe_int(string): """ Utility function to convert python objects to integer values without throwing an exception """ try: return int(string) except ValueError: return None
bigcode/self-oss-instruct-sc2-concepts
def directory_in_zip(zip_f, directory_name): """Determine if a directory exists in a ZIP""" return any(x.startswith("%s/" % directory_name.rstrip("/")) for x in zip_f.namelist())
bigcode/self-oss-instruct-sc2-concepts
import ast from typing import Tuple from typing import Type def is_contained(node: ast.AST, to_check: Tuple[Type[ast.AST], ...]) -> bool: """Checks whether node does contain given subnode types.""" for child in ast.walk(node): if isinstance(child, to_check): return True return False
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def timestamp() -> str: """Timestamp that can be used in a file name.""" return datetime.now().isoformat().replace(":", "-")
bigcode/self-oss-instruct-sc2-concepts
import re def split_string_on_punctuation(text): """Split on ?!.,; - e.g. "hi, how are you doing? blabla" -> ['hi', 'how are you doing', 'blabla'] (make sure you strip trailing spaces)""" pattern = r'[?!.,;][\s]*' return [i for i in re.sub(pattern, "|", text).split("|") if i != ""] pass
bigcode/self-oss-instruct-sc2-concepts
import json def getResponseUrl(response): """ Get the return url from a hosted payment API call :param response: Response object in JSON :return: Transaction ID """ resp_dict = json.loads(response.text) try: url = resp_dict["url"] except KeyError: print('Retrieval uns...
bigcode/self-oss-instruct-sc2-concepts
def prefix_max(array: list, i: int) -> int: """Return index of maximum item in array[:i+1]""" if i >= 1: j = prefix_max(array, i-1) if array[i] < array[j]: return j return i
bigcode/self-oss-instruct-sc2-concepts
def formatDollars(d,noneValue='',zeroValue='$0'): """Formats a number as a whole dollar value with alternatives for None and 0.""" if d is None: return noneValue elif d==0: return zeroValue return '${:.0f}'.format(d)
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any def pad(sents: List[List[Any]], pad_token: Any): """ Pad list of sentences according to the longest sentence in the batch. @param sents: list of sentences, where each sentence is represented as a list of words @param pad_to...
bigcode/self-oss-instruct-sc2-concepts
def parse_optionalString(value): """parse an optional string""" if not value: return None return value
bigcode/self-oss-instruct-sc2-concepts
def get_base_req(req): """Get the name of the required package for the given requirement.""" if isinstance(req, tuple): req = req[0] return req.split(":", 1)[0]
bigcode/self-oss-instruct-sc2-concepts
def optimize(f, g, c, x0, n, count, prob): """ Args: f (function): Function to be optimized g (function): Gradient function for `f` c (function): Function evaluating constraints x0 (np.array): Initial position to start from n (int): Number of evaluations allowed. Remember...
bigcode/self-oss-instruct-sc2-concepts
def addition(num1, num2=0): """ Adds two numbers Args: num1: The first number num2: The second number, default 0 Returns: The result of the addition process """ return (num1+num2)
bigcode/self-oss-instruct-sc2-concepts
def build_n_sequence_dictionary(n : int, txt : str) -> dict: """ Returns a dict counting appearances of n-long progressions Parameters ---------- n : int The length of progressions to count txt : str A comma-separated string of roman numerals Returns ------- dict ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def rb2coco_bbox( rb_label: Dict, label_id: int, image_id: int, category_id: int, width: int, height: int, ) -> Dict: """Convert rb bbox to coco bbox.""" assert rb_label["bbox2d"] xnorm = rb_label["bbox2d"]["xnorm"] ynorm = rb_label["bbox2d"]["ynorm"] ...
bigcode/self-oss-instruct-sc2-concepts