content
stringlengths
22
815k
id
int64
0
4.91M
def retrain(saver, retrain_ckpt): """Retrain the model""" dataset = TFRecordDataset( ARGS.train_set, is_training=True, keywords=ARGS.train_keyword, num_parallel_reads=ARGS.num_parallel_reads, is_shuffle=True, is_repeat=True, batch_size=ARGS.batch_size) graph = tf.compat.v1.get_default_graph...
68,000
def remap_instruction_position(position, mtext_src, mtext_dst): """ Remap an instruction position from one mtext to a *similar* position in another. """ line_num, x, y = position line = mtext_src.lines[line_num] # the block in the source mtext where the given position resides blk_token_src ...
68,001
def load_hparams(hparams_file, out_dir): """Load hparams from an json file. Partial hparams are augmented using default values for parameters that were added after the hparams file was written. Args: hparams_file: Filename of the hparams file. out_dir: Directory where the model output will be written....
68,002
def rename_file(pdf, bibitem): """Attempt to rename pdf according to bibitem. """ year = _get_bib_element(bibitem, "year") author = _get_bib_element(bibitem, "author") if author: author = author.split(",")[0] title = _get_bib_element(bibitem, "title") elem = [i for i in (year, autho...
68,003
def write_num_test_method(bid_methodcount: Dict[str, int], out_file: Path): """ Output a LaTeX source file for the result table (numbers of methods) :param bid_methodcount: dict returned by batch_count_method(), e.g. {"Lang-28": 20} :param out_file: path to the output (LaTeX source) :return: None ...
68,004
def get_access_token(tenant_id, resource): """ Retrieve an OAuth token by sending an OAuth2 token exchange request to the local URL that the ManagedIdentity extension is listening to """ # Extract the endpoint that the ManagedIdentity extension is listening on with open(ManagedIdentityExtLis...
68,005
def f_docstring(docstring: str) -> Callable: """Bypass for f formatted docstrings.""" def decorator_doc(func: Callable) -> Callable: @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.__doc__ = docstring return wrapper return decora...
68,006
def permutation_cluster_1samp_test( X, threshold=None, n_permutations=1024, tail=0, stat_fun=None, connectivity=None, verbose=None, n_jobs=1, seed=None, max_step=1, exclude=None, step_down_p=0, t_power=1, out_type='mask', check_disjoint=False, buffer_size=1000): """Non-parametric clu...
68,007
def getOrigShape(transform): """ Creates the Orig Shape used by deformers. Args: transform (pm.nodetypes.Transform): Transform to create orig shape of. Returns: (pm.nodetypes.Mesh): Shape created. """ shape = pm.deformableShape(transform, og=True) shape = list(filter(None, ...
68,008
def get_input(): """ Ask user for inputs about event: Title, Main Topic, Distance to Location. Checks for correct types and value ranges. If not correct, restarts asking 5 times. :return: Tuple(Str, Int, Int) => "Title", [0|1], [0,infinity[ OR None (to quit App) """ attempt = 0 title, topic,...
68,009
def test_combined_status_daemon_rpc_status_error( mock_socket, mock_last_block, mock_monero_rpc, caplog ): """Check combined daemon status. Daemon RPC status is 'ERROR' due to result of Moenro RPC 'hard_fork_info'. Last block status is fine. """ last_block_result = { "block_recent": Tr...
68,010
def get_dataset(args): """ Returns train and test datasets and a user group which is a dict where the keys are the user index and the values are the corresponding data for each of those users. """ if args.dataset == 'cifar': data_dir = '../data/cifar/' apply_transform = transforms.C...
68,011
def get_roulette(archive: utils.Archive[utils.Value], num: Optional[int] = None) -> Any: """Apply a roulette tournament selection. """ if num is None: num = int(.999 + np.sqrt(len(archive))) # the following sort makes the line deterministic, and function seedable, at the cost of complexity! ...
68,012
def print_system_inventory( inventory_list, details = False, skip_absent = False ): """ Prints the system inventory list into a table Args: inventory_list: The inventory list to print details: True to print all of the detailed info skip_absent: True to skip printing absent component...
68,013
def process_puzzle_input(ext=".txt"): """ Process puzzle input """ puzzle_data = [] with open("puzzle_data_" + DAY + "_" + YEAR + ext) as f: for line in f: puzzle_data.append([x for x in line.strip()]) return puzzle_data
68,014
def parse_warnings_2019_06(raw_input_file, parsed_output_file): """This function parses the raw Coverity warnings (version 2019.06) into the SCRUB format. Inputs: - raw_input_file: Full path to the file containing raw Coverity warnings [string] - parsed_output_file: Full path to the file where ...
68,015
def run_command(args, **kwargs): """Run a command without echo, return returncode, stdout and stderr (always as string).""" kwargs.setdefault('stdout', subprocess.PIPE) kwargs.setdefault('stderr', subprocess.PIPE) if _IN_PY3: r = subprocess.run(args, universal_newlines=True, **kwargs) ...
68,016
def minimum_bounding_rectangle(points): """ Find the smallest bounding rectangle for a set of points. Returns a set of points representing the corners of the bounding box. :param points: an nx2 matrix of coordinates :rval: an nx2 matrix of coordinates """ from scipy.ndimage.interpolation im...
68,017
def main(): """ Performs the following tasks: 1. Reads input from 'input.json' 2. Parses the GroundTruth annotations and creates a dataframe 3. Saves the dataframe to S3 """ with open("input.json") as fjson: input_dict = json.load(fjson) s3_bucket = input_dict["s3_bucket"] ...
68,018
def get_mentornet_network_hyperparameter(checkpoint_path): """Get MentorNet network configuration from the checkpoint file. Args: checkpoint_path: the file path to restore MentorNet. Returns: a named tuple MentorNetNetHParams. """ if checkpoint_path and tf.gfile.IsDirectory(checkpoint_path): che...
68,019
def densenet(images, num_classes=1001, is_training=False, dropout_keep_prob=0.8, scope='densenet'): """Creates a variant of the densenet model. images: A batch of `Tensors` of size [batch_size, height, width, channels]. num_classes: the number of classes in the dataset. is_training: specifies whether or not ...
68,020
def product(li: List[int]) -> int: """Calculates the product of all the numbers in a list. doctests: >>> product([2, 1, 4]) 8 >>> product([3, 1, 4, 2, 5, 8]) 960 """ x = reduce(lambda a, b: a * b, li) return x
68,021
def is_datetime64tz_dtype( arr_or_dtype: pandas.tests.extension.decimal.array.DecimalDtype, ): """ usage.dask: 1 """ ...
68,022
def load_jupyter_server_extension(nb_server_app): """Setup the papermillhub server extension.""" web_app = nb_server_app.web_app base_url = web_app.settings["base_url"] papermill_runner = PapermillRunner( contents_manager=nb_server_app.contents_manager, log=nb_server_app.log, ) ...
68,023
def CDLDOJI(data: xr.DataArray) -> xr.DataArray: """ Doji (Pattern Recognition) Inputs: data:['open', 'high', 'low', 'close'] Outputs: double series (values are -1, 0 or 1) """ return multiple_series_call(talib.CDLDOJI, data, ds.TIME, ds.FIELD, [f.OPEN, f.HIGH, f.LOW, f.CLOSE], ...
68,024
def test_help(capsys): """analog --help prints help and describes arguments.""" with pytest.raises(SystemExit): analog.main(['analog', '--help']) out, err = capsys.readouterr() # main docstring is used as help description assert analog.main.__doc__ in out # analog argum...
68,025
def filename(N, epsilon, v0, D, Dr, phi, launch): """ Name of simulation output files. Parameters ---------- N : int Number of particles in the system. epsilon : float Coefficient parameter of potential. v0 : float Self-propulsion velocity. D : float Tran...
68,026
def generate_ifm(emit: CommandStreamEmitter, ifm: NpuFeatureMap): """Generates general IFM registers""" emit.cmd0_with_param(cmd0.NPU_SET_IFM_REGION, ifm.region) generate_addresses( emit, [cmd1.NPU_SET_IFM_BASE0, cmd1.NPU_SET_IFM_BASE1, cmd1.NPU_SET_IFM_BASE2, cmd1.NPU_SET_IFM_BASE3], ...
68,027
def check_inventory_versions(): """ Actual version color idetifier of Loaded containers Check all track items and filter only Loader nodes for its version. It will get all versions from database and check if the node is having actual version. If not then it will color it to red. """ fro...
68,028
def g2c(coordinate:tuple, pixel_unit:int) -> tuple: """ Convert pygame coordinate to cartesian coordinate. x pixel unit refers to 1 unit in cartesian coordinate system. For example: if pixel unit is 100 then 100 pixel is one unit in cartesian system coordinate: game coordinate (x,...
68,029
async def site_base(): """Return the configured site prefix. Useful for correct client-side routing.""" return conf().metador.site
68,030
def test__compile_correction_potential(): """ test varecof_io.writer.corr_potentials.compile_correction_pot """ varecof_io.writer.corr_potentials.compile_corr_pot( MAKE_PATH)
68,031
def filter_labels( label_dict: Dict[str, np.ndarray], filter_dict: Dict[str, List[int]] ) -> Dict[str, np.ndarray]: """Filter out examples from arrays based on specified labels to filter. The most common use of this method is to remove examples whose gold label is unknown (marked with a -1) or examples...
68,032
def get_view_report_fields_list(report: str) -> Sequence[Dict[str, Any]]: """Gets the fields in the report month view :param report: the kind of the report :returns: list of fields in this report's month view""" report_fields = REPORT_TYPE_SWITCHER[report[:2]]['report_fields'] fields = [] for f...
68,033
def parse_options() -> Namespace: """ Parse command line arguments and liftoff configuration. """ opt_parser = OptionParser( "liftoff-status", ["experiment", "all", "timestamp_fmt", "results_path"] ) return opt_parser.parse_args()
68,034
def test_keypoints_censure_moon_image_star(): """Verify the actual Censure keypoints and their corresponding scale with the expected values for STAR filter.""" detector = CENSURE(mode='star') detector.detect(img) expected_keypoints = np.array([[ 21, 497], [ 36, 46]...
68,035
def test_compression_strategy(logger): """ Tests dns compression strategy. """ with engine.Engine(53, "[UDP:dport:53]-tamper{DNS:qd:compress}-|", server_side=False, environment_id="compress_test", output_directory=actions.utils.RUN_DIRECTORY, log_level=actions.utils.CONSOLE_LOG_LEVEL): os.system...
68,036
def generate_betas_inertia(time_periods: int) -> np.ndarray: """ Generate an array of beta_inertia values for t time periods """ betas = np.empty(time_periods) taste_shocks = np.random.normal(loc=0, scale=src.const.taste_shock_std, size=time_periods) b0 = np.clip(np.random.normal(loc=src.const....
68,037
def create_graph_hac(env, n_layers, n_steps, subtask_specs, level_algo_kwargs_list): """Create and return HAC graph.""" # If buffer size not specified, set it such that all transitions will fit into buffer # (assuming that the episodes always last for env.max_episode_length which is not the # case in ...
68,038
def add_cartesian_dummy(odf: dc_dd) -> dc_dd: """create a dummy dataframe with a column "cartesian" with the value 0 to force a cartesian join using merge. Args: odf (dc_dd): original dask_cudf or dd Returns: dc_dd: dummy dask_cudf or dd """ odf["cartesian"] = 0 odf = du.sh...
68,039
def info(): """py-info will print the most recent version of a package's metadata. Usage: py-info <package> [package] ...\ """ env = pkg_resources.Environment() separator = False for arg in sys.argv[1:]: try: pkg = env[pkg_resources.safe_name(arg)][0] except...
68,040
def parse_fname(fname): """ Returns dictionary of parameters encoded in file name. Assumes structure: der/<name1>-<unit1><val1>_<name2>-<unit2><val2>_<note1>_<note2>/trial_v<version>.txt No numbers are allowed in the name, unit, or note fields """ #assumes <path tail>/data/<date>/<path head>...
68,041
def get_etl_pipeline_ids(client): """Return a dict mapping pipeline ids to their names, filtering on ETL pipelines.""" paginator = client.get_paginator("list_pipelines") response_iterator = paginator.paginate() filtered_iterator = response_iterator.search("pipelineIdList[?contains(@.name, 'ETL') == `tru...
68,042
def GCBucket(bucket: str, prefix: Optional[str] = None, identifier: Optional[str] = None) -> Dict: """Get configuration object for Google Cloud storage volume. Parameters ---------- bucket: string Google Cloud Storage bucket identifier. prefix: string, default=None Key-prefix for al...
68,043
def segment_threshold(eventfile,segment_length,demod,tbin_size,threshold,PI1,PI2,t1,t2): """ Using the .dat files, rebin them into 1s bins, to weed out the segments below some desired threshold. Will return a *list* of *indices*! This is so that I can filter out the *sorted* array of .dat and .fft files...
68,044
def build_model(): """ Making a pipeline and using grid-search to optimize it. Input: None Output: Returns a model """ pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(RandomForestClassifier())) ]) parameters = { 'vect...
68,045
def load_remote_settings_cache(): """Load cached remote skill settings. Returns: (dict) Loaded remote settings cache or None of none exists. """ remote_settings = {} if REMOTE_CACHE.exists(): try: with open(str(REMOTE_CACHE)) as cache: remote_settings = j...
68,046
def get_blogroll(parser, token): """ {% get_blogroll %} """ return BlogRoll()
68,047
def otsu(data, num=400): """ Generate threshold value based on Otsu. :param data: cluster data :param num: intensity number :return: selected threshold """ max_value = np.max(data) min_value = np.min(data) total_num = data.shape[1] best_threshold = min_value best_in...
68,048
def get_states(start=None, stop=None, state_keys=None, cmds=None, continuity=None, reduce=True, merge_identical=False, scenario=None): """ Get table of states corresponding to intervals when ``state_keys`` parameters are unchanged given the input commands ``cmds`` or ``start`` date. If `...
68,049
def skip_long_utterance(wav_file, cut_off_len = 15): """ from "Text-Free Image-to-Speech Synthesis Using Learned Segmental Units" Appendix A: When computing duration statistics, we exclude utterances longer than 15s for SpokenCOCO... """ if os.path.islink(wav_file): wav_file = os.read...
68,050
def read_data(filename): """Extract the first file enclosed in a zip file as a list of words.""" with zipfile.ZipFile(filename) as f: data = tf.compat.as_str(f.read(f.namelist()[0])).split() return data
68,051
def create_logger(name='', logging_config=logging_config): """Create a Logger object Args: name (str, optional): The name of the module.function logging_config (TYPE, optional): Logging config Returns: TYPE: Description """ dictConfig(logging_config) logger...
68,052
def mark_all(request): """ Mark all notification as read or unread. """ action = request.data.get('action', None) success = True if action == 'read': request.user.notifications.read_all() msg = _("Marked all notifications as read") elif action == 'unread': request.us...
68,053
def GetUniqueName(path, name): """Make a file name that will be unique in case a file of the same name already exists at that path. @param path: Root path to folder of files destination @param name: desired file name base @return: string """ tmpname = os.path.join(path, name) if os.path...
68,054
def import_sbol_parts( path: str, add_i_seqs=False ) -> Generator[bsb.BasicPart, None, None]: """Imports BasicPart objects using sbol2.Document.exportToFormat. Note: Refer to Biopython documentation for further information on Bio.SeqIO.read(). Refer to pysbol2 documentation for further info...
68,055
def _split_mime_type(mime_type): """Split MIME type into main type and subtype. Args: mime_type: The full MIME type string. Returns: (main, sub): main: Main part of MIME type (e.g., application, image, text, etc). sub: Subtype part of MIME type (e.g., pdf, png, html, etc). Raises: _In...
68,056
def test_valid(): """Assert that expected valid dbnames are valid.""" for project in PROJECTS: for language in ["en", "de", "fr", "nds_nl", "zh_min_nan"]: dbname = "{}{}".format(language, project) assert valid_dbname(dbname) is True assert valid_dbname("{}_p".format(d...
68,057
def handler_get_user_connections_from_id_from_event_id(userID, eventID): """Get the connections of the user with the given IDs (user and event). .. :quickref: Users; Get the connections of the user with the given IDs (user and event). :param int userID: The ID of the user to retrieve the collection fr...
68,058
def test_step(): """ Select desired step""" for step in tmt.steps.STEPS: result = runner.invoke(tmt.cli.main, ['--path', MINI, step]) assert result.exit_code == 0 assert step.capitalize() in result.output if step != 'provision': assert 'Provision' not in result.output
68,059
def run(studata,cook): """获取处理后的数据 :param studatae:学生信息 :param cook:传入的cookie :return :打卡结果 """ # 读取个人提交信息 info = getinfo.data(studata, cook) if info == 0: print("今日打卡已完成,自动打卡取消\n") return "已完成" # 提交今日打卡 url = 'https://yq.weishao.com.cn/api/questionnaire/questionn...
68,060
def filter_label_2( context, label ): """Test Filter Label 2""" return False
68,061
def raise_404_if_no_object(fn): """ get_object_or_404 doesn't work with mongoengine, so this is needed for similar purpose """ def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: if not e.__class__.__name__ == "DoesNotExist": ...
68,062
async def generate_keys() -> Tuple[bytes, str]: """A helper function to generate the private and public keys. backend - The value specified is default_backend(). This is because the cryptography library used to support different backends, but now only uses the default_backend(). public_exponent - ...
68,063
def _is_named_tuple(instance): """Returns True iff `instance` is a `namedtuple`. Args: instance: An instance of a Python object. Returns: True if `instance` is a `namedtuple`. """ if not isinstance(instance, tuple): return False return (hasattr(instance, "_fields") and isinstance(ins...
68,064
def load_trained_model(pipeline_str='BDT', config='IC86.2012', return_metadata=False): """ Function to load pre-trained model to avoid re-training Parameters ---------- pipeline_str : str, optional Name of model to load (default is 'BDT'). config : str, optional ...
68,065
def orsGetSnapToRoadLatLon(loc, APIkey): """ A function to get snapped latlng for one coordinate using ORS Parameters ---------- loc: list The location to be snapped to road Returns ------- list A snapped location in the format of [lat, lon]. Note that this function will lose the info of altitude of the lo...
68,066
def department_list_current(): """Returns a list of all Departments as of today's date. """ resp = _call_organisations_service("GetDepartmentListCurrent") return _parse_list_response(resp, "OrganisationsList", "Organisation")
68,067
def start(builtins=False, profile_threads=True): """Starts profiling all threads and all greenlets. This function can be called from any thread at any time. Resumes profiling if stop() was called previously. * `builtins`: Profile builtin functions used by standart Python modules. * `profile_thread...
68,068
def run_pre_process(): """ run pre process """ print(config) cfg = config aug_dict = AUG_DICT if not cfg.self_ensemble: aug_dict = {"0": AUG_DICT["0"]} dataset, save_format = get_lr_dataset(cfg) for i in range(len(dataset)): img_key = dataset.get_key(i) org_...
68,069
def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, aggregate_size=None): """ Find the unique elements of a tensor. Returns the sorted unique elements of a tensor. There are three optional outputs in addition to the unique elements: * the indices of ...
68,070
def first(n, min_length, max_length, floor, ceiling, min_slope, max_slope): """ Return the lexicographically smallest valid composition of ``n`` satisfying the conditions. .. warning:: INTERNAL FUNCTION! DO NOT USE DIRECTLY! .. TODO:: Move this into Cython. Preconditions: ...
68,071
def load_with_native_transform( dss: Sequence[Dataset], bands: Sequence[str], geobox: GeoBox, native_transform: Callable[[xr.Dataset], xr.Dataset], basis: Optional[str] = None, groupby: Optional[str] = None, fuser: Optional[Callable[[xr.Dataset], xr.Dataset]] = None, resampling: str = "n...
68,072
def func(): """A docstring""" def inner_func(): """A docstring"""
68,073
def post_to_dto(post: Post, href: str = None, links: list = None) -> PostDto: """ Converts post resource into data transfer object. :param post: Post resource to convert. :type post: Post :param href: Post resource href link. :type href: str :param links: Post resource links. :type link...
68,074
def get_dual_coding_stop_stop_location( fs_coord, fs_type, strand, chr_seq, gencode): """Extend the starting coordinate (fs_coord) downstream until the stop-codon in the main frame, shift the frame (fs_type) at this stop-codon and then go upstream in the alternative until the second stop codon. ...
68,075
def delete_restaurant(restaurant_id): """V 0.0.0 POST Delete a restaurant: GET render Delete a restaurant form""" restaurant_to_delete = SESSION.query( Restaurant).filter_by(id=restaurant_id).one() if request.method == 'POST': SESSION.delete(restaurant_to_delete) SESSION.commit() ...
68,076
def get_clusters_from_file(path, ref_cluster_names=[]): """Get cluster names, labels, and cells from cluster file or metadata file """ clusters = {} with open(path) as f: lines = f.readlines() headers = [line.strip().split('\t') for line in lines[:2]] names = headers[0] types = hea...
68,077
def split_deltas(deltas_url): """Opens and decompress a gzipped text file and splits each line into two deltas""" left, right = [], [] with gzip.open(BytesIO(read_url(deltas_url))) as deltas: for line in deltas: line = line.decode().rsplit(" ", 1) left.append(line[0].st...
68,078
def test_extract_text_command(mocker): """ Given: - An image with text When: - Running the image-ocr-extract-text command Then: - The expected text is extracted - The Human Readable and context are stored with the proper values """ mocker.patch.object(demisto, 'args', retur...
68,079
def killIfHasMore(sprite, partner, game, resource, limit=1): """ If 'sprite' has more than a limit of the resource type given, it dies. """ if sprite.resources[resource] >= limit: killSprite(sprite, partner, game)
68,080
def restore(ctx): """Rebuild db from a backup""" backups = [ x for x in os.listdir('docker/backups/postgres') if not x.startswith('.') ] if not backups: click.echo('No backups found') return click.echo( 'Be careful as this will restore the database to a previ...
68,081
def transform(image, parameter_maps, verbose=False): """Transform an image according to some vector of parameter maps :param image: Image to be transformed :param parameter_maps: Vector of 3 parameter maps used to dictate the image transformation :type image: SimpleITK.Image ...
68,082
def put_lines(ax, cwaves, fluxes, ypos2, ypos3, labels, bars=None, bscale=None, edges=None, barskwargs=dict(), adjustkwargs=dict(), linekwargs=dict(), textkwargs=dict()): """ Automatic layout of labels for spectral lines in a plot. Parameters ---------- ax : Matplotlib A...
68,083
def sip_to_pv(infile,outfile,tpv_format=True,preserve=False,extension=0,clobber=True): """ Function which wraps the sip_to_pv conversion Parameters: ----------- infile (string) : name of input FITS file with TAN-SIP projection outfile (string) : name of output FITS file with TAN-TPV projection ...
68,084
def _tracking(fcn): """ Decorator to indicate the list has changed """ def new_fcn(self, *args): self.changed = True return fcn(self, *args) return new_fcn
68,085
def test(doorcount: int, switch: bool, trials: int) -> bool: """Returns a win rate for the Monty Hall problem with repeated trials.""" wins = sum(int(play(doorcount, switch) == CAR) for _ in range(trials)) return wins/trials
68,086
def getLastStepMeanSpeed(detID): """getLastStepMeanSpeed(string) -> double Returns the mean speed in m/s of vehicles that have been within the named multi-entry/multi-exit detector within the last simulation step. """ return _getUniversal(tc.LAST_STEP_MEAN_SPEED, detID)
68,087
def get_random_experiment_histories_from_file(experiment_path_prefix, net_number): """ Read history-arrays from the specified npz-file and return them as ExperimentHistories object. """ histories_file_path = generate_random_experiment_histories_file_path(experiment_path_prefix, net_number) with np.load(hist...
68,088
def caller_module(level=2, sys=sys): """This function is taken from Pyramid Web Framework - ``pyramid.path.caller_module``.""" module_globals = sys._getframe(level).f_globals module_name = module_globals.get('__name__') or '__main__' module = sys.modules[module_name] return module
68,089
def load( self, text, lineterminator="\r\n", quotechar='"', delimiter=",", escapechar=escapechar, quoting=csv.QUOTE_MINIMAL, ): """Item from CSV representation.""" f = io.StringIO(text) if not quotechar: quoting = csv.QUOTE_NONE reader = csv.DictReader( f, ...
68,090
def qr_householder(A): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the matrix A does not have to be square...
68,091
def login(): """ Página de entrada de la app """ if 'email' in session: # Obtenemos el ID del user _id = elastic.getIDByMail(session['email']) return render_template('index_sup.html', random_num = WebScraper.getRandomNumber(), msg = session['user'] + ' is already online!',...
68,092
def write_json(data, outfile): """ Writes the dictionary data to a json file. :param data: dictionary, data to be stored as json file :param outfile: str, path of the output file """ with open(outfile, 'w') as f: json.dump(data, f, indent=2)
68,093
def load_data(database_filepath): """ Load data from database Arguments: database_filepath -> Path to SQLite destination database Output: X -> a dataframe containing features Y -> a dataframe containing labels category_names -> List of categories name """ # l...
68,094
def cholesteric_droplet_data(shape, radius, pitch, hand = "left", no = 1.5, ne = 1.6, nhost = 1.5): """Returns cholesteric droplet optical block. This function returns a thickness, material_eps, angles, info tuple of a cholesteric droplet, suitable for light propagation calculation tests. Pa...
68,095
def test_multilayer_rnn( generate_dataset, batch_first, bidirectional, num_layers ): """Tests multilayer functionality for cells that output hidden state only.""" input_size = 1 hidden_size = 10 num_directions = 2 if bidirectional else 1 recurrent_layers = [nn.GRUCell(input_size, hidden_size)...
68,096
def check_story_priorities(features, policies, user_stories, modify=False): """Infer story priorities from feature and policy priorities as a sanity check. The story priority calculated will be the lowest of the priorities of the features and policies it relies upon. An inconsistency warning will be shown...
68,097
def getInterpolatedFzeroPzero( f, g, p ): """ look at the points of f, g and p surrounding where g crosses zero and interpolate f and p at 0 """ ndx = getIndexZeroDbCrossover( g ) f_zero_db = None g_zero_db = None p_zero_db = None if ndx != None: f_zero_db = f[ndx] g_z...
68,098
def create_tag(entity: Entity, source_name: str, color: str) -> Mapping[str, str]: """Create a tag.""" value = entity.value if value is None: value = f"NO_VALUE_{entity.id}" return {"tag_type": source_name, "value": value, "color": color}
68,099