content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def apply_patch(doc, patch, in_place=False): """Apply list of patches to specified json document. :param doc: Document object. :type doc: dict :param patch: JSON patch as list of dicts or raw JSON-encoded string. :type patch: list or str :param in_place: While :const:`True` patch will modify ...
e9a9149b98a79d04627d2bdf133b0190ddc6b936
3,616,400
def _gt_mapping(D, W, Z): """Computes the mapping B(X) for a Guttman transform V X = B(X) Z.""" # Compute the Euclidean distances between all pairs of points Dz = distance.cdist(Z, Z) # Fill the diagonal of Dz, because *we don't want a division by zero* np.fill_diagonal(Dz, 1e-5) B = - W * D / ...
a47916098ffaccf8e1dddc8ee7a363791bb574c9
3,616,401
def schema(_request): """API schema""" return JSONResponse({ '/': 'api root' })
69dbc1e53acbca5ebb3491bc33186ef04973666f
3,616,402
def cvar_historic(r, level =5): """ Computes the Conditional VaR of series or Dataframe """ if isinstance(r, pd.Series): is_beyond = r <= -var_historic(r, level = level) return -r[is_beyond].mean() elif isinstance(r, pd.DataFrame): return r.aggregate(cvar_historic, level=leve...
b11e37867b121c57cbf983d586709dfcf14e1b5a
3,616,403
def excepting(selector, handler_fn): """ Selector is not necessarily just an `Exception` subclass. Potentially it can be an id for any purpose, not just exception handling. It also can be an iterable of these things to register general handlers. """ def decorator(task): task_meta =...
e868b46e41844b8c41223100bd212dc5e49a3496
3,616,404
import os import pickle import warnings def load_data(name, path=None): """ Load data using either pickle or numpy's load function. Parameters ---------- name: str Name of file to load. path: None, str or list(str), optional (default=None) Absolute path or subfolder hierarchy ...
388307b9bc9726aaf2f485586ddab7266c6f218d
3,616,405
def add_check_theta_generator(measure): """ This is a decorator to add a ValueError to a function if theta is not in the proper interval. """ include_0 = True include_1 = True measure = measure.upper() # Should 0 be included if measure in select_names(['PPV', 'FDR', 'MCC', 'MK', 'FM']): ...
c39ba359c3b3c1a7cea86752720e2376f6b99fd9
3,616,406
def get_function_id(functions_client: functions.FunctionsManagementClient, app_id: str, function_name: str) -> str: """ Identifies function ID by its name :param functions_client: OCI Functions client :param app_id: OCI Functions app ID :param function_name: OCI Functions functio...
7e735035d24f89041516706a6e37a2228cbb9e12
3,616,407
def init_graphic_environment(screen_width=background_width, screen_height=background_height): """ Initialize the graphic environment. :param screen_width: width of the screen. :param screen_height: height of the screen. :return: the screen, the backgrounds and the font. """ pygame.init() ...
035c9a690c9945ea36be88a0c56915e6a60054c6
3,616,408
def ma(method, series, ma_period): """MA均线,直接调用pandas_ma的均线方法""" return ta.ma(method, series, length=ma_period, min_periods=1)
43f03b3c73902cb748b77e087ec2d7bceeb5884a
3,616,409
def resnet152(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ encoder = ResNetEncoder(Bottleneck, [3, 8, 36, 3]) if pretrained: encoder.load_state_dict(model_zoo.load_url(model_u...
0b66fcfa39a73667674c7fbb4e8e086329c1f996
3,616,410
def request_server_option(): """ Is used to request the option and prints it. Returns ------- option: int The option that has to be returned """ colors = decorators.Colors() option = 0 try: option = int(input(f"{colors.OK}Select what do you want to do: {colors.ENDC}"...
f58d432f49ee82ce60a08c49586a281c3be0e0a8
3,616,411
from typing import List from typing import Union async def get_all_actors( details: bool = False, sw: ServiceWorker = Depends(get_sw) ) -> GenResponse[List[Union[ActorSimpleOut, ActorBase]]]: """ Retrieve all actors. Choice between 2 response types. With details or not (default: false). **Without...
c60dc5d73f8d4ee1064a9fe40e1e70553bbdc39e
3,616,412
def getRectangles(conn, image): """ Returns a list of (x, y, width, height, zStart, zStop, tStart, tStop) of each rectangle ROI in the image """ rois = [] roiService = conn.getRoiService() result = roiService.findByImage(image.id, None) for roi in result.rois: x = None ...
d5f41fc93172bbb8e206391da075c842a3fb9d73
3,616,413
import re import os def _parse_rptfiles_from_log(log_filename): """Parses Red stdout log and returns a list with the names of output files with repeat coordinates""" rpt_files = [] try: logfile = open(log_filename) except OSError as error: print("# ERROR: cannot open/read file:",...
4607ba7005dfacf747f8dfe36b520737092d1747
3,616,414
def IRONMAN_user(user): """helper to determine if user is associated with the IRONMAN org""" # NB - not all systems have this organization! iron_org = Organization.query.filter_by(name='IRONMAN').first() if iron_org: OT = OrgTree() for org_id in (o.id for o in user.organizations if o.id)...
1009247a970d582fc2afcdf0d6e2948dc16b11af
3,616,415
def parse_date(text): """ Attempts to parse date from text. Returns None on failure. """ result = dateparser.parse(text.strip()) if (result is not None) and hasattr(result,'date'): return result.date() else: print("Could not parse %s as date. Returning None."%text) return
43905651b3dacac1ee8d49f6f6134f1e77a40180
3,616,416
def train_model(lrmodel, X, Y, devX, devY, devscores, verbose=0, epochs=100): """ Train model, using pearsonr on dev for early stopping """ done = False best = -1.0 r = np.arange(1,6) while not done: # Every 300 epochs, check Pearson on development set lrmodel.fit(X, Y, ...
01211bcdf1c472e96261485b110c5d43da77cd39
3,616,417
from datetime import datetime def _get_current_time(): """Gets the current timestamp.""" return datetime.datetime.now()
25ddd78e4cbd11cde826a9bb62a27afd3781ab22
3,616,418
def controller_put(id): """ Thing Manager Data Handler for PUT requests # Use type to know the serialization """ # Get the elements of the request service = Service(request, id) # Call processRDF service.put() return 'put'
653c586f7ccaa7334798cc3b50444b6955615c0a
3,616,419
import torch import math def positionalencoding2d(pos_embed_dim, height, width): """ :param pos_embed_dim: dimension of the model embeddings :param height: height of the positions :param width: width of the positions :return: height * width * pos_embed_dim matrix """ if pos_embed_dim % 4 !...
685396742b965df3b409203656707f1868e30c45
3,616,420
import os def gen_homedir(username, usertype): """Construct a user's home directory path given username and usertype.""" if usertype in ('member', 'associat'): letter = username[0] + os.sep else: letter = '' return '%s/%s/%s%s' % (dir_home, usertype, letter, username)
a557d2b6ffbc83805a21fc3ab8b6b2dd21b9b192
3,616,421
def test_get_header(): """ Test of the get header function of the DataTable Class """ test_dictionary={'Data_Description':{'x':'X Distance in microns.', 'y':'y Distance in microns.','Notes':'This data is fake'},'Data':[[1,2],[2,3]]} new_table=DataTable(**{'data_dictionary':test_dictionary}) header=n...
e15947852c40cec53ce391609fc9453a9fc95e32
3,616,422
import math def sorted_list_to_BST(head: ListNode) -> TreeNode: """ - can have an empty head Assumptions: - values of the linked list are integers Input: head = ListNode(-10) list = [-10,-3, 0, 5, 9] ^ ^ ^ ^ Intuition: - recursively s...
32c95106b34ba40c856b4a27b714481a75f85a17
3,616,423
def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv1d: """3x3 convolution with padding""" return nn.Conv1d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
a301bf80a297e47c5eedc573322f85a84d1aa7ba
3,616,424
def short_desc(event, words=25, strip_html=False): """Takes an event object and returns a shortened description.""" if event.short_description: description = event.short_description else: description = event.description if strip_html: description = unhtml(description) return ...
9dba787cdb0a481a16df1d4e249b741638fdc138
3,616,425
def ja_to_arabic(s: str, enable_validation: bool = True, accept_daiji: bool = True) -> int: """convert japanese number to arabic number Args: s (str): number in japanese format enable_validation (bool, optional): Whether to enable validation or not. Defaults to True. accept_daiji (bool,...
0c27192380f9dc02bae486025b981935b7be67ff
3,616,426
import random def shades_of_jop(): """Return a pretty colour.""" c1 = random.randint(127, 255) c2 = random.randint(0, 127) c3 = random.randint(0, 255) return tuple(random.sample([c1, c2, c3], 3))
366bc5bada332b6de3561d6c906a1880119b02f2
3,616,427
def check(func=None, *, dt='', n=0): """ A Decorator function that checks if the arguments are of the correct type an the right amount n: --> number of arguments dt: --> Data types of the arguments """ if func is None: return partial(check, dt=dt, n=n) @wraps(func) def check...
a84932645783c20f04db69ae3b721ff9e4eac801
3,616,428
def sigmoid(z): """The sigmoid function.""" return 1.0/(1.0+np.exp(-z))
ebded90a57df53dd51edc4a7ba079824ec5c14ea
3,616,429
import json import io import base64 def lambda_handler(event, context): """Sample pure Lambda function Parameters ---------- event: dict, required API Gateway Lambda Proxy Input Format Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integra...
60557aecdda4bb4eab6c23ab327b32653b37b982
3,616,430
def _final_frame_length(header, final_frame_bytes): """Calculates the length of a final ciphertext frame, given a complete header and the number of bytes of ciphertext in the final frame. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param ...
b7029e3b705194ee7daa02b4400d124ffe6efc2a
3,616,431
def real2complex(input_data): """ Parameters ---------- input_data : row x col x 2 Returns ------- output : row x col """ return input_data[..., 0] + 1j * input_data[..., 1]
9e359903f9653e8ea799a2baedcc9c274471f34f
3,616,432
from typing import cast from typing import Dict from typing import List def get_metrics( resource: celtypes.MapType, request: celtypes.MapType ) -> celtypes.Value: """ Reach into C7N and make a statistics request using the current C7N filter. This builds a request object that is passed through to AWS...
171595c3dd25cfc581ec4c77caa9bfd10bd88f2d
3,616,433
from typing import Dict def dy_static_file_server_dynamic_sidecar_service( docker_registry: str, node_meta_schema: Dict ) -> Dict[str, str]: """ Adds the below service in docker registry itisfoundation/dy-static-file-server-dynamic-sidecar """ return _pull_push_service( "itisfoundation...
867353e7a7ecd266a4017a6bae1e171aeba36ee2
3,616,434
def check_is_paired(df, subject, group): """ Check if samples are paired. :param df: pandas dataframe with samples as rows and protein identifiers as columns (with additional columns 'group', 'sample' and 'subject'). :param str subject: column with subject identifiers :param str group: column with ...
38f9b0722e77edb88ff44a7bc73eb24a8f1aa097
3,616,435
def norm_mac(mac): """Normalize a MAC Address from the pypowervm format to the neutron format. That means that the format will be converted to lower case and will have colons added. :param mac: A pypowervm mac address. E.g. 1234567890AB :returns: A mac that matches the standard neutron format. ...
b316d6bb6d72036955e01dab77860eef59b65a8f
3,616,436
from scipy.stats import f as F from scipy.special import gamma def hyperellipsoid(P, y=None, z=None, pvalue=.95, units=None, show=True, ax=None): """ Prediction hyperellipsoid for multivariate data. The hyperellipsoid is a prediction interval for a sample of a multivariate random variable and is such...
ca3b2bceb2d30b5ba9c48d9fe625bd09a9bd3f7b
3,616,437
import igl import scipy def get_mesh_laplacian_matrix_igl(mesh, fix_boundaries=True): """ Gets the laplace operator of the mesh Parameters ---------- mesh: :class: 'compas.datastructures.Mesh' fix_boundaries: bool Returns ---------- :class: 'scipy.sparse.csr_matrix' spars...
7783c52e773c6d54975fe66c72078334a245b6fb
3,616,438
import torch def qsgd_compress(t, pnorm="inf", quan_bits=8): """ Quantize float32 into uint8 using QSGD algorithm. Arguments: * `t` - Input PyTorch CUDA Tensor to be quantized. * `pnorm` - Order of norm used for QSGD compression. Default value is `inf`. * `quan_bits` - Number of q...
2ca1e5bd15b9bed4d8fbb4466f8d87a363e7e4a6
3,616,439
from sys import path def img_path(img): """ Get absolute path to img resource, works for dev and for PyInstaller """ return path.join(resource_path('img'), img)
6d64c56010706482465cfbbcd22bacb096bb1904
3,616,440
def permission_denied(request, exception, *args, **kwargs): """ Catch all 403 - Forbidden/Permission Denied """ return HttpResponseForbidden(**exception_response(request, 400, exception))
611cdfdb4316d0e7c46230f417f92ab8134d223a
3,616,441
import os def generate_io_files(gtc_paths, output_vcf_path, manifest_file): """ Generate input/output files for processing Args: gtc_paths (list(string)) : List of GTC files to process, may be None output_vcf_path (string) : Path to host output VCF files manifest_file (string) : P...
87847c8f81b91600eadb0e5a0fb78d91788c885a
3,616,442
import rospkg.os_detect def get_host_os(): """Determines the name of the host operating system""" os_detector = rospkg.os_detect.OsDetect() return (os_detector.detect_os())[0]
54ba91395ab1871168f353fff8a2560cc22a1138
3,616,443
def ascii(object: object) -> str: """ascii.""" return repr(object)
44dc1a77ebd46215aa25a2fea91f9c7c41bd4e7a
3,616,444
def perc(tags): """This function returns the ratio of the total of tags in repository Args: tags (List): Tags that are in the repository Returns: sum_of_perc*100 [float]: """ sum_of_perc=0 for tag in tags: # print(tag) if tag in store_tag: sum_...
4b95ddb96fd02243111f6865b00abb5ecdffeb83
3,616,445
def encode_labelmap(colour_img, colourlabelmap): """ Takes a colour image, where each colour represents one specific label-class and replaces the colour value with label ids. The mapping is defined by array `colourlabelmap`. """ colour_img = colour_img.astype(int) labels = np.zeros((colour_img.s...
10a7601391177161df44245d9f781b2a801d9421
3,616,446
def sol_rad_from_sun_hours(dl_hours, sun_hours, et_rad): """ Calculates incoming solar (or shortwave) radiation [MJ m-2 day-1] (radiation hitting a horizontal plane after scattering by the atmosphere) from relative sunshine duration based on FAO equations 34 and 35. If measured radiation data are no...
d10e6131e11262e493d4c1cfa1bedbfbb64644f2
3,616,447
def compute_corrected_dhf(mp_entry: ComputedEntry) -> float: """ Compute corrected :math:`\\Delta H_f(0K)` in ev/atom for a material in the Materials Project. We apply two corrections as follows: 1. Elemental contributions as used in the Materials Project. 2. For carbonates, we apply a correct...
eaa1a3d3f81dd9d7dcc930d3115cb259bf617c53
3,616,448
def tmux(ctx): """ Show some informantion in your tmux status. Output for tmux's status-right. As in, put this in ~/.tmux.conf:: set-option -g status-utf8 on set-option -g status-fg green set -g status-right '#(carml tmux)' set -g status-interval 2 """ cfg = ctx.obj...
5ab465bf11a0637e58c5ab80c71c97dda177b56e
3,616,449
def makefleetopts(): """ create option parser for events. """ parser = optparse.OptionParser(usage='usage: %prog [options] [list of bot names]', version=version) parser.add_option('', '--apiport', type='string', default=False, dest='apiport', help="port on which the api server will run") parser.add_opti...
f02a03827f122ad6342ca103839babdff45f3c37
3,616,450
import subprocess import sys import json def collect_clusteroperator_relatedobjects(): """ Returns a list of every namespace listed as a relatedObject by every clusterOperator. This captures managed namespaces that aren't defined in the OCP manifests. """ co_namespaces = [] try: result...
94324dbca3457d76f50d80020f560dad6f97798c
3,616,451
import threading import queue def InitSharedStorage(): """ Shared vars """ ''' All the methods in Python threading.events are atomic operations. https://docs.python.org/3/library/threading.html ''' SharedEvents = {} SharedEvents['update'] = threading.Event() SharedEvents['updat...
3a973ad7ef27cc0ed776f6e34b67f273b4884c9a
3,616,452
import json import os def fetch(): """Search the catalog using STAC format. Fetch a link from the catalog Args: query parameter: api_key, used to filter query results, must have READ:* or READ:[catalog] access to get results from that catalog. body parameters ...
9db519c2305d478f826f1f671f15b42ed582878a
3,616,453
from typing import List def translate_mav(wxdata: MavData, units: Units) -> List[MavPeriodTrans]: """Returns translations for a TafData object""" data = [] for line in wxdata.forecast: _data = _gfs_shared(line, units, MavPeriodTrans) return data
922621eaa4d27da73fca3eceb8f33e7d967322a0
3,616,454
from typing import Any def train_agent_fit_single_batch(args: Namespace, model: Agent, dataloaders: dict, opt: Optimizer, scheduler: _LRScheduler, acc_to...
f9af92f54a1f5ad077a0aa07d7ffad2d84df9e37
3,616,455
def specific_heat(mat): """Calculate specifc heat""" cw = 4183 mr = mat['m_heat'] mw = mat['m_w'] Tr = mat['Tr'] Tw = mat['Tw'] Te = mat['Te'] return (mw * cw * (Te - Tw)) / (mr * (Tr - Te))
7d3fbe3f67b3df593c94c93ab7d8523242d17b46
3,616,456
def get_first_day(histories: pd.DataFrame) -> pd.Timestamp: """ get_first_day gets the first day of the histories DataFrame in a way that is robust to outliers - for some reason, a small number of user summaries are very far into the past or future """ return histories.day.nsmallest(50).iloc[-1]
ce4449a398a2ab16af73e4b8a4284c091bf717be
3,616,457
from typing import Optional from typing import Tuple import os import re from typing import cast def netlist_from_yaml( yaml: str, *, models: Optional[Models] = None, settings: Optional[Settings] = None, default_models=None, ) -> Tuple[Netlist, Models]: """Load a sax `Netlist` from yaml defini...
624724e354c3ac889a8eb3a4f3a45f7538920db6
3,616,458
def inner(A, B): """Inner product of matrix A with matrix B. Parameters ---------- A : ndarray First matrix of the inner product. B : ndarray Second matrix of the inner product. Returns ------- result : ndarray Result of the inner product. Examples ---...
e6be04a6b0babc5e8bbcbd5abf743891ba4f0437
3,616,459
import xml def _parse_series( study: xml.etree.ElementTree.Element, ) -> xml.etree.ElementTree.Element: """Get series xml element from study xml element.""" expected_length = 3 if len(study) == 7 else 4 return _check_xml(study[5], "series", expected_length)
57c0714625b8a80f07f497716f5b4ae51f5416e5
3,616,460
def insertion_sort(a: list[int], debug=False) -> list[int]: """ Time complexity: O(n^2) """ if debug: print("insertion sort") arr = a.copy() n = len(arr) for i in range(1, n): el = arr[i] j = i - 1 while j >= 0 and arr[j] > el: arr[j + 1] = arr[j]...
c52df29c21a661c19e58e34d9a6264338c9a4cdc
3,616,461
def tail_correction(r, V, r_switch): """Apply a tail correction to a potential making it go to zero smoothly. Parameters ---------- r : np.ndarray, shape=(n_points,), dtype=float The radius values at which the potential is given. V : np.ndarray, shape=r.shape, dtype=float The potent...
eab44a4218b3d72bdcfa737e2310c564b2fd4cca
3,616,462
def case_detail(request, pk): """ Retrieve, update, or delete an AssuranceCase, by primary key """ try: case = AssuranceCase.objects.get(pk=pk) except AssuranceCase.DoesNotExist: return HttpResponse(status=404) permissions = get_case_permissions(case, request.user) if not per...
36ec8c2ef9b597edac57c4473f5924ad896a1f1a
3,616,463
from bs4 import BeautifulSoup def wikitable(page): """ Exports a Wikipedia table parsed by BeautifulSoup. Deals with spanning: multirow and multicolumn should format as expected. """ mediawikiapi = MediaWikiAPI() page = mediawikiapi.page(page) soup = BeautifulSoup(page.html(), 'html.pars...
b2adae70064296194b5f3c88188474aff84b507d
3,616,464
def _flatten(suitable_for_isinstance): """ isinstance() can accept a bunch of really annoying different types: * a single type * a tuple of types * an arbitrary nested tree of tuples Return a flattened tuple of the given argument. """ types = set() if not isinstance(sui...
5ba63f39b2d22da78f5a362ce6821239714a9e6a
3,616,465
def attach_tasks(queryset, as_field="tasks_attr"): """Attach tasks as json column to each object of the queryset. :param queryset: A Django user stories queryset object. :param as_field: Attach tasks as an attribute with this name. :return: Queryset object with the additional `as_field` field. """...
02a7e189226f9fb5809d7b4d18f3055e5fbc5462
3,616,466
def create_padding_mask(seq): """ The padding mask is used in the Encoder and Decoder layers to mask padding tokens. """ seq = tf.cast(tf.math.equal(seq, 0), tf.float32) # add extra dimensions to add the padding to the attention logits. return seq[:, tf.newaxis, tf.newaxis, :]
c8a335388906b8ceae8e2766e889243ddbd3d9cb
3,616,467
def decode_text(s): """ Decodes a PDFDocEncoding string to Unicode. Adds py3 compatibility to pdfminer's version. """ if type(s) == bytes and s.startswith(b'\xfe\xff'): return str(s[2:], 'utf-16be', 'ignore') else: ords = (ord(c) if type(c) == str else c for c in s) retur...
a5107ae9a99a198ea648eec06b84c2094bd45af5
3,616,468
def create_schema(client): """The query which creates the schema Parameters - it uses variables rather than the fluent style as an example ========== client : a WOQLClient() connection """ base = WOQLQuery().doctype("EphemeralEntity", label="Ephemeral Entity", description="An entity...
276c06eeb33144fca6b1895553eb946662fdd3f6
3,616,469
def process_cpc_testdata(path, variable='pr', lead_option='weekly', day_init=15, day_end=21, region=None): """ Open and process the CPC data for 11 ensemble members for training. Args: path (str): directory path to data. variable (str): variable for analysis. lead_option (str): ...
95ccc78c9b6ed0b2cbeaaf06c2fe90faf6dc5d4d
3,616,470
import time from datetime import datetime def trimap( X, triplets, weights, knn_tuple, use_dist_matrix, n_dims, n_inliers, n_outliers, n_random, distance, lr, n_iters, Yinit, weight_temp, apply_pca, opt_method, verbose, return_seq, ): """Appl...
eb45637992dceef11f51dcf406d06558333e42d3
3,616,471
def qtdmri_isotropic_scaling(data, q, tau): """ Constructs design matrix for fitting an exponential to the diffusion time points. """ dataclip = np.clip(data, 1e-05, 1.) logE = -np.log(dataclip) logE_q = logE / (2 * np.pi ** 2) logE_tau = logE * 2 B_q = np.array([q * q]) inv_B_q = ...
ed896224a2cded0cd2683082d895ce935f8ab5c9
3,616,472
from typing import Dict from typing import Any from typing import Optional import tqdm def nested_cv_param_search( # pylint:disable=invalid-name X: np.ndarray, # noqa y: np.ndarray, param_dict: Dict[str, Any], pipeline: Pipeline, outer_cv: BaseCrossValidator, inner_cv: BaseCrossValidator, ...
7cf91749a5cd9c22fc38ed03cd569ff58c106ba2
3,616,473
import re def extract_positive_integer_value(text, key): """ Extract an integer value for a given key in a text Args: text (str): text to extract value from key (str): key to extract value for Raises: ValueError: value is not a positive integer Returns: int: extrace...
28242d3445cb94511070eca6934ad2985283d4b3
3,616,474
def delete_from_s3(s3_path: str) -> bool: """Delete a path from s3 Args: s3_path: Full path on s3 in format "s3://<bucket_name>/<obj_path>". Returns: Boolean of whether the delete was successful. """ bucket, key = decompose_s3_path(s3_path) s3_client = boto3.client("s3") tr...
35c54fcff723e01c5f555b77cb8804649af58369
3,616,475
import torch def resnet18_feat(pretrained=False, initpath=None, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet_feat(BasicBlock, [2, 2, 2, 2], deep_base=False, **kwargs) if pretrained and initpath is ...
9724abbe0e4d1a578866626e14712ebb8994cd78
3,616,476
import pandas from typing import List from typing import Any def keep_these_labels_only( dataframe: pandas.DataFrame, label_column: str, labels_to_keep: List[Any] ): """ Parameters ---------- dataframe: `pandas.DataFrame`, required The input dataframe label_column: ...
25c9b1b83f690e1ef9ba15cc8dbd22fe939633b0
3,616,477
def create_blocks(arr, block_size=(1024, 1024)): """Split input array into uniformly-sized blocks This function will split the input array into uniformly-sized blocks with the size of each block specified as `block_size`. The input array will be zero-padded in either or both axes in order to expand th...
cd1456b967e0473031f74dde16445199d51b45de
3,616,478
import string def PrintableString(s): """For pretty-printing in tests.""" if all(c in string.printable for c in s): return s return repr(s)
4f22a5ed8152039a21e045ea2e04b4cff3dbec85
3,616,479
def expected_regularization(): """Build the expected alive vectors applying the rules of concat and group.""" concat = REG_STUB['conv1'] + REG_STUB['conv2'] # Grouping: Activation is alive after grouping if one of the constituents is # alive. grouped = [max(a, b) for a, b in zip(concat, REG_STUB['conv4'])] ...
cd3ee30a482bbd57a3cd7802b680a6a997ed86b1
3,616,480
def trans_concat(*args): """Concat all parts of tag and translate it.""" return _(''.join(args))
9d66c7ea0a8d2b68837db570824a93ac993c66a5
3,616,481
import test_module import ray import os import sys def test_captured_import(start_cluster, tmp_working_dir, option: str): """Tests importing a module in the driver and capturing it in a task/actor. This tests both that this fails *without* the working_dir and that it passes with it. """ cluster, ...
4492cbc1f9764bc95ef86619005740b8947f3ea1
3,616,482
def mean_normalize_data(data: np.ndarray) -> np.ndarray: """ Mean normalization method. :param data: Data cube. :return: Normalized data. """ for band_id in range(data.shape[SPECTRAL_AXIS]): max_ = np.amax(data[..., band_id]) min_ = np.amin(data[..., band_id]) mean = np....
5c7a951a46fad9eb7178c4581a78fad50e7096eb
3,616,483
def make_intervals(b3, b4): """ Given the already parsed igs block 3 and 4 dictionaries (aka '3. GNSS Receiver Information' and '4. GNSS Antenna Information') as parsed from an IgsLogFile instance (see IgsLogFile::parse_block), concatenate the intervals based on changes either on the 3 or 4 bl...
474edeb9e3885ade5b645e039849a72e938c92e6
3,616,484
def discretize_kernel( kernel, sampling_rate, area_fraction=default_kernel_area_fraction, num_bins=None, ensure_unit_area=False): """ Discretizes a kernel. :param kernel: The kernel or kernel function. If a kernel function is used it should take exactly one 1-D array as argument. :t...
6eaad515117dbe3ea5b2835fc944419f73cf7219
3,616,485
import six def bitcast_to_bytes(s): """ Take a string and return a string(PY2) or a bytes(PY3) object. The returned object contains the exact same bytes as the input string. (latin1 <-> unicode transformation is an identity operation for the first 256 code points). """ return s if six.PY2 ...
b902550be03f447a286490653a2a1361257ac88c
3,616,486
import functools import signal def waiting_for(func=None, *, timeout=settings.DEFAULT_TIMEOUT): """ Set maximum execution time for a function :param func: function to decorate :param timeout: maximum allowed execution time :return: result of the func """ def _alarm_handler(signal_number,...
e2ab885369b013442d9003cc2936e19fb8814fcc
3,616,487
import numbers import logging def orthogonal_regularizer(scale, scope=None): """ Return a function that computes orthogonal regularization. :param scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. :param scope: An optional scope name. :return: A function with signature `orthogonal_sum...
fe2c7823232737bcc8dbc94c0b95c8b049e3ca16
3,616,488
import copy def tabq_learn(t, agent, env, env_state, history, args): """Learning loop for TabularQAgent""" step_type, reward, discount, state = env_state state = copy.deepcopy(state) # Act action = agent.act_explore(state) step_type, reward, discount, successor = env.step(action) # Learn...
baf1fcf9d5ab1aa80852b76df7f8756dd87d956d
3,616,489
from typing import Type from typing import Hashable def _lookup(key: str, typ: Type, *args, **kwargs) -> Hashable: """ Gets the value of the given key in args, defaulting to the first positional. :param key: key to find value of in args. :param typ: type that dispatch is being perform on. :param ...
195e95cd1d77137890d0608195677c344e698ad7
3,616,490
def MakeStatefulPolicyPreservedStateDiskEntry(messages, stateful_disk_dict): """Create StatefulPolicyPreservedState from a list of device names.""" disk_device = messages.StatefulPolicyPreservedStateDiskDevice() if stateful_disk_dict.get('auto-delete'): disk_device.autoDelete = ( stateful_disk_dict.ge...
10b1fcb79b46455bef8bbfba90c84bcdb80773df
3,616,491
import os def new_name(location, is_dir=False): """ Return a new non-existing location from a `location` usable to write a file or create directory without overwriting existing files or directories in the same parent directory, ignoring the case of the filename. The case of the filename is ignore...
0fd0a33a73037997cf56bee878558859ade8dae2
3,616,492
def _doc(from_func): """copy doc from one function to another use as a decorator eg:: @_doc(file.tell) def tell(..): ... """ def decorator(to_func): to_func.__doc__ = from_func.__doc__ return to_func return decorator
907a12da3700cee02e4f369d5230bd8be04e55ea
3,616,493
async def get_prometheus_rules(ops_test: OpsTest, app_name: str, unit_num: int) -> list: """Fetch all Prometheus rules. Args: ops_test: pytest-operator plugin app_name: string name of Prometheus application unit_num: integer number of a Prometheus juju unit Returns: a list ...
c716c0d8293f5153e27ff7836c10e33a89e7d7bc
3,616,494
import torch def get_loss_func(config, device, logger, ewc_loss=False): """Get a function handle that can be used as task loss function. Note, this function makes use of function :func:`sequential.train_utils_sequential.sequential_nll`. Args: config (argparse.Namespace): The command line arg...
2b35a177d7998a3bdb8d67806550b9d9f49e6aff
3,616,495
import sqlite3 def connect_to_sqlite3_db(): """ Connects to the sqlite3 database. :return: Connection of type sqlite3.Connection. """ config = ConfigParser() config.read(CFG_FILE) conn = sqlite3.connect(config['paths']['path_to_database']) conn.row_factory = sqlite3.Row return conn
a25373b104b15d6bef1f00a854e1a2e459d6defb
3,616,496
def quote(): """Get stock quote.""" if request.method == "POST": stock_info = lookup(request.form.get("symbol")) if stock_info == None: return apology("cannot find that stock symbol", 403) else: return render_template("quote.html", ...
ab3782027eb2a58e5a770bc631aca1725169a6c8
3,616,497
import os def is_proc_group_parent(proc) -> bool: """ Checks if process is a group parent """ if os.uname().sysname == 'Darwin': fproc_names = filter(lambda x: len(x.cmdline()) > 0, proc.children()) procs_names = [ p.cmdline()[0] for p in fproc_names ] procs_names.append(pr...
c7174fdd725485fb4aeda544dca5313472d9c3ea
3,616,498
import re def validate_time_string(value, is_list): """ Checks that a "time string" quant is correctly formatted. A time string can contain three kinds of expressions, separated by + or -: Base values, which are just numeric (with an optional exponent on e form) Delta values, which are the...
802e7503f19ed1a5bb47ad887d1fe15219225fe1
3,616,499