content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def f(p, x): """ Parameters ---------- p : list A that has a length of at least 2. x : int or float Scaling factor for the first variable in p. Returns ------- int or float Returns the first value in p scaled by x, aded by the second value in p. Examples ...
3a5e464e7599b6233086e3dddb623d88c6e5ccb6
3,648,300
def get_contributors_users(users_info) -> list: """ Get the github users from the inner PRs. Args: users_info (list): the response of get_inner_pr_request() Returns (list): Github users """ users = [] for item in users_info: user = item.get('login') github_profile =...
1a7bdb6608600c2959ec3961dfd9567cf674f471
3,648,301
def euler2mat(roll, pitch, yaw): """ Create a rotation matrix for the orientation expressed by this transform. Copied directly from FRotationTranslationMatrix::FRotationTranslationMatrix in Engine/Source/Runtime/Core/Public/Math/RotationTranslationMatrix.h ln 32 :return: """ angles = _TORAD ...
2b635f50bb42f7a79938e38498e6e6fefd993d0f
3,648,302
def remove_articles(string: str, p: float = 1.0) -> str: """Remove articles from text data. Matches and removes the following articles: * the * a * an * these * those * his * hers * their with probability p. Args: string: text p: probability of removin...
af2b9f61dc36159cb027eae03dbf1b645e48be62
3,648,303
import os def _remove_overlaps(in_file, out_dir, data): """Remove regions that overlap with next region, these result in issues with PureCN. """ out_file = os.path.join(out_dir, "%s-nooverlaps%s" % utils.splitext_plus(os.path.basename(in_file))) if not utils.file_uptodate(out_file, in_file): w...
16a26ca0bcabf142f99b59bfb3e677c4fa81e159
3,648,304
import collections import re def _get_definitions(source): # type: (str) -> Tuple[Dict[str, str], int] """Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing...
a97fe58c3eb115bff041e77c26868bae3bc54c88
3,648,305
import requests def pairs_of_response(request): """pairwise testing for content-type, headers in responses for all urls """ response = requests.get(request.param[0], headers=request.param[1]) print(request.param[0]) print(request.param[1]) return response
f3a67b1cbf41e2c2e2aa5edb441a449fdff0d8ae
3,648,306
def setup(): """ The setup wizard screen """ if DRIVER is True: flash(Markup('Driver not loaded'), 'danger') return render_template("setup.html")
1c13ba635fcdd3dd193e511002d2d289786980a3
3,648,307
def ldns_pkt_set_edns_extended_rcode(*args): """LDNS buffer.""" return _ldns.ldns_pkt_set_edns_extended_rcode(*args)
3fed71706554170d07281a59ff524de52487244d
3,648,308
def sim_spiketrain_poisson(rate, n_samples, fs, bias=0): """Simulate spike train from a Poisson distribution. Parameters ---------- rate : float The firing rate of neuron to simulate. n_samples : int The number of samples to simulate. fs : int The sampling rate. Ret...
853a16ae50b444fad47dcbea5f7de4edf58f34b5
3,648,309
def getHausdorff(labels, predictions): """Compute the Hausdorff distance.""" # Hausdorff distance is only defined when something is detected resultStatistics = sitk.StatisticsImageFilter() resultStatistics.Execute(predictions) if resultStatistics.GetSum() == 0: return float('nan') # E...
933206c551f2abd6608bf4cdbb847328b8fee113
3,648,310
import re def _filesizeformat(file_str): """ Remove the unicode characters from the output of the filesizeformat() function. :param file_str: :returns: A string representation of a filesizeformat() string """ cmpts = re.match(r'(\d+\.?\d*)\S(\w+)', filesizeformat(file_str)) return '{...
c9811120a257fda8d3fe6c3ee1cd143f17fc4f6e
3,648,311
import math def radec_to_lb(ra, dec, frac=False): """ Convert from ra, dec to galactic coordinates. Formulas from 'An Introduction to Modern Astrophysics (2nd Edition)' by Bradley W. Carroll, Dale A. Ostlie (Eq. 24.16 onwards). NOTE: This function is not as accurate as the astropy conversion, no...
85156dae81a636f34295bcb8aab6f63243d9c2b3
3,648,312
from typing import Counter from datetime import datetime def status_codes_by_date_stats(): """ Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. """ def date_counter(queryset): return dict(Counter(map( ...
e56491e32a774f2b3399eb252bc5c7660539d573
3,648,313
def r8_y1x ( t ): """ #*****************************************************************************80 # #% R8_Y1X evaluates the exact solution of the ODE. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 30 August 2010 ...
b6146173c09aede82fab599a9e445d3d062bf71a
3,648,314
def get_target_model_ops(model, model_tr): """Get operations related to the target model. Args: * model: original model * model_tr: target model Returns: * init_op: initialization operation for the target model * updt_op: update operation for the target model """ init_ops, updt_ops = [], [] for v...
0967e754e2731140ca5d0d85c9c1b6cff7b2cbd2
3,648,315
import itertools import functools def next_count(start: int = 0, step: int = 1): """Return a callable returning descending ints. >>> nxt = next_count(1) >>> nxt() 1 >>> nxt() 2 """ count = itertools.count(start, step) return functools.partial(next, count)
299d457b2b449607ab02877eb108c076cb6c3e16
3,648,316
def show_locale(key_id: int): """Get a locale by ID""" return locales[key_id]
6bce0cc45e145a6bdfb5e84cdde8c6d386525094
3,648,317
def refresh(): """Pull fresh data from Open AQ and replace existing data.""" DB.drop_all() DB.create_all() update_db() DB.session.commit() records = Record.query.all() return render_template('aq_base.html', title='Refreshed!', records=records)
a1f138f92f8e7744d8fc5b659bb4d99fc32341e9
3,648,318
def get_similar_taxa(): """ Get a list of all pairwise permutations of taxa sorted according to similarity Useful for detecting duplicate and near-duplicate taxonomic entries :return: list of 2-tuples ordered most similar to least """ taxa = Taxon.objects.all() taxon_name_set = set([t.name f...
cb94efad4103edc8db0fe90f0e2bad7b52bf29f5
3,648,319
import json def make_img_id(label, name): """ Creates the image ID for an image. Args: label: The image label. name: The name of the image within the label. Returns: The image ID. """ return json.dumps([label, name])
4ddcbf9f29d8e50b0271c6ee6260036b8654b90f
3,648,320
def col2rgb(color): """ Convert any colour known by matplotlib to RGB [0-255] """ return rgb012rgb(*col2rgb01(color))
075dbf101d032bf1fb64a8a4fd86407ec0b91b2d
3,648,321
from typing import List import random def quick_select_median(values: List[tuple], pivot_fn=random.choice, index=0) -> tuple: """ Implementation quick select median sort :param values: List[tuple] :param pivot_fn: :param index: int :return: tuple """ k = len(values) // 2 return qui...
a2977424a9fc776b2448bed4c17eea754003242c
3,648,322
import time import hashlib def get_admin_token(key, previous=False): """Returns a token with administrative priviledges Administrative tokens provide a signature that can be used to authorize edits and to trigger specific administrative events. Args: key (str): The key for generating admin t...
6f92378676905b8d035bd201abe30d1d951a7fc0
3,648,323
def modSymbolsFromLabelInfo(labelDescriptor): """Returns a set of all modiciation symbols which were used in the labelDescriptor :param labelDescriptor: :class:`LabelDescriptor` describes the label setup of an experiment :returns: #TODO: docstring """ modSymbols = set() for labelSt...
323382cd5eaae963a04ec6a301260e1f2aed9877
3,648,324
def vulnerability_weibull(x, alpha, beta): """Return vulnerability in Weibull CDF Args: x: 3sec gust wind speed at 10m height alpha: parameter value used in defining vulnerability curve beta: ditto Returns: weibull_min.cdf(x, shape, loc=0, scale) Note: weibull_min.pdf...
4bb36643b483309e4a4256eb74bc3bbd7b447416
3,648,325
def _find_best_deals(analysis_json) -> tuple: """Finds the best deal out of the analysis""" best_deals = [] for deal in analysis_json: if _get_deal_value(analysis_json, deal) > MINIMUM_ConC_PERCENT: best_deals.append(deal) best_deals.sort(key=lambda x: _get_deal_value(analysis_jso...
5415f7104ec01a56249df9a142ff3c31b2964c42
3,648,326
def deserialize(s_transform): """ Convert a serialized :param s_transform: :return: """ if s_transform is None: return UnrealTransform() return UnrealTransform( location=s_transform['location'] if 'location' in s_transform else (0, 0, 0), rotation=s_transform['rotatio...
13daf861e84545d2f50b10617ece6d23976eacf0
3,648,327
def spectrum(x, times=None, null_hypothesis=None, counts=1, frequencies='auto', transform='dct', returnfrequencies=True): """ Generates a power spectrum from the input time-series data. Before converting to a power spectrum, x is rescaled as x - > (x - counts * null_hypothesis) / sqrt(co...
5a847f75eaa3fda0bc2906e14d56f7870da1edfa
3,648,328
def CalculatePercentIdentity(pair, gap_char="-"): """return number of idential and transitions/transversions substitutions in the alignment. """ transitions = ("AG", "GA", "CT", "TC") transversions = ("AT", "TA", "GT", "TG", "GC", "CG", "AC", "CA") nidentical = 0 naligned = 0 ndifferent...
84d67754d9f63eaee5a172425ffb8397c3b5a7ff
3,648,329
def render_ellipse(center_x, center_y, covariance_matrix, distance_square): """ Renders a Bokeh Ellipse object given the ellipse center point, covariance, and distance square :param center_x: x-coordinate of ellipse center :param center_y: y-coordinate of ellipse center :param covariance_matrix: Nu...
8f26a9a41a8f179f87925f0a931fbc81d2d8549b
3,648,330
def flow_to_image(flow): """Transfer flow map to image. Part of code forked from flownet. """ out = [] maxu = -999. maxv = -999. minu = 999. minv = 999. maxrad = -1 for i in range(flow.shape[0]): u = flow[i, :, :, 0] v = flow[i, :, :, 1] idxunknow = (abs(u...
301ef598b2e6aeda2e2f673854850faf0409e0e8
3,648,331
def joint_dataset(l1, l2): """ Create a joint dataset for two non-negative integer (boolean) arrays. Works best for integer arrays with values [0,N) and [0,M) respectively. This function will create an array with values [0,N*M), each value representing a possible combination of values from l1 and l...
6ba767739793f7c188d56e24e6e07d6e594c775e
3,648,332
import uuid def parse(asset, image_data, product): """ Parses the GEE metadata for ODC use. Args: asset (str): the asset ID of the product in the GEE catalog. image_data (dict): the image metadata to parse. product (datacube.model.DatasetType): the product information from the ODC ind...
815da17849b240a291332a695ca38374bb957d8a
3,648,333
def scale(pix, pixMax, floatMin, floatMax): """ scale takes in pix, the CURRENT pixel column (or row) pixMax, the total # of pixel columns floatMin, the min floating-point value floatMax, the max floating-point value scale returns the floating-point value that corresp...
455d0233cbeeafd53c30baa4584dbdac8502ef94
3,648,334
def most_distinct(df): """ :param df: data frame :return: """ headers = df.columns.values dist_list = [] # list of distinct values per list for idx, col_name in enumerate(headers): col = df[col_name] col_list = col.tolist() # if len(col_list) == 0: # dist...
f21ba5ffd2bfcf5262ffbbe30f24a77522a10bb0
3,648,335
def make_set(value): """ Takes a value and turns it into a set !!!! This is important because set(string) will parse a string to individual characters vs. adding the string as an element of the set i.e. x = 'setvalue' set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'} make_set(x) ...
c811729ea83dc1fbff7c76c8b596e26153aa68ee
3,648,336
def _get_parent_cache_dir_url(): """Get parent cache dir url from `petastorm.spark.converter.parentCacheDirUrl` We can only set the url config once. """ global _parent_cache_dir_url # pylint: disable=global-statement conf_url = _get_spark_session().conf \ .get(SparkDatasetConverter.PARENT_...
34abb96b64ab5338a6c9a5ef700a6fbb00f3905f
3,648,337
def make_variable(data, variances=None, **kwargs): """ Make a Variable with default dimensions from data while avoiding copies beyond what sc.Variable does. """ if isinstance(data, (list, tuple)): data = np.array(data) if variances is not None and isinstance(variances, (list, tuple)): ...
a712800df05c8c8f5f968a0fee6127919ae56d8f
3,648,338
def dt642epoch(dt64): """ Convert numpy.datetime64 array to epoch time (seconds since 1/1/1970 00:00:00) Parameters ---------- dt64 : numpy.datetime64 Single or array of datetime64 object(s) Returns ------- time : float Epoch time (seconds since 1/1/1970 00:00:00) ...
f7cdaf44312cb0564bf57393a5fde727bc24e566
3,648,339
def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits): """ Calculate the rpn loss for one FPN layer for a single image. The ground truth(GT) anchor labels and anchor boxes has been preprocessed to fit the dimensions of FPN feature map. The GT boxes are encoded from fast-rcnn paper ht...
00a554a536350c7d053ae3a4f776008a32f2d8a8
3,648,340
import math def calc_val_resize_value(input_image_size=(224, 224), resize_inv_factor=0.875): """ Calculate image resize value for validation subset. Parameters: ---------- input_image_size : tuple of 2 int Main script arguments. resize_inv_factor : float ...
5a8bcb77d849e62ef5ecfad74f5a3470ab4cfe59
3,648,341
import requests def fetch_http(url, location): """ Return a `Response` object built from fetching the content at a HTTP/HTTPS based `url` URL string saving the content in a file at `location` """ r = requests.get(url) with open(location, 'wb') as f: f.write(r.content) content_t...
b1229bec9c09528f5fb9dcdd14ee2cc6678410c4
3,648,342
def mat_normalize(mx): """Normalize sparse matrix""" rowsum = np.array(mx.sum(1)) r_inv = np.power(rowsum, -0.5).flatten() r_inv[np.isinf(r_inv)] = 0. r_mat_inv = sp.diags(r_inv) mx = r_mat_inv.dot(mx).dot(r_mat_inv) return mx
9caeaf660e7a11b7db558248deb3097e9cca2f57
3,648,343
from datetime import datetime import os import logging import tqdm def runjcast(args): """ main look for jcast flow. :param args: parsed arguments :return: """ # Get timestamp for out files now = datetime.datetime.now() write_dir = os.path.join(args.out, 'jcast_' + now.strftime('%Y%...
ed6c35818159e297c4adbc75907da10e79219524
3,648,344
def user_syntax_error(e, source_code): """Returns a representation of the syntax error for human consumption. This is only meant for small user-provided strings. For input files, prefer the regular Python format. Args: e: The SyntaxError object. source_code: The source code. Returns: A multi-li...
79272de37844b043656a98d796913769e89ebb17
3,648,345
import re def check_comment(comment, changed): """ Check the commit comment and return True if the comment is acceptable and False if it is not.""" sections = re.match(COMMIT_PATTERN, comment) if sections is None: print(f"The comment \"{comment}\" is not in the recognised format.") else: ...
6ad96bb465e2079895ad87d35b4bc7a000312eaf
3,648,346
def GetBankTaskSummary(bank_task): """ Summarizes the bank task params: bank_task = value of the object of type bank_task_t returns: String with summary of the type. """ format_str = "{0: <#020x} {1: <16d} {2: <#020x} {3: <16d} {4: <16d} {5: <16d} {6: <16d} {7: <16d}" out_string = forma...
afbc3b4e8707428dc951d5d199441923e477ac0c
3,648,347
def angle(o1,o2): """ Find the angles between two DICOM orientation vectors """ o1 = np.array(o1) o2 = np.array(o2) o1a = o1[0:3] o1b = o1[3:6] o2a = o2[0:3] o2b = o2[3:6] norm_a = np.linalg.norm(o1a) * np.linalg.norm(o2a) norm_b = np.linalg.norm(o1b) * np.linalg.norm...
db6211f4067339b7740eb52cc3f101f6ef69f08c
3,648,348
def get_project_id_v3(user_section='user'): """Returns a project ID.""" r = authenticate_v3_config(user_section, scoped=True) return r.json()["token"]["project"]["id"]
7cbb004609e3623d6a5d4bbf45766ea753027f5c
3,648,349
def get_platform_arches(pkgs_info, pkg_name): """.""" package_info = get_package_info(pkgs_info, pkg_name) platforms_info = package_info.get('platforms', {}) platform_arches = platforms_info.get('arches', []) return platform_arches
d6da2a95592f1ecf1e89935dfecef84fe2ee9313
3,648,350
import glob import os def get_preview_images_by_proposal(proposal): """Return a list of preview images available in the filesystem for the given ``proposal``. Parameters ---------- proposal : str The five-digit proposal number (e.g. ``88600``). Returns ------- preview_images ...
e0e952d745899272152824b05a594342bc25ea30
3,648,351
from typing import Optional def unformat_number(new_str: str, old_str: Optional[str], type_: str) -> str: """Undoes some of the locale formatting to ensure float(x) works.""" ret_ = new_str if old_str is not None: if type_ in ("int", "uint"): new_str = new_str.replace(",", "") ...
419698cf46c1f6d3620dbb8c6178f0ba387ef360
3,648,352
import os def mkdirs(path, raise_path_exits=False): """Create a dir leaf""" if not os.path.exists(path): os.makedirs(path) else: if raise_path_exits: raise ValueError('Path %s has exitsted.' % path) return path
d2491589f2ee9d9aa9b9ceeb5ae8d0f678fc5473
3,648,353
def is_triplet(tiles): """ Checks if the tiles form a triplet. """ return len(tiles) == 3 and are_all_equal(tiles)
a0223a0fde80c147de7e255db0a5563424d1a427
3,648,354
def cli(ctx, comment, metadata=""): """Add a canned comment Output: A dictionnary containing canned comment description """ return ctx.gi.cannedcomments.add_comment(comment, metadata=metadata)
bacfab650aac1a1785a61756a7cbf84aab7df77a
3,648,355
def get_latest_slot_for_resources(latest, task, schedule_set): """ Finds the latest opportunity that a task may be executed :param latest: type int A maximum bound on the latest point where a task may be executed :param task: type DAGSubTask The task to obtain the latest starting slot fo...
455f852152877c856d49882facabdd6faabad175
3,648,356
import requests def _get_text(url: str): """ Get the text from a message url Args: url: rest call URL Returns: response: Request response """ response = requests.get(url["messageUrl"].split("?")[0]) return response
fe711167748ca6b0201da7501f3b38cc8af8651d
3,648,357
def divideFacet(aFacet): """Will always return four facets, given one, rectangle or triangle.""" # Important: For all facets, first vertex built is always the most south-then-west, going counter-clockwise thereafter. if len(aFacet) == 5: # This is a triangle facet. orient = aFacet[4] #...
2e5891cb0ab7d23746ca18201be0f7360acc76b4
3,648,358
def compute_g(n): """g_k from DLMF 5.11.3/5.11.5""" a = compute_a(2*n) g = [] for k in range(n): g.append(mp.sqrt(2)*mp.rf(0.5, k)*a[2*k]) return g
86aeb38e4ecec67f539586b0a96aa95b396d0639
3,648,359
import sys def initialize_hs(IMAG_counter): """Initialize the HiSeq and return the handle.""" global n_errors experiment = config['experiment'] method = experiment['method'] method = config[method] if n_errors is 0: if not userYN('Initialize HiSeq'): sys.exit() ...
053fca1b93dad6c0d00a8e07a914f0fdde8df134
3,648,360
import argparse def print_toc() -> int: """ Entry point for `libro print-toc` The meat of this function is broken out into the generate_toc.py module for readability and maintainability. """ parser = argparse.ArgumentParser(description="Build a table of contents for an SE source directory and print to stdout....
e4334e24b9cb886a83f43a20ec3ecc561387b5c0
3,648,361
def get_colden(theta_xy, theta_xz, theta_yz, n_sample_factor=1.0, directory=None, file_name='save.npy', quick=False, gridrate=0.5, shift=[0, 0, 0], draw=False, save=False, verbose=False): """ Rotate gas into arbitrary direction """ if gridrate < 2**(-7): boxsize...
bb19845492adfde70c85f3a8faf64784130ab7b9
3,648,362
def PyException_GetCause(space, w_exc): """Return the cause (another exception instance set by raise ... from ...) associated with the exception as a new reference, as accessible from Python through __cause__. If there is no cause associated, this returns NULL.""" w_cause = space.getattr(w_exc, spa...
dce5c1df12af7074ce25387e493ccac1aaac27ec
3,648,363
import os def _get_style_data(stylesheet_file_path=None): """Read the global stylesheet file and provide the style data as a str. Args: stylesheet_file_path (str) : The path to the global stylesheet. Returns: str : The style data read from the stylesheet file """ global __style_d...
cf72309b07124620c1116efea4334aeae2e7b308
3,648,364
def row_interval(rows: int) -> Expression: """ Creates an interval of rows. Example: :: >>> tab.window(Over >>> .partition_by(col('a')) >>> .order_by(col('proctime')) >>> .preceding(row_interval(4)) >>> .following(CURRENT_ROW) ...
eaa998eb3498eeed8034d43efb89eaa3cbaa5b2b
3,648,365
from typing import Any def build_post_async_retry_failed_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest: """Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Az...
867cf51bec949367ce2722ca16d35462947623f3
3,648,366
def splitclass(classofdevice): """ Splits the given class of device to return a 3-item tuple with the major service class, major device class and minor device class values. These values indicate the device's major services and the type of the device (e.g. mobile phone, laptop, etc.). If you google ...
37c19ab17293b4fd0c46cff24c30e349459f7bd0
3,648,367
def change_to_local_price(us_fee): """Get us dollar change price from redis and apply it on us_fee. """ dollar_change = RedisClient.get('dollar_change') if not dollar_change: raise ValueError(ERRORS['CHANGE_PRICE']) Rial_fee = float(us_fee) * int(dollar_change) return int(Rial_fee)
bdd89a461e84a6acb6f49f2fb0159a9fa7404b17
3,648,368
def get_positive(data_frame, column_name): """ Query given data frame for positive values, including zero :param data_frame: Pandas data frame to query :param column_name: column name to filter values by :return: DataFrame view """ return data_frame.query(f'{column_name} >= 0')
2aec7f611a1b181132f55f2f3ca73bf5025f2474
3,648,369
def axes(*args, **kwargs): """ Add an axes to the figure. The axes is added at position *rect* specified by: - ``axes()`` by itself creates a default full ``subplot(111)`` window axis. - ``axes(rect, axisbg='w')`` where *rect* = [left, bottom, width, height] in normalized (0, 1) units. *ax...
1277afb8b3a6513129632216d8c3a6c2b5718449
3,648,370
def scrape_options_into_new_groups(source_groups, assignments): """Puts options from the :py:class:`OptionParser` and :py:class:`OptionGroup` objects in `source_groups` into the keys of `assignments` according to the values of `assignments`. An example: :type source_groups: list of :py:class:`OptionPar...
4524a975b604a146814c9c913d3727e0bd296368
3,648,371
def resnext56_32x2d_cifar10(classes=10, **kwargs): """ ResNeXt-56 (32x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431. Parameters: ---------- classes : int, default 10 Number of classification classes. pretr...
110b9b4443d4761b7f89a3d01b28d2c4ec8eba00
3,648,372
import argparse def _get_server_argparser(): """ Create a :class:`argparse.ArgumentParser` with standard configuration options that cli subcommands which communicate with a server require, e.g., hostname and credential information. :return: the argparser :rtype: argparse.ArgumentParser ""...
0e9300600640e622cd26ba76145f33ca682e6e4c
3,648,373
def is_internet_file(url): """Return if url starts with http://, https://, or ftp://. Args: url (str): URL of the link """ return ( url.startswith("http://") or url.startswith("https://") or url.startswith("ftp://") )
00f9d90d580da3fe8f6cbc3604be61153b17a154
3,648,374
from .observable.zip import zip_ from typing import Any from typing import Tuple def zip(*args: Observable[Any]) -> Observable[Tuple[Any, ...]]: """Merges the specified observable sequences into one observable sequence by creating a :class:`tuple` whenever all of the observable sequences have produced an ...
c33915df586bb2c337d7fee275d4df30364cd704
3,648,375
def GetFilter(image_ref, holder): """Get the filter of occurrences request for container analysis API.""" filters = [ # Display only packages 'kind = "PACKAGE_MANAGER"', # Display only compute metadata 'has_prefix(resource_url,"https://www.googleapis.com/compute/")', ] client = holder.cl...
276104cab3c9348151437548ecd69801f20e5363
3,648,376
def predict_image_paths(image_paths, model_path, target_size=(128, 128)): """Use a trained classifier to predict the class probabilities of a list of images Returns most likely class and its probability :param image_paths: list of path(s) to the image(s) :param model_path: path to the pre-trained model...
8071a178751ce25edbf664f1a69d1dd43b3e6290
3,648,377
def in_bounding_box(point): """Determine whether a point is in our downtown bounding box""" lng, lat = point in_lng_bounds = DOWNTOWN_BOUNDING_BOX[0] <= lng <= DOWNTOWN_BOUNDING_BOX[2] in_lat_bounds = DOWNTOWN_BOUNDING_BOX[1] <= lat <= DOWNTOWN_BOUNDING_BOX[3] return in_lng_bounds and in_lat_bounds
c4756c10bc45b81850f0e998be7bf420e355aa4d
3,648,378
def __DataContainerERT_addFourPointData(self, *args, **kwargs): """Add a new data point to the end of the dataContainer. Add a new 4 point measurement to the end of the dataContainer and increase the data size by one. The index of the new data point is returned. Parameters ---------- ...
11d42774e3e422aaa9a8fe664e5e4641b51248d4
3,648,379
import traceback def spin_up(work_func, cfgs, max_workers = 8, log=None, single_thread=False, pass_n=True): """ Run a threadable function (typically a subprocess) in parallel. Parameters ---------- work_func : callable This does the work. It gets called with one or two arguments. The first argument in alw...
0c88376f0d892c32749a2a2eac3aa2ab4d0e3863
3,648,380
import os import logging def list_run_directories(solid_run_dir): """Return list of matching run directories Given the name of a SOLiD run directory, find all the 'matching' run directories based on the instrument name and date stamp. For example, 'solid0127_20120123_FRAG_BC' and 'solid0127_2012...
9306baf2ca913d18a9fba1f90491ead3d4d5cc36
3,648,381
def refresh_remote_vpsa(session, rvpsa_id, return_type=None, **kwargs): """ Refreshes information about a remote VPSA - such as discovering new pools and updating how much free space remote pools have. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. ...
6acc4a049397862c72a21deb8e38f65af5c424a7
3,648,382
def zeros(shape, int32=False): """Return a blob of all zeros of the given shape with the correct float or int data type. """ return np.zeros(shape, dtype=np.int32 if int32 else np.float32)
68bb2960a3a364f01b8fcc39495e44562936c98f
3,648,383
def _connect(): """Connect to a XMPP server and return the connection. Returns ------- xmpp.Client A xmpp client authenticated to a XMPP server. """ jid = xmpp.protocol.JID(settings.XMPP_PRIVATE_ADMIN_JID) client = xmpp.Client(server=jid.getDomain(), port=settings.XMPP_PRIVATE_SERV...
1d407d80c22a371205c85e9223164cfa01063781
3,648,384
def index(): """Return the main page.""" return send_from_directory("static", "index.html")
2dbbf0d103e78bcd503f8254aac7f8a1a45f9176
3,648,385
from typing import List def get_groups(records_data: dict, default_group: str) -> List: """ Returns the specified groups in the SQS Message """ groups = records_data["Groups"] try: if len(groups) > 0: return groups else: return [default_group] except...
29ffe05da86816750b59bab03041d8bf43ca8961
3,648,386
def build_stats(history, eval_output, time_callback): """Normalizes and returns dictionary of stats. Args: history: Results of the training step. Supports both categorical_accuracy and sparse_categorical_accuracy. eval_output: Output of the eval step. Assumes first value is eval_loss and second...
3419bcc0b2441fd2ea67ddec0b50574017b71a75
3,648,387
def truncate_single_leafs(nd): """ >>> truncate_single_leafs(node(name='a', subs=[node(name='a', subs=None, layer='a')], layer=None)) node(name='a', subs=None, layer='a') """ if nd.layer: return nd if nd.subs and len(nd.subs) == 1: if nd.subs[0].layer: return node(nd....
46e837dbd84df3c2cad5c5597d56f3ba716146f8
3,648,388
def postprocess_output(output, example, postprocessor): """Applies postprocessing function on a translation output.""" # Send all parts to the postprocessing. if postprocessor is None: text = output.output[0] score = None align = None else: tgt_tokens = output.output ...
57c30c1cf9178ae28ef97c8662ed2fe6559f5dd6
3,648,389
def get_aqua_timestamp(iyear,ichunk,branch_flag): """ outputs a timestamp string for model runs with a predifined year-month-day timestamp split into 5 x 73 day chunks for a given year """ if branch_flag == 0: if ichunk == 0: timestamp = format(iyear,"04") + '-01-01-00000' ...
7566da7f22ee31e7e17a86a908bb510c176d32ea
3,648,390
def aggregate_native(gradients, f, m=None, **kwargs): """ Multi-Krum rule. Args: gradients Non-empty list of gradients to aggregate f Number of Byzantine gradients to tolerate m Optional number of averaged gradients for Multi-Krum ... Ignored keyword-arguments Returns: Ag...
6a0b6309c9296587f581d8d941896643e096a3d5
3,648,391
import types def isNormalTmpVar(vName: types.VarNameT) -> bool: """Is it a normal tmp var""" if NORMAL_TMPVAR_REGEX.fullmatch(vName): return True return False
4ca52c849f913d15ede4c3ed4d4888d68ca5cd8b
3,648,392
import os import stat import pickle def dump_obj(obj, path): """Dump object to file.""" file_name = hex(id(obj)) file_path = path + file_name with open(file_path, 'wb') as f: os.chmod(file_path, stat.S_IWUSR | stat.S_IRUSR) pickle.dump(obj, f) return file_name
d392ffa14e5eb8965ba84e353427358219c9eacc
3,648,393
import time def count_time(start): """ :param start: :return: return the time in seconds """ end = time.time() return end-start
1945f6e6972b47d7bbdb6941ee7d80b8a6eedd9a
3,648,394
def split_by_state(xs, ys, states): """ Splits the results get_frame_per_second into a list of continuos line segments, divided by state. This is to plot multiple line segments with different color for each segment. """ res = [] last_state = None for x, y, s in zip(xs, ys, states): ...
0a872617bd935f7c52ee0d10e759674969a19c4e
3,648,395
def final_spectrum(t, age, LT, B, EMAX, R, V, dens, dist, Tfir, Ufir, Tnir, Unir, binss, tmin, ebreak, alpha1, alpha2): """ GAMERA computation of the particle spectrum (for the extraction of the photon sed at the end of the evolution of the PWN) http://libgamera.github.io/GAMERA/docs/time_de...
00ce850d759739ffcb69a5af5c62325b39bd5446
3,648,396
def modal(): """Contributions input controller for modal view. request.vars.book_id: id of book, optional request.vars.creator_id: id of creator, optional if request.vars.book_id is provided, a contribution to a book is presumed. if request.vars.creator_id is provided, a contribution to a creator ...
13222d8e4d611fe0005f3df3db05f10c6c9fb057
3,648,397
def returns(data): """Returns for any number of days""" try: trading_days = len(data) logger.info( "Calculating Returns for {} trading days".format(trading_days)) df = pd.DataFrame() df['daily_returns'] = data.pct_change(1) mean_daily_returns = df['daily_retur...
c533433e23cb2f246cdb3f3d8f445afc9d0ea0bc
3,648,398
def do_rot13_on_input(input_string, ordered_radix=ordered_rot13_radix): """ Perform a rot13 encryption on the provided message. """ encrypted_message = str() for char in input_string: # Two possibilities: in radix, or NOT in radix. if char in ordered_radix: # must find inde...
ccf37364860a661498290245a408d7cc4edbf896
3,648,399