content
stringlengths
22
815k
id
int64
0
4.91M
def fitted_model(dates, spectra_obs, max_iter, avg_days_yr, num_coefficients): """Create a fully fitted lasso model. Args: dates: list or ordinal observation dates spectra_obs: list of values corresponding to the observation dates for a single spectral band num_coefficients:...
51,000
def printProgressBar (iteration, total, prefix = '', suffix = '', length = 50, fill = '█', printEnd = "\r"): """ Author: greenstick (Stack Overflow/GitHub) Call in a loop to create terminal progress bar Parameters: iteration - Required : current iteration (Int) total - Required : t...
51,001
def example_bytes(values): """Input must be float32 np.array""" return tf.train.Example( features=tf.train.Features( feature={'dosages': _bytes_feature(values.tobytes())} ) )
51,002
def _write_svg_file( filename: str, svg_root: _SvgNamedElement, write_dir: Union[Path, str] = None, ) -> Path: """Format the svg then write the svg to a file in write_dir.""" # Add a credit comment at top of SVG. comment = ( f"Created by https://github.com/SciTools/marketing/iris/logo/ge...
51,003
def _build_extension_download_url( extension_name: str, publisher_name: str, version: str ) -> str: """ Build the download url for the given parameters. Just a shortcut for the string formatting. :param extension_name: Desired extension name. :type extension_name: str :param publisher_name:...
51,004
def sortedEig(X,M=None,k=None, lambda0=0): """ Return the k largest eigenvalues and the corresponding eigenvectors of the solution to X*u = b*M*u Inputs: X: matrix M: matrix k: (int) if k is None, return all but one. lambda0: (float) regularization parameter to ensure posit...
51,005
def _fourier_transform_multi_fermionic_mode( n: int, amplitude: complex, modes: List[int]) -> np.ndarray: """Fermionic Fourier transform of a multi Fermionic mode base state. Args: n: State length, number of qubits used. amplitude: State amplitude. Absolute value must be equal to 1. ...
51,006
def get_metric_parser(op): """Return a function which can parse a line with this operator.""" return { OP_START_TIMER: parse_timer, OP_STOP_TIMER: parse_timer, OP_NAMED_EVENT: parse_named_event, OP_GAUGE: parse_gauge, }[op]
51,007
def parse_division(l, c, line, root_node, last_section_node): """ Extracts a division node from a line :param l: The line number (starting from 0) :param c: The column number :param line: The line string (without indentation) :param root_node: The document root node. :return: tuple(last...
51,008
def diff_eqs(INP, t): """The main set of equations""" Y = np.zeros((2)) V = INP Y[0] = gamma * (N0 - V[0]) - tau * V[1] Y[1] = ( tau * (n - 1) * (n * V[0] - V[1]) * V[1] / (n * V[0]) + gamma * (n * N0 - n * V[0] - V[1]) - tau * V[1] - tau * (n - 1) * V[1] * V[1] / (n ...
51,009
def register(): """ Функция регистрации пользователя :return: Страницы Login или Register """ if request.method == "POST": # Достаем из формы данные пользователя username = request.form["FirstName"] lastname = request.form["LastName"] email = request.form["Email"] ...
51,010
def play_loop(wav: str, event: Event) -> None: """Play wav file forever.""" while not event.is_set(): playsound(wav)
51,011
def get_detectron2_current_version(): """Version is not available for import through Python since it is above the top level of the package. Instead, we parse it from the file with a regex.""" # Get version info from detectron2 __init__.py version_source = (Path(__file__).parents[2] / "detectron2" / ...
51,012
def accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None): """Accuracy classification score. In multilabel classification, this function computes subset accuracy: the set of labels predicted for a sample must *exactly* match the corresponding set of labels in y_true. Read more in the...
51,013
def aspect_ratio(bbox, ratios): """ Enumerate box for each aspect ratio. Args: bbox (:py:class:`BBox2D`): 2D bounding box. ratios (:py:class:`list`): list of int/float values. """ cx, cy = bbox.center() w, h = bbox.w, bbox.h size = w * h ratios = np.asarray(ratios, dtyp...
51,014
def str2bool(value): """ Convert CLI args to boolean :param str value: :return bool: """ if value.lower() in ("yes", "true", "t", "y", "1"): return True elif value.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError("Boolean value...
51,015
def delete_bundles(uuids, force, recursive, data_only, dry_run): """ Delete the bundles specified by |uuids|. If |force|, allow deletion of bundles that have descendants or that appear across multiple worksheets. If |recursive|, add all bundles downstream too. If |data_only|, only remove from the bu...
51,016
def layernorm_cx(cx, w_in): """Accumulates complexity of layernorm into cx = (h, w, flops, params, acts).""" h, w, flops, params, acts = cx["h"], cx["w"], cx["flops"], cx["params"], cx["acts"] params += 2 * w_in return {"h": h, "w": w, "flops": flops, "params": params, "acts": acts}
51,017
async def _get_privileges(user_id: int, chat_id: int) -> Privileges: """ Check user access :param user_id: user id :param chat_id: access chat id :return: privileges """ bot = Bot.get_current() chat_member = await bot.get_chat_member(chat_id, user_id) if chat_member.is_chat_admin(): ...
51,018
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Random binary sensor.""" name = config.get(CONF_NAME) device_class = config.get(CONF_DEVICE_CLASS) async_add_entities([RandomSensor(name, device_class)], True)
51,019
def test_iterate_functional(receiver_and_sender: ReceiverAndSender): """The `for` loop construct can iterate by messages in queue.""" receiver, sender = receiver_and_sender sent_commands = [Command.RIGHT, Command.FORWARD, Command.LEFT, Command.JUMP] sender.send_many(sent_commands) # We have to li...
51,020
def _get_project_permissions(user, gl_project): """Return the user's access level for the given project.""" permissions = gl_project.attributes["permissions"] access_level = max( [x[1].get("access_level", 0) for x in permissions.items() if x[1]] ) current_app.logger.debug( "access le...
51,021
def sso_login_url(service): """Get SSO login url for service""" app_config = current_app.config login_host = app_config.get('SSO').get('HOST') sso_redirect_url = app_config.get(f'SERVER_{service}_DOMAIN_NAME') query = urlencode({ 'service': service, 'redirect_url': f'https://{sso_red...
51,022
def test_backup_cron_job(host): """Check backup cron job""" f = host.file("/var/spool/cron/crontabs/root") assert "/usr/local/bin/backup-influxdb.sh" in f.content_string
51,023
def check_for_commit(repo_path, commit): """Checks a directory for a specific commit. Args: repo_path: The name of the directory to test for the commit. commit: The commit SHA to check for. Returns: True if directory contains that commit. """ # Check if valid git repo. if not os.path.exists(o...
51,024
def test_task_info_iterater(manage, task_info_list, expected_result): """Test task_info_iterater, we can get a expected result.""" data = manage.task_info_iterater(task_info_list) assert data == expected_result
51,025
def get_config(): """Default configuration for the Harvest level.""" config = config_dict.ConfigDict() # Basic configuration. config.individual_observation_names = ["RGB"] config.global_observation_names = ["WORLD.RGB"] # Lua script configuration. config.lab2d_settings = { "levelName": # ...
51,026
def cos(z): """ 函数返回 ``z`` 的余弦值 """ pass
51,027
def evaluate_regression_error(predicted_output, true_output, norm=norms.euclidean_2): """Calculate the error with respect to a norm of regression output. Parameters ---------- predicted_output : numpy.ndarray The predictions made by the classifier. true_output...
51,028
def raise500(message=None): """ Sorry, an error has occurred. """ content = tags.h1()['Internal Server Error'] content += tags.hr() content += tags.p()['Sorry, an error has occurred:'] if(message): content += tags.strong()[message] raise web.HTTPStatus('500 Internal Server Error', [('Content-Type', 'text/html...
51,029
def test_new_signal(): """A signal takes an optional name and starts without any receivers""" x = accordian.Signal(name="x") anon = accordian.Signal() assert x.name == "x" assert anon.name is None assert x.receivers == anon.receivers == []
51,030
def quality_prediction(data): """Outputs the mean absolute error and the confusion matrix""" for key in data: confusion_results = list() mae_results = list() features = data[key][0] target = data[key][1] params = data[key][2] estimator = SVR(**params, kernel='...
51,031
def classify(character: str) -> int: """String classifier.""" if character.isupper(): return StringType.UPPER if character.islower(): return StringType.LOWER if character.isnumeric(): return StringType.NUMERIC return StringType.OTHER
51,032
def getGold(session, city): """ Parameters ---------- session : ikabot.web.session.Session city : dict Returns ------- gold : int """ url = 'view=finances&backgroundView=city&currentCityId={}&templateView=finances&actionRequest={}&ajax=1'.format(city['id'], actionRequest) dat...
51,033
def _iter_but_not_str_or_map(maybe_iter): """Helper function to differ between iterables and iterables that are strings or mappings. This is used for pynads.concrete.List to determine if an iterable should be consumed or placed into a single value tuple. """ return (isinstance(maybe_iter, Iterable) ...
51,034
def rclone_logs(conf): """ Sync logs folder from Google Drive. """ res = subprocess.run( './rclone_logs.sh "{}"'.format(conf.get('remote_logs_path')), capture_output=True, shell=True, check=True) stdout = res.stdout.decode('unicode-escape', errors='ignore').strip() stderr = res.stder...
51,035
def interrogate_decision_tree(wxtree): """ Obtain a list of necessary inputs from the decision tree as it is currently defined. Return a formatted string that contains the diagnostic names, the thresholds needed, and whether they are thresholded above or below these values. This output is used to cr...
51,036
def script_resolve_name(script_name, name): """ Name resolver for scripts. Supports ROS_NAMESPACE. Does not support remapping arguments. @param name: name to resolve @type name: str @param script_name: name of script. script_name must not contain a namespace. @type script_name: str ...
51,037
def offbyKExtra(s1,s2,k): """Input: two strings s1,s2 and integer k Process: to check if number of extra characters in s2 as compared to s1 (or vice versa) is equal to k Output: return True when above condition is met otherwise return False""" flag=0 extra1='' if len(s1)>len(s2): ...
51,038
def collect(basepath, exclude=None, processPlugins=True): """ Collects all the packages associated with the inputted filepath. :param module | <module> :return ([<str> pkg, ..], [(<str> path, <str> relpath), ..] data) """ if exclude is None: exclude = ['.py', '.pyc', '...
51,039
def Optimizer(Efunc,x0,method='L-BFGS-B',jac=None,optns={}): """ Efunc(x,count) See the scipy.optimize.minimize manual for options """ const.CONSOLEMESSAGE('Entered in lib.Optimizer') methlst=['Nelder-Mead','Powell','CG','BFGS','Newton-CG','Anneal','L-BFGS-B', 'TNC', 'C...
51,040
def plot_feature_calibrator(model_graph, feature_name, plot_submodel_calibration=True, font_size=12, axis_label_font_size=14, figsize=None): """Plots feature calibrator(s) extrac...
51,041
def main(): """ Command-line interface """ args = parse_args() outfile = open('{}.{}'.format(args.outfile, my_rank), 'w') insfile = open('{}.{}'.format(args.insfile, my_rank), 'w') for i, (h, s) in enumerate(iter_fasta(args.infile)): if i % nprocs != my_rank: continue ...
51,042
def calc_reg_cdd( temperatures, t_base_cooling, model_yeardays, crit_temp_min_max=False ): """Calculate CDD for every day and daily yd shape of cooling demand Arguments ---------- temperatures : array Temperatures t_base_cooling : array Base tempe...
51,043
def get_number_of_polymorphic_sites(pileup): """ # ======================================================================== GET NUMBER OF POLYMORPHIC SITES PURPOSE ------- Returns the number of polymorphic sites. INPUT ----- [PILEUP] [pileup] A Pileup object, which rep...
51,044
def test(sess, evaluate, ph, dataset, testmodel): """Apply the models.""" ## word model acc = Accuracies() out_sentences = [] results_w = [] for f_word in dataset.batches: batch_values, out_logits_w_out_w = sess.run( [testmodel.predictions_w, testmodel.out_logits_w], feed_dict={ph.inputs...
51,045
def write_items(entities, file=sys.stdout): """Write the items of the dictionary in the specified file.""" # The keys in the generated dictionary should be sorted # in a case-insensitive way, however, when two keys are equal, # the uppercase version should come first so that the result # looks like:...
51,046
def print_models(unprinted_designs, completed_models): """ Simulate printing each design, until none are left. Move each design to completed_models after printing. """ while unprinted_designs: current_design = unprinted_designs.pop() # Simulate creating a 3D print from the design. ...
51,047
def _compile_rules(rules_file, externals, cur_logger): """ Saves Yara rule content to file, validates the content with Yara Validator, and uses Yara python to compile the rule set. Args: rules_file: Yara rule file content. Returns: Compiled rules, compiled rules md5. """ tr...
51,048
async def hello(request): """Test webserver request.""" return web.Response(text="Hello, world")
51,049
def delete_unwanted(wanted: Set[PathLike], folder: PathLike, need_permission: bool=True) -> int: """ Deletes all Unwanted files in a folder. Returns amount of deleted files """ todelete = [] for path in listdir(folder): path = realpath(join(folder,path)) if path not in wanted: ...
51,050
def http_method_and_assert(with_httpsession: [ HttpSession.get, HttpSession.head, HttpSession.put, HttpSession.post, HttpSession.patch, HttpSession.options, HttpSession.delete ], assert_result_dict: dict): """ :param with_httpsession: use to get locust httpsession data :param assert_result_dict: use...
51,051
def user_save(form, is_patient=False, is_office=False): """Function saving the user to the database.""" user = form.save(commit=False) # The account is not active until the user activates it. user.is_active = False user.is_patient = is_patient user.is_office = is_office user.save() retur...
51,052
def int_divmod(context, builder, ty, x, y): """ Integer divmod(x, y). The caller must ensure that y != 0. """ if ty.signed: return int_divmod_signed(context, builder, ty, x, y) else: return builder.udiv(x, y), builder.urem(x, y)
51,053
def initial_state(layer, dimensions=None): """ Initalizes the recurrence relation with an initial hidden state if needed, else replaces with a "None" to tell Theano that the network **will** return something, but it does not need to send it to the next step of the recurrence """ if dimension...
51,054
def lin_smooth(x, window_len=15, window='hanning'): """ Smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that tr...
51,055
def generator(samples, batchSize=32): """ Generate the required images and measurments for training """ num_samples = len(samples) while 1: # Loop forever so the generator never terminates samples = sklearn.utils.shuffle(samples) for offset in range(0, num_samples, batchSize): ...
51,056
def create_dataset_json(id, version, met_file, ds_file): """Write dataset json.""" # get metadata with open(met_file) as f: md = json.load(f) # build dataset ds = { 'creation_timestamp': "%sZ" % datetime.utcnow().isoformat(), 'version': version, 'label': id, ...
51,057
def product_details(request, id): """ The view rendering the page for one selected product and all of its details """ selected_product = get_object_or_404(Product, id=id) # get existing number of views, increment and update model number = selected_product.num_of_views + 1 Product.objects.fi...
51,058
def compute_colors_for_labels(labels): """Simple function that adds fixed colors depending on the class """ palette = np.array([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1, 1]) colors = labels[:, None] * palette colors = (colors % 255).astype("float") colors /= 255 colors[:, -1] = 1 return colors
51,059
def set_log_level(logger, debug): """Set log level based on debug state.""" if debug: os.environ["HYPERGLASS_LOG_LEVEL"] = "DEBUG" base_logger("DEBUG") if debug: logger.debug("Debugging enabled") return True
51,060
def vms_ajax_revoke_ip(request, vm_id, template_name='generic/form.html', form_class=RevokeIPForm): """ Ajax view for detaching elastip IP from a virtual machine. """ rest_data = prep_data({'vm': ('user/vm/get_by_id/', {'vm_id': vm_id})}, request.session) if request.method == 'POST': form =...
51,061
def make_message_hash(msg, include=(), exclude=()): """ Returns hashcode for ROS message, as a hex digest. @param include message fields to include if not all, as [((nested, path), re.Pattern())] @param exclude message fields to exclude, as [((nested, path), re.Pattern())] """ hasher = ...
51,062
def threadloop( loclist ): """ threadloop( loclist ) -> None This manages the threads. loclist is a list of files to get, like ['http://www.foo.com/here/one.html', 'http://www.bar.com/there/two.html'] It'll spawn threads up to the global var MAXTHREAD to grab these files. """ while 1: if loclist ...
51,063
def non_overlap_df(input_df: pd.DataFrame) -> pd.DataFrame: """ Args: input_df: DataFrame with possibly overlapping calls Returns: a DataFrame object with non-overlapping calls (after merge). """ non_overlap = [] for file_name, file_df in input_df.groupby(by='filename'): file_df...
51,064
def benchmark_last_result(project,benchmark): """ Get latest benchmark result from Victoria Metrics Returns "-1" if result not found """ query = f"last_over_time(parity_benchmark_common_result_ns{{project=\"{project}\",benchmark=\"{benchmark}\"}}[1y])" query_result = prometheus_client.custom_que...
51,065
def get_lambda_config(module, aws): """ Returns the lambda function configuration if it exists. :param module: Ansible module reference :param aws: AWS client connection :return: """ client = aws.client('lambda') # set API parameters api_params = dict(FunctionName=module.params['f...
51,066
def standard_deviation(lst, population=True): """Calculates the standard deviation for a list of numbers.""" num_items = len(lst) mean = sum(lst) / num_items differences = [x - mean for x in lst] sq_differences = [d ** 2 for d in differences] ssd = sum(sq_differences) if population is True...
51,067
def solve(global_step): """add solver to losses""" # learning reate lr = _configure_learning_rate(82783, global_step) optimizer = _configure_optimizer(lr) tf.summary.scalar('learning_rate', lr) # compute and apply gradient losses = tf.get_collection(tf.GraphKeys.LOSSES) loss = tf.add_n(...
51,068
def group_points_into_lines(edges, x_coords, y_coords, x_size=10, y_size=3): """ Группирует отдельные точки в линии при помощи функции connect_line :param edges: :param x_coords: :param y_coords: :param x_size: :param y_size: :return: """ point_dict = {(x_, y_): i for i, (x_, y_)...
51,069
def extension(ctx): """Manage vcd-cli extensions. \b Description Manages commands added to vcd-cli. \b New commands can be added to vcd-cli as Python modules. The module containing the commands implementation needs to be present in the Python path. \b Examples vcd pr...
51,070
def start(image): """Function to find start point of the Non - White pixel""" for i in range(image.shape[0]): if 0 in image[i]: return i
51,071
def bench_merge_pandas(**kwargs) -> Dataset: """Merge benchmark for pandas.""" import pandas as pd # Fixed parameters which apply to all of the trials in this benchmark. warmup_iters = 1 iters = 5 # Setup parameters. rng_seeds = [12345] left_key_unique_counts = [100] rig...
51,072
def download_plot_analyses_to_txt(request, analyses): """Download plot data for given analyses as CSV file. Parameters ---------- request HTTPRequest analyses Sequence of Analysis instances Returns ------- HTTPResponse """ # T...
51,073
def create_package(source=None, manifest=None, project_id=None, auth_token=None): """ Upload a package manifest """ if manifest is None: if source is None: raise SaltInvocationError( "create_or_update_package requires either source or manifest" ) ...
51,074
def get_default_autodist(): """Get the AutoDist object the scope of which you are in.""" global _DEFAULT_AUTODIST return _DEFAULT_AUTODIST.get(os.getpid(), None)
51,075
def ip4_bytes_to_str(ip_bytes): """Convert ip address from byte representation to 127.0.0.1.""" return "%d.%d.%d.%d" % unpack_ipv4(ip_bytes)
51,076
def test_onehot_df(): """ Check level ids from one-hot """ df = pd.DataFrame({'target': [0, 0, 1, 1, 2, 3, 0]}) mapper = DataFrameMapper([(['target'], OneHotEncoder())], df_out=True) transformed = mapper.fit_transform(df) cols = transformed.columns assert len(cols) == 4 assert cols[0...
51,077
def BuildTelemax(x: int, c: int) -> str: """ utility fct to build Telemax Pointage """ msg = '123456MAC:4c24e9870203PROT005170817100*Q:' msg += str(x + c + 1).zfill(6) msg += '9103' msg += '0071' msg += '0093' msg += '2 ' msg += '0' # msg += 'xx' msg += '10020100^1*' ...
51,078
def renameFileName(fileName, toAdd): """ rename a fileName. Modify the basename of a path string with a given string. Example modify 'data.pk' to 'data_sample.pk'. Parameter : fileName : string relative path to fileName toAdd : strin...
51,079
def create_ephemeral_key_pair(curve_type: str) -> Tuple[PublicKey, SharedKeyGenerator]: """Facilitates ECDH key exchange.""" if curve_type != "P-256": raise NotImplementedError() key_pair = create_new_key_pair(curve_type) def _key_exchange(serialized_remote_public_key: bytes) -> bytes: ...
51,080
def get_unlisted_livestreams_by_username(username: str) -> Dict[str, Any]: """Get a user's unlisted livestreams from their username. Args: username (str): The user's username. Returns: Dict[str, Any]: The unlisted livestream. """ items = "user_snowflake, start_date, title, descript...
51,081
def save_images(originalA, generatedB, recosntructedA, originalB, generatedA, reconstructedB, path): """ Save images """ fig = plt.figure() ax = fig.add_subplot(2, 3, 1) ax.imshow(originalA) ax.axis("off") ax.set_title("Original") ax = fig.add_subplot(2, 3, 2) ax.imshow(generate...
51,082
def write_to_txt_file(): """ Rules: - Undirected graph (ie. If I am friends with you, you must be friends with me; Otherwise we are not friends) - A node cannot connect to itself (ie. You can't be friends with yourself) - A node must have at least one connection (ie. You must have at least one ...
51,083
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Add a weather entity from mapped location.""" fcst_coordinator = hass.data[DOMAIN][entry.entry_id]["fcst_coordinator"] if not fcst_coordinator.data: return cur_coordinator = hass.data...
51,084
def parse_sync_agent_forwarder_id(json): """ Extract the sync agent forwarder id from the get response of LearningLocker. :param json: JSON statement from the get response. :type json: dict(str, list(dict(str, str)) :return: The statement forwarder id from the sync agent. :rtype: str """ ...
51,085
def generate_lineal_parameter(parameter_values): """Generate parameters list for lineal parameter type.""" initial_value = parameter_values['initial_value'] final_value = parameter_values["final_value"] interval = parameter_values["interval"] param_options = numpy.arange( initial_value, ...
51,086
def _create_warehouse(cr, registry): """ This hook is used to add a warehouse on existing companies when module stock is installed. """ env = api.Environment(cr, SUPERUSER_ID, {}) company_ids = env['res.company'].search([]) company_with_warehouse = env['stock.warehouse'].search([]).mapped('comp...
51,087
def get_plugin_arguments(plugin_name): """Gets plugin arguments, as a dict of version to argument list.""" plugin = plugins_base.PLUGINS.get_plugin(plugin_name) versions = plugin.get_versions() return {version: plugin.get_image_arguments(version) for version in versions}
51,088
def _h5set(store, grp, key, value, path=None): """Set a key in an h5py container. This method recursively converts Mappings to h5py groups and transparently handles None values. """ import h5py import numpy # h5py depends on numpy, so this is safe. path = path + "/" + key if path else key...
51,089
def to_snake_case(s): """Convert a string to snake-case format Parameters ---------- s: String String to convert to snake-case Returns ------- String Snake-case formatted string Notes ----- Adapted from https://gist.github.com/jaytaylor/3660565 Examples ...
51,090
def get_var(name, program=None): """ Get a variable by name from the global block of a program Args: name(str): name of the variable program(Program|None): program object. If None, default_global_program() will be used. Returns: Variable """ if program is No...
51,091
def _update_cluster_config(cluster, session=None, user=None, **kwargs): """Update a cluster config.""" check_cluster_editable(cluster, user=user) return utils.update_db_object( session, cluster, **kwargs )
51,092
def read_file(file_path="data/short.list"): """ Reads file, short.list by default. """ data = "" with open(file_path, "r", encoding="utf8", errors="ignore") as file: data = file.read().split("\n")[14:-1] return tuple(set(data))
51,093
def inv_tabs(r): """ Add an expandable set of Tabs for a Site's Inventory Tasks @ToDo: Make these Expand/Contract without a server-side call """ settings = current.deployment_settings if settings.get_org_site_inv_req_tabs() and \ current.auth.s3_has_permission("read", "inv_inv_i...
51,094
def sample(lnprobs, temperature=1.0): """ Sample an element from a categorical distribution :param lnprobs: Outcome log-probabilities :param temperature: Sampling temperature. 1.0 follows the given distribution, 0.0 returns the maximum probability element. :return: The index of the sampled e...
51,095
def test_Fnm(kp): """Tests the function that returns a partial matrix element for :math:`n=n` and :math:`n=m` cases. """ from basis.evaluate import _Fnm cases = glob("tests/model/Fnm.*.dat") for case in cases: model = loadtxt(case) for i in range(len(model)): n, m...
51,096
def get_submit_input_metadata(body): """ Extract relevant metadata from the body message included with a submit input action. :param body: (dict) the body of the json payload, including details about the message and the button clicked :returns: user_id (str), the user who cl...
51,097
def test_validate_new_df(mocker, table): """Осуществляется проверка на уникальность и согласованность данных.""" mocker.patch.object(base, "check_unique_increasing_index") mocker.patch.object(base, "check_dfs_mismatch") table._validate_new_df(mocker.sentinel) base.check_unique_increasing_index.ass...
51,098
def connection_is_established(): """ Function to check if a connection to the remote server has been established """ return (not _remote_client is None)
51,099