seed
stringlengths
1
14k
source
stringclasses
2 values
import string def is_in(s): """Return 1 if the string contains at least one punctuation symbol""" is_p = 0 for i in s: if i in string.punctuation: is_p = 1 break return is_p
bigcode/self-oss-instruct-sc2-concepts
def _is_cov_update_task(task_id, num_tasks): """Returns True if this task should update K-FAC's covariance matrices.""" if num_tasks < 3: return False return 0.6 * num_tasks <= task_id < num_tasks - 1
bigcode/self-oss-instruct-sc2-concepts
import math def normalize(vx, vy): """ Normalizes the input vector and returns its coordinates. """ norm = math.sqrt(vx * vx + vy * vy) if (norm > 1e-6): vx /= norm vy /= norm return (vx, vy)
bigcode/self-oss-instruct-sc2-concepts
def get_default_acquisition_for_domain(domain): """ Returns the default acquisition for the domain. """ if domain.get_type() == 'euclidean': return 'ei-ucb-ttei-add_ucb' else: return 'ei-ucb-ttei'
bigcode/self-oss-instruct-sc2-concepts
def can_edit_user(logged_user, target_user): """ Is logged in user allowed to edit target user """ if logged_user == target_user: return True if logged_user.is_staff: return True return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def merge_dict(dest: Dict, src: Dict, path=None, overwrite=True): """ Merges src dict into dest dict. Parameters ---------- dest: Dict dest dict src: Dict source dict path: List merge path overwrite: bool Whether overwrite dest d...
bigcode/self-oss-instruct-sc2-concepts
def tokenised(text): """ Return a tokenised text list. :param text: text string to be tokenised. :return: list """ return [word for word in text.split()]
bigcode/self-oss-instruct-sc2-concepts
def subset_to_str_list(subset_sol): """From a subset solution (e.g.: [[0,1],[0,0]]) returns a list with the rows string and the columns string (e.g.: ['0 1', '0 0']) or NO_SOL""" return [' '.join([str(e) for e in subset_sol[0]]), \ ' '.join([str(e) for e in subset_sol[1]])]
bigcode/self-oss-instruct-sc2-concepts
def _default_with_off_flag(current, default, off_flag): """Helper method for merging command line args and noxfile config. Returns False if off_flag is set, otherwise, returns the default value if set, otherwise, returns the current value. """ return (default or current) and not off_flag
bigcode/self-oss-instruct-sc2-concepts
import math def add_smooth_sigma_round(cli_args, cur_smooth): """ Pull user-defined smoothing variables, calculate the sigma value for additional smoothing, and round the sigma value to 7 decimal places :param cli_args: Dictionary containing all command-line arguments from user :param cur_smooth: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def find_min_coins(coins: List[int], index: int, value: int): """ Find minimum number of coins that make a given value :param coins: List of coins. :param index: Length of the coins list minus one, for example: len(coins_list)-1. :param value: Amount required to be filled ...
bigcode/self-oss-instruct-sc2-concepts
def get_status(data_model, status) -> str: """Get the user friendly status name.""" statuses = data_model["sources"]["quality_time"]["parameters"]["status"]["api_values"] # The statuses have the human readable version of the status as key and the status itself as value so we need to # invert the diction...
bigcode/self-oss-instruct-sc2-concepts
def is_in_path(file_path, find_str): """ check if find_str is in filename given file path """ file_path = file_path.lower() find_str = find_str.lower() return file_path.split('/')[-1].find(find_str) >= 0
bigcode/self-oss-instruct-sc2-concepts
def partition_list(Z, L): """Returns a dictionary partitioning list L according to assignments in Z. Example: >>> Z = {0:0, 1:2, 2:7, 3: 7, 4:0} >>> L = [2, 1, 0, 4, 3] >>> partition_list(Z, L) {0:[0, 4], 2:[1], 7:[2, 3]} """ result = {} for l in L: k = Z[l] if k in ...
bigcode/self-oss-instruct-sc2-concepts
def create_category_index(categories): """Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing categor...
bigcode/self-oss-instruct-sc2-concepts
def get_module_version(module): """ Retrieve __version__ variable from an imported module. @param module: The module instance. @type module: module @return: The version hash without the surrounding text. If not present return None. @rtype: str or None """ if hasattr(module, '__v...
bigcode/self-oss-instruct-sc2-concepts
def dtanh(tanh_x): """ dTanH(x) = 1 - TanH(x)^2 """ return 1 - tanh_x**2
bigcode/self-oss-instruct-sc2-concepts
import json import requests def groupAdd(apikey,name): """ Creates a new Group with the chosen Name apikey: Your ApiKey from FileCrypt name: The name of your new group """ data={"api_key":apikey,"fn":"group","sub":"add","name":name,"parent":"0"} return json.loads(requests.post("https://filecrypt.cc/api.php",da...
bigcode/self-oss-instruct-sc2-concepts
def _is_case_insensitive_substring(a, b): """return True if `a` is a case insensitive substring of `b`, else False""" return str(a).lower() in str(b).lower()
bigcode/self-oss-instruct-sc2-concepts
def update_probability(prior, prob_given_true, prob_given_false): """Update probability using Bayes' rule.""" numerator = prob_given_true * prior denominator = numerator + prob_given_false * (1 - prior) return numerator / denominator
bigcode/self-oss-instruct-sc2-concepts
def h(p1, p2): """Manhattan distance""" (x1, y1), (x2, y2) = p1, p2 return abs(x1 - x2) + abs(y1 - y2)
bigcode/self-oss-instruct-sc2-concepts
def check_has_backup_this_month(year, month, existing_backups): """ Check if any backup in existing_backups matches year and month. """ for backup in existing_backups: if backup.createdYear == year and backup.createdMonth == month: return True return False
bigcode/self-oss-instruct-sc2-concepts
def get_file_info(fname): """ Parse the asset file name e.g. inp: 20200714_103348_ssc6_u0001_analytic.tif out: analytic, 20200714_103348_ssc6_u0001 """ info = fname.split("_") asset_type, other_info = info[4:], info[:4] # for asset_type of 2 words if len(asset_type) == 2: ...
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def normalize_text(text: str) -> str: """ Normalize text to NFC which represents chars as an unique code. Parameters ---------- text: str Input text string. Returns ------- str: Normalized text. """ return unicodedata.normalize("NFC", text)
bigcode/self-oss-instruct-sc2-concepts
def rdkit_atom_list(mol, key, method, args=None): """ Make a list of atoms with atomic information from rdkit.mol. Args: mol (rdkit.Chem.Mol): Mol object to get information from. key (str): Key of property to put in list. method (func): Class member method for rdkit.Chem.rdchem.Ato...
bigcode/self-oss-instruct-sc2-concepts
def bounding_box(X): """ Calculates the boundaries of a given dataset on all sides Parameters: X - a data matrix where each row is a dimensional array of an item to be clustered Returns: Two tuples, where the first contains the minimum and maximum x values, and the second con...
bigcode/self-oss-instruct-sc2-concepts
def _calcFlatSizes(canvasaxes, bounds, width, height, vert=True): """Used by :func:`calcVerticalSizes` and :func:`calcHorizontalSizes`. Calculates the width and height, in pixels, of each canvas. :arg vert: If ``True`` the sizes are calculated for a vertical layout; otherwise they are calcu...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json(path): """Read data from JSON file.""" with open(path, 'r') as file: return json.load(file)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import TextIO def _open_or_fallback( file_path : Optional[str], mode: str, fallback: Optional[TextIO] ): """ Arguments: file_path: a file path to open, or None to use the fallback. mode: mode to open with (e.g. "w" or "r") fallback: what to use when file_path is...
bigcode/self-oss-instruct-sc2-concepts
def Parent(tpe, criterion): """ A criterion used to search for records by filtering the parents using a criterion. For example * search for observables of TLP:RED cases * search for logs of tasks called 'Communication' Arguments: tpe (str): class name of the parent: `case`, `case_task`...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Mapping from typing import Any from typing import Dict def combine_api_output_dictionaries(input_dicts: Iterable[Mapping[str, Any]], require_uniqueness: bool = True ) -> Dict[str, Any]: """Merges...
bigcode/self-oss-instruct-sc2-concepts
def CP(record): """ "Channel Process": a CP input link will cause the linking record to process any time the linked record is updated. Example (Python source) ----------------------- `my_record.INP = CP(other_record)` Example (Generated DB) ---------------------- `field(INP, "other CP"...
bigcode/self-oss-instruct-sc2-concepts
def _make_dict(lang, my_tup): """Make tuple in a dictionary so can be jsonified into an object. """ labels = ['comment_text', 'offering_city', 'offering_fiscal_year', 'offering_quarter', 'stars', 'nanos'] results = {key: val for key, val in zip(labels, my_tup)} return results
bigcode/self-oss-instruct-sc2-concepts
def decompose_mask_status( x ): """ Given a mask value, decompose what sub-status compose it Example: One pixel mask value is 928: 928 decompose into 32, 128, 256, 512 :Parameters: x: int Mask value :Returns: powers: list of int List of powers of 2 ma...
bigcode/self-oss-instruct-sc2-concepts
def lower(text): """Returns text that has been lower. Args: text (str): input text to process. Output: result (str): corresponding text which has been lower. """ return text.lower()
bigcode/self-oss-instruct-sc2-concepts
def segment_signal(signal, length=2, skip=0.5, sample_rate=257): """ Segments a signal into overlapping sections with defined length and skip size :param signal: the signal to segment :param length: the length of each segment (in seconds) :param skip: length of the space between the start of two co...
bigcode/self-oss-instruct-sc2-concepts
def build_portfolio(processed_market, portfolio): """Build a processed portfolio by reindex processed_market dataframe""" return processed_market.reindex(portfolio.index)
bigcode/self-oss-instruct-sc2-concepts
import yaml def patterns(package_root): """Grab glob patterns from config file. """ conf_file = package_root.parent / "addheader.yml" if not conf_file.exists(): print(f"Cannot load configuration file from '{conf_file}'. Perhaps this is not development mode?") return None with open(...
bigcode/self-oss-instruct-sc2-concepts
import json def s3_create_anon_access_policy(bucket_name): """Create a bucket policy for anonymous read access and anonymous bucket listing. Returns ------- anon_access_policy: A json formatted s3 bucket policy """ anon_policy_dict = { "Version": "2012-10-17", "Statement": [ ...
bigcode/self-oss-instruct-sc2-concepts
import math def compute_ratio(a_value,b_value): """ Computes the ratio between two values, handles divide by zero errors """ if b_value == 0: if a_value == 0: ratio= float('Nan') else: ratio= math.copysign(float('inf'),a_value) else: ratio= a_value/...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def _in_0_region( interaction_coefficients: Tuple[float, float, float], weyl_tol: float = 1e-8, ) -> bool: """Tests if (x, y, z) ~= (0, 0, 0) assuming x, y, z are canonical.""" x, y, z = interaction_coefficients return abs(x) <= weyl_tol and abs(y) <= weyl_tol and abs(z) <...
bigcode/self-oss-instruct-sc2-concepts
def get_points(rays_o, rays_d, z_vals): """ Inputs: rays_o: (*Nrays, 3) rays_d: (*Nrays, 3) z_vals: (*Nrays, N) Output: points: (*Nrays, N, 3) """ points = rays_o[..., None, :] + \ rays_d[..., None, :] * z_vals[..., None] return points
bigcode/self-oss-instruct-sc2-concepts
import uuid def get_uuid() -> str: """ Generate UUID. :return: generated UUID """ return str(uuid.uuid4())
bigcode/self-oss-instruct-sc2-concepts
def percent_profitable(winning_trades: int, total_trades: int) -> float: """ Percent profitable .. math:: Winning Trades / Total Trades = Percent Profitable :param winning_trades: int of the number of winning trades :param total_trades: int of the total number of trades executed :return: f...
bigcode/self-oss-instruct-sc2-concepts
def modrange(x, low, high): """mod x such that it is between [low, high). >>> modrange(2.5, 1, 2) 1.5 >>> modrange(3., 1, 2) 1.0 """ spread = high - low diff = x - low mod = diff % spread return low + mod
bigcode/self-oss-instruct-sc2-concepts
def plus_two(x): """Add two to the argument.""" return x + 2
bigcode/self-oss-instruct-sc2-concepts
import json def get_robot_constraints_json() -> str: """Return a test robot_constraints.json.""" robot_constraints = { "devices": [{ "deviceType": "robot", "parameters": { "jointLimits": [[-363.0000016970871, 363.00000013981145], [-363.00000169...
bigcode/self-oss-instruct-sc2-concepts
def update_routing_segmentation_maps_from_source_segment( self, segment_id: int, segment_map: dict, ) -> bool: """Update D-NAT policies for specific source segment .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - vrf ...
bigcode/self-oss-instruct-sc2-concepts
import calendar def datetime2epoch(dt): """Convert a non-naive datetime object to a UNIX epoch timestamp""" return calendar.timegm(dt.utctimetuple())
bigcode/self-oss-instruct-sc2-concepts
def biggest_differences_paragraphs(table): """ Finds the paragraphs with greatest average differences between words and their most frequent alternative across each semantic dimension Parameters ---------- table : a data frame The data frame representing average a paragraph's arousal, va...
bigcode/self-oss-instruct-sc2-concepts
def element(point, p, q, n): """Test, whether the given point is on the curve (p, q, n)""" if point: x, y = point return (x * x * x - p * x - q) % n == (y * y) % n else: return True
bigcode/self-oss-instruct-sc2-concepts
def parse_mtm(mtm_serial): """ Parses a mtm_serial string to a result of machine, model, serial """ mtm, serial = mtm_serial.split('_', 1) model = mtm[4:7] machine = mtm[0:4] return machine, model, serial
bigcode/self-oss-instruct-sc2-concepts
def isdigit(char): """Return True iff char is a digit. """ return char.isdigit()
bigcode/self-oss-instruct-sc2-concepts
def mod(a, b): """ Given two numbers, this function will return the first number modulo the second number """ return a % b
bigcode/self-oss-instruct-sc2-concepts
def scriptClose(*args, **kwargs): """ Close the current script or group. Returns True if successful. """ return None
bigcode/self-oss-instruct-sc2-concepts
import json def load_config(config_file="config.json"): """ Read the given file to build configuration, the configuration needs to be json """ return json.load(open(config_file))
bigcode/self-oss-instruct-sc2-concepts
import hashlib import json def hash_dict(exp_dict): """Create a hash for an experiment""" return hashlib.md5(json.dumps(exp_dict, sort_keys=True).encode("utf-8")).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def esc (s, is_attribute=False): """ escape XML special charcters Parameters: is_attribute if True, also escape " and ' for attribute values Returns: the escaped string """ s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") if is_attribute: return s.r...
bigcode/self-oss-instruct-sc2-concepts
def is_admin(token): """Check if token has an admin role.""" roles = token.credentials.get("https://api.imjoy.io/roles", []) if "admin" not in roles: return False return True
bigcode/self-oss-instruct-sc2-concepts
def _center_strip_right(text: str, width: int) -> str: """Returns a string with sufficient leading whitespace such that `text` would be centered within the specified `width` plus a trailing newline.""" space = (width - len(text)) // 2 return space * " " + text + "\n"
bigcode/self-oss-instruct-sc2-concepts
def max_res_from_play_info( play_info: dict ) -> dict: """This is the parser for finding maximum resolution from play info (FVideo, VOD). Arguments: play_info (:class:`dict`) : Play info dict to find maximum resolution. Returns: :class:`dict`. Video data that has maximum resolution...
bigcode/self-oss-instruct-sc2-concepts
def to_visfmt(annot): """ Helper function that changes (tw,th,bw,bh) -> (tw,th,w,h). Used to convert annotations from ilsvr to visdrone's since most scripts are already written in visdrone's format. """ #Check if it's an empty bbox (neg scene) if len(annot) > 1: load = [annot[0]...
bigcode/self-oss-instruct-sc2-concepts
def triangle_area(a, b, c): """ Return the area of the triangle defined by ``[a, b, c]``, where each vertex contains floats ``[x, y]`` """ return 0.5 * abs( a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) )
bigcode/self-oss-instruct-sc2-concepts
def owner_ids_to_string_array(owner_ids): """ Converts a snowflake owner id to an array of strings. Parameters ---------- owner_ids : `iterable` of `int` Snowflakes. Returns ------- owner_id_array : `list` of `str` """ return [str(owner_id) for owner_id in owner...
bigcode/self-oss-instruct-sc2-concepts
def solution_linear(k: int, list_: list[int]) -> bool: """ O(n) Returns True if k can be found by addition of any 2 numbers in list """ potential = set() for a in list_: if a in potential: return True potential.add(k - a) return False
bigcode/self-oss-instruct-sc2-concepts
import logging def clean_eventbrite_url (url): """ Remove unneeded query info from Eventbrite URL """ if url.find('?') >= 0: try: base, params = url.split("?", 1) except ValueError as e: logging.error( "Could not split." "Offending url is {}".f...
bigcode/self-oss-instruct-sc2-concepts
def get_need_size_for_each_dimension(used_coordinates: list, num_dimensions) -> list: """ Given a list of tuples, where each tuple is a 2N dimensional coordinate, get back a tuple of length 2N with the max value in each coordinate (plus 1 so the number is correct for sizing buffers) :param used_coordina...
bigcode/self-oss-instruct-sc2-concepts
import pickle def unserialize_data(filename): """ Returns the stored dictionary of vocabulary given the filename in 'filename.pickle' format (filename must be a string). """ with open(f'pickles/{filename}', 'rb') as f: stored_vocab = pickle.load(f) return stored_vocab
bigcode/self-oss-instruct-sc2-concepts
import math def gsd(lat, zoom): """ Computes the Ground Sample Distance (GSD). More details can be found here: https://msdn.microsoft.com/en-us/library/bb259689.aspx Args: lat : float - latitude of the GSD of interest zoom : int - zoom level (WMTS) """ return (math.cos(lat * ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def _get_available_name(original, cond): """ Iterate over possibles names for original string, adding a different number as suffix at each iteration. The new name is available by checking if it pass the condition. """ for c in itertools.chain([""], itertools.count()): suff...
bigcode/self-oss-instruct-sc2-concepts
def GetGaiaContext(tab): """Returns Gaia's login page context.""" for context in tab.GetWebviewContexts(): if context.GetUrl().startswith('https://accounts.google.com/'): return context return None
bigcode/self-oss-instruct-sc2-concepts
def get_unit(operation, num, primary=True): """Return the correct form of the unit tracked by the given operation.""" if not primary: return "ISK" types = { "killboard": "ship|ships", "collection": "item|items" } if "unit" in operation: unit = operation["unit"] e...
bigcode/self-oss-instruct-sc2-concepts
import math def BIC(loglik, k, n): """ Bayesian Information Criterion Parameters ---------- loglik : float Log likelihood k : int Parameters estimated n : int Number of observations Parameters ---------- float BIC, the smaller the better """ ...
bigcode/self-oss-instruct-sc2-concepts
def is_close(a0, a1, tol=1.0e-4): """ Check if two elements are almost equal with a tolerance. :param a0: number to compare :param a1: number to compare :param tol: The absolute tolerance :return: Returns boolean value if the values are almost equal """ return abs(a0 - a1) < tol
bigcode/self-oss-instruct-sc2-concepts
def _split_str(s, n): """ split string into list of strings by specified number. """ length = len(s) return [s[i:i + n] for i in range(0, length, n)]
bigcode/self-oss-instruct-sc2-concepts
def meters_to_feet(n): """ Convert a length from meters to feet. """ return float(n) * 3.28084
bigcode/self-oss-instruct-sc2-concepts
def _find_missing_and_invalid_fields( required_fields, json_data ): """ Look for missing or invalid fields, and return them. """ missing = [] invalid = [] for req, types in required_fields.items(): if req not in json_data.keys(): missing.append( req ) if...
bigcode/self-oss-instruct-sc2-concepts
def listSubset(requiredList, suppliedList): """Returns true if the requiredList is a subset of the suppliedList.""" return set(requiredList).issubset(set(suppliedList))
bigcode/self-oss-instruct-sc2-concepts
def all_equal(*args): """ Returns True if all of the provided args are equal to each other Args: *args (hashable): Arguments of any hashable type Returns: bool: True if all of the provided args are equal, or if the args are empty """ return len(set(args)) <= 1
bigcode/self-oss-instruct-sc2-concepts
import json def loads(string, **kwargs): """Load object from JSON string.""" return json.loads(string, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def _utcnow(now): """Returns the given time if not None, or datetime.utcnow() otherwise.""" if now is None: return datetime.utcnow() return now
bigcode/self-oss-instruct-sc2-concepts
def _FormatHumanReadable(number): """Formats a float into three significant figures, using metric suffixes. Only m, k, and M prefixes (for 1/1000, 1000, and 1,000,000) are used. Examples: 0.0387 => 38.7m 1.1234 => 1.12 10866 => 10.8k 682851200 => 683M """ metric_prefixes = {-3: 'm',...
bigcode/self-oss-instruct-sc2-concepts
def _pair(s: str, i: int, i1: int, j: int, j1: int) -> str: """Return a stack representation, a key for the NN maps Args: s: Sequence being folded i: leftmost index i1: index to right of i j: rightmost index j1: index to left of j Returns: str: string re...
bigcode/self-oss-instruct-sc2-concepts
def find_cuds_object(criterion, root, rel, find_all, max_depth=float("inf"), current_depth=0, visited=None): """Recursively finds an element inside a container. Use the given relationship for traversal. Args: criterion (Callable): Function that returns True on the Cuds object ...
bigcode/self-oss-instruct-sc2-concepts
import re def condense_zero_units(css: str) -> str: """Replace `0(px, em, %, etc)` with `0`.""" return re.sub(r"([\s:])(0)(px|em|%|in|q|ch|cm|mm|pc|pt|ex|rem|s|ms|" r"deg|grad|rad|turn|vw|vh|vmin|vmax|fr)", r"\1\2", css)
bigcode/self-oss-instruct-sc2-concepts
def common_data(list1, list2): """ returns true if both lists have something in common """ result = False # traverse in the 1st list for x in list1: # traverse in the 2nd list for y in list2: # if one common if x == y: result = True return result return result
bigcode/self-oss-instruct-sc2-concepts
def dict2bibtex(data): """ Convert a single BibTeX entry dict to a BibTeX string. :param data: A dict representing BibTeX entry, as the ones from \ ``bibtexparser.BibDatabase.entries`` output. :return: A formatted BibTeX string. """ bibtex = '@' + data['ENTRYTYPE'] + '{' + data['ID'...
bigcode/self-oss-instruct-sc2-concepts
def translate_to_hsv(in_color): """ Standard algorithm to switch from one color system (**RGB**) to another (**HSV**). :param tuple(float,float,float) in_color: The RGB tuple list that gets translated to HSV system. The values of each element of the tuple is between **0** and **1**. :return: The transl...
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def getGlobValue(globs, path): """ Returns the value of the glob, where path matches :Parameters: - `globs`: The glob list (``[(glob, associated value)]``) - `path`: The path to match :Types: - `globs`: sequence - `path`: ``str`` :retur...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def preprocess_check_and_replace(old: str, new: str) -> Callable[[str], str]: """ Create a preprocess function that replaces `old` with `new` (and fails when there is no `old`). """ def preprocess(orig: str) -> str: assert old in orig return orig.replace(ol...
bigcode/self-oss-instruct-sc2-concepts
def get_info_fields(record_info, info_fields): """ Get info fields from pyvcf record_info Args: record_info (pyvcf record infos): info fields from vcf record info_fields (list): info to get from record_info Returns: info (dict): Info dictionary containing requested info fields ...
bigcode/self-oss-instruct-sc2-concepts
def index_(iterable, x) -> int: """Return zero-based index of the first item whose value is equal to x. Raises a ValueError if there is no such item. We need a custom implementation instead of the built-in list .index() to be compatible with NumPy array and Pandas Series. Parameters ----------...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def compose(*funcs): """ chained function composition wrapper creates function f, where f(x) = arg0(arg1(arg2(...argN(x)))) if *funcs is empty, an identity function is returned. Args: *funcs: list of functions to chain Returns: a new functio...
bigcode/self-oss-instruct-sc2-concepts
def str_or_none(val): """Like str, but allows a value of None to pass through as-is.""" return str(val) if val is not None else None
bigcode/self-oss-instruct-sc2-concepts
def fibonacci(i): """ This function finds the ith number in the Fibonaci series, -1 otherwise. """ if i <= 0: return -1 #Fixing the code to see if test cases go through if i <= 2: return 1 prev = 1 curr = 1 for k in range(i-2): temp = curr curr += prev prev = temp return curr
bigcode/self-oss-instruct-sc2-concepts
import math def set_angle(angle: float) -> float: """ Ensure the angle is within the range of [-pi, pi] radian convention """ return math.atan2(math.sin(angle), math.cos(angle))
bigcode/self-oss-instruct-sc2-concepts
def only_1st_and_lst(items): """Return (at most) the first and last items from a list. """ # print(str(items[0]) + '-' + str(items[len(items) - 1])) items_len = len(items) if items_len == 0: return False # Plot only 1st and last. return items if items_len == 1 else items[::items_len...
bigcode/self-oss-instruct-sc2-concepts
def b(string): """ convert string (unicode, str or bytes) to binary representation """ if isinstance(string, bytes): return string return string.encode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
def getSep(path, pattern='/\\'): """ Get path separator or indicator. :param path: relative or absolute path (str). :param pattern: guess characters to compare path (str). :return: sep (str). .. note:: It is equivalent to os.path.sep but obtained from the given path and patterns. """ i...
bigcode/self-oss-instruct-sc2-concepts
def widget_type(field): """ Template filter that returns field widget class name (in lower case). E.g. if field's widget is TextInput then {{ field|widget_type }} will return 'textinput'. """ if hasattr(field, 'field') and hasattr(field.field, 'widget') and field.field.widget: return fie...
bigcode/self-oss-instruct-sc2-concepts