content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from six.moves import urllib import os import gzip import pickle def load_mnist_data(dataset): """ Load the dataset Code adapted from http://deeplearning.net/tutorial/code/logistic_sgd.py :type dataset: string :param dataset: the path to the dataset (here MNIST) """ # Download the MNIST datas...
b595c0e1cc3443622a34f1ce07a6cb91005a549b
639,233
def schema_contest() -> str: """Schema for contest document""" return """ _id 5f70c6f3430508338f95ddab winner slateType 1 gameCount 13 siteSlateId 39913 start 2020-09-27T17:00:00.000Z sport 1 prizePool 4275000 maxEntriesPerUser 150 ...
9b29a8472895d389cbcb590c711596fd029f7328
639,234
def calc_min_max_2 (liste): """ recherche du min et du max pour les points afin de générer le point en haut a gauche,a droite en bas a gauche et droite """ dict= {} for resto in liste: if "latmax" not in dict: dict["lngmax"]=resto.copy() dict["lngmin"]=resto.copy() dict["latmax"]=resto.copy() dict["l...
044efd6c3a9ff6dd4dc2c27f3ddff56f11fd71ea
639,235
def format_kit_descriptor(name, version, iteration): """ Returns a properly formatted kit 'descriptor' string in the format <name>-<version>-<iteration> """ return '{0}-{1}-{2}'.format(name, version, iteration)
87fa82769648edf0c587b15bace329b63bcc5f8d
639,236
def richclub(graph, fraction=0.1, highest=True, scores=None, indices_only=False): # from http://igraph.wikidot.com/python-recipes#toc6 """Extracts the "rich club" of the given graph, i.e. the subgraph spanned between vertices having the top X% of some score. Scores are given by the vertex degrees by de...
ebbab04068709858fc3b88d2517e648a6a979c57
639,237
def chain_length(n, chains): """ Return the chain length of a number n. If the chain length of n isn't stored yet, then calculate it according to the collatz sequence rules recursively and store it for future reference. Also store all the chain lengths for numbers that are found duri...
efc213c8b5916be775e969f07309bce7a667914a
639,238
def calc_ertelPV(n2, bx, rel_vorticity, g=9.8,f=-1e-4): """ As in Thomas et al., 2013; Thompson et al., 2016 The assumption is made that flow is in geostrophic balance PV can be used as a diagnostic to indicate the suscepptibility of a flow to instability e.g., Hoskins, 1974; Thomas et al., 2008 Wh...
60a4b43d9290f1dbab15621a9384ff567975e16c
639,239
def extractFolders(folders): """ convert a string of folders to a list of tuples (db , schema, node) :param folders: a string containing folders db-schema-node seperated by , :return: a list of tuples (db , schema, node) """ output = [] folderList = folders.split('-') for folder in fol...
b5ba5e2ce3fcbc33e51fea06d2019c36b65aaece
639,240
def add_undef_techs(heat_pumps, all_specified_tech_enduse, enduse): """Add technology to dict Parameters ---------- heat_pumps : list List with heat pumps all_specified_tech_enduse_by : dict Technologey per enduse enduse : str Enduse Return ------- all_speci...
1dadeef0606ccffd65838347539cad5c3cf3b5aa
639,241
import argparse def parse_args(): """ Creates the argument parser for the command line :return: the args that were parsed from the command line """ # This file contains the commandline tools for the current tool parser = argparse.ArgumentParser(prog='cc_dcr.py', usage='cc_dcr.py [options]') ...
8c57e22ec7e6b132489fd4e705236f28c26908a4
639,242
import importlib def get_proxy_methods(): """Return a set of public names on all proxies""" names = ["otcextensions.sdk.anti_ddos.v1._proxy", "otcextensions.sdk.auto_scaling.v1._proxy", "otcextensions.sdk.cce.v1._proxy", "otcextensions.sdk.cts.v1._proxy", "o...
9a48bfea1fc2c880ccab6bffbb63f5206ebc6535
639,243
def menu_principal(request): """ Funcão que contém as configurações do menu principal do controle de acessos. Retorna um dicionário com as configurações """ menu_buttons = [ {'link': '/administracao/acesso/usuarios', 'text': 'Usuários'}, {'link': '/administracao/acesso/grupos', 'tex...
597e622155d3a2c2532d7326c1668720f85c9eea
639,244
def pdf_norm_from_kernel( kernel_val: float, **kwargs): """ Just use the pdf_max value passed, usually originating from the distance function. """ return kernel_val
0f70c8656ae80461bed86f6c3f52dff5b3fe3c6b
639,245
def batch_binary_confusion_matrix(pred, target): """ Compute the binary confusion matrix for batch of prediction, target. ---------- INPUT |---- pred (torch.tensor) the binary prediction with shape (B x *). |---- target (torch.tensor) the binary ground truth with shape (B x *). OUTPU...
20b24f0c91a37cf8e9447df21885d235cd8eac92
639,246
def factorial(_n_: int) -> int: """ Factorial function """ assert _n_ >= 0 return 1 if _n_ <= 1 else _n_ * factorial(_n_ - 1)
d2b6beaba861bbe6d1480888b597fd1835e6898e
639,247
def _to_value_seq(values): """ :param values: Either a single numeric value or a sequence of numeric values :return: A sequence, possibly of length one, of all the values in ``values`` """ try: val = float(values) return [val,] except (ValueError, TypeError): return valu...
cc571692d3c11429cc6b2a3591556a24af5d3396
639,248
import yaml def load_yaml_config_file(path): """ Returns the parsed structure from a yaml config file. :param path: Path where the yaml file is located. :return: The yaml configuration represented by the yaml file. """ result = None with open(path, 'r') as steam: result = yaml.safe_lo...
bad2844af34d57c1660d71b4d9ec43c145770390
639,249
def usage(cmd='', err=''): """ Prints the Usage() statement for the program """ m = '%s\n' %err m += ' Default usage is to scan latest Task Branch (TB) on SalesForce.\n' m += ' ' m += ' walkSF -c walk -s4.1 \n (walk sForce and enforce approval workflow)' m += ' or\n' m +=...
595123fbc1c920b4f0d7099adddbe549f71abd95
639,250
from typing import Tuple def split_tab_pair(x: str) -> Tuple[str, str]: """Split a pair of elements by a tab.""" a, b = x.strip().split('\t') return a, b
dc16ee922c857e12eb7af646790811bff990b025
639,251
def trim_data(data, xy, p = 0.1): """ RIGHT FROM iREP remove data from ends of sorted list """ if xy is False: length = len(data) num = int(length * (p/2)) return data[num:length - num] X, Y = data length = len(X) num = int(length * (p/2)) return X[num:length...
3636a056f82fa261bd882fa613b136af5d44c472
639,253
def center_data(x, dim=-1): """ Center x along the dimension dim. :param x: torch.Tensor :param dim: int, dim for centering :return: torch.Tensor, centered x """ return x - x.mean(dim=dim, keepdim=True)
66293bb4db508d75e9709c6e50dad3b6ad7fa01b
639,254
def _validate_hedge(hedge): """Validate hedge.""" if hedge is None: return None if not isinstance(hedge, dict): raise TypeError("hedge must be a dictionary, not %r" % (hedge,)) return hedge
0305b6b78c8a7277c588060638b8ff4d781a3fb2
639,255
async def get_text(page, b, norm=True): """Get the inner text of an element""" text = await page.evaluate('(element) => element.textContent', b) if norm: text = text.lower().strip() return text
30df718406b91a44e5e5d666259564e81d7e0909
639,256
import requests import json def post_gist(report_data, old_sha, new_sha): """Post the report to a GitHub Gist and return the URL of the gist.""" payload = { "description": ("Changes in OpenStack-Ansible between " "{0} and {1}".format(old_sha, new_sha)), "public": True, ...
2902c4312c34efcb839ecda6d3b03ec14c619e5e
639,257
def _add_graph_name(nodes, graph_stream): """Add graph_name in node.name.""" if len(graph_stream.graph_names) > 1: return nodes graph_name = graph_stream.graph_names[0] output_nodes = [] for node in nodes: node_basic_info = graph_stream.construct_node_basic_info( full_nam...
05bd7326ccc805a7de35f405d2d7bb4a4233afe4
639,258
import random def shuffle_list(arg): """ Return a shuffled copy of a list """ tmp = arg[:] random.shuffle(tmp) return tmp
d80de9f925332b857eacf42bc5edb4056555184f
639,259
import textwrap def cleantext(text: str) -> str: """ Clean a text string. :param text: The input text :type text: str :return: The cleaned text :rtype: str """ return " ".join(textwrap.dedent(text).strip().split("\n"))
7eb6a4f32c9268fae0f016fc50faa5c21901572e
639,261
def sort_data(lst_to_sort): """ Sorts the list of crossing entities by fields: date, value, border & measure in descending order """ print("---> Sorting the data...") sorted_list = list(lst_to_sort) # Need to call sort() in reverse order of "sortby" fields. # First, do a sort by "borde...
8da2f7018a0913ea79608825cf3ffc982af8698b
639,262
def slurp(filename): """ Return the contents of filename as a string. >>> 'public domain' in slurp('LICENSE.txt') True """ with open(filename) as file: return file.read()
5c62513119984dac80cded916085a58994dc4d8d
639,263
def format_date(str_date): """ Prepare string to be used by datetime.strptime using format "%Y-%m-%dT%H:%M:%S%z" :param str_date e.g. 2014-04-17T19:14:29+08:00: :return e.g. 2014-04-17T19:14:29+0800: """ str_length = len(str_date) return str_date[:-6] + str_date[str_length-6:str_length-3] + str_...
5bb027d87b6fdcde0e24373e01ad37545c59bba2
639,264
from typing import Dict def recover_info_from_exception(err: Exception) -> Dict: """ Retrives the information added to an exception by :func:`add_info_to_exception`. """ if len(err.args) < 1: return {} info = err.args[-1] if not isinstance(info, dict): return {} return ...
e172111ae364b9999c5c62f9bb549737584919a5
639,265
def _get_single_channel_feature_names(chan_dict): """Helper function for getting feature extractors.""" feature_list = [] for feature in chan_dict: if isinstance(chan_dict[feature], dict) and chan_dict[feature]['run']: feature_list.append(feature) return feature_list
3ad6129732cdd8a45414bb7ace1a3eb0d43144c3
639,266
def euler_problem_78(modulos=1000000): """ Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7. OOOOO OOOO O OOO OO OOO O O OO OO O OO O ...
2109977b3b5734ed72640b2732f6bd1e60028e09
639,267
def string_index(neg_idx, string): """Solution to exercise R-1.8. Python allows negative integers to be used as indices into a sequence, such as a string. If string s has length n, and expression s[k] is used for index −n ≤ k < 0, what is the equivalent index j ≥ 0 such that s[j] references the sam...
30e69a395e2b49e9edf15e68e7a4b663299a4956
639,268
def padding_mask(seq_k, seq_q): """For masking out the padding part of the keys sequence. Args: seq_k: Keys tensor, with shape [B, L_k] seq_q: Query tensor, with shape [B, L_q] Returns: A masking tensor, with shape [B, L_1, L_k] """ len_q = seq_q.size(1) # `PAD` is 0 pad_mask = seq_k.eq(0) ...
22f84e5b2e7b0ef31c0aa36771f50de110a1fa9d
639,269
def restrict_dict(d, keys): """ Return a dictionary that contains those keys that appear in both d and keys, with values from d. """ return dict([(k, v) for (k, v) in d.iteritems() if k in keys])
d647bf98ab2f314a7e417d5b1e6a9cef1a9f9f8a
639,270
def attempt_actions_for_machine(machine_action_definition, machine, context, actions): """Check the given actions for a machine and determine which action was successfully taken. For the given list of actions, the corresponding function from the given machine_action_definition will be called with the machi...
af3abe7a1a7c25f5ac54ab8659d9a111551c6ef5
639,272
def getSimData(opsimDb, sqlconstraint, dbcols, stackers=None, groupBy='default', tableName=None): """Query an opsim database for the needed data columns and run any required stackers. Parameters ---------- opsimDb : `rubin_sim.maf.db.OpsimDatabase` sqlconstraint : `str` SQL constraint to ap...
87798597fdc36902ea4b638be534efde60b37f77
639,273
def create_bottom_toolbar(): """ Generates the bottom toolbar html content. @param workflow_stat the WorkflowInfo object reference """ toolbar_content =""" <div id ='gantt_chart_footer_div' style='width: 1500px; margin : 0 auto;' > <img style='float: right' src = 'images/jobstates_all.png'/> <input type='checkbox...
300b54e32f21bb2b9f39fe538f068d5ccb47f0fc
639,275
import re def grab_internal_classes_list(x) : """ @param x : a VMAnalysis instance @rtype : a list of the canonical name (ex "android.widget.GridView") of the internal classes used """ tainted_list = x.get_tainted_packages().get_internal_packages() list = [] for item in tainted_list: name = item.get_met...
3656b82e411d1d3544f62270ec18236843e9fa4f
639,276
def load_dict(args): """ save dictionary as tsv file """ d={} with open(args.load_dict, "rt") as f: for line in f: form, upos, xpos, feats, lemma = line.strip().split("\t") d[(form, upos, xpos, feats)]=lemma return d
8d602cc2b7e9617c4075db4d0b5fbf0bf659914e
639,277
import torch def _same_padding(x, kernel_size=3, dilation=1): """The padding method used in slim.conv2d(..., padding='SAME'). Note: only for stride = 2 or stride = 3. """ k = kernel_size if isinstance(kernel_size, int) else kernel_size[0] d = dilation if isinstance(dilation, int) else dilatio...
793a25904333a10cadfdc5671901a25804361d3c
639,278
def ribbon(dimensions): """Return total ribbon needed for box of size dimensions The total ribbon is equal to twice the lengths of the shortest two dimensions plus the product of all three dimensions. """ s1, s2, s3 = sorted(dimensions) return (2 * s1) + (2 * s2) + (s1 * s2 * s3)
71b5fd29e4e080090a280b3852184271f552220c
639,279
def sublist(L,I): """ like L[I] """ # return [s for i,s in enumerate(L) if i in I] z = [] for i in range(len(I)): s = L[I[i]], s = list(s) z = z + s return z
7319eeed931cfc80968f0c6174b9bbde4bb582dc
639,280
def DeleteVersion(client, messages, version): """Deletes a version by its name.""" delete_ver_req = messages.ArtifactregistryProjectsLocationsRepositoriesPackagesVersionsDeleteRequest( name=version) return client.projects_locations_repositories_packages_versions.Delete( delete_ver_req)
f08dd41708021b06b29f92db745242d026b56188
639,281
def is_gem_update_avaliable(gem_name: str, last_updated: str) -> bool: """ Call is_o3de_gem_update_available :param gem_name: Name of gem to check for update on :param last_updated: Timestamp when gem was last updated, must be parsable using datetime.fromisoformat :return bool True...
de2df185289850f6df3912c3057422a2ac198c8e
639,282
def get_gradient_index(val, min_val, max_val, steps): """ Returns the index in gradient given p-value, minimum value, maximum value and number of steps in gradient. >>> get_gradient_index(0.002, 0.001, 0.0029, 10) 5 >>> get_gradient_index(0.0011, 0.001, 0.0029, 10) 0 >>> get_gradien...
998f4190abe2e43b6f01c3595425c5fd8349aff8
639,283
def getPredictedLabels(model, features): """Run inference on trained model to get predicted class labels.""" return model.predict(features)
d01b7457e6f3aa3af94a0621995363fa1a9b96e9
639,284
from typing import OrderedDict def get_comps(predicted_comp_cat): """Turn list of source_names, component_names into a list""" combined_names = list(OrderedDict.fromkeys(predicted_comp_cat['Source_Name'].values)) comp_dict = {s:[] for s in combined_names} for s, comp in zip(predicted_comp_cat.Source_N...
74c7811edc1f40d477b71044b4781096a7494f59
639,286
def evaluate_guess(guess: str, mystery: str): """Get the partition label for the mystery word given the guess. There are 3^n different partitions, where n is the number of characters in guess or mystery. Args: guess: word being guessed mystery: candidate for mystery word Returns: ...
b6a9ef35b6a776f9954bb2971c37677c68fd49e2
639,287
import subprocess def pathGet(): """Gets the path of macchanger, ip, and iwlink (required to gather interface info and change settings)""" macchanger = subprocess.check_output("which macchanger", shell=True)[:-1].decode("utf-8") ip = subprocess.check_output("which ip", shell=True)[:-1].decode("utf-8") ...
797bb6b033e86ec4465af579fce22605a0b8e25c
639,288
def c_is_fun(text): """ Return desired string for /c/<text> route, replace _ with space """ return "C {}".format(text.replace("_", " "))
fd3c49eff9a4c111f4424cc779531b89214b8234
639,289
def error_on_blank(_value, _error): """Raises an error if blank""" if _value not in [None, '']: return _value else: raise Exception(_error)
69a96364de6062c3f3fcfac8285bb8421cf822a1
639,291
import os def GetDebLibDir(): """ Returns the lib dir according to the debian system. """ # We're on Debian or Ubuntu, which use multiarch directories. # Call dpkg-architecture to get the multiarch libdir. handle = os.popen("dpkg-architecture -qDEB_HOST_MULTIARCH") multiarch = handle.read().strip(...
d54b0c35cb5f2da1f945286e8365ccde92078a18
639,292
import six def is_listlike(x): """ >>> is_listlike("foo") False >>> is_listlike(5) False >>> is_listlike(b"foo") False >>> is_listlike([b"foo"]) True >>> is_listlike((b"foo",)) True >>> is_listlike({}) True >>> is_listlike(set()) True >>> is_listlike((x ...
c6473bdd56ec71619a7c5455bdbeb7c35e7dc213
639,293
def _integer_surround(number): """Return the 2 closest integers to number, smaller integer first.""" if number > 0: return int(number), int(number) + 1 else: return int(number) - 1, int(number)
a309930e3d7992008c08085a1ea121480de1396e
639,294
def extraire_contenu_du_document(root): """Utilitaire permettant d'extraire le contenu du document dans une string. Args: root (Element): la racine du document XML Returns: [str]: le contenu du document """ contenu = '' for element in root.findall('.//BLOC_TEXTUEL/CONTENU'): ...
765b42a5f3504b2cccf114461d777da0193bbd8a
639,295
def get_initial_domains_by_genome_assembly(genome_assembly): """Get a list of defaults HiGlass data ranges for a file. Args: genome_assembly(string): Description of the genome assembly. Returns: A dict with these keys: initialXDomain(list): Contains 2 numbers. The HiGlass display wil...
6140d80f417e166942ac376d4383acda5d746937
639,297
def _is_ingredient_heading_1(line): """Returns True for the first heading line of ingredients section.""" return line.strip().lower() == 'amount measure ingredient -- preparation method'
81c9a552087b20c6138e303ff833a96d1d01c3fc
639,298
def date_marker(date, today): """Return a one-character date marker.""" if date == today: return '*' if date == today.tomorrow(): return '+' if date == today.tomorrow(-1): return '-' return ' '
dd1e5bb4392522ebf82ab28bf76ebe3140e11085
639,299
def find_cl_max_length(codelist): """ find and return the length of the longest term in the codelist :param codelist: codelist of terms :return: integer length of the longest codelist item """ max_length = 0 for term in codelist.split(", "): if len(term) > max_length: max...
820fbf7a1b3ac80679d3f1e4937e960c1bdbd77d
639,300
import os def get_database_path() -> str: """ Store data in ~/.home_service/home_service.db """ data_dir = os.path.join(os.environ["HOME"], ".home_service") try: os.makedirs(data_dir) except OSError: # pragma: no cover pass return os.path.join(data_dir, "home_service.db")
2e0f11d727ac0ccc44fa810292c4f6480e8ea1af
639,301
from datetime import datetime def scrapeEnd(soup): """ Scrapes ICO end date from ICODrops listing """ year = str(datetime.now().year) token_sale = list(filter(lambda x: "Sale:" in x.text, soup.findAll("h4"))) if token_sale: date_string = token_sale[0] \ .text \ .translate({ ord(x): "" for x i...
52f1c810a27aa49fd0e5ce5284ce3906554f24a6
639,302
import re def ljust(s,n,fillchar=' '): """ if string has unicode chars, the built-in l/rjust cannot auto-adjust and align, that's why this two functions come""" no_ascii_list = re.findall(r'[^\x00-\x7F]+', s) ln = len(''.join(no_ascii_list)) return s.ljust(n-ln, fillchar)
25e2c85f1bd293a965b3fd413de9bdeb41c92ac3
639,303
import inspect def derive_top_level_package_name(package_level=0, stack_level=1): """Return top level package name. Args: package_level (int): How many package levels down the caller is. 0 indicates this function is being called from the top level package, 1 indicates that it'...
e9ff1119cd02f01c355aef1e68fae55db7fbbba0
639,304
import torch def size_to_str(torch_size): """Convert a pytorch Size object to a string""" assert isinstance(torch_size, torch.Size) or isinstance(torch_size, tuple) or isinstance(torch_size, list) return '('+(', ').join(['%d' % v for v in torch_size])+')'
ffad3362dd32953fb78521e10262591d486049fb
639,305
def make_step_input(magnitude, start_time, t_vector): """ Generates step signal starting from start_time """ return [magnitude * (start_time < entry) for entry in t_vector]
4cd5624edb27582a7526c55f86123cda4a1b2428
639,306
def sort(list): ### Beginning of Selection Sort Algorithm """ NEEDS TO BE UPDATED """ return list
25ff7222528b92f9a09500eb1a2996fd81bfdc84
639,307
import requests def check_redirect(link): """ Function that checks if a url is redirected to other link. Also works as a comparator for sorting. returns 1 if a url is redirected to other. returns 0 if a url is not redirected. """ response = requests.head(link) redirect_code_lis...
e2392a9edf3cfc4ffbd707324a77b49044874f31
639,308
import mpmath def pdf(x): """ Probability density function (PDF) of the raised cosine distribution. The PDF of the raised cosine distribution is f(x) = (1 + cos(x))/(2*pi) on the interval (-pi, pi) and zero elsewhere. """ with mpmath.extradps(5): x = mpmath.mpf(x) if...
765d86f3baab3adf4370fe386aaf776e80694a5d
639,310
def _drop_zeros(df): """ Drop zeros from a DataFrame, returning an iterator over the columns in the DataFrame. Yields tuples of (column name, non-zero column values, non-zero indexes). Parameters ---------- df : pandas.DataFrame """ def for_each_col(col): nz = col.values.n...
06b82d521683ad1f521db0a6391fbe26e3bd0c64
639,311
from typing import Optional import dataclasses def field(description: str, *args, metadata: Optional[dict] = None, **kwargs): """ Creates an instance of :py:func:`dataclasses.field`. The first argument, ``description`` is the description of the field, and will be set as the ``"description"`` key in th...
151a6c5a171facbfc2ed7da8da179cd30d7db248
639,312
def rgb(red, green, blue): """ Return the string HTML representation of the color in 'rgb(red, blue, green)' format. :param red: 0 <= int <= 255 :param green: 0 <= int <= 255 :param blue: 0 <= int <= 255 :return: str """ assert isinstance(red, int) assert 0 <= red < 256 ...
dc10e8b3cd63a79380130397d5e4b064b7acb157
639,313
def get_type(uid): """ return variable type """ return uid.type
93dacc0390496a071681bb90c2d0c4ab2a1d0c9a
639,314
def evaluate_remote_response(): """ Returns a Javascript function that evals a request response Returns 'eval(request.responseText)' which is the JavaScript function that ``form_remote_tag`` can call in *complete* to evaluate a multiple update return document using ``update_element_function`` c...
b54f897b6ee5cb8a143d4b35d53a612be9777bd0
639,315
def getTransportLines(): """ This function provides the GAMS definition of the classic Dantzig transport problem https://www.gams.com/docs/example.htm """ transportLines=[ 'SETS', 'I canning plants / SEATTLE, SAN-DIEGO /', 'J markets / NEW-YORK, CHICAGO, TOPEK...
e57ded0b2db89422b424a7e95a6bd8be56eef106
639,316
def has_next_page(content: str) -> bool: """Check whether a Flaticon search page has another page Args: content (str): Contents of the current Flaticon search page Returns: bool: Whether a next page exists """ return "<span>Next page</span>" in content
8dc75963346e876da8c92eec9a476b95f45a866e
639,317
def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines)
a83e4ad25fedf3292b2678785cc9bb417ebe1452
639,319
def cleanup_trailing_spaces(message): """We need to cleanup trailing spaces as Sublime text removes them.""" actual_msg_array = message.split('\n') actual_msg_array = [s.rstrip() for s in actual_msg_array] return '\n'.join(actual_msg_array)
8681ea2deb6ca669db23a4af2510c12327e96bfc
639,320
def get_cityscapes_colors(): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ num_cls = 20 colors = [0] * (num_cls * 3) colors[0:3] = (128, 64, 128) # 0: 'road' colors[3:6] = (244, 35,232) ...
9ff7f3db8604fde8c79c8e232b2874e33cc1cdaa
639,321
import math def geo_bounds(xmin, ymin, xmax, ymax): """ Project web mercator bounds to geographic. Parameters ---------- xmin: float ymin: float xmax: float ymax: float Returns ------- [xmin, ymin, xmax, ymax] in geographic coordinates """ merc_max = 20037508.342...
ed44c70d01e310294823884d88fcfc37d240a3dd
639,322
def get_variation(type_variation, list_detections, str_detections): """Gets a specific variation list of detections""" return list_detections[str_detections.index(type_variation)]
fb2d79ff79bfd7246617f16d1e10ef38d4c4218b
639,323
def user_identity_lookup(user): """ Register a callback function that takes whatever object is passed in as the identity when creating JWTs and converts it to a JSON serializable format. """ return str(user.id)
2e6a2f2177cf53c4eab5d9dfc3b169381a29430e
639,324
def reverseDict(d): """ Reverses a dictionary. If a key isn't unique (replicated value in the original dict), only the "last" (iteration order dependent) is kept as a key in the result @type d: dictionary @param d: the dictionary to reverse """ return dict( (v,k) for k,v in d.iteri...
f9eb4a086a5f8d8a7c18065a43e26a83ecb8d9bb
639,325
def create_chart_histogram(workbook,sheetName,lastRow,title,axisTitle): """ Create histogram chart object """ c = workbook.add_chart({'type': 'column', 'subtype': 'stacked'}) c.set_style(2) c.add_series({ 'name': '='+sheetName+'!$F$3', 'categori...
e7c56b8a73576c98e1020baa029efabd42c47efd
639,326
def feat_step(r): """ Solid disc. """ return r <= 1
5d84c6facb2db718fb39c102cc1be6b1069b1f9e
639,327
def expand_list(list_list): """Expand list of list >>> expand_list([1,2,[3,4],5,[6,7,8]]) [[1, 2, 3, 5, 6], [1, 2, 4, 5, 7], [1, 2, 4, 5, 8]] >>> expand_list([1,2,4,5,6,7,8]) [[1, 2, 4, 5, 6, 7, 8]] """ list_in_list = [i for i in list_list if type(i) == list].copy() try: nbr_a...
55d7a37e6f1b7a9861da3b4d31ed1d777af0132f
639,328
from typing import Union def h(x: float) -> Union[int, float, None]: """ :param x: an input. :return: the value of the expression h(x) """ try: return x**2 + (1/x) + 2 except ZeroDivisionError: return None
f9ea4954234d637eb95feaf08137d64bad7186a0
639,329
import re def text_normalization(text): """ Normalize text Remove & Replace unnessary characters Parameter argument: text: a string (e.g. '.... *** New York N.Y is a city...') Return: text: a string (New York N.Y is a city.) """ text = re.sub(u'\u201e|\u201c', u'', text) text ...
e4aa05e4f81f3c625ee4334f52bf4672c3ac912b
639,330
def fortfloat(text: str) -> float: """Convert Fortran-style float to python float.""" text = text.strip() if text.endswith("d"): text = text[:-1] text.replace("d", "e") try: return float(text) except ValueError: if len(text) > 1 and "-" in text[1:]: text = f"{...
0af8820985ae44d07e04135783a0bc1e1c271d75
639,332
def safe_str(obj): """ return the byte string representation of obj """ try: return str(obj) except UnicodeEncodeError: return obj
9ce31492c09a33af6c3356c5fd07ec2857d1dc50
639,333
from typing import Counter def build_worddict(data, num_words=None): """ Build a dictionary associating words from a set of premises and hypotheses to unique integer indices. Args: data: A dictionary containing the premises and hypotheses for which a worddict must be built. The di...
a7dd855a9cfda93df88f1593236d0ccc3a4917b4
639,334
def b64pad(data): """ Pad base64 data with '=' so that it's length is a multiple of 4. """ missing = len(data) % 4 if missing: data += b'=' * (4 - missing) return data
76e0cb9954011511009d5508ed837ef5614660fa
639,337
def latex_template(name, title): """ return latex pic string """ return ( r"\begin{figure}[ht]" '\n' r" \centering" '\n' rf" \import{{./fig/}}{{{name}.pdf_tex}}" '\n' rf" \caption{{{title}}}" ...
d6521d7bbb149791a72afc8ce945e887f13e19ad
639,338
def _tpi_name(scale, smth_factor): """Return name for the array in output of the tpi function""" add = f"_SMTHFACT{smth_factor:.3g}" if smth_factor else "" return f"TPI_{scale}M{add}"
4ef4734c747983a7340da2835e602aff4b23b55c
639,339
def updatePersonId(emailAddressDf, participantsDf): """ This method update participants dataframe with PersonId for CDM :param emailAddressDf: emailAddressDf dataframe :type emailAddressDf: object :param participantsDf: Participants dataframe :type participantsDf: object """ return part...
44f1c13e41323fb39919d4ceec22f9d4de8791f4
639,340
import json def read_events(trace, options): """Reads all events from time-trace json file |trace|.""" trace_data = json.load(trace) def include_event(event, options): """Only include events if they are complete events, are longer than granularity, and are not totals.""" return ((...
677dbb6c039401141e58c9ad7f0acc9ebc323975
639,341
def qs2dict(qs, filter_items=[]): """ This function will take a query string of the form a=1&b=2 and return a dictionary of the form {'a': '1', 'b': '2'}. It will also filter any key in the filter list. """ result = {} params = qs.split('&') for param in params: if param.find('='...
b225d440207e39a7dc44c4a867aa4fca4075fd8d
639,342
import argparse def get_args(): """ Get command line arguments """ parser = argparse.ArgumentParser(description="Arg parser for Cochrane processing") parser.add_argument("-c", dest="crawl", action="store_true", help="Crawl Coc...
18a8e8604b94e059a801222ccadc5bc683261752
639,343
import base64 def get_data(fn, encoding=None): """Read the data from file and encode.""" mode = 'rb' if encoding == 'base64' else 'r' with open(fn, mode) as fp: data = fp.read() if encoding == 'base64': data = base64.b64encode(data) if isinstance(data, bytes): return data...
106ffd241a9dbc064190a0c0a0c13220e6c24a3c
639,344