content
stringlengths
22
815k
id
int64
0
4.91M
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv try: optlist, args = getopt.getopt( sys.argv[1:], param_short_options, param_long_options) except getopt.error, msg: p...
23,600
def run_fn(fn_args: TrainerFnArgs): """Train the model based on given args. Args: fn_args: Holds args used to train the model as name/value pairs. """ # get transform component output tf_transform_output = tft.TFTransformOutput(fn_args.transform_output) # read input data train_dataset...
23,601
def log_likelihood(X, Y, Z, data, boolean=True, **kwargs): """ Log likelihood ratio test for conditional independence. Also commonly known as G-test, G-squared test or maximum likelihood statistical significance test. Tests the null hypothesis that X is independent of Y given Zs. Parameters --...
23,602
def conjugada_matriz_vec(mat:list): """ Funcion que realiza la conjugada de una matriz o vector complejo. :param mat: Lista que representa la matriz o vector complejo. :return: lista que representa la matriz o vector resultante. """ fila = len(mat) columnas = len(mat[0]) resul = ...
23,603
def features2matrix(feature_list): """ Args: feature_list (list of Feature): Returns: (np.ndarray, list of str): matrix and list of key of features """ matrix = np.array([feature.values for feature in feature_list], dtype=float) key_lst = [feature.key for feature in feature_li...
23,604
def GenDataFrameFromPath(path, pattern='*.png', fs=False): """ generate a dataframe for all file in a dir with the specific pattern of file name. use: GenDataFrameFromPath(path, pattern='*.png') """ fnpaths = list(path.glob(pattern)) df = pd.DataFrame(dict(zip(['fnpath'], [fnpaths]))) df['di...
23,605
def is_heading(line): """Determine whether a given line is a section header that describes subsequent lines of a report. """ has_cattle = re.search(r'steer?|hfrs?|calves|cows?|bulls?', line, re.IGNORECASE) has_price = re.search(r'\$[0-9]+\.[0-9]{2}', line) return bool(has_cattle) and not bool(...
23,606
def get_channel_messages(channel_id): """ Holt fuer einen bestimmten Kanal die Nachrichten aus der Datenbank""" session = get_cassandra_session() future = session.execute_async("SELECT * FROM messages WHERE channel_id=%s", (channel_id,)) try: rows = future.result() except Exception: ...
23,607
def train(traj, pol, targ_pol, qf, targ_qf, optim_pol, optim_qf, epoch, batch_size, # optimization hypers tau, gamma, # advantage estimation sampling, ): """ Train function for deep deterministic policy gradient Parameters ---------- tra...
23,608
def test_create_secure_wireless_failure(mocked_secure_wireless_create_failure, capfd): """ Test : Create secure wireless connection w/failure """ with pytest.raises(SystemExit): nmcli.main() assert nmcli.Nmcli.execute_command.call_count == 2 arg_list = nmcli.Nmcli.execute_command.call_...
23,609
async def bot_start(message: types.Message): """ The function is designed to welcome a new bot user. """ await types.ChatActions.typing() first_name = message.from_user.first_name devs_id = await mention_html("no_n1ce", "Nikita") await message.answer( text=f"Привет, {first_n...
23,610
def upsample_gtiff(files: list, scale: float) -> list: """ Performs array math to artificially increase the resolution of a geotiff. No interpolation of values. A scale factor of X means that the length of a horizontal and vertical grid cell decreases by X. Be careful, increasing the resolution by X inc...
23,611
def merge_dicts(dict1, dict2): """ _merge_dicts Merges two dictionaries into one. INPUTS @dict1 [dict]: First dictionary to merge. @dict2 [dict]: Second dictionary to merge. RETURNS @merged [dict]: Merged dictionary """ merged = {**dict1, **dict2} return merged
23,612
def check_api_acls(acls, optional=False): """Checks if the user provided an API token with its request and if this token allows the user to access the endpoint desired. :arg acls: A list of access control :arg optional: Only check the API token is valid. Skip the ACL validation. """ import pagu...
23,613
def get_data(): """ Return data files :return: """ data = {} for df in get_manifest(): d, f = os.path.split(df) if d not in data: data[d] = [df] else: data[d].append(df) return list(data.items())
23,614
def china_province_head_fifteen(): """ 各省前15数据 :return: """ return db_request_service.get_china_province_head_fifteen(ChinaTotal, ChinaProvince)
23,615
def exec_sedml_docs_in_archive(sed_doc_executer, archive_filename, out_dir, apply_xml_model_changes=False, sed_doc_executer_supported_features=(Task, Report, DataSet, Plot2D, Curve, Plot3D, Surface), report_formats=None, plot_formats=None, ...
23,616
def pipeline(x_train, y_train, x_test, y_test, param_dict=None, problem='classification'): """Trains and evaluates a DNN classifier. Args: x_train: np.array or scipy.sparse.*matrix array of features of training data y_train: np.array 1-D arra...
23,617
def test_convolve_lti(u, h): """Test whether :func:`acoustics.signal.convolve` behaves properly when performing a convolution with a time-invariant system. """ H = np.tile(h, (len(u), 1)).T np.testing.assert_array_almost_equal(convolveLTV(u,H), convolveLTI(u,h)) np.testing.assert_array_almost_...
23,618
def p_command_statement_input_2(t): """ command_statement_input : object_list """ pass
23,619
def model_selection(modelname, num_out_classes, dropout=None): """ :param modelname: :return: model, image size, pretraining<yes/no>, input_list """ if modelname == 'xception': return TransferModel(modelchoice='xception', num_out_classes=num_o...
23,620
def insert_into_solr(): """ Inserts records into an empty solr index which has already been created. It inserts frequencies of each noun phrase per file along with the arxiv identifier (from the file name) and the published date (obtained from the arxiv_metadata Solr index).""" solr = pysolr.Solr('http:...
23,621
def make_binary_kernel(kernel_shape, sparsity): """ Create a random binary kernel """ filter_1d_sz = kernel_shape[0] filter_2d_sz = filter_1d_sz * kernel_shape[1] filter_3d_sz = filter_2d_sz * kernel_shape[2] filter_4d_sz = filter_3d_sz * kernel_shape[3] sparsity_int = np.ceil(sparsity...
23,622
def Packet_computeBinaryPacketLength(startOfPossibleBinaryPacket): """Packet_computeBinaryPacketLength(char const * startOfPossibleBinaryPacket) -> size_t""" return _libvncxx.Packet_computeBinaryPacketLength(startOfPossibleBinaryPacket)
23,623
def build_check_query(check_action: Action) -> str: """Builds check query from action item Parameters ---------- check_action : action check action to build query from Returns ------- str query to execute """ return f""" UPDATE todos SET completed = ...
23,624
def gen_positions(n, n_boulders): """Generates state codes for boulders. Includes empty rows Parameters: n: number of rows/columns n_boulders: number of boulders per row return value: Possible boulder and alien states """ boulder_positions=[]; b_p=[] alien_positions_with...
23,625
def analysis_linear_correlation(data1:np.array, data2:np.array, alpha:float = .05, return_corr:bool = True, verbose:bool = False)->bool: """ ## Linear correlation analysis to test i...
23,626
def sha256(buffer=None): """Secure Hash Algorithm 2 (SHA-2) with 256 bits hash value.""" return Hash("sha256", buffer)
23,627
def go(): """ Simple message queuing broker Same as request-reply broker but using QUEUE device """ # Create ROUTER socket. Socket facing clients frontend = yield from aiozmq.create_zmq_stream(zmq.ROUTER, bind='tcp://*:5559') # create DEALER socket. Socket facing services backend = yie...
23,628
def nmc_eig(model, design, observation_labels, target_labels=None, N=100, M=10, M_prime=None, independent_priors=False): """ Nested Monte Carlo estimate of the expected information gain (EIG). The estimate is, when there are not any random effects, .. math:: \\frac{1}{N}\\sum_{n=1}^...
23,629
def _orient_eigs(eigvecs, phasing_track, corr_metric=None): """ Orient each eigenvector deterministically according to the orientation that correlates better with the phasing track. Parameters ---------- eigvecs : 2D array (n, k) `k` eigenvectors (as columns). phasing_track : 1D arr...
23,630
def test_atomic_positive_integer_max_inclusive_4_nistxml_sv_iv_atomic_positive_integer_max_inclusive_5_5(mode, save_output, output_format): """ Type atomic/positiveInteger is restricted by facet maxInclusive with value 999999999999999999. """ assert_bindings( schema="nistData/atomic/positive...
23,631
def test_ihex_cut_1(datadir, capsys): """測試切割頁面函式 NOTE: 此函式輸入資料須為經過padding之codeblock 大小須符合 pgsz * N """ input = [ { 'address': 0, 'data': b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F' }, { 'address': 0xA...
23,632
def transform(item_paths, output_dir, compresslevel=0): """Transform the bmeg input to gen3 output directory.""" projects_emitter = emitter('project', output_dir=output_dir) experiments_emitter = emitter('experiment', output_dir=output_dir) cases_emitter = emitter('case', output_dir=output_dir) demo...
23,633
def test_CreativeProject_auto_multivariate_functional(max_iter, max_response, error_lim, model_type): """ test that auto method works for a particular multivariate (bivariate) function """ # define data covars = [(0.5, 0, 1), (0.5, 0, 1)] # covariates come as a list of tuples (one per covariate: (...
23,634
def applyCustomTitles(titles): """ Creates 'chapters-new.xml' which has the user created chapter names. """ # Read 'chapters.xml' into a string. with open('chapters.xml', 'rb') as f: xmlstr = f.read() # Since ElementTree doesn't have support for reading/writing the # DOCTYPE line fro...
23,635
def test_remove_field(): """Tests whether removing a field properly removes the index.""" test = migrations.remove_field( HStoreField(uniqueness=["beer"]), ["CREATE UNIQUE", "DROP INDEX"] ) with test as calls: assert len(calls.get("CREATE UNIQUE", [])) == 0 assert len(calls...
23,636
def configure_logging(verbose: int = 0) -> None: """Set loglevel. If ``-v`` flag passed to commandline decrease runtime loglevel for every repeat occurrence. ``-vvvv`` will always set logging to ``DEBUG``. Default loglevel is set in the toml config and overridden by environment variable if th...
23,637
def crossValidate(x, y, cv=5, K=None): """ :param y: N*L ranking vectors :return: """ results = {"perf": []} ## cross validation ## np.random.seed(1100) kf = KFold(n_splits=cv, shuffle=True, random_state=0) for train, test in kf.split(x): x_train = x[train, :] y_trai...
23,638
def make_word_groups(vocab_words): """ :param vocab_words: list of vocabulary words with a prefix. :return: str of prefix followed by vocabulary words with prefix applied, separated by ' :: '. This function takes a `vocab_words` list and returns a string with the prefix and the words...
23,639
def sync(input, output, all, overwrite): """Synchronise all your files between two places""" print("Syncing")
23,640
def gpi_g10s40(rescale=False): """ Multiply by the 'rescale' factor to adjust hole sizes and centers in entrance pupil (PM) (Magnify the physical mask coordinates up to the primary mirror size) """ demag = gpi_mag_asdesigned() if rescale: demag = demag/rescale # rescale 1.1 gives a bigge...
23,641
def test_close_sections(): """Parse sections without blank lines in between.""" def f(x, y, z): """ Parameters ---------- x : X y : Y z : Z Raises ------ Error2 error. Error1 ...
23,642
def get_good_contours(proc_image, image, bb, savedir, max_num_add=None): """ Adapted from `click_and_crop_v3.py`, except that we have to make the contours. Here, we're going to inspect and check that the contours are reasonable. Returns a list of processed contours that I'll then use for later. """...
23,643
def _int_converter(value): """Convert string value to int. We do not use the int converter default exception since we want to make sure the exact http response code. Raises: exception_handler.BadRequest if value can not be parsed to int. Examples: /<request_path>?count=10 parsed to {'count':...
23,644
def plot_iminuit_contours(): """plot the confidence contours obtained from the sherpa fit """ log.info("plotting parameters contours obtained from iminuit") # where to take the results, configurations for the individual butterflies instruments = ["fermi", "magic", "veritas", "fact", "hess", "joint"]...
23,645
def split_rule(rules, rule_name, symbols_to_extract: List[str], subrule_name: str): """ Let only options which are starting with symbols from symbols_to_extract. Put the rest to a subrule. """ r = rule_by_name(rules, rule_name) assert isinstance(r.body, Antlr4Selection), r sub_options = An...
23,646
def ESS(works_prev, works_incremental): """ compute the effective sample size (ESS) as given in Eq 3.15 in https://arxiv.org/abs/1303.3123. Parameters ---------- works_prev: np.array np.array of floats representing the accumulated works at t-1 (unnormalized) works_incremental: np.array ...
23,647
def new_line_over(): """Creates a new line over the cursor. The cursor is also moved to the beginning of the new line. It is not possible to create more than one new line over the cursor at a time for now. Usage: `In a config file:` .. code-block:: yaml - new_line_over: `Usi...
23,648
def lambda_handler(event, context): """Calls custom job waiter developed by user Arguments: event {dict} -- Dictionary with details on previous processing step context {dict} -- Dictionary with details on Lambda context Returns: {dict} -- Dictionary with Processed Bucket, Key(s) an...
23,649
def put_path(components, value): """Recursive function to put value in component""" if len(components) > 1: new = components.pop(0) value = put_path(components, value) else: new = components[0] return {new: value}
23,650
def con_orthogonal_checkboard(X,c_v1,c_v2,c_v3,c_v4,num,N): """for principal / isothermic / developable mesh / aux_diamond / aux_cmc (v1-v3)*(v2-v4)=0 """ col = np.r_[c_v1,c_v2,c_v3,c_v4] row = np.tile(np.arange(num),12) d1 = X[c_v2]-X[c_v4] d2 = X[c_v1]-X[c_v3] d3 = X[c_v4]-X[c_v2] ...
23,651
def _do_callback(s, begin, end, taglist, cont_handler, attrlookup): """internal function to convert the tagtable into ContentHandler events 's' is the input text 'begin' is the current position in the text 'end' is 1 past the last position of the text allowed to be parsed 'taglist' is the tag list ...
23,652
def _PropertyGridInterface_GetPropertyValues(self, dict_=None, as_strings=False, inc_attributes=False): """ Returns all property values in the grid. :param `dict_`: A to fill with the property values. If not given, then a new one is created. The dict_ can be an object as well, in ...
23,653
def get_pipelines(exp_type, cal_ver=None, context=None): """Given `exp_type` and `cal_ver` and `context`, locate the appropriate SYSTEM CRDSCFG reference file and determine the sequence of pipeline .cfgs required to process that exp_type. """ context = _get_missing_context(context) cal_ver = _g...
23,654
def distance_to_line(p,a,b): """ Computes the perpendicular distance from a point to an infinite line. Parameters ---------- p : (x,y) Coordinates of a point. a : (x,y) Coordinates of a point on a line. b : (x,y) Coordinates of another point on a line....
23,655
def list(): """ List current config settings """ downloader = create_downloader() click.echo(f"""Download german if available:\t{downloader.config.german or False} Download japanese if available:\t{downloader.config.japanese or False} Highest download quality:\t{downloader.config.quality.name if dow...
23,656
def rate_limited_imap(f, l): """A threaded imap that does not produce elements faster than they are consumed""" pool = ThreadPool(1) res = None for i in l: res_next = pool.apply_async(f, (i, )) if res: yield res.get() res = res_next yield res.get()
23,657
def test(model, dataloader, criterion, params): """Test the model using the testloader.""" model.eval() test_loss = 0 test_correct = 0 test_inputs = 0 bar = tqdm(enumerate(dataloader), total=len(dataloader), desc='Test: ') with torch.no_grad(): for _, (inputs, labels) in bar: ...
23,658
def pearsonr(A, B): """ A broadcasting method to compute pearson r and p ----------------------------------------------- Parameters: A: matrix A, (i*k) B: matrix B, (j*k) Return: rcorr: matrix correlation, (i*j) pcorr: matrix correlation p, (i*j) Example: ...
23,659
def test_get_team_member(client, jwt, session): """Assert that the endpoint returns the success status.""" team = create_team(client, jwt, member_role=ProjectRoles.Manager) response = _get_team_member_(client, jwt, str(team['projectId']), str(team['id'])) assert response.status_code == HTTPStatus.OK
23,660
def test_lovasz(S): """ >>> ha = qudit('a', 3) >>> np.random.seed(1) >>> S = TensorSubspace.create_random_hermitian(ha, 5, tracefree=True).perp() >>> test_lovasz(S) t: 3.8069736 total err: 0.0000000 total err: 0.0000000 duality gap: 0.0000000 """ cvxopt.solvers.options['show...
23,661
def inst_bench(dt, gt, bOpts, tp=None, fp=None, score=None, numInst=None): """ ap, rec, prec, npos, details = inst_bench(dt, gt, bOpts, tp = None, fp = None, sc = None, numInst = None) dt - a list with a dict for each image and with following fields .boxInfo - info that will be used to cpmpute the ...
23,662
def getpid(): # real signature unknown; restored from __doc__ """ getpid() -> pid Return the current process id """ pass
23,663
def _tee( cmd: str, executable: str, abort_on_error: bool ) -> Tuple[int, List[str]]: """ Execute command "cmd", capturing its output and removing empty lines. :return: list of strings """ _LOG.debug("cmd=%s executable=%s", cmd, executable) rc, output = hsysinte.system_to_string(cmd, abort_...
23,664
def normalized_str(token): """ Return as-is text for tokens that are proper nouns or acronyms, lemmatized text for everything else. Args: token (``spacy.Token`` or ``spacy.Span``) Returns: str """ if isinstance(token, SpacyToken): return token.text if preserve_case(...
23,665
def scatter_nd(*args, **kwargs): """ See https://www.tensorflow.org/api_docs/python/tf/scatter_nd . """ return tensorflow.scatter_nd(*args, **kwargs)
23,666
def validate_element(element, validator, csv_schema=SCHEMA): """Raise ValidationError if element does not match schema""" if validator.validate(element, csv_schema) is not True: field, errors = next(iter(validator.errors.items())) message_string = '''\nElement of type '{0}' has the following ...
23,667
def format_errors(errors, indent=0, prefix='', suffix=''): """ string: "example" "example" dict: "example": - """ if is_single_item_iterable(errors): errors = errors[0] if isinstance(errors, SINGULAR_TYPES): yield indent_message(repr(errors), indent...
23,668
def concatenate_sequences(X: Union[list, np.ndarray], y: Union[list, np.ndarray], sequence_to_value: bool = False) \ -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Concatenate multiple sequences to scikit-learn compatible numpy arrays. ´Parameters ----------- X ...
23,669
def print_help_page(bot, file=sys.stdout): """print help page""" def p(text): print(text, file=file) plugin = bot.get_plugin(Commands) title = "Available Commands for {nick} at {host}".format(**bot.config) p("=" * len(title)) p(title) p("=" * len(title)) p('') p('.. contents:...
23,670
def get_export_table_operator(table_name, dag=None): """Get templated BigQueryToCloudStorageOperator. Args: table_name (string): Name of the table to export. dag (airflow.models.DAG): DAG used by context_manager. e.g. `with get_dag() as dag: get_export_table_operator(..., dag=dag)`. Defaults to...
23,671
def test_winner_solver_after_run(): """Assert that the solver is the winning model after run.""" atom = ATOMClassifier(X_class, y_class, random_state=1) atom.run("LR") atom.branch = "fs_branch" atom.feature_selection(strategy="sfm", solver=None, n_features=8) assert atom.pipeline[0].sfm.estimato...
23,672
def run_command_with_code(cmd, redirect_output=True, check_exit_code=True): """Runs a command in an out-of-process shell. Returns the output of that command. Working directory is self.root. """ if redirect_output: stdout = sp.PIPE else: stdout = None p...
23,673
async def delete_project( delete_project_request: DeleteProject, token: str = Depends(oauth2_scheme) ): """[API router to delete project on AWS Rekognition] Args: delete_project_request (DeleteProject): [AWS Rekognition create project request] token (str, optional): [Bearer token for authen...
23,674
def _create_element_invocation(span_: span.Span, callee: Union[ast.NameRef, ast.ModRef], arg_array: ast.Expr) -> ast.Invocation: """Creates a function invocation on the first element of the given array. We need to create ...
23,675
def evaluate(feature_dir, prefix, settings, total_runs=10): """to evaluate and rank results for SYSU_MM01 dataset Arguments: feature_dir {str} -- a dir where features are saved prefix {str} -- prefix of file names """ gallery_cams, probe_cams = gen_utils.get_cam_settings(settings) ...
23,676
def test_door_pause_protocol(enable_door_safety_switch): """ Test that when the door safety switch is enabled, pause cannot be resumed until the door is closed """ pause_mgr = PauseManager(door_state=DoorState.CLOSED) assert pause_mgr.queue == [] pause_mgr.set_door(door_state=DoorState.OPEN...
23,677
def _CreateClassToFileNameDict(test_apk): """Creates a dict mapping classes to file names from size-info apk.""" constants.CheckOutputDirectory() test_apk_size_info = os.path.join(constants.GetOutDirectory(), 'size-info', os.path.basename(test_apk) + '.jar.info') class_to_fi...
23,678
def main(): """main function """ bcl2fastq_qc_script = os.path.abspath(os.path.join( os.path.dirname(sys.argv[0]), "bcl2fastq_qc.py")) assert os.path.exists(bcl2fastq_qc_script) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-t', "--testing", action='store_tru...
23,679
def train_deeper_better(train_data, train_labels, test_data, test_labels, params): """Same as 'train_deeper', but now with tf.contrib.data.Dataset input pipeline.""" default_params = { 'regularization_coeff': 0.00001, 'keep_prob': 0.5, 'batch_size': 128, 'fc1_size': 2048, ...
23,680
def assert_almost_equal( actual: Tuple[numpy.float64, numpy.float64], desired: numpy.ndarray, decimal: int ): """ usage.statsmodels: 4 """ ...
23,681
def test_data(landsat_number): """ Downloads a dataset for testing from Landsat 4, 5, 7, or 8 *Note that you must be signed into earthexplorer.usgs.gov Inputs: landsat_number 4, 5, 7, or 8 - the desired Landsat satellites to sample data from """ #ensure the input landsat number i...
23,682
def clear_file(filename: str): """Method to clean file.""" open(filename, 'w').close()
23,683
def redirect_return(): """Redirects back from page with url generated by url_return.""" return redirect(str(Url.get_return()))
23,684
def ButtonDisplay(hand_view): """ This updates draw pile and action buttons. It is called in HandView.update each render cycle. """ loc_xy = (hand_view.draw_pile.x, hand_view.draw_pile.y) hand_view.draw_pile.draw(hand_view.display, loc_xy, hand_view.draw_pile.outline_color) # update discard info and red...
23,685
def setup(coresys: CoreSys) -> EvaluateBase: """Initialize evaluation-setup function.""" return EvaluateOperatingSystem(coresys)
23,686
def _weight_initializers(seed=42): """Function returns initilializers to be used in the model.""" kernel_initializer = tf.keras.initializers.TruncatedNormal( mean=0.0, stddev=0.02, seed=seed ) bias_initializer = tf.keras.initializers.Zeros() return kernel_initializer, bias_initializer
23,687
def unot(b: bool) -> bool: """ """ ...
23,688
def inputs(eval_data, data_dir, batch_size): """Construct input for eye evaluation using the Reader ops. Args: eval_data: bool, indicating if one should use the train or eval data set. data_dir: Path to the eye data directory. batch_size: Number of images per batch. Returns: images...
23,689
def test_queryparser_stoplist_iter(): """Test QueryParser stoplist iterator. """ stemmer = xapian.Stem('en') # Check behaviour without having set a stoplist. queryparser = xapian.QueryParser() queryparser.set_stemmer(stemmer) queryparser.set_stemming_strategy(queryparser.STEM_SOME) exp...
23,690
def build_docker_image_docker(context, docker_file, external_docker_name, push_connection: Connection, pull_connection: typing.Optional[Connection] = None): """ Build and push docker image ...
23,691
def get_non_ready_rs_pod_names(namespace): """ get names of rs pods that are not ready """ pod_names = [] rs_pods = get_pods(namespace, selector='redis.io/role=node') if not rs_pods: logger.info("Namespace '%s': cannot find redis enterprise pods", namespace) return [] fo...
23,692
async def test_async_get_book(aresponses, readarr_client: ReadarrClient) -> None: """Test getting book info.""" aresponses.add( "127.0.0.1:8787", f"/api/{READARR_API}/book/0", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/js...
23,693
def lookup_material_probase(information_extractor, query, num): """Lookup material in Probase""" material_params = { 'instance': query, 'topK': num } result = information_extractor.lookup_probase(material_params) rank = information_extractor.rank_probase_result_material(result) r...
23,694
def get_unexpected_exit_events(op): """Return all unexpected exit status events.""" events = get_events(op) if not events: return None return [e for e in events if is_unexpected_exit_status_event(e)]
23,695
def count_reads(config_file, input_dir, tmp_dir, output_dir, read_counts_file, log_file, run_config): """ Count reads using :py:mod:`riboviz.tools.count_reads`. :param config_file: Configuration file (input) :type config_file: str or unicode :param input_dir: Input directory :ty...
23,696
async def delete_user(username: str) -> GenericResponse: """Delete concrete user by username""" try: await MongoDbWrapper().remove_user(username) except Exception as exception_message: raise DatabaseException(error=exception_message) return GenericResponse(detail="Deleted user")
23,697
def concat_files(concat_filename="similar.txt"): """ searches for a file named similar.txt in sub directories and writes the content of this to a file in the main directory """ inpath = concatPath("") outstring = "" for (dirpath, dirnames, filenames) in os.walk(inpath): if not inpath...
23,698
def get_changelog(): """download ChangeLog.txt from github, extract latest version number, return a tuple of (latest_version, contents) """ # url will be chosen depend on frozen state of the application source_code_url = 'https://github.com/pyIDM/pyIDM/raw/master/ChangeLog.txt' new_release_url = 'h...
23,699