seed
stringlengths
1
14k
source
stringclasses
2 values
import re def __valid_word(word, stopword, language): """ Check if the word is in the stopword list Return a boolean word = string stopword = stopword object (cf stopwords.py) language = string (french or english) """ # print(word) # print(language) # print(word not in stopword...
bigcode/self-oss-instruct-sc2-concepts
def ignore_filter(topics): """filter topics starts with !""" result = [t for t in topics if not t['title'].startswith('!')] for topic in result: more_topics = topic.get('topics', []) topic['topics'] = ignore_filter(more_topics) return result
bigcode/self-oss-instruct-sc2-concepts
def point_in_rectangle(point, rectangle): """ Determine if the given point is inside the rectangle Args: point(tuple): tuple of points x and y rectangle Returns: bool: True if point in the rect, False otherwise """ left_sides = 0 for i in rang...
bigcode/self-oss-instruct-sc2-concepts
import math def get_conv_output_shape(in_shape, kernel, stride=1, padding=0, dilation=1, out_channels=32): """ infer output shape after 1 layer of conv reference: https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d """ _, h, w = in_shape out_h = math.floor( (h + 2 * padding - dilation...
bigcode/self-oss-instruct-sc2-concepts
import re def parsePWDResponse(response): """ Returns the path from a response to a PWD command. Responses typically look like:: 257 "/home/andrew" is current directory. For this example, I will return C{'/home/andrew'}. If I can't find the path, I return L{None}. """ match = r...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import json def get_unambiguous_roots(base_forms_file: str) -> Dict[str, Dict[str, str]]: """Get the list of words repleaceable with an unambiguous lemma. This is a dictionary having the ISO 3-letter code of each language as a key, and as values dictionaries mapping words with the...
bigcode/self-oss-instruct-sc2-concepts
import re def _convert_to_regex(input_format: str): """Return regex of input_format.""" return re.compile(input_format.replace("(", "\\(") .replace(")", "\\)") .replace("<artiste>", "(.+)") .replace("<track>", "(\\w+)") .r...
bigcode/self-oss-instruct-sc2-concepts
def which_one(iterable): """Index of the first True value in an iterable.""" it = enumerate(iterable) i, x = next(it) while not x: i, x = next(it) return i
bigcode/self-oss-instruct-sc2-concepts
import torch def rotation_from_axis(axis): """ Expects Bx1x3 axis Tensor The axis is x, y, z with the angle being norm(axis). Returns a Bx3x3 rotation matix tensor """ device = axis.device # Trick for batch_size broadcasting theta = torch.norm(axis, p=2, dim=2).view(-1, 1, 1) axis...
bigcode/self-oss-instruct-sc2-concepts
def get_number_of_verb(sentence_token): """Return number of verbs in sentence Args: sentence_token (tuple): contains length of sentence and list of all the token in sentence Returns: int: number of verb in sentence """ number_of_verb = 0 for word in sentence_token[1]: i...
bigcode/self-oss-instruct-sc2-concepts
def chunkify(files_list, chunksize=1000): """ Create a list of chunks. Each chunk is a list itself, with size `chunksize`. Arguments: files_list: list: A list of Path objects chunksize: int: Size of each chunk Return: chunks: list: A list of lists. Each nested list has size ...
bigcode/self-oss-instruct-sc2-concepts
def _trunk(port_data): """Return trunk for specific ifIndex. Args: port_data: Data dict related to the port Returns: trunk: True if port is in trunking mode """ # Initialize key variables trunk = False # Determine if trunk for Cisco devices if 'vlanTrunkPortDynamicSta...
bigcode/self-oss-instruct-sc2-concepts
def construct_index_dict(field_names, index_start=0): """This function will construct a dictionary used to retrieve indexes for cursors. :param - field_names - list of strings (field names) to load as keys into a dictionary :param - index_start - an int indicating the beginning index to start from (default ...
bigcode/self-oss-instruct-sc2-concepts
from typing import BinaryIO import hashlib def get_md5(f: BinaryIO) -> str: """Make an MD5 hash of the page's contents.""" BLOCKSIZE = 65536 hasher = hashlib.md5() buf = f.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = f.read(BLOCKSIZE) return hasher.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def create_json(sensor): """Simple function that creates a json object to return for each sensor Args as data: sensor object retrieved from MongoDB Returns: { Formatted sensor object as below } """ json_object = {'building': sensor.get('building'), ...
bigcode/self-oss-instruct-sc2-concepts
def contains(script, keywords): """Performs DFS on the script to determine if keyword exists.""" # The keyword must be the first item in a list. if type(script) != list or not script: return False if script[0] in keywords: return True # Iterate over all children. return any(co...
bigcode/self-oss-instruct-sc2-concepts
def dict_get(D, k1, k2, default = 0.0): """ Custom retrieval from nested dictionary. Get D[k1][k2] if it exists, otherwise default. """ if k1 in D and k2 in D[k1]: return D[k1][k2] else: return default
bigcode/self-oss-instruct-sc2-concepts
import requests def get_pokeapi_data(pokemon): """ Retrieve data on Pokemon from PokeAPI in JSON format. """ endpoint = 'http://pokeapi.co/api/v2/pokemon/' + pokemon r = requests.get(endpoint) r.raise_for_status() return r.json()
bigcode/self-oss-instruct-sc2-concepts
def parse_qstat_jobid(output, job_id): """Parse and return output of the qstat command run with options to obtain job status. :param output: output of the qstat command :type output: str :param job_id: allocation id or job step id :type job_id: str :return: status :rtype: str """ ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Any from typing import Optional def find_element_in_list( element_list: List[Dict[str, Any]], **fields ) -> Optional[Dict[str, Any]]: """ Find element with some fields in list of elements >>> element_list = [dict(n="a", v=2), dict(n="...
bigcode/self-oss-instruct-sc2-concepts
def scatter_props(event): """ Get information for a pick event on a PathCollection artist (usually created with ``scatter``). Parameters: ----------- event : PickEvent The pick event to process Returns: -------- A dict with keys: "c": The value of the color array at the point clicked. "s": Th...
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def validate_print_ip_address(ip_address): """Validates the given IP address and returns a printable version. For IPv4 addresses no changes are made, for IPv6 addresses brakets are added. Args: ip_address: IP address to validate as string. Returns: A printable ve...
bigcode/self-oss-instruct-sc2-concepts
def contains_any(str, set): """ Check whether sequence str contains ANY of the items in set. """ return 1 in [c in str for c in set]
bigcode/self-oss-instruct-sc2-concepts
def trajs_matmul(trajs, coeffs): """Right matrix multiply coefficients to all trajectories.""" result = [] for traj in trajs: result.append(traj @ coeffs) return result
bigcode/self-oss-instruct-sc2-concepts
def read_file(filename): """Read the given file and return a list of lines of text read from it.""" with open(filename, "r") as file: lines_list = file.readlines() return lines_list
bigcode/self-oss-instruct-sc2-concepts
def _listset(i): """create a list of unique values from iterable `i`, and return those as comma-separated string """ return ", ".join(list(set(i)))
bigcode/self-oss-instruct-sc2-concepts
def tolerance(dimension_mm, itg): """ Returns the tolerance in micrometers using ISO standard using the given dimension and ITG number """ return 10 ** ((itg - 1) / 5) * (0.45 * dimension_mm ** (1 / 3) + dimension_mm / 1000)
bigcode/self-oss-instruct-sc2-concepts
import copy def topological_sort(structure): """Does the topological sorting of the given structure. Args: structure: A 'list' of the nodes, following the format described in architecture_graph.py. Returns: A list of ordered indexes. """ structure = copy.deepcopy(structure) set_l = [] s...
bigcode/self-oss-instruct-sc2-concepts
def _unpadd_symetric(arrays, p, paddtype): """ Helper function to unpadd in an assymetric way arrays. Parameters ---------- arrays : np.ndarray or list of np.ndarray array or list of arrays to padd. p : int, length of padding. paddtype : ['left', 'right'], where to pl...
bigcode/self-oss-instruct-sc2-concepts
def define_plot_layout(mapside, plotzoom, expidx): """Establish the visual of the igraph plot Args: mapside(int): side size of the map plotzoom(int): zoom of the map expidx(int): experiment index Returns: dict: to be used by igraph.plot """ # Square of the center surrounded by rad...
bigcode/self-oss-instruct-sc2-concepts
def convert_flux_to_nanoJansky(flux, fluxmag0): """Convert the listed DM coadd-reported flux values to nanoJansky. Based on the given fluxmag0 value, which is AB mag = 0. Eventually we will get nJy from the final calibrated DRP processing. """ #pylint: disable=C0103 AB_mag_zp_wrt_Jansky = 8.90 ...
bigcode/self-oss-instruct-sc2-concepts
def filter_by_substance_composition( data_set, compositions_to_include, compositions_to_exclude ): """Filters the data set so that it only contains properties measured for substances of specified compositions. This method is similar to `filter_by_smiles`, however here we explicitly define the full ...
bigcode/self-oss-instruct-sc2-concepts
def ZonalStats(valueCollection, zoneCollection, statistic, scale = 10, tileScale = 16): """Computes zonal statistics across an image collection as a table. An output value is computed: 1) For every zone in the input zone collection. 2) For every image in the value collection. Keyword arguments...
bigcode/self-oss-instruct-sc2-concepts
def compute_average(grades): """ Computes the average of all the grades in the list Parameters: grades (list) Returns: the average (float) rounded up to one decimal """ average = round(sum(grades)/len(grades), 1) return average
bigcode/self-oss-instruct-sc2-concepts
def get_masks(tokens, max_seq_length): """Mask for padding""" if len(tokens)>max_seq_length: raise IndexError("Token length more than max seq length!") return [1]*len(tokens) + [0] * (max_seq_length - len(tokens))
bigcode/self-oss-instruct-sc2-concepts
def orientation(u, v, w): """Computes the orientation (+/-1) of a basis""" det = u.dot(v.cross(w)) if det >= 0: return +1 else: return -1
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def get_lyrics_soup(url): """ Get a BeautifulSoup4 representation of a url :param str url: URL to read :rtype: BeautifulSoup :return: BeautifulSoup4 object of the loaded url """ html_text = requests.get(url).text soup = BeautifulSoup(html...
bigcode/self-oss-instruct-sc2-concepts
import json def open_locale_file(fname): """Opens a locale file""" with open(fname) as json_file: return json.load(json_file)
bigcode/self-oss-instruct-sc2-concepts
def plsPredict(pls, X, realY): """Given a PLSR model pls, and independent variables X, predict Y, and calculated difference to realY """ predY = pls.predict(X) dY = realY - predY return predY, dY
bigcode/self-oss-instruct-sc2-concepts
import json def dumpJson(path: str, data: dict): """ Dump data to json path. Returns ------- `tuple(path or exception, True or False)` : First item in tuple is a path if dumping succeeds, else it's an exceptions. Same thing goes for the second tuple """ try: with open(pat...
bigcode/self-oss-instruct-sc2-concepts
import json def document_contents_differ(old, new, threshold=20): """Returns whether the two document contents differ sufficiently to merit a new backup.""" # In both the road and schedule file formats, the significant differences would occur in the # second level of the JSON object. if old == new: ...
bigcode/self-oss-instruct-sc2-concepts
def uuid(anon, obj, field, val): """ Returns a random uuid string """ return anon.faker.uuid(field=field)
bigcode/self-oss-instruct-sc2-concepts
def safe_eval(command, module, allowed): """ A wrapper for the python eval() function that enforces the use of a list of allowable commands and excludes python builtin functions. This enables the use of an eval statement to convert user string input into a function or method without it being readily...
bigcode/self-oss-instruct-sc2-concepts
def normalize( df, baseline = 0.1 ): """ Normalize all spectrum. :param df: The Pandas DataFrame to normalize. :param baseline: Baseline correction threshold or False for no correction. [Default: 0.1] :returns: The normalized DataFrame. """ df = df.copy() df /= df.max() if b...
bigcode/self-oss-instruct-sc2-concepts
import re def literals(choices, prefix="", suffix=""): """Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually. """ return "|".join(prefix+re.escape(c)+suffix for c in choices.split())
bigcode/self-oss-instruct-sc2-concepts
def get_underlying_type_name(parameter_type: str) -> str: """Get the underlying type name of the given type. Strip away information from type name like brackets for arrays, leading "struct ", etc. leaving just the underlying type name. """ return parameter_type.replace("struct ", "").replace("[]", ...
bigcode/self-oss-instruct-sc2-concepts
def round_time(time): """Round up or down time based on set break_point.""" minutes = time.minute if time.second < 30 else time.minute + 1 hours = time.hour break_point = 7 # minutes if minutes > 45 + break_point: hours += 1 minutes = 0 elif minutes > 30 + break_point: m...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import gzip def gzip_archive(directory: str, glob_pattern: str) -> None: """GZip files, deletes, and places results in nested '/archive' subdirectory""" filepath = Path(directory) archivepath = Path(directory) / "archive" files = [file for file in filepath.glob(glob_pattern) i...
bigcode/self-oss-instruct-sc2-concepts
import json def load_category_names(category_names_file): """ Load the category file names of flowers Parameters: category_names_file - path name (starting from app current working directory) including the filename and its extension Returns: catalog of flower classes and labels """ ...
bigcode/self-oss-instruct-sc2-concepts
def to_coverage(total_n_reads, species_abundance, read_length, genome_size): """Calculate the coverage of a genome in a metagenome given its size and abundance Args: total_n_reads (int): total amount of reads in the dataset species_abundance (float): abundance of the species, between 0 and ...
bigcode/self-oss-instruct-sc2-concepts
def get_targets_in_network_of_expansion(node_file): """ In the network of expansion, the targets are scored 1.00. This function gets the targets in the network by identifying the nodes with score 1. """ targets_in_network = set() with open(node_file, 'r') as node_fd: for line in node_fd:...
bigcode/self-oss-instruct-sc2-concepts
def get_title(obj, objid): """ Returns title value of the object with given ID. :param obj: Structure containing YAML object ( nested lists / dicts ). :param objid: YAML ID of given node. :return: Title of given ID. """ result = None if isinstance(obj, dict): for key, val in o...
bigcode/self-oss-instruct-sc2-concepts
import pytz def get_utc(dt): """ Converts datetime to UTC timezone More info: http://pytz.sourceforge.net/ """ return dt.replace(tzinfo=pytz.utc)
bigcode/self-oss-instruct-sc2-concepts
import random def rand_int(start=1, end=10, seed=None): """ Returns a random integer number between the start and end number. .. versionadded:: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. vers...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash(input: str): """ Function to hash a sentence Parameters ---------- input : str Input sentence to hash. Returns ------- n : int Hashed value of the sentence. """ t_value = input.encode("utf8") h = hashlib.sha256(t_value) n = int...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def format_with_optional_units(value: Any, units: str) -> str: """ Ex: > format_with_optional_units(25.0, "cm") # returns "25.0 cm" > format_with_optional_units(25.0, None) # returns "25.0" """ if units is None: return f"{value}" if units == "%": ret...
bigcode/self-oss-instruct-sc2-concepts
def get_variables(interface1, interface2, interface3): """Create and return a dictionary of test variables. :param interface1: Name of an interface. :param interface2: Name of an interface. :param interface3: Name of an interface. :type interface1: string :type interface2: string :type inte...
bigcode/self-oss-instruct-sc2-concepts
def add_host(data, host): """Make the image path absolute for those served by the server.""" for i in range(len(data)): data[i]['image'] = f'http://{host}/{data[i]["image"]}' return data
bigcode/self-oss-instruct-sc2-concepts
def format_content(article): """ This function takes an Intercom article and formats its content as the HTML we'll use for the Guru card. Because Intercom has some extra fields on its articles, like the # of views, conversations, and counts of user reactions and we don't have these fields in Guru, we displa...
bigcode/self-oss-instruct-sc2-concepts
def remove_duplicates(n): """ Removes duplicates in a given list (referenced list) Returns a list of all duplicates. """ seen = [] duplicates = [] # determine duplicates for x in n: if x in seen: duplicates.append(x) else: seen.append(x) # m...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def save_binary_file(path: str, data: bytes): """ Save binary data to given path :param path: file path :param data: binary data """ return Path(path).write_bytes(data)
bigcode/self-oss-instruct-sc2-concepts
def mkmdict(seq, *, container=None): """Make multi-dict {key: [val, val]...}.""" if container is None: container = {} for key, val in seq: container.setdefault(key, []).append(val) return container
bigcode/self-oss-instruct-sc2-concepts
def get_center(x_min: int,y_min: int,x_max:int,y_max:int): """Get center of bounding box. Args: x_min (int): Minimum x value in pixels. y_min (int): Minimum y value in pixels. x_max (int): Maximum x value in pixels. y_max (int): Maximum y value in pixels. Returns: t...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List import random def generate_chain(model: Dict[str, List[str]], length: int, order: int) -> str: """Build a Markov chain from the given model. Args: model: A dictionary mapping ngrams to possible following words. length: The length of the markov c...
bigcode/self-oss-instruct-sc2-concepts
def dataset_metadata_fixture() -> dict: """Test fixture returning an example dataset metadata response dict Returns: dict: Example Dataset metadata response dict """ data = { "@context": ["metadata-v1"], "@type": "dcat:Dataset", "dct:title": "An example workflow definiti...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict import json def load_watermark(wm_file, wm_size, name_feat_map=None): """ Load watermark mapping data from file. :param wm_file: (str) json file containing the watermark mappings :param wm_size: (int) sixe of the trigger :param name_feat_map: (dict) mapping of feature n...
bigcode/self-oss-instruct-sc2-concepts
def url_from_key(key): """Given an OSF project key, retrieve the URL of the project metadata. """ return ('https://files.osf.io/v1/resources/{}' '/providers/osfstorage/'.format(key))
bigcode/self-oss-instruct-sc2-concepts
def T(*args): """A function that always returns true. Any passed in parameters are ignored""" return True
bigcode/self-oss-instruct-sc2-concepts
def flip(matrix): """ Flip a matrix vertically. Returns an immutable matrix. Example: 1 2 --> 2 1 3 4 4 3 """ return tuple([row[::-1] for row in matrix])
bigcode/self-oss-instruct-sc2-concepts
import base64 def encode_images_from_file(image_paths): """ Encodes the processed image(s). Args: image_paths: List of input image filepath Strings ex).jpg , .png, .tiff Returns: A list of encoded image(s) as ByteStrings """ ret = [] for path in image_paths: with open(pat...
bigcode/self-oss-instruct-sc2-concepts
def is_yes(indicator): """ Check if `indicator`represents positive state :param indicator: the bool literal like 'y', 'yes', 'true' and 'True' :type indicator: str :return: bool value to indicate positive or not :rtype: bool """ assert(type(indicator) == str) value_list = ('y', 'y...
bigcode/self-oss-instruct-sc2-concepts
def invcdf_uniform(val: float, lb: float, ub: float) -> float: """Returns the inverse CDF lookup of a uniform distribution. Is constant time to call. Args: val: Value between 0 and 1 to calculate the inverse cdf of. lb: lower bound of the uniform distribution ub: upper bound of ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def entity_dict_has_primary_key(pk_names: Sequence[str], entity_dict: dict) -> bool: """ Check whether the given dict contains all primary key fields """ return set(pk_names) <= set(entity_dict)
bigcode/self-oss-instruct-sc2-concepts
def sequence_index_word(sequence, index_word_dict, pad_value=' ', join=False): """Sequence index transfer to sequence word. Args: sequence: pd.Series or np.array or List of lists, sample sequence. index_word_dict: dict, {index: word}. pad_value: fillna value, if word not in index_wo...
bigcode/self-oss-instruct-sc2-concepts
def valid_alleles(alleles): """Return if alleles are valid (i.e. at least one non-symbolic alt).""" return len(alleles) > 1 and not any('<' in a or '[' in a or ']' in a for a in alleles)
bigcode/self-oss-instruct-sc2-concepts
from typing import List import math def fizzbuzz(n: int) -> List[str]: """Conunts and reterns N FizzBuzz numbers. The first number is "1", and the players then count upwards in turn. However, any number divisible by three is replaced by the word fizz and any number divisible by five by the word buzz. Numb...
bigcode/self-oss-instruct-sc2-concepts
def strip_trailing_zeroes(num) -> str: """Remove trailing zeroes, e.g. 0.500 --> 0.5 and 1.000 -> 1""" s = "{:.3f}".format(num) return s.rstrip("0").rstrip(".") if "." in s else s
bigcode/self-oss-instruct-sc2-concepts
def rotate(string_one, string_two): """Determines if one string is a rotation of the other. Args: string_one: any string of characters. string_two: any string of characters. Returns: True: if string_one is a rotation of string_two False: if string_one is not a rotation ...
bigcode/self-oss-instruct-sc2-concepts
def kelvin_to_farenheit(temp: float): """ Converts kelvin to farenheit """ far = (temp - 273.15) * (9 / 5) + 32 return int(far)
bigcode/self-oss-instruct-sc2-concepts
def first(iterable): """Returns the first value of the given iterable.""" return next(iter(iterable))
bigcode/self-oss-instruct-sc2-concepts
def _format_pep_8(camel_case_name: str) -> str: """ Helper that creates a pep8_compliant_method_name from a given camelCaseMethodName. """ return camel_case_name[0].lower() + "".join( f"_{letter.lower()}" if letter.isupper() else letter.lower() for letter in camel_case_name[1:] )
bigcode/self-oss-instruct-sc2-concepts
def linalg_vector_set_elem(a, n, v): """ Set vector element n to v. Returns copy of matrix with change. Parameters: a (array): The vector n (int): The index v (number): The new value """ a1 = a.copy() a1[n] = v return a1
bigcode/self-oss-instruct-sc2-concepts
import torch def threshold_resize_torch(preds, shape, threshold=0.5): """ Thresholds and resizes predictions as a tensor. Args: preds (torch tensor): Predictions. shape (tuple [2]): Shape to resize to threshold (float, optional): Threshold. Defaults to 0.5. Returns: n...
bigcode/self-oss-instruct-sc2-concepts
def filter_list_sorter(feed_filter): """ Provide a key to sort a list of feed filters. """ return feed_filter['class']
bigcode/self-oss-instruct-sc2-concepts
def gc_content_percent(sequence): """ Calculates the GC-content percentage of the input sequence Returns the percentage as an integer out of 100 """ gc = sequence.count('G') + sequence.count('C') atcg = len(sequence) percent_gc = (gc * 100) / atcg return percent_gc
bigcode/self-oss-instruct-sc2-concepts
def nucleotide_frequency(seq): """Count nucleotides in a given sequence. Return a dictionary""" tmpFreqDict = {"A": 0, "C": 0, "G": 0, "T": 0} for nuc in seq: tmpFreqDict[nuc] += 1 return tmpFreqDict # More Pythonic, using Counter # return dict(Counter(seq))
bigcode/self-oss-instruct-sc2-concepts
def rules(state, alive): """ 1. Any live cell with two or three live neighbours survives. 2. Any dead cell with three live neighbours becomes a live cell. 3. All other live cells die in the next generation. Similarly, all other dead cells stay dead. """ if state == 1: # c...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import importlib def import_object(name: str) -> Any: """Dynamically import a Python object (e.g. class, function, ...). .. note:: To dynamically import a module, use :func:`importlib.import_module`. Args: name (str): The path to the Python object to import. ...
bigcode/self-oss-instruct-sc2-concepts
def _IsSourceExtension(s): """File extension (excluding dot) matches a source file extension.""" return s in ('c', 'cc', 'cpp', 'cxx')
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 async def db_check(bot, msg, cursor, table: str): """ This function is coroutine. Checks if table exists. :param bot: Bot instance :param msg: Message :param cursor: Database cursor :param table: Table name :return: Bool """ try: cursor.execute('SELECT...
bigcode/self-oss-instruct-sc2-concepts
def gradient(color_one, color_two, blend_weight): """ Blend between two colors with a given ratio. :param color_one: first color, as an (r,g,b) tuple :param color_two: second color, as an (r,g,b) tuple :param blend_weight: Blend weight (ratio) of second color, 0.0 to 1.0 """ if blend_weig...
bigcode/self-oss-instruct-sc2-concepts
def no_signature(run_command, disk_path): """Return true if no known signatures exist on the disk.""" signatures = run_command(['blkid', '-p', disk_path]) return not 'UUID' in signatures[1]
bigcode/self-oss-instruct-sc2-concepts
def _validate_prefix(prefix, avoid): """ Validate an install prefix. """ if prefix.startswith(avoid): rest = prefix[0:len(avoid)] return rest != "/" and rest != "" return True
bigcode/self-oss-instruct-sc2-concepts
def compare_webapps(list1, list2): """ Return list of matching dictionaries from two lists of dictionaries. """ check = set([(d['name'], d['id']) for d in list2]) return [d for d in list1 if (d['name'], d['id']) in check]
bigcode/self-oss-instruct-sc2-concepts
import torch def node_covering_index(cover_index:torch.LongTensor, distribution=False, num_nodes=None): """Compute the node covering index of a given cover matrix, i.e., the number of occurrences of each node in the cover matrix. Args: cover_index (torch.LongTensor): Cover assignment matrix i...
bigcode/self-oss-instruct-sc2-concepts
import base64 def parse_signature(value: bytes) -> str: """ Return a base64 encoded signature. Since the signatures dont really have any representation apart from bytes, encode the bytes to a b64 string similar to stellar's xdr viewer. """ return base64.b64encode(value).decode()
bigcode/self-oss-instruct-sc2-concepts
def test_model(clients_to_test, set_to_use='test'): """Tests self.model on given clients. Tests model on self.selected_clients if clients_to_test=None. Args: clients_to_test: list of Client objects. set_to_use: dataset to test on. Should be in ['train', 'test']. """ metrics = {} ...
bigcode/self-oss-instruct-sc2-concepts
def split_image_name ( image_name ): """ Splits a specified **image_name** into its constituent volume and file names and returns a tuple of the form: ( volume_name, file_name ). """ col = image_name.find( ':' ) volume_name = image_name[ 1: col ] file_name = image_name[ col + 1: ] ...
bigcode/self-oss-instruct-sc2-concepts
def connect_db(client, db_name, username, password): """ Connect to a Arango database. :param db_name: Database name. :type db_name: str :param username: Username for basic authentication. :type username: str :param password: Password for basic authentication. :type password: str :r...
bigcode/self-oss-instruct-sc2-concepts
def f_bound(f, key, first, last, value, which, *args, **kwargs): """ :param f: the MONOTONIC function :param key: keyword arguments or position of argument to be searched :param first: [first, last) :param last: [first, last) :param value: value to be searched :param which: lower bound or u...
bigcode/self-oss-instruct-sc2-concepts