seed
stringlengths
1
14k
source
stringclasses
2 values
def decimal2dm(decimal_degrees): """ Converts a floating point number of degrees to the equivalent number of degrees and minutes, which are returned as a 2-element list. If 'decimal_degrees' is negative, only degrees (1st element of returned list) will be negative, minutes (2nd element) will always be p...
bigcode/self-oss-instruct-sc2-concepts
def sort_by_username(user): """Sort students by their username""" return user['username']
bigcode/self-oss-instruct-sc2-concepts
def _sanitize_str_to_list(dim): """Make dim to list if string, pass if None else raise ValueError.""" if isinstance(dim, str): dim = [dim] elif isinstance(dim, list) or dim is None: dim = dim else: raise ValueError( f"Expected `dim` as `str`, `list` or None, found {di...
bigcode/self-oss-instruct-sc2-concepts
def prepare(link:str): """A function to check if the link is complete (it includes the protocol) and that it can be used by the library (it should not end with a slash) Args: **link (str)**: The link to check/prepare Raises: **Exception**: Thrown if the protocol is not present in the URL Returns: **str...
bigcode/self-oss-instruct-sc2-concepts
def to_pandas_adjacency(G): """ Returns the graph adjacency matrix as a Pandas DataFrame. The row indices denote source and column names denote destination. Parameters ---------- G : cugraph.Graph Graph containing the adjacency matrix. """ pdf = G.to_pandas_adjacency() retur...
bigcode/self-oss-instruct-sc2-concepts
def parse_response_item(item_response_list): """ The function parses GetItemsResponse and creates a dict of ASIN to AmazonProduct object params: *item_response_list* List of Items in GetItemsResponse return Dict of ASIN to AmazonProduct object """ mapped_response = ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def to_lower(text_docs_bow: Iterable[Iterable[str]]) -> Iterable[Iterable[str]]: """Converts all letters in documents ("bag of words" format) to lowercase. Args: text_docs_bow: A list of lists of words from a document Returns: A generator expression for all of...
bigcode/self-oss-instruct-sc2-concepts
def is_parameter(value): """Returns True if the given value is a reference to a template parameter. Parameters ---------- value: string String value in the workflow specification for a template parameter Returns ------- bool """ # Check if the value matches the template par...
bigcode/self-oss-instruct-sc2-concepts
import math def get_average_color(x, y, x_len, y_len, image, skip=1): """ Returns a 3-tuple containing the RGB value of the average color of the given square bounded area of length = n whose origin (top left corner) is (x, y) in the given image""" i = image.load() r, g, b = 0, 0, 0 count = 0 ...
bigcode/self-oss-instruct-sc2-concepts
import datetime def convertfrom_epoch_time(epoch_time: "int | float"): """Takes a given epoch timestamp int or float and converts it to a datetime object. Examples: >>> now = get_epoch_time()\n >>> now\n 1636559940.508071 >>> now_as_dt_obj = convertfrom_epoch_time( no...
bigcode/self-oss-instruct-sc2-concepts
def is_prime(number): """checks if a given number is prime""" prime = True for n in range(2, number): if prime and number % n == 0: prime = False print("The number is not prime") if prime: print("The number is prime") return prime
bigcode/self-oss-instruct-sc2-concepts
def distance_from_origin(position): """ Get the 'taxicab geometry' distance of a position from the origin (0, 0). """ return sum([abs(x) for x in position])
bigcode/self-oss-instruct-sc2-concepts
import json def extract_aws_policies(action: str, client, managed: bool): """ Call the AWS IAM API to retrieve policies and perform an action with them. :param action: what action to take with the IAM policies (list, dump) :param client: the boto client to use :param managed: (boolean) if true, i...
bigcode/self-oss-instruct-sc2-concepts
def preprocess(matrix, index): """ Takes as list of lists (in other words a matrix), and returns a list of preprocessed sentences for all elements at the index specified for the inner list. For BERT models, dropping punctuation affects accuracy. See https://www.aclweb.org/anthology/2020.pam-1.1...
bigcode/self-oss-instruct-sc2-concepts
def one_hot(i, n): """ Makes a one-hot vector of length n with 1 in position i. """ one_hot = [0 for x in range(n)] one_hot[i] = 1 return one_hot
bigcode/self-oss-instruct-sc2-concepts
def convert36ToAscii(start, chs): """Convert decimal address to ascci address :param start: NBP adress in decimal reverse:Big Endian Byte Order: The most significant byte (the "big end") of the data is placed at the byte with the lowest address :param chs:tsring of all digits and ascii upper :return:NB...
bigcode/self-oss-instruct-sc2-concepts
def read_all_commits(filename): """Read all commits from the given GIT log file.""" commits = [] with open(filename) as fin: for line in fin: splitted = line.strip().split(" ", 1) commits.append(splitted) commits.reverse() return commits
bigcode/self-oss-instruct-sc2-concepts
def DetermineType(value): """Determines the type of val, returning a "full path" string. For example: DetermineType(5) -> __builtin__.int DetermineType(Foo()) -> com.google.bar.Foo Args: value: Any value, the value is irrelevant as only the type metadata is checked Returns: Type path stri...
bigcode/self-oss-instruct-sc2-concepts
def optional(args, key): """If the given key is in args, return the corresponding value, otherwise return None """ return key in args and args[key] or None
bigcode/self-oss-instruct-sc2-concepts
def get_correlation_metrics_from_args(args): """ Extract a list of correlation metrics to use from the program arguments. """ correlation_metrics = [] if args.pearson: correlation_metrics.append('pearson') if args.spearman: correlation_metrics.append('spearman') if args.kenda...
bigcode/self-oss-instruct-sc2-concepts
import math def distance_calculation(homeLattitude, homeLongitude, destinationLattitude, destinationLongitude): """ This function returns the distance between two geographiclocations using the haversine formula. Inputs: 1. homeLattitude - Home or Current Location's Latitude ...
bigcode/self-oss-instruct-sc2-concepts
def get_authors_by_publisher(data, ascending=True): """Returns the authors by each publisher as a pandas series Args: data: The pandas dataframe to get the data from ascending: The sorting direction for the returned data. Defaults to True. Returns: The sorted data as a pand...
bigcode/self-oss-instruct-sc2-concepts
import torch def temporal_iou(spans1, spans2): """ Args: spans1: (N, 2) torch.Tensor, each row defines a span [st, ed] spans2: (M, 2) torch.Tensor, ... Returns: iou: (N, M) torch.Tensor union: (N, M) torch.Tensor >>> test_spans1 = torch.Tensor([[0, 0.2], [0.5, 1.0]]) ...
bigcode/self-oss-instruct-sc2-concepts
def regular_plural(noun: str) -> str: """English rule to get the plural form of a word""" if noun[-1] == "s": return noun + "es" return noun + "s"
bigcode/self-oss-instruct-sc2-concepts
def get_requested_roles(settings): """Retrieve any valid requested_roles from dict settings""" if ('requested_roles' in settings and settings['requested_roles'] not in ['None', None]): return settings['requested_roles'].split(',') else: return []
bigcode/self-oss-instruct-sc2-concepts
import pickle def decode_pickle(data): """ Restore original object using Pickle. """ return pickle.loads(data, fix_imports=False)
bigcode/self-oss-instruct-sc2-concepts
import csv import io def splitStr(delimiter, escapeChar, s): """ Splits s based on delimiter that can be escaped via escapeChar """ # Let's use csv reader to implement this reader = csv.reader(io.StringIO(s), delimiter=delimiter, escapechar=escapeChar) # Unpack first line for x in reader: ...
bigcode/self-oss-instruct-sc2-concepts
def updated_querystring(request, params): """Updates current querystring with a given dict of params, removing existing occurrences of such params. Returns a urlencoded querystring.""" original_params = request.GET.copy() for key in params: if key in original_params: original_params....
bigcode/self-oss-instruct-sc2-concepts
def get_name(pbs_file): """ Extract the model name from a `CMIP5-compatible file name <https://cmip.llnl.gov/cmip5/output_req.html>`_. Parameters ---------- pbs_file : str A filename that obeys the CMIP5 standard. Returns ------- str The name of the model. """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_rn_freqs(core): """ Get red noise frequency array from a core, with error message if noise array has not been included. """ if core.rn_freqs is None: raise ValueError('Please set red noise frequency array in ' ' the core named {0}.'.format(core.label)) el...
bigcode/self-oss-instruct-sc2-concepts
def repeat_along_dimension(array, number, dim=0): """Return a view into the array with a new, repeated dimension. Parameters ---------- array : torch.Tensor number : int The number of repeats. dim : int The dimension along which to repeat. Returns ------- array : to...
bigcode/self-oss-instruct-sc2-concepts
def get_tableblocks(page): """Get all the TableBlocks for a given page. TableBlocks can be stored either directly in page's content, or in a FullWidthText item. So we must check both. """ try: data = page.specific.content.raw_data except Exception: return [] tableblocks = lis...
bigcode/self-oss-instruct-sc2-concepts
import six def hostport(scheme, host, port): """ Returns the host component, with a port specifcation if needed. """ if (port, scheme) in [(80, "http"), (443, "https"), (80, b"http"), (443, b"https")]: return host else: if isinstance(host, six.binary_type): return b...
bigcode/self-oss-instruct-sc2-concepts
def format_embed_length(data: list) -> list: """ If the length of the data is greater than 1024 characters, it will be shortened to that amount. Parameters ---------- data : list The list containing the description for an embed. Returns ------- list The shortened descri...
bigcode/self-oss-instruct-sc2-concepts
def renamed_prefix(cfg, old, new): """ Returns a new dictionary that has all keys of `cfg` that begin with `old` renamed to begin with `new` instead. """ renamed = dict(cfg) for k in cfg.keys(): if k.startswith(old): renamed[new + k[len(old):]] = renamed.pop(k) return ren...
bigcode/self-oss-instruct-sc2-concepts
def get_rec_names(study_folder): """ Get list of keys of recordings. Read from the 'names.txt' file in study folder. Parameters ---------- study_folder: str The study folder. Returns ---------- rec_names: list LIst of names. """ with open(study_folder / 'na...
bigcode/self-oss-instruct-sc2-concepts
def flatten_manifests(root_manifest, only_with_entries=False, recursion=0): """ Convert a tree-structure Manifest into a flat list structured list of Manifests. :param root_manifest: :type root_manifest: Manifest :param only_with_entries: Switch to filter result to only those manifests with ...
bigcode/self-oss-instruct-sc2-concepts
def split_list(doc_list, n_groups): """ Args: doc_list (list): is a list of documents to be split up n_groups (int): is the number of groups to split the doc_list into Returns: split_lists (list): a list of n_groups which are approximately equal in length, as a necessary step...
bigcode/self-oss-instruct-sc2-concepts
def insert_breaks(s, min_length, max_length): """Inserts line breaks to try to get line lengths within the given range. This tries to minimize raggedness and to break lines at punctuation (periods and commas). It never splits words or numbers. Multiple spaces may be converted into single spaces. Args: ...
bigcode/self-oss-instruct-sc2-concepts
def srun(arg_dict,qos=True,time=10,mem=4): """Return srun call, with certain parameters appended. Arguments: ---------- arg_dict : dict Dictionary of arguments passed into this script, which is used to append parameters to srun call. qos : bool, optional Quality of service, set to ...
bigcode/self-oss-instruct-sc2-concepts
def split_unique(df_data, field): """ Split the DataFrame based on unique value from field Parameters ---------- df_data : pandas DataFrame Original data to split field : String Column name to split data on unique value Returns ------- df_split : dict A dic...
bigcode/self-oss-instruct-sc2-concepts
def get_edge_vertex_ids(g, sort=True): """get_edge_vertex_ids Returns a list of tuples containing the source and target for each edge in the graph. Parameters ---------- g : :obj:`graph_tool.Graph` A graph with edges. sorted : :obj:`bool`: Determines whether...
bigcode/self-oss-instruct-sc2-concepts
def logistic(x, r): """Logistic map, with parameter r.""" return r * x * (1 - x)
bigcode/self-oss-instruct-sc2-concepts
def get_emotion_dict(emo_metrics): """Returns a dictionary in which keys are emotions and values are confidences. Args: emo_metrics: A list of dictionaries, which each have the keys 'name' and 'confidence', describing emotions detected from FeelNet. Returns: A dictionary as described above. """ ...
bigcode/self-oss-instruct-sc2-concepts
def encode_int(i): """Encode an integer for a bytes database.""" return bytes(str(i), "utf-8")
bigcode/self-oss-instruct-sc2-concepts
from typing import List from pathlib import Path from typing import Set def get_cl_tags(files: List[Path]) -> List[str]: """ Come up with descriptive tags given a list of files changed. For each path, use the first rule that applies in the following order: 1) Pick the path component right after the last "li...
bigcode/self-oss-instruct-sc2-concepts
def get_tuner_submodel_name(output_model_name="tuned_climpp", num_years=10, margin_in_days=45): """Returns submodel name for a given setting of model parameters """ return f"{output_model_name}_on_years{num_years}_margin{margin_in_days}"
bigcode/self-oss-instruct-sc2-concepts
def test_nan(dataframe): """ Test if dataframe contains nan value Parameters ---------- dataframe: pandas dataframe Raises ------ ValueError If contains nan, raise ValueError Returns ------- is_valid: boolean True if did not contain nan, False if contain ...
bigcode/self-oss-instruct-sc2-concepts
def hits(service): """Returns metric 'Hits'.""" return service.metrics.select_by(**{'system_name': 'hits'})[0]
bigcode/self-oss-instruct-sc2-concepts
def parse_field(field_string): """ Get a tuple of the first entries found in an psimitab column (xref, value, desc) :param field_string: :return: A tuple (xref, value, desc) - desc is optional """ parts = field_string.split(":") xref = parts[0] rest = parts[1] if "(" in rest: ...
bigcode/self-oss-instruct-sc2-concepts
def get_package_name(package, customer=None, python="2.7"): """ returns the egg filename (without the fs path), e.g. nexiles.gateway.appservice-1.0.0-py2.7-customer.egg """ if customer: return "{}-{}-py{}-{}.egg".format( package.import_name, package.version, ...
bigcode/self-oss-instruct-sc2-concepts
def d1d2_index(det_df,d1,d2): """ Return the index of a given detector pair from det_df. Parameters ---------- det_df : pandas dataFrame dataFrame of detector pair indices and angles d1 : int detector 1 channel d2 : int detector 2 channel Returns ---...
bigcode/self-oss-instruct-sc2-concepts
def load_from_file(ids, data_path = "."): """ Takes an array of ids or single id and loads that srt file and returns the srt files in a dictionary with IDs as keys. """ if type(ids) is int or type(ids) is str: with open(data_path+str(ids)+".srt","r") as f: data = f.read() ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def parse_time(s='2016-03-16T17:31:14Z'): """ Converts Piazza Date-time format into a pythonic construct. Examples of Piazza Datetime: - 2016-03-16T17:31:14Z """ format = "%Y-%m-%dT%H:%M:%SZ" return datetime.strptime(s,format)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def occluders_too_close(occluder: Dict[str, Any], x_position: float, x_scale: float) -> bool: """Return True iff a new occluder at x_position with scale x_scale would be too close to existing occluder occluder.""" existing_scale = occluder['shows'][0]['scale'...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_show_install(cmd_output): """ Parse output of 'show install request' :param cmd_output: an iterable of lines (str) from the command output :return: (is_complete, is_success) tuple of bool. is_complete indicates whether the request completed, is_success indicates whether...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def split_string(x: str, n: int) -> List[str]: """ Split string into chunks of length n """ # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
bigcode/self-oss-instruct-sc2-concepts
def _is_tabular(structure): """ Determines if a PDS4 structure can be shown as a table. Tabular structures are either: (1) Tables, or (2) Arrays Parameters ---------- structure : Structure PDS4 structure to check. Returns ------- bool True if *structure...
bigcode/self-oss-instruct-sc2-concepts
def get_localized_name(name): """Returns the localizedName from the name object""" locale = "{}_{}".format( name["preferredLocale"]["language"], name["preferredLocale"]["country"] ) return name['localized'].get(locale, '')
bigcode/self-oss-instruct-sc2-concepts
def sort_strlist(s): """Deserialise, sort, and reserialise a list of strings in the format "potato,spade,elephant" """ return ','.join(sorted(s.strip().split(',')))
bigcode/self-oss-instruct-sc2-concepts
def build_slack_payload(budgets, image_url): """ Builds the payload that is sent to the Slack webhook about our budget overspend. """ details = "\n".join( [f"{b.name}: {b.forecasted_spend} > {b.budget_limit}" for b in budgets] ) return { "username": "aws-budgets", "i...
bigcode/self-oss-instruct-sc2-concepts
import re def does_not_have_bad_pairs(chars): """ It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements. """ bad_pairs = ['ab', 'cd', 'pq', 'xy'] if not re.search('|'.join(bad_pairs), chars): return True return False
bigcode/self-oss-instruct-sc2-concepts
def get_attribute(t, key: str): """ Get an attribute from a given callable :param t: the callable :param key: the key, the attributes name :return: the attribute data """ return getattr(t, key)
bigcode/self-oss-instruct-sc2-concepts
import math def scaling(axis_len): """Scaling of plot figure size Parameter: ---------- axis_len : int Number of rows or columns Return: ---------- scale : float scale for axis """ return 0.5/math.log10(axis_len)
bigcode/self-oss-instruct-sc2-concepts
def der_order(order: int) -> str: """Return correct suffix for order. >>> der_order(1) ... "1-st" >>> der_order(4) ... "4-th" """ _suffix = ["st", "nd", "rd"] if order - 1 > 3: return f"{order}-th" else: return f"{order}-{_suffix[order - 1]}"
bigcode/self-oss-instruct-sc2-concepts
def accuracy(output, target): """ Computes accuracy, from predicted and true labels. """ batch_size = target.size(0) _, pred = output.topk(1, 1, True, True) correct = pred.eq(target.view(-1, 1).expand_as(pred)) correct_total = correct.float().sum() return correct_total * (100.0 / batch_...
bigcode/self-oss-instruct-sc2-concepts
def multicommand_get_command_short_help(self, ctx, cmd_name): """Returns the short help of a subcommand It allows MultiCommand subclasses to implement more efficient ways to provide the subcommand short help, for example by leveraging some caching. Parameters ---------- ctx : click.core.Contex...
bigcode/self-oss-instruct-sc2-concepts
def mydub(a): """Double a """ return a * 2
bigcode/self-oss-instruct-sc2-concepts
import torch def get_IoU(predictions: torch.Tensor, labels: torch.Tensor, threshold: float = 0.5): """Code inspired by https://www.kaggle.com/iezepov/fast-iou-scoring-metric-in-pytorch-and-numpy """ eps = 1e-6 # assert N x H x W if len(predictions.shape) != 3: predictions.unsqueeze_(0)...
bigcode/self-oss-instruct-sc2-concepts
def strip_comments(line: str) -> str: """Remove comments from line""" # comment at the beginning of the line if line.startswith("#"): return "" # in-line comment left = line.rsplit("#", 1)[0] # be sure we are not inside a string if left.count('"') % 2 == 0 and left.count("'") % 2 ==...
bigcode/self-oss-instruct-sc2-concepts
def get_alphabet_mapping(filename): """ Given a filename, return a 2D list of [alphabet1, alphabet2] representing two alphabet list mappings """ with open(filename) as data: res = [] for line in data.read().splitlines(): alphabet = [] for letter in line: ...
bigcode/self-oss-instruct-sc2-concepts
def HMStime(s): """ Given the time in seconds, an appropriately formatted string. """ if s<60.: return '%.3f s'%s elif s<3600.: return '%d:%.3f'%(int(s/60%60),s%60) else: return '%d:%d:%.3f'%(int(s/3600),int(s/60%60),s%60)
bigcode/self-oss-instruct-sc2-concepts
import collections def unique2lists(list1, list2, add=False): """Unique list1 and list2 based on list1 Args: list1(list): list2(list): add(Optional(bool)): add list2 elements with list1 duplicates Returns: list,list """ if add: cntr = collections.Counter() ...
bigcode/self-oss-instruct-sc2-concepts
def format_ISO_time(year,doy,timestr): """ Format an ISO-like time string: YYYY-DDDTHH:MM @param year : 4-digit year @type year : str @param doy : 3-digit day of year @type doy : str @param timestr : HHMM @type timestr : str @return: str """ return year + '-' + doy + 'T' + timestr[0:2] + ':...
bigcode/self-oss-instruct-sc2-concepts
import click def validate_page_size(ctx, param, value): """Ensure that a valid value for page size is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter("Page size must be non-zero or unset.", param=param) return value
bigcode/self-oss-instruct-sc2-concepts
import time def log(msg): """Print string s and current time.""" t = time.localtime() current_time = time.strftime("%H:%M:%S", t) return f"{current_time} | {msg}"
bigcode/self-oss-instruct-sc2-concepts
def scalar(p1, p2): """Scalar product between p1 and p2""" return p1.x*p2.x + p1.y*p2.y + p1.z*p2.z
bigcode/self-oss-instruct-sc2-concepts
def human_list(l): """ Formats a list of strings in a human-friendly way. """ l = ["'{0}'".format(x) for x in l] if len(l) == 0: return 'nothing' elif len(l) == 1: return l[0] elif len(l) == 2: return ' and '.join(l) else: return ', '.join(l[:-1]) + ' and...
bigcode/self-oss-instruct-sc2-concepts
import warnings import inspect def _get_members(*args, **kwargs): """ Same as :func:`inspect.getmembers` except that it will silence warnings, which avoids triggering deprecation warnings just because we are scanning a class """ with warnings.catch_warnings(): warnings.simplefilter(act...
bigcode/self-oss-instruct-sc2-concepts
import math def test3(x, sin=math.sin): """ >>> %timeit test3(123_456) 105 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) """ res = 1 for _ in range(1000): res += sin(x) return res
bigcode/self-oss-instruct-sc2-concepts
import collections def format_int_list(int_list, delim=',', range_delim='-', delim_space=False): """ Returns a sorted range string from a list of positive integers (*int_list*). Contiguous ranges of integers are collapsed to min and max values. Reverse of :func:`parse_int_list`. Args: int...
bigcode/self-oss-instruct-sc2-concepts
def seq2kmer(seq, k): """ Convert original sequence to kmers Arguments: seq -- str, original sequence. k -- int, kmer of length k specified. Returns: kmers -- str, kmers separated by space """ kmer = [seq[x:x+k] for x in range(len(seq)+1-k)] kmers = " ".join(kmer) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Union from typing import List from typing import Any import requests def get_record_by_doi( doi: str, is_version_doi=True, query_params: Dict[str, Union[int, str]] = {"size": 1} ) -> List[Dict[str, Any]]: """Retrieve a Record from the zenodo api, where doi or concept...
bigcode/self-oss-instruct-sc2-concepts
import six def _DictToMetadataMessage(message_classes, metadata_dict): """Converts a metadata dict to a Metadata message.""" message = message_classes.Metadata() if metadata_dict: for key, value in sorted(six.iteritems(metadata_dict)): message.items.append(message_classes.Metadata.ItemsValueListEntry(...
bigcode/self-oss-instruct-sc2-concepts
def set_zenodo(ctx, production): """Add Zenodo details: api urls, communities, to context object Parameters ---------- ctx: dict Click context obj to pass arguments onto sub-commands production: bool If True using production api, if False using sandbox Returns ------- c...
bigcode/self-oss-instruct-sc2-concepts
def transfer_annotations_prob(mapping_matrix, to_transfer): """ Transfer cell annotations onto space through a mapping matrix. Args: mapping_matrix (ndarray): Mapping matrix with shape (number_cells, number_spots). to_transfer (ndarray): Cell annotations matrix with shape (number_cells, numb...
bigcode/self-oss-instruct-sc2-concepts
def s_to_min(value): """Convert seconds to minutes.""" return "{}:{:02d}".format(int(value // 60), int(value % 60))
bigcode/self-oss-instruct-sc2-concepts
import random def is_prime_prob(n, k=5): """ Returns <True> if <n> is a prime number, returns <False> otherwise. It uses a probabilistic method based on the Fermat little theorem. The probability of false positives can be reduced incresing <k>. - The probability of error when returns <True> is ze...
bigcode/self-oss-instruct-sc2-concepts
def caseins_getattr(enum, attr): """Case-insensitive `getattr` for enumerated types.""" lower_attr_keys = list(map(lambda x: x.lower(), enum._fields)) attr_idx = lower_attr_keys.index(attr.lower()) orig_attr = enum._fields[attr_idx] return getattr(enum, orig_attr)
bigcode/self-oss-instruct-sc2-concepts
import yaml def get_configs(file="config.yaml"): """ Load project config file. Parameters ---------- file: str Filepath of config file Returns ------- config: dict A loaded config file """ if file.endswith('.yaml') or file.endswith('.yml'): try: ...
bigcode/self-oss-instruct-sc2-concepts
def isgoldrushlocation(location: str) -> bool: """ checks if the provided location is a location where a goldrush can happen. :param location: the provided location :return: boolean if location is in the list of locations where a goldrush can happen. """ goldrushlocationlist = open("commands/dat...
bigcode/self-oss-instruct-sc2-concepts
def separate_data(X, c1, c2): """Function for diving the dataset X into two separate classes. Input arguments: ================ X : ndarray [n_rows, n_cols] The entire dataset having 'n_rows' rows and 'n_cols' columns. c1, c2 : ndarray [4, ] The coordinates of the top left and botto...
bigcode/self-oss-instruct-sc2-concepts
def determinant(q_form): """ The determinant of a tensor, given in quadratic form Parameters ---------- q_form : ndarray The quadratic form of a tensor, or an array with quadratic forms of tensors. Should be of shape (x, y, z, 3, 3) or (n, 3, 3) or (3, 3). Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def get_skel(s): """Get a tuple representing an instrution skeleton. Args: s: String of chars in {0, 1, x} of the skeleton Returns: Tuple (before, length, after), where - before is the number before the mask - length is the length of x's in the mask - after is t...
bigcode/self-oss-instruct-sc2-concepts
import pickle def get_game_models(fname='models/game_regressions.pkl'): """ Load pre-trained models from pickle file """ with open(fname, 'rb') as fid: game_models = pickle.load(fid) return game_models
bigcode/self-oss-instruct-sc2-concepts
def addcss(value, arg): """ Adds a css class to a form field """ css_classes = value.field.widget.attrs.get('class', '').split(' ') if css_classes and arg not in css_classes: css_classes = '%s %s' % (css_classes, arg) return value.as_widget(attrs={'class': css_classes})
bigcode/self-oss-instruct-sc2-concepts
def find_clusters(unit_loc, index_clusters): """ 找到某个位置在clusters中的哪个cluster return: cluster的下标,若未找到,返回-1 """ if unit_loc in index_clusters: return index_clusters[unit_loc] return -1
bigcode/self-oss-instruct-sc2-concepts
import json def load_conf_file(metadata_path): """Load the json configuration file create with the function `create_conf_file`. :param metadata_path: path to the metadata folder :type metadata_path: str Example:: result = load_conf_file('/home/romain/Downloads/irsst/metadata/') """ json_...
bigcode/self-oss-instruct-sc2-concepts
def _make_pretty_extended(extended): """ Makes the extended description pretty and returns a formatted string. Otherwise, returns None. """ if extended is not None and extended.strip() != "": extended = "\n".join(map(lambda u: u.strip(), extended.split("\n"))) return "```%s```\n\n" ...
bigcode/self-oss-instruct-sc2-concepts
import base64 def get_string_encoding(image_path): """ Get the base64 encoding string of the given image :param image_path: The path to the image :returns: The base64 byte string of the image """ with open(image_path, 'rb') as image: string = base64.b64encode(image.read()) s = '...
bigcode/self-oss-instruct-sc2-concepts