seed
stringlengths
1
14k
source
stringclasses
2 values
def strip_hydrogen(atoms, bonds): """ Remove hydrogens from the atom and bond tables. """ atoms = atoms[atoms['element'] != 'H'] bonds = bonds[bonds['start'].isin(atoms['atom']) & bonds['end'].isin(atoms['atom'])] return (atoms, bonds)
bigcode/self-oss-instruct-sc2-concepts
import torch def entropy(probs): """ Computes the entropy of a normalized probability distribution. """ return -(torch.log(probs) * probs).sum(dim=-1)
bigcode/self-oss-instruct-sc2-concepts
def construct_address(host, port, route, args): """ {host}:{port}{route}?{'&'.join(args)} :param str host: '172.0.0.1' :param str port: '5000' :param str route: '/store/file/here' :param list[str] args: ['a=b', 'c=d'] """ return f"http://{host}:{port}{route}?{'&'.joi...
bigcode/self-oss-instruct-sc2-concepts
def get_repo_name(url: str) -> str: """ Get the name of the repo. :param url: The URL on which the name of the repo will be retrieved. :return: The name of the repo. """ return url.split('https://github.com/')[1].split('/')[1]
bigcode/self-oss-instruct-sc2-concepts
import errno def retry_when_interrupt(f, *a, **kw): """ Call C{f} with the given arguments, handling C{EINTR} by retrying. @param f: A function to call. @param *a: Positional arguments to pass to C{f}. @param **kw: Keyword arguments to pass to C{f}. @return: Whatever C{f} returns. ...
bigcode/self-oss-instruct-sc2-concepts
def first(the_iterable, condition=lambda x: True): """ Finds first item in iterable that meets condition """ for i in the_iterable: if condition(i): return i return None
bigcode/self-oss-instruct-sc2-concepts
def beta_moments(mean, sd): """Calculates the moments of a beta distribution based on mean and sd as they are more intuitive inputs More info on beta: https://en.wikipedia.org/wiki/Beta_distribution Inputs: mean - a float - the chosen mean of the distribution sd - a float ...
bigcode/self-oss-instruct-sc2-concepts
def find_in_response(resp, query): """ check if HTTP response contains 'to_find' string returns True if found, False otherwise """ return True if query in resp else False
bigcode/self-oss-instruct-sc2-concepts
import math def get_page_number_from_post(post_id:int) -> int: """Calculate the page number of a given post by assuming each game thread page has 30 posts. Args: post_id (int): The ID of the post of interest. Returns: int: The page number of the input post. """ page_number = ...
bigcode/self-oss-instruct-sc2-concepts
import re def reFindNext ( v, pos, pattern, bodyFlag, reFlags = None ): """ reFindNext: use re.search() to find pattern in a Leo outline. v the vnode to start the search. pos the position within the body text of v to start the search. pattern the search string bodyFlag true: search body text. false: se...
bigcode/self-oss-instruct-sc2-concepts
def dice_parser(text): """ A basic dice parser that takes a string of the type: x_1 D y_1 + x_2 D y_2 + .... x_n D y_n and converts it into two lists of dice amount and dice type Parameters: ----- text: string contains the text we want to parse Returns: ----- ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def station_by_name(station_list: List[dict], station_name: str) -> int: """Returns the current index of a station. The starting point is the name of the station. If no station with this name exists, -1 is returned. """ for index, station in enumerate(station_list): if...
bigcode/self-oss-instruct-sc2-concepts
import json def example_filter(request): """ Filters out reports with a 'document-uri' not from included.com. """ report = json.loads(request.body) doc_uri = report.get('document-uri', '') if doc_uri.startswith('http://included.com'): return True return False
bigcode/self-oss-instruct-sc2-concepts
def get_dimensions(corners): """ Get the dimension of a position based on the distance of its corners. This is used to determine the feild of view of a zoom :param corners: list containing 4 points with (x,y) values :return: (x,y) dimension of the position """ x0, y0 = corners[0] x1, y1 ...
bigcode/self-oss-instruct-sc2-concepts
import torch def tensor2onehot(labels): """Convert label tensor to label onehot tensor. Parameters ---------- labels : torch.LongTensor node labels Returns ------- torch.LongTensor onehot labels tensor """ eye = torch.eye(labels.max() + 1) onehot_mx = eye[la...
bigcode/self-oss-instruct-sc2-concepts
def startswith(prefix): """ Create a function that checks if the argument that is passed in starts with string :param str prefix: string to check the start for :return func startswith_function: a function that checks if the argument starts with the specified string """ def string_starts_...
bigcode/self-oss-instruct-sc2-concepts
def _answer(result, line): """Answer the question as best as we can""" msgs = [u"Q: {}".format(result["Input"][1])] del result["Input"] for pod_type in ["Result", "Solution", "Derivative"]: if pod_type in result: msgs.append(u"A: {}".format(result[pod_type][1])) return '...
bigcode/self-oss-instruct-sc2-concepts
import math def log_activation(x): """ Returns the log of x. """ return math.log(x)
bigcode/self-oss-instruct-sc2-concepts
import math def convtransp_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of transposed convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w = (h_w, h_w) if type(kernel_size) is n...
bigcode/self-oss-instruct-sc2-concepts
def normalize_whitespace(sent): """Substitutes extra contiguous whitespaces with a single whitespace""" return ' '.join(sent.strip().split())
bigcode/self-oss-instruct-sc2-concepts
def _size_crop(width, height): """Performs a cropping resize.""" return ("-vf", r"scale=max({height}*(iw/ih)\,{width}):max({width}/(iw/ih)\,{height}),crop={width}:{height}".format(width=width, height=height),)
bigcode/self-oss-instruct-sc2-concepts
def order_entries(files): """Re-order the file entries, if an order is given.""" order = files.get("order") files = files.get("entries", []) if order: files_ = files.copy() keys = [f["key"] for f in files] def get_file(key): idx = keys.index(key) keys.pop...
bigcode/self-oss-instruct-sc2-concepts
import socket def is_valid_ipv4(ip_str): """ Check the validity of an IPv4 address """ try: socket.inet_pton(socket.AF_INET, ip_str) except AttributeError: try: # Fall-back on legacy API or False socket.inet_aton(ip_str) except (AttributeError, socket.error): ...
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 from typing import Callable from typing import Optional def sql_binary_search( connection: sqlite3.Connection, table: str, column_value: str, column_index: str, fun_compare: Callable[[float], bool], *, lower_bound: bool = True, ) -> Optional[int]: """ Helper function...
bigcode/self-oss-instruct-sc2-concepts
def getReportPath(job, reportType): """ Return the filename for the error report. Does not include the folder to avoid conflicting with the S3 getSignedUrl method. """ path = 'submission_{}_{}_{}_report.csv'.format(job.submission_id, job.file_type.name, reportType) return path
bigcode/self-oss-instruct-sc2-concepts
def warmup_lines_to_chop(benchmark, warmup): """Returns the number of lines to be excluded from final measurements. """ # The main benchmark emits its own line. lines_to_chop = warmup # Each of the child benchmarks emit their own line. lines_to_chop += warmup * len(benchmark.children) # hhv...
bigcode/self-oss-instruct-sc2-concepts
def get_build(cloudbuild, image_project, build_id): """Get build object from cloudbuild.""" return cloudbuild.projects().builds().get(projectId=image_project, id=build_id).execute()
bigcode/self-oss-instruct-sc2-concepts
def get_fabric_ip_networks(cfmclient, fabric_uuid=None): """ Get a list of IP networks from the Composable Fabric. :param cfmclient: :param fabric_uuid: UUID of fabric :return: list of IP address dict objects :rtype: list """ path = 'v1/fabric_ip_networks' if fabric_uuid: pat...
bigcode/self-oss-instruct-sc2-concepts
import base64 def np_to_json(obj, prefix_name=""): """Serialize numpy.ndarray obj :param prefix_name: unique name for this array. :param obj: numpy.ndarray""" return {"{}_frame".format(prefix_name): base64.b64encode(obj.tostring()).decode("utf-8"), "{}_dtype".format(prefix_name): obj.dtype...
bigcode/self-oss-instruct-sc2-concepts
def label_gen(index): """Generates label set for individual gaussian index = index of peak location output string format: 'a' + index + "_" + parameter""" # generates unique parameter strings based on index of peak pref = str(int(index)) comb = 'a' + pref + '_' cent = 'center' sig = ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def compute_forgetfulness(correctness_trend: List[float]) -> int: """ Given a epoch-wise trend of train predictions, compute frequency with which an example is forgotten, i.e. predicted incorrectly _after_ being predicted correctly. Based on: https://arxiv.org/abs/1812.05159 """ if...
bigcode/self-oss-instruct-sc2-concepts
import cmath import math def op_tan(x): """Returns the tangent of this mathematical object.""" if isinstance(x, list): return [op_tan(a) for a in x] elif isinstance(x, complex): return cmath.tan(x) else: return math.tan(x)
bigcode/self-oss-instruct-sc2-concepts
def get_label_filter(input_labels): """ Allow labels input to be formatted like: -lb key1:value -lb key2:value AND -lb key1:value,key2:value Output: key1:value,key2:value :param list(str) input_labels: list of labels, like, ['key1:value1', 'key2:value2'] or ['key1:value1,key2:valu...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from datetime import datetime import pytz def date_from_string(dtstr: str, fmt: str, timezone: str) -> Optional[datetime]: """Get datetime object from a date string. Args: dtstr: input date string fmt: datetime format string timezone: time zone string Return...
bigcode/self-oss-instruct-sc2-concepts
def AioNodeNameFromMotorNickname(motor): """Returns AIO node name for the specified motor.""" return 'kAioNodeMotor' + motor.capitalize()
bigcode/self-oss-instruct-sc2-concepts
def get_rc(sequence): """Returns the reverse complement of sequence. Sequence may only contain letters A, C, G, or T (in uppercase).""" table = ['A', 'C', 'G', 'T'] sequence = list(sequence) for key, value in enumerate(sequence): sequence[key] = table[3 - table.index(value)] return...
bigcode/self-oss-instruct-sc2-concepts
def _is_part_dsn(msg): """ Receive a MIME part and returns True if it is a DSN False is returned otherwise """ if len(msg) <= 1: return False if msg[1].get_content_type() != 'message/delivery-status': return False return True
bigcode/self-oss-instruct-sc2-concepts
def join_s3_uri(bucket, key): """ Join AWS S3 URI from bucket and key. :type bucket: str :type key: str :rtype: str """ return "s3://{}/{}".format(bucket, key)
bigcode/self-oss-instruct-sc2-concepts
def lustre_ost_id(fsname, ost_index): """ Return the Lustre client ID """ return "%s:%s" % (fsname, ost_index)
bigcode/self-oss-instruct-sc2-concepts
def default_authority(pyramid_request): """ Return the test env request's default authority, i.e. 'example.com' Return the default authority—this automatically has a `__world__` group """ return pyramid_request.default_authority
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any from typing import Tuple from typing import Sequence def prepare_kwargs( kwargs: Dict[str, Any] ) -> Tuple[Sequence[str], Sequence[Any], Sequence[str]]: """Create three sequences from the provided kwargs. The first sequence is the keys of the kwargs. The second seque...
bigcode/self-oss-instruct-sc2-concepts
def ne(x, y): """Not equal""" return x != y
bigcode/self-oss-instruct-sc2-concepts
def remove_anchor(url: str) -> str: """ Removes anchor from URL :param url: :return: """ anchor_pos = url.find('#') return url[:anchor_pos] if anchor_pos > 0 else url
bigcode/self-oss-instruct-sc2-concepts
def admin2_urlname(view, action): """ Converts the view and the specified action into a valid namespaced URLConf name. """ return 'admin2:%s_%s_%s' % (view.app_label, view.model_name, action)
bigcode/self-oss-instruct-sc2-concepts
def get_kmer_from_index(kmax, index): """ takes a number (essentially base 4) and returns the kmer it corresponds to in alphabetical order eg. AAAA = 0*1 CA = 4*4 + 0*1 GC = 3*4 + 1 * 1 """ bases = 'ACGT' out = '' for k in range(kmax - 1, -1, -1): face, index = divmod...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Dict def bbox_to_geojson(bbox: Tuple) -> Dict: """Return bbox geojson feature.""" return { "geometry": { "type": "Polygon", "coordinates": [ [ [bbox[0], bbox[3]], [bbox[0], bbox[...
bigcode/self-oss-instruct-sc2-concepts
def permute_data(x, pe_dir): """ This function permutes data of the tensor x of size (batch, n_channels, 1st_size, ..., nth_size) so that the PE direction become the first dimension (except the batch and n_channels dimensions). :param x: the tensor of size (batch, n_channels, 1st_size, ..., nth_size) ...
bigcode/self-oss-instruct-sc2-concepts
def is_pandigital(n_str, k): """Verify number is pandigital.""" if len(n_str) == k and set(n_str) == set('123456789'[:k]): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
import itertools def construct_game_queries(base_profile, num_checkpts): """Constructs a list of checkpoint selection tuples to query value function. Each query tuple (key, query) where key = (pi, pj) and query is (p1's selected checkpt, ..., p7's selected checkpt) fixes the players in the game of diplomacy ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import List from typing import OrderedDict def order_json(data, sort_fn: Callable[[List[str]], List[str]] = sorted): """Sort json to a consistent order. When you hash json that has the some content but is different orders you get different fingerprints. .. cod...
bigcode/self-oss-instruct-sc2-concepts
import gzip def smart_open(path, *args, **kwargs): """Opens files directly or through gzip depending on extension.""" if path.endswith('.gz'): return gzip.open(path, *args, **kwargs) else: return open(path, *args, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
def tcp_traceflow(frame, *, data_link): """Trace packet flow for TCP. Args: frame (pcapkit.protocols.pcap.frame.Frame): PCAP frame. Keyword Args: data_link (str): Data link layer protocol (from global header). Returns: Tuple[bool, Dict[str, Any]]: A tuple of data for TCP reass...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def ip_port_hostname_from_svname(svname: str) -> Tuple[str, int, str]: """This parses the haproxy svname that smartstack creates. In old versions of synapse, this is in the format ip:port_hostname. In versions newer than dd5843c987740a5d5ce1c83b12b258b7253784a8 it is hostname_...
bigcode/self-oss-instruct-sc2-concepts
def ConstantTimeIsEqual(a, b): """Securely compare two strings without leaking timing information.""" if len(a) != len(b): return False acc = 0 for x, y in zip(a, b): acc |= ord(x) ^ ord(y) return acc == 0
bigcode/self-oss-instruct-sc2-concepts
import math def make_ids(n: int, prefix: str = "id_"): """ Return a length ``n`` list of unique sequentially labelled strings for use as IDs. Example:: >>> make_ids(11, prefix="s") ['s00', s01', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10'] """ if n < 1: ...
bigcode/self-oss-instruct-sc2-concepts
import math def generate_IDF(corpus, corpus_dict, total_queries): """ Function to generate IDF for all the words in the vocab. :param corpus: Corpus of words in the queries. :param corpus_dict: Mapping of query number and its corpus. :param total_queries: Total number of queries. :return idf_d...
bigcode/self-oss-instruct-sc2-concepts
import re def truncate(text, max_len=250, suffix="..."): """ Truncate a text string to a certain number of characters, trimming to the nearest word boundary. """ stripped = text.strip() if len(stripped) <= max_len: return stripped substr = stripped[0:max_len + 1] words = " ".jo...
bigcode/self-oss-instruct-sc2-concepts
def coding_problem_08(btree): """ A unival tree (which stands for "universal value") is a tree where all nodes have the same value. Given the root to a binary tree, count the number of unival subtrees. Example: >>> btree = (0, (0, (0, None, None), (0, (0, None, None), (0, None, None))), (1, None, N...
bigcode/self-oss-instruct-sc2-concepts
def get_first_years_performance(school): """ Returns performance indicator for this school, as well as an indicator (1-5; 3 is average, 1 is worse, 5 is better) that compares the school to the national average. """ performance = {} ratio = school['renondb'].strip() # bolletje compare...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def prepend_escape_character(escape_character_list: List[str], keyword: str) -> str: """Add escape character. If the argument 'keyword' contains the characters specified in 'escape_character_list', an escape character is added to the target character. Args: escape_cha...
bigcode/self-oss-instruct-sc2-concepts
def timetostr(dtime): """ Convert datetime into a string """ return dtime.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
bigcode/self-oss-instruct-sc2-concepts
def ngrams(input, n): """ Creates a set of strings with 'n' words :param input: The string to be split :param n: integer :return: set of strings with 'n' words """ input = input.split(' ') output = [] for i in range(len(input) - n + 1): output.append(input[i:i + n]) retu...
bigcode/self-oss-instruct-sc2-concepts
def add2(x, y): """ Add up two numbers """ return x + y
bigcode/self-oss-instruct-sc2-concepts
def scale(v, num): """ :param v: The vector we want to scale :param num: Scale amount :return: vector scaled by num """ a, b, c = v return (a*num, b*num, c*num)
bigcode/self-oss-instruct-sc2-concepts
def has_cyber_observable_data(instance): """Return True only if the given instance is an observed-data object containing STIX Cyber Observable objects. """ if (instance['type'] == 'observed-data' and 'objects' in instance and type(instance['objects']) is dict): return Tru...
bigcode/self-oss-instruct-sc2-concepts
def package_url(package_name): """Return fully-qualified URL to package on PyPI (JSON endpoint).""" return "https://pypi.python.org/pypi/%s/json" % package_name
bigcode/self-oss-instruct-sc2-concepts
def factorial(num: int) -> int: """ >>> factorial(7) 5040 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Number should not be negative. >>> [factorial(i) for i in range(10)] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] """ if num < 0: raise ...
bigcode/self-oss-instruct-sc2-concepts
def sub_with_none(v1,v2): """ Substract treating None as zero """ p1 = v1 is None p2 = v2 is None if p1 and p2: return None elif p1: return -v2 elif p2: return v1 else: return v1 - v2
bigcode/self-oss-instruct-sc2-concepts
def make_depth_safe(cube): """ Make the depth coordinate safe. If the depth coordinate has a value of zero or above, we replace the zero with the average point of the first depth layer. Parameters ---------- cube: iris.cube.Cube Input cube to make the depth coordinate safe Ret...
bigcode/self-oss-instruct-sc2-concepts
def __access_member_by_string(x, member): """ Return the result of x.#member or x.#member() where member is the name of the function/variable. :param x: Element to operate on :param member: Function or value member :return: """ action = getattr(x, member) if callable(action): ...
bigcode/self-oss-instruct-sc2-concepts
def sponsors_benefit_is_complete(orm, sponsor, name): """Return True - benefit is complete, False - benefit is not complete, or None - benefit not applicable for this sponsor's level """ if orm.BenefitLevel.objects.filter(level=sponsor.level, benefit__name=name).exists(): try: ...
bigcode/self-oss-instruct-sc2-concepts
import json def transform_kval_json_str(st): """ BQ + python transforms hist `values` attribute from {"k": v} => [{'key': k, 'value': v}]. This undoes this. """ d = json.loads(st) values = d.pop("values") values_dct = {str(d["key"]): d["value"] for d in values} d["values"] = values...
bigcode/self-oss-instruct-sc2-concepts
def overlap(a, b, min_length=3): """ Return length of longest suffix of 'a' matching a prefix of 'b' that is at least 'min_length' characters long. If no such overlap exists, return 0. """ start = 0 # start all the way at the left while True: start = a.find(b[:min_length], start) # look for b's suffx in a...
bigcode/self-oss-instruct-sc2-concepts
def halve_res_quick(array): """ Halves the resolution of the input 2D array, e.g. from 0.5km to 1km, by averaging every 2x2 grid of pixels into 1 pixel. :param array: 2D numpy array of data. :return: 2D numpy array with half the resolution of the input array. """ # Define ne...
bigcode/self-oss-instruct-sc2-concepts
def uniquify(s, delimiter=";"): """ Helper function It simplifies a delimited string with redundant fields if one unique field exist, a string is returned otherwise a list of the unique elements from the string is returned """ s = s.split(delimiter) s = list(set(s)) if len(s)==1: return s[0] ...
bigcode/self-oss-instruct-sc2-concepts
def args_from_id(id, arg_ranges): """Convert a single id number to the corresponding set of arguments""" args = list() for arg_range in arg_ranges: i = id % len(arg_range) id = id // len(arg_range) args.append(arg_range[i]) return tuple(args)
bigcode/self-oss-instruct-sc2-concepts
def extract_headers(event): """ Returns the headers from the request The format is: a dict of {name: value_list} where value_list is an iterable of all header values. Supports regular and multivalue headers. """ headers = event.get('headers') or {} multi_headers = (event.get('multiValueHea...
bigcode/self-oss-instruct-sc2-concepts
def interval_overlap_length(i1,i2): """Compute the length of overlap of two intervals. Parameters ---------- i1, i2 : pairs of two floats The two intervals. Returns ------- l : float The length of the overlap between the two intervals. """ (a,b) = i1 (c...
bigcode/self-oss-instruct-sc2-concepts
import base64 def _urlsafe_b64encode(s: bytes) -> bytes: """ Base 64 URL safe encoding with no padding. :param s: input str to be encoded :return: encoded bytes """ return base64.urlsafe_b64encode(s).rstrip(b"=")
bigcode/self-oss-instruct-sc2-concepts
def myTwistFunction(Epsilon): """User-defined function describing the variation of twist as a function of the leading edge coordinate.""" RootTwist = 0 TipTwist = -2 return RootTwist + Epsilon * TipTwist
bigcode/self-oss-instruct-sc2-concepts
import re def as_size(size): """ Return a size string as an integer """ if isinstance(size, (int, float,)): return int(size) # exact size in a string m = re.match(r'^\d+$', size) if m: return int(size) # gigabytes m = re.match(r'^([\d\.]+)gb?$', size, flags=re.I) ...
bigcode/self-oss-instruct-sc2-concepts
def thermal_time_constant_as_considered_load(TauR, dTOr, dTOi, dTOu, n): """ Returns the average oil time constant in minutes (for a given load) As per IEEE C57.91-2011 TauR = Thermal time constant at rated load dTOr = Top oil rise at rated load dTOi = Top oil rise initial dTOu = Top oil rise ul...
bigcode/self-oss-instruct-sc2-concepts
def from_settings(settings): """Return a dict created from application settings. Args: settings (dict): An application's settings. Returns: dict: The database-specific settings, formatted to use with :func:`connection_url`. """ return { k.replace('DATABASE_', '...
bigcode/self-oss-instruct-sc2-concepts
import time def timeit(method): """ A Python decorator for printing out the execution time for a function. Adapted from: www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods """ def timed(*args, **kw): time_start = time.time() result = m...
bigcode/self-oss-instruct-sc2-concepts
def offset_to_next_multiple(num, mult): """Calculates the amount needed to round num upward to the next multiple of mult. If num is divisible by mult, then this returns 0, not mult. """ if mult == 0: return 0 else: offset = mult - (num % mult) if offset == mult: ...
bigcode/self-oss-instruct-sc2-concepts
def secondary_spherical(rho, phi): """Zernike secondary spherical.""" return 20 * rho**6 + - 30 * rho**4 + 12 * rho**2 - 1
bigcode/self-oss-instruct-sc2-concepts
def get_hesitancy_dict(geo_df): """ Return dictionary of hesitancy proportions. Input: geo_df: (dataframe) location geomatic dataframe typically output from get_county_mapping_data(). Output: Dictionary with keys not_hesitant, hesitant_or_unsure, and strongly_hesita...
bigcode/self-oss-instruct-sc2-concepts
def fixed_embeddings_name(channel_id): """Returns the name of the fixed embedding matrix for some channel ID.""" return 'fixed_embedding_matrix_%d' % channel_id
bigcode/self-oss-instruct-sc2-concepts
import json def convert_format_in_metrics_list(metrics): """Converts from human-friendly metadata format to BigQuery friendly format. Before: 'metadata': {'file': 'example.py'} After: 'metadata': [{'key': 'file', 'value': '"example.py"'}] Args: metrics: A list of metrics dicts. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def postorder_traversal(node): """ recursive implementation of postorder traversal in which root is processed after left and right child :param node: Node of a binary tree """ if node is None: return None postorder_traversal(node.left) postorder_traversal(node.right) print(node....
bigcode/self-oss-instruct-sc2-concepts
def uniform_but_one_dataset_no_weight(n, p): """Generates an unweighted dataset according to the AMS lower bound. Args: n: The size of the dataset p: The frequency moment (used as a parameter in the lower bound) Returns: A list of keys, where all keys appear once, except for one key which accoun...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import List from typing import Tuple from typing import Any import inspect def get_func_arguments_types_defaults(func: Callable) -> List[Tuple[str, Tuple, Any]]: """ Parse function arguments, types and default values Args: func: a function to be xeamined ...
bigcode/self-oss-instruct-sc2-concepts
def get_lines(self): """The list returned contains all the Line of the SurRing Parameters ---------- self : SurfRing A SurfRing object Returns ------- line_list : list list of lines delimiting the surface """ line_list = self.out_surf.get_lines() line_list.ext...
bigcode/self-oss-instruct-sc2-concepts
import binascii def hex(b) -> str: """ Returns the hexily version of the binary datas. :param b: binary datas :return: the string """ return binascii.hexlify(b).decode('utf8')
bigcode/self-oss-instruct-sc2-concepts
def get_last_change(path): """ Figure out when the given path has last changed, recursively if a directory """ last_changed = path.stat().st_mtime if path.is_dir(): for entry in path.glob("**/*"): entry_changed = entry.stat().st_mtime if entry_changed > last_changed:...
bigcode/self-oss-instruct-sc2-concepts
def slice2enlist(s): """Convert a slice object into a list of (new, old) tuples.""" if isinstance(s, (list, tuple)): return enumerate(s) if s.step == None: step = 1 else: step = s.step if s.start == None: start = 0 else: start = s.start return enumerat...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict import six def _extract_simplified_filter_fields(filter_fields): """ Takes the filter_fields and simplifies them to a form django-filter can understand """ # If we are just dealing with a list we are fine if not isinstance(filter_fields, dict): return filter_...
bigcode/self-oss-instruct-sc2-concepts
import html def convert_unicode_to_html(text): """Convert unicode text to HTML by escaping it.""" return html.escape(text).encode("ascii", "xmlcharrefreplace").decode()
bigcode/self-oss-instruct-sc2-concepts
import time def timeMilis(plusSecs=0, plusMins=0, plusHours=0): """ Return current time in milis if no arguments. If arguments are present it will be current time plus argument time. Arguments: plusSecs {int}: Add this amount of seconds to current time plusMins {int}: Add this amount ...
bigcode/self-oss-instruct-sc2-concepts
def _app_complete_on_provider(application, provider): """ Determines if an Application is completely available on a Provider, i.e. all active ApplicationVersions have a ProviderMachine + InstanceSource on given Provider. Args: application: Application object provider: Provider object ...
bigcode/self-oss-instruct-sc2-concepts