seed
stringlengths
1
14k
source
stringclasses
2 values
def trim_description(desc: str, n_words: int) -> str: """Return the first `n_words` words of description `desc`/""" return " ".join(str(desc).split(" ")[0:n_words])
bigcode/self-oss-instruct-sc2-concepts
def ahs_url_helper(build_url, config, args): """Based on the configured year, get the version arg and replace it into the URL.""" version = config["years"][args["year"]] url = build_url url = url.replace("__ver__", version) return [url]
bigcode/self-oss-instruct-sc2-concepts
import uuid import json def create_event(_action, _data): """ Create an event. :param _action: The event action. :param _data: A dict with the event data. :return: A dict with the event information. """ return { 'event_id': str(uuid.uuid4()), 'event_action': _action, 'event_data': json.dumps(_data) }
bigcode/self-oss-instruct-sc2-concepts
def level_up_reward(level, new_level): """ Coins rewarded when upgrading to new_level. """ coins = 0 while level < new_level: coins += 5 + level // 15 level += 1 return coins
bigcode/self-oss-instruct-sc2-concepts
def substitute_str_idx(s: str, r: str, i: int) -> str: """Substitute char at position Arguments: s: The str in which to substitute r: The char to substitute i: index of the substitution Returns: The string `s` with the i'th char substitute with `r` """ z = ''.join([(lambda: r, lambda: x)[idx != i]() for idx, x in enumerate(s)]) return z
bigcode/self-oss-instruct-sc2-concepts
def rotate_address(level, address, rotate_num): """Rotates the address with respect to rotational symmetries of SG Args: level: A nonnegative integer representing the level of SG we're working with. address: np.array of size (level+1) representing the address vector of a point in some SG graph. rotate_num: A number in {0, 1, 2} representing the type of rotation we're making. 0 represent no rotation, 1 represent counterclockwise 2*np.pi/3, 2 represent counterclockwise 4*np.pi/3. Returns: new_address: np.array of size (level+1) representing the address vector of the rotated point in some SG graph. """ new_address = [] for i in range(level): new_address.append(int((address[i] + rotate_num) % 3)) new_address.append(int(address[-1])) return new_address
bigcode/self-oss-instruct-sc2-concepts
def get_key(file_name): """ Get id from file name """ return file_name.split('-')[0]
bigcode/self-oss-instruct-sc2-concepts
from tabulate import tabulate from typing import List def convert_cross_package_dependencies_to_table( cross_package_dependencies: List[str], markdown: bool = True, ) -> str: """ Converts cross-package dependencies to a markdown table :param cross_package_dependencies: list of cross-package dependencies :param markdown: if True, markdown format is used else rst :return: formatted table """ headers = ["Dependent package", "Extra"] table_data = [] prefix = "apache-airflow-providers-" base_url = "https://airflow.apache.org/docs/" for dependency in cross_package_dependencies: pip_package_name = f"{prefix}{dependency.replace('.','-')}" url_suffix = f"{dependency.replace('.','-')}" if markdown: url = f"[{pip_package_name}]({base_url}{url_suffix})" else: url = f"`{pip_package_name} <{base_url}{prefix}{url_suffix}>`_" table_data.append((url, f"`{dependency}`" if markdown else f"``{dependency}``")) return tabulate(table_data, headers=headers, tablefmt="pipe" if markdown else "rst")
bigcode/self-oss-instruct-sc2-concepts
def calc_league_points(pos_map, dsq_list): """ A function to work out the league points for each zone, given the rankings within that game. @param pos_map: a dict of position to array of zone numbers. @param dsq_list: a list of zones that shouldn't be awarded league points. @returns: a dict of zone number to league points. """ lpoints = {} for pos, zones in pos_map.iteritems(): # remove any that are dsqaulified # note that we do this before working out the ties, so that any # dsq tie members are removed from contention zones = [ z for z in zones if z not in dsq_list ] if len(zones) == 0: continue # max points is 4, add one because pos is 1-indexed points = (4 + 1) - pos # Now that we have the value for this position if it were not a tie, # we need to allow for ties. In case of a tie, the available points # for all the places used are shared by all those thus placed. # Eg: three first places get 3pts each (4+3+2)/3. # Rather than generate a list and average it, it's quicker to just # do some maths using the max value and the length of the list points = points - ( (len(zones) - 1) / 2.0 ) for z in zones: lpoints[z] = points # those that were dsq get 0 for z in dsq_list: lpoints[z] = 0.0 return lpoints
bigcode/self-oss-instruct-sc2-concepts
def getEnd(timefile, end_ind): """ Parameter ---------- timefile : array-like 1d the timefile. end_ind : integer the end index. Returns ------- the end of the condition. """ return timefile['ConditionTime'][end_ind]
bigcode/self-oss-instruct-sc2-concepts
from typing import List def split_module_names(mod_name: str) -> List[str]: """Return the module and all parent module names. So, if `mod_name` is 'a.b.c', this function will return ['a.b.c', 'a.b', and 'a']. """ out = [mod_name] while '.' in mod_name: mod_name = mod_name.rsplit('.', 1)[0] out.append(mod_name) return out
bigcode/self-oss-instruct-sc2-concepts
def import_class(name): """Import class from string. Args: name (str): class path Example: >>> model_cls = import_class("tfchat.models.PreLNDecoder") """ components = name.split(".") mod = __import__(".".join(components[:-1]), fromlist=[components[-1]]) return getattr(mod, components[-1])
bigcode/self-oss-instruct-sc2-concepts
def is_fractional_es(input_str, short_scale=True): """ This function takes the given text and checks if it is a fraction. Args: text (str): the string to check if fractional short_scale (bool): use short scale if True, long scale if False Returns: (bool) or (float): False if not a fraction, otherwise the fraction """ if input_str.endswith('s', -1): input_str = input_str[:len(input_str) - 1] # e.g. "fifths" aFrac = {"medio": 2, "media": 2, "tercio": 3, "cuarto": 4, "cuarta": 4, "quinto": 5, "quinta": 5, "sexto": 6, "sexta": 6, "séptimo": 7, "séptima": 7, "octavo": 8, "octava": 8, "noveno": 9, "novena": 9, "décimo": 10, "décima": 10, "onceavo": 11, "onceava": 11, "doceavo": 12, "doceava": 12} if input_str.lower() in aFrac: return 1.0 / aFrac[input_str] if (input_str == "vigésimo" or input_str == "vigésima"): return 1.0 / 20 if (input_str == "trigésimo" or input_str == "trigésima"): return 1.0 / 30 if (input_str == "centésimo" or input_str == "centésima"): return 1.0 / 100 if (input_str == "milésimo" or input_str == "milésima"): return 1.0 / 1000 return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Any from typing import List from typing import Set from typing import Type def _get_overloaded_args(relevant_args: Iterable[Any]) -> List[Any]: """Returns a list of arguments on which to call __torch_function__. Checks arguments in relevant_args for __torch_function__ implementations, storing references to the arguments and their types in overloaded_args and overloaded_types in order of calling precedence. Only distinct types are considered. If a type is a subclass of another type it will have higher precedence, otherwise the precedence order is the same as the order of arguments in relevant_args, that is, from left-to-right in the argument list. The precedence-determining algorithm implemented in this function is described in `NEP-0018`_. See torch::append_overloaded_arg for the equivalent function in the C++ implementation. Parameters ---------- relevant_args : iterable of array-like Iterable of array-like arguments to check for __torch_function__ methods. Returns ------- overloaded_args : list Arguments from relevant_args on which to call __torch_function__ methods, in the order in which they should be called. .. _NEP-0018: https://numpy.org/neps/nep-0018-array-function-protocol.html """ # Runtime is O(num_arguments * num_unique_types) overloaded_types: Set[Type] = set() overloaded_args: List[Any] = [] for arg in relevant_args: arg_type = type(arg) # We only collect arguments if they have a unique type, which ensures # reasonable performance even with a long list of possibly overloaded # arguments. if (arg_type not in overloaded_types and hasattr(arg_type, '__torch_function__')): # Create lists explicitly for the first type (usually the only one # done) to avoid setting up the iterator for overloaded_args. if overloaded_types: overloaded_types.add(arg_type) # By default, insert argument at the end, but if it is # subclass of another argument, insert it before that argument. # This ensures "subclasses before superclasses". index = len(overloaded_args) for i, old_arg in enumerate(overloaded_args): if issubclass(arg_type, type(old_arg)): index = i break overloaded_args.insert(index, arg) else: overloaded_types = {arg_type} overloaded_args = [arg] return overloaded_args
bigcode/self-oss-instruct-sc2-concepts
def get_view_setting(view, sname, default=None): """Check if a setting is view-specific and only then return its value. Otherwise return `default`. """ s = view.settings() value = s.get(sname) s.erase(sname) value2 = s.get(sname) if value2 == value: return default else: s.set(sname, value) return value
bigcode/self-oss-instruct-sc2-concepts
def strip_comments(lines): """ Returns the lines from a list of a lines with comments and trailing whitespace removed. >>> strip_comments(['abc', ' ', '# def', 'egh ']) ['abc', '', '', 'egh'] It should not remove leading whitespace >>> strip_comments([' bar # baz']) [' bar'] It should also strip trailing comments. >>> strip_comments(['abc #foo']) ['abc'] """ return [line.partition('#')[0].rstrip() for line in lines]
bigcode/self-oss-instruct-sc2-concepts
def find_between(s, first, last): """ Find sting between two sub-strings Args: s: Main string first: first sub-string last: second sub-string Example find_between('[Hello]', '[', ']') -> returns 'Hello' Returns: String between the first and second sub-strings, if any was found otherwise returns an empty string """ try: start = s.index(first) + len(first) end = s.index(last, start) return s[start:end] except ValueError: return ""
bigcode/self-oss-instruct-sc2-concepts
def makeAdder(amount): """Make a function that adds the given amount to a number.""" def addAmount(x): return x + amount return addAmount
bigcode/self-oss-instruct-sc2-concepts
import types import enum def skip_non_methods(app, what, name, obj, skip, options): """ Skip all class members, that are not methods, enum values or inner classes, since other attributes are already documented in the class docstring. """ if skip: return True if what == "class": # Functions if type(obj) in [ types.FunctionType, types.BuiltinFunctionType, types.MethodType # Functions from C-extensions ] or type(obj).__name__ in [ "cython_function_or_method", "method_descriptor", "fused_cython_function" # Enum Instance or inner class ] or isinstance(obj, enum.Enum) or isinstance(obj, type): return False return True
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def _answer_types_row(row: Dict[str, str]): """ Transform the keys of each answer-type CSV row. If the CSV headers change, this will make a single place to fix it. """ return { 'k': row['Key'], 'c': row['Choices'], }
bigcode/self-oss-instruct-sc2-concepts
def twos_complement_to_int(val, length=4): """ Two's complement representation to integer. We assume that the number is always negative. 1. Invert all the bits through the number 2. Add one """ invertor = int('1' * length, 2) return -((int(val, 2) ^ invertor) + 1)
bigcode/self-oss-instruct-sc2-concepts
import re import time def wait_for_logs(container, predicate, timeout=None, interval=1): """ Wait for the container to emit logs satisfying the predicate. Parameters ---------- container : DockerContainer Container whose logs to wait for. predicate : callable or str Predicate that should be satisfied by the logs. If a string, the it is used as the pattern for a multiline regular expression search. timeout : float or None Number of seconds to wait for the predicate to be satisfied. Defaults to wait indefinitely. interval : float Interval at which to poll the logs. Returns ------- duration : float Number of seconds until the predicate was satisfied. """ if isinstance(predicate, str): predicate = re.compile(predicate, re.MULTILINE).search start = time.time() while True: duration = time.time() - start if predicate(container._container.logs().decode()): return duration if timeout and duration > timeout: raise TimeoutError("container did not emit logs satisfying predicate in %.3f seconds" % timeout) time.sleep(interval)
bigcode/self-oss-instruct-sc2-concepts
import shutil def prepare_empty_dirs(dirs: list): """ 建立空目录。若已经存在,则删除后创建。 parents=True Args: dirs: Path list Returns: dirs 中各个目录的句柄 """ result = [] for d in dirs: if d.exists(): shutil.rmtree(d.as_posix()) d.mkdir(parents=True, exist_ok=False) result.append(d) return result
bigcode/self-oss-instruct-sc2-concepts
def update_header(login_response, call_header): """Function to process and update the header after login""" token = str(login_response).split()[2] + " " + str(login_response).split()[3] call_header['Authorization'] = token return call_header
bigcode/self-oss-instruct-sc2-concepts
import torch def log2(input, *args, **kwargs): """ Returns a new tensor with the logarithm to the base 2 of the elements of ``input``. Examples:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.log2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0])) tensor([ nan, nan, -inf, 1.0000, 2.2630, 3.0000]) >>> ttorch.log2(ttorch.tensor({ ... 'a': [-4.0, -1.0, 0, 2.0, 4.8, 8.0], ... 'b': {'x': [[-2.0, 1.2, 0.25], ... [16.0, 3.75, -2.34]]}, ... })) <Tensor 0x7ff90a4cff70> ├── a --> tensor([ nan, nan, -inf, 1.0000, 2.2630, 3.0000]) └── b --> <Tensor 0x7ff90a4bc070> └── x --> tensor([[ nan, 0.2630, -2.0000], [ 4.0000, 1.9069, nan]]) """ return torch.log2(input, *args, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
def binary_search(array, x): """ Binary search :param array: array: Must be sorted :param x: value to search :return: position where it is found, -1 if not found """ lower = 0 upper = len(array) while lower < upper: # use < instead of <= mid = lower + (upper - lower) // 2 # // is the integer division val = array[mid] if x == val: return mid elif x > val: if lower == mid: break lower = mid elif x < val: upper = mid return -1
bigcode/self-oss-instruct-sc2-concepts
def insert_position(player, ship, starting): """Insert a valid position (e.g. B2).""" while True: if starting: position = input(player.name + ", where do you want to place your " + ship[0] + "(" + str(ship[1]) + ")? ").upper() else: position = input(player.name + ", where do you want to shoot? ").upper() try: if (position[0] in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']) and (int(position[1:]) in range(1, 11)): return position else: print("Please insert a valid position.\n") except: print("Please insert a valid position.\n")
bigcode/self-oss-instruct-sc2-concepts
def select_longest_utr3_exonic_content(transcripts): """Select transcript(s) with longest UTR3 exonic content""" ret = [transcripts[0]] longest = transcripts[0].utr3_exonic_content_length for i in range(1, len(transcripts)): t = transcripts[i] exonic_content_length = t.utr3_exonic_content_length if exonic_content_length == longest: ret.append(t) elif exonic_content_length > longest: longest = exonic_content_length ret = [t] return ret
bigcode/self-oss-instruct-sc2-concepts
import torch def _moments(a, b, n): """ Computes nth moment of Kumaraswamy using using torch.lgamma """ arg1 = 1 + n / a log_value = torch.lgamma(arg1) + torch.lgamma(b) - torch.lgamma(arg1 + b) return b * torch.exp(log_value)
bigcode/self-oss-instruct-sc2-concepts
def single_byte_xor(byte_array, key_byte): """XOR every byte in 'byte_array' with the 'key_byte'""" result = bytearray() for i in range(0, len(byte_array)): result.append(byte_array[i] ^ key_byte) return result
bigcode/self-oss-instruct-sc2-concepts
def get_region_for_chip(x, y, level=3): """Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the specified region will ONLY select the given chip, for other regions surrounding chips will also be selected. Returns ------- int A 32-bit value representing the co-ordinates of the chunk of SpiNNaker chips that should be selected and the blocks within this chunk that are selected. As long as bits (31:16) are the same these values may be OR-ed together to increase the number of sub-blocks selected. """ shift = 6 - 2*level bit = ((x >> shift) & 3) + 4*((y >> shift) & 3) # bit in bits 15:0 to set mask = 0xffff ^ ((4 << shift) - 1) # in {0xfffc, 0xfff0, 0xffc0, 0xff00} nx = x & mask # The mask guarantees that bits 1:0 will be cleared ny = y & mask # The mask guarantees that bits 1:0 will be cleared # sig bits x | sig bits y | 2-bit level | region select bits region = (nx << 24) | (ny << 16) | (level << 16) | (1 << bit) return region
bigcode/self-oss-instruct-sc2-concepts
def get_calendar_event_id(user, block_key, date_type, hostname): """ Creates a unique event id based on a user and a course block key Parameters: user (User): The user requesting a calendar event block_key (str): The block key containing the date for the calendar event date_type (str): The type of the date (e.g. 'due', 'start', 'end', etc.) hostname (str): A hostname to namespace this id (e.g. 'open.edx.org') Returns: event id (str) """ return f'{user.id}.{block_key}.{date_type}@{hostname}'
bigcode/self-oss-instruct-sc2-concepts
def dnn_activation(data, model, layer_loc, channels=None): """ Extract DNN activation from the specified layer Parameters: ---------- data[tensor]: input stimuli of the model with shape as (n_stim, n_chn, height, width) model[model]: DNN model layer_loc[sequence]: a sequence of keys to find the location of the target layer in the DNN model. For example, the location of the fifth convolution layer in AlexNet is ('features', '10'). channels[list]: channel indices of interest Return: ------ dnn_acts[array]: DNN activation a 4D array with its shape as (n_stim, n_chn, n_r, n_c) """ # change to eval mode model.eval() # prepare dnn activation hook dnn_acts = [] def hook_act(module, input, output): act = output.detach().numpy().copy() if channels is not None: act = act[:, channels] dnn_acts.append(act) module = model for k in layer_loc: module = module._modules[k] hook_handle = module.register_forward_hook(hook_act) # extract dnn activation model(data) dnn_acts = dnn_acts[0] hook_handle.remove() return dnn_acts
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def expected(request) -> Any: """Expected test case result.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def clean_path(path): """ Add ws:///@user/ prefix if necessary """ if path[0:3] != "ws:": while path and path[0] == "/": path = path[1:] path = "ws:///@user/" + path return path
bigcode/self-oss-instruct-sc2-concepts
def strip_comments(s): """Strips the comments from a multi-line string. >>> strip_comments('hello ;comment\\nworld') 'hello \\nworld' """ COMMENT_CHAR = ';' lines = [] for line in s.split('\n'): if COMMENT_CHAR in line: lines.append(line[:line.index(COMMENT_CHAR)]) else: lines.append(line) return '\n'.join(lines)
bigcode/self-oss-instruct-sc2-concepts
def translate_p_vals(pval, as_emoji=True): """ Translates ambiguous p-values into more meaningful emoji. Parameters ---------- pval : float as_emoji : bool (default = True) Represent the p-vals as emoji. Otherwise, words will be used. Returns ------- interpreted : string """ if pval is None: interpreted = r"ಠ_ಠ" if as_emoji else "NA" elif pval <= 0.01: interpreted = r"¯\(ツ)/¯" if as_emoji else "maybe" elif 0.01 < pval <= 0.05: interpreted = r"¯\_(ツ)_/¯" if as_emoji else "maybe (weak)" elif 0.05 < pval <= 0.1: interpreted = r"¯\__(ツ)__/¯" if as_emoji else "maybe (very weak)" elif 0.1 < pval <= 1: interpreted = r"(╯°□°)╯︵ ┻━┻" if as_emoji else "nope" else: raise ValueError("p-values must be between 0 and 1 (not {})".format(pval)) return interpreted
bigcode/self-oss-instruct-sc2-concepts
def str2LaTeX(python_string): """ Function that solves the underscore problem in a python string to :math:`\LaTeX` string. Parameters ---------- python_string : `str` String that needs to be changed. Returns ------- LaTeX_string : `str` String with the new underscore symbol. """ string_list = list(python_string) for idx, string in enumerate(string_list): if string_list[idx] == '_': string_list[idx] = '\\_' LaTeX_string = ''.join(string_list) return LaTeX_string
bigcode/self-oss-instruct-sc2-concepts
def ip_range(network): """Return tuple of low, high IP address for given network""" num_addresses = network.num_addresses if num_addresses == 1: host = network[0] return host, host elif num_addresses == 2: return network[0], network[-1] else: return network[1], network[-2]
bigcode/self-oss-instruct-sc2-concepts
def none_split(val): """Handles calling split on a None value by returning the empty list.""" return val.split(', ') if val else ()
bigcode/self-oss-instruct-sc2-concepts
def distinct_terms(n): """Finds number of distinct terms a^b for 2<=a<=n, 2<=b<=n""" return len(set([a**b for a in range(2, n+1) for b in range(2, n+1)]))
bigcode/self-oss-instruct-sc2-concepts
def t01_SimpleGetPut(C, pks, crypto, server): """Uploads a single file and checks the downloaded version is correct.""" alice = C("alice") alice.upload("a", "b") return float(alice.download("a") == "b")
bigcode/self-oss-instruct-sc2-concepts
def get_as_list(base: dict, target): """Helper function that returns the target as a list. :param base: dictionary to query. :param target: target key. :return: base[target] as a list (if it isn't already). """ if target not in base: return list() if not isinstance(base[target], list): return [base[target]] return base[target]
bigcode/self-oss-instruct-sc2-concepts
def intget(integer, default=None): """Returns `integer` as an int or `default` if it can't.""" try: return int(integer) except (TypeError, ValueError): return default
bigcode/self-oss-instruct-sc2-concepts
def hexagonal(n): """Returns the n-th hexagonal number""" return n*(2*n-1)
bigcode/self-oss-instruct-sc2-concepts
def isSubListInListWithIndex(sublist, alist): """ Predicates that checks if a list is included in another one Args: sublist (list): a (sub)-list of elements. alist (list): a list in which to look if the sublist is included in. Result: (True, Index) if the sublist is included in the list. False otherwise. """ for i in range(len(alist) - len(sublist) + 1): if sublist == alist[i: i + len(sublist)]: return True, i return False, -1
bigcode/self-oss-instruct-sc2-concepts
def gcd(x: int, y: int) -> int: """ Euclidean GCD algorithm (Greatest Common Divisor) >>> gcd(0, 0) 0 >>> gcd(23, 42) 1 >>> gcd(15, 33) 3 >>> gcd(12345, 67890) 15 """ return x if y == 0 else gcd(y, x % y)
bigcode/self-oss-instruct-sc2-concepts
from glob import glob def list_files_local(path): """ Get file list form local folder. """ return glob(path)
bigcode/self-oss-instruct-sc2-concepts
def combine(background_img, figure_img): """ :param background_img: SimpleImage, the background image :param figure_img: SimpleImage, the green screen figure image :return: SimpleImage, the green screen pixels are replaced with pixels of background image """ # (x, y) represent every pixel in the figure image for x in range(figure_img.width): for y in range(figure_img.height): # get pixel at (x, y) in figure image pixel_fg = figure_img.get_pixel(x, y) # find the maximum value between R-value and B-value at (x, y) bigger = max(pixel_fg.red, pixel_fg.blue) # check whether pixel at (x, y) is green screen if pixel_fg.green > bigger * 2: # get pixel at (x, y) in background image pixel_bg = background_img.get_pixel(x, y) # replace figure image's R-value at (x, y) with background image's R-value at (x, y) pixel_fg.red = pixel_bg.red # replace figure image's G-value at (x, y) with background image's G-value at (x, y) pixel_fg.green = pixel_bg.green # replace figure image's B-value at (x, y) with background image's B-value at (x, y) pixel_fg.blue = pixel_bg.blue # return the combined image return figure_img
bigcode/self-oss-instruct-sc2-concepts
import socket import struct def ip2long(ip): """ Convert IPv4 address in string format into an integer :param str ip: ipv4 address :return: ipv4 address :rtype: integer """ packed_ip = socket.inet_aton(ip) return struct.unpack("!L", packed_ip)[0]
bigcode/self-oss-instruct-sc2-concepts
def invert(record): """ Invert (ID, tokens) to a list of (token, ID) Args: record: a pair, (ID, token vector) Returns: pairs: a list of pairs of token to ID """ return [(k,record[0]) for k,v in record[1].iteritems()]
bigcode/self-oss-instruct-sc2-concepts
def inv_map(dictionary: dict): """ creates a inverse mapped dictionary of the provided dict :param dictionary: dictionary to be reverse mapped :return: inverse mapped dict """ return {v: k for k, v in dictionary.items()}
bigcode/self-oss-instruct-sc2-concepts
import re def IsValidFolderForType(path, component_type): """Checks a folder is named correctly and in a valid tree for component type. Args: path: a relative path from ontology root with no leading or trailing slashes. Path should be the top level for the component. component_type: the base_lib.ComponentType that this folder is for. Returns: True if the path is valid. """ m = re.match(r'(\w*)[/\\]?{0}'.format(component_type.value), path) if m is None: return False return True
bigcode/self-oss-instruct-sc2-concepts
def convert_021_to_022(cfg): """Convert rev 0.21 to 0.22 The rev 0.22 only affected the fuzzy logic methods. The membership shape is now explicit so that the user has the freedom to choose alternatives. """ assert ("revision" in cfg) and (cfg["revision"] == "0.21") cfg["revision"] = 0.22 for v in cfg["variables"]: procedures = [f for f in cfg["variables"][v] if f in ("fuzzylogic", "morello2014")] for procedure in procedures: for o in cfg["variables"][v][procedure]["output"]: f_cfg = cfg["variables"][v][procedure]["output"][o] if isinstance(f_cfg, list): if (o == "high") and (len(f_cfg) == 2): f_cfg = {"type": "smf", "params": f_cfg} elif (len(f_cfg) == 3): f_cfg = {"type": "trimf", "params": f_cfg} else: assert (False), "Can't guess membership shape" cfg["variables"][v][procedure]["output"][o] = f_cfg for f in cfg["variables"][v][procedure]["features"]: f_cfg = cfg["variables"][v][procedure]["features"][f] if ("low" in f_cfg) and (isinstance(f_cfg["low"], list)): if len(f_cfg["low"]) == 2: f_cfg["low"] = {"type": "zmf", "params": f_cfg["low"]} elif len(f_cfg["low"]) == 3: f_cfg["low"] = {"type": "trimf", "params": f_cfg["low"]} else: assert False, "Can't guess membership shape" if ("medium" in f_cfg) and (isinstance(f_cfg["medium"], list)): assert (len(f_cfg["medium"]) == 4), "Can't guess membership shape" f_cfg["medium"] = {"type": "trapmf", "params": f_cfg["medium"]} if ("high" in f_cfg) and (isinstance(f_cfg["high"], list)): assert (len(f_cfg["high"]) == 2), "Can't guess membership shape" f_cfg["high"] = {"type": "smf", "params": f_cfg["high"]} return cfg
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def filter_tests(tests, filters): """Returns a filtered list of tests to run. The test-filtering semantics are documented in https://bit.ly/chromium-test-runner-api and https://bit.ly/chromium-test-list-format, but are as follows: Each filter is a list of glob expressions, with each expression optionally prefixed by a "-". If the glob starts with a "-", it is a negative glob, otherwise it is a positive glob. A test passes the filter if and only if it is explicitly matched by at least one positive glob and no negative globs, or if there are no positive globs and it is not matched by any negative globs. Globbing is fairly limited; "?" is not allowed, and "*" must only appear at the end of the glob. If multiple globs match a test, the longest match wins. If both globs are the same length, an error is raised. A test will be run only if it passes every filter. """ def glob_sort_key(k): if k and k[0] == '-': return (len(k[1:]), k[1:]) else: return (len(k), k) for globs in filters: include_by_default = all(glob.startswith('-') for glob in globs) filtered_tests = [] for test in tests: include = include_by_default for glob in sorted(globs, key=glob_sort_key): if (glob.startswith('-') and not glob[1:]) or not glob: raise ValueError('Empty glob filter "%s"' % (glob, )) if '*' in glob[:-1]: raise ValueError( 'Bad test filter "%s" specified; ' 'wildcards are only allowed at the end' % (glob, )) if glob.startswith('-') and glob[1:] in globs: raise ValueError('Both "%s" and "%s" specified in test ' 'filter' % (glob, glob[1:])) if glob.startswith('-'): include = include and not fnmatch.fnmatch(test, glob[1:]) else: include = include or fnmatch.fnmatch(test, glob) if include: filtered_tests.append(test) tests = filtered_tests return tests
bigcode/self-oss-instruct-sc2-concepts
def get_all_descendants(root, children_map): """ Returns all descendants in the tree of a given root node, recursively visiting them based on the map from parents to children. """ return {root}.union( *[get_all_descendants(child, children_map) for child in children_map.get(root, [])] )
bigcode/self-oss-instruct-sc2-concepts
import time def curr_time() -> int: """Return the current time in ms.""" return int(time.perf_counter() * 1000)
bigcode/self-oss-instruct-sc2-concepts
def team_game_result(team, game): """Return the final result of the game as it relates to the team""" if game.winner == team: return "Win" elif game.winner and game.winner != team: return "Lose" elif game.home_team_score > 0: return "Tie" else: return "Scoreless Tie"
bigcode/self-oss-instruct-sc2-concepts
def get_assay_collections(assays, irods_backend): """Return a list of all assay collection names.""" return [irods_backend.get_path(a) for a in assays]
bigcode/self-oss-instruct-sc2-concepts
def fact(n): """ Factorial function :arg n: Number :returns: factorial of n """ if n == 0: return 1 return n * fact(n - 1)
bigcode/self-oss-instruct-sc2-concepts
def has_no_overlap(r1, r2): """Returns True if the two reads overlap. """ r1_start, r1_end = r1.reference_start, r1.reference_end r2_start, r2_end = r2.reference_start, r2.reference_end return (r2_end <= r1_start) or (r1_end <= r2_start)
bigcode/self-oss-instruct-sc2-concepts
def pick(*args): """ Returns the first non None value of the passed in values :param args: :return: """ for item in args: if item is not None: return item return None
bigcode/self-oss-instruct-sc2-concepts
def get_dataframe_name(s): """ Split dataframe and variable name from dataframe form field names (e.g. "___<var_name>___<dataframe_name>__"). Args: s (str): The string Returns: 2-tuple<str>: The name of the variable and name of the dataframe. False if not a properly formatted string. """ # Return tuple with variable_name, and dataframe_name if the type is dataframe. if s[-2:] == "__": s = s[:-2] dataframe_name = s.split("___")[-1] variable_name = s.split("___")[0] return variable_name, dataframe_name else: return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Any def count_bool(blist: Iterable[Any]) -> int: """ Counts the number of "truthy" members of the input list. Args: blist: list of booleans or other truthy/falsy things Returns: number of truthy items """ return sum([1 if x else 0 for x in blist])
bigcode/self-oss-instruct-sc2-concepts
import re def WrapWords(textlist, size, joiner='\n'): """Insert breaks into the listed strings at specified width. Args: textlist: a list of text strings size: width of reformated strings joiner: text to insert at break. eg. '\n ' to add an indent. Returns: list of strings """ # \S*? is a non greedy match to collect words of len > size # .{1,%d} collects words and spaces up to size in length. # (?:\s|\Z) ensures that we break on spaces or at end of string. rval = [] linelength_re = re.compile(r'(\S*?.{1,%d}(?:\s|\Z))' % size) for index in range(len(textlist)): if len(textlist[index]) > size: # insert joiner into the string at appropriate places. textlist[index] = joiner.join(linelength_re.findall(textlist[index])) # avoid empty comment lines rval.extend(x.strip() for x in textlist[index].strip().split(joiner) if x) return rval
bigcode/self-oss-instruct-sc2-concepts
def _format_param_value(key, value): """Wraps string values in quotes, and returns as 'key=value'. """ if isinstance(value, str): value = "'{}'".format(value) return "{}={}".format(key, value)
bigcode/self-oss-instruct-sc2-concepts
def echo_args(*args, **kwargs): """Returns a dict containng all positional and keyword arguments. The dict has keys ``"args"`` and ``"kwargs"``, corresponding to positional and keyword arguments respectively. :param *args: Positional arguments :param **kwargs: Keyword arguments :rtype: dict """ return {"args": args, "kwargs": kwargs}
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def resolve_import(import_: str, location: str, file: Path) -> str: """Resolve potentially relative import inside a package.""" if not import_.startswith('.'): return import_ import_parts = import_.split('.') up_levels = len([p for p in import_parts if p == '']) import_down = import_parts[up_levels:] if file.stem == '__init__': up_levels -= 1 location_parts = location.split('.') # up_levels can be 0 location_parts = location_parts[:-up_levels or None] return '.'.join(location_parts + import_down)
bigcode/self-oss-instruct-sc2-concepts
def time2int(float_time): """ Convert time from float (seconds) to int (nanoseconds). """ int_time = int(float_time * 10000000) return int_time
bigcode/self-oss-instruct-sc2-concepts
def fp_rate(FP, neg): """ Gets false positive rate. :param: FP: Number of false positives :type FP: `int` :param: neg: Number of negative labels :type neg: `int` :return: false positive rate :rtype: `float` """ if neg == 0: return 0 else: return FP / neg
bigcode/self-oss-instruct-sc2-concepts
def cmd_automation_event_lost(msg): """ (From protocol docs) Panel's automation buffer has overflowed. Automation modules should respond to this with request for Dynamic Data Refresh and Full Equipment List Request. """ return { }
bigcode/self-oss-instruct-sc2-concepts
def columns_to_nd(array2reshape, layers, rows, columns): """ Reshapes an array from columns layout to [n layers x rows x columns] """ if layers == 1: return array2reshape.reshape(columns, rows).T else: return array2reshape.T.reshape(layers, rows, columns)
bigcode/self-oss-instruct-sc2-concepts
def convert_none_type_object_to_empty_string(my_object): """ replace noneType objects with an empty string. Else return the object. """ return ('' if my_object is None else my_object)
bigcode/self-oss-instruct-sc2-concepts
import re def is_weight(word): """ is_weight() Purpose: Checks if word is a weight. @param word. A string. @return the matched object if it is a weight, otherwise None. >>> is_weight('1mg') is not None True >>> is_weight('10 g') is not None True >>> is_weight('78 mcg') is not None True >>> is_weight('10000 milligrams') is not None True >>> is_weight('14 grams') is not None True >>> is_weight('-10 g') is not None False >>> is_weight('grams') is not None True """ regex = r"^[0-9]*( )?(mg|g|mcg|milligrams|grams)$" return re.search(regex, word)
bigcode/self-oss-instruct-sc2-concepts
import re def get_locus_info(locus): """ Returns chrom, start and stop from locus string. Enforces standardization of how locus is represented. chrom:start_stop (start and stop should be ints or 'None') """ chrom, start_stop = locus.split(':') if chrom == 'None': chrom = None start, stop = re.split("\.\.|-", start_stop) if start == 'None': start = None else: start = int(float(start)) if stop == 'None': stop = None else: stop = int(float(stop)) return (str(chrom), start, stop)
bigcode/self-oss-instruct-sc2-concepts
def gameboard(level): """ This function will generate a gameboard, determined by the level size parameter. To keep the rows equivalent for both the user and the player, the board_size is guarenteed to be a multiple of two. Parameters: ----------- level: required parameter. Level determines the size of the gameboard. """ #To keep the number of rows symmetrical, we need to always increase the board size by a factor of 2 board_size = 10 + level * 2 board = [] #Create each row of the gameboard by iterating through its size. for row_index in range(1,board_size + 1): #for half of the genereated rows, denote column entries with periods. #for the other half, user asterisks. if row_index <= board_size / 2: board.append(["."] * board_size) else: board.append(["*"] * board_size) return(board)
bigcode/self-oss-instruct-sc2-concepts
import time def convert_time(longTime): """ Ignore time of day to help with grouping contributions by day. 2018-01-03 00:00:00 --> 2018-01-03 """ try: t = time.strptime(longTime, "%Y-%m-%d %H:%M:%S") except ValueError: return longTime ret = time.strftime( "%Y-%m-%d", t) return ret
bigcode/self-oss-instruct-sc2-concepts
def computeRR(self): """ Compute the rectangularity ratio (RR) of the max-tree nodes. RR is defined as the area (volume) of a connected component divided by the area (volume) of its bounding-box. """ xmin,xmax = self.node_array[6,:], self.node_array[7,:] + 1 ymin,ymax = self.node_array[9,:], self.node_array[10,:] + 1 area = self.node_array[3,:] if self.node_index.ndim == 2: return 1.0*area/((xmax-xmin)*(ymax-ymin)) else: zmin,zmax = self.node_array[12,:], self.node_array[13,:] + 1 return 1.0*area/((xmax-xmin)*(ymax-ymin)*(zmax-zmin))
bigcode/self-oss-instruct-sc2-concepts
def shape3d_to_size2d(shape, axis): """Turn a 3d shape (z, y, x) into a local (x', y', z'), where z' represents the dimension indicated by axis. """ shape = list(shape) axis_value = shape.pop(axis) size = list(reversed(shape)) size.append(axis_value) return tuple(size)
bigcode/self-oss-instruct-sc2-concepts
def orsample(df): """ Return the bitwise-OR of every value in the data frame. >>> orsample(empty) 0 >>> result = 1 | 3 | 5 | 6 | 8 >>> assert result == orsample(sample) """ if len(df) == 0: return 0 result = 0 for val in df.iloc[::, 0]: if val > 0: result |= int(val) return result
bigcode/self-oss-instruct-sc2-concepts
def camels_to_move(camel_dict, space, height): """Getting information about camels that need to move Parameters ---------- camel_dict : nested dict Dictionary with current camel positions space : int Space the camel is on height : int Height of the camel Returns ------- min_height_movers : int The minimum height of the camels that are moving num_movers : int The number of camels moving movers : list List of camels that are moving """ min_height_movers = 10000 num_movers = 0 movers = [] for key, val in camel_dict.items(): if val["space"] == space and val["height"] >= height: if val["height"] < min_height_movers: min_height_movers = val["height"] num_movers += 1 movers.append(key) return min_height_movers, num_movers, movers
bigcode/self-oss-instruct-sc2-concepts
def make_feasible(x_0, c): """ Returns a feasible x with respect to the constraints g_3, g_4, g_5, and g_6. :param np.array x_0: (n,) Initial, infeasible point. :param dict c: Constants defining the constraints. :return np.array: (n,) Initial, feasible point. Notes: - x_0 should follow: x0 = [200000, 355, 1, 1, 1, 1] for one backstress - x_0 should follow: x0 = [200000, 355, 1, 1, 1, rho_gamma_12_inf, 1, 1] for two backstresses """ n_backstresses = int((len(x_0) - 4) // 2) # Get the average of the bounds rho_yield_avg = 0.5 * (c['rho_yield_inf'] + c['rho_yield_sup']) rho_iso_avg = 0.5 * (c['rho_iso_inf'] + c['rho_iso_sup']) rho_gamma_avg = 0.5 * (c['rho_gamma_inf'] + c['rho_gamma_sup']) # Calculate the feasible set gamma2_0 = 1. / rho_gamma_avg * x_0[5] c1_0 = -x_0[5] * (-1. + rho_iso_avg) * (-1 + rho_yield_avg) * x_0[1] q_inf_0 = -c1_0 * rho_iso_avg / (x_0[5] * (-1. + rho_iso_avg)) b_0 = 1. / rho_gamma_avg * x_0[5] if n_backstresses == 2: x_0[[2, 3, 4, 7]] = [q_inf_0, b_0, c1_0, gamma2_0] elif n_backstresses == 1: x_0[[2, 3, 4]] = [q_inf_0, b_0, c1_0] return x_0
bigcode/self-oss-instruct-sc2-concepts
def binary_sum(S, start, stop): """Return the sum of the numbers in implicit slice S[start:stop].""" if start >= stop: # zero elemetns in slice return 0 elif start == stop - 1: return S[start] # one element in slice else: # two or more elements in slice mid = (start + stop) // 2 return binary_sum(S, start, mid) + binary_sum(S, mid, stop)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def gen_string(i: int, base: int, digits: List[str]): """Returns a string representation of an integer given the list of digits. Args: i (int): The integer to generate base (int): The base representation of the number. (based on the length of the list) digits (int): The list of digits to use. """ num_string = "" while i > 0: # Prepend the digit num_string = digits[i % base] + num_string # Effectively right shifting the number (dividing by the base) i //= base return num_string
bigcode/self-oss-instruct-sc2-concepts
import math def round_up_to_multiple(x: int, base: int) -> int: """ Round a positive integer up to the nearest multiple of given base number For example: 12 -> 15, with base = 5 """ return base * math.ceil(x / base)
bigcode/self-oss-instruct-sc2-concepts
def module_name_join(names): """Joins names with '.' Args: names (iterable): list of strings to join Returns: str: module name """ return '.'.join(names)
bigcode/self-oss-instruct-sc2-concepts
def _calculate_texture_sim(ri, rj): """ Calculate texture similarity using histogram intersection """ return sum([min(a, b) for a, b in zip(ri["texture_hist"], rj["texture_hist"])])
bigcode/self-oss-instruct-sc2-concepts
def pp_value(TP, FP): """ Gets positive predictive value, or precision. :param: TP: Number of true positives :type TP: `int` :param: FP: Number of false positives :type FP: `int` :return: positive predictive value :rtype: `float` """ if TP == 0 and FP == 0: return 0 else: return TP / (TP + FP)
bigcode/self-oss-instruct-sc2-concepts
def _no_pending_images(images): """If there are any images not in a steady state, don't cache""" for image in images: if image.status not in ('active', 'deleted', 'killed'): return False return True
bigcode/self-oss-instruct-sc2-concepts
def get_data(fname: str) -> list: """ Read the data file into a list. """ with open(fname) as f: return [int(line) for line in f]
bigcode/self-oss-instruct-sc2-concepts
def format_skills(text: str, ents: list) -> list: """ Get the list of skills according to the HrFlow.ai Job format @param text: text description of the job @param ents: list of entities in the text @return: list of skills """ skills = [{ "name": text[ent["start"]:ent["end"]].lower(), "value": None, "type": "hard" if ent["label"] == "HardSkill" else "soft"} for ent in ents if ent["label"].endswith("Skill")] return list({v["name"]:v for v in skills}.values())
bigcode/self-oss-instruct-sc2-concepts
import csv def write_csv(f, extract, fields=None): """ Writers extract to file handle Parameters __________ f : file handle (string mode) extract: list of dicts fields: list of str Field names to include in CSV. Returns _______ f : file handle (string mode) """ keys = fields if fields is not None else extract[0].keys() dict_writer = csv.DictWriter(f, keys, extrasaction='ignore') dict_writer.writeheader() dict_writer.writerows(extract) return f
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _replace_with(items: List[int], value: int) -> List[int]: """Replaces all values in items with value (in-place).""" length = len(items) del items[:] items.extend(length * [value]) return items
bigcode/self-oss-instruct-sc2-concepts
import requests def token(code, redirect_uri, client_id, client_secret): """Generates access token used to call Spotify API Args: code (str): Authorization code used to generate token redirect_uri (str): Allowed redirect URL set in Spotify's developer dashboard client_id (str): Application's id needed for OAuth 2.0 client_secret (str): Application's secret needed for OAuth 2.0 Returns: token (str): Access token for Spotify API See: https://developer.spotify.com/documentation/general/guides/authorization-guide/ """ params = { "grant_type": "authorization_code", "client_id": client_id, "client_secret": client_secret, "code": code, "redirect_uri": redirect_uri } return requests.post(url='https://accounts.spotify.com/api/token', data=params).json()['access_token']
bigcode/self-oss-instruct-sc2-concepts
import torch def broadcast_backward(input, shape): """Sum a tensor across dimensions that have been broadcasted. Parameters ---------- input : tensor Tensor with broadcasted shape. shape : tuple[int] Original shape. Returns ------- output : tensor with shape `shape` """ input_shape = input.shape dim = len(input_shape) for i, s in enumerate(reversed(shape)): dim = len(input_shape) - i - 1 if s != input_shape[dim]: if s == 1: input = torch.sum(input, dim=dim, keepdim=True) else: raise ValueError('Shapes not compatible for broadcast: ' '{} and {}'.format(tuple(input_shape), tuple(shape))) if dim > 0: input = torch.sum(input, dim=list(range(dim)), keepdim=False) return input
bigcode/self-oss-instruct-sc2-concepts
def _getrawimagelist(glance_client): """Helper function that returns objects as dictionary. We need this function because we use Pool to implement a timeout and the original results is not pickable. :param glance_client: the glance client :return: a list of images (every image is a dictionary) """ images = glance_client.images.list() return list(image.to_dict() for image in images)
bigcode/self-oss-instruct-sc2-concepts
import uuid def prefixUUID(pre: str = "PREFIX", max_length: int = 30) -> str: """ Create a unique name with a prefix and a UUID string :param pre: prefix to use :param max_length: max length of the unique name :return: unique name with the given prefix """ if len(pre) > max_length: raise ValueError(f"max_length is greater than the length of the prefix: {len(pre)}") uid_max = max_length - len(pre) uid = str(uuid.uuid4()).replace("-", "")[:uid_max] if pre in ["", " ", None]: return f"{uid}"[:max_length] return f"{pre}-{uid}"[:max_length]
bigcode/self-oss-instruct-sc2-concepts
import re def _make_safe_id_component(idstring): """Make a string safe for including in an id attribute. The HTML spec says that id attributes 'must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".")'. These regexps are slightly over-zealous, in that they remove colons and periods unnecessarily. Whitespace is transformed into underscores, and then anything which is not a hyphen or a character that matches \w (alphanumerics and underscore) is removed. """ # Transform all whitespace to underscore idstring = re.sub(r'\s', "_", '%s' % idstring) # Remove everything that is not a hyphen or a member of \w idstring = re.sub(r'(?!-)\W', "", idstring).lower() return idstring
bigcode/self-oss-instruct-sc2-concepts
def is_pickup(df): """Return if vehicle is a pickup truck, per NHTSA convention.""" yr = df['YEAR'] body = df['BODY_TYP'] return ((yr.between(1975, 1981) & (body == 50)) | (yr.between(1982, 1990) & body.isin([50, 51])) | ((1991 <= yr) & body.between(30, 39)))
bigcode/self-oss-instruct-sc2-concepts
def _num_items_2_heatmap_one_day_figsize(n): """ uses linear regression model to infer adequate figsize from the number of items Data used for training: X = [2,4,6,10,15,20,30,40,50,60] y = [[10,1],[10,2],[10,3],[10,4],[10,6],[10,8],[10,10],[10,12],[10,15],[10,17]] Parameters ---------- n : int number of items Returns ------- (w,h) : tuple the width and the height of the figure """ w = 10 h = 0.27082*n + 1.38153 return (int(w), int(h))
bigcode/self-oss-instruct-sc2-concepts