seed
stringlengths
1
14k
source
stringclasses
2 values
import tempfile import re def read_xyz(datapath_or_datastring, is_datafile=True): """ Read data in .xyz format, from either a file or a raw string. :param (string) datapath_or_datastring: Either the path to the XYZ file (can be relative or absolute...
bigcode/self-oss-instruct-sc2-concepts
def get( coin, in_coin, try_conversion=None, exchange=None, aggregate=None, limit=None, all_data=None, to_timestamp=None, extra_params=None, sign=None, ): """ Get open, high, low, close, volumefrom and volumeto from the dayly hi...
bigcode/self-oss-instruct-sc2-concepts
def shared_lib_name(group_name: str) -> str: """Given a group name, return the actual name of its extension module. (This just adds a suffix to the final component.) """ return '{}__mypyc'.format(group_name)
bigcode/self-oss-instruct-sc2-concepts
def format_alignment(align1, align2, score, begin, end): """format_alignment(align1, align2, score, begin, end) -> string Format the alignment prettily into a string. """ s = [] s.append("%s\n" % align1) s.append("%s%s\n" % (" "*begin, "|"*(end-begin))) s.append("%s\n" % align2) s.appe...
bigcode/self-oss-instruct-sc2-concepts
def transform_to_bytes(content: str): """ Transform a string to bytes Parameters ---------- - content (str): The string to convert Raises ------ ValueError: the string is not valid Returns ------- - bytes: the converted string in bytes """ if isinsta...
bigcode/self-oss-instruct-sc2-concepts
def get_input(question: str) -> int: """Get input (int) from user returns int""" while True: try: value = int(input(question)) if value < 0: print("Input must be a positive integer, try again: \n") continue break except...
bigcode/self-oss-instruct-sc2-concepts
def get_pausers(df): """ Filters the DataFrame for paused (begun but did not finish) replies. :param df: :return: """ return df[df['dispcode'] == 22]
bigcode/self-oss-instruct-sc2-concepts
def non_binary_search(data, item): """Return the position of query if in data.""" for index, val in enumerate(data): if val == item: return index return None
bigcode/self-oss-instruct-sc2-concepts
def count_noun(number, noun, plural=None, pad_number=False, pad_noun=False): """ EXAMPLES:: sage: from sage.doctest.util import count_noun sage: count_noun(1, "apple") '1 apple' sage: count_noun(1, "apple", pad_noun=True) '1 apple ' sage: count_noun(1, "apple", p...
bigcode/self-oss-instruct-sc2-concepts
def get_dim_order(x, y, z): """ Returns a tuple with the order of dimensions. Tuple can be used with DIM_ROT. """ if x <= y and x <= z: if y <= z: return ('x', 'y', 'z') else: return ('x', 'z', 'y') elif y <= x and y <= z: if x <= z: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def content_check(data: List[Dict[str, str]], check: str, json_file: str, msg: str) -> bool: """ Checks whether a dictionary contains a column specific to expected data and returns a corresponding boolean value. This avoids writing files of...
bigcode/self-oss-instruct-sc2-concepts
def steps(execution_id, query_params, client): """Get execution steps for a certain execution.""" return client.get_execution_steps(execution_id, **query_params)
bigcode/self-oss-instruct-sc2-concepts
def gen_labor_force_change(shortened_dv_list): """Create variables for the change in labor force for the current and previous months.""" labor_force_change = round((shortened_dv_list[5] - shortened_dv_list[4]) * 1000) prev_labor_force_change = round((shortened_dv_list[4] - shortened_dv_list[3]) * 1000)...
bigcode/self-oss-instruct-sc2-concepts
import json def validate(resp): """Check health status response from application. Args: resp (string): Response will be converted to JSON and then analyzed. Returns: (bool): True if application healthy. """ print(resp) try: data = json.loads(resp) except: ...
bigcode/self-oss-instruct-sc2-concepts
def get_index_size_in_kb(opensearch, index_name): """ Gets the size of an index in kilobytes Args: opensearch: opensearch client index_name: name of index to look up Returns: size of index in kilobytes """ return int( opensearch.indices.stats(index_name, metric='s...
bigcode/self-oss-instruct-sc2-concepts
def getbox(face): """Convert width and height in face to a point in a rectangle""" rect = face.face_rectangle left = rect.left top = rect.top right = left + rect.width bottom = top + rect.height return top, right, bottom, left
bigcode/self-oss-instruct-sc2-concepts
def exponential(start_at): """Return and exponentially increasing value :param float start_at: Initial delay in seconds :rtype func: """ def func(count): count -= 1 return start_at * (2**count) return func
bigcode/self-oss-instruct-sc2-concepts
def use_node_def_or_num(given_value, default_func): """Transform a value of type (None, int, float, Callable) to a node annotation function.""" # Default: use pre-defined function from this module if given_value is None: func = default_func # Transform: value to function that returns the value ...
bigcode/self-oss-instruct-sc2-concepts
def find_root(ds): """ Helper function to find the root of a netcdf or h5netcdf dataset. """ while ds.parent is not None: ds = ds.parent return ds
bigcode/self-oss-instruct-sc2-concepts
from typing import List def make_parallel_commands( commands: str, repeats: int, parallel: int ) -> List[List[str]]: """ Build list of lists, where the inner list contains a group of commands to be executed in a sequence""" command_list = commands.split("|") command_list = [comm.strip() for comm...
bigcode/self-oss-instruct-sc2-concepts
def prime_sieve(n): """ Return a list of all primes smaller than or equal to n. This algorithm uses a straightforward implementation of the Sieve of Eratosthenes. For more information, see https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Algorithmic details ------------------- ...
bigcode/self-oss-instruct-sc2-concepts
def _create_into_array_list(phrase): """Create load or store into array instructions For example, with the phrase 'astore': [ 'iastore', 'fastore', ... 'aastore' ] """ # noinspection SpellCheckingInspection return [letter + phrase for letter in 'lfdibcsa']
bigcode/self-oss-instruct-sc2-concepts
def removekeys(toc, chapnum): """Return new dictionary with all keys that don't start with chapnum""" newtoc = {} l = len(chapnum) for key, value in toc.items(): if key[:l] != chapnum: newtoc[key] = value return newtoc
bigcode/self-oss-instruct-sc2-concepts
import builtins import gzip def open(filename, mode='r', compress=False, is_text=True, *args, **kwargs): """ Return a file handle to the given file. The only difference between this and the standard open command is that this function transparently opens zip files, if specified. If a gzipped file is ...
bigcode/self-oss-instruct-sc2-concepts
import random import string def generate_random_string(length): """Utility to generate random alpha string for file/folder names""" return ''.join(random.choice(string.ascii_letters) for i in range(length))
bigcode/self-oss-instruct-sc2-concepts
def check_header_gti(hdr): """ Check FITS header to see if it has the expected data table columns for GTI extension. Require the following keywords:: TELESCOP = 'NuSTAR' / Telescope (mission) name HDUCLAS1 = 'GTI' / File contains Good Time Intervals NAXIS = ...
bigcode/self-oss-instruct-sc2-concepts
def convert_args_to_list(args): """Convert all iterable pairs of inputs into a list of list""" list_of_pairs = [] if len(args) == 0: return [] if any(isinstance(arg, (list, tuple)) for arg in args): # Domain([[1, 4]]) # Domain([(1, 4)]) # Domain([(1, 4), (5, 8)]) ...
bigcode/self-oss-instruct-sc2-concepts
import re def has_datas(command): """ Function to determine if there is data in the curl command, even if the datas are empty or only if there is --data or -d without something next to it.""" has_datas_pattern = r"(-d|--data)" has_datas = re.search(has_datas_pattern, command) return True if has_d...
bigcode/self-oss-instruct-sc2-concepts
def check_key(data, key): """ Check if key in data. If so, then return the value, otherwise return the empty string. """ if data.keys().__contains__(key): return data[key] else: return ''
bigcode/self-oss-instruct-sc2-concepts
def guess_type_value_type(none=True): """ @param none if True and all values are empty, return None @return the list of types recognized by guess_type_value """ typstr = str return [None, typstr, int, float] if none else [typstr, int, float]
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def decode_answer(response_data: dict) -> Any: """ Decode the answer described by *response_data*, a substructure of an enrollment document. Returns a string, number, tuple of strings, or None. """ answer = response_data["answer"] if answer["type"] in ["String", "N...
bigcode/self-oss-instruct-sc2-concepts
def extract_line_coverage(coverage): """Extract line coverage from raw coverage data.""" line_coverage = {} # file name -> function data for filename, function_data in coverage.items(): line_coverage[filename] = {} # function -> line data for _, line_data in function_data.items(...
bigcode/self-oss-instruct-sc2-concepts
import random def reduce_dicts(titles, gold, shuffle=False): """ reduce 2 dictionaries to 2 lists, providing 'same index' iff 'same key in the dictionary' """ titles, gold = dict(titles), dict(gold) titles_list = [] gold_list = [] for key in titles: titles_list.append(titles[key]) ...
bigcode/self-oss-instruct-sc2-concepts
def int_list_to_str(lst): """ Given a list of integers: [1, 10, 3, ... ] Return it as a string of the form: "[1,10,3,...]" """ return "[%s]" % ','.join([str(l) for l in lst])
bigcode/self-oss-instruct-sc2-concepts
import time def wait_for(predicate, timeout, period=0.1): """ Wait for a predicate to evaluate to `True`. :param timeout: duration, in seconds, to wait for the predicate to evaluate to `True`. Non-positive durations will result in an indefinite wait. :param period: predicate evaluat...
bigcode/self-oss-instruct-sc2-concepts
def _create_statistics_data(data_list, is_multi_series=False): """ Transforms the given list of data to the format suitable for presenting it on the front-end. Supports multi series charts (like line and bar charts) and or single series ones (like pie/donut charts). :param data_list: a list of ...
bigcode/self-oss-instruct-sc2-concepts
import struct def ubyte_to_bytes(byte_data: int)->bytes: """ For a 8 bit unsigned byte :param byte_data: :return: bytes(); len == 1 """ result = struct.pack('<B', byte_data) return result
bigcode/self-oss-instruct-sc2-concepts
def member_to_beacon_proximity(m2badge, id2b): """Creates a member-to-beacon proximity DataFrame from member-to-badge proximity data. Parameters ---------- m2badge : pd.DataFrame The member-to-badge proximity data, as returned by `member_to_badge_proximity`. id2b : pd.Series ...
bigcode/self-oss-instruct-sc2-concepts
def get_height_magnet(self): """get the height of the hole magnets Parameters ---------- self : HoleM50 A HoleM50 object Returns ------- Hmag: float height of the 2 Magnets [m] """ # magnet_0 and magnet_1 have the same height Hmag = self.H3 return Hmag
bigcode/self-oss-instruct-sc2-concepts
def get_deployment_labels(deployments): """ Get labels for a given list of deployments. Returns a dictionary in the below format: { deployment_name: {dictionary of deployment labels}, ...} """ deployment_dictionary = {} for deployment in deployments: deployment_dictionary[deploymen...
bigcode/self-oss-instruct-sc2-concepts
def getFloatFromStr(number: str) -> float: """ Return float representation of a given number string. HEX number strings must start with ``0x``. Args: numberStr: int/float/string representation of a given number. """ numberStr = number.strip() isNegative = False if "-" in numberStr: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import math def calculate_percentile(times: List[int], percent=0.95) -> int: """ Calculate percentile (by default 95%) for sorted `times`. If we cannot choose one index, we use average of two nearest. """ index = (len(times) - 1) * percent if index.is_integer(): ...
bigcode/self-oss-instruct-sc2-concepts
def insertion_sort(array: list, ascending=True) -> list: """This function sort an array implementing the insertion sort method Parameters ---------- array : list A list containing the elements to be sorted ascending : boolen Indicates whether to sort in ascending order Retu...
bigcode/self-oss-instruct-sc2-concepts
import re def get_pool_uuid_service_replicas_from_stdout(stdout_str): """Get Pool UUID and Service replicas from stdout. stdout_str is something like: Active connections: [wolf-3:10001] Creating DAOS pool with 100MB SCM and 0B NvMe storage (1.000 ratio) Pool-create command SUCCEEDED: UUID: 9cf5be...
bigcode/self-oss-instruct-sc2-concepts
import copy def copy_list(src, deep_copy=False): """ Copies list, if None then returns empty list :param src: List to copy :param deep_copy: if False then shallow copy, if True then deep copy :return: Copied list """ if src is None: return list() if deep_copy: return co...
bigcode/self-oss-instruct-sc2-concepts
def get_head(text, headpos, numchars): """Return text before start of entity.""" wheretostart = headpos - numchars if wheretostart < 0: wheretostart = 0 thehead = text[wheretostart: headpos] return thehead
bigcode/self-oss-instruct-sc2-concepts
def get_in(dct, keys): """Gets the value in dct at the nested path indicated by keys""" for key in keys: if not isinstance(dct, dict): return None if key in dct: dct = dct[key] else: return None return dct
bigcode/self-oss-instruct-sc2-concepts
def initial_investment(pv_size, battery_size, n_batteries = 1, capex_pv = 900, capex_batt = 509): """Compute initial investment""" return pv_size*capex_pv + battery_size*capex_batt*n_batteries
bigcode/self-oss-instruct-sc2-concepts
def compress(years): """ Given a list of years like [2003, 2004, 2007], compress it into string like '2003-2004, 2007' >>> compress([2002]) '2002' >>> compress([2003, 2002]) '2002-2003' >>> compress([2009, 2004, 2005, 2006, 2007]) '2004-2007, 2009' >>> compress([2001, 2003, 2004, 2005]) '2001, 20...
bigcode/self-oss-instruct-sc2-concepts
import torch def predict_cmap_interaction(model, n0, n1, tensors, use_cuda): """ Predict whether a list of protein pairs will interact, as well as their contact map. :param model: Model to be trained :type model: dscript.models.interaction.ModelInteraction :param n0: First protein names :type...
bigcode/self-oss-instruct-sc2-concepts
def parse_country_details(response, pos=0): """Parses the country details from the restcountries API. More info here: https://github.com/apilayer/restcountries Args: response (:obj:`list` of `dict`): API response. Returns: d (dict): Parsed API response. """...
bigcode/self-oss-instruct-sc2-concepts
def obtain_factorial(x): """ Helper function obtain_factorial() for the factorial() function. Given value x, it returns the factorial of that value. """ product = 1 for ii in list(range(x)): product = product * (ii + 1) return(product)
bigcode/self-oss-instruct-sc2-concepts
def get_ascii_from_char(char: str) -> int: """Function that converts ascii code to character Parameters ---------- char : character character to convert to ascii Returns ------- ascii_code : int Ascii code of character """ return ord(char)
bigcode/self-oss-instruct-sc2-concepts
def get_comments(github_object): """Get a list of comments, whater the object is a PR, a commit or an issue. """ try: return github_object.get_issue_comments() # It's a PR except AttributeError: return github_object.get_comments()
bigcode/self-oss-instruct-sc2-concepts
def _resolve_subkeys(key, separator='.'): """Resolve a potentially nested key. If the key contains the ``separator`` (e.g. ``.``) then the key will be split on the first instance of the subkey:: >>> _resolve_subkeys('a.b.c') ('a', 'b.c') >>> _resolve_subkeys('d|e|f', separator='|') ...
bigcode/self-oss-instruct-sc2-concepts
import math def gcd(x, y): """ gcd :: Integral a => a -> a -> a gcd(x,y) is the non-negative factor of both x and y of which every common factor of x and y is also a factor; for example gcd(4,2) = 2, gcd(-4,6) = 2, gcd(0,4) = 4. gcd(0,0) = 0. (That is, the common divisor that is "greatest" in...
bigcode/self-oss-instruct-sc2-concepts
import re def problem1(searchstring): """ Match phone numbers. :param searchstring: string :return: True or False """ str_search = re.search(r'^(\S?\d+\W?)\W?(\d+)\-(\d+)',searchstring) #str_search1 = re.search(r'^(\S\d+\W)(?=(\s|\d)\d+)',searchstring) #print(str_search) ...
bigcode/self-oss-instruct-sc2-concepts
def rank_as_string(list1, alphanum_index): """ Convert a ranked list of items into a string of characters based on a given dictionary `alph` of the format that contains the ranked items and a random alphanumeric to represent it. Parameters ---------- list1 : list A lis...
bigcode/self-oss-instruct-sc2-concepts
def get_n_params(model): """ Returns the number of learning parameters of the model """ pp=0 for p in list(model.parameters()): nn=1 for s in list(p.size()): nn = nn*s pp += nn return pp
bigcode/self-oss-instruct-sc2-concepts
def get_instances(ClassName, arguments, attributes): """Get instances of a class with specific attributes Assumes ClassName is a class type Assumes arguments is an ordered collection of dictionaries as defined in the module documentation Assumes attributes is a list of dictionaries that maps stri...
bigcode/self-oss-instruct-sc2-concepts
def _remove_field(metadata, field): """Remove a certain field from the metadata Args: metadata (dict): Metadata to be pruned field ([string]): Coordinates of fields to be removed """ if len(field) == 1: if field[0] in metadata: del metadata[field[0]] else: ...
bigcode/self-oss-instruct-sc2-concepts
import math def is_pentagon(x): """ Checks if x is a pentagon number """ n = (1 + math.sqrt(24*x + 1))/6 return(n == round(n))
bigcode/self-oss-instruct-sc2-concepts
def compute_user_vector_with_threshold(array, threshold=3.5): """Compute a user profile by summing only vectors from items with a positive review. Item vectors with a rating above a set threshold are included, other vectors are discarded. The user profile is not normalized. Args: array (rdd ob...
bigcode/self-oss-instruct-sc2-concepts
import math def two_divider(num): """Solution to exercise P-1.30. Write a Python program that can take a positive integer greater than 2 as input and write out the number of times one must repeatedly divide this number by 2 before getting a value less than 2. """ if not isinstance(num, int) o...
bigcode/self-oss-instruct-sc2-concepts
import re from datetime import datetime def is_valid_timestamp(timestamp): """Checks whether timestamp is a string that is a proper ISO 8601 timestamp Format for string is is YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]] e.g. 2008-01-23T19:23:10+00:00 Parameters: timesta...
bigcode/self-oss-instruct-sc2-concepts
def feasible(growth_rate): """Feasibility function for the individual. Returns True if feasible False otherwise.""" if growth_rate > 1e-6: return True return False
bigcode/self-oss-instruct-sc2-concepts
def is_kind_of_class(obj, a_class): """checks if an object is an instance of, or if the object is an instance of a class that inherited from, the specified class""" return (isinstance(obj, a_class) or issubclass(type(obj), a_class))
bigcode/self-oss-instruct-sc2-concepts
def str_list_to_dict(pairs_list): """ Parses strings from list formatted as 'k1=v1' to dict with keys 'k1', 'v1'. Example: str_list_to_dict(['k=v', 'a=b']) —> {'k':'v', 'a': 'b'} :param pairs_list: list of strings :return: dict with parsed keys/values """ result = {} for l in pairs_list:...
bigcode/self-oss-instruct-sc2-concepts
def get_auth_type_from_header(header): """ Given a WWW-Authenticate or Proxy-Authenticate header, returns the authentication type to use. We prefer NTLM over Negotiate if the server suppports it. """ if "ntlm" in header.lower(): return "NTLM" elif "negotiate" in header.lower(): ...
bigcode/self-oss-instruct-sc2-concepts
def _get_number_of_warmup_and_kept_draws_from_fit(fit): """Get number of warmup draws and kept draws.""" if 'warmup2' not in fit: n_warmup = 0 n_draws = fit['n_save'][0] else: n_warmup = fit['warmup2'][0] n_draws = fit['n_save'][0] - fit['warmup2'][0] return n_warmup, n...
bigcode/self-oss-instruct-sc2-concepts
import ast def get_all_names(tree): """ Collect all identifier names from ast tree :param tree: _ast.Module :return: list """ return [node.id for node in ast.walk(tree) if isinstance(node, ast.Name)]
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict import functools def merge_list_of_dicts(list_of_dicts: List[Dict]) -> Dict: """A list of dictionaries is merged into one dictionary. Parameters ---------- list_of_dicts: List[Dict] Returns ------- Dict """ if not list_of_dicts: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import json def load_user(filename: str) -> Dict: """Load json file with Discord userid and corresponding wellcome message Args: filename (str): filename of a json file Returns: Dict: {userid: text, date} """ with open(filename, 'r', encoding='utf-8') as f...
bigcode/self-oss-instruct-sc2-concepts
import string def find_words(text): """ text: string Returns a list of words from input text """ text = text.replace("\n", " ") for char in string.punctuation: text = text.replace(char, "") words = text.split(" ") return words
bigcode/self-oss-instruct-sc2-concepts
def hexdump(data: bytes) -> None: """ https://code.activestate.com/recipes/579064-hex-dump/ >>> hexdump(b'\x7f\x7f\x7f\x7f\x7f') #doctest: +NORMALIZE_WHITESPACE 0000000000: 7F 7F 7F 7F 7F ..... """ def _pack(a): """ ['7F', '7F', '7F', '7F', '7...
bigcode/self-oss-instruct-sc2-concepts
def get_note_head(note_path): """ Return first line of a text file Parameters ---------- note_path : str A text file path Returns ------- str First line of the text file """ with open(note_path, "r") as f: head = f.read() return head
bigcode/self-oss-instruct-sc2-concepts
def MassFlowProperty(self): """Mass flow (kg/hr).""" return self.mol[self.index] * self.MW
bigcode/self-oss-instruct-sc2-concepts
def encode_db_connstr(name, # pylint: disable=too-many-arguments host='127.0.0.1', port=5432, user='postgres', password='password', scheme='postgresql'): """ builds a database connection string """ con...
bigcode/self-oss-instruct-sc2-concepts
import copy def override_config(config, kwargs): """ Helper function to override the 'config' with the options present in 'kwargs'. """ config = copy.deepcopy(config) for k, v in kwargs.items(): if k not in config.keys(): print('WARNING: Overriding non-existent kwargs key', k) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def system_call_count_feats(tree): """ arguments: tree is an xml.etree.ElementTree object returns: a dictionary mapping 'num_system_calls' to the number of system_calls made by an executable (summed over all processes) """ c = Counter() in_all_secti...
bigcode/self-oss-instruct-sc2-concepts
def create_marker_and_content(genome_property_flat_file_line): """ Splits a list of lines from a genome property file into marker, content pairs. :param genome_property_flat_file_line: A line from a genome property flat file line. :return: A tuple containing a marker, content pair. """ columns ...
bigcode/self-oss-instruct-sc2-concepts
def init_model_nn(model, params): """ ## Description: It initializes the model parameters of the received model ## Args `model`: (Pytorch Model) The model to be initialized `params`: (dict) Parameters used to initialize the model ## Returns: The initialized model """ ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_config(filename): """Loads in configuration file. Args: filename (string): The filename of the config file. Returns: object: A deserialised pickle object. """ with open(filename, 'rb') as file_ptr: return pickle.load(file_ptr)
bigcode/self-oss-instruct-sc2-concepts
def _get_or_create_main_genre_node(main_genre_name, taxonomy_graph): """ Return the node for the main genre if it exists, otherwise create a new node and make it a child of the root node. """ if main_genre_name in taxonomy_graph: main_genre_node = taxonomy_graph.get_node(main_genre_name) ...
bigcode/self-oss-instruct-sc2-concepts
def format_time(time_): """ Returns a formatted time string in the Orders of magnitude (time) Args: time_: if -1.0 return 'NOT-MEASURED'' Returns: str: formatted time: Orders of magnitude (time) second (s) millisecond (ms) One thousandth of one second micros...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def default(obj): """Encode datetime to string in YYYY-MM-DDTHH:MM:SS format (RFC3339)""" if isinstance(obj, datetime): return obj.isoformat() return obj
bigcode/self-oss-instruct-sc2-concepts
import hashlib def is_placeholder_image(img_data): """ Checks for the placeholder image. If an imgur url is not valid (such as http//i.imgur.com/12345.jpg), imgur returns a blank placeholder image. @param: img_data (bytes) - bytes representing the image. @return: (boolean) True if placeholder image otherwise...
bigcode/self-oss-instruct-sc2-concepts
def list_to_lower(string_list): """ Convert every string in a list to lower case. @param string_list: list of strings to convert @type string_list: list (of basestring) @rtype: list (of basestring) """ return [s.lower() for s in string_list]
bigcode/self-oss-instruct-sc2-concepts
def is_handler_authentication_exempt(handler): """Return True if the endpoint handler is authentication exempt.""" try: is_unauthenticated = handler.__caldera_unauthenticated__ except AttributeError: is_unauthenticated = False return is_unauthenticated
bigcode/self-oss-instruct-sc2-concepts
import requests def live_data(key): """ Requests latest covid-19 stats from rapidapi using requests. Parameters ---------- key: rapidapi key Returns ------- response: A dictionary containing data in json format. """ # https://rapidapi.com/astsiatsko/api/coronavirus-monitor ...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def pike_tmp_package(pike_init_py): """Fixture: Create a Python package inside a temporary directory. Depends on the pike_init_py fixture :param pike_init_py: fixture with py.path.local object pointing to directory with empty __init__.py :return: t...
bigcode/self-oss-instruct-sc2-concepts
def normalize_min_max(x, min_val=None, max_val=None): """ normalize vector / matrix to [0, 1]. :param x: a numpy array. :param min_val: the minimum value in normalization. if not provided, takes x.min() :param max_val: the maximum value in normalization. if not provided, takes x.max() :return: ...
bigcode/self-oss-instruct-sc2-concepts
def _get_nn_idx(row, neigh, radius, columns): """Retrieve the NN of a sample within a specified radius. Parameters ---------- row : pd.Series neigh : sklearn.NearestNeighbors radius : float columns : list Returns ------- list Nearest Neighbors of given sample within rad...
bigcode/self-oss-instruct-sc2-concepts
def mdot(matrix, benchmark_information): """ Calculates a product between a matrix / matrices with shape (n1) or (a, n1) and a weight list with shape (b, n2) or (n2,), where n1 and n2 do not have to be the same """ n1 = matrix.shape[-1] weights_t = benchmark_information.T n2 = weights_t.sha...
bigcode/self-oss-instruct-sc2-concepts
def number_to_name(number): """ Converts an integer called number to a string. Otherwise, it sends an error message letting you know that an invalid choice was made. """ if number == 0: return "rock" elif number == 1: return "Spock" elif number == 2: return "pap...
bigcode/self-oss-instruct-sc2-concepts
def makeSiblingTemplatesList(templates, new_template_file, default_template=None): """Converts template paths into a list of "sibling" templates. Args: templates: search list of templates (or just a single template not in a list) from which template paths will be extracted ...
bigcode/self-oss-instruct-sc2-concepts
import re def n_credit(sentence): """ If a phrase in the form "X credit" appears in the sentence, and X is a number, add a hyphen to "credit". If "X-credit" appears, split it into "X" and "-credit". Do not hyphenate "X credits" or "Y credit" where Y is not a number. Run this after the tokenize...
bigcode/self-oss-instruct-sc2-concepts
def _convert_dict_to_list(d): """This is to convert a Python dictionary to a list, where each list item is a dict with `name` and `value` keys. """ if not isinstance(d, dict): raise TypeError("The input parameter `d` is not a dict.") env_list = [] for k, v in d.items(): env_list...
bigcode/self-oss-instruct-sc2-concepts
def readrecipe(recipebook, index): """ Returns one recipe, for command line output """ try: return recipebook.recipes[index].prettyprint() except IndexError: return "Error: no such recipe"
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Any from typing import Optional def binary_search_iter(seq: Sequence, value: Any) -> Optional[int]: """ Iterative binary search. Notes ----- Binary search works only on sorted sequences. Parameters ---------- seq : Sequence where...
bigcode/self-oss-instruct-sc2-concepts