seed
stringlengths
1
14k
source
stringclasses
2 values
def _mid(pt1, pt2): """ (Point, Point) -> Point Return the point that lies in between the two input points. """ (x0, y0), (x1, y1) = pt1, pt2 return 0.5 * (x0 + x1), 0.5 * (y0 + y1)
bigcode/self-oss-instruct-sc2-concepts
import glob def get_num_files(start_year, end_year, perf_dir): """ Get number of files to read given start_year end_year and path to performance files """ count = 0 for year in range(start_year, end_year + 1): count += len(glob.glob(perf_dir + f"/*{year}*")) return count
bigcode/self-oss-instruct-sc2-concepts
def _CountChar(line, opening_char, closing_char): """Count (number of opening_char) - (number of closing_char) in |line|. Used to check for the end of JSON parameters. Ignores characters inside of non-escaped quotes. Args: line: line to count characters in opening_char: "+1" character, { or [ clos...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def find_indexes(haystack: List[str], regex: str) -> List[int]: """ Find indexes in a list where a regular expression matches. Parameters ---------- haystack List of strings. regex Regular expression to match. Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def optimize(gan, ddgan): """ Create optimizer Args: gan (GAN): The GAN to optimize ddgan (Module): The ddgan module Returns: Optimizer: The optimizer """ kwargs_opt = { "start_from": 0, "nPOD": 10, "nLatent": 100, "npredictions": 2, ...
bigcode/self-oss-instruct-sc2-concepts
def _batch_updates(updates): """Takes a list of updates of form [(token, row)] and sets the token to None for all rows where the next row has the same token. This is used to implement batching. For example: [(1, _), (1, _), (2, _), (3, _), (3, _)] becomes: [(None, _), (1, _), (2,...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_best_non_unk_predictions(logits: torch.Tensor, unk_id): """ For every sample, returns the prediction with the highest score. If this is the <unk> token, then the prediction with the second highest score will be returned instead :param logits: batch_size x num_predict x num_subtoke...
bigcode/self-oss-instruct-sc2-concepts
def tf(words) -> float: """Boolean term frequency, weighted over the document's word count.""" return 1/len(words)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def knapsack_no_value(target: int, objects: List[int], cur: int) -> bool: """ we should assume objects are in heavy to light order :param target: the target weight, or the capacity of the knapsack :param objects: all available weights for items :param cur: current index in...
bigcode/self-oss-instruct-sc2-concepts
def nested_getattr(obj, attr): """getattr implementation supporting nested attributes.""" attributes = attr.split('.') for i in attributes: if obj is None: break try: obj = getattr(obj, i) except AttributeError: raise return obj
bigcode/self-oss-instruct-sc2-concepts
def ndependents(dependencies, dependents): """ Number of total data elements that depend on key For each key we return the number of data that can only be run after this key is run. The root nodes have value 1 while deep child nodes will have larger values. Examples -------- >>> dsk = {'...
bigcode/self-oss-instruct-sc2-concepts
def unique_values_from_query(query_result): """Simplify Athena query results into a set of values. Useful for listing tables, partitions, databases, enable_metrics Args: query_result (dict): The result of run_athena_query Returns: set: Unique values from the query result """ r...
bigcode/self-oss-instruct-sc2-concepts
def create_dockerfile(ctx): """ Creates a Dockerfile for this project. """ return ctx.obj['docker'].create_dockerfile( project=ctx.obj['project_name'] )
bigcode/self-oss-instruct-sc2-concepts
def find_name_from_len(lmin, lens): """ reverse lookup, get name from dict >>> lens = {'chr1': 4, 'chr2': 5, 'chr3': 4} >>> find_name_from_len(5, lens) 'chr2' """ for fname, l in lens.iteritems(): if l == lmin: return fname raise Exception('name not found')
bigcode/self-oss-instruct-sc2-concepts
def bits_to_byte(bits): """ Return int represented by bits, padded on right. @param str bits: a string representation of some bits @rtype: int >>> bits_to_byte("00000101") 5 >>> bits_to_byte("101") == 0b10100000 True """ return sum([int(bits[pos]) << (7 - pos) for p...
bigcode/self-oss-instruct-sc2-concepts
def remove_background(df): """ Helper function removing background flows from a given dataframe :param df: the dataframe :return: the no-background dataframe """ df = df[df['label'] != 'Background'] return df
bigcode/self-oss-instruct-sc2-concepts
def optimal_tilt(lat): """ Returns an optimal tilt angle for the given ``lat``, assuming that the panel is facing towards the equator, using a simple method from [1]. This method only works for latitudes between 0 and 50. For higher latitudes, a static 40 degree angle is returned. These result...
bigcode/self-oss-instruct-sc2-concepts
def for_language(cell, languages=set()): """Check if a given paragraph is in an expected language""" return cell.get("_lang") in languages
bigcode/self-oss-instruct-sc2-concepts
def to_binary(x): """Convert a binary field to 1's and 0's""" if x == None: return 0 else: return 1
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def bernstein3_d1(t: float) -> Sequence[float]: """ First derivative of Bernstein polynom of 3rd degree. """ t2 = t * t a = -3.0 * (1.0 - t) ** 2 b = 3.0 * (1.0 - 4.0 * t + 3.0 * t2) c = 3.0 * t * (2.0 - 3.0 * t) d = 3.0 * t2 return a, b, c, d
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def parse_tag_list(message: str, tag: str, allowed_chars: str) -> List[str]: """Parses a comma separated list following a tag. Example: The function call parse_tag_list('abc IMPORTS=foo,bar abc', 'IMPORTS', 'a-z') returns ['foo', 'bar']. Args...
bigcode/self-oss-instruct-sc2-concepts
def upload_dup_file(rest_obj, module): """Upload DUP file to OME and get a file token.""" upload_uri = "UpdateService/Actions/UpdateService.UploadFile" headers = {"Content-Type": "application/octet-stream", "Accept": "application/octet-stream"} upload_success, token = False, None dup_...
bigcode/self-oss-instruct-sc2-concepts
def rename_uuid_columns(data): """Renames any columns called or containing `uuid`, to the convention of `id`. Args: data (:obj:`pandas.Dataframe`): dataframe with column names to amend Returns: (:obj:`pandas.Dataframe`): the original dataframe with amended column names """ renames ...
bigcode/self-oss-instruct-sc2-concepts
def _remove_none(**kwargs): """Drop optional (None) arguments.""" return {k: v for k, v in kwargs.items() if v is not None}
bigcode/self-oss-instruct-sc2-concepts
def get_straights(edge): """ Get vectors representing straight edges """ return [v for v in edge if v[0] == 0 or v[1] == 0]
bigcode/self-oss-instruct-sc2-concepts
def clean_img_attributes(page): """ Remove image alt and data-mathml attributes because they confuse html2text. """ imgs = page.find_all('img') for img in imgs: img['alt'] = '' img['data-mathml'] = '' return page
bigcode/self-oss-instruct-sc2-concepts
import math def cal_line_length(point1, point2): """Calculate the length of line. Args: point1 (List): [x,y] point2 (List): [x,y] Returns: length (float) """ return math.sqrt( math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2))
bigcode/self-oss-instruct-sc2-concepts
import textwrap def reindent(text, indentation): """Return reindented text that matches indentation.""" if '\t' not in indentation: text = text.expandtabs() text = textwrap.dedent(text) return '\n'.join( [(indentation + line).rstrip() for line in text.splitlines()]).rstrip()...
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_yaml_config(yaml_path): """Helper function to load a yaml config file""" with open(yaml_path, "r") as stream: try: return yaml.safe_load(stream) except yaml.YAMLError as exc: raise ValueError("Yaml error - check yaml file")
bigcode/self-oss-instruct-sc2-concepts
def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]: """ Extended Euclidean Algorithm. Finds 2 numbers a and b such that it satisfies the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) >>> extended_euclidean_algorithm(1, 24) (1, 0) >>> extended_euclidean_algorithm(...
bigcode/self-oss-instruct-sc2-concepts
import json def load_from_json(file_path): """ Loading data from a json file. Input: file_path: (the source file) Output: data: the loaded data """ # catching possible pathlib.Path object if isinstance(file_path, str) is False: file_path = str(file_path) # c...
bigcode/self-oss-instruct-sc2-concepts
def get_mean_value(predicted_values): """ Method for calculate mean prediction value by all predicted value :param predicted_values: all predicted values :type predicted_values: list :return: mean prediction value :rtype: float """ if len(predicted_values) == 0: return None ...
bigcode/self-oss-instruct-sc2-concepts
def crop_center(img, crop_x, crop_y): """ Crops image from center to new size Args: img: input image width: width of cropped image height: height of cropped image Returns: Cropped image """ height, width = img.shape startx = width // 2 - (crop_y // 2) st...
bigcode/self-oss-instruct-sc2-concepts
import uuid def generate_id() -> str: """ Create a unique ID. This is passed in each message, and used to match requests to responses. """ return uuid.uuid4().hex
bigcode/self-oss-instruct-sc2-concepts
def xstr(s): """return empty string if input is none/false""" return '' if not s else s
bigcode/self-oss-instruct-sc2-concepts
def get_column(wks, row, col, number): """Get column with starting row and column, and then going down `number` rows.""" return list(map(lambda x: x.value, wks.range(row, col, number+row-1, col)))
bigcode/self-oss-instruct-sc2-concepts
def not_empty(x): """Check if a collection is not empty or object is not None""" if hasattr(x, '__len__'): return len(x) > 0 return x is not None
bigcode/self-oss-instruct-sc2-concepts
import time def get_object_paths(s3, bucket, prefix): """List objects in S3 bucket with given prefix. Uses paginator to ensure a complete list of object paths is returned. """ # r1 = s3.list_objects(Bucket=DEND_BUCKET, Prefix=prefix) # r2 = list(map(lambda obj: obj['Key'], r1['Contents'])) # r...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json(json_path): """Read json file.""" with open(json_path, "r") as f: meta = json.load(f) return meta
bigcode/self-oss-instruct-sc2-concepts
def keymap(fn, d): """ Apply function to keys of dictionary >>> bills = {"Alice": [20, 15, 30], "Bob": [10, 35]} >>> keymap(str.lower, bills) # doctest: +SKIP {'alice': [20, 15, 30], 'bob': [10, 35]} See Also: valmap """ return dict(zip(map(fn, d.keys()), d.values()))
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Optional from typing import Tuple import multiprocessing def start_process( target: Callable, args: Optional[Tuple] = None ) -> multiprocessing.Process: """Start a process from with the multiprocessing framework. Parameters ---------- target: callabl...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha256(_input: str): """ Creates a sha256 hash from the input Args: _input (str): A string Returns: A sha256 hash string """ m = hashlib.sha256() m.update(_input.encode("UTF-8")) return m.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
import json def build_search_body(event): """Extract owners and filters from event.""" owners = json.loads(event["Owners"]) filters = json.loads(event["Filters"]) return {"Owners": owners, "Filters": filters}
bigcode/self-oss-instruct-sc2-concepts
import traceback def read_txt(*, file_path: str) -> str: """ Read specified file's text. Parameters ---------- file_path : str File path to read. Returns ------- txt : str Target file's text. """ with open(file_path, 'r', encoding='utf-8') as f: try: ...
bigcode/self-oss-instruct-sc2-concepts
def _get_interior_years(from_year, to_year, start_year, end_year): """Return the Rule years that overlap with the Match[start_year, end_year]. """ years = [] for year in range(start_year, end_year + 1): if from_year <= year and year <= to_year: years.append(year) return years
bigcode/self-oss-instruct-sc2-concepts
def get_show(name, cursor): """returns None if TV series name does not exists in database Args: name: name of TV series cursor: cursor object """ sql = "select id from tvshow where name = %s" cursor.execute(sql, (name,)) result = cursor.fetchone() if result == None: return None else: return result[0]
bigcode/self-oss-instruct-sc2-concepts
def distribute_indices_base(indices, nprocs, rank, allow_split_comm=True): """ Partition an array of "indices" evenly among a given number of "processors" This function is similar to :func:`distribute_indices`, but allows for more a more generalized notion of what a "processor" is, since the number of ...
bigcode/self-oss-instruct-sc2-concepts
def blend_union(da, db, r): """ Blend union of the distances da, db with blend radius r. """ e = max(r - abs(da - db), 0) return min(da, db) - e * e * 0.25 / r
bigcode/self-oss-instruct-sc2-concepts
def get_subplot_rows_columns_figsize(number_subplots): """Get the size of a sub plot in (rows, columns), based on the number of subplots that are going to be plotted. Parameters ----------- number_subplots : int The number of subplots that are to be plotted in the figure. """ if number_...
bigcode/self-oss-instruct-sc2-concepts
def combsort(array, scaling_factor): """ combsort(array, scaling_factor) -> list array -> [list]: A list of elements to be sorted using combsort scaling_factor -> [float]: A scalar that reduces the size of the gap every sweep (>1) """ steps = 0 gap = len(array) while ...
bigcode/self-oss-instruct-sc2-concepts
def is_palindrome(n): """ Returns true/false if a number (or string) is a palindrome """ string = str(n) reversed_string = str(n)[::-1] length = len(string) for position in range(length): if string[position] != reversed_string[position]: return False return Tr...
bigcode/self-oss-instruct-sc2-concepts
import re def modify_vars(vars_orig, var_modifiers): """Return a copy of `vars_orig` modified according to `var_modifiers`. Parameters ---------- vars_orig : list of str A list of variable names. var_modifiers : list of str or None, optional A list of variable modifiers. Each vari...
bigcode/self-oss-instruct-sc2-concepts
def ck_cmd( msg, cmd ): """Checks if the first n characters of msg contain cmd. Should not contain the bot prefix when passed in. msg: String to search in.. cmd: String to search for.""" return cmd in msg[0:len(cmd)]
bigcode/self-oss-instruct-sc2-concepts
def line_format(label): """ Convert time label to the format of pandas line plot """ month = label.month_name()[:3] if month == 'Jan': month += f'\n{label.year}' return month
bigcode/self-oss-instruct-sc2-concepts
import json def format_response(output_format, response): """Format the API response to the desired output format""" if not response.content: formatted = '' elif output_format == 'json': formatted = json.dumps(response.json()) elif output_format == 'pprint': formatted = json.du...
bigcode/self-oss-instruct-sc2-concepts
def websocketize(value): """Convert a HTTP(S) URL into a WS(S) URL.""" if not (value.startswith('http://') or value.startswith('https://')): raise ValueError('cannot websocketize non-HTTP URL') return 'ws' + value[len('http'):]
bigcode/self-oss-instruct-sc2-concepts
def gradient_descent_momentum(grads, velocity, var_list, lr, mom): """Gradient descent with momentum update. Args: grads: List of gradients of the trainable variables. velocity: List of velocity of the trainable variables. var_list: List of variables to be optimized. lr: Learnin...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def find_duplicate_movies(filename: str) -> List[str]: """ Finds the duplicate movie titles from the given file. :param filename: str :return: list[str] """ with open(filename) as f: movies = f.readlines() seen = set() duplicates = [] for movie in m...
bigcode/self-oss-instruct-sc2-concepts
import torch def energy(x: torch.Tensor, sps: float = 1.0): """Calculate the average energy (per symbol if provided) for each example. This function assumes that the signal is structured as: .. math:: Batch x Channel x IQ x Time. Args: x (torch.Tensor): Input Tensor (BxCxIQxT) ...
bigcode/self-oss-instruct-sc2-concepts
def get_primary_uri_field(fields): """Find the first field name containing URI""" for f in fields: if "URI" in f.field_name: return f return None
bigcode/self-oss-instruct-sc2-concepts
def make_iterable(obj): """Get a iterable obj.""" if isinstance(obj, (tuple, list)): return obj return obj,
bigcode/self-oss-instruct-sc2-concepts
def w020_from_defocus(radius, zi, deltaZ, wavelen=1.0): """Return the maximum wavefront error corresponding to defocus amount `deltaZ` Parameters ---------- radius : float The radius of the aperture in units of length (usually mm) zi : float Image distance (or the distance of th...
bigcode/self-oss-instruct-sc2-concepts
def corrected_proj_param(big_H, lil_h, R): """ Eq. 4.11 Calculates the corrected projection parameter for a cloud target Parameters ------------ big_H : int Satellite's height above the Earth's surface, in km lil_h : int Cloud's altitude above the Earth's surface, in km ...
bigcode/self-oss-instruct-sc2-concepts
def get_captcha_image_element(form): """ Return the <img> element in an lxml form that contains the CAPTCHA. NOTE: This assumes the first image in the form is the CAPTCHA image. If a form has multiple images, maybe use the etree .sourceline attribute to figure out which image is closer to the CAPTC...
bigcode/self-oss-instruct-sc2-concepts
def floor_div(arr, val): """ Floor division of array by value. """ return [i // val for i in arr]
bigcode/self-oss-instruct-sc2-concepts
def keep_never_expires(flags): """Filter flags to contain only flags that never expire. >>> keep_never_expires([{'expiry_milestone': -1}, {'expiry_milestone': 2}]) [{'expiry_milestone': -1}] """ return [f for f in flags if f['expiry_milestone'] == -1]
bigcode/self-oss-instruct-sc2-concepts
def rk4_step(u, f, dt, *args): """Returns the solution at the next time-step using the RK4 method. Assumes that f is time independent Parameters ---------- u : array of floats solution at the current time-step. f : function function to compute the right hand-side of the sys...
bigcode/self-oss-instruct-sc2-concepts
def is_pr_comment(event): """Determine if a comment applies to a pull request.""" try: right_type = event.type == 'IssueCommentEvent' right_payload = 'pull_request' in event.payload['issue'].to_json() return right_type and right_payload except (KeyError, IndexError, AttributeError, T...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_password(password, salt): """ Securely hash a password using a provided salt :param password: :param salt: :return: Hex encoded SHA512 hash of provided password """ password = str(password).encode("utf-8") salt = str(salt).encode("utf-8") return hashlib.sha5...
bigcode/self-oss-instruct-sc2-concepts
def frange(start, end, n): """frange(start, end, n): Python's range(), for floats and complexes.""" # If the arguments are already float or complex, this won't hurt. # If they're int, they will become float. start *= 1.0 end *= 1.0 step = (end - start) / n list = [] current = start for k in range(0, n): ...
bigcode/self-oss-instruct-sc2-concepts
def matchStrengthNoNoise(x, y, n): """Compute the match strength for the individual *x* on the string *y* excluding noise *n*. """ return sum(xi == yi for xi, yi, ni in zip(x, y, n) if ni != "#")
bigcode/self-oss-instruct-sc2-concepts
def gap_detector(data, mask, start_pixel, width_gap): """ Reproduce a detector gap in reciprocal space data and mask. :param data: the 3D reciprocal space data :param mask: the corresponding 3D mask :param start_pixel: pixel number where the gap starts :param width_gap: width of the gap in pixe...
bigcode/self-oss-instruct-sc2-concepts
def is_reserved_node(node): """ Return true if the node is reserved. """ reserved_title = node.title and '[Reserved]' in node.title reserved_text = node.text and '[Reserved]' in node.text return reserved_title or reserved_text
bigcode/self-oss-instruct-sc2-concepts
def third_measurer_I_P(uniqueTuplesDf): """ third_measurer_I_P: computes the measure I_P that counts the number of problematic tuples (tuples participating in a violation of the constraints). Parameters ---------- uniqueTuplesDf : dataframe the result of the query that finds all tu...
bigcode/self-oss-instruct-sc2-concepts
def key_to_option(key): """Convert a dictionary key to a valid command line option. This simply replaces underscores with dashes. """ return key.replace('_', '-')
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Any import json import logging def load_json(s: Union[str, bytes]) -> Any: """ Like json.loads() but prints the input if parsing fails """ try: return json.loads(s) except json.decoder.JSONDecodeError: sep = "----------------" log...
bigcode/self-oss-instruct-sc2-concepts
def nlopt_status(constant): """ Convert the enumerated constant returned by the optimization process into a human-readable string. Input ----- constant : ``int`` The constant returned by the optimization algorithm as result. Returns ------- status : ``str`` A human-read...
bigcode/self-oss-instruct-sc2-concepts
def render_no_change(text): """Render inline markdown text with no changes """ return [text]
bigcode/self-oss-instruct-sc2-concepts
def join(separator: str, separated: list) -> str: """ >>> join("", ["a", "b", "c", "d"]) 'abcd' >>> join("#", ["a", "b", "c", "d"]) 'a#b#c#d' >>> join("#", "a") 'a' >>> join(" ", ["You", "are", "amazing!"]) 'You are amazing!' >>> join("#", ["a", "b", "c", 1]) Traceback (most ...
bigcode/self-oss-instruct-sc2-concepts
def update(event, context): """Noop.""" return event["PhysicalResourceId"], {}
bigcode/self-oss-instruct-sc2-concepts
def _get_opt_attr(obj, attr_path): """Returns the value at attr_path on the given object if it is set.""" attr_path = attr_path.split(".") for a in attr_path: if not obj or not hasattr(obj, a): return None obj = getattr(obj, a) return obj
bigcode/self-oss-instruct-sc2-concepts
import random def randomized_primality_test(n, k): """ Checks if n is a prime number using probabilitic methods. In particular, this function uses Fermat's primality test. See http://en.wikipedia.org/wiki/Fermat_primality_test for a description of the method. Args: n: int, number to test...
bigcode/self-oss-instruct-sc2-concepts
import math def sqrt(x): """Returns square root of x value""" return math.sqrt(x)
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_synthetic(name, datadir): """ Loads data from pickle file with the given name (produced by save_synthetic function) :param name: name of the pickle file in datadir containing the expression data :return: np.array of expression with Shape=(nb_samples, nb_genes) and list of gene s...
bigcode/self-oss-instruct-sc2-concepts
def net_addr(addr): """Get network address prefix and length from a given address.""" if addr is None: return (None, None) nw_addr, nw_len = addr.split('/') nw_len = int(nw_len) return nw_addr, nw_len
bigcode/self-oss-instruct-sc2-concepts
def kw_bigram_score(concept, segment): """ Rank the segment using the key word search algorithm :param segment (list): a list of the tokens in the segment :param concept (str): the concept :return: a numeric score of the number of occurences of the concept word normalized by document length """ ...
bigcode/self-oss-instruct-sc2-concepts
def even_or_odd(number): """Return 'Even' or 'Odd' if number is even or odd.""" if number % 2 == 0: return "Even" return "Odd"
bigcode/self-oss-instruct-sc2-concepts
def _winpath_to_uri(path): """Converts a window absolute path to a file: URL.""" return "///" + path.replace("\\", "/")
bigcode/self-oss-instruct-sc2-concepts
def get_gq(df): """ Calculate GQ """ pl_arr = df[['PL_ref', 'PL_het', 'PL_hom']].values pl_arr.sort(axis=1) gq = [(row[1] - row[0]) for row in pl_arr] return gq
bigcode/self-oss-instruct-sc2-concepts
def binary_search(sorted_arr, wanted_num): """ Szuka elementu w posortwanej tablicy, jeżeli znajdzie to zwraca indeks szukanego elementu. W przypadku nie znalezienia elemetu zwraca -1.""" left = 0 right = len(sorted_arr) - 1 mid = 0 while left <= right: mid = (right + left) // 2 if ...
bigcode/self-oss-instruct-sc2-concepts
def check_for_period(message): """Check that there is no period in the end of the subject line.""" splitted = message.splitlines() check = not splitted[0].endswith(".") return check
bigcode/self-oss-instruct-sc2-concepts
def str2bool(val): """ Convert the strings "True" and "False" to the booleans True and False. """ if val == "True": return True elif val == "False": return False else: raise Exception("unknown string for bool '%s'" % val)
bigcode/self-oss-instruct-sc2-concepts
def GetTokensInSubRange(tokens, start, end): """Get a subset of tokens within the range [start, end).""" tokens_in_range = [] for tok in tokens: tok_range = (tok.lineno, tok.column) if tok_range >= start and tok_range < end: tokens_in_range.append(tok) return tokens_in_range
bigcode/self-oss-instruct-sc2-concepts
def metadata_filter_as_dict(metadata_config): """Return the metadata filter represented as either None (no filter), or a dictionary with at most two keys: 'additional' and 'excluded', which contain either a list of metadata names, or the string 'all'""" if metadata_config is None: return {} ...
bigcode/self-oss-instruct-sc2-concepts
def unpad(text): """ Unpads the text from the given block size. :param text | <str> :return <str> """ return text[0:-ord(text[-1])]
bigcode/self-oss-instruct-sc2-concepts
def get_reverted_disk_rses_id_name_map(disk_rses_id_name_map): """Revert k:v to v:k""" return {v: k for k, v in disk_rses_id_name_map.items()}
bigcode/self-oss-instruct-sc2-concepts
def print_name(name, word_count_threshold=7, break_point_ratio=0.6): """Splits name of item in legend into 2 lines if word count exceeds threshold""" words = name.split(" ") word_count = len(words) if word_count > word_count_threshold: position = round(word_count*break_point_ratio) ...
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def netmask_to_prefixlen(netmask: str) -> int: """ Takes an IP netmask and returns the corresponding prefix length :param str netmask: IP netmask (e.g. 255.255.0.0) :return: prefix length """ return ipaddress.ip_network('0.0.0.0/{}'.format(netmask)).prefixlen
bigcode/self-oss-instruct-sc2-concepts
def GetBuilderSuccessMap(builder_run, overall_success): """Get the pass/fail status of all builders. A builder is marked as passed if all of its steps ran all of the way to completion. We determine this by looking at whether all of the steps for all of the constituent boards ran to completion. In cases wher...
bigcode/self-oss-instruct-sc2-concepts
def find_versions(dependencies, heuristics): """ Try to find version information by calling a series of functions in turn. *dependencies*: a list of Dependency objects. *heuristics*: a list of functions that accept a component as the single argument and return a version number o...
bigcode/self-oss-instruct-sc2-concepts