seed
stringlengths
1
14k
source
stringclasses
2 values
def read_voca(path): """ open file from path and read each line to return the word list """ with open(path, 'r') as f: return [word.strip() for word in f.readlines()]
bigcode/self-oss-instruct-sc2-concepts
import locale def get_day_name(day): """ Get the short day name in the currently activated locale. :param day: :return: day 0 = Sunday """ # Locale keys are 1=Sun, 2=Mon, ... locale_key = "ABDAY_%d" % (1 + day) option = getattr(locale, locale_key) day_name = locale.nl_langinfo(...
bigcode/self-oss-instruct-sc2-concepts
def color_to_str(C): """Convert color value to hex string.""" # Scale from [0-1] to [0-255] V = [int(round(c * 255)) for c in C] # Clamp values to [0-255] for i in range(len(V)): V[i] = max(min(V[i], 255), 0) return '#{:02X}{:02X}{:02X}'.format(V[0], V[1], V[2])
bigcode/self-oss-instruct-sc2-concepts
import struct def decode_ga(ga: int) -> str: """ Decodes a group address into human readable string representation >>> decode_ga(270) '0/1/14' """ if not isinstance(ga, int): ga = struct.unpack('>H', ga)[0] return '{}/{}/{}'.format((ga >> 11) & 0x1f, (ga >> 8) & 0x07, (ga) & 0xff)
bigcode/self-oss-instruct-sc2-concepts
def ccw(a, b, c): """ 1: c is left of the line a->b -1: c is on the right of line a->b 0: c is on the line a->b >>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 8)) 0 >>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 9)) 1 >>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 7)) -1 """ ...
bigcode/self-oss-instruct-sc2-concepts
import ast def get_literal_tuple(param_type): """ get literal option from annotation string and return result in tuple. """ s_index: int = str(param_type).index('[') e_index: int = str(param_type).index(']') str_list = str(param_type)[s_index + 1:e_index] res = ast.literal_eval(str_list) ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List def get_all_files_in_directory(path: Path) -> List[Path]: """ Returns all the files in a directory structure. For example, given a directory structure like:: dir_a: dir_b, file_a, file_b dir_b: file_c and you provide the path to ``dir...
bigcode/self-oss-instruct-sc2-concepts
import copy def get_object_state(obj, ignore_attributes=()): """Returns a dictionary with the state of the attributes of an object. Note that this is not general. For example, it will throw an error for classes that define a __slots__ field (like namedtuples). Args: obj: a Python object ignore_attri...
bigcode/self-oss-instruct-sc2-concepts
def remove_trailings(input_string): """ Remove duplicated spaces. """ output_string = " ".join(input_string.split()) return output_string
bigcode/self-oss-instruct-sc2-concepts
def scaleFromRedshift(redshift): """ Converts a redshift to a scale factor. :param redshift: redshift of the object :type redshift: float or ndarray :return: scale factor :rtype: float or ndarray """ return 1. / (redshift + 1.)
bigcode/self-oss-instruct-sc2-concepts
def calc_f_number(aperture_diameter, focal_length): """ Calculate the f-number N (or f#) of an optical system. https://en.wikipedia.org/wiki/F-number Returns ------- double : no units """ return focal_length / aperture_diameter
bigcode/self-oss-instruct-sc2-concepts
def timezone_format(value): """ Check the value of the timezeone offset and, if postive, add a plus sign""" try: if int(value) > 0: value = '+' + str(value) except: value = '' return value
bigcode/self-oss-instruct-sc2-concepts
def fastFib(n, memo = {}): """ Assumes n is an int >= 0, memo used only by recursive calls Returns Fibonacci of n """ if n == 0 or n == 1: return 1 try: return memo[n] except KeyError: result = fastFib(n-1, memo) + fastFib(n-2, memo) memo[n] = result ...
bigcode/self-oss-instruct-sc2-concepts
def escape_for_query(query_part: str) -> str: """Escapes all characters reserved by jriver in a natural string. Do not put a complete query in here - this method is used to escape reserved characters in a natural string that will be used as a query fragment. This is usually the content of a field (e.g....
bigcode/self-oss-instruct-sc2-concepts
def create_firmware_update_payload(device_info: dict, compliance_data_list: list) -> list: """ Creates the payload to send to OME to execute the firmware update Args: device_info: A dictionary of dictionaries containing the type information for each device compliance_data_list: A list of di...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def mapProfiles(settings): """Profile ID mapped to index in the list in an OrderedDict""" profileMap = OrderedDict() i = 0 print(settings) while i < len(settings): if "profileID" in settings[i]: index = settings[i]["profileID"] profil...
bigcode/self-oss-instruct-sc2-concepts
def test_datasource_connection(connection, body, error_msg=None): """Test a datasource connection. Either provide a connection id, or the connection parameters within connection object. Args: connection: MicroStrategy REST API connection object. body: Datasource Connection info. err...
bigcode/self-oss-instruct-sc2-concepts
def _noto_relative_path(filepath): """Return relative path from some noto root, or None""" x = filepath.find('noto-fonts') if x == -1: x = filepath.find('noto-cjk') if x == -1: x = filepath.find('noto-emoji') if x == -1: return None return filepath[x:]
bigcode/self-oss-instruct-sc2-concepts
import jinja2 def load_template(in_template): """ Returns a jinja2 template from file. Parameters --------- in_template: str path and name of jinja2 template Returns ------- output_template: jinja template object """ with open(in_template, 'r') as default: output_...
bigcode/self-oss-instruct-sc2-concepts
def parse_ptimes(ln): """ Mini function for getting the time (in a string) from a line of an errlog file. """ timestring = ln.split(" ")[3] return timestring
bigcode/self-oss-instruct-sc2-concepts
def wrap(x, low, high): """Wraps data between low and high boundaries.""" diff = high - low while x > high: x -= diff while x < low: x += diff return x
bigcode/self-oss-instruct-sc2-concepts
def _get_chunks(text, length=200, overlap=50): """Splits text into chunks Args: text (str): Text length (int, optional): Chunk length. Defaults to 200 overlap (int, optional): Chunk overlap. Defaults to 50 Return: list: Text chunks """ l_total = [] l_partial = ...
bigcode/self-oss-instruct-sc2-concepts
def _get_header(soup): """Extract the column names from the "list-row-headings" class. Parameters ---------- soup: bs4.BeautifulSoup The html web page. Returns ------- list Each element is a string with a column name. """ column_heading_class = "list-row-headings" ...
bigcode/self-oss-instruct-sc2-concepts
def getDistance (origin, point): """ Returns the distance between two points. """ dist = ((origin[0]-point[0])**2 + (origin[1]-point[1])**2)**0.5 return dist
bigcode/self-oss-instruct-sc2-concepts
def cart_count(a) -> int: """ Count the number of items in the cart. :param a: List of products. Untyped as I'm unsure how 'dict_items' type truly works. :return: Int of the number of items in the cart. """ count = 0 # a is of type 'dict_items' for i, this_tuple in enumerate(a): ...
bigcode/self-oss-instruct-sc2-concepts
import re def confirm(prompt, default='y'): """Confirmation prompt.""" default = default.lower() if default not in ['y', 'n']: default = 'y' choicebox = '[Y/n]' if default == 'y' else '[y/N]' prompt = prompt + ' ' + choicebox + ' ' while True: some_input = input(prompt).strip(...
bigcode/self-oss-instruct-sc2-concepts
def check_if_number_even(n): """ checks if int n is an even number """ if (n % 2) == 0: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def is_close(first, second, rel_tol=1e-09, abs_tol=0.0): """ Almost equality for float numbers :param first :param second :param rel_tol: relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference ...
bigcode/self-oss-instruct-sc2-concepts
def user_id(uid): """Google user unique id to feedly ``:user_id`` format :param uid: Google unique account UUID :type uid: :class:`basestring` :returns: :rtype: :class:`basestring` >>> user_id('00000000-0000-0000-0000-000000000000') 'user/00000000-0000-0000-0000-000000000000' ...
bigcode/self-oss-instruct-sc2-concepts
def timedelta_to_seconds(delta): """ Take a timedelta object and return the total number of seconds. """ return delta.seconds + (delta.days * 86400)
bigcode/self-oss-instruct-sc2-concepts
def fetch_all_table_names(schema, eng): """ Finds all tables within a given schema. """ tables = eng.execute( f"SELECT table_name FROM information_schema.tables WHERE table_schema = '{schema}';" ) return [table[0] for table in tables]
bigcode/self-oss-instruct-sc2-concepts
def is_xml_article_set(filename: str) -> bool: """ Check if input file is pubmed xml compressed archive from name. Arguments: filename {str} -- the name of the file Returns: bool -- true if file is compressed pubmed article set """ if filename.endswith('.xml.gz'): retur...
bigcode/self-oss-instruct-sc2-concepts
def get_bd_addr(packet): """Helper function to get bd_addr filed from HCI CMD/EVT packet. Args: packet: packet object from pyshark. Returns: bd_addr value (MAC string). If the packet doesn't have bd_addr or not is not HCI CMD/EVT, will return None. """ bd_addr = None if 'bthci_evt' in packet: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Union def od_parse(data: str) -> Dict[str, Union[str, list]]: """Parse od command output without argument, return a dict with the following keys: hex, ascii, list, text Returns: dict: with key hex, ascii, list, text """ text, asc_data, hex_data, list_...
bigcode/self-oss-instruct-sc2-concepts
import re def ShellEscape(arg): """ Escape a single argument for passing into a remote shell """ arg = re.sub(r'(["\\])', r'\\\1', arg) return '"%s"' % arg if re.search(r'[\' \t\r\n]', arg) else arg
bigcode/self-oss-instruct-sc2-concepts
import re def get_args(argv): """Store command-line args in a dictionary. -, -- prefixes are removed Items not prefixed with - or -- are stored as a list, indexed by 'args' For options that take a value use --option=value Consider using optparse or getopt (in Python standard library) instea...
bigcode/self-oss-instruct-sc2-concepts
import math def calc_term_count(order, var_count): """ Inputs: order- the order of the model var_count- the number of variables in the model Calculates the number of terms in a model. """ term_count = int( math.factorial(order + var_count) / (math.factorial(order) ...
bigcode/self-oss-instruct-sc2-concepts
import re def timestamp_to_terraref(timestamp): """Converts a timestamp to TERRA REF format Args: timestamp(str): the ISO timestamp to convert Returns: The ISO string reformatted to match the TERRA REF time & date stamp. Returns the original string if time units aren't specified ...
bigcode/self-oss-instruct-sc2-concepts
def min_point(points, n_points): """ Return the index of the closest point to (0,0) :param points: tuple of list for each coordinate :param n_points: number of points :return: the index of the selected point in the list """ min_y_indexes = [0] min_y = points[1][0] # Find minimum y ...
bigcode/self-oss-instruct-sc2-concepts
import re from bs4 import BeautifulSoup def remove_html_tags(text): """ Removes HTML tags from text. """ # prevent missing white space in further deletion of html symbols text = re.sub('<p>', ' ', text) # add punctuation after headings text = re.sub('</h1>', '. ', text) text = re.sub('</h2>'...
bigcode/self-oss-instruct-sc2-concepts
def _is_2xx_status(status_code): """Returns 'True' if a given status code is one of successful.""" return str(status_code).startswith("2")
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def output_filename(filename, cli_args): """ Construct the output filename """ if cli_args.timestamp: date_time = datetime.now().strftime("%m-%d-%Y_%H.%M.%S") lname = filename.split(".")[0] rname = filename.split(".")[-1] new_filename = f"{...
bigcode/self-oss-instruct-sc2-concepts
import math def update_one_contribute_score(user_total_click_num): """ item cf update similarity score by user :param user_total_click_num: :return: 1/log(1 + input) """ return 1 / math.log10(1 + user_total_click_num)
bigcode/self-oss-instruct-sc2-concepts
def nCr(n,r): """Calculate ways of selecting *r* members out of a collection of *n* members. :param n: Size of the collection :param r: Number of members to be selected from the collection :returns: n!/[r!(n-r)!] .. note:: :sup:`n` C :sub:`r` is typically read as *n co...
bigcode/self-oss-instruct-sc2-concepts
import copy def firecrown_sanitize(config): """Sanitizes the input for firecrown, that is removes keys that firecrown doesn't recognize Parameters: ---------- config : dict The dictinary that is ready for firecrown to munch on, but might have extra keys that are augur specific...
bigcode/self-oss-instruct-sc2-concepts
def _scalarize(value): """Scalarize a value. If VALUE is a list that consists of a single element, return that element. Otherwise return VALUE.""" if type(value) == list and len(value) == 1: return value[0] return value
bigcode/self-oss-instruct-sc2-concepts
def MeansOpenInProject(status, config): """Return true if this status means that the issue is still open. Args: status: issue status string. E.g., 'New'. config: the config of the current project. Returns: Boolean True if the status means that the issue is open. """ status_lower = status.lower()...
bigcode/self-oss-instruct-sc2-concepts
def choose_peers(relay, relay_count, worker_count, min_w2r, min_r2w): """ Given `relay`, the position of relay within the affinity set for a given service, the number of relays in that set (`relay_count`), the number of workers for the service (`worker_count`), the minimum number of connections requ...
bigcode/self-oss-instruct-sc2-concepts
def str_as_bool(val): """ Interpret the string input as a boolean """ if val.lower() in ("false", "none", "no", "0"): return False return True
bigcode/self-oss-instruct-sc2-concepts
def MakeCopyList(alist): """Make a copy of a list""" #newlist = the copied list newlist = [] for x in range(len(alist)): newlist.append(alist[x]) return newlist
bigcode/self-oss-instruct-sc2-concepts
import re def scraping_txt_file(filetxt): """This scrape the data inside text files using regular expression. """ datum = [] with open(filetxt, "r", encoding="latin1") as foo: for line in foo: # I think a genertator is imaginable here! pattern = re.compile( r"(?P<Date_...
bigcode/self-oss-instruct-sc2-concepts
def val_interpolate(x1, y1, x2, y2, x): """Perform linear interpolation for x between (x1,y1) and (x2,y2) """ d = [[x1, y1],[x2, y2]] output = d[0][1] + (x - d[0][0]) * ((d[1][1] - d[0][1])/(d[1][0] - d[0][0])) return(output)
bigcode/self-oss-instruct-sc2-concepts
def subtract(x, y): """ Returns the first vector minus the second. """ n = len(x) assert len(y) == n return map(lambda i: x[i]-y[i], range(0, n))
bigcode/self-oss-instruct-sc2-concepts
import re def remove_non_ascii(text): """ Remove non ascii characters in the text Parameters ---------- text : str Returns ------- text: str """ return re.sub(r'[^\x00-\x7F]', ' ', text)
bigcode/self-oss-instruct-sc2-concepts
def lens(lists): """Returns the sizes of lists in a list.""" return list(map(len, lists))
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_transform(file): """ Load a transform object """ with open(file, 'rb') as input_file: transform = pickle.load(input_file) return transform
bigcode/self-oss-instruct-sc2-concepts
def report_file_path(report_path, report_label, report_extension): """ Function to create a path for report files. Parameters: report_path (path): Report file path report_label (str): Report file label report_extension (str): Report file extension. e.g. txt, csv Return: r...
bigcode/self-oss-instruct-sc2-concepts
def random_walk_step(r, p0, W, pt): """ r = probability of restart p0 = initial probability vector W = column-normalized adjacency matrix pt = probability vector at time step t pt = probability vector at time step t + 1 """ #print 'r', r #print 'W', W #print 'pt', pt #print '...
bigcode/self-oss-instruct-sc2-concepts
import math def distance_nautical_miles(ll1,ll2): """ Given two (lat,lon) points ll1 and ll2, returns the distance between them in nautical miles. """ lat1,lon1=ll1 lat2,lon2=ll2 rad = math.pi / 180.0 yDistance = (lat2 - lat1) #* nauticalMilePerLat xDistance = (math.cos(lat1 * rad) + math.cos(l...
bigcode/self-oss-instruct-sc2-concepts
def pairwise_diff(X, Y): """Compute pairwise difference of rows of X and Y. Returns tensor of shape len(X) x len(Y) x dim.""" return X.unsqueeze(1) - Y
bigcode/self-oss-instruct-sc2-concepts
import re def _tracwiki_list_separate_from_paragraph(text: str): """ During conversion from TracWiki to RST, ensure an empty line between each non-list-item and the list item following it, if any. """ lines = text.split('\n') newlines = [] was_list_item_or_blank = True for l in lines...
bigcode/self-oss-instruct-sc2-concepts
def _is_sub_partition(sets, other_sets): """ Checks if all the sets in one list are subsets of one set in another list. Used by get_ranked_trajectory_partitions Parameters ---------- sets : list of python sets partition to check other_sets : list of python sets partition to ...
bigcode/self-oss-instruct-sc2-concepts
def scoreClickAUC(num_clicks, num_impressions, predicted_ctr): """ Calculates the area under the ROC curve (AUC) for click rates Parameters ---------- num_clicks : a list containing the number of clicks num_impressions : a list containing the number of impressions predicted_ctr : a li...
bigcode/self-oss-instruct-sc2-concepts
import re def multi_replace(target: str, replacements: dict[str, str]) -> str: """Given a string and a replacement map, it returns the replaced string. See https://gist.github.com/bgusach/a967e0587d6e01e889fd1d776c5f3729. Args: target: String to execute replacements on. replacements: Rep...
bigcode/self-oss-instruct-sc2-concepts
def _resolve_name(name, package, level): """Resolve a relative module name to an absolute one.""" bits = package.rsplit('.', level - 1) if len(bits) < level: raise ValueError('attempted relative import beyond top-level package') base = bits[0] return '{}.{}'.format(base, name) if name else b...
bigcode/self-oss-instruct-sc2-concepts
def _error(y_true, y_pred): """ Simple error """ return y_true - y_pred
bigcode/self-oss-instruct-sc2-concepts
def lower(value): """ returns the lowercase copy of input string. :param str value: string to make lowercase. :rtype: str """ return value.lower()
bigcode/self-oss-instruct-sc2-concepts
def frange(limit1, limit2 = None, increment = 1.): """ Range function that accepts floats (and integers). Usage: frange(-2, 2, 0.1) frange(10) frange(10, increment = 0.5) The returned value is a list. """ if limit2 is None: limit2, limit1 = limit1, 0. else: limit1 = float(limit1) result =...
bigcode/self-oss-instruct-sc2-concepts
import string def letter_part(n): # takes quotient and index """ Function to calculate the lettered part for a given number of parts n Eg. letter_part(1) = 'a', letter_part(26) = 'z', letter_part(27) = 'az', letter_part(702) = zz this is the max Values for n > 702 return None :param n:number of ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def get_distribution(labels: List[str]) -> Dict[str, int]: """ Get the distribution of the labels. Prameters --------- labels : List[str] This list is non-unique. Returns ------- distribution : Dict[str, int] Maps (label...
bigcode/self-oss-instruct-sc2-concepts
def fc_forward(mat_x, mat_w, vec_b): """Forward pass of Fully-Connected layer. A good reference for this is: http://cs231n.github.io/linear-classify/#score Args: mat_x: NxD ndarray, N is number of features, D is length of feature vector mat_w: DxC ndarray, C is number of classes. vec_b: length C nda...
bigcode/self-oss-instruct-sc2-concepts
def one_semitone_up(freq, amount=1): """ Returns the key, one semitone up :param freq: the frequency in hz :param amount: the amount of semitones up :return: the frequency one tone up in hz """ return freq * 2 ** (amount / 12)
bigcode/self-oss-instruct-sc2-concepts
def srange(characters): """Construct a list with all characters in the string""" return [c for c in characters]
bigcode/self-oss-instruct-sc2-concepts
import json def deserialize(recipe): """Deserialise JSON strings.""" recipe["tags"] = json.loads(recipe.get("tags", [])) recipe["newTags"] = json.loads(recipe.get("newTags", {})) return recipe
bigcode/self-oss-instruct-sc2-concepts
def extract_used_columns_from_nba_response(nba_response, desired_column_headers): """ Keeps all columns specified in desired_column_headers and returns the processed list of rows. """ try: desired_column_indicies = [nba_response.headers.index( header) for header in desired_column...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle(filename): """ Load saved data from pickle file :param filename: pickle file name :return: data from pickle file """ with open(filename, "rb") as f: data = pickle.load(f) return data
bigcode/self-oss-instruct-sc2-concepts
import re def only_numbers(string): """Return a string w only the numbers from the given string""" return re.sub("\D", "", string)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def _get_address_from_instance_response(instance_response: dict) -> Union[str, None]: """ Extracts the instance's IP address (public if possible, private if not) from the boto3 response dict :param instance_response: Boto3 response dict :return: IP address of the instance (pub...
bigcode/self-oss-instruct-sc2-concepts
def decode(b): """Decodes as UTF-8""" return b.decode('UTF-8')
bigcode/self-oss-instruct-sc2-concepts
def return_all(columns): """ Check if all columns should be returned """ return columns is None
bigcode/self-oss-instruct-sc2-concepts
import ast def get_functions(_ast): """ Gets all function definitions immediately below an ast node @param _ast the ast node to search for functions in @return a tuple of function definition ast nodes """ return (node for node in _ast.body if isinstance(node, ast.FunctionDef))
bigcode/self-oss-instruct-sc2-concepts
from typing import List def fibonacci_sequence(n) -> List[int]: """Generate n+1 terms of the fibonacci sequence""" fibo_sequence = [0, 1] a, b = fibo_sequence for i in range(2, n+1): a, b = b, a + b fibo_sequence += [b] return fibo_sequence
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Optional def _pick_remote_uri(uris: Sequence[str]) -> Optional[int]: """ Return the offset of the first uri with a remote path, if any. """ for i, uri in enumerate(uris): scheme, *_ = uri.split(":") if scheme in ("https", "http", "ftp", "s...
bigcode/self-oss-instruct-sc2-concepts
def bool_converter(value): """Simple string to bool converter (0 = False, 1 = True).""" return value == "1"
bigcode/self-oss-instruct-sc2-concepts
def CheckChangeHasNoCR(input_api, output_api, source_file_filter=None): """Checks no '\r' (CR) character is in any source files.""" cr_files = [] for f in input_api.AffectedSourceFiles(source_file_filter): if '\r' in input_api.ReadFile(f, 'rb'): cr_files.append(f.LocalPath()) if cr_files: return [...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def simple_clean_cells(cells: List) -> List: """ Removes cells that lack a bounding box or have a volume equal to 0 Args: cells: List of spatial features Returns: List of spatial features """ return [cell for cell in cells if len(cell.get_...
bigcode/self-oss-instruct-sc2-concepts
def get_noaa_url(start, end, station): """ Formats url with params for tides request from NOAA. Args: start (int or str): YYYYMMDD start date. end (int or str): YYYYMMDD end date (max 30 days from start). station (int or str): NOAA station ID. Returns: URL for NOAA tides ca...
bigcode/self-oss-instruct-sc2-concepts
import torch def is_loss(module): """Return whether `module` is a `torch` loss function. Args: module (torch.nn.Module): A PyTorch module. Returns: bool: Whether `module` is a loss function. """ return isinstance(module, torch.nn.modules.loss._Loss)
bigcode/self-oss-instruct-sc2-concepts
def GetLabel(plist): """Plists have a label.""" return plist['Label']
bigcode/self-oss-instruct-sc2-concepts
import math def get_evaldiff(evalue1, evalue2): """Return absolute value of the order of magnitude evalue difference for two given E-values. """ return round(abs(math.log(float(evalue1),10) - math.log(float(evalue2),10)))
bigcode/self-oss-instruct-sc2-concepts
def get_initial_lock_expiration(block_number, settle_timeout): """ Returns the expiration for first hash-time-lock in a mediated transfer. """ # The initiator doesn't need to learn the secret, so there is no need to # decrement reveal_timeout from the settle_timeout. # # The lock_expiration could be...
bigcode/self-oss-instruct-sc2-concepts
def catch_input(default_value, desired_type, input_message = "Input: ", failure_message = "Invalid input.", default_message = "Default value used.", num_attempts = 3): """ Function to better catch type errors in user input. If the input can be parsed using desired_type, th...
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Union def knn_gather( x: torch.Tensor, idx: torch.Tensor, lengths: Union[torch.Tensor, None] = None ): """ A helper function for knn that allows indexing a tensor x with the indices `idx` returned by `knn_points`. For example, if `dists, idx = knn_points(p, x, leng...
bigcode/self-oss-instruct-sc2-concepts
def get_date(date): """ Getting date in the format %B %d. :param date: datetime.datetime :return: str """ return date.strftime("%B %d").replace(" 0", " ")
bigcode/self-oss-instruct-sc2-concepts
def sec_to_time(seconds, days_only=False, ): """Convert seconds in human readable values :param int seconds: Time in seconds :param bool days_only: Output only in days :return str: Human readable string """ seconds = int(seconds) if seconds == 0: seconds = 1 if seconds < 0: ...
bigcode/self-oss-instruct-sc2-concepts
def add_missing_columns(df_in, required_columns, fill_val=0.0): """Adds columns to the DataFrame 'df_in' if it does not contain all of the columns in the list 'required_columns'. 'fill_val' is the value that is used to fill the new columns. """ missing_cols = set(required_columns) - set(df_in.colum...
bigcode/self-oss-instruct-sc2-concepts
def load_stop_words(filename): """Load a set of stop words from a file. One word each line.""" # you are using CPython, don't you? # http://stackoverflow.com/a/11027437/1240620 stopwords = {w.strip() for w in open(filename)} return stopwords
bigcode/self-oss-instruct-sc2-concepts
def uniquify_str(str_, str_set): """Uniquifies :attr:`str_` if :attr:`str_` is included in :attr:`str_set`. This is done by appending a number to :attr:`str_`. Returns :attr:`str_` directly if it is not included in :attr:`str_set`. Args: str_ (string): A string to uniquify. str_set (se...
bigcode/self-oss-instruct-sc2-concepts
def transform_images(X, max_x_value=255): """Flatten and rescale input.""" # Divide by a fixed value to be sure that we are making the same # transformation on training and test data. return X.reshape(X.shape[0], -1) / max_x_value
bigcode/self-oss-instruct-sc2-concepts
import math def get_nearest_location(x, places): """ Given a location `x`, and a list of locations, `places`, returns the list index corresponding to the minimum distance, and the minimum distance. """ min_dist, min_i = 1e10, 0 for i, place in enumerate(places): name = place['name'...
bigcode/self-oss-instruct-sc2-concepts