content
stringlengths
22
815k
id
int64
0
4.91M
def on_builder_inited(app: Sphinx) -> None: """Initialize DurationDomain on bootstrap. This clears results of last build. """ domain = cast(DurationDomain, app.env.get_domain('duration')) domain.clear()
63,500
def update_eigensystem(L, U, v, sigma): """ Perform rank one update to eigensystem. Requires the eigenpairs to be ordered Parameters ---------- L : numpy.ndarray, 1d Current eigenvalues U : numpy.ndarray, 2d Current eigenvectors v : numpy.ndarray, 2d Column vecto...
63,501
def is_cooled_down(token: str, event_type='normal', **kwargs) -> Rule: """ 检查冷却事件是否已经结束的规则。如果仍在生效则为 `False`,反之为 `True`。 参数: - `token: str`:事件标签。 关键字参数: - `type: str`:事件类型,默认为 `normal`。包括: - `global`:全局冷却事件; - `group`:群组冷却事件,需要额外的关键字参数 `group: int` 指定群组 ID; - `normal`:一般...
63,502
def solve(c4n,n4e,n4db,ind4e,f,u_D,degree): """ Computes the coordinates of nodes and elements. Parameters - ``c4n`` (``float64 array``) : coordinates for nodes - ``n4e`` (``int32 array``) : nodes for elements - ``n4db`` (``int32 array``) : nodes for Dirichlet boundary - ``ind4e`` (``int32 array``) : indice...
63,503
def is_empty_element_tag(tag): """ Determines if an element is an empty HTML element, will not have closing tag :param tag: HTML tag :return: True if empty element, false if not """ empty_elements = ['area', 'base', 'br', 'col', 'colgroup', 'command', 'embed', 'hr', ...
63,504
def test_build_no_commandline_config(): """Try building experiment with no commandline configuration.""" with OrionState(experiments=[], trials=[]): with pytest.raises(NoConfigurationError): experiment_builder.build("supernaekei")
63,505
def bad_request(error): """Redirect all bad requests.""" results = { "message": HTTPStatus.BAD_REQUEST.phrase, "status-code": HTTPStatus.BAD_REQUEST, } return results
63,506
def get_outlier_definition(biomarker): """ Centralised definitions of biomarker outliers for filtering """ if biomarker == "APHalfWidth": outlier_definition = 100.0 # ms else: raise ValueError(f"Biomarker {biomarker} not found.") return outlier_definition
63,507
def _symbol(s, matching_symbol=None): """Return s if s is a Symbol, else return either a new Symbol (real=True) with the same name s or the matching_symbol if s is a string and it matches the name of the matching_symbol. >>> from sympy import Symbol >>> from sympy.geometry.util import _symbol >...
63,508
def register_image_dataset(name, dataset): """Registers a new image dataset. Args: name (str): key corresponding to the new dataset. dataset (Dataset): the new dataset class. Examples:: import torchreid import NewDataset torchreid.data.register_image_datase...
63,509
def test_credential_type_fails(): """Test that an IncorrectTypeError is correctly raised when the credentials parameter is of an incorrect type""" with pytest.raises(CiscoWLCAPIExceptions.IncorrectTypeError): CiscoWLCAPIValidators.credential("admin, password") with pytest.raises(CiscoWLCAPIExcep...
63,510
def code_to_string(code: StatusCode) -> str: """ Args: code (StatusCode): a value from the StatusCode enumeration Returns: str: A string explanation of the error """ if code == StatusCode.OK: return "OK" elif code == StatusCode.TensorLoadFailure: return "Error: fa...
63,511
def set_commit(repo_config: RepoInfo, github_token: str = None) -> None: """ Lookup tag specified in the RepoInfo object and use that to set the commit for that object :param repo_config: RepoInfo object to update :return: None """ if not repo_config.old_tag: error(f"Must give a tag for {repo_config.n...
63,512
def find_repositories_by_walking(path, followlinks): """Walk a tree and return a sequence of (directory, dotdir) pairs.""" repos = [] for dirpath, dirnames, filenames in os.walk(path, followlinks=followlinks): for dotdir in set(dirnames) & DOTDIRS: repos.append((dirpath, dotdir)) ret...
63,513
def test_copy_prm_file(): """ Test the copy_prm_file routine.""" # Create a temporary directory save_loc = Path('./tmp_pytest/') if not save_loc.exists(): save_loc.mkdir() # Run the routine copy_prm_file(save_loc=save_loc, which='default') # Clean things up if all went fine _ ...
63,514
def recurse_filestats(dir: PathLike, *, channel: Channel = None) -> Channel: """ Starts a worker thread that finds all files in `dir` (recursively) and writes them to a :obj:`Channel`. Each file found is written as a :obj:`FileStats` object. :param dir: The directory to search. :param channel: ...
63,515
def correl(df,periods=21,columns=None,include=True,str=None,detail=False,how='value',**correl_kwargs): """ how : string value pct_chg diff """ def _correl(df,periods=21,columns=None,include=True,str=None,detail=False,**correl_kwargs): study='CORREL' df,_df,columns=validate(df,columns) _df['CORREL']...
63,516
def silhouette_score_inner_loop(i, cluster_ids, cluster_labels, all_pcs): """ Helper to loop over cluster_ids in one dimension. We dont want to loop over both dimensions in parallel- that will create too much worker overhead Args: i: index of first dimension cluster_ids: iterable of clus...
63,517
def problem_5_14_9(scalars, vectors): """ Problem c cutoff in Kindle edition. Using value from Coursera course: https://github.com/jimcarson/Coursera/blob/master/CodingTheMatrix/hw12_basis_problems/The_Basis_problems.py#L118 >>> zero_vec_4 = zero_vec_n(4) >>> a_vectors = list_of_lists_to_vecs([[one...
63,518
def pytest_register_spec_collectors(collectors: CollectorsMapping) -> None: """Register available spec collectors""" collectors["sphinx"] = SphinxCollector
63,519
def split_tree(node: TreeNode): """ Split the tree between the given node and its previous sibling(s). All of the previous siblings are moved to their own branch with a new parent, leaving this node and any siblings on the right with the original parent. """ # If this is the first node of a...
63,520
def main(): """ Entry function """ import argparse # intialisize parser parser = argparse.ArgumentParser(description="sample application") # define some options (better import from defaultParser) parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", ...
63,521
def get_csv(url: str, comment_prefix: str = None, **kwargs) -> Tuple[pd.DataFrame, Union[bytes, None]]: """Remove comments in csv-like files. But unlike pandas.read_csv, this function only removes comments at the beginning of the file. Args: url (str): Source URL. comment_prefix (str, optio...
63,522
def start_all_harvesters(request): """ This function starts all harvesters. :param request: the request :return: an HttpResponseRedirect to the Main HCC page """ harvesters = Harvester.objects.all() for harvester in harvesters: if harvester.enabled: api = InitHarvester(h...
63,523
def get_incident_message_ids(client, incident_id): """ Returns the message ids for all the events for the input incident. """ detail_response = client.get_incident_details(incident_id) message_ids = [] # loop through all the events of this incident and collect the message ids if 'events' in...
63,524
def _Dirname(path): """Returns the parent directory of path.""" i = path.rfind("/") + 1 head = path[:i] if head and head != "/" * len(head): head = head.rstrip("/") return head
63,525
async def test_manacube_not_found(mcsrvstats_client: Client) -> None: """Checks manacube returns correct data when player is not found.""" with aioresponses() as m: m.get( "https://manacube.com/stats_data/fetch.php?username=_iTempo", status=200, payload={ ...
63,526
def unshare_resource_with_user(request, shortkey, user_id, *args, **kwargs): """this view function is expected to be called by ajax""" res, _, user = authorize(request, shortkey, needed_permission=ACTION_TO_AUTHORIZE.VIEW_RESOURCE) user_to_unshare_with = utils.user_from_id(user_id) ajax_response_data =...
63,527
def coords_distance(coords0, coords1): """ Euclidean distance between two coordinates """ total = 0 for x0, x1 in zip(coords0, coords1): total += (x0 - x1) ** 2 return sqrt(total)
63,528
def create_url(artist, song, language): """Create the URL in the LyricWikia format""" url = __BASE_URL__ + '/wiki/{artist}:{song}'.format(artist=urlize(artist), song=urlize(song)) if language: url += '/{language}'.format(language=urlize(language).lower()) return url
63,529
def _clean_inner_tags_file(outfile, stream): """Accepts an output filename and a stream of the byte contents of a tags file and writes the cleaned contents to a new file on disk. Args: outfile: the path to which the modified stream should be written stream: the byte datapipe of the contents...
63,530
def bound_free_absorption(wavelength_um, temperature): """bound free absorption of H- Note: alpha has a value of 1.439e4 micron-1 K-1, the value stated in John (1988) is wrong """ # here, we express alpha using physical constants alpha = CONST_C*CONST_H/CONST_K*10000.0 lambda_0 = 1....
63,531
def output(num_rows, solution): """Outputs the final solution.""" for i in xrange(num_rows): print(solution[i])
63,532
def get_representative_time_series(path_to_irf: PathLike) -> numpy.array: """ Extract a time series from a representative voxel in the occipital pole. Args: path_to_irf (PathLike): Path to the IRF image. Returns: numpy.array: Vector containing time series of voxel from occipital pole. ...
63,533
def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth...
63,534
def RemoveHotlist(cnxn, hotlist_id, services): """Removes the given hotlist from the database. Args: hotlist_id: the id of the hotlist to be removed. services: interfaces to data storage. """ services.hotlist_star.ExpungeStars(cnxn, hotlist_id) services.features.DeleteHotlist(cnxn, hotlist_id)
63,535
def test_unit_Validators__validate_training_data(custom_models_simple_training_data_4elements, monkeypatch): """ unit test __validate_training_data. Use monkeypatching for embedded call to Validators.__validate_num_covars. """ # initialize the class cls = Validators() # data train_X = cust...
63,536
def retrieve_context_connectivity_service_end_point_end_point_by_id(uuid, local_id): # noqa: E501 """Retrieve end-point by ID Retrieve operation of resource: end-point # noqa: E501 :param uuid: ID of uuid :type uuid: str :param local_id: ID of local_id :type local_id: str :rtype: Connect...
63,537
def IsLoopExit(op): """Return true if `op` is an Exit.""" return op.type == "Exit" or op.type == "RefExit"
63,538
def update_covid_data(name="covid update", repeat=False, is_both=False) -> None: """Updates all relevant data for the index template and stores it in CSV files. :param name: User-defined name of the update. defaults to 'covid update'. :param repeat: Boolean variable that dictates whether the function w...
63,539
def process_fovea(fovea, pixel_norm = 'standard', mutation = False) : """ Fn preprocesses a single fovea array. If mutation == True, modifications to input images will be made, each with 0.5 probability: * smallest dimension resized to standard height and width supplied in size param *...
63,540
def also_load_config(modelname, net_config, evaluation_data, starting_weights, _run): """In case of only a single training experiment, we also load the exact network config from this experiment as a default""" # Load the training experiment training_experiment = ExperimentData(starting_weights) mod...
63,541
def fasta_file_to_lists(path, marker_kw=None): """Reads a FASTA formatted text file to a list. Parameters ---------- path : str Location of FASTA file. marker_kw : str Keyword indicating the sample is a marker. Returns ------- dict Contains list of ids, descript...
63,542
def _get_fallback_text(data: Data) -> str: """Get a fallback text from data.""" return data.get("text/plain", "Image")
63,543
def decode_cl_value(obj: typing.Union[dict, str]) -> CLValue: """Decodes a CL value. """ cl_type = decode_cl_type(obj["cl_type"]) as_bytes = bytes.fromhex(obj["bytes"]) if isinstance(cl_type, (CLType_Simple, CLType_ByteArray, CLType_Option)): parsed = byte_array_decoder(cl_type, as_bytes) ...
63,544
def test_d4_3_16v05_d4_3_16v05i(mode, save_output, output_format): """ Tests the simpleType dateTime and its facets, explicitTimezone """ assert_bindings( schema="ibmData/valid/D4_3_16/d4_3_16v05.xsd", instance="ibmData/valid/D4_3_16/d4_3_16v05.xml", class_name="Root", ve...
63,545
def probability_sum_weight(probability, token_frequency, n, word, alpha, original_tokens, top_expansion, wv): """Assigns weighted score to document based on summation of probabilities. Args: probability (float): Previously calculated probability. token_frequency (float): Number of appearanc...
63,546
def save_cv(cv_name, cv): """Save gridsearch as pickle file Args: cv_name => name you want to call file of cross validation in format 'file.pickle' cv => Gridsearch object returned from grid_search function Returns: None """ with open('../models/{}.pickle'.format(cv_name), '...
63,547
def _make_builder_configs(): """Construct a list of BuilderConfigs. Construct a list of CityscapesCorruptedConfig objects, corresponding to the corruptions in _CORRUPTIONS and 5 severities. Returns: A list of CityscapesCorruptedConfig objects. """ config_list = [] for corruption in _CORRUPTIONS: ...
63,548
def validation_early_stopping(model, device, valid_loader): """ Evaluates the validation set. This is done during early stopping. Parameters ---------- model : PyTorch model class device : device Options are torch cpu or cuda. valid_loader : Dataloader Dataloader for th...
63,549
def islazy(f): """Internal. Return whether the function f is marked as lazy. When a function is marked as lazy, its arguments won't be forced by ``lazycall``. This is the only effect the mark has. """ # special-case "_let" for lazify/curry combo when let[] expressions are present return hasattr...
63,550
def wind12(): """Sends all 12 hour wind forecasts. Returns: str: JSON response. """ return util.returnMany({'type': 'WINDS_12_HR'}, request)
63,551
def modis_snow_grain_mosaic(DIRECTORY, YEARS=None, BOUNDS=None, SPACING=None, PROJECTION=None, VERBOSE=False, MODE=0o775): """ Create daily mosaics of snow grain size from MODIS imagery """ # projection for output mosaic # attempt to use EPSG code and fall back on PROJ4 code try: crs...
63,552
def transform_data(df, mva=30): """ This is for scaling the original data for use in machine learning. Takes a numpy array as input, divides by a moving average with period mva (integer), and returns the scaled data as well as the scaler and moving average (needed for returning the data to its orig...
63,553
def surrogate_test( mata, matb, pval=0.005, nshuffles=1000, return_extra=False, nworkers=8, pcalc_discard0=0, pcalc_discard1=1000, lrG=0.01, verbose=False, ): """shuffling/permutation strat to compare trajectories # mata: matrix of dims (ntrajectories, ninterpolatedspace)...
63,554
def test_remove_head_pointers(test_lists): """Test remove from head of list changes pointers.""" test_lists[2].remove(5) assert test_lists[2].head.data is 4 assert test_lists[2].head.prev is None
63,555
def test_format_asctime(): """ If a user requests asctime in the default keys, then it should be rendered in the final log output. """ # Generate a real `logging.LogRecord` from the provided dictionary. record = logging.makeLogRecord({"msg": "alpha"}) value = Logfmter(keys=["asctime"]).form...
63,556
def declaration_path(name): """Return the path to an included declaration""" from os.path import dirname, join, exists import metatabdecl from metatab.exc import IncludeError d = dirname(metatabdecl.__file__) path = join(d, name) if not exists(path): path = join(d, name + '.csv')...
63,557
def _pop_complex_predicates(args): """ Compute the cartesian product of "accept" and "content_type" fields to establish all possible predicate combinations. .. seealso:: https://github.com/mozilla-services/cornice/pull/91#discussion_r3441384 """ # pop and prepare individual predicate ...
63,558
def cifar10_fp_net_resnet23_prediction(image, maps=64, n=8, delta=2**-4, test=False): """ Construct FixedPointNet using resnet23. """ # Residual Unit def res_unit(x, scope_name, dn=False): C = x.shape[1] with nn.parameter_scope(scope_name): ...
63,559
def _get_agenda_event_range(): """Get times from now until the end of the day.""" start = now_tz() stop = end_of_day_tz() _logger.info("agenda range: %s - %s", start.isoformat(), stop.isoformat()) return start.isoformat(), stop.isoformat()
63,560
def _fake_networks(network_count, tenant_id): """id is the id from melange network_id is the id from quantum. Dumb""" return [{'id': str(uuidutils.generate_uuid()), 'name': 'net%d' % i, 'network_name': 'qnet%s' % i, 'cidr': '10.0.0.0/8', 'network_id': str(...
63,561
def oligoTm(seqobj): """ Takes either a SeqRecord object, a Seq object, or a string and computes the melting temp based on the NN model (yes?). This is Kun's code CHECK THE NN PARAMETERS From Uri Laserson """ if isinstance(seqobj,SeqRecord): seq = str(seqobj.seq).upper(...
63,562
def test_list_xml(): """Test that where elements occur multiple times, a list is generated.""" tree = xml_to_navigable_dict(etree.fromstring('<test><element>Test</element><element>Test 2</element></test>')) assert isinstance(tree.element, list) assert len(tree.element) == 2 assert tree.element[0]._t...
63,563
def migration_step_5(): """ Bots can be either system-wide or tied to a specific account. """ with db.cursor() as c: ACCOUNT_ID_FIELD_NULLABLE = 'account INTEGER DEFAULT NULL REFERENCES accounts(id) ON DELETE CASCADE' c.execute("ALTER TABLE bots ADD COLUMN {account};".format(account=ACCOUNT_ID_F...
63,564
def _helper(node: BST, target: int, diff: int): """ :param node: :param target: :param diff: :return: """ if node is None: return diff val = node.value new_diff = abs(val - target) if abs(diff - target) > new_diff: diff = val a = _helper(node.left, target, di...
63,565
def compensation(module_name: str, original_weights_2: torch.Tensor, scaling_matrix: torch.Tensor) -> torch.Tensor: """ [Inputs] original_weights_2: (N[i+2], N[i+1], K, K) scaling_matrix: (P[n+1], N[i+1]) [Outputs] new_weights_2: (N[i+2], P[i+1]) """ if module_name.start...
63,566
def cookRedirectObject(repos, db, cfg, recipeClass, sourceVersion, macros={}, targetLabel = None, alwaysBumpCount=False, ignoreDeps = False): """ Turns a redirect recipe object into a change set. Returns the absolute changeset created, a list of the names of the packa...
63,567
def save_timeseries_csv(column_vals, column_names, save_fpath): """Save a series of data points to CSV file""" if len(column_names) != column_vals.shape[1]: raise ValueError('Number of column names must match # cols in `column_vals`') with open(save_fpath, mode='w', newline='') as csv_file: ...
63,568
def obter_ganhadores(tab): """ Obtem os jogadores que fizeram 3 em linha. :param tab: tabuleiro :return: tuplo Recebe um tabuleiro e retorna um tuplo com as pecas dos jogador(es) que ganharam o jogo. Caso nao haja nenhum jogador ganhador, a funcao retorna um tuplo com uma peca vazia. ...
63,569
def upload_tsv_to_workspace(tsv, project, workspace): """Split large TSV file and upload individual smaller TSV files to Terra workspace.""" # initiate list that will contain n items where each n = header + 5000 rows of input tsv data tsv_strings = [] # open input tsv, save header, split large tsv into...
63,570
def login(): """ Handles login of a user and returns a session_token if supplied password and username is correct. Token and Username needs to be supplied with every request in order to access restricted routes. Example: { "username": "Chris", "token": "0e45b5df2e6c42ae9b69f1a2a2470209" ...
63,571
def screen_refurbs_deglassing_batch_complete(): """This route is for processing refurb completions, generating associated reports and adding to stock'""" start_time = time.time() webhook = flask.request.get_data() # Authenticate & Create Object data = monday_handshake(webhook) if data[0] is Fal...
63,572
def get_csv_header(data_location, delimiter): """Gets the CSV header from the input files. This function assumes that the header is present as the first line in all the files in the input path. Args: data_location: Glob pattern(s) specifying the location of the input data files. ...
63,573
def get_stats(stats_type): """[Get statistic by type from bind] Arguments: stats_type {[String]} -- [Type of statistic] Returns: [dict] -- [statistic value get follow input type] """ url = "http://{}:{}{}".format( BIND_CONFIGURATION["host"], BIND_CONFIGURATION["port"]...
63,574
def pack_dataframe(dt_targ, times, paths, history=HISTORY, tol_time=TOLERANCE_TIME_SEC, ): """Export a pandas dataframe to extract background. DataFrame contains the time, the relative path to the original filename (including its parent folder), ...
63,575
def FindTestsToRun(env, build, BUILD_TARGETS, otherVars, component=None, project=None): """Find header files defining tests to run. One of component or project must be specified; this says which Chaste component or user project to hunt for tests in. If otherVars['requested_tests'] i...
63,576
def test_ap_wpa2_eap_aka_prime(dev, apdev): """WPA2-Enterprise connection using EAP-AKA'""" if not os.path.exists("/tmp/hlr_auc_gw.sock"): logger.info("No hlr_auc_gw available"); return "skip" params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap") hostapd.add_ap(apdev[0]['ifname'], param...
63,577
def get_CG_bonds_distrib(ns, beads_ids, grp_type): """"Calculate bonds distribution from CG trajectory. ns requires: cg_universe bw_bonds bw_constraints bins_constraints bins_bonds """ bond_values = np.empty(len(ns.cg_universe.trajectory) * len(beads_ids)) fr...
63,578
def update_translations(request): """ Actualiza las traducciones eliminando las huérfanas y generando traducciones vacías para todos los objetos que existan en base de datos. """ FieldTranslation.delete_orphan_translations() num_translations = FieldTranslation.update_translations() return render_to_response('mo...
63,579
def validate_lower(value): """Ensure value is all lowercase.""" if value.lower() != value: raise ValidationError("{0} must be all lower case.".format(value))
63,580
def flux(vrc_ret, ts_run_fs, ts_save_fs, ts_locs=(0,), vrc_locs=(0,)): """ Save the VaReCoF flux and input """ # Unpack the ret inf_obj, inp_strs, out_str = vrc_ret tst_str, divsur_str, molpro_str, tml_str, struct_str, pot_str = inp_strs # Get the flux string (somehow) flux_str = '' #...
63,581
def _sample_ncols(col_limits, random_state): """ Sample a valid number of columns from the column limits. """ integer_limits = [] for lim in col_limits: try: integer_lim = sum(lim) except TypeError: integer_lim = lim integer_limits.append(integer_lim) re...
63,582
def main(args=None): """ Parse the arguments, get the data in a df, and create the plot :return: if requested, return the plot as JSON object """ if args is None: args = sys.argv[1:] parsed_args = parse_arguments(arguments=args) conn = connect_to_database(db_path=parsed_args.databa...
63,583
def exercise_b2_106(): """ Write a Python program to test whether a given integer is pandigital number or not. Go to the editor From Wikipedia, In mathematics, a pandigital number is an integer that in a given base has among its significant digits each digit used in the base at...
63,584
def resamb_lambda(nav, sat): """ resolve integer ambiguity using LAMBDA method """ nx = nav.nx na = nav.na xa = np.zeros(na) ix = ddidx(nav, sat) nb = len(ix) if nb <= 0: print("no valid DD") return -1, -1 # y=D*xc, Qb=D*Qc*D', Qab=Qac*D' y = nav.x[ix[:, ...
63,585
def download_PDB(pdb): """ Downloads a PDB from protein data base :param pdb: pdb identifier """ url = 'http://www.rcsb.org/pdb/files/{0}.pdb'.format(pdb) print('downloading %s (%s)' % (pdb, url)) req = requests.get(url) with get_file(pdb) as newPDB: print(req.text, file=newPDB)
63,586
def handle_list_datasets_by_run_id(project_id, experiment_id, run_id, operator_id): """Handles GET requests to /.""" accept = request.headers.get('Accept') application_csv = False if accept and 'appl...
63,587
async def test_if_action_before_sunset_with_offset(opp, opp_ws_client, calls): """ Test if action was before sunset with offset. Before sunset is true from midnight until sunset, local time. """ await async_setup_component( opp, automation.DOMAIN, { automation.DO...
63,588
def cPickleDumpDictionary(dictionary, output): """ Dumps a dictionary of data to a cPickled file. :param dictionary: a Python data container does not have to be a dictionary :param output: name of the output file :return: None """ out = open(output, 'wb') cPickle.dump(dictionary, out) ...
63,589
def start(update: Update, _: CallbackContext) -> None: """Send a message when the command /start is issued.""" user = update.effective_user update.message.reply_markdown_v2( fr'Hi {user.mention_markdown_v2()}\!' '\n\nType /help to see what can i do' )
63,590
def test_delete_verification_page(testapp, fill_the_db): """Test delete verifiation page renders without error.""" response = testapp.get('/journal/6/verification', status=200) html = response.html assert html.find("form")
63,591
def smiles_to_seq(smiles, seq_length, char_dict=smiles_dict): """ Tokenize characters in smiles to integers """ smiles_len = len(smiles) seq = [] keys = char_dict.keys() i = 0 while i < smiles_len: # Skip all spaces if smiles[i:i + 1] == ' ': i = i + 1 # F...
63,592
def test_query_flask_state_host(app): """ Tests whether the query data returns to the specified format """ model_init_app(app) test_right_day = [1, 3, 7, 30] test_error_day = [5, 10, 31, 100] with app.app_context(): for day in test_right_day: response_content = host_statu...
63,593
def create_worker(doc: Dict) -> Worker: """Factory pattern for workers. Create an instance of a worker implementation from a given worker serialization. Parameters ---------- doc: dict Dictionary serialization for a worker. Returns ------- flowserv.controller.worker.base.W...
63,594
def load_some_app_reviews(app_ids: list) -> pd.DataFrame: """ Load reviews for a given set of Play Store apps Args: app_ids: list - a list of app ids whose reviews will be loaded Returns: Pandas DataFrame """ data_types = { "appId": str, "content": str, ...
63,595
def test_fetch_market_trade_data_dataframe(): """Tests downloading of market and trade/order data from dataframe """ ### Get market data market_loader = Mediator.get_tca_market_trade_loader() market_data_store = DatabaseSourceCSV(market_data_database_csv=csv_market_data_store).fetch_market_data( ...
63,596
def highpass(x, fs, fc, order=4): """ Applies highpass filter Parameters: - x: numpy.array, input signal, sampled at fs - fs: float, sampling frequency - fc: float, cutoff frequency - order: filter order Returns: numpy.array """ nyq = 0.5 * fs norm_fc = fc / n...
63,597
def is_printable(s: str) -> bool: """ does the given string look like a very simple string? this is just a heuristic to detect invalid strings. it won't work perfectly, but is probably good enough for rendering here. """ return all(map(lambda b: b in string.printable, s))
63,598
def sync_redis_delete(username: str, email: str): """MySQL数据库删除数据同步到Redis :param username: 需要删除的用户名 :param email: 用户的邮箱 :return: bool """ # db = pymysql.Connect(host='localhost', user='root', password=mysql_passwd, # database=mysql_base, charset='utf8') # 通过docker部署...
63,599