content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _is_sub_partition(sets, other_sets): """ Checks if all the sets in one list are subsets of one set in another list. Used by get_ranked_trajectory_partitions Parameters ---------- sets : list of python sets partition to check other_sets : list of python sets partition to ...
b2a1d60245a8d2eca1f753f998ac1d69c8ff9d08
646,120
def scoreClickAUC(num_clicks, num_impressions, predicted_ctr): """ Calculates the area under the ROC curve (AUC) for click rates Parameters ---------- num_clicks : a list containing the number of clicks num_impressions : a list containing the number of impressions predicted_ctr : a li...
5c5d3a6bf6f634e6b39ccdda96cdaca2e54d168a
646,122
import re def multi_replace(target: str, replacements: dict[str, str]) -> str: """Given a string and a replacement map, it returns the replaced string. See https://gist.github.com/bgusach/a967e0587d6e01e889fd1d776c5f3729. Args: target: String to execute replacements on. replacements: Rep...
390047f6525f5fb2025fca818b09e8b80f231244
646,124
def _resolve_name(name, package, level): """Resolve a relative module name to an absolute one.""" bits = package.rsplit('.', level - 1) if len(bits) < level: raise ValueError('attempted relative import beyond top-level package') base = bits[0] return '{}.{}'.format(base, name) if name else b...
fc2df72f07594fd0e0e9d72ccfa870bb235a4868
646,126
def _error(y_true, y_pred): """ Simple error """ return y_true - y_pred
75c5f29a82b89258bf47fa33b6882cbec2d6d2c9
646,127
def lower(value): """ returns the lowercase copy of input string. :param str value: string to make lowercase. :rtype: str """ return value.lower()
266bd0b32bb79a62d4ecc2d0e5bdee55a1bcc05f
646,128
def frange(limit1, limit2 = None, increment = 1.): """ Range function that accepts floats (and integers). Usage: frange(-2, 2, 0.1) frange(10) frange(10, increment = 0.5) The returned value is a list. """ if limit2 is None: limit2, limit1 = limit1, 0. else: limit1 = float(limit1) result =...
a70512b1264a9352bc9e48e88baa41497eb53b32
646,129
import string def letter_part(n): # takes quotient and index """ Function to calculate the lettered part for a given number of parts n Eg. letter_part(1) = 'a', letter_part(26) = 'z', letter_part(27) = 'az', letter_part(702) = zz this is the max Values for n > 702 return None :param n:number of ...
42af53ade009abf86219f42849de9fdf7d56bc2d
646,130
from typing import List from typing import Dict def get_distribution(labels: List[str]) -> Dict[str, int]: """ Get the distribution of the labels. Prameters --------- labels : List[str] This list is non-unique. Returns ------- distribution : Dict[str, int] Maps (label...
cbc42b4cbdc8924226979e1fe63e3cb0b409efba
646,133
def fc_forward(mat_x, mat_w, vec_b): """Forward pass of Fully-Connected layer. A good reference for this is: http://cs231n.github.io/linear-classify/#score Args: mat_x: NxD ndarray, N is number of features, D is length of feature vector mat_w: DxC ndarray, C is number of classes. vec_b: length C nda...
5ab37b3a58e23a0c4b57162ea373aa4b8ad9a988
646,135
def one_semitone_up(freq, amount=1): """ Returns the key, one semitone up :param freq: the frequency in hz :param amount: the amount of semitones up :return: the frequency one tone up in hz """ return freq * 2 ** (amount / 12)
c7db7202e992c4d4b9cd5e8d778bbd8854196737
646,136
def srange(characters): """Construct a list with all characters in the string""" return [c for c in characters]
bebae3c6ef5a056a2e97a47f722463dca6829759
646,140
import json def deserialize(recipe): """Deserialise JSON strings.""" recipe["tags"] = json.loads(recipe.get("tags", [])) recipe["newTags"] = json.loads(recipe.get("newTags", {})) return recipe
0ba065157ba3b1c91225814c0312f305db30722e
646,141
def extract_used_columns_from_nba_response(nba_response, desired_column_headers): """ Keeps all columns specified in desired_column_headers and returns the processed list of rows. """ try: desired_column_indicies = [nba_response.headers.index( header) for header in desired_column...
4e2f4d0b0a160d563f0ce4a6f698c7a8a2087c44
646,151
import pickle def load_pickle(filename): """ Load saved data from pickle file :param filename: pickle file name :return: data from pickle file """ with open(filename, "rb") as f: data = pickle.load(f) return data
aabb0fb57fca48ef53c75129d662bf82f683d978
646,153
import re def only_numbers(string): """Return a string w only the numbers from the given string""" return re.sub("\D", "", string)
99bf3aeae8a462c5f6b2f217445d8d2fc616984e
646,158
from typing import Union def _get_address_from_instance_response(instance_response: dict) -> Union[str, None]: """ Extracts the instance's IP address (public if possible, private if not) from the boto3 response dict :param instance_response: Boto3 response dict :return: IP address of the instance (pub...
08c7623ec2d1e0af8a36b3fafdf8439ae818c80f
646,160
def decode(b): """Decodes as UTF-8""" return b.decode('UTF-8')
f717dfe10945a25b5d9548482c8b828aa17baad3
646,162
def return_all(columns): """ Check if all columns should be returned """ return columns is None
cebd501fa37df08063513f0ae623678a13f659bf
646,164
import ast def get_functions(_ast): """ Gets all function definitions immediately below an ast node @param _ast the ast node to search for functions in @return a tuple of function definition ast nodes """ return (node for node in _ast.body if isinstance(node, ast.FunctionDef))
8d9816b9ea6c20090e72e833644c69dbf982d436
646,166
from typing import List def fibonacci_sequence(n) -> List[int]: """Generate n+1 terms of the fibonacci sequence""" fibo_sequence = [0, 1] a, b = fibo_sequence for i in range(2, n+1): a, b = b, a + b fibo_sequence += [b] return fibo_sequence
861fee1758d9ac3496af1e1cd9af048846038bc1
646,167
from typing import Sequence from typing import Optional def _pick_remote_uri(uris: Sequence[str]) -> Optional[int]: """ Return the offset of the first uri with a remote path, if any. """ for i, uri in enumerate(uris): scheme, *_ = uri.split(":") if scheme in ("https", "http", "ftp", "s...
c4ce40dda5778b57890d000131bf2ec5a6bb5170
646,173
def bool_converter(value): """Simple string to bool converter (0 = False, 1 = True).""" return value == "1"
06962569a732b176f0a904ab4cf186a634f01f1a
646,175
def CheckChangeHasNoCR(input_api, output_api, source_file_filter=None): """Checks no '\r' (CR) character is in any source files.""" cr_files = [] for f in input_api.AffectedSourceFiles(source_file_filter): if '\r' in input_api.ReadFile(f, 'rb'): cr_files.append(f.LocalPath()) if cr_files: return [...
c9649f5f5e35c04f6f13d88b81823571f67cfb44
646,176
from typing import List def simple_clean_cells(cells: List) -> List: """ Removes cells that lack a bounding box or have a volume equal to 0 Args: cells: List of spatial features Returns: List of spatial features """ return [cell for cell in cells if len(cell.get_...
2904b961127d0250c13e8a2647c9745dfa396981
646,185
def get_noaa_url(start, end, station): """ Formats url with params for tides request from NOAA. Args: start (int or str): YYYYMMDD start date. end (int or str): YYYYMMDD end date (max 30 days from start). station (int or str): NOAA station ID. Returns: URL for NOAA tides ca...
992af0db89bb5a61baf71beaac213d815fb9e2f6
646,186
import torch def is_loss(module): """Return whether `module` is a `torch` loss function. Args: module (torch.nn.Module): A PyTorch module. Returns: bool: Whether `module` is a loss function. """ return isinstance(module, torch.nn.modules.loss._Loss)
b106c327c1c1ba24b55acae588224af493dfc7f4
646,188
def GetLabel(plist): """Plists have a label.""" return plist['Label']
b6692b603c72e829fe819e22dc219905f6db151f
646,196
import math def get_evaldiff(evalue1, evalue2): """Return absolute value of the order of magnitude evalue difference for two given E-values. """ return round(abs(math.log(float(evalue1),10) - math.log(float(evalue2),10)))
7919a3213c6ca3ba671b541281cba05856fcbe2d
646,201
def get_initial_lock_expiration(block_number, settle_timeout): """ Returns the expiration for first hash-time-lock in a mediated transfer. """ # The initiator doesn't need to learn the secret, so there is no need to # decrement reveal_timeout from the settle_timeout. # # The lock_expiration could be...
e125518810afd65950f77586f0036ac32e7b1b4b
646,202
def catch_input(default_value, desired_type, input_message = "Input: ", failure_message = "Invalid input.", default_message = "Default value used.", num_attempts = 3): """ Function to better catch type errors in user input. If the input can be parsed using desired_type, th...
c3177bfabff11c9875e6ef80c22f06d251b2447a
646,203
import torch from typing import Union def knn_gather( x: torch.Tensor, idx: torch.Tensor, lengths: Union[torch.Tensor, None] = None ): """ A helper function for knn that allows indexing a tensor x with the indices `idx` returned by `knn_points`. For example, if `dists, idx = knn_points(p, x, leng...
5e72639f0b9671a69451fbd9b8f53aeb76b0af62
646,211
def get_date(date): """ Getting date in the format %B %d. :param date: datetime.datetime :return: str """ return date.strftime("%B %d").replace(" 0", " ")
2b7bd897412b599ba1fc70f0eea5ecd01ea04b2a
646,214
def sec_to_time(seconds, days_only=False, ): """Convert seconds in human readable values :param int seconds: Time in seconds :param bool days_only: Output only in days :return str: Human readable string """ seconds = int(seconds) if seconds == 0: seconds = 1 if seconds < 0: ...
3ffbacc819201756416df30cc78e93a30bb3e12f
646,217
def add_missing_columns(df_in, required_columns, fill_val=0.0): """Adds columns to the DataFrame 'df_in' if it does not contain all of the columns in the list 'required_columns'. 'fill_val' is the value that is used to fill the new columns. """ missing_cols = set(required_columns) - set(df_in.colum...
0375934c7fe91e16c174dbb73041cd643de8ebe7
646,220
def load_stop_words(filename): """Load a set of stop words from a file. One word each line.""" # you are using CPython, don't you? # http://stackoverflow.com/a/11027437/1240620 stopwords = {w.strip() for w in open(filename)} return stopwords
e23ec9a1d20396a0694bdd366a283bfbafb66f2b
646,221
def uniquify_str(str_, str_set): """Uniquifies :attr:`str_` if :attr:`str_` is included in :attr:`str_set`. This is done by appending a number to :attr:`str_`. Returns :attr:`str_` directly if it is not included in :attr:`str_set`. Args: str_ (string): A string to uniquify. str_set (se...
0cd412cedf3c676604e184916a9db5d80cd721c8
646,231
def transform_images(X, max_x_value=255): """Flatten and rescale input.""" # Divide by a fixed value to be sure that we are making the same # transformation on training and test data. return X.reshape(X.shape[0], -1) / max_x_value
fd876b96e90732e5f071d571a9fed5bbbf4902f7
646,232
import math def get_nearest_location(x, places): """ Given a location `x`, and a list of locations, `places`, returns the list index corresponding to the minimum distance, and the minimum distance. """ min_dist, min_i = 1e10, 0 for i, place in enumerate(places): name = place['name'...
251e97cc0ad2117f40e68e9690dfb6094e18205e
646,234
import re def remove_namespace(xml): """ Strips the namespace from XML document contained in a string. Returns the stripped string. """ regex = re.compile(' xmlns(:ns2)?="[^"]+"|(ns2:)|(xml:)') return regex.sub("", xml)
1a53503032fab79a2123e69d73481c5f5eceaadb
646,239
from datetime import datetime def datetime_to_iso(date): """ Converts a datetime to the ISO8601 format, like: 2014-05-20T06:11:41.733900. Parameters: date -- a `datetime` instance. """ if not isinstance(date, datetime): date = datetime.combine(date, datetime.min.time()) return dat...
1fc89c2b96d6a4ec3021d87630b6fa611ee0653d
646,240
def mean(*args): """ Calculates the mean of a list of numbers :param args: List of numbers :return: The mean of a list of numbers """ index = 0 sum_index = 0 for i in args: index += 1 sum_index += float(i) return (sum_index / index) if index != 0 else "Division by z...
4857118cf841f82274c5eaf712b5241a261e1033
646,241
def _expand_dim_specification(image_shape, dim_spec): """Expand mex dimension specification. The dimension specification can be 2 or 3 long, it is processed in two steps: 1. If it is of length 2, a -1 is prepended to it 2. Each dimension with -1 is replaced with the whole corresponding image dimens...
35ec014d3624ae078ca8d84eb74613f3f79059f2
646,242
def atttyp(att: str) -> str: """ Helper function to return attribute type as string. :param str: attribute type e.g. 'U002' :return: type of attribute as string e.g. 'U' :rtype: str """ return att[0:1]
275e90c7403109bc2caae57b5ed26c811a5c7702
646,243
def test_single_threaded_tree() -> list: """Return tree data for building a test single threaded tree.""" return [ (4, ""), (1, ""), (7, ""), (3, ""), (5, ""), (8, ""), (2, ""), (6, ""), ]
8668d20d52bde347a1abe8784b07e92d717df24e
646,244
def createDictFromAttr(objList, attr): """\ Group the objects in objList based on their value for a specific attribute. Return: A dict where each key is one of the values attested for the attribute. The value associated with each key is a list of objects whose value for attr was the same as the key. Parameters: ...
6774068b04dc8d6a126afc4054e1b503dec37182
646,245
def normal_range(mean, sd, treshold=1.28): """ Returns a bottom and a top limit on a normal distribution portion based on a treshold. Parameters ---------- treshold : float maximum deviation (in terms of standart deviation). Rule of thumb of a gaussian distribution: 2.58 = keeping 99%, 2.33...
8f130a40d85ab423770ef9a6ee1bf731db72cc9a
646,247
def grouping(df, col_name): """ :param df: Pandas DataFrame. :param col_name: Name of column. :return DataFrame grouped by given column with count aggregation function """ return df.groupby(col_name)['rating'].count()
880a92587ac5462d41db1f3f75c4ec00b4e6c849
646,251
def has_shape(a): """Returns True if the input has the shape attribute, indicating that it is of a numpy array type. Note that this also applies to scalars in jax.jit decorated functions. """ try: a.shape return True except AttributeError: return False
7c3883509a0ec0d8a9b805c93cb31a56db2070c5
646,252
import logging def stylesheets(soup=None): """Find stylesheet URLs in HTML code. :param soup: The parsed HTML, defaults to None :param soup: BeautifulSoup, optional :return: All stylesheet URLs from link tags :rtype: list """ if soup is None: logging.info('⚠️ No HTML content avail...
5651c58352c1d22e25b903271724e28fd0a73ede
646,254
def build_traversal_spec(client_factory, name, type, path, skip, select_set): """Builds the traversal spec object. :param client_factory: Factory to get API input specs :param name: Name for the traversal spec :param type: Type of the managed object reference :param path: P...
79b38d40f48f03b69d7ef41a452bee4a4e086485
646,256
def two_sum(target, ls): """ Check if two numbers within input array sum to target """ complements = set() for num in ls: if num in complements: return True complements.add(target - num) return False
21cab4cd4b214f48a8c84e0e4a8c48265ea68844
646,258
def tuple_remove(tup, *items): """Return a copy of a tuple with some items removed. :param tup: The tuple to be copied. :param items: Any number of items. The first instance of each item will be removed from the tuple. """ tuple_list = list(tup) for item in items: tuple_list.rem...
8d14f15b2c674f465171e951f06735b9ace28ebb
646,259
import torch def stft3d(x: torch.Tensor, *args, **kwargs): """Multichannel functional wrapper for torch.stft Args: x (Tensor): audio waveform of shape (nb_samples, nb_channels, nb_timesteps) Returns: STFT (Tensor): complex stft of shape (nb_samples, nb_channels, nb...
07ff5c547f7419e62f8408adecaba7bdf0a3299f
646,260
from datetime import datetime def time_until(next_mins): """ Given N minutes, this function calculates the timestamp (in UTC) when the Nth minute next occurs. Example: If the time is 16:43:02 and we run time_until(15) the string 17:15:00 will be returned. Args: next_mins (int): The n...
c4009c16d81be925e02998aaabedfbffbb930166
646,262
def num_occurance_atob(a,b,df): """ find num occurance of activity a followed by activity b in dataframe df args: a: activity number (dtype: int) b: activity number (dtype: int) df: dataframe (pandas) where a, b occur (must have ActivityID column) returns: num_occurance (dtype: int...
ba533b42809879aa5589ebb6280d19a5aaed4e27
646,267
def createICDdictionary(filename): """This function takes the sorted_icd_codes file as an arg. and create the following dictionary: ex. {'1': 'BEXT', '3': 'CALI', '2': 'BINT',....,'35': 'XTRN'}""" fh = open(filename) ICDdict = {} for line in fh: line = line.strip().split() ICDdict[li...
34effc8a933ceea55a86fabf7e41bdbae2b8df10
646,269
def files_changed(ctx): """ Return the list of file changed in the current branch compared to `master` """ changed_files = ctx.run('git diff --name-only master...', hide='out').stdout.splitlines() # Remove empty lines return [f for f in changed_files if f]
29af46c492466fb15e3b9a7a46bc6d47c9f8a52f
646,271
def parse_payload_v1(event): """ Get HTTP request method/path/body for v1 payloads. """ body = event.get('body') method = event.get('httpMethod') try: package, *_ = event['pathParameters']['package'].split('/') except KeyError: package = None return (method, package, body...
2a32dd96bcaf916efdb53ba3dd8430ba4c5eef5d
646,273
import json def getConfigNames(xen, session, logger, ref): """ Return all config names associated with the given disk by reading the disk's other config in Xen. :param logger: A logger used for logging possible errors. :type logger: seealso:: :class:`logging:Logger` :param ref: Xen reference of ...
d108c718b244163a23ee974ca456714fdca88ee9
646,279
def initial_sigmoid_params(x, y): """Reasonable initial guesses for the parameters.""" b = 7.0 / max(x) r = max(y) m = (max(x) + min(x)) / 2.0 return [b, r, m]
499925d5175f8c79d591e9ca0e4d9b3e3b78c6d1
646,285
def s_hint(ans): """ :param ans: str, the answer for user to guess :return: str, dashed version of "ans" to show number of character within this word as a hint for user """ hint = '' for i in range(len(ans)): hint += '-' return hint
2a18966db7ad979775225c13b273783ea03ddebf
646,286
from datetime import datetime import calendar def get_first_and_last_dates_of_month(month: int, year: int): """Return first and last dates for a given month and year.""" start_date = datetime.now().replace(day=1, year=year, month=month) end_date = start_date.replace(day=calendar.monthrange(year=year, mont...
06b58e5257dd0bde1002f7d2ccbb5f1937de87e9
646,287
def total_seconds(delta): """Return the total seconds of datetime.timedelta object. Compute total seconds of datetime.timedelta, datetime.timedelta doesn't have method total_seconds in Python2.6, calculate it manually. """ try: return delta.total_seconds() except AttributeError: ...
e138b08fdadaf3675a0ff42a50875e09b823c883
646,289
def clean_value(value): """ Clean the value; if N/A or empty :param value: original value :return: cleaned value """ if value: value = value.strip() if value.lower() == 'n/a': value = None if value == '': value = None return value
eaaf71b8e4cf931e50c319bebee59d41b33fcfb9
646,292
def update_keeper(keeper, next_point): """ Update values of the keeper dict. """ keeper["prev_point"] = keeper["curr_point"] keeper["curr_point"] = next_point keeper["coverage_path"].append(next_point) # If everything works this conditional # should evaluate to True always if not ke...
9e9aa43488080d4c8af8b90989712f609238ba4a
646,299
def id2trc(s_id, grid_dim): """ Convert state id to row, col, cell type """ t = s_id // (grid_dim[0] * grid_dim[1]) r = (s_id - t * grid_dim[0] * grid_dim[1]) // grid_dim[1] c = (s_id - t * grid_dim[0] * grid_dim[1] - r * grid_dim[1]) // 1 return t, r, c
b261d3b37d70b5578814b9f099d9763752838e2b
646,304
from typing import Iterable from typing import List def indent(level: int, lines: Iterable[str]) -> List[str]: """ Indent the lines by the specified level. """ return [' ' * level + line for line in lines]
9fea8a60c3dfa9f91b49c39167cd3dadf1b21604
646,305
def gaussian_kl(q, p): """ computes the KL divergence per batch between two Gaussian distributions parameterized by q and p Args: q (list) Gaussian distribution parametrized by q[0] (torch tensor): mean of q [batch_size, *latent_dims] q[1] (torch tensor): varianc...
c5ecc089d3c60de0f037be446596a2691b3b742a
646,306
import torch def make_features(x): """Builds features i.e. a matrix with colums [x,x^2,x^3]. """ x=x.unsqueeze(1) return torch.cat([x**i for i in range(1,4)],1)
c5b282901efb15af9f98c865f0422378dd85b1f0
646,309
def slice2gridspec(key): """Convert a 2-tuple of slices to start,stop,steps for x and y. key -- (slice(ystart,ystop,ystep), slice(xtart, xstop, xstep)) For now, the only accepted step values are imaginary integers (interpreted in the same way numpy.mgrid, etc. do). """ if ((len(key) != 2) or ...
3e8eaacbf2ef21e5c3538cbe5e7aa2349b0e52b5
646,313
def make_shell_logfiles_url(host, shell_port, _, instance_id=None): """ Make the url for log-files in heron-shell from the info stored in stmgr. If no instance_id is provided, the link will be to the dir for the whole container. If shell port is not present, it returns None. """ if not shell_port: r...
33b762e6361481736dd7a0b30e1cca385bc8bc7a
646,314
def leaves(G): """ Return the nodes of G with out-degree zero in a list. G-- nx.Digraph return-- List of leaves nodes. Example: >>> G=random_dag(10,20) >>> leaves_list=leaves(G) >>> len(leaves_list)>0 True >>> any([G.out_degree(x)>0 for x in leaves_list]) False """ ...
2e9dd6ad037437fdeecb6c814c9b1334c20f141c
646,317
def removeMacColons(macAddress): """ Removes colon character from Mac Address """ return macAddress.replace(':', '')
babe078c4a2b91e7ee56be15f62e58baa4189b8d
646,320
import torch def load_model(load_path, net, device): """ Loads a stored network with pytorch. """ checkpoint = torch.load(load_path, map_location=device) net.load_state_dict(checkpoint) net.to(device) net.eval() return net
0ef5fcf3d532c0096f1e16023836559a583c87c8
646,321
def prefix_strip(mystring, prefixes=["rust_"]): """ strip passed in prefixes from the beginning of passed in string and return it """ if not isinstance(prefixes, list): prefixes = [prefixes] for prefix in prefixes: if mystring.startswith(prefix): return mystring[len(prefix):]...
d19c4903ec28e035bbbc769c6dfcad96faaad13e
646,323
def method_available(klass, method): """Checks if the provided class supports and can call the provided method.""" return callable(getattr(klass, method, None))
f061a7c7fc322881895644284f8a637424f86e66
646,324
def punnettParse(s : str) -> list: """Take a str and turn it into a list of strings punnett can accept""" if len(s) % 2: raise ValueError('Even number of alleles required') return ["".join(sorted(s[i:i+2])) for i in range(0,len(s),2)]
e95e27191691e5e603f03830b491559ec19c5c6b
646,325
def str_month(month): """Transforms datetime month object into a "%m/%y" string. Args: month (datetime/datetime.date): Month. Returns: A "%m/%y" string representation. """ return month.strftime("%m/%y")
38e50628157934747e7ee4d1f0a4093292df40d0
646,326
def _ReadCsv(path): """Returns the contents of the .csv as a list of (int, int).""" ret = [] with open(path) as f: for line in f: parts = line.rstrip().split(',') if len(parts) == 2 and parts[0] != 'revision': ret.append((int(parts[0]), int(float(parts[1])))) return ret
1180ac4391293d0f538ffcc58f80d903f8cb29a0
646,327
import requests def getJson(url): """ HTTP GET request :param url: - api url :return: - json object, if response status is OK """ response = requests.get(url) if response.status_code == 200: return response.text raise Exception(response.text)
4016f82de8591ffb2c62f99936b7f3d52fba9cf4
646,328
def mt_loss(theta, R, beta): """Compute objective function for multi task group lasso.""" n_samples = len(R) obj = 0. for n in range(n_samples): obj += R[n] ** 2 obj *= 0.5 return obj
edb1693d71f0cc880cd91ae76a7780ebbf2794fc
646,330
import re def RemoveMatchingTests(test_output, pattern): """Removes output of specified tests from a Google Test program's output. This function strips not only the beginning and the end of a test but also all output in between. Args: test_output: A string containing the test output. pattern: ...
7cc3bcf11a8f7fce8f95d3cc615f7eb62e902a33
646,334
def reconcile_countries_by_code(codeinfo, plot_countries, gdp_countries): """ Inputs: codeinfo - A country code information dictionary plot_countries - Dictionary whose keys are plot library country codes and values are the corresponding country name gdp_countries ...
1734538a83381b075709ef2324c24394ea2cf6dd
646,336
def is_cdap_entity_role(role): """ CDAP create roles for entities by default. These roles are in the format of '.namespace', '.program' etc. :param role: The role to judge :return: bool: if role is a cdap entity role """ return role['name'].startswith(('.artifact', '.application', '.program', '.dataset', 's...
8ffe9c8525d711e38a061136045f948b31691dd3
646,337
def islice(vals, inds): """Returns a list of values from `vals` at the indices in `inds`.""" sliced = [] for (i, v) in enumerate(vals): if i in inds: sliced.append(v) return sliced
247c94fd42c4201d740aee2d4851a77c31626e04
646,340
def merge_ranges(ranges): """Merge short, fragmental ranges into long, continuous ones. Parameters ---------- ranges : list of int Ranges to merge. Returns ------- list of int Merged ranges. Notes ----- Ranges that have overlaps will be merged into one. For exa...
e13817f71163c75425daac6acbb024f989467ff7
646,342
def crop_border(img_list, crop_border): """Crop borders of images Args: img_list (list [Numpy]): HWC crop_border (int): crop border for each end of height and weight Returns: (list [Numpy]): cropped image list """ if crop_border == 0: return img_list else: ...
4c076b1e16969f86cb61485a6def6c3ba6185e35
646,344
import torch def argmax(x): """ Arg max of a torch tensor (2 dimensional, dim=1) :param x: torch tensor :return: index the of the max """ return torch.max(x, dim=1)[1]
511b073d7ad2bfcd2b16f18fe8bf8a4cc14927cb
646,347
def nos_unknown_host_cb(host, fingerprint): """An unknown host callback. Returns `True` if it finds the key acceptable, and `False` if not. This default callback for NOS always returns 'True' (i.e. trusts all hosts for now). """ return True
576c0a195e15bc33079050c4c527c3b196d5325f
646,349
async def async_handle_google_actions(cloud, payload): """Handle an incoming IoT message for Google Actions.""" return await cloud.client.async_google_message(payload)
ec43b1b33da6596bb5cb42d6b3548e45001a42d3
646,353
def check_status(status): """ A little helper function that checks an API error code and returns a nice message. Returns None if no errors found """ if status == 'REQUEST_DENIED': return 'The geocode API is off in the Google Developers Console.' elif status == 'ZERO_RESULTS': ret...
5adfcd923e5384fa08f6ba0b89aa17492a891923
646,355
def surface_area(l, w, h): """Return the total surface area of a box""" return (2 * l * w) + (2 * w * h) + (2 * h * l)
be40294c8b1f80108e951936e8b8fe58e3e555bd
646,356
def get(isdsAppliance, check_mode=False, force=False): """ Get information on existing snapshots """ return isdsAppliance.invoke_get("Retrieving snapshots", "/snapshots")
026008004fd43eebf234c08f7d3a1cb5ce7fc481
646,357
def solidity_library_symbol(library_name): """ Return the symbol used in the bytecode to represent the `library_name`. """ # the symbol is always 40 characters in length with the minimum of two # leading and trailing underscores length = min(len(library_name), 36) library_piece = library_name[:leng...
b20d961e0885b3784f670136f99b2c6981f17d65
646,360
def hostname_valid(hostname): """ Test if specified hostname should be considered valid Args: hostname (str): hostname to test Returns: bool: True if valid, otherwise False """ if (not hostname or hostname.startswith('localhost') or hostname.e...
19ac5d58961569034535b9dda2b94e875e543b91
646,361
import itertools def global_integration_cli_args(integration_config_paths): """ The first arguments to pass to a cli command for integration test configuration. """ # List of a config files in order. return list(itertools.chain(*(('--config_file', f) for f in integration_config_paths)))
ee0c552453ed18197890a2666e0a6ccdbb6c53a1
646,362
def euclidean_dist_vec(y1, x1, y2, x2): """ Calculate Euclidean distances between pairs of points. Vectorized function to calculate the Euclidean distance between two points' coordinates or between arrays of points' coordinates. For accurate results, use projected coordinates rather than decimal de...
7c0787c4a90f4ac07bcf9faeee2dfd7fdb88085e
646,364
def streak_next(values, i): """Given a list of numbers, skip forward over consecutive streaks Used by DfView.find() If i references a value within a consecutive streak, the value returned will be the index of the end of the streak. If i references a value at the end of a streak, the value retu...
ca81546314aab1ac963fa227b97fb692145a40c6
646,365
from datetime import datetime def epoch_to_date(s): """ UNIX epoch timestamp in string or float to datetime object """ return datetime.utcfromtimestamp(float(s))
1ce9d4e2ae0992dda78b561b67df994c212b1862
646,369