seed
stringlengths
1
14k
source
stringclasses
2 values
def neurips2021_tex(*, family="serif"): """Fonts for Neurips 2021. LaTeX version.""" preamble = r"\renewcommand{\rmdefault}{ptm}\renewcommand{\sfdefault}{phv}" if family == "serif": return { "text.usetex": True, "font.family": "serif", "text.latex.preamble": pream...
bigcode/self-oss-instruct-sc2-concepts
def calculate_IoU(geom, match): """Calculate intersection-over-union scores for a pair of boxes""" intersection = geom.intersection(match).area union = geom.union(match).area iou = intersection/float(union) return iou
bigcode/self-oss-instruct-sc2-concepts
def powerset(lst): """returns the power set of the list - the set of all subsets of the list""" if lst == []: return [[]] #power set is a list of lists #this way is more efficent for getting the combinations of the characters in a list lose_it = powerset(lst[1:]) use_it = map(lambda subs...
bigcode/self-oss-instruct-sc2-concepts
import re def tokenize(text): """Parses a string into a list of semantic units (words) Args: text (str): The string that the function will tokenize. Returns: list: tokens parsed out by the mechanics of your choice """ tokens = re.sub('[^a-zA-Z 0-9]', '', text) tokens = t...
bigcode/self-oss-instruct-sc2-concepts
def iou_bbox(gt_box, pred_box): """ Method to calculate the Intersection over Union between two boxes """ inter_box_top_left = [max(gt_box[0], pred_box[0]), max(gt_box[1], pred_box[1])] inter_box_bottom_right = [min(gt_box[0] + gt_box[2], pred_box[0] + pred_box[2]), min...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import math def get_graph_dimen(fields: dict, uniq_cnt_threshold: int) -> Tuple[int,int]: """ Helper function to first figure out how many graphs we'll be displaying, and then based on that determine the appropriate row and column count for display """ graph_cnt = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def flatten(iterable): """Flatten a given nested iterable.""" return (x for e in iterable for x in e)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def date_from_string(indate): """ Returns a python datetime.date object from a string formatted as '2012-11-21' = 'yyyy-mm-dd' """ return datetime.strptime(indate, "%Y-%m-%d").date()
bigcode/self-oss-instruct-sc2-concepts
import torch import gc def torch_pca( X, device='cpu', mean_sub=True, zscore=False, rank=None, return_cpu=True, return_numpy=False): """ Principal Components Analysis for PyTorch. If using GPU, then call...
bigcode/self-oss-instruct-sc2-concepts
import pathlib import yaml def load_config_as_dict(path: pathlib.Path) -> dict: """ loads the ``yaml`` config file and returns a dictionary Args: path: path to json config file Returns: a nested object in which parameters are accessible using dot notations, for example ``config.model...
bigcode/self-oss-instruct-sc2-concepts
def insertion_sort(lst: list) -> list: """Sort a list in ascending order. The original list is mutated and returned. The sort is stable. Design idea: Iterate over the list. After i iterations, the first i elements of the list should be sorted. Insert the i+1'th element in the appropriate spot in th...
bigcode/self-oss-instruct-sc2-concepts
def create_ds_118(packer, filler1, filler2, filler3, brakectr, awdlckmax, awdlckmn, drvstate, drvtq, emergbrk, stoplmp, angle): """Creates a CAN message for the Ford 118 message.""" values = { "BrkCtrFnd_B_Stat": brakectr, "AwdLck_Tq_RqMx": awdlckmax, "AwdLck_Tq_RqMn": awdlckmn, "DrvSte_D_Stat": d...
bigcode/self-oss-instruct-sc2-concepts
def cipher(text, shift, encrypt=True): """ Encrypt and decrypt letter text by using the Caesar cipher. Parameters ---------- text : string A string only contains letters from alphabet shift : int A number that you wish to replace each original letter to the letter with that number o...
bigcode/self-oss-instruct-sc2-concepts
def load_image_mask_gt_eval(dataset, image_id): """Load and return ground truth data for an image, no processing. """ # Load image and mask image = dataset.load_image(image_id) point, class_ids, bbox, mask = dataset.load_mask(image_id) return image, class_ids, bbox, mask, point
bigcode/self-oss-instruct-sc2-concepts
def char_is_printable(char): """ Check if char is ascii number (<128) and printable """ if ord(char) >= 32 and ord(char) <= 126: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def _url_joiner(*args): """Helper: construct an url by joining sections with /""" return '/'.join(s.strip('/') for s in args)
bigcode/self-oss-instruct-sc2-concepts
import requests def query(uri): """ Fill in this method. Query the passed URI and return the text response. See https://2.python-requests.org/en/master/ """ response = requests.get(uri) return response.text
bigcode/self-oss-instruct-sc2-concepts
def to_int(value): """Returns the value as integer, or None if not integer.""" try: return int(value) except ValueError: return None
bigcode/self-oss-instruct-sc2-concepts
def calculateAverage(list): """ Calculate the average value from a list """ size = len(list) if size > 0: sum = 0 for i in range(0, size): sum += list[i] return sum / size return 0
bigcode/self-oss-instruct-sc2-concepts
def exclude_variants(pages): """Checks if page is not a variant :param pages: List of pages to check :type pages: list :return: List of pages that aren't variants :rtype: list """ return [page for page in pages if (hasattr(page, 'personalisation_metadata') is False) ...
bigcode/self-oss-instruct-sc2-concepts
def check_input_expression_characters(expression): """Check whether characters of an expression are all valid. :type expression: str :rtype : bool :param expression: The expression. :return: True if all characters are valid. """ # Construct valid characters. valid_char = "0123456789AB...
bigcode/self-oss-instruct-sc2-concepts
def new_incremented_param_name(basename, currnames, start=1): """ Generate new integer incremented version of the parameter name defined by `basename` based on a list of current names in `currnames`. :param basename: base name to increment :type basename: :py:str :param currnames: curr...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_ugrid_mesh_description(nc_file): """ Collect UGRID mesh description from mesh file and return a list of UGRID variables; only one mesh description is allowed """ # Look for UGRID mesh description dummy variable mesh_names = [] for var_name, var in nc_file.variables....
bigcode/self-oss-instruct-sc2-concepts
import socket def is_ipv6(addr): """Checks if a given address is an IPv6 address.""" try: socket.inet_pton(socket.AF_INET6, addr) return True except socket.error: return False
bigcode/self-oss-instruct-sc2-concepts
def create_schema(base, engine): """ Create database schema. """ base.metadata.create_all(engine) return engine
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def sort_dict(d): """ Helper function; returns a recursively sorted OrderedDict (by key). :param d: A dictionary to sort. :return: An OrderedDict. """ res = OrderedDict() for k, v in sorted(d.items()): if isinstance(v, dict): res[k] = sort...
bigcode/self-oss-instruct-sc2-concepts
def get_names_from_wordlist(filepath): """Read wordlist line by line and store each line as a list entry.""" with open(filepath) as f: content = f.readlines() # Remove whitespace characters like '\n' at the end of each line return [x.strip() for x in content]
bigcode/self-oss-instruct-sc2-concepts
def max_change_day(prices): """Returns the day (index) of the maximum single day change in price.""" diff_list = [] for x in range(len(prices)-1): diff_list += [prices[x+1] - prices[x]] maxindex = 0 maximum = diff_list[0] for x in range(len(diff_list)): if diff_list[x] ...
bigcode/self-oss-instruct-sc2-concepts
import json def json_extract(json_path): """Converts JSON file to Python Dict Args: json_path (str): Path to JSON file Returns: data (dict): Dictionary containing JSON information """ with open(json_path) as f: data = json.load(f) return data
bigcode/self-oss-instruct-sc2-concepts
import re def sorted_alphanumeric(l, reverse=False): """ Sorts the given iterable alphanumerically. If values are numeric, sort numerically; if strings, alphanumerically. If string operations don't work we just sort normally; this works for numeric types. """ try: convert = lambda ...
bigcode/self-oss-instruct-sc2-concepts
import math def get_two_point_dis(point1, point2): """ Args: point1 (list): point1 point2 (list): point2 Returns: int: Euclidean distance between point1 and point2 """ # calculate the euclidean distance dist = math.sqrt((point1[0] - point2[0]) * ...
bigcode/self-oss-instruct-sc2-concepts
import functools def product(iterable): """returns the product of the elements of the iterable""" return functools.reduce(lambda a, b: a * b, iterable, 1)
bigcode/self-oss-instruct-sc2-concepts
import collections def secs_to_text(cs): """Convert time in seconds to a human readable string. """ v = collections.OrderedDict() v['s'] = cs % 60 cs //= 60 v['m'] = cs % 60 cs //= 60 v['h'] = cs % 24 cs //= 24 v['d'] = cs parts = [] for k in v: if v[k] != 0: ...
bigcode/self-oss-instruct-sc2-concepts
def connections(activities): """Enumerates the connections within a list of activities. Args: activities: The activities to process. Parents/children outside these are ignored. Returns: A list of two-tuples. Each tuple is a (parent, child) relationship. """ acts = frozenset(activitie...
bigcode/self-oss-instruct-sc2-concepts
import glob import re def GetTtyDevices(tty_pattern, vendor_ids): """Finds all devices connected to tty that match a pattern and device id. If a serial device is connected to the computer via USB, this function will check all tty devices that match tty_pattern, and return the ones that have vendor identifica...
bigcode/self-oss-instruct-sc2-concepts
import torch def cross_squared_distance_matrix(x, y): """Pairwise squared distance between two (batch) matrices' rows (2nd dim). Computes the pairwise distances between rows of x and rows of y Args: x: [batch_size, n, d] float `Tensor` y: [batch_size, m, d] float `Tensor` ...
bigcode/self-oss-instruct-sc2-concepts
def cli_parse(parser): """Add method specific options to CLI parser. Parameters ---------- parser : argparse object Returns ---------- Updated argparse object """ parser.add_argument('-M', '--m-coef', type=int, required=False, default=4, help='M coefficient,...
bigcode/self-oss-instruct-sc2-concepts
def _getSubtitleNumber(entry): """ Helper function that returns the subtitle number of a TTI block. Used to sort a list of TTI blocks by subtitle number. """ return entry['SN']
bigcode/self-oss-instruct-sc2-concepts
def extract_amount(accident, base_key): """ Get the amound of wounded/dead people from the accident data. """ if not base_key in accident.keys(): return 0 else: if len(accident[base_key].keys()) == 2: return int(accident[base_key][f"{base_key}_min"]) else: ...
bigcode/self-oss-instruct-sc2-concepts
def write_bytes(fp, data): """ Write bytes to the file object and returns bytes written. :return: written byte size """ pos = fp.tell() fp.write(data) written = fp.tell() - pos assert written == len(data ), 'written=%d, expected=%d' % (written, len(data)) r...
bigcode/self-oss-instruct-sc2-concepts
def request_path(context): """Return request.path""" return context['request'].path
bigcode/self-oss-instruct-sc2-concepts
import inspect def keyword(name=None, tags=(), types=()): """Decorator to set custom name, tags and argument types to keywords. This decorator creates ``robot_name``, ``robot_tags`` and ``robot_types`` attributes on the decorated keyword function or method based on the provided arguments. Robot Frame...
bigcode/self-oss-instruct-sc2-concepts
import math def truncate_middle(content, max_length, middle="..."): """ Truncates the middle part of the string if the total length if too long. For example: truncate_middle('testabcdecho', 8) == 'tes...ho' :param content: The string that must be truncated. :type: str :param max_length: ...
bigcode/self-oss-instruct-sc2-concepts
def merge_jsons(jsons): """Merge JSONS returned from api.API.retrieve_pages. Args: jsons (list[dict]): Having the form: {"query": { "normalized": [ { "from": "", "to": "", }, ], "redirects": [ { "from": "", "to": "...
bigcode/self-oss-instruct-sc2-concepts
def truncate_description(desc: str) -> str: """Take the first line of a multiline description, truncated to 40 chars""" first_line = desc.strip().split("\n")[0] return first_line[:40]
bigcode/self-oss-instruct-sc2-concepts
import re def _check_separator(line, read_order): """Identify data separators, tabs or blanks """ temp = line.strip() lread = len(read_order) terms1 = re.split('\t', temp) # terms2 = re.split(' ', temp) if len(terms1) == lread: use_tabs = True print('Information: Reading ta...
bigcode/self-oss-instruct-sc2-concepts
def base_test_dir(tmp_path_factory): """Creates a temporary directory for the tests.""" return tmp_path_factory.mktemp("test_files")
bigcode/self-oss-instruct-sc2-concepts
def _user_can_administer(user, org): """ Whether this user can administer the given org """ return user.is_superuser or org.administrators.filter(pk=user.pk).exists()
bigcode/self-oss-instruct-sc2-concepts
def _get_element_type(tag): """This function extracts the type of tag specified in tag Args: tag (str or bytes): Full valid html tag from < to > Returns: str: type of HTML tag, e.g. div, p, meta, span, td, etc """ # decode tag parameter if its a bytes object tag = tag.decode() ...
bigcode/self-oss-instruct-sc2-concepts
import requests import json def query_vep(variants, search_distance): """Query VEP and return results in JSON format. Upstream/downstream genes are searched up to a given distance.""" ensembl_request_url = 'https://rest.ensembl.org/vep/human/region' headers = {'Content-Type': 'application/json', 'Accept':...
bigcode/self-oss-instruct-sc2-concepts
def to_none(field): """ Returns the value of None for input empty strings and empty lists. """ if field == '' or field == []: return None else: return field
bigcode/self-oss-instruct-sc2-concepts
def ReadFile(file_path): """Returns the content of |file_path|.""" with open(file_path) as f: content = f.read() return content
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Hashable from typing import List def _switch_keys_and_values( key_value: Dict[Hashable, int] ) -> Dict[int, List[Hashable]]: """ Returns dictionary with switched key-value arguments where new values (old keys) stored in the list. """ value_key = {} ...
bigcode/self-oss-instruct-sc2-concepts
def should_assume_role(role_arn): """ Handles the case when AWS_IAM_ROLE_ARN Codefresh input parameter is omitted, which will cause the role ARN to contain the literal string "${{AWS_IAM_ROLE_ARN}}". In this case, we do not want to assume role. """ if role_arn == '${{AWS_IAM_ROLE_ARN}}': ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path from typing import Any import pickle def read_pickle(path: Union[str, Path]) -> Any: """ Read a pickle file from path. Args: path: File path Returns: Unpickled object """ with open(path, "rb") as fp: return pickle.load...
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import OrderedDict def load_model(fname,model): """ Load saved model's parameter dictionary to initialized model. The function will remove any ``.module`` string from parameter's name. Parameters ---------- fname : :py:class:`str` Path to saved model model :...
bigcode/self-oss-instruct-sc2-concepts
import socket def unused_port(hostname): """Return a port that is unused on the current host.""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((hostname, 0)) port = s.getsockname()[1] s.close() return port
bigcode/self-oss-instruct-sc2-concepts
def get_values_as_int(history, key): """Retrieve values from sequence of dictionaries, convert all values to int.""" return [int(i[key]) for i in history]
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def empty_ref_tree(tmpdir): """Empty reference directory.""" tree = Path(tmpdir) / "ref" tree.mkdir() return tree
bigcode/self-oss-instruct-sc2-concepts
import random def split_cases(cases, part=0.5): """Randomly split a list into two parts. part is a float between 0 and 1, indicating the relative size of the first part. """ cases = cases.copy() random.shuffle(cases) idx = int(len(cases) * part) return cases[:idx], cases[idx:]
bigcode/self-oss-instruct-sc2-concepts
def _make_signal_unique(signal_name: str, db: dict) -> str: """ Preserve duplicated signal in WaveDrom format by adding extra space that will be removed later on. Add as many spaces it is required to make the identifier unique. """ new_name = signal_name while new_name in db: new_nam...
bigcode/self-oss-instruct-sc2-concepts
def get_annot_reviewed_matching_aids(ibs, aid_list, eager=True, nInput=None): """ Returns a list of the aids that were reviewed as candidate matches to the input aid """ ANNOT_ROWID1 = 'annot_rowid1' ANNOT_ROWID2 = 'annot_rowid2' params_iter = [(aid,) for aid in aid_list] colnames = (ANNOT_R...
bigcode/self-oss-instruct-sc2-concepts
def never_swap(doors, past_selections): """ Strategy that never swaps when given a chance. """ return past_selections[-1]
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Set def get_unique_affected_entity_ids(security_problems: List[Dict]) -> Set[str]: """Extract all unique affected entity IDs from a list of security problems. :param security_problems: the security problems, parsed from JSON to Dicts of Dicts ...
bigcode/self-oss-instruct-sc2-concepts
import re def get_anchor_format(a): """Extract the resource file-type format from the anchor""" # (. or format=) then (file_extension) then (? or $) # e.g. "...format=txt" or "...download.mp4?..." file_format = re.search("(?:\.|format=)(\w+)(?:\?.*)?$", a) return file_format.group(1) if file_forma...
bigcode/self-oss-instruct-sc2-concepts
import copy def convert_to_binary_cols(df, col, vals, targ_vals): """ convert_to_binary_cols(df, col, vals, targ_vals) Returns the input dataframe with the column values converted to categorical binary columns. The original column is dropped. Required args: - df (pd DataFrame): dataframe...
bigcode/self-oss-instruct-sc2-concepts
def compute_avg_cosine(similarity_result, topn): """ Compute and return the average cosine similarities. Args ---- similarity_result (list): List of word:cosine similarity dict pairs. Return: avg_cosine (float): Computed average cosine similarity """ if len(similarity_result) >=...
bigcode/self-oss-instruct-sc2-concepts
def default_preprocessing(df): """Replace Attrition Yes/No with 1/0""" status_map = {'No': 1, 'Yes': 0} df['Attrition'] = df['Attrition'].replace(status_map) return df
bigcode/self-oss-instruct-sc2-concepts
def valid(board, val, pos): """Checks if value is valid to be entered in the cell or not params : val : int pos : tuple (cell cordinates) returns : boolean """ # Check row for i in range(len(board[0])): if board[pos[0]][i] == val and pos[1] != i: return False # C...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def convert_records_to_dict(records: List[tuple]) -> dict: """Converts pyscopg2 records list to a dict.""" dict = {} for record in records: # Add record tuple data to dict. dict[record[0]] = record[1] return dict
bigcode/self-oss-instruct-sc2-concepts
def is_key(obj): """Return True if object is most likely a key.""" if obj is not None and isinstance(obj, str): return "'" in obj
bigcode/self-oss-instruct-sc2-concepts
def cmd( admin_only=False, acl="*", aliases=None, while_ignored=False, reply_in_thread=False, reply_broadcast=False, parse=None, strip_formatting=False, *args, **kwargs ): """ Decorator to mark plugin functions as commands in the form of !<cmd_name> * admin_only - in...
bigcode/self-oss-instruct-sc2-concepts
def until(n, filter_func, v): """Build a list: list( filter( filter_func, range(n) ) ) >>> list( filter( lambda x: x%3==0 or x%5==0, range(10) ) ) [0, 3, 5, 6, 9] >>> until(10, lambda x: x%3==0 or x%5==0, 0) [0, 3, 5, 6, 9] """ if v == n: return [] if filter_func(v): ret...
bigcode/self-oss-instruct-sc2-concepts
def matrix_to_text(mat): """ Convert matrix array to text using spaces/newlines as col/row delimiters """ rows = [] for row in mat: rows.append(" ".join([str(v) for v in row])) return "\n".join(rows)
bigcode/self-oss-instruct-sc2-concepts
def clean_data(df): """ Function to load the data sets and clean the data (so as to give column names corresponding to the different categories). Args: The merged dataframe containing the messages and the categories Returns: Dataframe that has the messages and one column for each...
bigcode/self-oss-instruct-sc2-concepts
def drelu(x): """ dReLu(x) = 1 if (x>0), 0 otherwise """ return (x > 0).float()
bigcode/self-oss-instruct-sc2-concepts
import random def add_parameter_noise(cfg, noise_ratio): """ Add noise to the hyperparameters of the Dynamic DropConnect model. This changes the input dictionary in-place. Args: cfg: Dictionary containing the configuration with all hyperparameters noise_ratio: Ratio of noise relative ...
bigcode/self-oss-instruct-sc2-concepts
import re def get_currents( content ): """ Gets the currents from an Igor file :param content: The content to search :returns: A numpy array of the currents """ j_search = 'WAVES\s*PhotoCurrent1\nBEGIN\n(.*)\nEND' match = re.search( j_search, content, flags = ( re.IGNORECASE | re.DOTALL )...
bigcode/self-oss-instruct-sc2-concepts
def _include_file_data(login, record): """Ensure that 'files' field is present in the input record""" if 'files' not in record: if 'files' in record.get('links', {}): url = record['links']['files'] elif 'id' in record: url = login.base_url + 'api/deposit/depositions/{0}/f...
bigcode/self-oss-instruct-sc2-concepts
def get_n_beads(n, i1 ,i2): """ given length of the ring polymer (n) and the starting-ending positions (i1, i2) returns the length of the segment of the smaller length :param n: number of elements :type n: int :param i1: starting position :type i1: int :param i2: ending position :ty...
bigcode/self-oss-instruct-sc2-concepts
def variation_length(lastz_cig): """Determines how long the mapping is (sum of insertion/deletion/match), based on the lastz cig. Args: lastz_cig (string): a lastz cigar, e.g. "M50D3I5M30" Returns: int: sum of I+D+M in cigar. """ # Parsing cigars: # indices 0, 2, 4,... are ...
bigcode/self-oss-instruct-sc2-concepts
def next_indentation(line, tab_length): """Given a code line, return the indentation of the next line.""" line = line.expandtabs(tab_length) indentation = (len(line) - len(line.lstrip(" "))) // tab_length if line.rstrip().endswith(":"): indentation += 1 elif indentation >= 1: if line...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def normalize_entity(in_dict): """Converts BlitzDB Document to standard dictionary Parameters ---------- in_dict : dict BlitzDB Document-compatible dictionary of values Returns ------- dict normal dictionary of values, output of to_dictionary...
bigcode/self-oss-instruct-sc2-concepts
def formatDuration(context, totminutes): """ Format a time period in a usable manner: eg. 3h24m """ mins = totminutes % 60 hours = (totminutes - mins) / 60 if mins: mins_str = '%sm' % mins else: mins_str = '' if hours: hours_str = '%sh' % hours else: hou...
bigcode/self-oss-instruct-sc2-concepts
def findpop(value, lst): """ Return whether `value` is in `lst` and remove all its occurrences """ if value in lst: while True: # remove all instances `value` from lst try: lst.pop(lst.index(value)) except ValueError: break return True # ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def health() -> Any: """Returns an ok status for uptime monitoring purposes""" return {"status": "ok"}
bigcode/self-oss-instruct-sc2-concepts
def replace_full_stop(string: str) -> str: """ Replace full width full stop character with Japanese dot character. :param string: String to be processed :type string: str :return: Result string :rtype: str **Example:** .. code-block:: python string = "Hello.World" res...
bigcode/self-oss-instruct-sc2-concepts
import math def haversine(coord1, coord2): """use the Haversine function to determine the distance between two points in the WGS84 coordinate system. Returns the distance between the two points in meters. Source: https://janakiev.com/blog/gps-points-distance-python/ coord1: (lat, lon) coord...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def paths(base, network): """ Get the paths for the network directory, the wallet database file, and the blockchain database file. """ netDir = Path(base) / network dbPath = netDir / "wallet.db" dcrPath = netDir / "dcr.db" return netDir, dbPath, dcrPath
bigcode/self-oss-instruct-sc2-concepts
def _detect_cycles(node, graph, visited, ps_stack): """ Perform DFS on PricingServices dependecy graph looking for cycles Params: node: PricingService graph: dict with adjacency list of PricingServices visited: set of already visited PricingServices during graph traversal ps...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def u(x: Any) -> str: """Convert x to string.""" if isinstance(x, str): return x return str(x)
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional def task_list(items: List[str], items_to_check: Optional[List[int]] = None) -> str: """Creates a task list in GitHub Flavored Markdown where each item can be checked off. This task list cannot be used inside a table. :param items: The items in the task ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def _get_data_and_md5_bulk(container, obj_hashkeys): """Get the MD5 of the data stored under the given container as a single bulk operation. :param container: a Container :param obj_hashkeys: a list of object hash keys :return: a dictionary where the keys are the object hash keys and t...
bigcode/self-oss-instruct-sc2-concepts
def events_event_id_delete(event_id: str): """Deletes an event.""" return '', 204
bigcode/self-oss-instruct-sc2-concepts
def is_palindrome(n): """ Fill in the blanks '_____' to check if a number is a palindrome. >>> is_palindrome(12321) True >>> is_palindrome(42) False >>> is_palindrome(2015) False >>> is_palindrome(55) True """ x, y = n, 0 f = lambda: y * 10 + x % 10 while x >...
bigcode/self-oss-instruct-sc2-concepts
def perm_to_string(p): """ Convert p to string, slightly more compact than listprinting. """ s = "(" for x in p: s = s + "%2d "%x s += ")" return s
bigcode/self-oss-instruct-sc2-concepts
import re def xisabs(filename): """ Cross-platform version of `os.path.isabs()` Returns True if `filename` is absolute on Linux, OS X or Windows. """ if filename.startswith('/'): # Linux/Unix return True elif filename.startswith('\\'): # Windows return True elif re.match(r'\w:[\\/]'...
bigcode/self-oss-instruct-sc2-concepts
def hot_cold_process( curr_yr, p_cold_rolling_steel, assumptions ): """Calculate factor based on the fraction of hot and cold rolling processes in steel manufacturing. The fraction of either process is calculated based on the scenario input of the future share of cold rolllin...
bigcode/self-oss-instruct-sc2-concepts
def mcari(b3, b4, b5): """ Modified Chlorophyll Absorption in Reflectance Index \ (Daughtry et al. 2000). .. math:: MCARI = ((b5 - b4) - 0.2 * (b5 - b3)) * (b5 / b4) :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-e...
bigcode/self-oss-instruct-sc2-concepts
def get_object_or_none(model_class, name): """ Returns the object or None. """ try: return model_class.objects.get(name=name) except model_class.DoesNotExist: return None
bigcode/self-oss-instruct-sc2-concepts