seed
stringlengths
1
14k
source
stringclasses
2 values
def scale(val, minx, maxx, minscale, maxscale): """ Scales a value in one range to another. """ # https://stackoverflow.com/a/5295202 return (maxscale - minscale) * (val - minx) / maxx - minx + minscale
bigcode/self-oss-instruct-sc2-concepts
def gsutil_rm_rf_step(url): """Returns a GCB step to recursively delete the object with given GCS url.""" step = { 'name': 'gcr.io/cloud-builders/gsutil', 'entrypoint': 'sh', 'args': [ '-c', 'gsutil -m rm -rf %s || exit 0' % url, ], } return step
bigcode/self-oss-instruct-sc2-concepts
def find_disjoint_subsequences(li, seq): """ Returns a list of tuples (i,j,k,...) so that seq == (li[i], li[j], li[k],...) Greedily find first tuple, then second, etc. """ subseqs = [] cur_subseq_inds = [] for (i_el, el) in enumerate(li): if el == seq[len(cur_subseq_inds)]: ...
bigcode/self-oss-instruct-sc2-concepts
def average_named_tuple(named_tuple_): """Return an averaged named-tuple.""" return type(named_tuple_)(*map(lambda x: x.mean().item(), named_tuple_))
bigcode/self-oss-instruct-sc2-concepts
def is_counting_line_passed(point, counting_line, line_orientation): """ To check if the point passed the counting line by the x coord if it left/right or y coord if it bottom/top. :param point: the object location. :param counting_line: the coordinates list of the area. :param line_orientation: the...
bigcode/self-oss-instruct-sc2-concepts
def amin(a, axis=None, keepdims=False, initial=None, where=True): """ Returns the minimum of an array or minimum along an axis. Note: Numpy argument `out` is not supported. On GPU, the supported dtypes are np.float16, and np.float32. Args: a (Tensor): Input data. axis (...
bigcode/self-oss-instruct-sc2-concepts
def sortTable(tSkill): """ Sort tSkill by decreasing total damage """ # Order of the skills by decreasing total damage gDmgOrder = [ i[0] for i in sorted(enumerate([ float(t) for t in tSkill[2] ]), key = lambda x: x[1], reverse = True) ] for i in range(len(tSkill)): tSkill[i] = tSkill[i][gDm...
bigcode/self-oss-instruct-sc2-concepts
def siqs_choose_nf_m(d): """Choose parameters nf (sieve of factor base) and m (for sieving in [-m,m]. """ # Using similar parameters as msieve-1.52 if d <= 34: return 200, 272 if d <= 36: return 300, 546 if d <= 38: return 400, 1094 if d <= 40: return 500,...
bigcode/self-oss-instruct-sc2-concepts
def lookup_relevant(score): """Returns the string classifcation of the score""" category = "" if score > 2.0: category = "RELEVANT" elif score > 0.0: category = "PARTIALLY RELEVANT" else: category = "NOT RELEVANT" return category
bigcode/self-oss-instruct-sc2-concepts
def factorial(n): """ factorial: calculate factorial n! :param n: input number :return: n! """ fact=1 for i in range(1,n+1): fact*=i return fact
bigcode/self-oss-instruct-sc2-concepts
def object_id(identifier, keep_version=False) -> str: """ Returns the core object_id of a CURIE, with or without the version suffix. Note: not designed to be used with a URI (will give an invalid outcome) :param identifier: candidate CURIE identifier for processing :param keep_version: True if the ...
bigcode/self-oss-instruct-sc2-concepts
import re def get_text(file): """Read text from a file, normalizing whitespace and stripping HTML markup.""" _text = open(file).read() _text = re.sub(r'<.*?>', ' ', _text) _text = re.sub('\s+', ' ', _text) return _text
bigcode/self-oss-instruct-sc2-concepts
def listi(list_, elem, default=None): """ Return the elem component in a list of lists, or list of tuples, or list of dicts. If default is non-None then if the key is missing return that. Examples: l = [("A", "B"), ("C", "D")] listi(l, 1) == ["B", "D"] l = [{"A":1, "B":2}, {"A"...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def find_lines_from_points( p0: Tuple[float, float], p1: Tuple[float, float] ) -> Tuple[float, float]: """ Function calculating the line passing throught a pair of points. Args: p1 (Tuple[float, float]): First point. p2 (Tuple[float, float]): Second point....
bigcode/self-oss-instruct-sc2-concepts
def create_filename(file_name: str, extension: str) -> str: """ Replaces white spaces of the string with '-' and adds a '.' and the extension to the end. :param file_name: File name :param extension: File extension :return: str Transformed filename """ return file_name.replace(' ', '-') ...
bigcode/self-oss-instruct-sc2-concepts
def module_fuel(mass): """Calculate needed fuel for mass.""" return mass // 3 - 2
bigcode/self-oss-instruct-sc2-concepts
def compute_set_difference_one(s1, s2): """ Computes the set difference between s1 and s2 (ie: in s1 but not in s2) PRE: s1 and s2 differ by one element and thus their set difference is a single element :arg s1 (set(T)): super set :arg s2 (set(T)): subset :returns (T): the s...
bigcode/self-oss-instruct-sc2-concepts
import re def Amatch(tmpl, strn): """ Test for AIPS match of string A "?" matches one of any character, "*" matches any string all blanks matches anything Returns True or False * tmpl = Template string * strng = String to search for occurance of tmpl """ # All blank? ...
bigcode/self-oss-instruct-sc2-concepts
def distance1(x1, y1, x2, y2): """Retourner la "Manhattan distance" entre (x1, y1) et (x2, y2).""" return abs(x1 - x2) + abs(y1 - y2)
bigcode/self-oss-instruct-sc2-concepts
def within_ID(idx, b0, b1): """ Tests whether an object identifer is within the remit of the shard bounds. """ return b0 <= idx < b1
bigcode/self-oss-instruct-sc2-concepts
def merge_sort(array): """ Sort array in ascending order by merge sort Merge Sort is a Divide and Conquer algorithm. Conceptually, a merge sort works as follows: 1. Divide the unsorted list into n sub-lists, each containing one element (a list of one element is considered sorted). 2. Repe...
bigcode/self-oss-instruct-sc2-concepts
def parse_responsive_length(responsive_length): """ Takes a string containing a length definition in pixels or percent and parses it to obtain a computational length. It returns a tuple where the first element is the length in pixels and the second element is its length in percent divided by 100. No...
bigcode/self-oss-instruct-sc2-concepts
def Pack(flatten, nmap_list): """Packs the list of tensors according to `.NestedMap` in `nmap_list`. `Pack` is loosely the inverse of `Flatten`. Args: flatten: A list of tensors. nmap_list: A list of `.NestedMap`. Returns: A list of `.NestedMap`, say ret is the returned list. We have 1. le...
bigcode/self-oss-instruct-sc2-concepts
def ptime(s: float) -> str: """ Pretty print a time in the format H:M:S.ms. Empty leading fields are disgarded with the exception of times under 60 seconds which show 0 minutes. >>> ptime(234.2) '3:54.200' >>> ptime(23275.24) '6:27:55.240' >>> ptime(51) '0:51' >>> ptime(325) '5:25' """ h: float m: float...
bigcode/self-oss-instruct-sc2-concepts
def knot_vector_uniform(num_points, degree, periodic=False): """Computes a uniform knot vector. Parameters ---------- num_points : int Number of points to compute parameters for. degree : int The degree of the curve. Returns ------- list of float The knot vector...
bigcode/self-oss-instruct-sc2-concepts
def stream_hashsum(ioobj, hasher, blocksize=65536): """Generate a hash sum from a filelike object using the supplied hashlib algorithm. Example: stream_hashsum(open('foobar.txt','rb'), hashlib.md5()) """ while True: block = ioobj.read(blocksize) if len(block) > 0: ...
bigcode/self-oss-instruct-sc2-concepts
def non_valid_devs(host): """Inventory Filter for Nornir for all non-valid devices. Return True or False if a device is not valid Args: host(Host): Nornir Host Returns: bool: True if the device do not have a config, False otherwise. """ if host.data["has_config"]: return...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_ics(url): """ Gets the ICS file residing at the given url. :param url: the url from which to download the ics file :type url: str :return: string containing the ical file contents """ req = requests.get(url) assert req.ok, "Failed to download the file" retur...
bigcode/self-oss-instruct-sc2-concepts
def add_units(metric_name): """ Given a metric name, it adds the units according to its input. Parameters ---------- metric_name : str The name of the metric where the units will be added Returns ------- label : str The new label of the metric containing the units that ...
bigcode/self-oss-instruct-sc2-concepts
import re def pathsplit(p): """Split a path into a WebDataset prefix and suffix. The prefix is used for grouping files into samples, the suffix is used as key in the output dictionary. The suffix consists of all components after the last "." in the filename. In torchdata, the prefix consists...
bigcode/self-oss-instruct-sc2-concepts
def get_distance(particle): """Get Manhattan distance of particle.""" return sum(abs(num) for num in particle['position'])
bigcode/self-oss-instruct-sc2-concepts
def color565(red, green=0, blue=0): """ Convert red, green and blue values (0-255) into a 16-bit 565 encoding. """ try: red, green, blue = red # see if the first var is a tuple/list except TypeError: pass return (red & 0xf8) << 8 | (green & 0xfc) << 3 | blue >> 3
bigcode/self-oss-instruct-sc2-concepts
def is_url(url): """test for HTTP and HTTPS protocol in the string""" if len(url) > 6 and (url[0:7] == "http://" or url[0:8] == "https://"): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
import re def replace_location(match: re.Match, location: str) -> str: """Replace location data in the warning string.""" text = match.string start, end = match.span(2) return text[:start] + location + text[end:]
bigcode/self-oss-instruct-sc2-concepts
def q_learn(old_state_action_q_value, new_state_max_q_value, reward, learn_rate=0.01, discount_factor=0.9): """ Returns updated state-action Q_value. :param old_state_action_q_value: Q_value of the chosen action in the previous state. :param new_state_max_q_value: maximum Q_value of new state. :para...
bigcode/self-oss-instruct-sc2-concepts
def stripLabels(testFeatures): """ Strips label from a test sentence feature vector """ return [testFeatures[i][0] for i in range(len(testFeatures))]
bigcode/self-oss-instruct-sc2-concepts
def find_pair_in_hits( hits, pair, max_separation = None, separation = None ): """Finds the locations where a pair of TFs bind in a sequence of hits hits: The hits pair: A tuple ( binder1, binder2, orientation1, orientation2 ) max_separation: If specified determines maxi...
bigcode/self-oss-instruct-sc2-concepts
import random def make_act_type_data(act_tp): """ 随机生成账号等级,提高高级别账号权重 :param act_tp: 账号类型 :return: 随机账号类别标识码,高级别账号权重较大 """ if act_tp == "11": act_typ = random.choice(["3", "3", "3", "2", "2", "1"]) elif act_tp == "211": act_typ = random.choice(["1", "1", "1", "2", "2", "3"])...
bigcode/self-oss-instruct-sc2-concepts
def XCOMmaterial(massdic): """ Function to convert the mass percentages into XCOM readable input string Parameters ---------- massdic : dict Dictionary which stores the mass percentage for each element (which are the keys). Returns ------- xcomstr : str String w...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Tuple def get_num_neutrinos(fpath: Path) -> Tuple[int, int]: """Get the number of neutrinos (both electrons and muons) from the MiniBooNE data text file Args: fpath: path to the text file Returns: Tuple of (num_electron, num_muon) """ ...
bigcode/self-oss-instruct-sc2-concepts
def factorial(num): """ Find the factorial of a number :type num: integer :param num: The number to find the factorial for. >>> factorial(4) 24 """ if num == 0: return 1 return num * factorial(num - 1)
bigcode/self-oss-instruct-sc2-concepts
def empty_config_file(tmpdir): """produce an empty config file Returns: tuple -- Tuple containing following: 1. Path to an empty config file 2. A blank dictionary """ cfg = tmpdir.join('empty-config.yaml') cfg.write('') emptydict = {} return (...
bigcode/self-oss-instruct-sc2-concepts
def feature_test_qual_value(feature, **kwargs): """Test qualifier values. For every feature, check that at least one value in feature.quailfiers(kwargs['qualifier']) is in kwargs['attribute_list'] """ for attribute_value in feature.qualifiers.get(kwargs['qualifier'], []): if attribute_value...
bigcode/self-oss-instruct-sc2-concepts
def gen_State(drone_id, battery, direction, position, status, speed): """Generate a State objects.""" state = { "@type": "State", "DroneID": drone_id, "Battery": battery, "Direction": direction, "Position": position, "Status": status, "Speed": speed, }...
bigcode/self-oss-instruct-sc2-concepts
import pickle def predictSVM(X_test): """This function takes a dataset and predict the letter for each data point. Parameters ---------- dataset: M X 128 numpy array A dataset represented by numpy-array Returns ------- M x 1 numpy array Returns a numpy array of letter that each data point represents """...
bigcode/self-oss-instruct-sc2-concepts
import json def build_trace_dict(f, start_time, end_time): """Creates a python dictionary that has trace ids as keys and the corresponding trace objects as values. Input: python file object that points to a file with traces, written by htrace-c's local file span receiver. The exact format shouldn...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List def check_filetype(estimated_filetype: str, allowed_types: Union[str, List[str]]) -> bool: """ Check if a file has an expected filetype. param: estimated_filetype: The filetype that was estimated by magic. param: allowed_types: A string or a list of st...
bigcode/self-oss-instruct-sc2-concepts
import torch def correct(output, target, topk=(1,)): """Computes how many correct outputs with respect to targets Does NOT compute accuracy but just a raw amount of correct outputs given target labels. This is done for each value in topk. A value is considered correct if target is in the topk hig...
bigcode/self-oss-instruct-sc2-concepts
def qs_opt_eq(qs, opt, value): """ Returns True if the query string option is equal to value. """ for opt_value in qs.get(opt, []): if opt_value == value: return True
bigcode/self-oss-instruct-sc2-concepts
def all_input_tagged_nodes( graph): """Gets all input-tagged nodes that are reachable in a graph. An input-tagged node is considered reachable if there is a way to get to that node by an edge of that input type. Output will be ordered lexicographically, first by the node ordering in the input graph's ke...
bigcode/self-oss-instruct-sc2-concepts
import xml def is_document_related(err): """Returns True for expat errors related to errors in the document, which should not be reported as internal errors. """ errors = xml.parsers.expat.errors err_str = xml.parsers.expat.ErrorString(err.code) # All errors in the expat.errors-module in Pyt...
bigcode/self-oss-instruct-sc2-concepts
def get_blueprints(app): """Returns blueprints dict.""" return app.blueprints
bigcode/self-oss-instruct-sc2-concepts
def int_from_digits(digits): """ Returns a positive integer ``n`` which is a decimal expansion of a sequence of digits in descending order from the most significant digit. The input can be a sequence (list, tuple) or a generator, e.g. :: [1,2,3] -> 1x10^2 + 2x10^1 + 3x10^0 = ...
bigcode/self-oss-instruct-sc2-concepts
def filter_valid_tournaments(df): """Filter for valid tournaments Notes: Excluding Tour championship for 2019 and 2020 due to rule change in score totals. Args: df (pd.DataFrame) : espn tournaments Returns: valid_df (pd.Dataframe) : valid espn tournaments """ ...
bigcode/self-oss-instruct-sc2-concepts
def global_dependencies(context): """ Dependencies that are loaded for all tethys gizmos (after gizmo dependencies). """ return('tethys_gizmos/css/tethys_gizmos.css', 'tethys_gizmos/js/tethys_gizmos.js')
bigcode/self-oss-instruct-sc2-concepts
def subtract(x,y): """Subtract x from y and return value""" return y-x
bigcode/self-oss-instruct-sc2-concepts
def calculate_points(prediction, outcome): """ Adjusted version of the Brier scoring function, as described at https://fivethirtyeight.com/features/how-to-play-our-nfl-predictions-game/ """ diff = (prediction / 100) - outcome brier_score = diff ** 2 adjusted_score = -(brier_score - 0.25) * 2...
bigcode/self-oss-instruct-sc2-concepts
import functools def rget(dict_obj, attrpath): """ A fancy version of `get` that allows getting dot-separated nested attributes like `license.license_name` for use in tree comparisons attribute mappings. This code is inspired by solution in https://stackoverflow.com/a/31174427. """ def _getnoe...
bigcode/self-oss-instruct-sc2-concepts
def integer_to_octet_string_primitive(length: int, integer: int) -> bytes: """Convert a nonnegative integer to an octet string.""" # https://tools.ietf.org/html/rfc8017#section-4.1 if integer >= 256 ** length: raise ValueError(f"{integer} >= 256 ** {length}") index = 0 digits = [0] * length ...
bigcode/self-oss-instruct-sc2-concepts
def check_inorganic(struct): """ Checks if the structure contains inorganic atoms. """ ele = struct.geometry["element"] metals = ['Ag', 'Al', 'As', 'Au', 'Ba', 'Be', 'Bi', 'Ca', 'Cd', 'Ce', 'Co', 'Cr', 'Cu', 'Dy', 'Er', 'Eu', 'Fe', 'Ga', 'Gd', 'Ge', 'Hf', 'Hg', 'Ho',...
bigcode/self-oss-instruct-sc2-concepts
def _errorr_input(endfin, pendfin, errorrout, mat, ign=2, iwt=2, temp=293.6, iprint=False, **kwargs): """Write acer input for fast data. Parameters ---------- endfin : `int` tape number for input ENDF-6 file pendfin : `int` tape number for inp...
bigcode/self-oss-instruct-sc2-concepts
import itertools def sequence(start=0, step=1): """:yaql:sequence Returns an iterator to the sequence beginning from start with step. :signature: sequence(start => 0, step => 1) :arg start: start value of the sequence. 0 is value by default :argType start: integer :arg step: the next element...
bigcode/self-oss-instruct-sc2-concepts
import torch def hermitify(kern, dim): """Enforce Hermitian symmetry. This function takes an approximately Hermitian-symmetric kernel and enforces Hermitian symmetry by calcualting a tensor that reverses the coordinates and conjugates the original, then averaging that tensor with the original. ...
bigcode/self-oss-instruct-sc2-concepts
import re def namespace_for_username(username: str) -> str: """ Get the Kubernetes namespace for a JupyterHub user. Not all JupyterHub usernames are validate kubernetes namespaces, so we have to # translate it somehow. This replaces lowercases the input and replaces non-ascii alphanumeric charact...
bigcode/self-oss-instruct-sc2-concepts
def isoformat(dt): """Return iso-formatted timestamp Like .isoformat(), but uses Z for UTC instead of +00:00 """ return dt.isoformat().replace('+00:00', 'Z')
bigcode/self-oss-instruct-sc2-concepts
def get_remote_orders(connection): """Returns orders from a remote player. Parameters ---------- connection: sockets to receive/send orders (tuple) Returns ---------- player_orders: orders given by remote player (str) Raises ------ IOError: if remote player cannot be r...
bigcode/self-oss-instruct-sc2-concepts
def get_dx(p0, p1, smooth_line, cl_id, id_end, id_mid, id_start): """Get the displacement for the Voronoi point Args: p0 (ndarray): Point i on the old centerline. p1 (ndarray): Point i on the new centerline. smooth_line (bool): Turn on/off increasing curvuature. cl_id (int): ID ...
bigcode/self-oss-instruct-sc2-concepts
def has_outputfile(records: dict) -> list: """ Convenience function for finding output files in a dictionary of records""" keys, has_outputs = [], [] # check to see which records have outputfiles for key, record in records.items(): keys.append(key) has_outputs.append(record['output'] is ...
bigcode/self-oss-instruct-sc2-concepts
def bytes_from_hex(value): """There are many ways to convert hex to binary in python. This function is here to attempt to standardize on a single method. Additionally, it will return None of None is passed to it instead of throwing an expected string exception """ if not value: return No...
bigcode/self-oss-instruct-sc2-concepts
def modes(nums): """Returns the most frequently occurring items in the given list, nums""" if len(nums) == 0: return [] # Create a dictionary of numbers to how many times they occur in the list frequencies = {} for num in nums: frequencies[num] = 1 + frequencies.get(num, 0) # How...
bigcode/self-oss-instruct-sc2-concepts
def get_degree_of(links: list, node_i: int) -> int: """ computes the degree of each node and maps the node id to its degree :param links: a list of tuples with [(src, dst), ...] :param node_i: index i of node :return: degree of node i """ deg_i = sum(1 if node_i == i else 0 for i, _ in link...
bigcode/self-oss-instruct-sc2-concepts
def vector_dot(v1,v2): """ Calculate vector dot product of two vectors. Parameters ---------- v1,v2 : ndarray The arrays to calculate the product from. The vectors are represented by the last axis. Returns ------- product : float or ndarray Scalar produc...
bigcode/self-oss-instruct-sc2-concepts
def make_video_path(task_path, itr): """ Generate a video name based on a task name and iteration number :param task_path: the name of the task :param itr: the iteration number """ return "{}_tune_iter{}.mp4".format(task_path.replace("_center", ""), itr)
bigcode/self-oss-instruct-sc2-concepts
def get_label_name(node, dialogue_list): """ Takes a node and returns the name for its label """ for dialogue in dialogue_list: if dialogue["Id"] == node["Parent"]: label_name = "{}_{}".format(dialogue["DisplayName"], node["Id"]) return label_name
bigcode/self-oss-instruct-sc2-concepts
def add_numbers(number1: int, number2: int) -> int: """Add two numbers together. Args: number1 (int): The first number. number2 (int): The second number. Returns: int: The sum of number1 + number2. Examples: >>> add_numbers(10, 5) 15 """ return number1 ...
bigcode/self-oss-instruct-sc2-concepts
def cent_from_year(year): """ takes an integer and returns the matching century """ if year == 0: return 1 elif year < 0: return -(year - 1) // -100 else: return (year - 1) // 100 + 1
bigcode/self-oss-instruct-sc2-concepts
def y_fitted_line(m_val, b_val, vec_x): """ This function returns the fitted baseline constructed by coeffecient m and b and x values. ---------- Parameters ---------- x : list Output of the split vector function. x value of the input. m : int/float inclination of the bas...
bigcode/self-oss-instruct-sc2-concepts
def dissolve_footer(soup): """ Remove the BNN footer, generated date, build, etc. This is included with all OOTP pages. """ # Dissolve the BNN footer trs = soup.body.table.find_all('tr') last_tr = trs[-1] last_tr.decompose() # Dissolve the generated date and build tbls = soup.bo...
bigcode/self-oss-instruct-sc2-concepts
def _compile_module(s, name='<string>'): """ Compiles a string representing a python module (file or code) and returns the resulting global objects as a dictionary mapping name->val. @param name: Optional name for better error message handling. """ gen_module = {} code = compile(s, name...
bigcode/self-oss-instruct-sc2-concepts
def siqs_build_matrix_opt(M): """Convert the given matrix M of 0s and 1s into a list of numbers m that correspond to the columns of the matrix. The j-th number encodes the j-th column of matrix M in binary: The i-th bit of m[i] is equal to M[i][j]. """ m = len(M[0]) cols_binary = [""] * m ...
bigcode/self-oss-instruct-sc2-concepts
def binary_to_int(binary: str) -> int: """Convert a binary string to an integer Args: binary (str): Binary string Returns: int: Integer value of binary string """ return int(binary, 2)
bigcode/self-oss-instruct-sc2-concepts
def is_timerange(item: str) -> bool: """Returns True if the item is a TAF to-from time range""" return ( len(item) == 9 and item[4] == "/" and item[:4].isdigit() and item[5:].isdigit() )
bigcode/self-oss-instruct-sc2-concepts
def ensure_arg(args, arg, param=None): """Make sure the arg is present in the list of args. If arg is not present, adds the arg and the optional param. If present and param != None, sets the parameter following the arg to param. :param list args: strings representing an argument list. :param string arg: arg...
bigcode/self-oss-instruct-sc2-concepts
def ns_split(term): """ Take apart an ElementTree namespaced name, returning the namespace and a localpart. """ (ns, local) = term.split("}") assert ns[0] == "{" ns = ns[1:] return ns, local
bigcode/self-oss-instruct-sc2-concepts
import requests def get_request(url, headers): """ Method which makes a GET request to specified url :param url: url :param headers: headers :return: get response """ return requests.get(url, headers=headers)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def genId(filename): """ Generates an identifier suitable for ingestion Based off of the Watson Discovery Tooling method of generating IDs """ return hashlib.md5(filename).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def validate_key_value_pairs(string): """ Validates key-value pairs in the following format: a=b;c=d """ result = None if string: kv_list = [x for x in string.split(';') if '=' in x] # key-value pairs result = dict(x.split('=', 1) for x in kv_list) return result
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Tuple def _to_tuple(value: Union[Tuple[float, float], float]) -> Tuple[float, float]: """Convert value to a tuple if it is not already a tuple. Args: value: input value Returns: value if value is a tuple, else (value, value) """ if isin...
bigcode/self-oss-instruct-sc2-concepts
def walkable(grid_array: list) -> list: """Get a list of all the coordinates that are walkable Args: grid_array (list): map of the terrain Returns: list: all coordinates that are walkable """ walkable = [] for i, row in enumerate(grid_array): for j, cell in enumerate(ro...
bigcode/self-oss-instruct-sc2-concepts
import re def _sanitized_conf(parser): """Formats parser config, redacting database url password.""" out = parser.format_values() return re.sub(r'(?<=:)\w+(?=@)', '<redacted>', out)
bigcode/self-oss-instruct-sc2-concepts
def image(img): """Function to obtain image from tensor""" img = img / 2 + 0.5 # unnormalize return img.numpy()
bigcode/self-oss-instruct-sc2-concepts
def total_consumption(consumption: float, area: float) -> float: """Get the total consumption of a building in a year. It's function of the energy consumption and total area. Args: consumption (float): The consumption of the building in kWh/m².year. area (float): The total area of the buil...
bigcode/self-oss-instruct-sc2-concepts
def OffsetList(inputList, offset): """ Return a list equal to the input list with all entries equal to the corresponding entries in the input list plus the supplied offset """ outputList = [] for entry in inputList: outputList.append(entry + offset) return outputList
bigcode/self-oss-instruct-sc2-concepts
import re def set_filename_version(filename, version_number, pattern): """Write the given version number in the given (in filename) file, after the given pattern. E.g.: set_filename_version('setup.py', '1.0.0', 'version') Extracted from Flask source, see: - file: flask/scripts/make-r...
bigcode/self-oss-instruct-sc2-concepts
def create_end_repeat(nstep, iline, protocol, inrepeat): """ Given a line from a file with format: add to the protocol an [# : End repeat nstep steps :] line Parameters ----------- nstep : int Number of steps in a loop iline : int Counter for protocol lines protocol : ...
bigcode/self-oss-instruct-sc2-concepts
import math def columnate(strings, separator=", ", chars=80): """ render a list of strings as a in a bunch of columns Positional arguments: strings - the strings to columnate Keyword arguments; separator - the separation between the columns chars - the maximum with of a row """ col_w...
bigcode/self-oss-instruct-sc2-concepts
def _before(node): """ Returns the set of all nodes that are before the given node. """ try: pos = node.treeposition() tree = node.root() except AttributeError: return [] return [tree[x] for x in tree.treepositions() if x[: len(pos)] < pos[: len(x)]]
bigcode/self-oss-instruct-sc2-concepts
def calculate_immediate_dominators(nodes, _dom, _sdom): """ Determine immediate dominators from dominators and strict dominators. """ _idom = {} for node in nodes: if _sdom[node]: for x in _sdom[node]: if _dom[x] == _sdom[node]: # This must be th...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def simulate_day(school: List[int]) -> List[int]: """Simulates a school of fish for one day and returns the school.""" return [*school[1:7], school[0] + school[7], school[8], school[0]]
bigcode/self-oss-instruct-sc2-concepts
def chromedriver_path_of(system_name) -> str: """Gets system name and returns a string path :param string system_name: should be "Windows", "Linux" or "Darwin". System name can be obtained from "platform" module and "system" function """ if system_name == 'Windows': return "./chromedriver....
bigcode/self-oss-instruct-sc2-concepts