seed
stringlengths
1
14k
source
stringclasses
2 values
def apply_twice(f, x): """Return f(f(x)) >>> apply_twice(square, 2) 16 >>> from math import sqrt >>> apply_twice(sqrt, 16) 2.0 """ return f(f(x))
bigcode/self-oss-instruct-sc2-concepts
def extract_wikipedia_page(line): """Extracts the Wikipedia page for an entity""" if "sitelinks" in line and "enwiki" in line["sitelinks"]: return line["sitelinks"]["enwiki"]["title"].strip().replace(" ", "_") return None
bigcode/self-oss-instruct-sc2-concepts
def _get_port_interface_id_index(dbapi, host): """ Builds a dictionary of ports indexed by interface id. """ ports = {} for port in dbapi.ethernet_port_get_by_host(host.id): ports[port.interface_id] = port return ports
bigcode/self-oss-instruct-sc2-concepts
import random def random_correct_answer_message(correct_answer, points): """ Return a random encouraging phrase for getting a right answer """ phrases = [ "Nailed it!", "Nice one!", "Great work!", "You got it!", "Woohoo, nice job!", "You're amazing!", "C...
bigcode/self-oss-instruct-sc2-concepts
def is_protein_family(bio_ontology, node): """Return True if the given ontology node is a protein family.""" if bio_ontology.get_ns(node) == 'FPLX': return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def camel_to_snake(s: str) -> str: """Convert a string from camelCase string to snake_case. Args: s: String to be converted. Returns: A string where camelCase words have been converted to snake_case. """ return re.sub(r'(?<!^)(?=[A-Z])', '_', s).lower()
bigcode/self-oss-instruct-sc2-concepts
def inputNumber(message): """ Get an input number from user. Prompt is str @message """ while True: try: userInput = int(input(message)) except ValueError: print("Not an integer! Try again.") continue else: return userInput ...
bigcode/self-oss-instruct-sc2-concepts
def d3(x): """Evaluate the estimate 3*x**2+2*x+1.""" return (3*x+2)*x+1
bigcode/self-oss-instruct-sc2-concepts
def prompt_output(cli_input, converted=None): """Return expected output of simple_command, given a commandline cli_input string.""" return f'Opt: {cli_input}\n{converted or cli_input}\n'
bigcode/self-oss-instruct-sc2-concepts
def only_for_board_and_development(boards): """ Create a filter that is only considered when the given board matches and when development is toggled. """ def _inner(context): return context["board"] in boards and context["development"] return _inner
bigcode/self-oss-instruct-sc2-concepts
def convert_environment_id_string_to_int( environment_id: str ) -> int: """ Converting the string that describes the environment id into an int which needed for the http request :param environment_id: one of the environment_id options :return: environment_id represented by an int """ try...
bigcode/self-oss-instruct-sc2-concepts
import grp def get_gid_from_group(group): """Return GID from group name Looks up GID matching the supplied group name; returns None if no matching name can be found. NB returned GID will be an integer. """ try: return grp.getgrnam(group).gr_gid except KeyError as ex: ret...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def image_file_path(instance, filename, ext='.jpg'): """Returns the path with modified file name for the image files. Args: instance (object): instance of the file being uploaded. filename (str): current name of the file. Returns: str: new file path. ...
bigcode/self-oss-instruct-sc2-concepts
def merge_variables(variables, name=None, **kwargs): """Merge/concatenate a list of variables along the row axis. Parameters ---------- variables : :obj:`list` A list of Variables to merge. name : :obj:`str` Optional name to assign to the output Variable. By default, uses the ...
bigcode/self-oss-instruct-sc2-concepts
def replace_fields(field_list, *pairs): """Given a list of field names and one or more pairs, replace each item named in a pair by the pair. fl = 'one two three'.split() replace_fields(fl, ('two', 'spam')) # ['one', ('two', 'spam'), 'three'] """ result = list(field_list) for field_name,...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def rsubstringstartingwith(sub: str, s: str) -> Optional[str]: """ >>> rsubstringstartingwith('://', 'database://foo') 'foo' >>> rsubstringstartingwith('://', 'database://foo://bar') 'bar' >>> rsubstringstartingwith('://', 'foo') None """ try: re...
bigcode/self-oss-instruct-sc2-concepts
def parse_bool(x, true=('true', 'yes', '1', 'on'), add_true=(), false=('false', 'no', '0', 'off'), add_false=()): """Parse boolean string. Parameters ---------- x : bool or str Boolean value as `bool` or `str`. true : list of str List of accepted string representation...
bigcode/self-oss-instruct-sc2-concepts
def get_space_from_string(space_str): """ Convert space with P, T, G, M to int """ M = 1024 G = 1024 * M T = 1024 * G P = 1024 * T if 'M' in space_str: return int(float(space_str.split('M')[0]) * M) elif 'G' in space_str: return int(float(space_str.split('G')[0]) * G...
bigcode/self-oss-instruct-sc2-concepts
async def read_vlq(stream): """ Reads a VLQ from a stream, and returns both the parsed value and the bytes belonging to it. :param stream: A stream object, with readexactly() defined. :return: int, bytes: The parsed value and unparsed value of the VLQ. """ raw_bytes = b"" value = 0 while...
bigcode/self-oss-instruct-sc2-concepts
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_l...
bigcode/self-oss-instruct-sc2-concepts
def get_file_names(in_list): """Makes a list of each index[1] in a list of lists This method is deployed in the get_medical_image_list route :param in_list: list of lists containing patient medical images and file names :return: list containing file names """ temp = list()...
bigcode/self-oss-instruct-sc2-concepts
import re def _agg_removing_duplicates(agg_elem): """Aggregate while removing the duplicates. Aggregate the labels or alt labels together as a single element can have several Wikidata entities that need to be merged. Args: agg_elem (list of string): elem to aggregate Returns: st...
bigcode/self-oss-instruct-sc2-concepts
def get_aps_in_grid_inorder(ue_location, neighboring_aps_in_grid_unordered): """ Function to retrieve a list of neighboring APs in the increasing order of ue_ap distance """ def distance(p1, p2): return((p1[0]-p2[0])**2+(p1[1]-p2[1])**2) neighboring_aps_in_grid = sorted( neighbo...
bigcode/self-oss-instruct-sc2-concepts
import re def is_git_error(txt): """ Whether response from the git command includes error :param str txt: :return: :rtype: bool """ b_error = re.findall(r'^(.*?(\bfatal\b)[^$]*)$', txt, re.I | re.MULTILINE) \ or re.findall(r'^(.*?(\bCONFLICT\b)[^$]*)$', txt, re.I | re.MULTIL...
bigcode/self-oss-instruct-sc2-concepts
import shutil def del_dir(directory): """Delete directory""" try: shutil.rmtree(directory) return 0 except FileExistsError: return 1
bigcode/self-oss-instruct-sc2-concepts
def writeonly(func): """Marks an API function as write-only""" func._write_only_ = True return func
bigcode/self-oss-instruct-sc2-concepts
def calc_l2distsq(x, y): """ Calculate L2 distance between tensors x and y. """ d = (x - y)**2 return d.view(d.shape[0], -1).sum(dim=1)
bigcode/self-oss-instruct-sc2-concepts
def parse_string_to_list(line): """Parse a line in the csv format into a list of strings""" if line is None: return [] line = line.replace('\n', ' ') line = line.replace('\r', ' ') return [field.strip() for field in line.split(',') if field.strip()]
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import re def parseResourceId(resource_uri: str, resource_type: str) -> Optional[str]: """Parses the resource ID of the given type from the given URI, or returns None if not found.""" matches = re.search('{}/([^/]+)'.format(resource_type), resource_uri) if not matches: ...
bigcode/self-oss-instruct-sc2-concepts
def _get_manifest_path(repository, manifest=None): """Return the path for a manifest, or list of manifests if manifest is empty. """ if manifest: return '/acr/v1/{}/_manifests/{}'.format(repository, manifest) return '/acr/v1/{}/_manifests'.format(repository)
bigcode/self-oss-instruct-sc2-concepts
def replicate_z_samples(t, n_z_samples): """Replicates a tensor `n_z_samples` times on a new first dim.""" return t.unsqueeze(0).expand(n_z_samples, *t.shape)
bigcode/self-oss-instruct-sc2-concepts
def make_lookup_phrase(row): """Return full name and address for google geo api text search.""" address_text = "{} {}".format(row[1], row[2]) return address_text
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def _func_to_class_and_method(fn) -> Tuple[str, str]: """Returns the names of the function's class and method.""" split = fn.__qualname__.split('.') if len(split) >= 2: class_name = split[-2] method_name = split[-1] else: module_name = fn.__module__ class_name = module...
bigcode/self-oss-instruct-sc2-concepts
def hex_to_rgb(_hex): """ Convert a HEX color representation to an RGB color representation. hex :: hex -> [000000, FFFFFF] :param _hex: The 3- or 6-char hexadecimal string representing the color value. :return: RGB representation of the input HEX value. :rtype: tuple """ _hex = _hex....
bigcode/self-oss-instruct-sc2-concepts
def check_streams(streams='*'): """ Checks that the streams given are a list containing only possible streams, or is all streams - '*'. """ possible_streams = ['prices_ahead', 'prices', 'temperatures', 'emissions', 'generation-mix'] if isinstance(streams, list): unrecognised_streams = list...
bigcode/self-oss-instruct-sc2-concepts
import copy def is_subsequence(seq1, seq2): """Check if seq1 is a subsequence of seq2 >>> is_subsequence(((2,), (3, 5)), ((2, 4), (3, 5, 6), (8,))) True >>> is_subsequence(((1,), (2,)), ((1, 2), (3, 4))) False >>> is_subsequence(((2,), (4,)), ((2, 4), (2, 4), (2, 5))) True """ seq...
bigcode/self-oss-instruct-sc2-concepts
def truncate(source, max_len: int, el: str = "...", align: str = "<") -> str: """Return a truncated string. :param source: The string to truncate. :param max_len: The total length of the string to be returned. :param el: The ellipsis characters to append to the end of the string if it exceeds max_len. ...
bigcode/self-oss-instruct-sc2-concepts
def is_parser_function(string): """Return True iff string is a MediaWiki parser function.""" # see https://www.mediawiki.org/wiki/Help:Extension:ParserFunctions return string.startswith('#') # close enough for our needs
bigcode/self-oss-instruct-sc2-concepts
def get_scores(database, person, multi=True): """ Return a string representing the scores a person has in the database. The parameter `multi' is to specify whether the scores are used for displaying the scores of a single person or multiple people. """ indent = ' ' if multi else '' retu...
bigcode/self-oss-instruct-sc2-concepts
def split_b64_file(b64_file): """Separate the data type and data content from a b64-encoded string. Args: b64_file: file encoded in base64 Returns: tuple: of strings `(content_type, data)` """ return b64_file.encode('utf8').split(b';base64,')
bigcode/self-oss-instruct-sc2-concepts
def _dequantized_var_name(var_name): """ Return dequantized variable name for the input `var_name`. """ return "%s.dequantized" % (var_name)
bigcode/self-oss-instruct-sc2-concepts
def arcs2d(arcs): """Convert arcseconds into degrees.""" return arcs / 3600.0
bigcode/self-oss-instruct-sc2-concepts
def hamming_distance(a, b): """Returns the Hamming distance between two strings of equal length""" try: assert len(a) == len(b) return sum(i != j for i, j in zip(a, b)) except AssertionError as error: print('Barcode lengths are not equal for {}. {}'.format(a, b)) raise(error)
bigcode/self-oss-instruct-sc2-concepts
def tf_binary(dtm): """ Transform raw count document-term-matrix `dtm` to binary term frequency matrix. This matrix contains 1 whenever a term occurred in a document, else 0. :param dtm: (sparse) document-term-matrix of size NxM (N docs, M is vocab size) with raw term counts. :return: (sparse) bina...
bigcode/self-oss-instruct-sc2-concepts
def unzip(iterable): """ Unzip iterable of tuples into tuple of iterables :param iterable: Any iterable object yielding N-tuples :return: A N-tuple of iterables """ return zip(*iterable)
bigcode/self-oss-instruct-sc2-concepts
def make_matrix(num_rows, num_cols, entry_fn): """构造一个第 [i, j] 个元素是 entry_fn(i, j) 的 num_rows * num_cols 矩阵""" return [ [ entry_fn(i, j) # 根据 i 创建一个列表 for j in range(num_cols) ] # [entry_fn(i, 0), ... ] for i in range(num_rows) ]
bigcode/self-oss-instruct-sc2-concepts
def get_id_from_url(url: str) -> str: """Get the id of the image from the url. The url is of the format https://sxcu.net/{image_id}, so we simply split the url by `/` and return the last part. Parameters ---------- url : str The original url. Returns ------- str The...
bigcode/self-oss-instruct-sc2-concepts
def extract_var_key(raw_line: str, var_id: str) -> str: """ Extract the key from an line in the form "dict['key']" or "dict.get('key', *args)". """ line = raw_line.strip()[len(var_id) :] state_var = "" if line[0] == "[": state_var = line[2:-2] elif line[0:4] == ".get": ca...
bigcode/self-oss-instruct-sc2-concepts
def inherits_from(obj, a_class): """ Function that determine if a class is an inherited class. Args: obj (object any type): The object to analyze. a_class (object any type): The reference object. Returns: Returns True if the object is an instance of a class that inher...
bigcode/self-oss-instruct-sc2-concepts
def get_resource_by_path(path, resources): """gets the resource that matches given path Args: path (str): path to find resources (list(str)): list of resources Returns: dict: resource that matches given path, None otherwise """ return next( (x for x in resources if ...
bigcode/self-oss-instruct-sc2-concepts
def get_vigra_feature_names(feature_names): """ For the given list of feature names, return the list of feature names to compute in vigra. Basically, just remove prefixes and suffixes For example: ['edge_vigra_mean', 'sp_vigra_quantiles_25'] -> ['mean', 'quantiles'] """ feature_names = list...
bigcode/self-oss-instruct-sc2-concepts
def default_wire_map(ops): """Create a dictionary mapping used wire labels to non-negative integers Args: ops Iterable[Operation] Returns: dict: map from wires to sequential positive integers """ # Use dictionary to preserve ordering, sets break order used_wires = {wire: None ...
bigcode/self-oss-instruct-sc2-concepts
def bestMutation(shape, model, cycles=50, startHeat=100, heatDiv=1.01, alpha=.5): """ Mutates a shape for a given number of cycles and returns the best scoring change :param shape: The shape to mutate :param model: The model object :param cycles: The number of cycles (attempts at mutation) :para...
bigcode/self-oss-instruct-sc2-concepts
def allow_timefloor(submitmode): """ Should the timefloor mechanism (multi-jobs) be allowed for the given submit mode? :param submitmode: submit mode (string). """ return True
bigcode/self-oss-instruct-sc2-concepts
def get_base_worker_instance_name(experiment): """GCE will create instances for this group in the format "w-|experiment|-$UNIQUE_ID". 'w' is short for "worker".""" return 'w-' + experiment
bigcode/self-oss-instruct-sc2-concepts
import torch def objective(expec_t, look_back=20000): """ Creates the objective function to minimize. Args: expec_t (list): time-dependent quantum yield look_back (int): number of previous time steps over which to average the yield Returns: obj (torch.Tensor): obje...
bigcode/self-oss-instruct-sc2-concepts
def compare_dict_keys(dict_1, dict_2): """Check that two dict have the same keys.""" return set(dict_1.keys()) == set(dict_2.keys())
bigcode/self-oss-instruct-sc2-concepts
def get_price_estimate(client, coordinates): """Returns the price estimate data for the given `coordinates`. :param client: :class:`UberRidesClient <UberRidesClient>` object. :param client: :class:`Coordinates <Coordinates>` object. :return: price estimate data :rtype: list of dictionaries """ ...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def slide_factory(tag, id: int, classes: list = []): """ Factory for creating slides from a given Beautifulsoup tag, id, and list of classes to use for the slide. Args: tag (_type_): The tag to put into the slide. id (int): The id of the slide (used for the J...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_optional_regex(pattern, name): """Removes an optional part of the regex by capture name Must be of the format '(?:[anything](?P<[name]>[anything])[anything])?' """ return re.sub("\(\?:[^(]*\(\?P<{}>[^)]*\)[^)]*\)\?".format(name), "", pattern)
bigcode/self-oss-instruct-sc2-concepts
def column_selection(names, columns): """ select the columns that contain any of the value of names Args: names (TYPE): DESCRIPTION. columns (TYPE): DESCRIPTION. Returns: features (TYPE): DESCRIPTION. """ features = [] for col in columns: if any([name in co...
bigcode/self-oss-instruct-sc2-concepts
def _clean_key(root_key, filekey): """Return the cleaned key 'filekey', using 'root_key' as the root Args: root_key (str): root_key for accessing object store filekey (str): filename to access in object store Returns: str: Location to access the file """ i...
bigcode/self-oss-instruct-sc2-concepts
def get_pipe_parent(job): """Check if the job has a pipe_from parent and if so return that. If the does does not have any pipe targets, the job itself is returned. :param job: the job :type job: :class:`jip.db.Job` :returns: pipe source job or the job itself if no pipe parent is found """ i...
bigcode/self-oss-instruct-sc2-concepts
def _shift_twelve(number): """Shifts the number by 12, if it is less than 0. Parameters ---------- number : int Returns ------- int """ return number + 12 if number < 0 else number
bigcode/self-oss-instruct-sc2-concepts
def get_affiliate_code_from_request(request): """ Helper method that gets the affiliate code from a request object if it exists Args: request (django.http.request.HttpRequest): A request Returns: Optional[str]: The affiliate code (or None) """ return getattr(request, "affiliate...
bigcode/self-oss-instruct-sc2-concepts
def nub(l, reverse=False): """ Removes duplicates from a list. If reverse is true keeps the last duplicate item as opposed to the first. """ if reverse: seen = {} result = [] for item in reversed(l): if item in seen: continue seen[item] = 1 result.append(item) return revers...
bigcode/self-oss-instruct-sc2-concepts
def _validate_bool(value, default): """Validate a boolean value parsed from the config file. @type value: any @param value: Raw value read from config. @type default: bool @param default: Default value to use if the input value isn't valid. @rtype: bool @return: Value to use. """ ...
bigcode/self-oss-instruct-sc2-concepts
def diff21(n): """ dado um inteiro n retorna a diferença absoluta entre n e 21 porém se o número for maior que 21 retorna o dobro da diferença absoluta diff21(19) -> 2 diff21(25) -> 8 dica: abs(x) retorna o valor absoluto de x """ if n > 21: return abs(n - 21) * 2 return abs(...
bigcode/self-oss-instruct-sc2-concepts
def write_score_summary(scores, analogy_types, filename): """ Write score summary to a string :param scores: list of pairs (number of correctly answered questions in category, number of questions in category) :param analogy_types: :param filename: :return: score summary (strin...
bigcode/self-oss-instruct-sc2-concepts
def empty_statement(_evaluator, _ast, _state): """Evaluates empty statement.""" return None, False
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def oss_artifact() -> Path: """ Return the path to a build artifact for DC/OS OSS master. """ return Path('/tmp/dcos_generate_config.sh')
bigcode/self-oss-instruct-sc2-concepts
def two_sum(arr, target): """Function takes in two args, the input array and the target. T: O(n) - We loop through the array once S: O(n) - We use an extra data structure to store the target-curr :param arr: Input array :param target: Target :return: list of two numbers, else empty a...
bigcode/self-oss-instruct-sc2-concepts
import torch def MRR(logits, target): """ Compute mean reciprocal rank. :param logits: 2d tensor [batch_size x rel_docs_per_query] :param target: 2d tensor [batch_size x rel_docs_per_query] :return: mean reciprocal rank [a float value] """ assert logits.size() == target.size() sorted,...
bigcode/self-oss-instruct-sc2-concepts
def update_query_object(query, data, exceptions=[]): """Iterates over given data object. Set attributes to SQLAlchemy query. Args: query (obj): SQLAlchemy query object data (obj): Given request's arguments from JSON exceptions (list): Keys for which iteration ...
bigcode/self-oss-instruct-sc2-concepts
def pv_f(fv, r, n): """Objective: estimate present value fv : = future value r : = rate of discount n : = num of iterations (usually num of years, num of months etc) fv formula : pv = -------- (1 + r) ^ n """ pv = 0 iCount = 0 for cash in fv: ...
bigcode/self-oss-instruct-sc2-concepts
def _deep_get(instance, path): """ Descend path to return a deep element in the JSON object instance. """ for key in path: instance = instance[key] return instance
bigcode/self-oss-instruct-sc2-concepts
def _is_db_connection_error(args): """Return True if error in connecting to db.""" # NOTE(adam_g): This is currently MySQL specific and needs to be extended # to support Postgres and others. conn_err_codes = ('2002', '2003', '2006') for err_code in conn_err_codes: if args.find(...
bigcode/self-oss-instruct-sc2-concepts
def linear_full_overlap(dep_t, dep_h): """Checks whether both the head and dependent of the triplets match.""" return (dep_h[0] in dep_t[0]) and (dep_h[2] in dep_t[2])
bigcode/self-oss-instruct-sc2-concepts
def points_2_xywh(box): """ Converts [xmin, ymin, xmax, ymax] to [xmin, ymin, width, height]. """ box = [box[0], box[1], box[2] - box[0], box[3] - box[1]] box = [int(round(x)) for x in box] return box
bigcode/self-oss-instruct-sc2-concepts
def _find_appliance(oneandone_conn, appliance): """ Validates the appliance exists by ID or name. Return the appliance ID. """ for _appliance in oneandone_conn.list_appliances(q='IMAGE'): if appliance in (_appliance['id'], _appliance['name']): return _appliance['id']
bigcode/self-oss-instruct-sc2-concepts
import time def get_datetime_string(format_string='%m:%d:%Y:%X'): """ Returns a string representation of current (local) time :kw format_string: Format string to pass to strftime (optional) """ return time.strftime(format_string, time.localtime())
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def sanitize_for_latex(text): """ Sanitzes text for use within LaTeX. Escapes LaTeX special characters in order to prevent errors. """ escape = '%_&~' replacers = (lambda s: s.replace(e, r'\{}'.format(e)) for e in escape) return reduce(lambda s, f: f(s), replacers,...
bigcode/self-oss-instruct-sc2-concepts
def make_free_energy_lines(condition_lambda0, condition_lambda1, alchemical_molecule, lambda_step, starting_lambda=0, couple_intramol='no', sc_alpha=0.5, ...
bigcode/self-oss-instruct-sc2-concepts
def get_gdrive_id(url): """ Returns the gdrive ID by splitting with the delimiter "/" and getting the element on index 5 which is usually the gdrive ID for a file or folder Requires one argument to be defined: - The gdrive link (string) """ url = url.split("/")[5] if "?" in url: url = url.s...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def split_quoted_string(string_to_split: str, character_to_split_at: str = ",", strip: bool = False) -> List[str]: """ Split a string but obey quoted parts. from: "first, string", second string to: ['first, string', 'second string'] Parameters ---------- ...
bigcode/self-oss-instruct-sc2-concepts
def postprocess(path,line1,line2): """return data as an array... turn data that looks like this: 100 0.98299944 200 1.00444448 300 0.95629907 into something that looks like this: [[100, 0.98299944], [200, 1.00444448], [300, 0.95629907], ... ]""" y = [] d...
bigcode/self-oss-instruct-sc2-concepts
import re def ValidateKeyId(key_id): """Ensures a key id is well structured.""" # Keys are hexadecimal return re.match(r'[a-z0-9]+', key_id)
bigcode/self-oss-instruct-sc2-concepts
def _get_color_definitions(data): """Returns the list of custom color definitions for the TikZ file. """ definitions = [] fmt = "\\definecolor{{{}}}{{rgb}}{{" + ",".join(3 * [data["float format"]]) + "}}" for name, rgb in data["custom colors"].items(): definitions.append(fmt.format(name, rgb...
bigcode/self-oss-instruct-sc2-concepts
def create_multiset_format(n, rs, pfs): """ Function that converts the given n, rs and pfs into a multiset format. Arguments ========= n: Total length of the permutations rs: How many of each non-X elements should be present within each permutation pfs: The value of each non-X prime factor ...
bigcode/self-oss-instruct-sc2-concepts
import logging def is_db_user_superuser(conn): """Function to test whether the current DB user is a PostgreSQL superuser.""" logger = logging.getLogger('dirbs.db') with conn.cursor() as cur: cur.execute("""SELECT rolsuper FROM pg_roles WHERE rolname...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Tuple def my_quat_conjugate(q: Sequence[float]) -> Tuple[float,float,float,float]: """ "invert" or "reverse" or "conjugate" a quaternion by negating the x/y/z components. :param q: 4x float, W X Y Z quaternion :return: 4x float, W X Y Z quaternion """ return q[0]...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Sequence def arg_str_seq_none(inputs, name): """Simple input handler. Parameters ---------- inputs : None, string, or iterable of strings Input value(s) provided by caller name : string Name of input, used for producing a meaningful er...
bigcode/self-oss-instruct-sc2-concepts
from typing import MutableMapping from typing import Any def flatten( dictionary: MutableMapping[Any, Any], separator: str = ".", parent_key=False ): """ Turn a nested dictionary into a flattened dictionary Parameters: dictionary: dictionary The dictionary to flatten paren...
bigcode/self-oss-instruct-sc2-concepts
def ramp(x): """smooth ramp function from curl noise paper""" if x > 1.0: return 1.0 elif x < -1.0: return -1.0 else: return 15.0 / 8.0 * x - 10.0 / 8.0 * x * x * x + 3.0 / 8.0 * x * x * x * x * x
bigcode/self-oss-instruct-sc2-concepts
import statistics def score(text, *score_functions): """Score ``text`` using ``score_functions``. Examples: >>> score("abc", function_a) >>> score("abc", function_a, function_b) Args: text (str): The text to score *score_functions (variable length argument list): function...
bigcode/self-oss-instruct-sc2-concepts
def line_lister(line): """ Returns a a list of stripped line split on ','. """ return [li.strip() for li in line.split(',')]
bigcode/self-oss-instruct-sc2-concepts
def ip_key(key): """Function to make a 'canonical' IP string for sorting. The given IP has each subfield expanded to 3 numeric digits, eg: given '1.255.24.6' return '001.255.014.006' """ ip = key[0] fields = ip.split('.') result = [] for f in fields: result.append('%03d' % ...
bigcode/self-oss-instruct-sc2-concepts
def to_camel_case(snake_case): """ convert a snake_case string to camelCase """ components = snake_case.split('_') return components[0] + "".join(x.title() for x in components[1:])
bigcode/self-oss-instruct-sc2-concepts
import re def RemoveLocations(test_output): """Removes all file location info from a Google Test program's output. Args: test_output: the output of a Google Test program. Returns: output with all file location info (in the form of 'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or 'DIRECTORY\\...
bigcode/self-oss-instruct-sc2-concepts
def _ValidateReplicationFlags(flag_dict): """Verifies correct usage of the bigtable replication flags.""" return (not flag_dict['bigtable_replication_cluster'] or flag_dict['bigtable_replication_cluster_zone'])
bigcode/self-oss-instruct-sc2-concepts