seed
stringlengths
1
14k
source
stringclasses
2 values
import json def question_pack(info="", userid="A0001", key="A0001"): """Package the question as the JSON format specified by the server. 将问题打包为服务器指定的json格式。 Args: info: User question. 用户的聊天或提问。 Defaults to "". userid: User id. 用户唯一标识。 Defaults to "userid". Ret...
bigcode/self-oss-instruct-sc2-concepts
def _parsems(value): """Parse a I[.F] seconds value into (seconds, microseconds).""" if "." not in value: return int(value), 0 else: i, f = value.split(".") return int(i), int(f.ljust(6, "0")[:6])
bigcode/self-oss-instruct-sc2-concepts
import ast def parse_cwes(str1): """ Converts string to list. """ lst = ast.literal_eval(str1) lst = [x.strip() for x in lst] return lst
bigcode/self-oss-instruct-sc2-concepts
def reader(fileaddress): """Reads the contents of a given file into an array""" tied = [] with open(fileaddress, 'r') as ft: for line in ft: if(line[0]!="#"): tied.append(line) ft.close() return tied
bigcode/self-oss-instruct-sc2-concepts
def _expand_path(graph, source, step, visited, degrees): """Walk a path on a graph until reaching a tip or junction. A path is a sequence of degree-2 nodes. Parameters ---------- graph : NBGraph A graph encoded identically to a SciPy sparse compressed sparse row matrix. See the doc...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable import importlib def get_callable(function_string: str) -> Callable: """get_callable import a function based on its dot notation format as as string :param function_string: the dot notation location of the function. (i.e. foo_module.bar_function) :type function_string: str ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import pickle def load_pickle(filename: str) -> Any: """Load object from pickle filename. Args: filename (string): The absolute path to the saved pickle. Returns: data (any): The loaded object. """ with open(filename, 'rb') as fp: data = pickle.load...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_all_weather_data(city="st. john's"): """ Helper function. Makes a request to openweathermap server. :param city: :return: Returns entire current weather for the city. """ base_url = "https://api.openweathermap.org/data/2.5/weather?" api_key = "e3a3f627f93effe0dc13ea...
bigcode/self-oss-instruct-sc2-concepts
def is_json(filename): """Predicate for checking if a filename is .json""" return filename.lower().endswith(".json")
bigcode/self-oss-instruct-sc2-concepts
def new_sequence(num, sequence): """ :param num: int, allow users to input a number that is used to offset the original order in the sequence (ALPHABET). :param sequence: str, the sequence (ALPHABET) that users want to shift the order. :return: str, the new sequence (ALPHABET) with a new order. """ ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Set import collections def load_qrels(path: str) -> Dict[str, Set[str]]: """Loads qrels into a dict of key: query_id, value: set of relevant doc ids.""" qrels = collections.defaultdict(set) with open(path) as f: for i, line in enumerate(f): li...
bigcode/self-oss-instruct-sc2-concepts
def get_gap_HS_data(modeling_data, gap_period, gap_station): """ Get original HS data in the gap period. Only winter values (Nov-Apr) will be returned. """ y_true = (modeling_data .loc[modeling_data['stn']==gap_station, 'HS'] .loc[gap_period] ) y_true =...
bigcode/self-oss-instruct-sc2-concepts
import base64 def get_base64_encoded_image(image_path): """ encode image to string for use in html later""" with open(image_path, "rb") as img_file: return base64.b64encode(img_file.read()).decode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
def agent_ids(cur, archetype): """Gets all agentids from Agententry table for wanted archetype agententry table has the following format: SimId / AgentId / Kind / Spec / Prototype / ParentID / Lifetime / EnterTime Parameters ---------- cur: cursor sqlite cursor3...
bigcode/self-oss-instruct-sc2-concepts
def sol_tracker(w2v_model, solution): """Keep a record of those solution words that do not appear in the W2V vocabulary Args : w2v_model : standard Word2Vec 'KeyedVectors' data structure solution : List of tokenised words representing solution """ sol_errors = [] for word in solution...
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def is_updated(dictionary: Mapping, update_dict: Mapping) -> bool: """Checks if the dictionary has been updated with the values from update_dict.""" for k, v in update_dict.items(): if isinstance(v, dict): if not is_updated(dictionary.get(k, {}), v): ...
bigcode/self-oss-instruct-sc2-concepts
def colorspace_prefixed_name(colorspace): """ Returns given *OCIO* colorspace prefixed name with its family name. Parameters ---------- colorspace : ColorSpace ColorSpace to prefix. Returns ------- str or unicode Family prefixed *OCIO* colorspace name. """ pref...
bigcode/self-oss-instruct-sc2-concepts
import re def extract_pmc(citation): """ Extract PMC from a given eutils XML tree. Parameters ---------- tree: Element An lxml Element parsed from eutil website Return ------ pmc: str PubMed Central ID (PMC) of an article """ pmc_text = [c for c in citation.sp...
bigcode/self-oss-instruct-sc2-concepts
def PrefixFromPattern(pattern): """Given a path pattern, return the prefix to use in ListKeys. If a pattern ends with '*', the prefix is the pattern without the '*', otherwise, we format is as a directory. """ if pattern.endswith('*'): return pattern[:-1] elif pattern.endswith('/'): return '' if patte...
bigcode/self-oss-instruct-sc2-concepts
def coords_to_lat_lon_lists(coords): """Converts a list of coordinates in tuple form (latitude,longitude) to a list of latitudes and a list of longitudes. Parameters ---------- coords : list(tuple) a list of coordinates in tuple form (latitude,longitude) Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def bin_filter(input: float, abs_boundary: float) -> float: """ Simple binary filter, will provide abs_ceiling as a binary output, according to the 'negativity' of the input value :param input : input value :param abs_boundary : abs boundary value :return : output binary value...
bigcode/self-oss-instruct-sc2-concepts
def lsb(x, n): """Return the n least significant bits of x. >>> lsb(13, 3) 5 """ return x & ((2 ** n) - 1)
bigcode/self-oss-instruct-sc2-concepts
import math def is_square(num : int) -> bool: """ Check if a number is perfect square number or not. Parameters: num: the number to be checked Returns: True if number is square number, otherwise False """ if num < 0: raise ValueError("math domain error") if m...
bigcode/self-oss-instruct-sc2-concepts
def get_display_data_single(fields, data, missing_field_value=None): """Performs slicing of data by set of given fields. :param fields: Iterable containing names of fields to be retrieved from data :param data: Collection of objects representing some external entities :param missin...
bigcode/self-oss-instruct-sc2-concepts
import re def IsGitSha(revision): """Returns true if the given string is a valid hex-encoded sha""" return re.match('^[a-fA-F0-9]{6,40}$', revision) is not None
bigcode/self-oss-instruct-sc2-concepts
def bits_table_l() -> dict[int, int]: """The table of the maximum amount of information (bits) for the version L. Returns: dict[int, int]: Dictionary of the form {version: number of bits} """ table = { 1: 152, 2: 272, 3: 440, 4: 640, 5: 864, 6: 1088, 7: 1248, 8: 1552, 9: 1856, 1...
bigcode/self-oss-instruct-sc2-concepts
def is_triangle(side_a, side_b, side_c): """Returns True if the input satisifes the sides of a triangle""" return side_a + side_b > side_c and side_a + side_c > side_b and side_b + side_c > side_a
bigcode/self-oss-instruct-sc2-concepts
def _get_list_feat_names(idx_feat_dict, num_pair): """Creates flattened list of (repeated) feature names. The indexing corresponds with the flattened list of T values and the flattened list of p-values obtained from _get_list_signif_scores(). Arguments: idx_feat_dict: {int: string} ...
bigcode/self-oss-instruct-sc2-concepts
def read_file(file: str) -> str: """ Reads a file. Args: file (str): file to read Returns: (str): content """ content = "" with open(file) as fp: content = fp.read() return content
bigcode/self-oss-instruct-sc2-concepts
def is_box_inside(in_box, out_box): """ check if in_box is inside out_box (both are 4 dim box coordinates in [x1, y1, x2, y2] format) """ xmin_o, ymin_o, xmax_o, ymax_o = out_box xmin_i, ymin_i, xmax_i, ymax_i = in_box if (xmin_o > xmin_i) or (xmax_o < xmax_i) or (ymin_o > ymin_i) or (ymax_...
bigcode/self-oss-instruct-sc2-concepts
def convert_path_to_targetname(include_path): """Convert an included header file's path to a quickstep library target in cmake. Args: include_path (str): A header file path taken from a C++ include statement. Returns: str: The target name in CMake that corresponds to the sp...
bigcode/self-oss-instruct-sc2-concepts
def parseMalformedBamHeader(headerDict): """ Parses the (probably) intended values out of the specified BAM header dictionary, which is incompletely parsed by pysam. This is caused by some tools incorrectly using spaces instead of tabs as a seperator. """ headerString = " ".join( "{}...
bigcode/self-oss-instruct-sc2-concepts
def parse_es_tag_results(response): """Parses results of es_tag_query such that a list of dicts is returned""" to_return = [] for hit in response: if tags := hit.to_dict().get('tags'): for key, value in tags.items(): to_return.append({'name': key, 'value': value}) ret...
bigcode/self-oss-instruct-sc2-concepts
def _is_required_parameter(param): """Indicates whether the parameter is required or not.""" return param.default is param.empty and param.kind is not param.VAR_POSITIONAL
bigcode/self-oss-instruct-sc2-concepts
def set_out_names(count_p2sh, non_std_only): """ Set the name of the input / output files from the experiment depending on the given flags. :param count_p2sh: Whether P2SH should be taken into account. :type count_p2sh: bool :param non_std_only: Whether the experiment will be run only considering no...
bigcode/self-oss-instruct-sc2-concepts
def normalizeWeights(weights): """ Normalize a list of weights so the sum of the list is equal to one. :return: List of normalized weights :rtype: list of floats """ multiplier = 1/sum(weights) if multiplier == 1: return weights return [w*multiplier for w in weights]
bigcode/self-oss-instruct-sc2-concepts
import json def kernel_for(notebook): """Read the notebook and extract the kernel name, if any""" with open(notebook, "r") as f: nb = json.load(f) md = nb.get("metadata") if md: ks = md.get("kernelspec") if ks: return ks["name"] return None
bigcode/self-oss-instruct-sc2-concepts
def find_parent(i3, window_id): """ Find the parent of a given window id """ def finder(con, parent): if con.id == window_id: return parent for node in con.nodes: res = finder(node, con) if res: return res return None ...
bigcode/self-oss-instruct-sc2-concepts
import logging def setup_logger(options): """Configure Python logging module""" log_fmt = "OpenNESS Setup: [%(levelname)s] %(module)s(%(lineno)d): %(message)s" ts_fmt = "%Y-%m-%dT%H:%M:%S" handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(log_fmt, ts_fmt)) root_logger =...
bigcode/self-oss-instruct-sc2-concepts
import calendar from datetime import datetime def date_n_month(date, n_month): """ returns the same date with "n_month" offset :param date: the date :param n_month: the number of month, 0 means this month, positive future month, negative previous month :return: the same date minus the "n_month_bac...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Pattern import re from typing import Optional from typing import Match def _remove_blank_lines(*, expression: str) -> str: """ Remove blank (break or spaces only) lines from expression string. Parameters ---------- expression : str Target express...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Callable from typing import Any import json def build_dumber(encoders: Dict[str, Callable[[Any], Any]]): """ Build a json dumber function from a map of encoders for fields that needs to be encoded differently. Args: encoders (Dict[str, Callable[[Any], Any]]): The ...
bigcode/self-oss-instruct-sc2-concepts
def butterworth(X, cutoff, order, mu=0, cutin=None): """ Butterworth transfer function. Parameters ---------- X : numpy.ndarray, required Range of values to plot over. cutoff : float, required Cut-off value for function. Note that if array X includes values both above a...
bigcode/self-oss-instruct-sc2-concepts
def is_from_module(obj, module): """Check if an object "belongs" to a module. >>> import collections >>> is_from_module(collections.ChainMap, collections) True >>> is_from_module(is_from_module, collections) False """ return getattr(obj, '__module__', '').startswith(module.__name__)
bigcode/self-oss-instruct-sc2-concepts
def has_all_permissions(user, permissions): """ Return `True` only if the user has all the permissions """ for perm in permissions: if not user.has_perm(perm): return False return True
bigcode/self-oss-instruct-sc2-concepts
def ensure_list(list_or_scalar): """Convert the input to a list if it is not.""" if isinstance(list_or_scalar, list): return list_or_scalar return [list_or_scalar]
bigcode/self-oss-instruct-sc2-concepts
def remove_templates(text): """Remove all text contained between matched pairs of '{{' and '}}'. Args: text (str): Full text of a Wikipedia article as a single string. Returns: str: A copy of the full text with all templates removed. """ good_char_list = [] prev_char = None ...
bigcode/self-oss-instruct-sc2-concepts
def _find_scalar_and_max_depth(pylist): """Finds nesting depth of scalar values in pylist. Args: pylist: A nested python `list` or `tuple`. Returns: A tuple `(scalar_depth, max_depth)`. `scalar_depth` is the nesting depth of scalar values in `pylist`, or `None` if `pylist` contains no scalars. ...
bigcode/self-oss-instruct-sc2-concepts
def binary_search(lo, hi, condition): """Binary search.""" # time complexity: O(log N) # space complexity: O(1) # dep: condition() # keep looping as long as the substring exists while lo <= hi: mid = (lo + hi) // 2 # the int division result = condition(mid) if ...
bigcode/self-oss-instruct-sc2-concepts
def info_qry(tickers, flds) -> str: """ Logging info for given tickers and fields Args: tickers: tickers flds: fields Returns: str Examples: >>> print(info_qry( ... tickers=['NVDA US Equity'], flds=['Name', 'Security_Name'] ... )) ticker...
bigcode/self-oss-instruct-sc2-concepts
def waveform_time_to_spec_time(t, spectrogram_len, spectrogram_generator): """Converts time in waveform space to time in spectrogram space given parameters of STFT""" hop_length, window_length = spectrogram_generator.hop_length, spectrogram_generator.win_length for hop in range(spectrogram_len): if...
bigcode/self-oss-instruct-sc2-concepts
def tokenize_rulekey_line(line): """ Tokenizes a line of the form: '<type>(<value>):<type>(<value>):...<type>(<value>):' Tokens are returned in reverse order, because the serialization was also reversed. """ # Since ':' can appear within a token value, we cheat and delimit tokens by '):'. delimi...
bigcode/self-oss-instruct-sc2-concepts
def generate_nav_urls(host, query, results): """Generate links to previous and next pages for navigation.""" cur_page = results.current_page() if cur_page > 1: url_prev_page = 'http://' + host + '/search?q=' + query \ + '&page=' + str(cur_page - 1) else: url_prev_...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def calculate_vwap( first_stock_values: dict, pv: float, sum_volume: float, actual_pv: float, actual_vol: float ) -> Tuple[float, float, float]: """ Function to calculate the VWAP. Volume-weighted average price(VWAP) """ if not ...
bigcode/self-oss-instruct-sc2-concepts
def GetMatchingDepsEntries(depsentry_dict, dir_path): """Gets all deps entries matching the provided path. This list may contain more than one DepsEntry object. Example: dir_path='src/testing' would give results containing both 'src/testing/gtest' and 'src/testing/gmock' deps entries for Chromium's DEPS. Exa...
bigcode/self-oss-instruct-sc2-concepts
def _ensure_is_list(obj): """ Return an object in a list if not already wrapped. Useful when you want to treat an object as a collection,even when the user passes a string """ if obj: if not isinstance(obj, list): return [obj] else: return obj else: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def convert_negative_none(value: int) -> Optional[int]: """Convert an negative int value from the ToonAPI to a NoneType.""" return None if value < 0 else value
bigcode/self-oss-instruct-sc2-concepts
import re def short_expression(original: str, level: int = 0) -> str: """Abbreviate the expression, keeping it human-readable. If `level` is 0, just remove parts that are implicit from context, such as a leading ``PSA_KEY_TYPE_``. For larger values of `level`, also abbreviate some names in an una...
bigcode/self-oss-instruct-sc2-concepts
def frame_center(array, verbose=False): """ Return the coordinates y,x of the frame(s) center. Parameters ---------- array : 2d/3d/4d array_like Frame or cube. verbose : bool optional If True the center coordinates are printed out. Returns ------- cy, cx : float ...
bigcode/self-oss-instruct-sc2-concepts
import re def _sanitize_to_identifer(name): """ Changes a string with various characters into an identifier that is valid for python. i.e. 'minimum RR-interval' -> 'minimum_RR_interval' """ n = name.strip() n = re.sub('/', ' ', n) n = re.sub('-', ' ', n) n = re.sub(' +', '_', n) ...
bigcode/self-oss-instruct-sc2-concepts
def time_switch(x): """ Convenience codes to convert for time text to pandas time codes. """ return { 'min': 'Min', 'mins': 'Min', 'minute': 'Min', 'minutes': 'Min', 'hour': 'H', 'hours': 'H', 'day': 'D', 'days': 'D', 'week': 'W', ...
bigcode/self-oss-instruct-sc2-concepts
async def get_sensor(client, sensor_name): """Get last sensor value (in encoded form), or None if no value.""" reply, informs = await client.request('sensor-value', sensor_name) assert reply == [b'1'] status = informs[0].arguments[3] value = informs[0].arguments[4] if status in {b'nominal', b'wa...
bigcode/self-oss-instruct-sc2-concepts
from itertools import islice, tee def sliding_window(iterable, length=2): """ Return a sliding window over iterable. """ its = ( islice(it, i, None) for i, it in enumerate(tee(iterable, length)) ) return zip(*its)
bigcode/self-oss-instruct-sc2-concepts
def get_auth_results(reportee, dkim_result, spf_result, **kw): """Return "auth_results" part. This can be no or more raw DKIM results and one or more SPF results. For now we always return either no or one DKIM and one SPF result, based on the passed `dkim_result` and `spf_result` and use only the `reportee` dom...
bigcode/self-oss-instruct-sc2-concepts
def _compare_dacls(dacl1, dacl2): """ This method compare the two given DACLs to check if they are identical. Identical means here that they contains the same set of ACEs in the same order. """ return ([dacl1.GetAce(index) for index in range(dacl1.GetAceCount())] == [dacl2.GetAce(index) ...
bigcode/self-oss-instruct-sc2-concepts
def cat_dist(x, y): """ A dummy implementation of a binary distance metric. """ return int(x['x'] != y['x']) + int(x['xx'] != y['xx'])
bigcode/self-oss-instruct-sc2-concepts
def makelower(indict): """return a copy of a string->string dict such that all keys and values are lowercase.""" return {k.lower(): v for k, v in indict.items()}
bigcode/self-oss-instruct-sc2-concepts
import random def make_humane_gibberish(length): """Generate a meaningless but human-friendly string. Characters are chosen so that no two characters are alike. Easily confused characters, such as '1' and 'l' are also excluded. """ result = '' for i in range(length): result += random.choice('ACEFHJKNPQRTVXY...
bigcode/self-oss-instruct-sc2-concepts
def as_tuple(*values): """ Convert sequence of values in one big tuple. Parameters ---------- *values Values that needs to be combined in one big tuple. Returns ------- tuple All input values combined in one tuple Examples -------- >>> as_tuple(None, (1, 2,...
bigcode/self-oss-instruct-sc2-concepts
def _process_edge_df(subgraph): """ Returns an edge DataFrame with the names of the genes instead of their IDs. """ return subgraph.get_edge_dataframe().merge( subgraph.get_vertex_dataframe().reset_index(), left_on='source', right_on='vertex ID', ).merge( subgraph.get...
bigcode/self-oss-instruct-sc2-concepts
def active(config): """ Verifies that the signature of a configuration has not timed out. :param config: :return: True/False """ return True
bigcode/self-oss-instruct-sc2-concepts
def get_data_year_location_age(year, location, age, data_structure): """ Retrieve the data for a given year, location, and age. :param year: a defined year for which corresponding data will be returned :param location: a defined location for which corresponding data will be returned :param age: a d...
bigcode/self-oss-instruct-sc2-concepts
def getChange(current, previous): """Get the Percentage Change. Parameters: current (int): Current value previous (int): Previous value Returns: int: Percentage Change """ if current == previous: return 0 try: return ((current - previous) / previous) * 100.0 e...
bigcode/self-oss-instruct-sc2-concepts
def logical_xor(a, b, unsafe=False): """logical xor without the bloat of numpy.logical_xor could be substituted with numpy.logical_xor !important: if unsafe is set to True, a and b are not checked. This improves speed but is risky. expects integers [0,1] or bools """ if not unsafe: ...
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_output_gradient_times_vec_intermediate(relu_network, x, z0): """ Compute z and Wz defined in output_gradient_times_vector() function. Notice that when the relu network input is 0, we use only the right derivative. Return: z, Wz: Refer to output_gradient_times_vector...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def sector_to_subreddit_list(sector: str) -> List: """Returns list of subreddit for respective sector Parameters ---------- sector : str sector of ticker Returns ------- List List of subreddits """ sector_subreddit_map = { "Basic Ma...
bigcode/self-oss-instruct-sc2-concepts
def v_relative(v, met): """ Estimates the relative air velocity which combines the average air velocity of the space plus the relative air velocity caused by the body movement. Parameters ---------- v : float air velocity measured by the sensor, [m/s] met : float metabolic rate,...
bigcode/self-oss-instruct-sc2-concepts
def list_duplicates(cells): """Find duplicates in list for detailed reporting """ # reference https://stackoverflow.com/questions/9835762 seen = set() # save add function to avoid repeated lookups seen_add = seen.add # list comprehension below chosen for computational efficiency # adds a...
bigcode/self-oss-instruct-sc2-concepts
def convert_range(p): """Convert a float from 0-1 range to integer 0-255 range.""" return max(0, min(255, round(255 * p)))
bigcode/self-oss-instruct-sc2-concepts
def GetRunKeyName(name): """Returns a str used to uniquely identify a run.""" return 'Run_%s' % name
bigcode/self-oss-instruct-sc2-concepts
def binary_search(my_list: list, item: int) -> int: """ 二分法排序 :param my_list: 查找列表 :param item: 所需要查找的元素 :return: 索引位置, 没有找到返回 -1 """ low_index = 0 hight_index = len(my_list) - 1 while low_index <= hight_index: mid = (low_index + hight_index) // 2 guess = my_list[mid]...
bigcode/self-oss-instruct-sc2-concepts
def parse_data(dataframe): """ Dataframe looks like: label1 label2 label3 ... trial1 0.4 0.4 ... trial2 0.6 0.1 ... . . . . . . returns: [ [0.4, 0.6, ...] , [0.4, 0.1, ...] ] """ labels = dataframe.co...
bigcode/self-oss-instruct-sc2-concepts
def _is_all_zeros(data: bytes) -> bool: """Returns True if data is None, empty, or consists of all zeros.""" if data is None: return True for i in data: if i != 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
def get_left_child(iIndex): """ Given an index it returns it's left child's index. """ return 2 * iIndex + 1
bigcode/self-oss-instruct-sc2-concepts
def unbox_enum(typ, obj, c): """ Convert an enum member's value to its native value. """ valobj = c.pyapi.object_getattr_string(obj, "value") return c.unbox(typ.dtype, valobj)
bigcode/self-oss-instruct-sc2-concepts
def unsigned_int(value): """Convert from signed to unsigned int (Channel Access does not support unsigend int)""" if type(value) == int and value < 0: value = value+0x100000000 return value
bigcode/self-oss-instruct-sc2-concepts
def find_all(str_:str, key:str): """ Returen all the starting indices of string `key` in string `str_`. Example: ---------- >>> find_all("abcaa", 'a') [0, 3, 4] """ p, indices = -1, [] while True: p = str_.find(key, p + 1) if p < 0: break indices.append(...
bigcode/self-oss-instruct-sc2-concepts
def _token_symbols(token_list): """Given a list of tokens, returns a list of their symbol names.""" return [token.symbol for token in token_list]
bigcode/self-oss-instruct-sc2-concepts
def formatannotation(annotation, base_module=None): """ This is taken from Python 3.7's inspect.py; the only change is to add documentation. INPUT: - ``annotation`` -- annotation for a function - ``base_module`` (optional, default ``None``) This is only relevant with Python 3, so the doct...
bigcode/self-oss-instruct-sc2-concepts
def bytes2human(size, *, unit="", precision=2, base=1024): """ Convert number in bytes to human format. Arguments: size (int): bytes to be converted Keyword arguments (opt): unit (str): If it will convert bytes to a specific unit 'KB', 'MB', 'GB', ...
bigcode/self-oss-instruct-sc2-concepts
def boolean(obj): """ Convert obj to a boolean value. If obj is string, obj will converted by case-insensitive way: * convert `yes`, `y`, `on`, `true`, `t`, `1` to True * convert `no`, `n`, `off`, `false`, `f`, `0` to False * raising TypeError if other values passed If obj is non...
bigcode/self-oss-instruct-sc2-concepts
from operator import mod def is_islamic_leap_year(i_year): """Return True if i_year is an Islamic leap year.""" return mod(14 + 11 * i_year, 30) < 11
bigcode/self-oss-instruct-sc2-concepts
def _split_up_multiple_entries(entry): """Split up lists of entries that have been recorded as a single string.""" split_types = ['<br>', '<br/>', '<br />'] for split_type in split_types: if split_type in entry: return entry.split(split_type) return [entry]
bigcode/self-oss-instruct-sc2-concepts
def fibonacci(n): """Return nth term in fibonacci sequence Parameters ---------- n: int nth term in fibonacci sequence to calculate Returns ------- int: int nth term of fibonacci sequence, equal to sum of previous two terms Examples ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_all_args(fn) -> list: """ Returns a list of all arguments for the function fn. >>> def foo(x, y, z=100): return x + y + z >>> get_all_args(foo) ['x', 'y', 'z'] """ sig = inspect.signature(fn) return list(sig.parameters)
bigcode/self-oss-instruct-sc2-concepts
import typing def _remove_arg( source: typing.List[str], flag: str, has_value: bool, ) -> typing.List[str]: """ Search for and remove the specified flag within the source arguments. This function removes it and its optional value if has_value is specified, returning a copy of the source l...
bigcode/self-oss-instruct-sc2-concepts
def canBalance(arr): """ Determine if a list of numbers is balance. Parameter: arr := list of numbers Return: True if a split position can be found in the arr such that both halves sum of numbers are equal. False otherwise. Assuming numbers can be integers or float...
bigcode/self-oss-instruct-sc2-concepts
import itertools def std_from_mean_kde(data): """ Plot the KDE of the pandas series along with vertical reference lines for each standard deviation from the mean. Parameters: - data: pandas Series with numeric data Returns: Matplotlib Axes object. """ mean_mag, st...
bigcode/self-oss-instruct-sc2-concepts
def makeopendir(fs, directory): """ Creates and opens the given directory in the given PyFilesystem. """ if not fs.isdir(directory): fs.makedir(directory) return fs.opendir(directory)
bigcode/self-oss-instruct-sc2-concepts
import functools def patch(cls, attr): """Patch the function named attr in the object cls with the decorated function.""" orig_func = getattr(cls, attr) @functools.wraps(orig_func) def decorator(func): def wrapped_func(*args, **kwargs): return func(orig_func, *args, **kwargs) ...
bigcode/self-oss-instruct-sc2-concepts