content
stringlengths
22
815k
id
int64
0
4.91M
def Wizard(): """ Creates a wizardcharacter :returns: fully initialised wizard :rtype: Character """ character = (CharacterBuilder() .with_hit_points(5) .with_max_hp(5) .with_spirit(20) .with_max_spirit(20) .wi...
48,500
def clear_fallback_cache(target, workload): """Clear fallback cache. Pass the same argument as _query_inside to this function to clean the cache. Parameters ---------- target: Target The current target workload : Workload The current workload. Note ---- This is used...
48,501
def tournament_communication(comm, comm_fn=lambda x,y: None, comm_kw={}): """ This is useful for the development of parallelized O(N) duplicate check functions. The problem with such functions is that the operation of checking if a set of param...
48,502
def create_permutation_feature(number, rate_pert=1., name=None): """Create permutation for features.""" n = np.random.randint(0, 100000) if name is None: name = f_stringer_pert_rate(rate_pert) lista_permuts = [] for i in range(number): lista_permuts.append((name, PartialPermutationP...
48,503
def test_finding_collection_other_file(dispatcher, ntbk_dir, mocker): """Test using the --find flag wit 'dune' file name finds dune.md""" mocker.patch('builtins.print') aliases = ['collection', 'col', 'c'] expected_path = ntbk_dir / 'collections/books/dune.md' for alias in aliases: dispatche...
48,504
def DiceRoll(): """A function to simulate rolling of one or more dice.""" def Roll(): return random.randint(1,6) print("\nRoll Dice: Simulates rolling of one or more dice.") num = 1 try: num = int(input("\nEnter the number of dice you wish to roll: ")) except: print("Input should b...
48,505
def rook_move(self, game, src): """ Validates rook move """ x = src[0] y = src[1] result = [] loop_condition = (lambda i: i < 8) if self.color == 'white' else (lambda i: i >= 0) reverse_loop_condition = (lambda i: i < 8) if self.color == 'black' else (lambda i: i >= 0) counter_eval = +1 if ...
48,506
def figure_5a(): """ This creates the plot for figure 5A in the Montague paper. Figure 5A is a 'plot of ∂(t) over time for three trials during training (1, 30, and 50).' """ # Create Processing Components sample_mechanism = pnl.TransferMechanism(default_variable=np.zeros(60), ...
48,507
def init(): """Return top level command handler.""" @click.group(cls=cli.make_commands(__name__)) @click.option('--distro', required=True, help='Path to treadmill distro.', envvar='TREADMILL_DISTRO') @click.option('--install-dir', required=True, hel...
48,508
def lambda_handler(event, context): """ Transforms a binary payload by invoking "decode_{event.type}" function Parameters ---------- DeviceId : str Device Id ApplicationId : int LoRaWAN Application Id / Port number PayloadData : str Base64 ...
48,509
def torch_to_onnx(torch_path, onnx_path, image_path): """ Converts PyTorch model file to ONNX with usable op-set :param torch_path: Torch model path to load :param onnx_path: ONNX model path to save :param image_path: Path of test image to use in export progress """ pytorch_model = get_torch...
48,510
def _get_adi_snrs(psf, angle_list, fwhm, plsc, flux_dist_theta_all, wavelengths=None, mode='median', ncomp=2): """ Get the mean S/N (at 3 equidistant positions) for a given flux and distance, on a median subtracted frame. """ snrs = [] theta = flux_dist_theta_all[2] flux = flux...
48,511
def compute_nearest_neighbors(fit_embeddings_matrix, query_embeddings_matrix, n_neighbors, metric='cosine'): """Compute nearest neighbors. Args: fit_embeddings_matrix: NxD matrix """ fit_eq_query = False if ((fit_embeddings_matrix.shape == query_embeddings_matri...
48,512
def commodify_cdli_no( cdli_no ): """ Given a CDLI number, fetch the text of the corresponding artifact from the database and pass it to commodify_text """ # Ensure that we have a valid artifact number: if re.match(r'P[0-9]{6}', cdli_no) is not None: art_no = int(cdli_no[1:]) elif re...
48,513
def do_verify(options, _fuse): """ @param options: Commandline options @type options: object @param _fuse: FUSE wrapper @type _fuse: dedupsqlfs.fuse.dedupfs.DedupFS """ tableOption = _fuse.operations.getTable("option") curHashFunc = tableOption.get("hash_function") tableHash = ...
48,514
def connect_flow(group, fl_src, fl_target, connect_stat=True, connect_tot=True, connect_w=True): """ connect flow variables """ warnings.simplefilter('always', DeprecationWarning) warnings.warn(f"Deprecation warning: `connect_flow` function is deprecated. Use the `pyc_connect_flow` method from `Cycle` clas...
48,515
def today(ctx): """Display a random quote, seeding the random number generator with the date to produce a random quote that remains the same on a given day. """ quotefile = ctx.obj['QUOTEFILE'] quotes = api.read_quotes(quotefile) if len(quotes) > 0: # Get random random quote based on d...
48,516
def do_view_change_with_pending_request_and_one_fast_node(fast_node, nodes, looper, sdk_pool_handle, sdk_wallet_client): """ Perform view change while processing request, with one node receiving commits much sooner than others. With current implement...
48,517
def zvalues(r, N=1): """ Generate random pairs for the CDF a normal distribution. The z-values are from the cumulative distribution function of the normal distribution. Args: r: radius of the CDF N: number of pairs to generate Returns: pairs of random numbers """ ...
48,518
def exp(fdatagrid): """Perform a element wise exponential operation. Args: fdatagrid (FDataGrid): Object to whose elements the exponential operation is going to be applied. Returns: FDataGrid: Object whose elements are the result of exponentiating the elements of th...
48,519
def ksvm(param, data): """ kernelized SVM """ certif = np.linalg.eigvalsh(data['K'])[0] if certif < 0: data['K'] = data['K'] - 2 * certif * np.eye(data['K'].shape[0]) optimal = {} if len(param['kappa']) > 1 or float('inf') not in param['kappa']: optimal.update(dist_rob_ksvm(param, da...
48,520
def _ordered_unique(arr): """ Get the unique elements of an array while preserving order. """ arr = np.asarray(arr) _, idx = np.unique(arr, return_index=True) return arr[np.sort(idx)]
48,521
def is_byte_array(value, count): """Returns whether the given value is the Python equivalent of a byte array.""" return isinstance(value, tuple) and len(value) == count and all(map(lambda x: x >= 0 and x <= 255, value))
48,522
def save_image(img, file_path, image_type=None): """ Helper to save Image object to file, with optional explicit type. """ if image_type: img.save(file_path, image_type) else: img.save(file_path)
48,523
def replace_labels_string(element, label, newstring): """ Replaces in the text of Element and its childs the text label for newstring """ # When the element does not have children, we replace the string in the # element text. if len(element) == 0 and element.text is not None: element.tex...
48,524
def adjust_learning_rate(optimizer, epoch, args): """Sets the learning rate to the initial LR decayed by 10 every 10 epochs""" lr = args.lr * (0.1 ** (epoch // 10)) for param_group in optimizer.param_groups: param_group['lr'] = lr
48,525
def test_transformer_transform_X_categorical(data_classification_balanced, feature_name, csr_matrix_flag): """Testing if every categorical column from a test data is transformed correctly.""" df = pd.concat([data_classification_balanced[0], data_classification_balanced[1]], axis=1) # replacing for SimpleImp...
48,526
def test_ndb_future_executor_nested(): """ This test illustrates that nested NDB futures are handled correctly. """ query = 'query Nested { a { b c } }' @ndb.tasklet def resolver_a(*_): ATuple = namedtuple('ATuple', 'c') future = ndb.Future() future.set_result(ATuple('yo...
48,527
def _FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices): """Filter substructure match atom indices by atom map indices corresponding to atom map numbers. """ if AtomMapIndices is None: return list(AtomIndices) ...
48,528
def questions_for_written_answer_tabled_in_range(start, end): """Returns a list of all Questions for Written Answer tabled in date range. """ try: _start = start.isoformat() except AttributeError: return [] try: _end = end.isoformat() except AttributeError: return...
48,529
def get_headers_token(security_scopes: SecurityScopes, encoded: str = Depends(get_reusable_oauth2())) -> Token: """ This FastAPI dependency *will not* result in an argument added to the OpenAPI spec. This should generally be used for dependencies involving the access token. """ return get_validated...
48,530
def worker_mode(self): """ bool: Whether or not all MPI ranks are in worker mode, in which all worker ranks are listening for calls from the controller rank. If *True*, all workers are continuously listening for calls made with :meth:`~_make_call` until set to *False*. By default, this is *False...
48,531
def add_bc_fr_node( label: str, a: str, n: int, d: float, tab_nam: str = None, ) -> None: """Add fixed rotation boundary conditions on a single node Parameters ---------- label : str The label of the boundary condition tab_nam : str The name of the table defi...
48,532
def async_put(table): """ async put """ print("\nasync put") rowkey_list = ["async"] for key in rowkey_list: mu = table.NewRowMutation(key) mu.Put("cf0", "qu0", "value") mu.SetCallback(write_callback) table.ApplyMutation(mu) while not table.IsPutFinished(): ti...
48,533
def test_techsupport(request, config, duthosts, enum_rand_one_per_hwsku_frontend_hostname): """ test the "show techsupport" command in a loop :param config: fixture to configure additional setups_list on dut. :param duthost: DUT host """ duthost = duthosts[enum_rand_one_per_hwsku_frontend_hostna...
48,534
def run_devutils(skip_testbeds): """Run devutils to check icmp reachability for testbeds""" health_results = [] ping_results = [] testbeds_dict = get_testbeds_dict() for group in GROUPS: input_file_name ='ping_{}.json'.format(group) command_dut = './devutils -i {} -a ping -j > {}'....
48,535
def test_circle_example(repetitions): """Check that the circle example dataset never changes. If, for some reason, it changes (or needs to be changed) on purpose, then delete `circle.csv` and run this test again.""" history = run_circle_example() try: expected = pd.read_csv("tests/circle.c...
48,536
def _pcolor(text, color, indent=0): """ Colorized print to standard output """ esc_dict = { 'black':30, 'red':31, 'green':32, 'yellow':33, 'blue':34, 'magenta':35, 'cyan':36, 'white':37, 'none':-1 } if esc_dict[color] != -1: return ( '\033[{color_code}m{indent}{text}\...
48,537
def naninterp(X, method='linear'): """ --------------------------------------------------------------------- fill 'gaps' in data (marked by NaN) by interpolating --------------------------------------------------------------------- """ inan = np.argwhere(np.isnan(X)) if inan.size == 0: ...
48,538
def to_op_list(elements: list) -> OperatorList: """elements should be a properly written reverse polish notation expression to be made into OperatorLists""" if len(elements) == 0: raise InvalidExpressionError() new_elements = [] for e in elements: if isinstance(e, Element): n...
48,539
def story_simple(directory): """Generate simple Story sample.""" mass_set = ConstructionSet('Thermal Mass Construction Set') pts_1 = (Point3D(0, 0, 3), Point3D(0, 10, 3), Point3D(10, 10, 3), Point3D(10, 0, 3)) pts_2 = (Point3D(10, 0, 3), Point3D(10, 10, 3), Point3D(20, 10, 3), Point3D(20, 0, 3)) pts...
48,540
def future(fn): """Mark a test as expected to unconditionally fail. Takes no arguments, omit parens when using as a decorator. """ fn_name = fn.__name__ def decorated(*args, **kw): try: fn(*args, **kw) except Exception, ex: print ("Future test '%s' failed as ...
48,541
def prodXTXv(v): """ Fast computation function for the product between a vector v, the matrix X and the transpose of the matrix X, where X is the triangular matrix with only one below the diagonal. :parameters: - v : (array-like) the vector v :return: - res : the result of the mat...
48,542
def gevent_hub_main(): """Run the gevent hub main loop forever.""" # This doesn't work with Syncless, but we have a monkey-patch for that, # see syncless.patch.gevent_hub_main(). __import__('gevent.hub').hub.get_hub().switch()
48,543
def input_fn(mode, batch_size, data_dir): """Input_fn using the contrib.data input pipeline for CIFAR-10 dataset. Args: mode: Standard names for model modes (tf.estimators.ModeKeys). batch_size: The number of samples per batch of input requested. """ dataset = record_dataset(filenames(mode, data_di...
48,544
def _get_default_arguments(obj: Any) -> Set[str]: """Get the names of the default arguments on an object The default arguments are determined by comparing the object to one constructed from the object's class's initializer with Mocks for all positional arguments Arguments: obj: the object to f...
48,545
def restart_openstack_node(*args): """Restarts the contrail openstack services in once openstack node. USAGE:fab restart_openstack_node:user@1.1.1.1,user@2.2.2.2""" openstack_services = get_openstack_services() if detect_ostype() in ['ubuntu']: openstack_services['services'] += ['memcached'] els...
48,546
def execute_query( connection: mysql.connector.connection_cext.CMySQLConnection, sql_query: str, data: Union[dict, tuple], commit=True, ) -> Optional[int]: """ Execute and commit MySQL query Parameters ---------- connection : mysql.connector.connection_cext.CMySQLConnection ...
48,547
def analyze_records(): """ """ analyze_mean() # plot_mean()
48,548
def rpn_targets(anchors, bbox_gt, config): """Build the targets for training the RPN Arguments --------- anchors: [N, 4] All potential anchors in the image bbox_gt: [M, 4] Ground truth bounding boxes config: Config Instance of the Config class that stores the parameters ...
48,549
def add_years(d, years): """Return a date that's `years` years after the date (or datetime). Return the same calendar date (month and day) in the destination year, if it exists, otherwise use the following day (thus changing February 29 to February 28). """ try: return d.replace(year=d.y...
48,550
def adj_to_knn(adj, n_neighbors): """convert the adjacency matrix of a nearest neighbor graph to the indices and weights for a knn graph. Arguments --------- adj: matrix (`.X`, dtype `float32`) Adjacency matrix (n x n) of the nearest neighbor graph. n_neighbors: 'int' (o...
48,551
def write_class_diagram(package, output="/tmp/gen.wsd", draw_depend=False): """Write a class diagram Draw the class diagram provided the description from class_list Parameters ---------- package : dict Dictionary with field of subpackages and modules output : str The outpu...
48,552
def typeck(banana_file): """ Type-check the provided BananaFile instance. If it type check, it returns the associated TypeTable. :type banana_file: ast.BananaFile :param banana_file: The file to typecheck. :rtype: typetbl.TypeTable :return: Returns the TypeTable for this BananaFile """ ...
48,553
def stylemap(styles, paths=None): """Return path to mapfile for a given style. Searches mapfile in the following locations: 1. templatepath/style/map 2. templatepath/map-style 3. templatepath/map """ if paths is None: paths = templatepath() elif isinstance(paths, str): ...
48,554
async def authenticate( session: aiohttp.ClientSession, username: str, password: str ) -> str: """Authenticate and return a token.""" with async_timeout.timeout(10): resp = await session.request( "post", BASE_URL + "authenticate", data={"username": username, "pass...
48,555
async def create_individual_sensors( hass: HomeAssistantType, sensor_config: dict ) -> list[SensorEntity]: """Create entities (power, energy, utility_meters) which track the appliance.""" source_entity = await create_source_entity(sensor_config[CONF_ENTITY_ID], hass) try: power_sensor = await ...
48,556
def test_photoinfo_exiftool_no_groups(): """ test PhotoInfo.exiftool which returns ExifTool object for photo without tag group names""" import osxphotos photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB) for uuid in EXIF_UUID_NO_GROUPS: photo = photosdb.photos(uuid=[uuid])[0] exiftool = ph...
48,557
def collatz(number): """If number is even (number // 2) else (3 * number + 1) Args: number (int): number to collatz Returns: int: collatz number """ if (number % 2) == 0: print(number // 2) return number // 2 print(3 * number + 1) return 3 * number + 1
48,558
def maximum_clique(adjacency): """Maximum clique of an adjacency matrix. Parameters ---------- adjacency : (M, M) array Adjacency matrix. Returns ------- maximum_clique : list with length = size of maximum clique Row indices of maximum clique coordinates. Set to ...
48,559
def buy(): """ GROUP to buy things. """
48,560
def get_disk_at(board, position): """ Return the disk at the given position on the given board. - None is returned if there is no disk at the given position. - The function also returns None if no disk can be obtained from the given board at the given position. This is for ins...
48,561
def test_import_line_mangles_issues_505() -> None: """Test to ensure comment on import with parens doesn't cause issues""" test_input = "from sys import * # (\n\n\ndef test():\n" ' print("Test print")\n' assert isort.code(test_input) == test_input
48,562
def incr_key_store(key, amount=1): """ increments value of key in store with amount :param key: key of the data :param amount: amount to add :return: new value """ if get_use_redis(): return rds.incr(str(key), amount) else: if exists_key_store(key): value = g...
48,563
def firstUniqChar(s): """ :type s: str :rtype: int """ if len(s) == 0: return -1 if len(s) == 1: return 0 hash_table = {} for i in s: if i not in hash_table: hash_table[i] = 1 else: hash_table[i] += 1 for i in s: ...
48,564
def sum_of_powers_of_transition_matrix(adj, pow): """Computes \sum_{r=1}^{pow) (D^{-1}A)^r. Parameters ----- adj: sp.csr_matrix, shape [n_nodes, n_nodes] Adjacency matrix of the graph pow: int Power exponent Returns ---- sp.csr_matrix Sum of powers of the transi...
48,565
def print_header(s): """Print a nice header for string s.""" print() print(f"##{'#'*len(s)}##") print(f"# {s} #") print(f"##{'#'*len(s)}##") print()
48,566
def test_set_model_pointer_fails_if_tuple(): """Test that the model_pointer property fails with tuple.""" model_pointer = (3, 4) p.model_pointer = model_pointer
48,567
def get_current_sites( brand_id: Optional[BrandID] = None, *, include_brands: bool = False ) -> set[Union[Site, SiteWithBrand]]: """Return all "current" (i.e. enabled and not archived) sites.""" query = db.session.query(DbSite) if brand_id is not None: query = query.filter_by(brand_id=brand_id)...
48,568
def commonOptions(grp, defaults, bw=True, plots=True, preprocessing=False): """ Common options found in many workflows grp is an argument group that's simply appended to """ if not preprocessing: grp.add_argument("--downsample", dest="downsample", ...
48,569
def get_text_editor_for_attr(traits_ui, attr): """ Grab the Qt QLineEdit for attr off the UI and return its text. """ widget = get_widget_for_attr(traits_ui, attr) return widget.text()
48,570
def check_coords(lat, lng): """ Accepts a list of lat/lng tuples. returns the list of tuples that are within the bounding box for the US. NB. THESE ARE NOT NECESSARILY WITHIN THE US BORDERS! """ if bottom <= lat <= top and left <= lng <= right: inside_box = 1 else: inside...
48,571
async def confirm_email(body: ConfirmTokenModel, include_in_schema=False): """Mark a user's email as confirmed""" email = verify_access_token(body.token) if not email: logger.info("Error getting email") return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, c...
48,572
def rebuild(): """ Deploy current master and run full buildout """ project.site.update() project.site.build_full() project.site.restart()
48,573
def add(measurement_obj): """ Add a Measurement Object to the database """ crud.add(measurement_obj)
48,574
def create_config_hyperparameter_search(dataset_name): """ Create the config file for the hyper-parameter tuning given a dataset. """ hidden_layer_size = [16, 32, 64] n_hidden_layers = [2, 3, 4] learning_rate = [0.005, 0.01, 0.02, 0.05] lr_decay = [0.99, 0.995, 0.999, 1.0] pyto...
48,575
def get_genome_set(gids=[], def_name=None): """Wrapper for Genome object creation, checks if cache (created through unique option set) exists first and returns that. returns dict: key = genome_id, value = Genome() object see: help(Genome) """ if not gids: sys.stderr.write("No ids inputt...
48,576
def sample_tag(user: User, name: str = "Main course") -> Tag: """Create and return a sample name""" return Tag.objects.create(user=user, name=name)
48,577
def update(todo_id, done): """Handle request. Delete todo.""" update_todo(username=current_user.id, todo_id=todo_id, done=done) return redirect(url_for('hello'))
48,578
def initialize_maps(app): """ Initialize maps storage. Make sure the maps directory exists, and create a new "current" map if one does not exist. This may make starting up a new system easier. """ maps_repo = get_map_repository() maps_dir = maps_repo.get_base_dir() os.makedirs(maps_dir...
48,579
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as Returns ------- trustworthiness : float Trustworthiness of the low-dimensional embedding. """ if ...
48,580
def calculate_score(model, device, data_dir, output_dir, metadata_path, **kwargs): """Calculate score""" data_dir = Path(data_dir) if output_dir is None: output_dir = data_dir else: output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) output_path = Path(o...
48,581
def compute_logomaker_df(adata, indices, fixed_length: int = None): """ The sample names (adata.obs_names) must be strings made of amino acid characters. The list of allowed characters is stored in the variable aminoacids. """ if fixed_length is None: pos_list = np.arange(max([len(adata.obs_...
48,582
def test_post_and_patch_all_items_error(testapp, post_data): """ additional property introduced into 'family' item json - designed to test appropriate error message produced in 'output' when item fails to post """ post_data['post']['family'][0]['extra_field'] = 'extra field value' output, succe...
48,583
def parse_test_stats_from_output(output: str, fail_type: Optional[str]) -> Tuple[int, int]: """Parse tasks output and determine test counts. Return tuple (number of tests, number of test failures). Default to the entire task representing a single test as a fallback. """ # pytest m = re.search(...
48,584
def _constraint_items_missing_from_collection( constraints: List[Tuple], collection: Dict[str, int] ) -> List[str]: """ Determine the constrained items that are not specified in the collection. """ constrained_items = set() for constraint in constraints: if len(constraint) > 1: ...
48,585
def coldpool_edge_shear_direction_split( tv0100, ds_profile, l_smoothing=L_SMOOTHING_DEFUALT, l_edge=L_EDGE_DEFAULT, d_theta_v=COLDPOOL_THRESHOLD_DEFAULT, shear_calc_z_max=SHEAR_DIRECTION_Z_MAX_DEFAULT, profile_time_tolerance=60.0, ): """ Computes a mask for the edge of coldpools in ...
48,586
def store_audio_tracks(): """ Store the audio tracks of an event identified after probing the first HLS video segment. Body: .. code-block:: python { "Name": string, "Program": string, "AudioTracks": list } Returns: None Raises: ...
48,587
def isqrt(n): """ Return the integer part of the square root of the input. (math.isqrt from Python 3.8) """ n = operator.index(n) if n < 0: raise ValueError("isqrt() argument must be nonnegative") if n == 0: return 0 c = (n.bit_length() - 1) // 2 a = 1 d = 0 f...
48,588
def createPreviewImg(zipfilename, finalOutputDir, metainfo, dummy, verbose, noOverwrite, makereadonly=False): """ Create the preview image, in the final output directory """ pngFilename = os.path.basename(zipfilename).replace('.zip', '.png') finalPngFile = os.path.join(finalOutputDir, pngFilename) ...
48,589
def seasonal_maps(time, dir = '.', show = True): """ Creates plots of insolation, temperature, and ice balance over the course of an orbit (4 orbits for temp) Parameters ---------- time : float The time of the data you want to plot (see SeasonalClimateFiles directory) Keyword Arguments -----------...
48,590
def main(file_in, file_out): """ Read in lines, flatten list of lines to list of words, sort and tally words, write out tallies. """ with open(file_in, 'r') as f_in: word_lists = [line.split() for line in f_in] # Flatten the list # http://stackoverflow.com/questions/952914/\ # ...
48,591
def check_api_key(current_request): """ Check if an API Key for GitHub was provided and return a 403 if no x-api-key header was sent by the client. """ x_api_key = current_request.headers.get('x-api-key', False) if not x_api_key: return Response( body='Missing x-api-key heade...
48,592
def read_mm_stamp(fh, byteorder, dtype, count): """Read MM_STAMP tag from file and return as numpy.array.""" return numpy_fromfile(fh, byteorder+'8f8', 1)[0]
48,593
def _upload_blob(bucket_name: str, source_file_name: str, destination_blob_name: str): """ Uploads a local file to a given GCS bucket path """ storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_...
48,594
def Qfromq(q): """ converts five-element set q of unique Q-tensor elements to the full 3x3 Q-tensor matrix """ return np.array( [ [ q[0], q[1], q[2] ], [ q[1], q[3], q[4] ], [ q[2], q[4], -q[0] - q[3] ] ] )
48,595
def test(configuration): """ test loop :param configuration: the config file :return: """ analytical_ada_in_module = net.AdaptiveInstanceNormalization() encoder = net.get_trained_encoder(configuration) decoder = net.get_trained_decoder(configuration) pretrained_model_path = configur...
48,596
def print_results(candidate_names, win_probs, vote_for_n): """ Given list of candidate_names and win_probs pairs, print summary of the Bayesian audit simulations. Input Parameters: -candidate_names is an ordered list of strings, containing the name of every candidate in the contest we are audi...
48,597
def load_atomic(val): """ Load a std::atomic<T>'s value. """ valty = val.type.template_argument(0) # XXX This assumes std::atomic<T> has the same layout as a raw T. return val.address.reinterpret_cast(valty.pointer()).dereference()
48,598
def sample_trunc_beta(a, b, lower, upper): """ Samples from a truncated beta distribution in log space Parameters ---------- a, b: float Canonical parameters of the beta distribution lower, upper: float Lower and upper truncations of the beta distribution Returns ------...
48,599