content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def start_end_epoch(graph): """ Start epoch of graph. :return: (start epoch, end epoch). """ start = 0 end = 0 for e in graph.edges_iter(): for _, p in graph[e[0]][e[1]].items(): end = max(end, p['etime_epoch_secs']) if start == 0: start = p['s...
724726ec83d3a98539eed859ec584c6f1adb8567
3,642,100
def distance_metric(seg_A, seg_B, dx): """ Measure the distance errors between the contours of two segmentations. The manual contours are drawn on 2D slices. We calculate contour to contour distance for each slice. """ table_md = [] table_hd = [] X, Y, Z = seg_A.shape ...
4ae5de6428914c8352ae1c6cdd9e94183d9ea3f8
3,642,101
def tomographic_redshift_bin(z_s, version=default_version): """DES analyses work in pre-defined tomographic redshift bins. This function returns the photometric redshift bin as a function of photometric redshift. Parameters ---------- z_s : numpy array Photometric redshifts. version...
b4a21c111b8d5b5a34c018315f95cf18deb356af
3,642,102
def is_point_in_rect(point, rect): """Checks whether is coordinate point inside the rectangle or not. Rectangle is defined by bounding box. :type point: list :param point: testing coordinate point :type rect: list :param rect: bounding box :rtype: boolean :return: boolean check result """ x0, y0,...
d0c7a64138899f4e50b42dc75ea6030616d4dfec
3,642,103
def chinese_theorem_inv(modulo_list): """ Returns (x, n1*...*nk) such as x mod mk = ak for all k, with modulo_list = [(a1, n1), ..., (ak, nk)] n1, ..., nk most be coprime 2 by 2. """ a, n = modulo_list[0] for a2, n2 in modulo_list[1:]: u, v = bezout(n, n2) a, n = a*v*n2+a...
3d1398901b75ca8b21fb97af0acdfbd65fec0a3e
3,642,104
def compute_segment_cores(split_lines_of_utt): """ This function returns a list of pairs (start-index, end-index) representing the cores of segments (so if a pair is (s, e), then the core of a segment would span (s, s+1, ... e-1). The argument 'split_lines_of_utt' is list of lines from a ctm-edits ...
0d054d1f891127f0a27b20bfbd82ad6ce85dec39
3,642,105
import math def local_neighborhood_nodes_for_element(index, feature_radius_pixels): """ local_neighborhood_nodes_for_element returns the indices of nodes which are in the local neighborhood of an element. Note that the nodes and elements in a mesh have distinct coordinates: elements exist in the centroids...
cf0f55b71af34cebce69cfc8fa6d201ff83c9808
3,642,106
def _classification(dataset='iris',k_range=[1,31],dist_metric='l1'): """ knn on classificaiton dataset Inputs: dataset: (str) name of dataset k: (list) k[0]:lower bound of number of nearest neighbours; k[1]:upper bound of number of nearest neighbours dist_metric: (str) 'l1' or 'l2' ...
ce5d0516cffcb545787abe15c46fe086ff8e4991
3,642,107
from os.path import expanduser def parse_pgpass(hostname='scidb2.nersc.gov', username='desidev_admin'): """Read a ``~/.pgpass`` file. Parameters ---------- hostname : :class:`str`, optional Database hostname. username : :class:`str`, optional Database username. Returns --...
929b705fa8a753f773321e47c73d096ffb4bd171
3,642,108
def make_move(board, max_rows, max_cols, col, player): """Put player's piece in column COL of the board, if it is a valid move. Return a tuple of two values: 1. If the move is valid, make_move returns the index of the row the piece is placed in. Otherwise, it returns -1. 2. The updat...
62ecffbabb83e0ee4119b8b8dbead6bdaeb24fb6
3,642,109
def convert_timestamp(ts): """Converts the timestamp to a format suitable for Billing. Examples of a good timestamp for startTime, endTime, and eventTime: '2016-05-20T00:00:00Z' Note the trailing 'Z'. Python does not add the 'Z' so we tack it on ourselves. """ return ts.isoformat() + 'Z...
6b8d19671cbeab69c398508fa942e36689802cdd
3,642,110
def object_id(obj, clazz=None): """Turn a given object into an ID that can be stored in with the notification.""" clazz = clazz or type(obj) if isinstance(obj, clazz): obj = obj.id elif is_mapping(obj): obj = obj.get('id') return obj
617ae362af894c2f27cc6e032aad7f8df4c33a7c
3,642,111
def get_email_from_request(request): """ Get 'Authorization' from request header, and parse the email address using cpg-util """ auth_header = request.headers.get('Authorization') if auth_header is None: raise web.HTTPUnauthorized(reason='Missing authorization header') try: ...
353604d8021948f4cb6ed80d4fb8a9000b8457ce
3,642,112
def play(url, offset, text, card_data, response_builder): """Function to play audio. Using the function to begin playing audio when: - Play Audio Intent is invoked. - Resuming audio when stopped / paused. - Next / Previous commands issues. https://developer.amazon.com/docs/custom-s...
1a7159adc481d86c35c9206cf8525940b6d1ece3
3,642,113
from typing import List from typing import Dict def all_flags_match_bombs(cells: List[List[Dict]]) -> bool: """ Checks whether all flags are placed correctly and there are no flags over regular cells (not bombs) :param cells: array of array of cells dicts :return: True if all flags are placed cor...
67cc53d8b2ea3541112245192763a6c5f8593b86
3,642,114
def household_id_list(filelist, pidp): """ For a set of waves, obtain a list of household IDs belonging to the same individual. """ hidp_list = [] wave_list = [] wn = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g'} c=1 for name in filelist: print("Loading wave %d data..." % c) ...
8fd7b271034eb953c708ea38bd75ab4671f420cb
3,642,115
from typing import Tuple def biggest_labelizer_arbitrary(metrics: dict, choice: str, *args, **kwargs) -> Tuple[str, float]: """Given dict of metrics result, returns (key, metrics[key]) whose value is maximal.""" metric_values = list(metrics.values()) metric_keys = list(metrics.keys()) # print(items) big = m...
99f4a0f5233f33d80a328cef4e43f339813371a1
3,642,116
from typing import Optional from typing import Dict from typing import Any def _seaborn_viz_histogram(data, x: str, contrast: Optional[str] = None, **kwargs): """Plot a single histogram. Args: data (DataFrame): The data x (str): The name of the column to plot. contrast (str, optional)...
27aed8280c372273e02e7b49647b4e2285a81fa7
3,642,117
def str2bool( s ): """ Description: ---------- Converting an input string to a boolean Arguments: ---------- [NAME] [TYPE] [DESCRIPTION] (1) s dict, str The string which Returns: ---------- T...
cb68fe0382561d69fb332b75c99c01c5a338196f
3,642,118
def im_detect(net, im, boxes=None): """Detect object classes in an image given object proposals. Arguments: net (caffe.Net): Fast R-CNN network to use im (ndarray): color image to test (in BGR order) boxes (ndarray): R x 4 array of object proposals or None (for RPN) Returns: ...
f37cb46375f39b6baf839be5ec68388c79f47e16
3,642,119
def preCSVdatagen(xy_p, radius, nbin, PlainFirst): """Format the data before generating the csv input for ili'. Args: xy_p (str): path to the X and Y coordiantes of ablation marks .npy file. radius (int): displayed radius of the marks in ili'. nbin (int): bin factor used to bin the imag...
2d19439eb82930e622b897a9ee1ddda364f0a04a
3,642,120
def dispatch_error_adaptor(func): """Construct a signature isomorphic to dispatch_error. The actual handler will receive only arguments explicitly declared, and a possible tg_format parameter. """ def adaptor(controller, tg_source, tg_errors, tg_exceptions, *args, **kw): tg_for...
67be23f01c11d668d86f5e2b1afcfb76db79ea6c
3,642,121
import re def address_split(address, env=None): """The address_split() function splits an address into its four components. Address strings are on the form detector-detectorID|device-deviceID, where the detectors must be in dir(xtc.DetInfo.Detector) and device must be in (xtc.DetInfo.Device). @param addr...
c5d362c7fc6121d64ec6a660bcdb7a9b4b532553
3,642,122
import time def solveGroth(A, n, init_val=None): """ ... Parameters ---------- A: np.matrix dfajdslkf n: int ddddddd init_val: float, optional dsfdsafdasfd Returns ------- list of float: float: float: float: """ ep...
a8f4a3ea2274bd1a81565500683dea84378ccddc
3,642,123
def verify_any(func, *args, **kwargs): """ Assert that any of `func(*args, **kwargs)` are true. """ return _verify(func, 'any', *args, **kwargs)
618165e6a9f252ac2ddeffdb9defa34f2d281900
3,642,124
def can_create_election(user_id, user_info): """ for now, just let it be""" return True
06c8290b41b38a840b7826173fd65130d38260a7
3,642,125
import locale def get_system_language(): """ Get system language and locale """ try: default_locale = locale.getdefaultlocale() except ValueError: if IS_MAC: # Fix for "ValueError: unknown locale: UTF-8" on Mac. # The default English locale on Mac is set as "UTF-8" ...
6ab566ca6274480c7af5dd65456e675ae614df7a
3,642,126
from .path import Path2D def circle_pattern(pattern_radius, circle_radius, count, center=[0.0, 0.0], angle=None, **kwargs): """ Create a Path2D representing a circle pattern. Parameters ------------ pat...
b82d60c7a76f12349605191b16bf04d7899c3a3a
3,642,127
def boolean(input): """Convert the given input to a boolean value. Intelligently handles boolean and non-string values, returning as-is and passing to the bool builtin respectively. This process is case-insensitive. Acceptable values: True * yes * y * ...
09c09206d5487bf02e3271403e2ba67358e1d148
3,642,128
def find_horizontal_up_down_links(tc, u, out_up=None, out_down=None): """Find indices of nodes that locate at horizontally upcurrent and downcurrent directions """ if out_up is None: out_up = np.zeros(u.shape[0], dtype=np.int) if out_down is None: out_down = np.zeros(u.shape[0], d...
b61976a57d8dd850c26c7a9baff11483ccdb306f
3,642,129
def _compute_composite_beta(model, robo, j, i): """ Compute the composite beta wrench for link i. Args: model: An instance of DynModel robo: An instance of Robot j: link number i: antecedent value Returns: An instance of DynModel that contains all the new values...
0fa80859787a4e523402d10237b63e33ca0082f4
3,642,130
def pos(x, y): """Returns floored and camera-offset x,y tuple. Setting out of bounds is possible, but getting is not; mod in callers for get_at. """ return (flr(xo + x), flr(yo + y))
1a17648c074157c6164856f44cfa309923ca2226
3,642,131
from typing import List from typing import Dict from typing import Tuple def _check_blockstream_for_transactions( accounts: List[BTCAddress], ) -> Dict[BTCAddress, Tuple[bool, FVal]]: """May raise connection errors or KeyError""" have_transactions = {} for account in accounts: url = f'http...
a17a9204dc0d5f11b8c0352d15c871141e7bb09b
3,642,132
from typing import Callable from typing import Tuple def metropolis_hastings( proposal: Proposal, state: State, step_size: float, ns: int, unif: float, inverse_transform: Callable ) -> Tuple[State, Info, np.ndarray, bool]: """Computes the Metropolis-Hastings accept-...
b5390d8a420ebb3d62c700fe246127935b658b6c
3,642,133
import os def continuous_future(root_symbol_str, offset=0, roll="volume", adjustment="mul", bundle=None): """ Return a ContinuousFuture object for the specified root symbol in the specified bundle (or default bundle). Parameters ---------- root_symbol_str : str The root symbol for the...
e48241a8d098089f0f61c1e6587ccad0cf366f82
3,642,134
from datetime import datetime def Now(): """Returns a datetime.datetime instance representing the current time. This is just a wrapper to ease testing against the datetime module. Returns: An instance of datetime.datetime. """ return datetime.datetime.now()
9a0657011e10b47eb755a575216944a786218f2e
3,642,135
def ndvi_list_hdf(hdf_dir, satellite=None): """ List all the available HDF files, grouped by tile Args: hdf_dir: directory containing one subdirectory per year which contains HDF files satellite: None to select both Tera and Aqua, 'mod13q1' for MODIS, 'myd...
068062bdef503b6652c62c142a1cf80d830fc8db
3,642,136
from typing import List import os def read_levels(dir_path: str, progress_monitor: PyramidLevelCallback = None) -> List[xr.Dataset]: """ Read the of a multi-level pyramid with spatial resolution decreasing by a factor of two in both spatial dimensions. :param dir_path: The directory p...
5e8145c5dcca47f51e1f5190e42976b37ea433c6
3,642,137
def create_provisioned_product_name(account_name: str) -> str: """ Replaces all space characters in an Account Name with hyphens, also removes all trailing and leading whitespace """ return account_name.strip().replace(" ", "-")
743e7438f421d5d42c071d27d1b0fa2a816a9b4d
3,642,138
def case34(): """ Create the IEEE 34 bus from IEEE PES Test Feeders: "https://site.ieee.org/pes-testfeeders/resources/”. OUTPUT: **net** - The pandapower format network. """ net = pp.create_empty_network() # Linedata # CF-300 line_data = {'c_nf_per_km': 3.8250977, 'r_ohm_pe...
8e04a125df0e0a64008724d419bafe19481f5ac1
3,642,139
def _hack_namedtuple(cls): """Make class generated by namedtuple picklable.""" name = cls.__name__ fields = cls._fields def reduce(self): return (_restore, (name, fields, tuple(self))) cls.__reduce__ = reduce cls._is_namedtuple_ = True return cls
89468f0ffb5506ef0c9a33fec0d390576638e659
3,642,140
import os import logging import json def load_config(settings_file='./test_settings.py'): """ Loads the config files merging the defaults with the file defined in environ.PULLSBURY_SETTINGS if it exists. """ config = Config(os.getcwd()) if 'PULLSBURY_SETTINGS' in os.environ: config.fr...
c85060806c0045d0e4a9410de2583fad879e99f6
3,642,141
import tokenize def build_model(): """ Returns built and tuned model using pipeline Parameters: No arguments Returns: cv (estimator): tuned model """ pipeline = Pipeline([ ('Features', FeatureUnion([ ('text_pipeline', Pipeline([ ...
94bc0ad8a3eb48531cb6229972099369a9b9cf61
3,642,142
def INPUT_BTN(**attributes): """ Utility function to create a styled button """ return SPAN(INPUT(_class = "button-right", **attributes), _class = "button-left")
6c6610626367795518ca737b53950d3687ae4d91
3,642,143
def load_annotations(file_path): """Loads a file containing annotations for multiple documents. The file should contain lines with the following format: <DOCUMENT ID> <LINES> <SPAN START POSITIONS> <SPAN LENGTHS> <SEVERITY> Fields are separated by tabs; LINE, SPAN START POSITIONS and SPAN LENGTHS ...
0c674142ae0d99670e63959c3c00ed0ca2c8fac1
3,642,144
import re def search(request, template_name='blog/post_search.html'): """ Search for blog posts. This template will allow you to setup a simple search form that will try to return results based on given search strings. The queries will be put through a stop words filter to remove words like 'the'...
fdb72279b6ed5fe5e87c888b7a10c8a3ed8f94d0
3,642,145
import math def orient_data (data, header, header_out=None, MLBG_rot90_flip=False, log=None, tel=None): """Function to remap [data] from the CD matrix defined in [header] to the CD matrix taken from [header_out]. If the latter is not provided the output orientation will be North up, Eas...
6ef27074692f46de56e5decd7d6b315e11c4d686
3,642,146
def _batchnorm_to_groupnorm(module: nn.modules.batchnorm._BatchNorm) -> nn.Module: """ Converts a BatchNorm ``module`` to GroupNorm module. This is a helper function. Args: module: BatchNorm module to be replaced Returns: GroupNorm module that can replace the BatchNorm module provi...
1b923a28a4727b72768acf0fc00d93d9012c5349
3,642,147
def _compute_bic( data: np.array, n_clusters: int ) -> BICResult: """Compute the BIC statistic. Parameters ---------- data: np.array The data to cluster. n_clusters: int Number of clusters to test. Returns ------- results: BICResult The results as a BICR...
3eb1a759a60f834f4e4fb7e364c9bce4ffb61230
3,642,148
def release_branch_name(config): """ build expected release branch name from current config """ branch_name = "{0}{1}".format( config.gitflow_release_prefix(), config.package_version() ) return branch_name
0d97c515aca8412882c8b260405a63d20b4b0f63
3,642,149
def torch2numpy(data): """ Transfer data from the torch tensor (on CPU) to the numpy array (on CPU). """ return data.numpy()
c7ca4123743c4f054d809f0e307a4de079b0af10
3,642,150
def new_schema(name, public_name, is_active=True, **options): """ This function adds a schema in schema model and creates physical schema. """ try: schema = Schema(name=name, public_name=public_name, is_active=is_active) schema.save() except IntegrityError: raise Exception('...
efd6ed2737c6a25e8beeaef9f7fffebdb9592f10
3,642,151
def find_appropriate_timestep(simulation_factory, equilibrium_samples, M, midpoint_operator, temperature, timestep_range, DeltaF_neq_thresho...
94000a07cfc8cf00e3440ff242c63da5c8be5d00
3,642,152
def critical_bands(): """ Compute the Critical bands as defined in the book: Psychoacoustics by Zwicker and Fastl. Table 6.1 p. 159 """ # center frequencies fc = [ 50, 150, 250, 350, 450, 570, 700, 840, 1000, 1170, ...
6301a6ee86d0ea3fb588213aa8b9453b14fb7036
3,642,153
def repackage(r, amo_id, amo_file, target_version=None, sdk_dir=None): """Pull amo_id/amo_file.xpi, schedule xpi creation, return hashtag """ # validate entries # prepare data hashtag = get_random_string(10) sdk = SDK.objects.all()[0] # if (when?) choosing sdk_dir will be possible # sdk ...
9527f2fbe6077e25eee72a570f2e9702cbf3b510
3,642,154
def edges_to_adj_list(edges): """ Transforms a set of edges in an adjacency list (represented as a dictiornary) For UNDIRECTED graphs, i.e. if v2 in adj_list[v1], then v1 in adj_list[v2] INPUT: - edges : a set or list of edges OUTPUT: - adj_list: a dictionary with the vertices as ...
683f10e9a0a9b8a29d63b276b2e550ebe8287a05
3,642,155
from typing import Optional def _get_lookups( name: str, project: interface.Project, base: Optional[str] = None) -> list[str]: """[summary] Args: name (str): [description] design (Optional[str]): [description] kind (Optional[str]): [description] Returns: list...
c8f700a19bbae0167c8474f033d625a763743db8
3,642,156
def unwrap(value): """ Unwraps the given Document or DocumentList as applicable. """ if isinstance(value, Document): return value.to_dict() elif isinstance(value, DocumentList): return value.to_list() else: return value
7e25c2935ff0a467e51097c4291e8d5f751c34db
3,642,157
def home_all(): """Home page view. On this page a summary campaign manager view will shown with all campaigns. """ context = dict( oauth_consumer_key=OAUTH_CONSUMER_KEY, oauth_secret=OAUTH_SECRET, all=True, map_provider=map_provider() ) # noinspection PyUnresol...
d987486f30cc5a8f6e697d9ccb92741b2d2067e4
3,642,158
import math def _sqrt(x): """_sqrt.""" isnumpy = isinstance(x, np.ndarray) isscalar = np.isscalar(x) return np.sqrt(x) if isnumpy else math.sqrt(x) if isscalar else x.sqrt()
16f566493deeaaf35841548e6db89408ca686bfe
3,642,159
def update_subnet(context, id, subnet): """Update values of a subnet. : param context: neutron api request context : param id: UUID representing the subnet to update. : param subnet: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow_put'...
f1ac159f612d3b8a5459ee3b70c440cf7cf84cd5
3,642,160
def validate_params(): """@rtype bool""" def validate_single_param(param_name, required_type): """@rtype bool""" inner_result = True if not rospy.has_param(param_name): rospy.logfatal('Parameter {} is not defined but needed'.format(param_name)) inner_result = Fal...
8734d9db7e29b8b6c30dc8a3ae72b0cf18c85310
3,642,161
import os def run_test_general_base_retrieval_methods(query_dic, query_types, trec_cast_eval, similarity, string_params, searcher: SimpleSearcher, reranker, write_to_trec_eval, write_results_to_file, reranker_query_config, ...
c0320231f65955b65f447bf0303f4443dcc5110d
3,642,162
def user_exists(username): """Return True if the username exists, or False if it doesn't.""" try: adobe_api.AdobeAPIObject(username) except adobe_api.AdobeAPINoUserException: return False return True
3767bec38c8058e7bd193e5532e4150ca501a96a
3,642,163
def bags_containing_bag(bag: str, rules: dict[str, list]) -> int: """Returns the bags that have bag in their rules.""" return {r_bag for r_bag, r_rule in rules.items() for _, r_color in r_rule if bag in r_color}
f9e67a4ade4dd9bdf25e05669741c71270007215
3,642,164
def default_mutable_arguments(): """Explore default mutable arguments, which are a dangerous game in themselves. Why do mutable default arguments suffer from this apparent problem? A function's default values are evaluated at the point of function definition in the defining scope. In particular, we can ...
a58a8c2807e29af68d501aa5ad4b33ad1aa80252
3,642,165
def is_text_file(file_): """ detect if file is of type text :param file_: file to be tested :returns: `bool` of whether the file is text """ with open(file_, 'rb') as ff: data = ff.read(1024) return not is_binary_string(data)
d064b51ea239f34ed97d47416b1f411650ce8a1a
3,642,166
from typing import Union from datetime import datetime from typing import List import pytz def soft_update_datetime_field( model_inst: models.Model, field_name: str, warehouse_field_value: Union[datetime, None], ) -> List[str]: """ Uses Django ORM to update DateTime field of model instance if the ...
33034a548ee572706cd1e6e696d5a9249ad0b528
3,642,167
import itertools def plot_confusion_matrix( y_true, y_pred, normalize=False, cmap=plt.cm.Blues, label_list = None, visible=True, savepath=None): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normali...
f15d2170ba0e869cb47e554ea374f93b05dbcab8
3,642,168
def _test_pressure_reconstruction(self, g, recon_p, point_val, point_coo): """ Testing pressure reconstruction. This function uses the reconstructed pressure local polynomial and perform an evaluation at the Lagrangian points, and checks if the those values are equal to the point_val array. Param...
b70b202cc21ba632f18af2f5fcf72f7b6d509e91
3,642,169
def logout(): """Logout :return: Function used to log out the current user """ logout_user() return redirect(url_for('index'))
f5e2ef30b47c645ba5671395a115eb6d6c9425f1
3,642,170
import json import base64 import os import requests def get_authorization_url( app_id, redirect_uri, scope='all', state='', extra_data='', **params): """ Get the url to start the first leg of OAuth flow. Refer to `Authentication Docs <https://developers.kloudless.com/docs/latest/ authenticati...
27abfc9c9c14887f1a3a963f7eb07d92706e288a
3,642,171
def get_user_messages(user, index=0, number=0): """ 返回指定user按时间倒序的从index索引开始的number个message """ if not user or user.is_anonymous or index < 0 or number < 0: return tuple() # noinspection PyBroadException try: if index == 0 and number == 0: all_message = user.messa...
bb0c499e5ca8ec650d2ebca12852d2345733e882
3,642,172
def third_party_apps_default_dc_modules_and_settings(klass): """ Decorator for DefaultDcSettingsSerializer class. Updates modules and settings fields defined in installed third party apps. """ logger.info('Loading third party apps DEFAULT DC modules and settings.') for third_party_app, app_dc_...
59be03a271e60352b429d45ecff647100388f9ab
3,642,173
from typing import Union from pathlib import Path def split_lvis( n_experiences: int, train_transform=None, eval_transform=None, shuffle=True, root_path: Union[str, Path] = None, ): """ Creates the example Split LVIS benchmark. This is a toy benchmark created only to show how a detect...
efece586ec6bfbc45911ed9f4f2ad5ead2cfd88b
3,642,174
def compute_log_ksi_normalized(log_edge_pot, #'(t-1,t)', log_node_pot, # '(t, label)', T, n_labels, log_alpha, log_beta, temp_array_1, temp_array_2): """ to obtain the two-slice posteri...
e4e6ea464851ba64d640e14fd7c88e9c52f28f50
3,642,175
import argparse from pathlib import Path def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description="Map gleason data to standard format.") parser.add_argument("-d", "--data_path", type=Path, help="Path to folder with the data.", required=True) parser.add_argument("-n...
0a1a1cb404d74c48d550642e31399410d1bd13c3
3,642,176
from typing import Any from typing import Type def _deserialize_union(x: Any, field_type: Type) -> Any: """Deserialize values for Union typed fields Args: x (Any): value to be deserialized. field_type (Type): field type. Returns: [Any]: desrialized value. """ for arg in f...
01793983a0a82fc16c03adbe57f52de9be5c81ea
3,642,177
def read_simplest_expandable(expparams, config): """ Read expandable parameters from config file of the type `param_1`. Parameters ---------- expparams : dict, dict.keys, set, or alike The parameter names that should be considered as expandable. Usually, this is a module subdictiona...
4e2068e4a6cbca050da6a33a24b5fb0d2477e4e3
3,642,178
from typing import Callable from typing import Iterable from typing import Any def rec_map_reduce_array_container( reduce_func: Callable[[Iterable[Any]], Any], map_func: Callable[[Any], Any], ary: ArrayOrContainerT) -> "DeviceArray": """Perform a map-reduce over array containers recursivel...
885862371ece1e1f041a44693704300945d8d4a0
3,642,179
def load_data_test(test_path, diagnoses_list, baseline=True, multi_cohort=False): """ Load data not managed by split_manager. Args: test_path (str): path to the test TSV files / split directory / TSV file for multi-cohort diagnoses_list (List[str]): list of the diagnoses wanted in case of s...
50b739425ca76a3d170688f19e230a0d84c21221
3,642,180
import json def load_augmentations_config( placeholder_params: dict, path_to_config: str = "configs/augmentations.json" ) -> dict: """Load the json config with params of all transforms Args: placeholder_params (dict): dict with values of placeholders path_to_config (str): path to the json ...
49f3170033411418e7e5468aecdcdc612a677e66
3,642,181
import numpy def simplify_mask(mask, r_ids, r_p_zip, replace=True): """Simplify the mask by replacing all `region_ids` with their `root_parent_id` The `region_ids` and `parent_ids` are paired from which a tree is inferred. The root of this tree is value `0`. `region_ids` that have a corresponding `p...
b8344a893319ad7a26f931b2edbc6ef452b82c24
3,642,182
def getStops(ll): """ getStops Returns a list of stops based off of a lat long pair :param: ll { lat : float, lng : float } :return: list """ if not ll: return None url = "%sstops?appID=%s&ll=%s,%s" % (BASE_URI, APP_ID, ll['lat'], ll['lng']) try: f = u...
eedfc49a02ab6c2ccf45e241262236804007a156
3,642,183
import warnings import six def rws(log_joint, observed, latent, axis=None): """ Implements Reweighted Wake-sleep from (Bornschein, 2015). This works for both continuous and discrete latent `StochasticTensor` s. :param log_joint: A function that accepts a dictionary argument of ``(string, Tens...
eb6278919dd484884b3110681680e67d3ee17d2f
3,642,184
def fit_svr(X, y, kernel: str = 'rbf') -> LinearSVR: """ Fit support vector regression for the given input X and expected labes y. :param X: Feature data :param y: Labels that should be correctly computed :param kernel: type of kernel used by the SVR {‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed...
10a38fca990c4ab058d582fbe38bd05df7456660
3,642,185
import typing def process_get_namespaces_from_accounts( status: int, json: list, network_type: models.NetworkType, ) -> typing.Sequence[models.NamespaceInfo]: """ Process the "/account/namespaces" HTTP response. :param status: Status code for HTTP response. :param json: JSON data for resp...
748bdca72db0640e75f8a0c063f7968ea9583e94
3,642,186
from typing import Optional import os def _initialize_pydataverse(DATAVERSE_URL: Optional[str], API_TOKEN: Optional[str]): """Sets up a pyDataverse API for upload.""" # Get environment variables if DATAVERSE_URL is None: try: DATAVERSE_URL = os.environ["DATAVERSE_URL"] except...
716ce3a3e589cc9323159e6285194ab74706dc92
3,642,187
def _hexsplit(string): """ Split a hex string into 8-bit/2-hex-character groupings separated by spaces""" return ' '.join([string[i:i+2] for i in range(0, len(string), 2)])
672e475edeaafaa08254845e620b0a771b294fa8
3,642,188
def get_analysis_id(analysis_id): """ Get the new analysis id :param analysis_id: analysis_index DataFrame :return: new analysis_id """ if analysis_id.size == 0: analysis_id = 0 else: analysis_id = np.nanmax(analysis_id.values) + 1 return int(analysis_id)
3318764daadca6c1e1921847f623fcac169e2cb5
3,642,189
from typing import Union def get_station_pqr(station_name: str, rcu_mode: Union[str, int], db): """ Get PQR coordinates for the relevant subset of antennas in a station. Args: station_name: Station name, e.g. 'DE603LBA' or 'DE603' rcu_mode: RCU mode (0 - 6, can be string) db: inst...
d796639866421876bc58a7621d37bbe7239da6df
3,642,190
from typing import List def hello_world(cities: List[str] = ["Berlin", "Paris"]) -> bool: """ Hello world function. Arguments: - cities: List of cities in which 'hello world' is posted. Return: - success: Whether or not function completed successfully. """ try: [print("Hello...
a24f0f47c9b44c97f46524d354fff0ed9a735fe3
3,642,191
import os import re def parse_dir(directory, default_settings, oldest_revision, newest_revision, rep): """Parses bench data from files like bench_r<revision>_<scalar>. (str, {str, str}, Number, Number) -> {int:[BenchDataPoints]}""" revision_data_points = {} # {revision : [BenchDataPoint...
8a802eec0c528f67bffdfc239079eba3729eb2f3
3,642,192
import random def random_samples(traj_obs, expert, num_sample): """Randomly sample a subset of states to collect expert feedback. Args: traj_obs: observations from a list of trajectories. expert: an expert policy. num_sample: the number of samples to collect. Returns: new expert data. """ ...
55aa4312c095ce97b8cf2840ff9ca61e393dff63
3,642,193
import os def makeFolder(path): """Build a folder. Args: path (str): Folder path. Returns: bool: Creation status. """ if(not os.path.isdir(path)): try: os.makedirs(path) except OSError as error: print("Directory %s can't be created (%s)" % ...
4bd1535fb3ffc69f5638b6cfbeaf90a1ccbdf2f9
3,642,194
def get_p2_vector(img): """ Returns a p2 vector. We calculate the p2 vector by taking the radial mean of the autocorrelation of the input image. """ radvars = [] dimX = img.shape[0] dimY = img.shape[1] fftimage = np.fft.fft2(img) final_image = np.fft.ifft2(fftimage*np.conj(fftim...
7544751bf268d6eea432e21efe3d3a7703b16c1b
3,642,195
import os def start_replica_cmd(builddir, replica_id): """ Return a command that starts an skvbc replica when passed to subprocess.Popen. Note each arguments is an element in a list. """ statusTimerMilli = "500" viewChangeTimeoutMilli = "10000" path = os.path.join(builddir, "tests", "...
5f30b328dd0e583581310afeb3de0af3bc79c17c
3,642,196
def multiplex(n, q, **kwargs): """ Convert one queue into several equivalent Queues >>> q1, q2, q3 = multiplex(3, in_q) """ out_queues = [Queue(**kwargs) for i in range(n)] def f(): while True: x = q.get() for out_q in out_queues: out_q.put(x) t...
4de6fa4fd495c2b320c4cdf28aa56df4411b7aa9
3,642,197
def stack(arrays, axis=0): """ Join a sequence of arrays along a new axis. The `axis` parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. .. versionadded:: 1.1...
ba8a2b514c32a1dc7a15215e5e26a90f2ace9a26
3,642,198
import logging import sys def get_runs(runs, selected_runs, cmdline): """Selects which run(s) to execute based on parts of the command-line. Will return an iterable of run numbers. Might also fail loudly or exit after printing the original command-line. """ name_map = dict((r['id'], i) for i, r i...
fefeb7ec2e9c11767e2e15856321bf68aaad8a83
3,642,199