content
stringlengths
22
815k
id
int64
0
4.91M
def visualize_demux(base_dir, data_artifact): """ :param base_dir: Main working directory filepath :param data_artifact: QIIME2 data artifact object :return: QIIME2 demux visualization object """ logging.info('Visualizing demux...') # Path setup export_path = os.path.join(base_dir, 'dem...
8,000
def socfaker_dns_answers(): """ A list of DNS answers during a DNS request Returns: list: A random list (count) of random DNS answers during a DNS request """ if validate_request(request): return jsonify(str(socfaker.dns.answers))
8,001
def create_app(): """Create and configure and instance of the Flask Application""" app = Flask(__name__) # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('HEROKU_POSTGRESQL_COPPER_URL') app.config['SQLALCHEMY_TRACK_MODIFICA...
8,002
def bilin(x, y, data, datax, datay): # --DC """ x, y ARE COORDS OF INTEREST data IS 2x2 ARRAY CONTAINING NEARBY DATA datax, datay CONTAINS x & y COORDS OF NEARBY DATA""" lavg = ( (y - datay[0]) * data[1,0] + (datay[1] - y) * data[0,0] ) / (datay[1] - datay[0]) ravg = ( (y - datay[0]) * data[1,1] + ...
8,003
def _process_asset(trackable_asset, asset_info, resource_map): """Add `trackable_asset` to `asset_info` and `resource_map`.""" original_path_tensor = trackable_asset.asset_path original_path = tensor_util.constant_value(original_path_tensor) try: original_path = str(original_path.astype(str)) except Attri...
8,004
def slice_data(xdata, ydata, x_range): """ crops or slices the data in xdata,ydata in the range x_range on the x axis """ data = zip(xdata, ydata) sliced_data = [d for d in data if d[0] >= x_range[0] and d[0] <= x_range[1]] return array(zip(*sliced_data))
8,005
def displaySmoothness(q=1,all=1,bn=1,dc=1,du="int",dv="int",f=1,hl=1,ps="int",pw="int",po="int",rt=1,su="int",sv="int"): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/displaySmoothness.html ----------------------------------------- displaySmoothness is undoable, queryable, and NO...
8,006
def run(): """ Execute the rotation of AWS keys """ aws_profile = get_current_aws_profile() aws_credentials_file = get_aws_credentials_file() backup_aws_credentials(aws_credentials_file) aws_credentials = open_aws_credentials(aws_credentials_file) current_access_key = get_current_access_...
8,007
def main(): """ call GET /access/2/catalog/models/attributes and GET /access/2/catalog/models/referenceAttributes the /access/2/catalog/models/attributes call returns all attributes (system + custom), so we filter for only the custom attrs these start with "com.infa.appmodels.ldm. output -...
8,008
def best_low_rank(A, rank): """ Finding the best low rank approximation by SVD """ u, s, vh = np.linalg.svd(A) s = np.sqrt(s[:rank]) return u[:, range(rank)] @ np.diag(s), np.diag(s) @ vh[range(rank)]
8,009
def get_bangumi(uid: int, type_: str = "bangumi", limit: int = 114514, callback=None, verify: utils.Verify = None): """ 自动循环获取追番/追剧列表 :param callback: 回调函数 :param uid: :param type_: :param limit: :param verify: :return: """ if verify is None: verify = utils.Verify() ...
8,010
def local_cases_range(start_date='2020-06-01',end_date='2020-07-01',areaname='Hartlepool'): """calculate new cases in a time range""" try: q=DailyCases.objects.filter(areaname=areaname,specimenDate=start_date)[0] start_total=q.totalLabConfirmedCases q=DailyCases.objects.filter(areaname=areaname,specimenDate=e...
8,011
def ecal_phisym_flattables(process, produce_by_run : bool=False): """ Add the NanoAOD flat table producers. This functions adjust also the output columns. Should be called once nMisCalib has been set in the EcalPhiSymRecHitProducer """ process.load('Calibration.EcalCalibAlgos.EcalPhiSymFlatTabl...
8,012
def nx_add_prefix(graph, prefix): """ Rename graph to obtain disjoint node labels """ assert isinstance(graph, nx.DiGraph) if prefix is None: return graph def label(x): if isinstance(x, str): name = prefix + x else: name = prefix + repr(x) ...
8,013
def infected_asymptomatic_20x80(): """ Real Name: b'Infected asymptomatic 20x80' Original Eqn: b'Infected asymptomatic 20+Infected asymptomatic 80' Units: b'person' Limits: (None, None) Type: component b'' """ return infected_asymptomatic_20() + infected_asymptomatic_80()
8,014
async def test_step_reauth( hass, config, config_entry, reauth_config, setup_simplisafe, sms_config ): """Test the re-auth step (testing both username and user ID as unique ID).""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_REAUTH}, data=config ) as...
8,015
def make_forecast_json(data: str): """Generate custom forecast file in JSON format :param data: JSON string containing weather.gov data """ try: if data: # Current conditions conditions_now: str = data["properties"]["periods"][0] # Determine where in the da...
8,016
def biosample_table_data(): """Return a dictionary containing the expected values of the BioSample Table""" columns = [ "id", "BioSample_id", "BioSampleAccession", "BioSampleAccessionSecondary", "BioSampleBioProjectAccession", "BioSampleSRAAccession", "Bi...
8,017
def grid_adapter3D( out_dim=(100.0, 100.0), in_dim=(50.0, 50.0), z_dim=-10.0, out_res=(10.0, 10.0, 10.0), in_res=(5.0, 5.0, 5.0), out_pos=(0.0, 0.0), in_pos=(25.0, 25.0), z_pos=0.0, in_mat=0, out_mat=0, fill=False, ): """ Generate a grid adapter. 3D adapter from ...
8,018
def concat_dtypes(ds: Sequence[np.dtype]) -> np.dtype: """Concat structured datatypes.""" def _concat( acc: Tuple[Mapping[Any, Any], int], a: np.dtype ) -> Tuple[DTYPE_FIELDS_T, int]: acc_fields, acc_itemsize = acc fields = dtype_fields(a).throw() intersection = set(acc_f...
8,019
def repeatedly0( loader: Iterator, nepochs: int = sys.maxsize, nbatches: int = sys.maxsize ): """Repeatedly returns batches from a DataLoader.""" for epoch in range(nepochs): for sample in itt.islice(loader, nbatches): yield sample
8,020
def mutation(param_space, config, mutation_rate, list=False): """ Mutates given configuration. :param param_space: space.Space(), will give us information about parameters :param configs: list of configurations. :param mutation_rate: integer for how many parameters to mutate :param list: boolean...
8,021
def uncertainty_batch_sampling(classifier: Union[BaseLearner, BaseCommittee], X: Union[np.ndarray, sp.csr_matrix], n_instances: int = 20, metric: Union[str, Callable] = 'euclidean', n_jobs: Option...
8,022
def only_digits(raw, force_int=False): """Strips all not digit characters from string. Args: raw (str or unicode): source string. Kwargs: force_int (boolean): not to seek for dot, seek only for int value. Returns: int or float: in dependence of "raw" argument content. ...
8,023
def log_global_state(): """ Executed periodically. Requets local and global state and logs (outputs it). """ global last_log_timestamp global last_local_pcount global last_global_pcount # receive local values t_get_local_start = time.time() pcount_local = get_ecounter("pcount") ...
8,024
def namedtuple(typename, field_names, verbose=False): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args o...
8,025
def save_image(image, path, extension="tif"): """Save an image. The input image should have between 2 and 5 dimensions, with boolean, (unsigned) integer, or float. The dimensions should be in the following order: (round, channel, z, y, x). Parameters ---------- image : np.ndarray ...
8,026
def get_users(compartment_id: Optional[str] = None, external_identifier: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetUsersFilterArgs']]] = None, identity_provider_id: Optional[str] = None, name: Optional[str] = None, state: ...
8,027
def server(ctx, source, destination, station_id, max_message_per_sec, max_message_per_mmsi_per_sec, notifier): """Example: aisdownsampler server '{"type": "listen", "listen":"tcp:4711"}' '{"type": "listen", "listen":"tcp:4712"}' """ aisdownsampler.server.server( notifier = notifier, source = j...
8,028
def _jvm_import_external(repository_ctx): """Implementation of `java_import_external` rule.""" if (repository_ctx.attr.generated_linkable_rule_name and not repository_ctx.attr.neverlink): fail("Only use generated_linkable_rule_name if neverlink is set") name = repository_ctx.attr.generated_r...
8,029
def se_resnet20(num_classes: int = 10, in_channels: int = 3 ) -> ResNet: """ SEResNet by Hu+18 """ return resnet(num_classes, 20, in_channels, block=partial(SEBasicBlock, reduction=16))
8,030
def test_load_related__JSONB_objects(n): """ Test making JSONB on the server. Make objects with row_to_json() """ query = QUERY_TEMPLATE.format( # Use JSONB for nested objects AGG_FUNCTION='jsonb_agg', # Select rows as JSONB objects # Select ids needed for joining as well ...
8,031
def parallel_threaded(function): """ A decorator for running a function within a parallel thread """ def decorator(*args, **kwargs): t = ParallelThread(target=function, args=args, kwargs=kwargs) t.daemon = True t.start() return t return decorator
8,032
def Upsample(x, size): """ Wrapper Around the Upsample Call """ return nn.functional.interpolate(x, size=size, mode="bilinear", align_corners=True)
8,033
def xcode_project(**kwargs): """ Generate an Xcode project name: attr.string name of the target targets: attr.label_list bazel: attr.string path to Bazel used during Xcode builds xchammer: attr.string path to xchammer project_name: (optional) target_config: (optional) struct(target_co...
8,034
def get_user_playlists(spotipy_obj, username): """Gets and returns all Spotify playlists owned by the username specified. Parameters: spotipy_obj: Spotipy object username: Spotify username Returns: List of dictionaries, each dictionary a Spotify playlist object. """ # Gra...
8,035
def run(coro) -> Any: """ Create a new task from the given coroutine and run it until it completes. Returns the value returned by *coro*. """ ...
8,036
def test_blur_effect_channel_axis(): """Test that passing an RGB image is equivalent to passing its grayscale version. """ image = astronaut() B0 = blur_effect(image, channel_axis=-1) B1 = blur_effect(rgb2gray(image)) B0_arr = blur_effect(image, channel_axis=-1, reduce_func=None) B1_arr ...
8,037
def osu_run1(data_set="osu_run1", sample_every=4): """Ohio State University's Run1 motion capture data set.""" path = os.path.join(access.DATAPATH, data_set) if not access.data_available(data_set): import zipfile access.download_data(data_set) zip = zipfile.ZipFile(os.path.join(acce...
8,038
def package_data(pkg, root_list): """ Generic function to find package_data for `pkg` under `root`. """ data = [] for root in root_list: for dirname, _, files in os.walk(os.path.join(pkg, root)): for fname in files: data.append(os.path.relpath(os.path.join(dirname...
8,039
async def validate_ws(hass: core.HomeAssistant, data): """Validate the user input allows us to connect over WS.""" ws_port = data.get(CONF_WS_PORT) if not ws_port: return host = data[CONF_HOST] port = data[CONF_PORT] username = data.get(CONF_USERNAME) password = data.get(CONF_PASSWO...
8,040
def create(dataset, target, features=None, l2_penalty=1e-2, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'...
8,041
def argument(*name_or_flags, **kwargs): """Convenience function to properly format arguments to pass to the subcommand decorator. """ args = list() for arg in name_or_flags: args.append(arg) return args, kwargs
8,042
def get_logger(): """ Provides the stem logger. :returns: **logging.Logger** for stem """ return LOGGER
8,043
def test_raise_exception_if_rootdir_not_found(tmp_path): """Raises exception if no rootdir is found (rootdir is None).""" os.chdir(tmp_path) with pytest.raises(SystemExit): _form_backupsub_pathname()
8,044
def get_graphql_type_for_model(model): """ Return the GraphQL type class for the given model. """ app_name, model_name = model._meta.label.split('.') # Object types for Django's auth models are in the users app if app_name == 'auth': app_name = 'users' class_name = f'{app_name}.graph...
8,045
def load_image_files(container_path, dimension=(64, 64)): """ Load image files with categories as subfolder names which performs like scikit-learn sample dataset """ image_dir = Path(container_path) folders = [directory for directory in image_dir.iterdir() if directory.is_dir()] catego...
8,046
def trim_whitespace( input_file_name, output_file_name, border_width_pixels=10, convert_exe_name=DEFAULT_CONVERT_EXE_NAME): """Trims whitespace around edge of image. :param input_file_name: Path to input file (may be in any format handled by ImageMagick). :param output_file_name: Pa...
8,047
def create_calendar(year=None, month=None): """ Create an inline keyboard with the provided year and month :param int year: Year to use in the calendar, if None the current year is used. :param int month: Month to use in the calendar, if None the current month is used. :return: Returns the I...
8,048
def format_allowed_section(allowed): """Format each section of the allowed list""" if allowed.count(":") == 0: protocol = allowed ports = [] elif allowed.count(":") == 1: protocol, ports = allowed.split(":") else: return [] if ports.count(","): ports = ports.s...
8,049
def upload_image(): """ form-data: image: a jpeg picture :return: a file pathname, assigned by backend. """ if 'image' not in request.files: return '', 400 f = request.files['image'] if f.filename == '': return '', 400 if not _allowed_file(f.filename): return ...
8,050
def get_airmass(when, ra, dec): """Return the airmass of (ra,dec) at the specified observing time. Uses :func:`cos_zenith_to_airmass`. Parameters ---------- when : astropy.time.Time Observation time, which specifies the local zenith. ra : astropy.units.Quantity Target RA angle(...
8,051
def get_metadata(class_): """Returns a list of MetaDataTuple structures. """ return list(get_metadata_iterator(class_))
8,052
def get_register(regname): """ Get register value. Exception will be raised if expression cannot be parse. This function won't catch on purpose. @param regname: expected register @return register value """ t = gdb.lookup_type("unsigned long") reg = gdb.parse_and_eval(regname) return ...
8,053
def test_MultiPhaseModel_4(): """Test the eval method""" model = mod.MultiPhaseModel("a * x") model.set_value(a=1) x = np.linspace(0, 5, 6) y = np.zeros(6) model.set_data(x, y) model.eval() assert np.array_equal(model.get_profile().ycalc, x)
8,054
def create_queries(project_id, ticket_number, pids_project_id, pids_dataset_id, pids_table): """ Creates sandbox and truncate queries to run for EHR deactivated retraction :param project_id: bq name of project :param ticket_number: Jira ticket number to identify and title sandbox tab...
8,055
def getAxisValueInPercentage(axisValue:float)->int: """This function takes in an axisValue and outputs a percentage as an int"""
8,056
def test_folder_with_one_label(): """[summary] """ # Empty dir empty_dir(TEST_DIRECTORY_PATH) # Build catalog nb_labels = 1 catalog_path, label_paths, img_paths = build_catalog(TEST_DIRECTORY_PATH, nb_labels=nb_labels) # Get all ...
8,057
def test_handle_rsvp_bad_id( mock_send_reply, make_handler_params, make_time, ): """ Ensures that handle_rsvp failes correctly when the plan ID is not malformed but does not correspond to a plan. """ params = make_handler_params("rsvp not-tjs") plan = Plan("tjs", make_time(12, 30), []) ...
8,058
def div(spreadsheet: t.IO[str]) -> None: """Each row has one evenly divisible pair - each divided pair is summed.""" click.echo(str(divisor_checksum(spreadsheet)))
8,059
def load_and_estimate(file, arguments, denoise=medfilt, data=None): """Loads mean+std images and evaluates noise. Required for parallelization.""" # Pipeline for µCT data if data is not None: # Evaluate noise on data noises = np.zeros(len(metrics)) for m in range(len(metrics)): ...
8,060
def make_fig(): """ make a figure No need to close figures or clean up since the objects will be destroyed when they go out of scope """ fig = Figure() #ax = fig.add_subplot(111) # add a standard subplot # add an axes at left, bottom, width, height; by making the bottom # at 0.3, ...
8,061
def _update_from(x: Dict[str, Any], y: Dict[str, Any], attrs: Sequence[str]) -> None: """ A utility function for copying attributes from one object to another """ for attr in attrs: val = y.get(attr, None) if val is not None: x[attr] = get_val(val)
8,062
def calc_self_attn( bert_model: BertModel, protein: dict, device="cuda:0", **kwargs ): """Calculate self-attention matrices given Bert model for one protein. Args: bert_model: a BertModel instance protein: a dict object from LM-GVP formatted data (json record). device: device to...
8,063
def MakeDir(path): """Make dir, succeed if it already exists.""" try: os.makedirs(path) except OSError, e: if e.errno != errno.EEXIST: raise
8,064
def compute_median_survival_time(times, surv_function): """ Computes a median survival time estimate by looking for where the survival function crosses 1/2. Parameters ---------- times : 1D numpy array Sorted list of unique times (in ascending order). surv_function : 1D numpy array...
8,065
def TDMAsolver_no_vec(coeffs): """ TDMA solver, a b c d can be NumPy array type or Python list type. refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm and to http://www.cfd-online.com/Wiki/Tridiagonal_matrix_algorithm_-_TDMA_(Thomas_algorithm) """ a = coeffs[1:, 0] b = coef...
8,066
def aggregate_ant(data, sub_num, response_type="full"): """ Aggregate data from the ANT task. Calculates various summary statistics for the ANT task for a given subject. Parameters ---------- data : dataframe Pandas dataframe containing a single subjects trial data for the task. su...
8,067
def parse_search_after(params): """Validate search_after and return it as a list of [score, ID].""" search_pair = params.get("search_after") sort = params.get("sort") if not search_pair or not sort: return if '_' not in search_pair or len(search_pair.split("_")) != 2: return _sco...
8,068
def read_csv(filepath_or_buffer: str, usecols: List[Literal["e", "b", "a"]]): """ usage.modin: 1 """ ...
8,069
def compute_cosine_distance( features, others=None, cuda=False, ): """Computes cosine distance. Args: input1 (torch.Tensor): 2-D feature matrix. input2 (torch.Tensor): 2-D feature matrix. Returns: torch.Tensor: distance matrix. """ if others is None: if cuda: ...
8,070
def convert_dict_keys_case(obj: Any, case_style: str = CaseStyle.CAMEL): """ This function recursively changes the case of all the keys in the obj argument """ case_style = process_case_style(case_style=case_style) if isinstance(obj, (tuple, list)): return type(obj)( [conver...
8,071
def tmobilenet(lanes): """Mobilenet test template. Paramters --------- lanes : Int The number of vector lanes. """ if skip_test(): return if not is_tflite_available(): return model = get_mobilenet_model() mod, params = compile_model_to_relay(model) mod = o...
8,072
def chain_exception(new_exc, old_exc): """Set the __cause__ attribute on *new_exc* for explicit exception chaining. Returns the inplace modified *new_exc*. """ if DEVELOPER_MODE: new_exc.__cause__ = old_exc return new_exc
8,073
def wrap_class(cls, class_name, class_method_inst): """ wrap class methods with instrumentation calls """ if not cls: return for (method, method_log_args) in class_method_inst.iteritems(): fn = getattr(cls, method, None) if not fn: # Not all methods may be in all versions...
8,074
def make_input_fn(x_out, prob_choice): """Use py_func to yield elements from the given generator.""" inp = {"inputs": np.array(x_out).astype(np.int32), "problem_choice": prob_choice} flattened = tf.contrib.framework.nest.flatten(inp) types = [t.dtype for t in flattened] shapes = [[None] * len(t.sha...
8,075
def test_artifact_ungroup(element_factory): """Test removal of artifact from node.""" n = element_factory.create(UML.Node) a = element_factory.create(UML.Artifact) assert group(n, a) assert ungroup(n, a) assert not n.deployment assert not element_factory.lselect(UML.Deployment)
8,076
def url_validate(url): """ URL验证 用于登录传递URL """ regex = r'^\?next=((/\w+)*)' if isinstance(url, str) and re.match(regex, url): return url.split('?next=')[-1] return '/'
8,077
def mie_harmonics(x: np.ndarray, L: int) -> Tuple[np.ndarray]: """Calculates the spherical harmonics of the mie field. The harmonics are calculated up to order L using the iterative method. Parameters ---------- x : ndarray The cosine of the angle defined by the line passing through origo ...
8,078
def is_version_dir(vdir): """Check whether the given directory contains an esky app version. Currently it only need contain the "esky-files/bootstrap-mainfest.txt" file. """ if exists(pathjoin(vdir,ESKY_CONTROL_DIR,"bootstrap-manifest.txt")): return True return False
8,079
def session_decrypt_raw(encrypted_message, destination_key): """ Decrypts the message from a random session key, encrypted with the destination key. Superior alternative when the destination key is slow (ex RSA). """ block_size = destination_key.block_size encrypted_session_key = encrypted_...
8,080
def gef_pybytes(x): """Returns an immutable bytes list from the string given as input.""" return bytes(str(x), encoding="utf-8")
8,081
def plot_2d_morphing_basis( morpher, xlabel=r"$\theta_0$", ylabel=r"$\theta_1$", xrange=(-1.0, 1.0), yrange=(-1.0, 1.0), crange=(1.0, 100.0), resolution=100, ): """ Visualizes a morphing basis and morphing errors for problems with a two-dimensional parameter space. Parameters ...
8,082
def test_masterdata__Table__3(address_book, browser, login): """It renders no add link for any calendar user.""" browser.login(login) browser.open(browser.CALENDAR_MASTERDATA_EVENTVIEW_URL) with pytest.raises(LinkNotFoundError): browser.getLink(EVENT_VIEW_CONFIGURATION_ADD_TEXT)
8,083
def single_lut_conversion(lookup_table): """ This constructs the function to convert data using a single lookup table. Parameters ---------- lookup_table : numpy.ndarray Returns ------- callable """ _validate_lookup(lookup_table) def converter(data): if not isinst...
8,084
def signal_average(cov,bin_edges=None,bin_width=40,kind=3,lmin=None,dlspace=True,return_bins=False,**kwargs): """ dcov = cov * ellfact bin dcov in annuli interpolate back on to ell cov = dcov / ellfact where ellfact = ell**2 if dlspace else 1 """ modlmap = cov.modlmap() assert np.all...
8,085
def count_sort(data: list, log: bool=False) -> None: """Sorts a list of positive integers from least to greatest. The count sort algorithm is a type of integer sorting algorithm. It sorts a list by finding the maximum number within that list, creating a different list of that maximum size, and using th...
8,086
def _create_parameters_file(path): """ Saves an example parameters json file where the sprites and the settings are specified. :param str path: path where to save file """ settings = agglomerate.SheetSettings(_default_algorithm, _default_format) settings_dict = settings.to_dict() spri...
8,087
def find_tree_diameter(g): """ Standard awesome problem So for each node, I want to find the maximum distance to another node :param n: :param g: :return: """ # First finding the arbitary node that is maximum distance from root # DFS - First time q = deque() q.append((1,0))...
8,088
def edge_list_to_adjacency(edges): """ Create adjacency dictionary based on a list of edges :param edges: edges to create adjacency for :type edges: :py:list :rtype: :py:dict """ adjacency = dict([(n, []) for n in edge_list_to_nodes(edges)]) for edge in edges: adjacency...
8,089
def __renormalized_likelihood_above_threshold_lnlikelihood(data, thr=__thr, alpha=models.__alpha, beta=models.__beta, num_mc=models.__num_mc, **kwargs): """ only include data that is above thr, treats them all as signals, and renormalizes the likelihood so that it only covers "detectable data" """ truth...
8,090
def run(options, configfile): """Run waterpy with a model configuration file. The model configuration file contains the specifications for a model run. This command takes in the path to model configuration file. """ try: click.echo("Running model...") waterpy(configfile, options) ...
8,091
def _build_tags(model_uri, model_python_version=None, user_tags=None): """ :param model_uri: URI to the MLflow model. :param model_python_version: The version of Python that was used to train the model, if the model was trained in Python. :param user_tags: A collection o...
8,092
def test_token(current_user: usermodels.User = Depends(get_current_user)): """ Test access token """ return current_user
8,093
def student_list_prof_request(): """Return a JSON containing adding instructor requests, or raise 401 if not authorized.""" role_student = Role.query.filter_by(name='student').first() if current_user.is_authenticated and has_membership(current_user.id, role_student): list_approved = request.args.get...
8,094
def set_complete(request, id): """ Marque un ticket comme complet :param request: :param id: """ ticket = Tickets.objects.get(pk=id) ticket.complete = 1 ticket.save() return redirect('/ticket/id=%s' % id)
8,095
def parse_version_from_path(path): """Get version parts from a path name.""" path = pathlib.Path(path).absolute() version = path.name try: parts = version.split("_") ret = {} ret["major"] = try_int(parts[0]) ret["minor"] = try_int(parts[1]) ret["protocol"] = try_i...
8,096
def assign_partitions_to_actors( ip_to_parts: Dict[int, Any], actor_rank_ips: Dict[int, str]) -> Dict[int, Sequence[Any]]: """Assign partitions from a distributed dataframe to actors. This function collects distributed partitions and evenly distributes them to actors, trying to minimize dat...
8,097
async def test_dyson_set_temperature_when_cooling_mode( mocked_login, mocked_devices, hass ): """Test set climate temperature when heating is off.""" await async_setup_component(hass, DYSON_DOMAIN, _get_config()) await hass.async_block_till_done() device = mocked_devices.return_value[0] device....
8,098
def infer(test_reader, vocab_tag, use_cuda, model_path): """ inference function """ place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() exe = fluid.Executor(place) with fluid.scope_guard(fluid.core.Scope()): infer_program, feed_target_names, fetch_vars = fluid.io.load_inference_model( ...
8,099