content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_connector_cluster_by_conf(channel_name, project_id=None, bk_biz_id=None, cluster_type=None): """ :param channel_name: channel_name :param project_id: 项目id :param bk_biz_id: 业务id :param cluster_type: 集群类型 :return: 优先根据project_id,bk_biz_id选择集群 """ project_route_config = model_mana...
8ef3f40639fca1785c9328aa0a07f82c05e17ab6
3,613,300
import struct def convert_to_unsigned64(value): """Convert an integer to 64-bit unsigned.""" if value > 0xffffffffffffffff: raise TahuInterfaceError(f"Cannot convert large integer {value} to 64-bit") if value > 0: return value if value < -0x8000000000000000: raise TahuInterfa...
cc17af6d32507279ff524f529e7dc715bc06447e
3,613,301
import torch def f(x): """A transformation that has both a fully-predictable part and an inherently-random part.""" a, b = torch.split(x, 16, -1) return torch.cat((a+1, b-1 + torch.randn_like(b)/3), -1)
0da307982a0af0823a1928da097235bf3214b559
3,613,302
def msd(r): """ Mean square displacement Parameters ---------- r: numpy array. dimensions: (t, 3) Array containing the coordinates along t """ shifts = np.arange(len(r)) msds = np.zeros(shifts.size) for i, shift in enumerate(shifts): diffs = r[:-shift if shift els...
a767f611f4c99baebda583bbf7bfe90785304005
3,613,303
import re def align_shiplabels(text): """Return the announcement with the ship labels aligned.""" # See comment in is_unscheduled() for a description of the regex, def monospace(matched): return '`{}`'.format(matched.group(0)) return re.sub('^\d\d:(?!\d\d\s)', monospace, text, flags=re.MULTILI...
c266846f67d212f8cc996f65b46cccc3cb51ff31
3,613,304
def _get_data_type( version: str, name: str, property_definition: dict, entity_class_name: str ) -> kuber_maker.DataType: """...""" setter_type_hint = None reference = property_definition.get("$ref") reference_type = (reference or "").rsplit(".", 1)[-1] api_type = property_definition.get("type")...
9635849b3e67a9d75ffa4f83b21550d0e66bf27b
3,613,305
def create_api_client(base_path, access_token): """ Function for creating api clinet, to interact with docusign. input :: - base_path : base path uri - access_token : auth token received from docusign output :: api_client object """ api_client = ApiClient() api_client.host = base_pa...
dc6d84a6adc743c9bd52f6b50ff0b25f07a4a0be
3,613,306
def stopsNearby(coordX, coordY, maxRadius=None, maxNumber=None, timeout=5): """ Finds stops close to given coordinates. Args: coordX (float): Longitude. coordY (float): Latitude. maxRadius (int): The radius in meters to search within. maxNumber (int): The number of results to re...
aaca1eddd16cbf37ff84580057eeba683d6bf953
3,613,307
def _healpix_bot_left(p, nside, steps=10, reverse=False): """Returns the boundary on the bottom left side of a healpix pixel in healpix x and y coordinates. Parameters ---------- p : int Healpix pixel index. nside : int Healpix Nside. steps : int, optional Number of ...
53adf6b40c3697cafc00a8807240039b5ec7f25d
3,613,308
def imag(x): """Returns the imaginary part of a complex tensor. :param x: The complex tensor :type x: torch.Tensor :returns: The imaginary part of `x`; will have one less dimension than `x`. :rtype: torch.Tensor """ return x[1, ...]
e2a9a3ba22a4ec896a60b3991618f32014d088fd
3,613,309
def crossing_from_taper(taper=lambda: taper(width2=2.5, length=3.0)) -> Component: """Returns Crossing based on a taper. The default is a dummy taper Args: taper: taper function. """ taper = gf.get_component(taper) c = Component() for i, a in enumerate([0, 90, 180, 270]): _tape...
5b78df94084fa08a529a1e6209ef8350e807cd54
3,613,310
async def send_group_forward_msg(group_id: int, msg): """ 发送合并转发 (群) """ try: await nonebot.get_bot().call_api('send_group_forward_msg', **{ 'group_id': group_id, 'messages': msg }) except exception.NetworkError as ne: logger.warning(f'向{group_id}发送 合并...
07caa7209b8f9e87d3e3a30e83daa51e3a7953d0
3,613,311
import torch def unflatten_array(X, N, param_shapes): """Takes flattened array and returns in natural shape for network parameters.""" return [torch.reshape(X[N[i]:N[i + 1]], s) \ for i, s in enumerate(param_shapes)]
1b127de0d8389d2b44d4f50c3cb85429d2629107
3,613,312
def quantize_values(values, centers=None): """On a particular 1d latice, quantize points to nearest Args: values (ndarray[Float]): Array of values to quantize to the centers centers (ndarray[Float]): Center values to quantize to. If None it will attempt to get the centers from the v...
424aea184208942c8b52349c312a9a8ef9acdef5
3,613,313
def bs_se(bs_pdf): """ Calculates the bootstrap standard error estimate of a statistic """ N = len(bs_pdf) return np.std(bs_pdf) * np.sqrt(N / (N - 1))
d08dc819f72e9c288e85b597eb5764980475cd58
3,613,314
import six def _create_subnetwork_report_proto(materialized_subnetwork_report): """Creates a Subnetwork proto.""" def _update_proto_map_from_dict(proto, field_name, dictionary): """Updates map field of proto with key-values in dictionary. Args: proto: the proto to be updated in place. field_...
9aff035cb7b8ae08c59a3f7508164c62f023c18d
3,613,315
import time import re def parse_timestamp(timestamp, time_format=None): """ parse_timestamp(timestamp, time_format=None) -> struct_time Does NOT raise ValueError. Return None on formatting error. """ if time_format is None: time_format = '%a, %d %b %Y %H:%M:%S %Z' try: return time.strptime(timest...
f1a9064a5da4791b1a652c3acfc6ee092144c21f
3,613,316
def decrypt(value): """decoding""" print(value) src = signing.loads(value) print(src) return src
93b113b695b6927bda88e8ed4d6a1c59b05380b9
3,613,317
def calculate_activation_statistics(act): """Calculation of the statistics used by the FID. Params: -- images : Numpy array of dimension (n_images, hi, wi, 3). The values must lie between 0 and 255. -- sess : current session -- batch_size : the images numpy array is...
3dc8702a7af8edb5ebed4583ad0c35d630adee2b
3,613,318
def user_view_list_data(): """ Fixture for testing VideoDetail view permissions with a collection view_list """ video = VideoFactory() collection = video.collection moira_list = factories.MoiraListFactory() collection.view_lists.set([moira_list]) return SimpleNamespace(video=video, moira...
2b3dcef2cec60f87fdf25c7e10f0b7eb8f4cb717
3,613,319
import pandas import numpy def _fast_spearman(corr_method, x, y, destination): """internal method for calculating spearman correlation, allowing subsititution of methods for calculationg correlation (corr_method), allowing to choose methods that are fast (fast_corr) or tolerant of nan's (nan_fast_corr) to be ...
41449bdd5e73bfd1beca7412a960a498d9340e02
3,613,320
import time def amountValidation(amount, minWithdrawAccount, maxWithdrawAccount, atmCash, accountBalance, minBill): """Validate the amount of money. Args: amount (int): Amount of money. minWithdrawAccount (int): Minimum amount of money allowed to withdraw. maxWithd...
5a0b70da29832cbf31f114c5941471ff69762016
3,613,321
def catchItem(f, theSpider=None): """Decorador, ejecuta la función parse y procesa el resultado como una lista de items, ejecutando la función 'saveitem' que corresponda.""" def new_f(*args, **kwargs): #print("thepath "+os.getcwd()) #print("the spider") #print(str(theSpider)) ...
2f2bba543a2ecf783d7372a39cc1edc4a9fc788c
3,613,322
def _MatchGlobToken_Fast(line, start_pos): """Returns (id, end_pos).""" tok_type, end_pos = fastlex.MatchGlobToken(line, start_pos) return IdInstance(tok_type), end_pos
3dd3c7e117e2237ea4f7659240af90faaddf3a9a
3,613,323
import math def roundoff(a, digit=2): """ roundoff the number with specified digits. :param a: float :param digit: :return: :Examples: >>> roundoff(3.44e10, digit=2) 3.4e10 >>> roundoff(3.49e-10, digit=2) 3.5e-10 """ if a > 1: return round(a, -int(math.log10...
c2bded960f9fa6431a03f6562b49f73477379a32
3,613,324
def trial(car, initial, change, verbose=False): """Perform the simulation of one trial Parameters ---------- car : int The door the car is behind (1, 2 or 3) initial : int The player's initial door selection (1, 2 or 3) change : bool If true, the player will change their...
cd6f328f18b7ea22281f3993b43f89e3118064c1
3,613,325
def imgMI(inImg, refImg, inMask=None, refMask=None, numBins=128, samplingFraction=1.0): """ Compute mattes mutual information between input and reference images """ # In SimpleITK the metric can't be accessed directly. # Therefore we create a do-nothing registration method which uses an ...
60a94e7029978a3b567a4d7569f08b6ed49b1f7d
3,613,326
import re def natsort(alist): """ Sort the given iterable in the way that humans expect. From: https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python """ convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for ...
3ceabceab67a78d41966095f4a2b51c4e8cf1a72
3,613,327
def get_field(data, ml=0, member=None): """ Arguments: data: N-D array of data ml: Prefer this model level, if there are several levels Returns: np.array: 3D array: Time X, Y """ if(len(data.shape) == 4): # Extract the right model level, if multip...
be81c095097bfa77c0043cc31a5913dcd3c7419a
3,613,328
import os def predict_with_lgbm_meter(test_df, row_ids, model_filepath): """" Takes a given directory which contains four models (one for each meter type) and then predicts the rows with the respective model :param test_df: DataFrame containing the test data :param row_ids: A vector with the match...
6101481263ca615b13331e4b8c2195272b23abfc
3,613,329
def validate_unreal_paths(properties): """ This function checks each of the entered unreal paths to see if they are correct. :param object properties: The property group that contains variables that maintain the addon's correct state. :return bool: True if the objects passed the validation. """...
732182c239e8166964f49350aa7b51e37bc04111
3,613,330
def parse_args(): """Parse the command line arguments and perform some validation on the arguments Returns ------- args : argparse.Namespace The namespace containing the arguments """ parser = ArgumentParser( description='''Run GIST calculations through command-line.''') ...
8efbbc7b56e27661bef95661491ce065c630cdb7
3,613,331
def parse_labels_yolo(label_file, labels, img_width, img_height): """ Definition: Parses label files to extract label and bounding box coordinates. Converts (x1, y1, x1, y2) KITTI format to (x, y, width, height) normalized YOLO format. Parameters: label_file - file with KITTI label(s) inside labels - list ...
73a892f87c1419bf24e3b99cbda49f3c489a4a83
3,613,332
import six def build_dict(min_word_freq=50, train_filename="", test_filename=""): """ Build a word dictionary from the corpus, Keys of the dictionary are words, and values are zero-based IDs of these words. """ with open(train_filename) as trainf: with open(test_filename) as testf: ...
fb9dd7832d38d1c71ba36b2fcaf1118d8a23ce3c
3,613,333
from typing import Tuple from typing import List def deltaG_fwd(model, sys_params) -> Tuple[Tuple[float, List], np.array]: """same signature as DeltaG_from_results, but returns the full tuple""" results = run_model_simulations(model, sys_params) return _deltaG_from_results(model=model, results=results, sy...
79aa0ad79e66246b7bfb8aff37315d235c192464
3,613,334
from datetime import datetime def parse_iso8601tz(date_string): """return a datetime object for a string in ISO 8601 format. This function parses strings in exactly this format: '2012-12-26T13:31:47.823-08:00' Sadly, datetime.strptime's %z format is unavailable on many platforms, so we can't use...
a4a3c233ebad1d2ea3537c40b8f6114a791d5311
3,613,335
def sp_compute_adj_att(node_features, adj_matrix_sp): """Self-attention for edges as in GAT with sparse adjacency.""" out_dim = node_features.shape[-1] # Self-attention mechanism a_row = tf.get_variable( initializer=WEIGHT_INIT, dtype=tf.float32, name='selfatt-row', shape=(out_dim, 1)) ...
31b4e3fc3b3508d3a631252b27574c0a1fdbef8c
3,613,336
def mat_mul2(A, B, alpha=1): """ https://www.benjaminjohnston.com.au/matmul """ return alpha * np.matmul(A, B) # return LA.blas.sgemm(alpha, A, B)
7a92469cd5348dc636eead8b9965a8d507cfa59e
3,613,337
def observation_encoder(o): """ """ with tf.variable_scope('observation_encoder_module'): std1 = tf.nn.space_to_depth(o, 4) cs1 = conv_stack(std1, 3, 16, 5, 16, 3, 64) std2 = tf.nn.space_to_depth(cs1, 2) cs2 = conv_stack(std2, 3, 32, 5, 32, 3, 64) e = tf.nn.relu(cs2) ...
6602d13a74bab4175c0c1edc94a9523ce9a4a875
3,613,338
def getSuperUserTimezone(): """ For the calculation of correct datetimes for payment gateways on when exactly to charge recurring payments Assumption: the superuser has set the correct local timezone which matches with the payment gateway's timezone setting """ su = User.objects.get(is_superuser=1) ...
4d1d625628854f561465abe9a1863c87b956b0af
3,613,339
import numpy def empirical(datafile,vavg,crew,rigging,tstroke,trecovery,doplot=1): """ Reads in empirical acceleration data to be compared with acceleration plot """ lin = rigging.lin lscull = rigging.lscull lout = lscull - lin tempo = crew.tempo mc = crew.mc mb = rigging.mb ...
ce3e3c67c424fac7bf579373e0058181c8d26dc1
3,613,340
def dup_zz_factor(f, K): """ Factor (non square-free) polynomials in `Z[x]`. Given a univariate polynomial `f` in `Z[x]` computes its complete factorization `f_1, ..., f_n` into irreducibles over integers:: f = content(f) f_1**k_1 ... f_n**k_n The factorization is computed by redu...
fc501028de0908bea8d36d78baac2c007e987413
3,613,341
def non_net_metering(tfr_dfs): """ Transform the EIA 861 Non-Net Metering table. Args: tfr_dfs (dict): A dictionary of transformed EIA 861 DataFrames, keyed by table name. It will be mutated by this function. Returns: dict: A dictionary of transformed EIA 861 dataframes, ke...
ced698f5636872a241578f667d61aa323fb6e14f
3,613,342
def create_user(**params): """Create and return a new user.""" return get_user_model().objects.create_user(**params)
73d8b30547229b2a8d2d0478d5830a7ce3c289ac
3,613,343
from typing import Counter def answer_counts(answers): """Rank the most popular answers to a question, given a per-student mapping of answers to questions from final_answers_from_df() TODO: Make this into an expectation maximization problem instead to find source reliability, and then also retur...
ca8d8e3bc17167a76baa1cc0394cb599f64c7ccf
3,613,344
import os def create_configuration() -> Config: """Create and populate the configuration.""" return Config(dict(os.environ))
310c1eb680aed85ccd22e4878f9fc7e0d216898d
3,613,345
def napari_get_reader(path): """Show OME XML if an ome.xml file is dropped on the viewer.""" if isinstance(path, str) and path.endswith("ome.xml"): return view_ome_xml
189215539c83c192f0eb036d946761edeb91d8e6
3,613,346
def Hx(sk, messages): """A helper function Hx""" assert len(messages) == len(sk) - 1 total = sk[0] for xi, mi in zip(sk[1:], messages): total = total + (xi * mi) return total
609794cc6bcf7b6321192d23a0d4903ffce05b91
3,613,347
import six def rpc_context_span_extractor(context): """ Extract and create Span object from context object. Expects context object to have span attribute. :param context: :return: opentracing.span.Span object """ log.debug("In rpc_context_span_extractor...") try: # If c...
6454c5fa1819b806384e25c9f68e1a7386b99eb5
3,613,348
def _unsur(s: str) -> str: """Merge surrogates.""" return s.encode("utf-16", "surrogatepass").decode("utf-16", "surrogatepass")
d6bc230a77c735c9922ec66aa6a3537beea5b42f
3,613,349
def chatload(): """ Load all chat messages on a conversation channel """ rq = RequestData(request) channel = rq["channel"] if not channel: # We must have a valid channel return jsonify(ok=False) user_id = current_user_id() game = None if channel.startswith("game:"): ...
237a00a580609709c16a79f4a9440837ca6c4935
3,613,350
import os def register_memory(): """Register an approximation of memory used by FTP server process and all of its children. """ # XXX How to get a reliable representation of memory being used is # not clear. (rss - shared) seems kind of ok but we might also use # the private working set via ge...
f89cae41214d1e6f6c6b1e9d10bf5d5c48bbb3b3
3,613,351
def newgpg(ui, **opts): """create a new gpg instance""" gpgpath = ui.config(b"gpg", b"cmd") gpgkey = opts.get('key') if not gpgkey: gpgkey = ui.config(b"gpg", b"key") return gpg(gpgpath, gpgkey)
7f82c1b1413c5940b109d9968266ad487981fabd
3,613,352
def main(args=None): """Console script for cli_password_manager.""" pass_mgr = PasswordManager() pass_mgr.screen() return 0
5a82b952e11fc9d9db4ac5af49d7c64ed08d9140
3,613,353
from typing import TextIO from typing import List import textwrap from datetime import datetime def test(general: _general.Params, command: Params, stdout: TextIO) -> List[str]: """ Test the specified functions. Return errors if any. """ if not command.path.exists(): return ["The file to ...
84fa55fa07378b7b7471be4873c3282dd90ac324
3,613,354
def make_routing_table(obj, keys, prefix='on_'): """ :return: a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``, but ``obj`` does not have to define all methods. It may define the needed ones only. :param obj: the object :param keys: a list of keys ...
79006027e74869b4de663f8d908c66f0c22e9de8
3,613,355
def series_greater_than_zero(series: pd.Series): """Return a bool series indicating whether the elements of s are > 0""" return series > 0
1e5ed1eae2a8e2cfb20ac4220652eaf672475f04
3,613,356
def Seq_of_t(tau,Te,R): """ Python implementation of Seq(tau) Time domain auto-correlation of a tunnel junction at thermal equilibrium Latex : S_{eq} = - \frac{\pi (k T)^2}{R \hbar} \sinh^{-2} \bigg( \frac{\pi k T}{\hbar} \tau \bigg) See Also -------- Thesis : Mesu...
047b5e6b28a095560fb6f2b817a6a514b7d34c5b
3,613,357
import urllib3 from bs4 import BeautifulSoup def get_html_page(page_url): """ Get the whole page source code""" http = urllib3.PoolManager() response = http.request('GET', page_url) soup = BeautifulSoup(response.data, 'html.parser') response.release_conn() return soup
5c535322f713d94c541d423e79e780016977d4e6
3,613,358
def get_aname(value: str) -> str: """Pass.""" return strip_right(obj=str(value or ""), fix="_adapter")
ef586cfbccb5a81ff561024967771827456adc1e
3,613,359
def air_cargo(): """ [Figure 10.1] AIR-CARGO-PROBLEM An air-cargo shipment problem for delivering cargo to different locations, given the starting location and airplanes. Example: >>> from planning import * >>> ac = air_cargo() >>> ac.goal_test() False >>> ac.act(expr('Load(C2,...
7cbcf38abad878b7f381904a16eb440d602a5e34
3,613,360
import os def compare(r1, r2, label, outdir): """Compares results * r1, r2 :: TesseraeResults The score returned is the sum of the differences of scores between the same match pair. """ with open(os.path.join(outdir, label+'.results'), 'w') as ofh: r1_stop = {s for s in r1.stopwo...
d9a3fbcba8e578500816b22ff0b1af9cb91a5c11
3,613,361
import tempfile def create_spooled_temporary_file(filepath=None, fileobj=None): """ Create a spooled temporary file. if ``filepath`` or ``fileobj`` is defined its content will be copied into temporary file. :param filepath: Path of input file :type filepath: str :param fileobj: Input file ob...
5254c01194a94063e405c721735fb9e390fd8380
3,613,362
def _split_comma_separated(string): """Return a set of strings.""" return set(filter(None, string.split(',')))
855c23c7a6602c9306b73016cc66573773d1d502
3,613,363
def make_ur_axialregion(asm_input, reg, mat_dict, flow_rate): """Process DASSH Assembly AxialRegion input to obtain un-rodded region input parameters; to be used when instantiating un-rodded region objects as axial regions in DASSH Assembly object""" model = asm_input['AxialRegion'][reg]['model'] ar...
70dc0e07fb5e707fb22c11ed036b4418e2412172
3,613,364
from typing import Optional from typing import Callable from re import T def deprecate( remove_by_version: str, replacement: Optional[str] = None ) -> Callable[[T], T]: """Return a function that can be used to deprecate functions. Currently this is only used for deprecation of hook functions, but it may b...
b18a5abcc63d3ad142d5c13a0f592cee39503bc5
3,613,365
def triangular(n): """Compute the n-th triangular number.""" return np.floor_divide(n * (n + 1), 2)
d328f4c8c38452fbadcacd59f583e37c86ce4e02
3,613,366
from bs4 import BeautifulSoup def list_captures(): """Get a list of the videos and photo files on the GoPro Use BeautifulSoup to parse the GoPro's list of captures This list of captures is provided by the Cherokee webserver on the GoPro To get this capture the GoPro Hero 3 Black """ page = ur...
3931c2017825d3df3a0fcd36d78c7f086e3c4f3c
3,613,367
def get_nbest(lat, n, aw=1.0, lw=1.0, ip=0.0): """Obtain nbest hypotheses with scores from the lattice.""" hyps, scores = [], [] nbest_paths = lat.nbest(n, aw=aw, lw=lw, ip=0.0) for path in nbest_paths: hyp = [arc.dest.sym for arc in path] # sos, eos, and other tokens are stripped ...
235f49f24ed55c40f653146c2fae39fa960fcdf5
3,613,368
import os def static_filename(config, path, logger): """ Check if there is a static file matching 'path'. :param config: IdP config :param path: URL part to check :param logger: Logging logger :return: False, None or filename as string :type config: IdPConfig :type path: string :...
ad5c545906c204f8c3a9facbcb9f8312dd443ca8
3,613,369
def get_tests(): """Parse the TESTS file. Parse the TESTS file and return a list of Entry objects """ if not check_test_index(): add_ids_test_index() in_file = open(TESTS, 'rb') entries = [] entry = Entry() cur = entry.buffer counter = 1 is_pre = False pre_sapces = 0...
8a532b2e710cff5db86f55aa5bd3e1096a84a52c
3,613,370
def interpolate(xs: list, ys: list, zs: list, ratio: float) -> list: """ This interpolates between two points """ x = xs[1] - xs[0] y = ys[1] - ys[0] z = zs[1] - zs[0] return [xs[0] + x * ratio, ys[0] + y * ratio, zs[0] + z * ratio]
63816ec83adbabef21ea92ee36a92884417755cc
3,613,371
import hashlib def str_to_sha256(s: str): """Generate a 256 bit integer hash of an arbitrary string.""" return int.from_bytes(hashlib.sha256(s.encode("utf-8")).digest(), "big")
90fcae50485e1469cdb0f363e4110011d5e6b642
3,613,372
def comment(pitch_id): """This will add a comment """ pitches = Pitch.query.all() comment_form = CommentForm() comments = Comment.query.all() if comment_form.validate_on_submit(): comment = Comment(comment = comment_form.comment.data, upvote = comment_form.vote.data,pitch_id = pitch_id,u...
84ce837f77f8f0d6317d5b7ab71615400b58737e
3,613,373
def get_template_redirects(site, template_name): """Gets the names of all of the template-space redirects to the provided template. The names come without namespaces. Example, if `site` is a enwiki site object: >>> get_template_redicts(site, "Hexadecimal") [u'hexdigit'] """ print(template_n...
a201e1d59864dad58afb34a82db89afe164ed4aa
3,613,374
def GetActiveWindow(*args): """ GetActiveWindow() -> Window Get the currently active window of this application, or None """ return _misc_.GetActiveWindow(*args)
13cfcd3b47cfa431c81f602498b5c77cc9f49db4
3,613,375
def get_pysyd_parameters(args, parallel, CLI): """ Basic function to call the individual functions that load and save parameters for different modules. Parameters ---------- args : argparse.Namespace command-line arguments CLI : bool `True` if running pysyd via command line ...
1e0ead51a82cd4692b9b3129038e8462f2bf3924
3,613,376
def cityscapes_palette(num_cls=None): """ Generates the Cityscapes data-set color palette. Data-Set URL: https://www.cityscapes-dataset.com/ Color palette definition: https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py Original source taken from: ...
b1a69a4e511e541f13aeb584003b7f4ec0dde956
3,613,377
import numpy def entropymatrix(elements): """Calculates the unnormalized Shannon entropy for a numpy matrix.""" entropysum = 0 result = 0.0 for (x, y), value in numpy.ndenumerate(elements): element = elements[x, y] if element > 0: result += xlogx(element) entrop...
b959f099d2f853da2987bc2bff4022bd6999687b
3,613,378
from typing import Optional def dislodged_unit_type_from_area( area_id: AreaID, board_state: np.ndarray) -> Optional[UnitType]: """Returns the type of any dislodged unit in the province.""" if board_state[area_id, OBSERVATION_DISLODGED_ARMY] > 0: return UnitType(UnitType.ARMY) elif board_state[area_id, ...
739c31ca93dc77006e2909b51b19411656817628
3,613,379
def try_with_lazy_context(error_context, f, *args, **kwargs): """ Call an arbitrary function with arbitrary args / kwargs, wrapping in an exception handler that attaches a prefix to the exception message and then raises (the original stack trace is preserved). The `error_context` argument should be...
7e2a4cfee7b4acf5a449b4b07f8c56baca5a63d3
3,613,380
def make_tweet_fn(text, time, lat, lon): """An alternate implementation of make_tweet: a tweet is a function. >>> t = make_tweet_fn("just ate lunch", datetime(2012, 9, 24, 13), 38, 74) >>> tweet_text_fn(t) 'just ate lunch' >>> tweet_time_fn(t) datetime.datetime(2012, 9, 24, 13, 0) >>> latit...
3f465f91dce37641e1ce391f6025c742d9e6ef36
3,613,381
import hashlib import base64 import secrets import traceback def user_login(): """ Endpoint for login password submission """ try: hashfunc = hashlib.sha256() hashfunc.update(request.form["password"].encode("utf-8")) stored_hash = DSCLIENT.get(DSCLIENT.key("config", "password_hash")) ...
4a81b690630e7d14bd60220ffaf323b0555230f1
3,613,382
def initial_wumpus_axioms(xi, yi, width, height, heading='east'): """ Generate all of the initial wumpus axioms xi,yi = initial location width,height = dimensions of world heading = str representation of the initial agent heading """ axioms = [axiom_generator_initial_location_assertions...
fb94f7e562518be272a3971018b4597d66ad253e
3,613,383
def feed(): """Live Video Feed """ global accessGranted print "/feed Requested" print accessGranted if accessGranted: return render_template('index.html') else: return redirect(url_for('login'))
04f12a55cc5904999cdc199ecab00800728583cb
3,613,384
from typing import Optional import google from typing import Dict import os def load_model_from_vertex( project: str, region: str, endpoint_id: str, credentials: Optional[google.auth.credentials.Credentials] = None, input_modalities: Optional[Dict[str, str]] = None ) -> model_lib.Model: """Loads...
ba46b1a108ab0433b09729de401353bfb0e624e4
3,613,385
def frametimes_from_file(infile): """infile is a frametimes file each row has [frame number, start dur, stop] in seconds Returns ------- ft: array [start, duration, stop] in seconds for each frame """ ft = np.loadtxt(infile, delimiter = ',', usecols = (1,2,3), skiprows =...
8a23d1612dc876c10aef6c19d45307ff98ff9e72
3,613,386
def _get_wordpiece_detokenized_text( token_span: _SpanType, raw_prediction: _RawPredictionType, tokenizer: tokenization.FullTokenizer) -> str: """Gets the normalized answer token text given the token span.""" answer_tokens = tokenizer.convert_ids_to_tokens( raw_prediction["long_token_ids"][token_span[...
ad807a5827df46193260953905596152bb59c5f8
3,613,387
def select_sentiment_by_date(search_string, search_date): """ Query column(s) from `search_string` in the tweets table where date LIKE `search_date` :param search_string: column name(s) to Query :param search_date: date to search :return: Query results from search_string and search_date """ ...
efa7877ebc1707a6ca4e70c005d61e80399b6ddf
3,613,388
import pandas as pd def noaaDateConv(dataframe): """ This function takes a dataframe with datetime values and converts it into a format that the NOAA ccg tool can easily read :param dataframe: A dataframe that has to have a column labeled 'datetime' which contains dt.datetime formatted items ...
2556009e803ce1406ed5845636ff7cad4d5c1d21
3,613,389
def sms_rest(msg): """ :param msg: <str> :return: <int> return the difference between length of message and capacity of sms """ if sms_is_limited(msg): return 70 - len(msg) return 160 - len(msg)
c9dfca6d5770ff3e20832b0221f664ef8ab8ec2b
3,613,390
import numpy def mel_filter_bank(fs, nfft, lowfreq, maxfreq, widest_nlogfilt, widest_lowfreq, widest_maxfreq,): """Compute triangular filterbank for cepstral coefficient computation. :param fs: sampling frequency of the original signal. :param nfft: number of points for the Fourier Transform :param l...
4aae716001b281e1008cb9d98e1a6d6a7f7fe491
3,613,391
def mod3(): """ Create a simple model for multiple incorporation tests """ class mod3(mod1, mod1b, Model): def __init__(self, name, description): super().__init__(name, "Model 3") self.a = self.createVariable("a",dimless,"a") self.b = self.createVariable(...
4897a039075743dade45676e3f76cc5b671d6e1b
3,613,392
def is_convex_polygon(polygon): # noqa """Return True if the polynomial defined by the sequence of 2D points is 'strictly convex': points are valid, side lengths non- zero, interior angles are strictly between zero and a straight angle, and the polygon does not intersect itself. See: https://stack...
bd5ff1efc10e2455c3c65279869c34aff5c17373
3,613,393
def make_paragraph(text): """ An example function that takes in text and returns a paragraph from it that can be used in the Knuth-Plass Algorithm. """ # Turn chunk of text into a paragraph L = [] for ch in text: if ch in ' \n': # Add the space between words ...
e702db1698abcda587d8d4cf7c0b298b005355c3
3,613,394
def even_time_series_spacing(dfi, n, t0=None, t_n=None): """Interpolate irregularly spaced time series. To obtain regularly spaced data. Parameters ---------- dfi : pandas dataframe dataframe with one dimensional index containing time stamps as index values. n : int n...
98c3ecda0a82e989de80b7c27fd73f952b851401
3,613,395
import zipfile def loader(path_zip, file_img): """ Load imagefile from zip. """ with zipfile.ZipFile(path_zip, 'r') as myzip: img = Image.open(myzip.open(file_img)) return img.convert('RGB')
22606417819087100120be2cae0f549c5b405056
3,613,396
def get_triplets_at_q(grid_point, bz_grid, reciprocal_rotations=None, is_time_reversal=True, swappable=True): """Parameters ---------- grid_point : int A grid point in the grid type chosen by is_dense_gp_map. ...
a6e2142c8bb972bf4011fd36de7f8f34559f462a
3,613,397
def search_text_to_suggestion(search_text: SearchText, term: OntologyTerm) -> ConditionMatchingSuggestion: """ Does this term match the search_text, if so, add it as a suggestion (possibly with some validation) """ cms = ConditionMatchingSuggestion() if match_info := search_text.matches(term): ...
8113134ce1b1c46a375bf38ab213c0693cbeb2e6
3,613,398
import json def get_section_with_options(section_name): """ Takes section name(str) and returns section with option=value keys as json """ section_dict = {} option_value = {} for option, value in SAMBA_CONFIG_PARSER.items(section_name): option_value[option] = value section_dict[s...
52a8ab8437cfd4925a11e4472f999a433b5865bd
3,613,399