content
stringlengths
22
815k
id
int64
0
4.91M
def nutanix_hypervisor_task_results_get_command(client: Client, args: Dict): """ Poll tasks given by task_ids to check if they are ready. Returns all the tasks from 'task_ids' list that are ready at the moment Nutanix service was polled. In case no task is ready, waits 'TIMEOUT_INTERVAL' (1 second) ...
5,291,600
def concatenate(adatas, merge_var_cols=None, **kwargs): """ Extension of scanpy's native `concatenate` funcion. Allows to merge columns in `var` of the same name with same contents into a single one instead of generating col-1, col-2, ... The columns to merge need to be specified explicitly. ...
5,291,601
def parse_options(option_name: str) -> dict: """Parse a Kakoune map option and return a str-to-str dict.""" items = [ elt.split('=', maxsplit=1) for elt in os.environ[f"kak_opt_{option_name}"].split() ] return {v[0]: v[1] for v in items}
5,291,602
def downgrade_images(I_MS,I_PAN,ratio,sensor): """ downgrade MS and PAN by a ratio factor with given sensor's gains """ I_MS=np.double(I_MS) I_PAN=np.double(I_PAN) ratio=np.double(ratio) flag_PAN_MTF=0 if sensor=='QB': flag_resize_new = 2 GNyq = np.asarray([0.34, 0.3...
5,291,603
def less_equal(evaluator, ast, state): """Evaluates "left <= right".""" res = UppaalBool(evaluator.eval_ast(ast["left"], state) <= evaluator.eval_ast(ast["right"], state)) return res
5,291,604
def get_vo_oasis_managers(global_data, vo): """return OASIS Managers list for given vo, if any, else an empty list""" vos_data = global_data.get_vos_data() return safe_dict_get(vos_data, vo, "OASIS", "Managers", default=[])
5,291,605
def normalize_string(string, able=None): """ Parameters ---------- string: str able: list[str] or None, default None Returns ------- str """ if able is None: return string if "space" in able: string = re.sub(r"[\t\u2028\u2029\u00a0\u1680\u180e\u2000\u2001\u20...
5,291,606
def load_data(filename, smooth=False, filter_window=3, order=1): """ Reads the input datafile which is a multiindex pandas array generated by DeepLabCut as a result of analyzing a video. Parameters ---------- filename: string Full path of the multiindex pandas array(.h5) file as a string. ...
5,291,607
def create_function_dictionary(node): """Creates a dictionary from a node describing a FunctionDef Args: **node (:obj: `ast.FunctionDef`)**: The node to create the dictionary for Returns: A dictionary """ func_dict = { 'new_name': hex_name(node.name), 'prev_name': n...
5,291,608
def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) ret...
5,291,609
def get_p_Y_val_approx_mahalanobis(post_samples, y_mean, y_truth, cov): """Calculate the percentage of draws from the predicted distribution that encompasses the truth, for all of the examples in the validation set. Parameters ---------- post_samples : np.array of shape [n_samples, n_sightlines, Y_...
5,291,610
def parse_data_frame(data_bytes: bytearray, data_format_name: str) -> Dict[int, Any]: """Convert bytearray block from XEM buffer into formatted data. Args: data_bytes: a data block from the FIFO buffer data_format_name: a designation of how this is encoded so it can be parsed correctly Retu...
5,291,611
def test_list_base64_binary_max_length_4_nistxml_sv_iv_list_base64_binary_max_length_5_2(mode, save_output, output_format): """ Type list/base64Binary is restricted by facet maxLength with value 10. """ assert_bindings( schema="nistData/list/base64Binary/Schema+Instance/NISTSchema-SV-IV-list-bas...
5,291,612
def cmcf(vertices, faces, max_iters: int, step_size=0.05, threshold_rd=1e-3): """ cMCF implementation in Python using Pytorch See : https://arxiv.org/pdf/1203.6819.pdf :param vertices: torch.float [V, 3], vertices coordinates of the mesh in euclidean space :param faces: torch.long [F, 3], index of v...
5,291,613
def wavs_in_ranges(wavs, ranges): """Determine if wavelength is in one of the ranges given. wavs: wavelengths to check ranges: list of (lower limit, upper limit) pairs Returns ------- in_range: np.array containing True if the wavelength at the same index was in one of the ranges """ ...
5,291,614
def node_compute_accuracy(l_inferred, l_targets) -> dict: """ - l_inferred : list of tensors of shape (N_nodes_i) - l_targets : list of tensors of shape (N_nodes_i) """ return edgefeat_compute_accuracy(l_inferred, l_targets)
5,291,615
def _eval_knn(k,train_x,train_y,query_x,query_y,dist_metric,compute_loss=True): """ knn algorithm Inputs: k: (list) k[0]:lower bound of number of nearest neighbours; k[1]:upper bound of number of nearest neighbours train_x: (np.array) input training vector train_y: (np.array) input ...
5,291,616
def spherical_uniform(size, dim=3, r=1.): """ Samples points from a uniform distribution on a spherical manifold. Uniform sampling on the sphere can be achieved by sampling from a Gaussian in the ambient space of the CCM, and then projecting the samples onto the sphere. :param size: number of po...
5,291,617
def la_roots(n, alpha, mu=False): """Gauss-generalized Laguerre quadrature Computes the sample points and weights for Gauss-generalized Laguerre quadrature. The sample points are the roots of the `n`th degree generalized Laguerre polynomial, :math:`L^{\\alpha}_n(x)`. These sample points and weight...
5,291,618
def cmd_serve(args): """Serve the root directory forever. Shutdown via Ctrl+C or another killing technique. By default the local browser will be launched to view the served (hosted) site. This behavior can be changed using the `server.browse` config. Note that this built-in server is designed only...
5,291,619
def modify_coco(coco): """ :param coco: json file containing coco ground truth, loaded with coco :return: json file containing coco ground truth where each object (all sailing ships) is segmented separately """ anns = coco['annotations'] L_im = [[] for i in range(16)] idx = 0 for i in r...
5,291,620
def average_above_zero(tab): """ Brief: computes of the avrage of the positive value sended Arg: a list of numeric values, except on positive value, else it will raise an Error Return: a list with the computed average as a float value and the max value Raise: Valu...
5,291,621
def _sample_discrete_actions(batch_probs): """Sample a batch of actions from a batch of action probabilities. Args: batch_probs (ndarray): batch of action probabilities BxA Returns: List consisting of sampled actions """ action_indices = [] # Subtract a tiny value from probabilitie...
5,291,622
def get_data_dir() -> Path: """ * relative path: relative to package * Path with ~ is expanded * Absolute paths supported """ path = Path(config["global"]["datadir"].get()).expanduser() path = path if path.is_absolute() else DIR.parent / path if not path.exists(): path.mkdir(pare...
5,291,623
def first(seq: Seq[T], default=NOT_GIVEN) -> T: """ Return the first element of sequence. Raise ValueError or return the given default if sequence is empty. Examples: >>> sk.first("abcd") 'a' See Also: :func:`second` :func:`last` :func:`nth` """ try...
5,291,624
def test_new_file_size_processed_none(client): """Make request with missing file size.""" file_no_size_processed = FIRST_NEW_FILE.copy() file_no_size_processed["size_processed"] = None args = {"json": file_no_size_processed, "query_string": {"project": "file_testing_project"}} response_json = post_...
5,291,625
def se3ToVec(se3mat): """ Converts an se3 matrix into a spatial velocity vector :param se3mat: A 4x4 matrix in se3 :return: The spatial velocity 6-vector corresponding to se3mat Example Input: se3mat = np.array([[ 0, -3, 2, 4], [ 3, 0, -1, 5], ...
5,291,626
def CommentPattern(lang_id=0): """Returns a list of characters used to comment a block of code @keyword lang_id: used to select a specific subset of comment pattern(s) """ if lang_id == synglob.ID_LANG_SQUIRREL: return ['//'] else: return list()
5,291,627
def handle_exception(e: Exception, verbose: bool) -> int: """ Handle exception from a scan command. """ if isinstance(e, click.exceptions.Abort): return 0 elif isinstance(e, click.ClickException): raise e else: if verbose: traceback.print_exc() raise c...
5,291,628
def windrose( station, database="asos", months=np.arange(1, 13), hours=np.arange(0, 24), sts=datetime(1970, 1, 1), ets=datetime(2050, 1, 1), units="mph", nsector=36, justdata=False, rmax=None, sname=None, sknt=None, drct=None, valid=None, level=None, bins=...
5,291,629
def get_std(array, axis=None): """ Computes the standard deviation of an array, along a given axis. Parameters ---------- array: numpy array The array over which the operation will be done. axis : None, int Axis along which the operation will be done. Returns ---...
5,291,630
def calc_montage_horizontal(border_size, *frames): """Return total[], pos1[], pos2[], ... for a horizontal montage. Usage example: >>> calc_montage_horizontal(1, [2,1], [3,2]) ([8, 4], [1, 1], [4, 1]) """ num_frames = len(frames) total_width = sum(f[0] for f in frames) + (border_siz...
5,291,631
def getArkoudaClientLogger(name : str) -> ArkoudaLogger: """ A convenience method for instantiating an ArkoudaLogger that retrieves the logging level from the ARKOUDA_LOG_LEVEL env variable and outputs log messages without any formatting to stdout. Parameters ---------- name : str ...
5,291,632
def is_valid_file(ext, argument): """ Checks if file format is compatible """ formats = { 'input_dataset_path': ['csv'], 'output_results_path': ['csv'], 'output_plot_path': ['png'] } return ext in formats[argument]
5,291,633
async def test_no_expires(setup: SetupTest) -> None: """Test creating a user token that doesn't expire.""" token_data = await setup.create_session_token() csrf = await setup.login(token_data.token) r = await setup.client.post( f"/auth/api/v1/users/{token_data.username}/tokens", headers=...
5,291,634
def load_data(filename, kfold=3, seed=333, split='random'): """ Function to load the pressure data with stratified k fold Parameters ---------- filename : string Path to the data file. augment : bool, optional Whether or not to add random noise to the pressure data. ...
5,291,635
def test_ioclass_core_id(filesystem): """ title: Test for `core_id` classification rule description: | Test if IO to core with selective allocation enabled is cached and IO to core with selective allocation disabled is redirected to pass-through mode pass_criteria: - IO to core with...
5,291,636
def get_media_importer(): """Get an importer function for `pyglet.media.Source` resources. Given the resource subfolder and accepted extensions, return a function in the form of :py:attr:`GameModel.LAMBDA_SIG` that will only accept files in the given resource subfolder(`location`) and returns the p...
5,291,637
def test_get_remote(client): """ retrieve from DHT (this key is not on the first node -> remote search) """ assert client.get("2") == "xpto"
5,291,638
async def add_user_to_group( group_id: int, group_user_add: GroupUserAddOrRemove, db: Session = Depends(get_db)): """ Add user to group. todo: add only if not already added """ group = UserGroupsRepository(db).get(group_id) user = UserRepository(db).get(group_user_add.use...
5,291,639
def distance(pointA, pointB): """Donne la distance entre deux points Args: pointA (Point): Point A pointB (Point): Point B Returns: float: Distance entre A et B Raises: TypeError: Si A ou B n'est pas un point """ if isinstance(pointA, Point) and isinstance(pointB, Point): return sqrt((...
5,291,640
def confused(total, max_part, threshold): """Determine whether it is too complex to become a cluster. If a data set have several(<threshold) sub parts, this method use the total count of the data set, the count of the max sub set and min cluster threshold to determine whether it is too complex to becom...
5,291,641
def test_simulation(orca_session): """ Test that predicted values are correctly written to Orca. """ modelmanager.initialize() m = OLSRegressionStep() m.tables = 'obs' m.model_expression = 'a ~ b' m.fit() m.out_column = 'a_predicted' m.run() assert orca.ge...
5,291,642
def rbf_kernel_conv(X, Y, gamma, sigma, device=DEFAULT_DEVICE): """ Vectorized implementation Performs rbf kernel convolution on input distributions and hinge point grid """ N, d = X.shape if gamma is None: gamma = 1. / d if sigma is None: sigma = torch.zeros(N) if sigma...
5,291,643
def rs(axes, natom): """ rs density parameter (!!!! axes MUST be in units of bohr) Args: axes (np.array): lattice vectors in row-major, MUST be in units of bohr Returns: float: volume of cell """ vol = volume(axes) vol_pp = vol/natom # volume per particle rs = ((3*vol_pp)/(4*np.pi))**(1./3) # ...
5,291,644
def _start_streaming(terminate_condition, terminate_condition_args, shupdown_grace_period, stream_target, stream_args): """Start streaming for the stream target. """ import colorama colorama.init() try: t = threading.Thread(target=stream_target, args=stream_args) t.daemon = True ...
5,291,645
def predicted_retention(alpha, beta, t): """ Generate the retention probability r at period t, the probability of customer to be active at the end of period t−1 who are still active at the end of period t. Implementing the formula in equation (8). """ assert t > 0, "period t should be positive" ...
5,291,646
def nopeak_mask(size): """The function which generates an upper triangular matrix""" opt = Opt.get_instance() np_mask = np.triu(np.ones((1, size, size)), k=1).astype('uint8') np_mask = Variable(torch.from_numpy(np_mask) == 0).to(opt.device) return np_mask
5,291,647
def is_palindrome(s): """ Determine whether or not given string is valid palindrome :param s: given string :type s: str :return: whether or not given string is valid palindrome :rtype: bool """ # basic case if s == '': return True # two pointers # one from left, one...
5,291,648
def get_joke(name): """Gets a hysterical joke""" print(name,"...enough said.")
5,291,649
def range_to_level_window(min_value, max_value): """Convert min/max value range to level/window parameters.""" window = max_value - min_value level = min_value + .5 * window return (level, window)
5,291,650
def test_anchor_layers(): """Ensure the anchor generation is the same than tensorpack for the feature pyramidal network.""" ratios = [0.5, 1, 2] strides = (4, 8, 16, 32, 64) scales = (32, 64, 128, 256, 512) feature_maps = [np.zeros((1, shape, shape, 1)) for shape in [200, 100, 50, 25, 12]] for ...
5,291,651
def miles_distant(entity_1, entity_2): """ _miles_distant :entity_type: (airport_code, city_name) :entity_type: (city_name, city_name) """ entity_type_1, entity_value_1 = get_entity_value(entity_1) entity_type_2, entity_value_2 = get_entity_value(entity_2) if entity_type_1 == 'airport_c...
5,291,652
def type_(printer, ast): """Prints "[const|meta|...] type".""" prefixes_str = ''.join(map(lambda prefix: f'{prefix} ', ast["prefixes"])) type_id_str = printer.ast_to_string(ast["typeId"]) return f'{prefixes_str}{type_id_str}'
5,291,653
def random_feature_table_filename(invalid_data): """ Generate Random Feature Table Filename return: string containing imitation filename in ".tbl" format. """ # call random_filename, ignoring invalid_data information. return (random_filename(invalid_data)[0] + '.tbl'), global_valid_data
5,291,654
def _tensor_run_opt_ext(opt, momentum, learning_rate, gradient, weight, accum, stat): """Apply sgd optimizer to the weight parameter using Tensor.""" success = True success = F.depend(success, opt(weight, gradient, learning_rate, accum, momentum, stat)) return success
5,291,655
async def websocket_create(opp, connection, msg): """Create credentials and attach to a user.""" provider = _get_provider(opp) await provider.async_initialize() user = await opp.auth.async_get_user(msg["user_id"]) if user is None: connection.send_message( websocket_api.error_me...
5,291,656
def print_exception(*args, file=None, **kwargs): """ Print the formatted output of an exception object. """ for line in format_exception(*args, **kwargs): vtml.vtmlprint(line, file=file)
5,291,657
def split_by_quantile(data, q, env_name='Hopper-v2'): """splits the data according to the quantile q of the Dataset""" if env_name == 'MountainCar-v0': proxy_list = data['obs'][:,:,0].sum(axis=-1) / np.count_nonzero(data['obs'][:,:,0]) elif env_name == 'Hopper-v2': proxy_list = [np.sum(...
5,291,658
def get_vggm_rcnn_test(num_classes=config.NUM_CLASSES): """ Fast R-CNN Network with VGG :param num_classes: used to determine output size :return: Symbol """ data = mx.symbol.Variable(name="data") rois = mx.symbol.Variable(name='rois') # reshape rois rois = mx.symbol.Reshape(data=ro...
5,291,659
async def test_set_states(v2_server): """Test the ability to set the state of a v2 system.""" v2_server.post( ( f"https://api.simplisafe.com/v1/subscriptions/{TEST_SUBSCRIPTION_ID}" "/state?state=away" ), status=200, body=load_fixture("v2_state_away_respon...
5,291,660
def test_get_slice(mocker, con, ds): """It should return a slice of spreadsheet""" run_fetch_mock = mocker.patch.object( GoogleSheets2Connector, '_run_fetch', return_value=FAKE_SHEET ) ds = con.get_slice(ds, limit=2) assert '!1:3' in run_fetch_mock.call_args_list[0][0][0] assert ds.df.s...
5,291,661
def check_dst_drive_utilization(): """ This function checks our dst drives for utilization in excess of the limits we have set in our config file and sends us a notification in the event we exceed this utilization. """ log.debug('check_dst_drive_utilization() started') if chianas.local_p...
5,291,662
def generative(f): """ A decorator to wrap query methods to make them automatically generative. """ @wraps(f) def wrapped(self, *args, **kwargs): self = self._generate() f(self, *args, **kwargs) return self return wrapped
5,291,663
def test_certificate_cn_admin(client, authority, logged_in_admin): """Admin is exempt from CN/SAN domain restrictions.""" from lemur.certificates.schemas import CertificateInputSchema input_data = { 'commonName': '*.admin-overrides-whitelist.com', 'owner': 'jim@example.com', 'authori...
5,291,664
def get_aws_region(): """ Get the caller's AWS region from the environment variable AWS_REGION :return: the AWS region name (e.g. us-east-1) """ region = environ.get("AWS_REGION") if not region: raise EnvironmentVariableError("Missing AWS_REGION environment variable.") return region
5,291,665
def flat(list_object): """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" return sum([list(item) for item in list_object], [])
5,291,666
def test_store_user_integrityerror(mocker): """Tests the store_user function. Database commit raises an IntegrityError.""" mocker.patch('app.dbops.AppUser') mocked_db = mocker.patch('app.dbops.db') mocked_db.session.commit.side_effect = IntegrityError('foo', 'bar', 'baz') mocked_update_user = mocker...
5,291,667
def json_doc_replace(doc, pointer, value=None, search=None): """ Search and replace list element while iterating through the list and keep its index. :param doc: :param pointer: :param value: :param search: :return: """ ref = doc parts, last = validate_pointer(pointer) c...
5,291,668
def get_download_variables(dataset: str, country: str, end_date: str, config_path: str): """ Function to get downlaod variable for a particular dataset from config file This could be simplified """ # Get config variables from repository config = get_config(config_path) # Extract dataset i...
5,291,669
def get_subpattern_mutations(subpattern: dict) -> list: """Get rotated variations of given subpattern""" flattened = format_subpattern(subpattern) mutations = [flattened] for i, layers in enumerate(flattened): copied_layers = flattened[:] # copy original layers rotated = rotate_la...
5,291,670
def tokenize(text): """ Creates tokens from sentences using WordNetLemmatizer :param text: string :return: list of tokens """ tokens = word_tokenize(text) lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok = lemmatizer.lemmatize(tok).lower().stri...
5,291,671
def is_same_transform(matrix0, matrix1): """Return True if two matrices perform same transformation. >>> is_same_transform(numpy.identity(4), numpy.identity(4)) True >>> is_same_transform(numpy.identity(4), random_rotation_matrix()) False """ matrix0 = numpy.array(matrix0, dtype=numpy.floa...
5,291,672
def _run_pandoc(uploaded_file, new_file_name, file_path): """ Run pandoc and report output messages :param uploaded_file: uploaded file :param new_file_name: converted file name :param file_path: source path :param options_json: optional path to the `converti` command JSON file :return: er...
5,291,673
def command(): """Goes through the database and clears any Evidence, TrackRecord, Evaluation, Comment which were in ManyToMany rel and aren't linked to any other models. Since some tables are quite large (TrackRecord for example), it's best to run this script in a background after the `populate_histori...
5,291,674
def update_subject(case, subject): """Updates the subject of the case. Subject is a text field. """ s = """UPDATE cases SET subject=? WHERE id=?""" result = db.cursor.execute(s, (subject, case['id'])) db.connection.commit()
5,291,675
def composable(func): """ Decorates a callable to support function composition using ``|``. For example: .. code-block:: python @Composable.decorate def add1(x): return x + 1 def mult2(x): return x * 2 composed = add1 | mult2 """ return Co...
5,291,676
def hg_remote_repo(remote_repos_path: pathlib.Path): """Pre-made, file-based repo for push and pull.""" return _create_hg_remote_repo( remote_repos_path=remote_repos_path, remote_repo_name="dummyrepo", remote_repo_post_init=hg_remote_repo_single_commit_post_init, )
5,291,677
def index(): """Sign In controller""" return render_template('signin.html')
5,291,678
def q_parse_color(color): """ Convert a color string into a QColor. Parameters ---------- color : string A CSS3 color string to convert to a QColor. Returns ------- result : QColor The QColor for the given color string """ rgba = parse_color(color) if rgba is N...
5,291,679
def draw_right_hand_box(data): """ Displays the cropped image with a red box around the right hand. Parameters ---------- data : dict The input data. Returns ------- hand : numpy.ndarray The cropped image with the right hand boxed in red. """ box = data['rhb'][d...
5,291,680
def get_instance(api): """ Generate a TrelloCard instance """ return TrelloCard('card_id', api, '123', '987')
5,291,681
def nrWords(text): """Scrieti o functie care returneaza numarul de cuvinte din string. Cuvintele sunt separate de spatii, semne de punctuatie (, ;, ? ! . ). """ list = text.replace(',', ' ').replace('.', ' ').replace(';', ' ') list = list.replace('!', ' ').replace('?', ' ').split() return len(...
5,291,682
def execute(command_line, directory = None, \ print_timing_info = False, shell='/bin/bash', \ grab_output = True, ignore_exit_code = False, \ input_string = None, auto_decode=True, decode_using=sys.stdout.encoding): """Run an operating system command. This is an updated version o...
5,291,683
def check_predicate(request, p): """ Check a repoze predicate against a particular request """ try: get_log().info("Checking pred %r" % p) #get_log().info(pprint.pformat(request.environ)) p.check_authorization(request.environ) except predicates.NotAuthorizedError: rai...
5,291,684
def create_or_update_product(request, product_id): """ Implements POST /products/<id> and PUT /products/<id> """ try: user = Token.objects.get(key=request.META[AUTH_TOKEN_LABEL]).user data = get_request_data(request) tags = get_tags(request) if request.method == 'POST': # TODO Remove price and shop try...
5,291,685
def maskfalse(array: np.ndarray, mask: np.ndarray) -> np.ndarray: """ Replace False-masked items with zeros. >>> array = np.arange(10) >>> mask = np.random.binomial(1, 0.5, len(array)).astype(bool) >>> masked = maskfalse(array, mask) >>> (masked[mask] == array[mask]).all() True >>> (mask...
5,291,686
def main() -> None: """An example for the use of this module.""" window_flags = ( tcod.lib.SDL_WINDOW_RESIZABLE | tcod.lib.SDL_WINDOW_MAXIMIZED ) renderer_flags = tcod.lib.SDL_RENDERER_PRESENTVSYNC with init_sdl2(640, 480, None, window_flags, renderer_flags): console = tcod.console.C...
5,291,687
def read_file_by_line(filename) -> list: """Read the contents of the file by line :param filename: path to the file to be read :return: list with each line of the file in a different node """ return read_file(filename).splitlines()
5,291,688
def Gesamt(*args, **kwargs): """:py:obj:`~swamp.wrappers.gesamt.Gesamt` instance""" from swamp.wrappers.gesamt import Gesamt return Gesamt(*args, **kwargs)
5,291,689
def prefetch_buffer(PULP_OBI=0): """ args: PULP_OBI: Legacy PULP OBI behavior """ # local parameters # FIFO_DEPTH also controls the number of outstanding memory requests # FIFO_DEPTH > 1 -> respect assertion in prefetch controller # FIFO_DEPTH % 2 == 0 -> FIFO implementation...
5,291,690
def _RIPPER_growphase_prune_metric(rule, pos_pruneset, neg_pruneset): """ RIPPER/IREP* prune metric. Returns the prune value of a candidate Rule. Cohen's formula is (p-n) / (p+n). Unclear from the paper how they handle divzero (where p+n=0), so I Laplaced it. Weka's solution was to ...
5,291,691
def set_value(component, name, value): """ Set a variable to a component """ variable = component.variables[name] vr = [variable.valueReference] if variable.type == 'Real': component.fmu.setReal(vr, [float(value)]) elif variable.type in ['Integer', 'Enumeration']: componen...
5,291,692
def clim_regr_values(n_cascade_levels, outdir_path, n_model=0, skill_kwargs=None): """Obtains the climatological correlation values and regression parameters from a file called NWP_weights_window.bin in the outdir_path. If this file is not present yet, the values from :cite:`BPS2004` are used. Paramet...
5,291,693
def create_srpm(dist='el7'): """Create an srpm Requires that sources are available in local directory dist: set package dist tag (default: el7) """ if not RPM_AVAILABLE: raise RpmModuleNotAvailable() path = os.getcwd() try: specfile = spec_fn() spec = Spec(specfile) ...
5,291,694
def variational_loss(input, img, model, beta_ten, z=None): """ Computes negative ELBO loss with scaling beta for KL part. :param input: [mean, logarithm of the covariance diagonal] :param img: datapoints :param model: vae model for probability computations :param beta_ten: tensor with scaling p...
5,291,695
def get_collect(): """ Returns: obj (Collect) """ return Collect()
5,291,696
def rid(num): """Translate from id to rid""" return num-1
5,291,697
async def notes(p: 'Player', c: Messageable, msg: Sequence[str]) -> str: """Retrieve the logs of a specified player by name.""" if len(msg) != 2 or not msg[1].isdecimal(): return 'Invalid syntax: !notes <name> <days_back>' if not (t := await glob.players.get(name=msg[0], sql=True)): return ...
5,291,698
def revert_dict(dct): """Revert {a: [lits of b's]} to {b: [list of a's]}.""" reverted = defaultdict(list) for k, value in dct.items(): for v in value: reverted[v].append(k) verbose(f"chain_genes_data dict reverted, there are {len(reverted.keys())} keys now") return reverted
5,291,699