seed
stringlengths
1
14k
source
stringclasses
2 values
import time import hmac import hashlib def verify_request( *, timestamp: str, signature: str, request_data: bytes, signing_secret: str ) -> bool: """ This function validates the received using the process described https://api.slack.com/docs/verifying-requests-from-slack and using ...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def bytes_to_int(bindata): """Convert a sequence of bytes into a number""" return reduce(lambda x,y: (x<<8) | y, map(ord,bindata), 0)
bigcode/self-oss-instruct-sc2-concepts
import re def word_filter(word): """ The filter used for deleting the noisy words in changed code. Here is the method: 1. Delete character except for digit, alphabet, '_'. 2. the word shouldn't be all digit. 3. the length should large than 2. Args: word Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import json def get(event, context): """Handle the GET request and return the full lambda request event""" return { "statusCode": 200, "body": json.dumps(event) }
bigcode/self-oss-instruct-sc2-concepts
import importlib def import_model(type_module, type_name): """ :param str type_module: :param str type_name: :return: Model type :rtype: type :raise ImportError: When the model cannot be found. """ try: mod = importlib.import_module(type_module) except ImportError as e: ...
bigcode/self-oss-instruct-sc2-concepts
import re def float_from_str(text): """ Remove uncertainty brackets from strings and return the float. """ return float(re.sub("\(.+\)", "", text))
bigcode/self-oss-instruct-sc2-concepts
import string def capwords(value, sep=None): """ Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a sin...
bigcode/self-oss-instruct-sc2-concepts
def filter_OD(origins, destinations): """ takes lists of origins and destinations in (1D notation) and returns list of tuples with OD coorinates """ if len(origins) == len(destinations): return list(zip(origins, destinations)) else: return []
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def do_instruction(current_position: int, accumulator_value: int, instruction: int, instruction_value: int) -> Tuple[int, int]: """Perform instruction.""" if instruction == 0: current_position += 1 elif instruction =...
bigcode/self-oss-instruct-sc2-concepts
def get_vertex_names_from_indices(mesh, indices): """ Returns a list of vertex names from a given list of face indices :param mesh: str :param indices: list(int) :return: list(str) """ found_vertex_names = list() for index in indices: vertex_name = '{}.vtx[{}]'.format(mesh, inde...
bigcode/self-oss-instruct-sc2-concepts
def add_articles_from_xml(thread, xml_root): """Helper function to create Article objects from XML input and add them to a Thread object.""" added_items = False for item in xml_root.find('articles').findall('article'): data = { 'id': int(item.attrib['id']), 'username': item....
bigcode/self-oss-instruct-sc2-concepts
import base64 def decode(payload): """ https://en.wikipedia.org/wiki/Base64#URL_applications modified Base64 for URL variants exist, where the + and / characters of standard Base64 are respectively replaced by - and _ """ variant = payload.replace('-', '+').replace('_', '/') return base64....
bigcode/self-oss-instruct-sc2-concepts
def BuildInstanceConfigOperationTypeFilter(op_type): """Builds the filter for the different instance config operation metadata types.""" if op_type is None: return '' base_string = 'metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.' if op_type == 'INSTANCE_CONFIG_CREATE': return base...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def _parse_publishing_date(string): """ Parses the publishing date string and returns the publishing date as datetime. Input example (without quotes): "Wed, 09 Nov 2016 17:11:56 +0100" """ return datetime.strptime(string,"%a, %d %b %Y %H:%M:%S +0100")
bigcode/self-oss-instruct-sc2-concepts
def multiply(k, v1): """Returns the k*v1 where k is multiplied by each element in v1. Args: k (float): scale factor. v1 (iterable): a vector in iterable form. Returns: iterable: the resultant vector. """ newIterable = [k * i for i in v1] return tuple(newIterable) if typ...
bigcode/self-oss-instruct-sc2-concepts
import string def is_valid_sha1(sha1: str) -> bool: """True iff sha1 is a valid 40-character SHA1 hex string.""" if sha1 is None or len(sha1) != 40: return False return set(sha1).issubset(string.hexdigits)
bigcode/self-oss-instruct-sc2-concepts
def _is_projective(parse): """ Is the parse tree projective? Returns -------- projective : bool True if a projective tree. """ for m, h in enumerate(parse): for m2, h2 in enumerate(parse): if m2 == m: continue if m < h: i...
bigcode/self-oss-instruct-sc2-concepts
import torch def safe_power(x, exponent, *, epsilon=1e-6): """ Takes the power of each element in input with exponent and returns a tensor with the result. This is a safer version of ``torch.pow`` (``out = x ** exponent``), which avoids: 1. NaN/imaginary output when ``x < 0`` and exponent has a frac...
bigcode/self-oss-instruct-sc2-concepts
def fattr(key, value): """Decorator for function attributes >>> @fattr('key', 42) ... def f(): ... pass >>> f.key 42 """ def wrapper(fn): setattr(fn, key, value) return fn return wrapper
bigcode/self-oss-instruct-sc2-concepts
import pickle def unpickle_from_disk(filename): """Unpickle an object from disk. Requires a complete filename Passes Exception if file could not be loaded. """ # Warning: only using 'r' or 'w' can result in EOFError when unpickling! try: with open(filename, "rb") as pickle_file...
bigcode/self-oss-instruct-sc2-concepts
def merge_intervals(intervals): """ Merge intervals in the form of a list. """ if intervals is None: return None intervals.sort(key=lambda i: i[0]) out = [intervals.pop(0)] for i in intervals: if out[-1][-1] >= i[0]: out[-1][-1] = max(out[-1][-1], i[-1]) else: ...
bigcode/self-oss-instruct-sc2-concepts
def _check_file(f, columns): """Return shell commands for testing file 'f'.""" # We write information to stdout. It will show up in logs, so that the user # knows what happened if the test fails. return """ echo Testing that {file} has at most {columns} columns... grep -E '^.{{{columns}}}' {path} && err=1 echo ...
bigcode/self-oss-instruct-sc2-concepts
def find_if(cond, seq): """ Return the first x in seq such that cond(x) holds, if there is one. Otherwise return None. """ for x in seq: if cond(x): return x return None
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def _list_to_dict(items): """ Convert a list of dicts to a dict with the keys & values aggregated >>> _list_to_dict([ ... OrderedDict([('x', 1), ('y', 10)]), ... OrderedDict([('x', 2), ('y', 20)]), ... OrderedDict([('x', 3), ('y', 30)]), ... ]) O...
bigcode/self-oss-instruct-sc2-concepts
def check(product, data): """Check if product does not exist in the data""" if type(data) == dict: data = data.values() for d in data: if product == d: return False return True
bigcode/self-oss-instruct-sc2-concepts
def _parse_cal_product(cal_product): """Split `cal_product` into `cal_stream` and `product_type` parts.""" fields = cal_product.rsplit('.', 1) if len(fields) != 2: raise ValueError(f'Calibration product {cal_product} is not in the format ' '<cal_stream>.<product_type>') ...
bigcode/self-oss-instruct-sc2-concepts
def largest(a, b): """ This function takes two numbers to determine which one is larger """ if a > b: larger = a else: larger = b return larger
bigcode/self-oss-instruct-sc2-concepts
def extend_range(min_max, extend_ratio=.2): """Symmetrically extend the range given by the `min_max` pair. The new range will be 1 + `extend_ratio` larger than the original range. """ mme = (min_max[1] - min_max[0]) * extend_ratio / 2 return (min_max[0] - mme, min_max[1] + mme)
bigcode/self-oss-instruct-sc2-concepts
def build_risk_dataframe(financial_annual_overview): """Build risk dataframe Notes: Copies financial_annual_overview Args: financial_annual_overview (dataframe): An annual overview of financial data Returns: risk_dataframe (dataframe): An instance of a a...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import struct def bytes_to_shortint(byteStream: bytes) -> Tuple[int]: """Converts 2 bytes to a short integer""" # Ignore this in typing, as the 'H' will guarantee ints are returned return struct.unpack('H', byteStream)
bigcode/self-oss-instruct-sc2-concepts
def make_transparent(img, bg=(255, 255, 255, 255)): """Given a PIL image, makes the specified background color transparent.""" img = img.convert("RGBA") clear = bg[0:3]+(0,) pixdata = img.load() width, height = img.size for y in range(height): for x in range(width): if pixda...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def get_words(list_name: str): """ Reads the given word list from file into a list of capitalized words """ resource_package = __name__ resource_path = "/".join(("data", f"{list_name}.txt")) word_list = pkg_resources.resource_string(resource_package, resource_path) wor...
bigcode/self-oss-instruct-sc2-concepts
def tree_prec_to_adj(prec, root=0): """Transforms a tree given as predecessor table into adjacency list form :param prec: predecessor table representing a tree, prec[u] == v iff u is descendant of v, except for the root where prec[root] == root :param root: root vertex of the tree :ret...
bigcode/self-oss-instruct-sc2-concepts
def minutesToHours(minutes): """ (number) -> float convert input minutes to hours; return hours >>> minutesToHours(60) 1.0 >>> minutesToHours(90) 1.5 >>>minutesToHours(0) 0.0 """ hours = minutes / 60 hours = round(hours, 2) return hours
bigcode/self-oss-instruct-sc2-concepts
def url_to_be(url): """An expectation for checking the current url. url is the expected url, which must be an exact match returns True if the url matches, false otherwise.""" def _predicate(driver): return url == driver.current_url return _predicate
bigcode/self-oss-instruct-sc2-concepts
def _get_ordered_keys(rows, column_index): """ Get ordered keys from rows, given the key column index. """ return [r[column_index] for r in rows]
bigcode/self-oss-instruct-sc2-concepts
def _older_than(number, unit): """ Returns a query item matching messages older than a time period. Args: number (int): The number of units of time of the period. unit (str): The unit of time: "day", "month", or "year". Returns: The query string. """ return f"older_th...
bigcode/self-oss-instruct-sc2-concepts
import fnmatch from pathlib import Path def generate_lists_of_filepaths_and_filenames(input_file_list: list): """For a list of added and modified files, generate the following: - A list of unique filepaths to cluster folders containing added/modified files - A set of all added/modified files matching the ...
bigcode/self-oss-instruct-sc2-concepts
def handle(string: str) -> str: """ >>> handle('https://github.com/user/repo') 'user/repo' >>> handle('user/repo') 'user/repo' >>> handle('') '' """ splt = string.split("/") return "/".join(splt[-2:] if len(splt) >= 2 else splt)
bigcode/self-oss-instruct-sc2-concepts
def proxy_result_as_dict(obj): """ Convert SQLAlchemy proxy result object to list of dictionary. """ return [{key: value for key, value in row.items()} for row in obj]
bigcode/self-oss-instruct-sc2-concepts
def write_env(env_dict, env_file): """ Write config vars to file :param env_dict: dict of config vars :param env_file: output file :return: was the write successful? """ content = ["{}={}".format(k, v) for k, v in env_dict.items()] written = True try: with open(env_file, 'w...
bigcode/self-oss-instruct-sc2-concepts
def get_image(camera): """Captures a single image from the camera and returns it in PIL format.""" data = camera.read() _, im = data return im
bigcode/self-oss-instruct-sc2-concepts
def _hashSymOpList(symops): """Return hash value for a sequence of `SymOp` objects. The symops are sorted so the results is independent of symops order. Parameters ---------- symops : sequence The sequence of `SymOp` objects to be hashed Returns ------- int The hash va...
bigcode/self-oss-instruct-sc2-concepts
def add_PDF_field_names(equiplist, type="NonEnc"): """Takes a list of items and their type and returns a dictionary with the items as values and the type followed by a sequential number (type0, type1, etc.) as keys. These are generally used to fill fields in a blank PDF, with keys corresponding to field...
bigcode/self-oss-instruct-sc2-concepts
def sclose(HDR): """input: HDR_TYPE HDR output: [-1, 0] Closes the according file. Returns 0 if successfull, -1 otherwise.""" if HDR.FILE.OPEN != 0: HDR.FILE.FID.close() HDR.FILE.FID = 0 HDR.FILE.OPEN = 0 return 0 return -1 # End of SCLOSE ########### # SREAD # ###########
bigcode/self-oss-instruct-sc2-concepts
import yaml def read_yaml_file(file_path): """Parses yaml. :param file_path: path to yaml file as a string :returns: deserialized file """ with open(file_path, 'r') as stream: data = yaml.safe_load(stream) or {} return data
bigcode/self-oss-instruct-sc2-concepts
def byte_to_string(byte): """ Converts an array of integer containing bytes into the equivalent string version :param byte: The array to process :return: The calculated string """ hex_string = "".join("%02x" % b for b in byte) return hex_string
bigcode/self-oss-instruct-sc2-concepts
import re def get_indent(str_): """ Find length of initial whitespace chars in `str_` """ # type: (str) -> int match = re.search(r'[^\s]|$', str_) if match: return match.start() else: return 0
bigcode/self-oss-instruct-sc2-concepts
def get_acph2_m2_min(m1: float) -> float: """ Get minimum value of m2 (second moment) for ACPH(2) fitting. According to [1], M2 has only lower bound since pow(CV, 2) should be greater or equal to 0.5. If m1 < 0, then `ValueError` is raised. Parameters ---------- m1 : float Retur...
bigcode/self-oss-instruct-sc2-concepts
def clamp(value, lower=None, upper=None): """ Returns value no lower than lower and no greater than upper. Use None to clamp in one direction only. """ if lower is not None: value = max(value, lower) if upper is not None: value = min(value, upper) return value
bigcode/self-oss-instruct-sc2-concepts
def _finish_plot(ax, names, legend_loc=None, no_info_message="No Information"): """show a message in the axes if there is no data (names is empty) optionally add a legend return Fase if names is empty, True otherwise""" if( not names ): ax.text(0.5,0.5, no_info_message, fon...
bigcode/self-oss-instruct-sc2-concepts
import json import fnmatch from pathlib import Path def cmpmanifests(manifest_path_1, manifest_path_2, patterns=None, ignore=None): """Bit-accuracy test between two manifests. Their format is {filepath: {md5, size_st}}""" with manifest_path_1.open() as f: manifest_1 = json.load(f) with manifest_path_2.ope...
bigcode/self-oss-instruct-sc2-concepts
import random def rand_uniform(a, b): """ Returns a sample from a uniform [a, b] distribution. """ return random.random() * (b - a) + a
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterator from typing import ByteString from typing import Any from typing import Union def hash_a_byte_str_iterator( bytes_iterator: Iterator[ByteString], hasher: Any, as_hex_str: bool = False ) -> Union[ByteString, str]: """ Get the hash digest of a binary string iterator. https:/...
bigcode/self-oss-instruct-sc2-concepts
def recursive_config_join(config1: dict, config2: dict) -> dict: """Recursively join 2 config objects, where config1 values override config2 values""" for key, value in config2.items(): if key not in config1: config1[key] = value elif isinstance(config1[key], dict) and isinstance(val...
bigcode/self-oss-instruct-sc2-concepts
def iterativeFactorial(num): """assumes num is a positive int returns an int, num! (the factorial of n) """ factorial = 1 while num > 0: factorial = factorial*num num -= 1 return factorial
bigcode/self-oss-instruct-sc2-concepts
def remove_code_parameter_from_uri(url): """ This removes the "code" parameter added by the first ORCID call if it is there, and trims off the trailing '/?' if it is there. """ return url.split("code")[0].strip("&").strip("/?")
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List from typing import Dict import time def get_dir_data(path: Path) -> List[Dict[str, str]]: """Returns list of files and folders in given directory sorted by type and by name. Parameters ---------- path : Path Path to directory which will be expl...
bigcode/self-oss-instruct-sc2-concepts
def decide_compiler(config): """确定使用的编译器 如果设置中使用的是clang,则使用设置中的编译器 否则使用默认的clang++ """ if 'clang'in config: return config else: return 'clang++'
bigcode/self-oss-instruct-sc2-concepts
def map_to_45(x): """ (y-y1)/(x-x1) = (y2-y1)/(x2-x1) ---> x1 = 1, x2 = 5, y1 = 1, y2 = 4.5 output = output_start + ((output_end - output_start) / (input_end - input_start)) * (input - input_start) """ input_start = 1 input_end = 5 output_start = 1 output_end = 4.5 if x >= 5: ...
bigcode/self-oss-instruct-sc2-concepts
import struct def read_unsigned_var_int(file_obj): """Read a value using the unsigned, variable int encoding.""" result = 0 shift = 0 while True: byte = struct.unpack(b"<B", file_obj.read(1))[0] result |= ((byte & 0x7F) << shift) if (byte & 0x80) == 0: break ...
bigcode/self-oss-instruct-sc2-concepts
def phrase(term: str) -> str: """ Format words to query results containing the desired phrase. :param term: A phrase that appears in that exact form. (e.q. phrase "Chicago Bulls" vs. words "Chicago" "Bulls") :return: String in the format google understands """ return '"{}"'.format(term)
bigcode/self-oss-instruct-sc2-concepts
def clear_tier_dropdown(_): """ whenever a new cluster is in focus reset the tier dropdown to empty again Parameters ---------- _ : str reactive trigger for the process Returns ------- str empty string """ return ''
bigcode/self-oss-instruct-sc2-concepts
import json def format_report(jsn): """ Given a JSON report, return a nicely formatted (i.e. with indentation) string. This should handle invalid JSON (as the JSON comes from the browser/user). We trust that Python's json library is secure, but if the JSON is invalid then we still want to ...
bigcode/self-oss-instruct-sc2-concepts
import json def readfile(filename): """ Read JSON from file and return dict """ try: with open(filename, 'r') as f: return json.load(f) except IOError: print('Error while reading from file')
bigcode/self-oss-instruct-sc2-concepts
def signed_leb128_encode(value: int) -> bytes: """Encode the given number as signed leb128 .. doctest:: >>> from ppci.utils.leb128 import signed_leb128_encode >>> signed_leb128_encode(-1337) b'\xc7u' """ data = [] while True: byte = value & 0x7F value >>= ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def generage_sha1(text: str) -> str: """Generate a sha1 hash string Args: text (str): Text to generate hash Returns: str: sha1 hash """ hash_object = hashlib.sha1(text.encode('utf-8')) hash_str = hash_object.hexdigest() return hash_str
bigcode/self-oss-instruct-sc2-concepts
def flatten_list(nested_list, list_types=(list, tuple), return_type=list): """Flatten `nested_list`. All the nested lists in `nested_list` will be flatten, and the elements in all these lists will be gathered together into one new list. Parameters ---------- nested_list : list | tuple ...
bigcode/self-oss-instruct-sc2-concepts
def encrypt(msg, a, b, k): """ encrypts message according to the formula l' = a * l + b mod k """ encrypted_message = "" for letter in msg: if letter == " ": encrypted_message += " " else: encrypted_letter_index = (a * (ord(letter) - ord('a')) + b) % k enc...
bigcode/self-oss-instruct-sc2-concepts
def decimal_to_base(n, base): """Convert decimal number to any base (2-16)""" chars = "0123456789ABCDEF" stack = [] is_negative = False if n < 0: n = abs(n) is_negative = True while n > 0: remainder = n % base stack.append(remainder) n = n // base ...
bigcode/self-oss-instruct-sc2-concepts
def split_output(cmd_output): """Function splits the output based on the presence of newline characters""" # Windows if '\r\n' in cmd_output: return cmd_output.strip('\r\n').split('\r\n') # Mac elif '\r' in cmd_output: return cmd_output.strip('\r').split('\r') # Unix elif ...
bigcode/self-oss-instruct-sc2-concepts
def _parse_bool(value): """Parse a boolean string "True" or "False". Example:: >>> _parse_bool("True") True >>> _parse_bool("False") False >>> _parse_bool("glorp") Traceback (most recent call last): ValueError: Expected 'True' or 'False' but got 'glorp' ...
bigcode/self-oss-instruct-sc2-concepts
import struct def one_byte_array(value): """ Convert Int to a one byte bytearray :param value: value 0-255 """ return bytearray(struct.pack(">B", value))
bigcode/self-oss-instruct-sc2-concepts
def get_column_widths(columns): """Get the width of each column in a list of lists. """ widths = [] for column in columns: widths.append(max([len(str(i)) for i in column])) return widths
bigcode/self-oss-instruct-sc2-concepts
def filter_arglist(args, defaults, bound_argnames): """ Filters a list of function argument nodes (``ast.arg``) and corresponding defaults to exclude all arguments with the names present in ``bound_arguments``. Returns a pair of new arguments and defaults. """ new_args = [] new_defaults ...
bigcode/self-oss-instruct-sc2-concepts
import string def clean_string(s): """Function that "cleans" a string by first stripping leading and trailing whitespace and then substituting an underscore for all other whitepace and punctuation. After that substitution is made, any consecutive occurrences of the underscore character are reduced to ...
bigcode/self-oss-instruct-sc2-concepts
def error_dict(error_message: str): """Return an error dictionary containing the error message""" return {"status": "error", "error": error_message}
bigcode/self-oss-instruct-sc2-concepts
import zipfile def listing(zip_path): """Get list of all the filepaths in a ZIP. Args: zip_path: path to the ZIP file Returns: a list of strings, the ZIP member filepaths Raises: any file i/o exceptions """ with zipfile.ZipFile(zip_path, "r") as zipf: return zipf.na...
bigcode/self-oss-instruct-sc2-concepts
import math def all_possible_combinations_counter(subset_size, set_size): """ Return a number (int) of all possible combinations of elements in size of a subset of a set. Parameters ------- subset_size: int Size of the subset. set_size: int ...
bigcode/self-oss-instruct-sc2-concepts
def read_weights(nnf_path): """ Format: c weights PW_1 NW_1 ... PW_n NW_n :param nnf_path: Path to NNF file :return: list of weights """ weight_str = None with open(nnf_path, "r") as ifile: for line in ifile.readlines(): if "c weights " in line: weight_str...
bigcode/self-oss-instruct-sc2-concepts
import uuid def validate_id_is_uuid(input_id, version=4): """Validates provided id is uuid4 format value. Returns true when provided id is a valid version 4 uuid otherwise returns False. This validation is to be used only for ids which are generated by barbican (e.g. not for keystone project_id) ...
bigcode/self-oss-instruct-sc2-concepts
import copy def with_base_config(base_config, extra_config): """Returns the given config dict merged with a base agent conf.""" config = copy.deepcopy(base_config) config.update(extra_config) return config
bigcode/self-oss-instruct-sc2-concepts
def get_subtext(soup): """Gets the subtext links from the given hacker news soup.""" subtext = soup.select(".subtext") return subtext
bigcode/self-oss-instruct-sc2-concepts
def players_in_tournament(t_body): """Get number of players in a tournament Args: t_body (element.tag) : tourn table body. Child of ResponsiveTable Returns: number of players """ players = t_body.find_all("tr", class_="Table__TR Table__even") if players is not None: ...
bigcode/self-oss-instruct-sc2-concepts
def PyEval_GetBuiltins(space): """Return a dictionary of the builtins in the current execution frame, or the interpreter of the thread state if no frame is currently executing.""" caller = space.getexecutioncontext().gettopframe_nohidden() if caller is not None: w_globals = caller.get_w_glob...
bigcode/self-oss-instruct-sc2-concepts
def map_hostname_info(hostname, nmap_store): """Map hostname if there is one to the database record.""" if hostname is not None: nmap_store["hostname"] = hostname.get('name') return nmap_store nmap_store["hostname"] = None return nmap_store
bigcode/self-oss-instruct-sc2-concepts
def sum_ascii_values(text: str) -> int: """Sum the ASCII values of the given text `text`.""" return sum(ord(character) for character in text)
bigcode/self-oss-instruct-sc2-concepts
from typing import MutableMapping from typing import Any def get_dict_item_with_dot(data: MutableMapping, name: str) -> Any: """Get a dict item using dot notation >>> get_dict_item_with_dot({'a': {'b': 42}}, 'a') {'b': 42} >>> get_dict_item_with_dot({'a': {'b': 42}}, 'a.b') 42 """ if not ...
bigcode/self-oss-instruct-sc2-concepts
def _has_exclude_patterns(name, exclude_patterns): """Checks if a string contains substrings that match patterns to exclude.""" for p in exclude_patterns: if p in name: return True return False
bigcode/self-oss-instruct-sc2-concepts
def max_multiple(divisor, bound): """ Finds the largest dividable integer that is lower than bound. :param divisor: positive integer. :param bound: positive integer. :return: the largest integer N, such that, N is divisible by divisor, N is less than or equal to bound, and N is greater ...
bigcode/self-oss-instruct-sc2-concepts
import json def get_count(json_filepath): """Reads the count from the JSON file and returns it""" with open(json_filepath) as json_file: data = json.load(json_file) try: return data["count"] except KeyError: return None
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup import six def _convert_toc(wiki_html): """Convert Table of Contents from mediawiki to markdown""" soup = BeautifulSoup(wiki_html, 'html.parser') for toc_div in soup.findAll('div', id='toc'): toc_div.replaceWith('[TOC]') return six.text_type(soup)
bigcode/self-oss-instruct-sc2-concepts
import re import logging def check_edge(graph, edge_label): """ Parameters ---------- graph : nx.DiGraph A graph. edge_label : str Edge label. Returns ------- int Counts how many edges have the property `label` that matches `edge_label`. """ edge_label...
bigcode/self-oss-instruct-sc2-concepts
def _str_to_bytes(s): """Convert str to bytes.""" if isinstance(s, str): return s.encode('utf-8', 'surrogatepass') return s
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def _pydantic_dataclass_from_dict(dict: dict, pydantic_dataclass_type) -> Any: """ Constructs a pydantic dataclass from a dict incl. other nested dataclasses. This allows simple de-serialization of pydentic dataclasses from json. :param dict: Dict containing all attributes and v...
bigcode/self-oss-instruct-sc2-concepts
import importlib def load_module(mod): """Load a python module.""" module = importlib.import_module(mod) print(module, mod) return module
bigcode/self-oss-instruct-sc2-concepts
def gcd(a, b): """Returns the greatest common divisor of a and b, using the Euclidean algorithm.""" if a <= 0 or b <= 0: raise ValueError('Arguments must be positive integers') while b != 0: tmp = b b = a % b a = tmp return a
bigcode/self-oss-instruct-sc2-concepts
def find_server(dbinstance, params): """ Find an existing service binding matching the given parameters. """ lookup_params = params.copy() for srv in dbinstance.servers: # Populating srv_params must be in sync with what lookup_target() # returns srv_params = {} for ...
bigcode/self-oss-instruct-sc2-concepts
def __is_global(lon, lat): """ check if coordinates belong to a global dataset Parameters ---------- lon : np.ndarray or xarray.DataArray lat : np.ndarray or xarray.DataArray Returns ------- bool """ if lon.max() - lon.min() > 350 and lat.max() - lat.min() > 170: re...
bigcode/self-oss-instruct-sc2-concepts
def correctPR(text): """ Remove the trailing space in the PR avlues. :param text: :return: corrected PR """ return text.replace(" ", "")
bigcode/self-oss-instruct-sc2-concepts