content
stringlengths
22
815k
id
int64
0
4.91M
async def get_snapshot(request): """ get list of available snapshots :Example: curl -X GET http://localhost:8081/foglamp/snapshot/category curl -X GET http://localhost:8081/foglamp/snapshot/schedule When auth is mandatory: curl -X GET http://localhost:8081/foglamp/snaps...
5,298,900
def score_sig_1A(sim, est_distrib): """ euclidian norm between normalized trinucleotide context counts (empirical), and the reconstituted profile """ raw_data_distrib = np.zeros(96) val, c = np.unique(sim.T, return_counts=True) raw_data_distrib[val.astype(int)] = c raw_data_distrib = raw...
5,298,901
async def test_position_template_with_entity_id(opp, mqtt_mock): """Test position by updating status via position template.""" assert await async_setup_component( opp, cover.DOMAIN, { cover.DOMAIN: { "platform": "mqtt", "name": "test", ...
5,298,902
def problem_default_script(request, script_name: str): """ Function to provide the facility to download the default compilation or test script. :param request: the request object used :type request: HttpRequest :param script_name: name of the script - one of `compilation_script` or `test_script...
5,298,903
def permission_to_edit_page(request, page, context={}): """Calls user.permission_to_edit_page() on the user in the request, or returns False if no user in the request.""" if hasattr(request, 'user') and request.user.is_authenticated(): profile = get_profile(request.user) if profile: ...
5,298,904
def is_admin_user(): """判断是否是管理员用户分配不同的逻辑""" # 访问管理员登录页面,不需要拦截处理 if request.url.endswith('/admin/login'): pass else: # 每一次请求之前都进行拦截判断处理 # 1.用户id user_id = session.get("user_id") # 2.管理员标志位 is_admin = session.get("is_admin", False) # 如果用户没有登录,或者登录...
5,298,905
def ecdf_formal(x, data): """ Compute the values of the formal ECDF generated from `data` at x. I.e., if F is the ECDF, return F(x). Parameters ---------- x : int, float, or array_like Positions at which the formal ECDF is to be evaluated. data : array_like One-dimensional a...
5,298,906
def AverageOverlap(l1, l2, depth = 10): """Calculates Average Overlap score. l1 -- Ranked List 1 l2 -- Ranked List 2 depth -- depth @author: Ritesh Agrawal @Date: 13 Feb 2013 @Description: This is an implementation of average overlap measure for comparing two score (R...
5,298,907
def _view_connections_cmd(options): """ Return the post_setup hook function for 'openmdao view_connections'. Parameters ---------- options : argparse Namespace Command line options. Returns ------- function The post-setup hook function. """ def _viewconns(prob):...
5,298,908
def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(word2),inner(word3))
5,298,909
def accepts(*accepted_arg_types): """ A decorator to validate the parameter types of a given function. It is passed a tuple of types. eg. (<type 'tuple'>, <type 'int'>) Note ----- It doesn't do a deep check, for example checking through a tuple of types. The argument passed must only be typ...
5,298,910
def trigger_to_dict(trigger: Union[DateTrigger, IntervalTrigger, CronTrigger]) -> Dict: """Converts a trigger to an OrderedDict.""" data = OrderedDict() if isinstance(trigger, DateTrigger): data['trigger'] = 'date' data['run_date'] = trigger.run_date.strftime("%Y-%m-%d %H:%M:%S") elif ...
5,298,911
def info(): """Show information about the AiiDAlab configuration.""" click.echo(f"AiiDAlab, version {__version__}") click.echo(f"Apps path: {Path(AIIDALAB_APPS).resolve()}") click.echo(f"Apps registry: {AIIDALAB_REGISTRY}")
5,298,912
def run_sentiment(model, tokenizer, device): """ SECTION : sentiment DESCRIPTION 1: Running sentiment analysis using comments from 'video_comment.pkl' DESCRIPTION 2: Calling 'run_model' function to run BERT model """ # ====================== Setup ====================== # pd.options.mode.cha...
5,298,913
def fix_task_env(): """ Set up a testing environment for tasks. """ from qmt.tasks import Task import numpy as np class InputTaskExample(Task): """Simple example task. This is the first task in the chain. :param dict options: Dictionary specifying the input parts. It should be ...
5,298,914
def declare_roles(env, roles, base_role=None, meta_role=None): """Given a list of role declarations, validate them and store them in the environment""" role_names = [role.name for role in roles] if len(role_names) != len(set(role_names)): raise Exception("Cannot declare duplicate roles") # Ensu...
5,298,915
def tulostusfunktioxd(tulostettavat): """ Tulostaa pelaajan _mahtavat_ saavutukset """ try: for i, tulos in enumerate(tulostettavat): if tulos == None: continue else: print("pelikerta #{}. pvm: {}\nkenttä {}x{}, miinojen lkm: {}kpl...
5,298,916
def participants(root_dir): """ Render the participants page, which shows a directory of all the students with their forge links, blog posts, assignment links, and etc. """ yaml_dir = app_path('people', root_dir) student_data = [] for dirpath, dirnames, files in os.walk(yaml_d...
5,298,917
def test_animate_hidden_function_type(pos_history): """Tests if the hidden _animate() function returns the expected type""" fig, ax = mpl.pyplot.subplots(1, 1) ax = mpl.pyplot.scatter(x=[], y=[]) return_plot = _animate(i=1, data=pos_history, plot=ax) assert isinstance(return_plot, tuple)
5,298,918
def adjacency_list_from_adjacency_list_bipartite(old_adj_list): """ Creates the adjacency list from another adjacency list, converting the data type to integers. Method for bipartite networks. Returns two dictionaries, each representing an adjacency list with the rows or columns as keys, respectively. ...
5,298,919
def is_integer(db_type): """Return True if the database type is an integer supported type, False otherwise. """ return db_type in ACCEPTED_INTEGER_DB_TYPES
5,298,920
def add_custom_header(res): """レスポンスにカスタムヘッダーを追加する。""" res.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" res.headers["Expires"] = "0" res.headers["Server"] = "Roppo-JSON" return res
5,298,921
def render_form(): """Render form for selecting genes and samples.""" genes_options = [ {"label": gene_symbol, "value": gene_symbol} for gene_symbol in natsorted( set((tx.gene_symbol for tx in genes.load_transcripts().values())) ) ] samples_options = [ {"label...
5,298,922
def _get_table_ids( api: ThoughtSpot, *, db: str, schema: str='falcon_default_schema', table: str=None ) -> List[str]: """ Returns a list of table GUIDs. """ r = api._metadata.list(type='LOGICAL_TABLE', subtype=['ONE_TO_ONE_LOGICAL']) table_details = r.json()['headers'] guid...
5,298,923
def get_entity_heading(geopoint): """ Acquires heading based on spawn position in map. Prompts user to select lane if multiple lanes exist at spawn position. Throws error if spawn position is not on lane. Args: geopoint: [AD Map GEOPoint] point of click event Returns: lane_head...
5,298,924
def plot_face( model=None, au=None, vectorfield=None, muscles=None, ax=None, feature_range=False, color="k", linewidth=1, linestyle="-", gaze=None, *args, **kwargs ): """Function to plot facesself Args: model: sklearn PLSRegression instance au: ve...
5,298,925
def find_cell_with_tag(nb, tag): """ Find a cell with a given tag, returns a cell, index tuple. Otherwise (None, None) """ out = find_cell_with_tags(nb, [tag]) if out: located = out[tag] return located['cell'], located['index'] else: return None, None
5,298,926
def profile_to_node(src_profile): """convert source profile to graph node.""" return (src_profile['uid'], src_profile)
5,298,927
def instruction_interval_seconds(): """ returns every how many seconds there should be a check for new instructions """ if instruction_interval_overwrite is None: return float(_get_option_with_default('instruction_check_interval_time_seconds', DEFAULT_INSTRUCTION_CHECK_INTERVAL_SECONDS)) else: ...
5,298,928
def plot_nmf(NMF_object, cmaps = dict([('Asphalt','Greys'), ('Concrete', 'Greys'), ('Snow','Greys'), ('Soil', 'Oranges'), ...
5,298,929
def UpdateTimeZones(): """Updates time zones. Valid time zones are values of the kTimeZones array in timezone_settings.cc <http://goo.gl/WSVUeE>. """ cpp_code = GetChromiumSource('chromeos/settings/timezone_settings.cc') match = re.search(r'static[^\n]+kTimeZones\[\] = \{(.+?)^\}', cpp_...
5,298,930
def sample( sampler: Sampler, machine: Union[Callable, nn.Module], parameters: PyTree, *, state: Optional[SamplerState] = None, chain_length: int = 1, ) -> Tuple[jnp.ndarray, SamplerState]: """ Samples chain_length elements along the chains. Arguments: sampler: The Monte Car...
5,298,931
def purge_all(zone): """Purge all files in a zone.""" zone_id, zone_name = zone click.echo('Purge all files on zone {} ({})'.format(zone_name, zone_id)) cf.purge_all(zone_id)
5,298,932
def get_dist_usage(): """得到硬盘使用""" return psutil.disk_usage('/')
5,298,933
def set_center(data, origin, crop='maintain_size', axes=(0, 1), verbose=False, center=_deprecated): """ Move image origin to mid-point of image. Parameters ---------- data : 2D np.array the image data origin : tuple (row, column) coordinates of the image origin ...
5,298,934
def index(): """Global index for the whole application.""" golab = app.config.get('GOLAB', False) return render_template("index.html", golab = golab)
5,298,935
def print_graph(session, model, step, nn_generator): """ A helper function for printing key training characteristics. """ if nn_generator: real, fake = session.run([model.average_probability_real, model.average_probability_fake]) print("Saved model with step %d; real = %f, fake = %f" % (...
5,298,936
def compile_program(client, code): """This Functon helps to compile our source code Args: client: [description] code: source code Returns: Encoded compiled code """ compiler_response =client.compile(code) return base64.b64decode(compiler_response["result"])
5,298,937
async def make_request(model_id, message): """Make asynchronous call to model service :param model_id: str :param message: dict :return: response for the service as dict """ async with aiohttp.ClientSession(headers={'Content-Type': 'application/json'}) as session: async with session.pos...
5,298,938
def print_report_info(dataset, train_size, test_size, sensitive, contextual, expl, target, train_params, test_params, display_params, output_stream): """ Prints report information. Parameters ----------- dataset : the dataset used train_size ...
5,298,939
def plot_fig_3_4(idx, idy, f, axs, power, power_ms, l_minus, l_plus): """ Plot the figures labelled Figures 3 and 4 in our paper given the data. """ x_values = [i for i in range(1, 1 + len(power[0]))] axs[idx, idy].plot( x_values, power[0], CB_color_cycle[1], marker="...
5,298,940
def parse_args(): """parse custom arguments and set default value""" parser = argparse.ArgumentParser( description="Trim spaces at the end of every lines." ) parser.add_argument("-R", "-r", action="store_true", help="Whether to recursive") parser.add_argument("-y", "--yes", action="store_tru...
5,298,941
def _setup_storage_handlers(): """ Setup the storage handlers. Uses the ``EOXS_STORAGE_HANDLERS`` setting which falls back to the ``DEFAULT_EOXS_STORAGE_HANDLERS`` """ global STORAGE_HANDLERS specifiers = getattr( settings, 'EOXS_STORAGE_HANDLERS', DEFAULT_EOXS_STORAGE_HANDLERS ) ...
5,298,942
def poll_routing_table(device, username, password, ssh_port): """Calls polling routing table""" GetRoutes.RoutingIos(device, username, password, ssh_port)
5,298,943
def load_image(img_path, df_info, reduce_factor=1): """ Load image and make sure sizes matches df_info """ image_fname = img_path.rsplit("/", -1)[-1] W = int(df_info[df_info.image_file == image_fname]["width_pixels"]) H = int(df_info[df_info.image_file == image_fname]["height_pixels"])...
5,298,944
def feature(self): """Check misc cases for frame clause. """ for scenario in loads(current_module(), Scenario): Scenario(run=scenario, flags=TE)
5,298,945
def test_vif_process(): """ Verify the results of processing set of frames for a given tracker """ try: trackers = init_tracker() # vif = VIF() print(trackers[0].getHistory()) # vif.process(trackers[0].getHistory()) assert 1 except: assert 0
5,298,946
def mult(v1, m): """multiplies a vector""" return (v1[0]*m,v1[1]*m)
5,298,947
def linear_function_fa(A, W, B, b=None): """An alias for using class :class:`LinearFunctionFA`. Args: (....): See docstring of method :meth:`LinearFunctionFA.forward`. """ # Note, `apply()` doesn't allow keyword arguments, which is why we build # this wrapper. if b is None: retu...
5,298,948
def dis_ten(fea): """fea: Series""" fea_range = [fea.quantile(x) for x in np.arange(11)/10.] fea_range[0] = fea_range[0] - 0.1 fea_range = set(fea_range) fea_range = np.sort(list(fea_range)) return pd.cut(fea,fea_range,labels=np.arange(len(fea_range)-1))
5,298,949
def default_seed(): """Default numpy.random.Generator seed. Returns ------- int """ return 7
5,298,950
def get_height_variable_name(obj, variable=None): """ Determines the height variable name in the Dataset using variable coordinate information. Parameters ---------- obj : Xarray.Dataset Xarray Dataset containing data variable : string Varible name to correct Returns ...
5,298,951
def mass_metric(sat_size, sat_mass): """ This function calculates the metric for the mass of the satellite based upon the maximum allowed for its size. :param sat_size: Either 1, 1.5, 2 or 3, to correlate to CubeSat sizes of 1U, 1.5U, 2U and 3U :param sat_mass: the total mass of the satellite including ...
5,298,952
def get_electricity_generation_data(): """Read in electricity generation and fuel use by individual power plants in the US for 2015. :return: dataframe of electricity generation and fuel use values """ data = pkg_resources.resource_filename('interflow', "input_data/EIA923_genera...
5,298,953
def is_whitelist_violation(rules, policy): """Checks if the policy is not a subset of those allowed by the rules. Args: rules (list): A list of FirewallRule that the policy must be a subset of. policy (FirweallRule): A FirewallRule. Returns: bool: If the policy is a subset of one of the ...
5,298,954
def modifygroup(ctx, # Mandatory main parameter groupsnapshotid, # Optional main parameter expirationtime = None, # Optional main parameter enableremotereplication = None, # Optional main parameter snapmirrorlabel = None): """Mo...
5,298,955
def main(args): """Start the upload command and return exit status code.""" return upload_command(args.directory, args.site, args.user, args.token)
5,298,956
def silabify(text): """pyverse as a command line tool returns 3 things: \t1. The syllabified verse or word specified in the TEXT argument.\n \t2. The count of the syllables.\n \t3. The assonant and consonant rhymes.""" verso = Pyverse(text) click.echo( f""" Syllabified Text | {...
5,298,957
def get_k_mesh_by_cell(cell, kspace_per_in_ang=0.10): """ Args: cell: kspace_per_in_ang: Returns: """ latlens = [np.linalg.norm(lat) for lat in cell] kmesh = np.ceil(np.array([2 * np.pi / ll for ll in latlens]) / kspace_per_in_ang) kmesh[kmesh < 1] = 1 return kmesh
5,298,958
def remove_log(id: int) -> None: # переименовать """ Удаление выбранного элемента из log_tab по id. :param id: id удаляемого элемента в channel_tab. :return: None. """ try: if db_log_mod.search_log_by_id(id): db_log_mod.remove_log(id) if db_log_mod.search_log_b...
5,298,959
def _required_params(param_list): """ return params without a default""" # params with defaults come last for i, p in enumerate(param_list): if p.default is not Parameter.empty: return param_list[:i] # no defaults return param_list
5,298,960
def exercise(prefix="tst_polder_3"): """ Test for phenix.polder sphere radius and box buffer. """ f = open("%s.pdb" % prefix, "w") f.write(pdb_str+pdb_str_ligand) f.close() # get mtz file from model using fmodel cmd = " ".join([ "phenix.fmodel", "%s.pdb" % prefix, "high_res=2.0", "type=...
5,298,961
def write_out_email_attachments(message) -> list: """ Write out email attachments from the passed message and return the list of written files :param message: Message associated with email request :return: list of paths to attachment files """ email = message.data["email"] title = message.da...
5,298,962
def test_roundtrip_with_unconsistent_comments(): """test_roundtrip_with_unconsistent_comments. Comments badly placed should be pushed to 1 char after content """ s_input = """--- apiVersion: v1 # with comment kind: Pod metadata: name: yan_solo namespace: tatouine spec: containers: - name : f...
5,298,963
def valid_token(response): """ Checks if token is valid. """ if ('detail' in response): if (response['detail'] == 'Invalid token'): echo("The authentication token you are using isn't valid. Please try again.") return False if (response['detail'] == 'Token has exp...
5,298,964
def register(name, func, weight=0): """ Register a function to a hook. The function will be called, in order of weight, when the hook is run. :param name: The name of the hook to register too. I.e. ``pre_setup``, ``post_run``, etc. :param func: The function to register to the hook. Th...
5,298,965
def generate_applied_template( name: str = TEMPLATE_SOURCE_NAME_ARGUMENT, template_root: Path = TEMPLATE_ROOT_ARGUMENT, add_mode: Optional[AddMode] = ADD_MODE_OPTION, no_input: bool = NO_INPUT_OPTION, quiet: bool = QUIET_OPTION, ): """ Applies a template to a given location, and stores it in...
5,298,966
def test_toHTML_sampleLine_0(displayPage=False): """ create an empty htmlDoc, then render the MorhphemeGloss into it """ print("--- test_toHTML_sampleLine_0") #grammaticalTerms = open(grammaticalTermsFile).read().split("\n") grammaticalTerms = ['3A','hab','mouth'] mg = MorphemeGloss(sampl...
5,298,967
def forward_elimination_m(matrix): """Perform the forward elimination over the given matrix. This function applies a forward elimination using the selection of the main elements Arguments: matrix -- two-dimensional matrix """ ctrl_vector = matrix.sum(axis = 1) log['control vector bef...
5,298,968
def _build_treelite_classifier(m, data, arg={}, tmpdir=None): """Setup function for treelite classification benchmarking""" from cuml.utils.import_utils import has_treelite, has_xgboost if has_treelite(): import treelite import treelite.runtime else: raise ImportError("No treelit...
5,298,969
def CRUD_remote_likes(likes_dict_list: list): """ This will create Like entries into our database based on the list of like dict args: likes_dict_list - The list of like in private dict form to create from return: None """ try: for like_dict in likes_dict_list: ...
5,298,970
def name2fips(loc: Dict[str, str]) -> Dict[str, str]: """name2fips converts a dictionary with keys corresponding to geography types ("state", "msa", "county", "city"). Values are english names of locations. Note that the state must be included in each geography. It's annoying, but necessary to guarantee uni...
5,298,971
def recon_brainstem_plus_cerebellum_surface(name, mask=None, regions=None, region_id_array=_region_id_array, cortex_mask_array=_cortex_mask_array, temp=None): """Reconstruct surface of...
5,298,972
def filter_local_hams(new_hams: pd.DataFrame) -> pd.DataFrame: """ Return the subset of hams that are within 30km of Seattle downtown. Parameters ---------- new_hams : pd.DataFrame A dataframe containing new ham callsigns and email addresses. Returns ------- pd.DataFrame ...
5,298,973
def main_api(config: argparse.Namespace) -> str: """ Main API entrypoint. """ executor = Executor(config) try: return executor.execute() except ExecutorError as e: raise CLIError(e)
5,298,974
def cria_peca(peca): """ cria_peca: str -> peca Recebe um identificador de jogador (ou peca livre) e devolve um dicionario que corresponde ah representacao interna da peca. R[peca] -> {'peca': peca} """ if type(peca) != str or len(peca) != 1 or peca not in 'XO ': raise ValueError('cr...
5,298,975
def _compile_shline(shline, argv): """Return a callable to interpret argv""" # Fail fast if no input line parsed if argv is None: how = _compile_return_error() # hope crash in _parse_shline printed a message return how # Plan to call a built-in verb verb = argv[0] if argv else...
5,298,976
def get_multiple_sources(filenames, **kwargs): """ Load multiple sources at once using multprocessing Parameters: filenames=filenames kwargs: keyword arguemnts """ source_type=kwargs.get('source_type', 'source') if source_type=='spectrum': method=partial(getter_function...
5,298,977
def printAVLTree(avl, verbose = False): """Works nicely, and is elegant, but can be optimized for speed.""" print() print("In order: ", avl.inOrder(avl.getRoot())) print("Pre order: ", avl.preOrder(avl.getRoot())) print("BFS: ", avl.BFS(avl.getRoot())) print("Heights (in order):") ...
5,298,978
def bin_data(array, binning, debugging=False): """ Rebin a 1D, 2D or 3D array. If its dimensions are not a multiple of binning, the array will be cropped. Adapted from PyNX. :param array: the array to resize :param binning: the rebin factor - pixels will be summed by groups of binning (x ...
5,298,979
def basic(s, coeffs): """Performs the "standard" de Casteljau algorithm.""" r = 1 - s degree = len(coeffs) - 1 pk = list(coeffs) for k in range(degree): new_pk = [] for j in range(degree - k): new_pk.append(r * pk[j] + s * pk[j + 1]) # Update the "current" values...
5,298,980
def min_max_normalize(mri_imgs: List[np.memmap]): """ Function which normalize the mri images with the min max method Parameters ---------- mri_imgs: list of images Returns ------- list of normalized images """ for i in range(len(mri_imgs)): mri_imgs[i] -= np.mi...
5,298,981
def default_joystick_handler(btn): """ Default handler to call when the joystick is pressed and no application handler is registered """ print("Default joystick_handler", btn)
5,298,982
def check_lorentz_process(process, evaluator,options=None): """Check gauge invariance for the process, unless it is already done.""" amp_results = [] model = process.get('model') for i, leg in enumerate(process.get('legs')): leg.set('number', i+1) logger.info("Checking lorentz transformat...
5,298,983
def create_credential(account, user_name, account_password): """ Function to create new credential """ new_credential = Credentials(account, user_name, account_password) return new_credential
5,298,984
def form_stars_from_group_older_version( group_index, sink_particles, newly_removed_gas, lower_mass_limit=settings.stars_lower_mass_limit, upper_mass_limit=settings.stars_upper_mass_limit, local_sound_speed=0.2 | units.kms, minimum_sink_mass=0.01 | units.MSun, logger=None, randomseed...
5,298,985
def format_sentence_about_nodes(sentence, nodes): """ example 1: input: sentence = '%s seems(seem) dead.', nodes = ['rpi0'] output: 'Node rpi0 seems dead.' example 2: input: sentence = '%s seems(seem) dead.', nodes = ['rpi0', 'rpi1', 'rpi2'] output: 'Nodes rpi0, rpi1 and rpi2...
5,298,986
def transform_vector(t: transform, v: vec3) -> vec3: """ Apply the transform to a vector v treating the homogenous coordinate as w=0 (rotation only). """ ...
5,298,987
def test_euclidean(): """ Tests that :func:`euclidean` calculates the correct GCD. """ assert 89 == euclidean(2047, 267) assert 1 == euclidean(47, 57)
5,298,988
def _filter_no_header(paths: Iterable[Path]) -> Iterable[Path]: """Return a subset of files that do not already have a header.""" for path in paths: anchor = Path(path.anchor) remainder = str(path.relative_to(path.anchor)) for file in anchor.glob(remainder): if not _file_has_...
5,298,989
def fillout_defaults(config: Dict[str, Any]) -> Dict[str, Any]: """Fillout default values for a cluster_config based on the provider.""" from ray.autoscaler._private.util import fillout_defaults return fillout_defaults(config)
5,298,990
def update_server(DisableAutomatedBackup=None, BackupRetentionCount=None, ServerName=None, PreferredMaintenanceWindow=None, PreferredBackupWindow=None): """ Updates settings for a server. This operation is synchronous. See also: AWS API Documentation Exceptions :example: response = cli...
5,298,991
def get_system(context, system_id=None): """ Finds a system matching the given identifier and returns its resource Args: context: The Redfish client object with an open session system_id: The system to locate; if None, perform on the only system Returns: The system resource ...
5,298,992
def has_group(user, group_name): """Tests if a user belongs to a given group. Source: https://www.abidibo.net/blog/2014/05/22/check-if-user-belongs-group-django-templates/#sthash.vGVYYdzi.dpuf """ group = Group.objects.get(name=group_name) return True if group in user.groups.all() else Fals...
5,298,993
def create_matrix(dataset, column_names=None, column_roles=None, receiver=None): """Returns a new Matrix object from the provided dataset. Parameters: $dataset_parameters $receiver_parameter """ if receiver is None: receiver = Receiver() matrix = _create_matrix(dataset, co...
5,298,994
def text(name: str, defaultValue: str, label: str) -> None: """ Creates a text input widget with a given name and default value """ widgets_map[name] = defaultValue
5,298,995
def function_call(f, *args, **kwargs): """Execute the function `f` with given arguments. Intended to be used in conjunction with :func:`call`. Arguments of type :class:`ObjectId` are transparently mapped to the object they refer to. """ return f(*((get_object(arg) if type(arg) is ObjectId else ...
5,298,996
def new_flow_logs(ec2, vpc_id, log_group_name, role_arn): """ Enable VPC Flow Logs """ try: flow_logs = ec2.create_flow_logs( ResourceIds = [vpc_id], ResourceType = 'VPC', TrafficType = 'ALL', LogGroupName = log_group_name, DeliverLogsPermissionArn = role_arn ) except Cl...
5,298,997
def prime_vars(vrs): """Return `list` of primed variables from `vrs`.""" return [prime(var) for var in vrs]
5,298,998
def is_teacher_or_staff(original_function=None): """ Security decorator to detect if the user is teacher or part of the staff team. :returns: Boolean pair .. versionadded:: 0.1 """ def decorated(request, course_slug=None, *args, **kwargs): course = get_object_or_404(Course, slug=...
5,298,999