content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def remove_unwanted_chars(x: str, *chars: str, to_replace: str = "") -> str: """Remove unwanted characters from a string.""" return re.sub(f"[{''.join(chars)}]", to_replace, x)
4a1e25b1ad12f47f835d4f6cdbac4a6e08413077
72,700
async def get_by_name(name : str, current_user: User = Depends(get_current_active_user)): """ Looks for an item in the database """ data = await fetch_item(name) if data is None: return HTTPException(404, "Item not found") return data
841cfa4854f54076d7e6bcf29ad321ccd73382f1
72,701
def readMatrix( infile, format = "full", separator = "\t", numeric_type = numpy.float, take = "all", headers = True, missing = None, ): """read a matrix from file ane return a numpy matrix. formats a...
bb63ebf3319ef6a547794fe963fd3323b06a6da8
72,702
from typing import List def ranked_followers(username: str, rank_by: str, value: str) -> List[Follower]: """ Rank followers based on specified criteria using db queries. Return a list of ranked followers' user id and their screen names who have not already been sent a DM. params: username...
232ca94bed58a12b086fccc760fbfd73f5d19208
72,703
def get_entity_group_version(entity_or_key): """Returns the version of the entity group containing `entity_or_key`. Args: entity_or_key: a key or entity whose version you want. Returns: The version of the entity group containing `entity_or_key`. This version is guaranteed to increase on every change to t...
11f6a3fa0f0ff93a3201e1208c2b591dd686a7c2
72,704
def get_first_shape(node): """ Returns the first active shape on a given transform :param node: str, transform node to get shape from :return: str """ shapes = get_shapes(node=node, non_intermediates=True, intermediates=False) if shapes: return shapes[0] return None
c8dfdcbabfce591e9484c8023f6a1ab42b20a9cb
72,705
def UDPOS(*args, **kwargs): """ Universal Dependencies English Web Treebank Separately returns the training, validation, and test dataset Arguments: root: Directory where the datasets are saved. Default: ".data" vocabs: A list of voabularies for each columns in the dataset. Must be in an ...
fba09e0dbdeb79fab747ab39b990632563622174
72,706
def generate_openid_signature(openid): """对openid进行加密,返回加密后的openID""" # 1.创建加密的实例对象 serializer = Serializer(settings.SECRET_KEY, 600) # 2.调用dumps方法进行加密,返回bytes类型 data = {'openid': openid} openid_sign = serializer.dumps(data) # 3.返回 return openid_sign.decode()
99203760d8e8efaae0731e3c9054898308072697
72,707
def write_the_species_tree(annotated_species_tree, output_file): """ this function writes the species tree to file args: annotated_species_tree : a string of annotated species tree in .newick format output_file : a file name to write to output: a file containing the annotated sp...
7db9d5fc10cd27b1e7a5e51427e7de6991a1157a
72,708
import functools def compose(*functions): """ A functional helper for dealing with function compositions. It ignores any None functions, and if all are None, it returns None. Parameters ---------- *functions function arguments to compose Returns ------- function or None ...
8a18b1e0beef43c0cfac4439fa158675a486b560
72,709
import os import shutil def remove_any_tmp_dir(): """ Remove the temporary directory if it exists. Returns its location either way. """ tmp_dir = get_tmp_dir() if os.path.exists(tmp_dir): shutil.rmtree(tmp_dir) return tmp_dir
5156cad84f7455d32a7b9e77f18e9fc94a71a4e1
72,710
def pretty_print_list(lst, name = 'features', repr_format=True): """ Pretty print a list to be readable. """ if not lst or len(lst) < 8: if repr_format: return lst.__repr__() else: return ', '.join(map(str, lst)) else: topk = ', '.join(map(str, lst[:3])) ...
d199261e6b9fd226256a151601d0bd86e7458fe1
72,711
import json def load_api_config(): """Grab our config parameters from our provided config file (JSON format).""" with open(Config.config_file, 'r', encoding="utf-8") as file_config: conf = json.loads(file_config.read()) return OAuth2(client_id=conf["falcon_client_id"], client_se...
7c73cfd066e4f243c80cfc098c3950b4801f157f
72,712
def factorial(n): """ :type n: int :rtype: int """ f = n for i in range(n - 1, 0, -1): f = f * i return f
17d6e211911417507e5887232f181bf774396c73
72,713
def train_model(X_train, Y_train): """ This function takes in the training data and label arrays and returns a clf classifier object """ n_estimators = 400 max_depth = 5 min_child_weight = 5 learning_rate = 0.1 clf = XGBClassifier(n_estimators=n_estimators, max_d...
b4e0c26796b14ff1938f736f8dcb5420cccff9c2
72,714
def pairify(string): """Convert a string of the form "key: value" to a tuple ("key", "value"). May raise a ParseError.""" items = string.split(":", 1) try: return items[0].strip(), items[1].strip() except IndexError: raise ParseError("'%s': Keys must be terminated with a colon." % ...
1541e94b4fb6feba91c07f71445e719832afa687
72,715
def get_provenance_record(attributes, ancestor_files, plot_type): """Create a provenance record describing the diagnostic data and plot.""" caption = ("Correlation of {long_name} between {dataset} and " "{reference_dataset}.".format(**attributes)) record = { 'caption': caption, ...
3b813a500edd4e93becb469d5cb967a4e32465b4
72,716
def encryptCharacter(PQ, character, powers): """Encrypting a single given character""" ascii = getAscii(character) k = 0 powers.setPrevSQR(ascii, k) modNum = ascii % PQ powers.setModNum(modNum, k) for x in range(0, powers.getLength() - 1): k = k + 1 prevSQR = modNum * modNum ...
dd206c39e5fe80fec0290a226f8341b2fa9a475d
72,717
def matching( obs0, obs1, cost_fn, min_cost, max_cost ): """ match objects using cost fn where min_cost <= cost <= max_cost, return list of index tuple matches """ m = cost_matrix( obs0, obs1, cost_fn ) row_idx, col_idx = linear_sum_assignment( m ) result = [] for i in range( len(col_idx) ): ...
fc95d8ec487eea2e78db7bb3e0d68f5a8757ba3a
72,718
def _resource_schema_base(available_resources, selected_resources): """Resource selection schema.""" known_available_resources = { sensor_id: sensor[0] for sensor_id, sensor in SENSOR_TYPES.items() if sensor_id in available_resources } return { vol.Required(CONF_RESOURC...
0c41f907fea5792b586ad9bad90085c9ef248906
72,719
import os import uuid import requests import html def download_page(url, cookie_jar): """ Request page using authenticated cookies (cookiejar). Download html source and save in browser directory, to be used by in show_in_browser(). """ browser_dir = os.path.join(server_path, 'static/browser') ...
c97b39434d5793c7b58229b43eb8365dfc326980
72,720
import json import os import pandas as pd import numpy as np def load_fry(frydir, output_format="scRNA", nonzero=False, quiet=False): """ load alevin-fry quantification result into an AnnData object Required Parameters ---------- frydir : `str` The path to a output directory returned by a...
d77b41f1df3c23c937131a3559691c78cdc3c867
72,721
from typing import Optional from operator import or_ def get_resource_holders_permissions( db_session: Session, resource_id: UUID, holder_id: Optional[UUID] = None ) -> data.ResourceHoldersListResponse: """ Get list of permissions for exact holder. """ query = ( db_session.query( ...
a64f71eba95a0ab1852c8be097ace96f6361341e
72,722
def delete_user(self): """" function to check if the user is deleted """ return User.user_list.remove(self)
6fb17b7d5794174de44954243258d9c83782b8d5
72,723
def calcMaxEntPolicy(trans_mat, horizon, r_weights, state_features, beta): """ For a given reward function and horizon, calculate the MaxEnt policy that gives equal weight to equal reward trajectories trans_mat: an S x A x S' array of transition probabilites from state s to s' if action a is taken horizon: t...
5615fbbc86a0a80cdeae59b5e5790f1b379ac6df
72,724
def bed_count_region_overlaps(site_bed, region_bed, overlap_out, only_incomplete=False, intersectBed_f=False): """ Overlap sites with regions, and return number of sites overlapping for each region. Also return the list of site IDs for each region....
f456b4b0388e5e9c2b57fc1178ee25f9c13b9b64
72,725
def _generate_fake_input_arg_componentsdk(arg_spec): """Generate a fake argument value for inputs of module spec Args: arg_spec (dict) : argument specification from yaml module spec Returns: object: sample fake value Raises: NotImplementedError: if arg type is not implemented ...
62d92059ff6df74f4f08e6c2d09186f48058b617
72,726
def get_matrix26(): """ Return the matrix with ID 26. """ return [ [4.0, 4.0, 7.0, 7.0], [3.0, 3.0, 7.0, 7.0], [2.0, 2.0, 7.0, 7.0], [1.0, 1.0, 7.0], [0.0, 0.0, 7.0, 7.0], ]
9650bda70c0b7818950d1165edaadc7a6e2df889
72,727
def get_shortest_path(start, goal): """ Returns shortest path. For this problem space some of the problems have more than one problem space. This function returns the first occurrence it finds :param start: node from :param goal: node to :return: list of the path with the shortest walk f...
a41bead86fb21bf99b2035568bc6fc035152de11
72,728
import os def format_filename_target(path): """ Swaps /source/ to /target/ + extra formatting. :param path: :return: """ base = os.path.dirname(path.replace("\source\\", "\\target\\")) # TODO Better this. if GLOBAL_FLAG is EXTENSIONS.TXT: return f'{base}\\{os.path.basename(path...
e8b0672526b812a28887a282ad1b76a21d96069d
72,729
from typing import OrderedDict def finalize_autosummaries() -> None: """Create the necessary ops to include autosummaries in TensorBoard report. Note: This should be done only once per graph. """ global _finalized tfutil.assert_tf_initialized() if _finalized: return None _finaliz...
50f5520dd9684c957d30bc470ef97f28102e75d9
72,730
from ..model.types import TypeReference from typing import Union def package_local_name(obj: "Union[_Name, TypeReference]") -> str: """ Return the name of a DAML object, assuming that the referent exists in the same package as the target (i.e., _not_ scoped with a package ID). """ # TODO: Rewrite...
2be9a0baafc36760d914ecb5997757d64cb6d046
72,731
def create_model(model_object, input_data, model_name: str = None) -> Model: """ Creates Model instance from arbitrary model objects and sample of input data :param model_object: model object (function, sklearn model, tensorflow output tensor list etc) :param input_data: sample of input data (numpy arr...
b54fe92a73bb22ca3da8a8845d364af385003d8b
72,732
def make_disjunctive_chaum_pedersen_zero( message: ElGamalCiphertext, r: ElementModQ, k: ElementModP, seed: ElementModQ ) -> DisjunctiveChaumPedersenProof: """ Produces a "disjunctive" proof that an encryption of zero is either an encrypted zero or one. :param message: An ElGamal ciphertext :param ...
97b0b15b265b795bfcf0e2e8d3ca0737dda8c455
72,733
def get_conf_dfs(df, log=False): """Df is info df, return the collection of dfs in the confirmed_df_dict column with some extra information.""" df_all = pd.DataFrame() for _, row in df.iterrows(): site = row["site"] try: df_frame = pd.DataFrame(row["confirmed_df_dict"]) ...
89e97635edd8062d1ec1cb0878114467e80298ae
72,734
def vib_ent(temp, t_d_perov, t_d_brownm): """ Vibrational entropy based on the Debye model :param temp: temperature :param delta: non-stoichiometry delta :return: vibrational entropy """ # integral for vibrational entropy using the Debye model def s_int(temp, t_d...
aa4ceeadc9be5e6f1489c8f9cf6ebb10908d0d05
72,735
import tqdm import time import logging import torch from typing import OrderedDict def train(train_loader, model, criterion, optimizer, scheduler, num_classes, batch_size, ep_idx, progress_log, device, scale, ...
73cf675c5446ba407908dca6fdf7b0c6406b1ff4
72,736
def Object_ClassName(): """Object_ClassName() -> char const *""" return _DataModel.Object_ClassName()
54043519d451286642268c6c971e3cad60a176c2
72,737
def get_model_from_key(key: str) -> object: """ Get model from key """ class_name, pk = key.split(":", 1) return apps.get_model(class_name)
fea798a3626bd516edcda64ad18e278537f3b159
72,738
def hernquist_profile_3d(cosmo, concentration, halo_mass, odelta, a, r): """Calculate the 3D Hernquist halo profile at a given radius or an array of radii, for a halo with a given mass, mass definition, and concentration, at a given scale factor, with a cosmology dependence. .. note:: Note that thi...
b7257e15408694220aa13d299ea4e346a30fb2c5
72,739
def masked_softmax(data, mask, dim=-1): """Computes the axis wise softmax over chosen elements. Args: data: 2-D float `Tensor` of size [n, m]. mask: 2-D boolean `Tensor` of size [n, m]. dim: The dimension over which to compute the softmax. Returns: masked_softmax: 2-D float `Tensor` of size [n, ...
befba39ab8a43d5b09618461aa9c46523fce6515
72,740
def bc(n, k): """ return the binomial coefficient "n choose k". Can you figure out a method that is less likely to cause an overflow than using the formula(n*(n-1)*...*(n-k+1))/(k*(k-1)*...*2)? """ return special.binom(n, k)
140b4b84fb370fb8ffd7ae61b3a8c67f4766c50a
72,741
def get_data(lookup_key: str, location: str) -> pd.DataFrame: """Retrieves data from an appropriate source. Parameters ---------- lookup_key The key that will eventually get put in the artifact with the requested data. location The location to get data for. Returns ...
217c9f4dae939f7f073a98885638b9bbc64f342b
72,742
def handle_http_error(response): """ Check HTTP response for errors and process them accordingly. :param response: HTTP response to check """ if response.status_code != 200: # check if there is some info about error in json format if response.headers.get("content-type") == "applicat...
ca2f9ecc414b1d6a60a29f5e10952acf2cd4ada7
72,743
import math import copy def golden_section_search(var1, func, point=True, e=EPSILON, idx=0, print_stats=False): """ Golden section search algorithm :param var1: Can be list with two elements representing the interval or can be single number from which we find unimodal interval. :param func: Function t...
698aa3750dc7632c0e27cb2381da4731af7ba5ae
72,744
def gradient(P, Q, Y): """ Calculates the gradient of the Kullback-Leibler divergence between P and Q :param P: the joint probability matrix :param Q: the Student-t based joint probability distribution matrix :param Y: low dimensional matrix representation of high dimensional matrix X :return: a...
b08116b5bca764b1b9149eaf03f7b3525c99ce3e
72,745
def _exclude_loop_arguments_variables( param: _pipeline_param.PipelineParam) -> str: """Gets the pipeline param name excluding loop argument variables. Args: param: The pipeline param object which may or may not be a loop argument. Returns: The full name of the pipeline param without loop arguments ...
5c7d55c75db12afe6862a79d7fc8745443a650b6
72,746
import logging def rulextraction(source_side, target_side, alignment, max_nonterminals=2, nodeset_size_limit=5, initial_rule_nodeset_size_limit=0, subgraph_df_limit=100, parse_graph=False): """ Extract the maximum set of rules allowed under constraints from a single example consisting of sour...
c8eb06e737c2f183a8bbeb152b3788894856271b
72,747
import os import zipfile def make_lib_c(lib_name, lib_path, deploy_path): """ pyc打包单个库 :param lib_name: string jszt_core_py :param lib_path: string 库路径 :param deploy_path: string 部署文件路径 :return: """ lib_path = os.path.join(lib_path, lib_name) zip_path = "%s.zip" % deploy_path z...
68ad788bdc118b7e49386e79321cac6054599b8a
72,748
def get_integration_filter(args, targets): # type: (IntegrationConfig, t.List[IntegrationTarget]) -> t.Set[str] """Return a list of test targets to skip based on the host(s) that will be used to run the specified test targets.""" invalid_targets = sorted(target.name for target in targets if target.target_type ...
46a936aa797b928506ba2328034c1319da3f821a
72,749
def callback(func): """Decorator for non blocking functions.""" setattr(func, "_pyhap_callback", True) return func
6b1f2297dda8c7b3df5a75142a921e20fd4768f8
72,750
def docker_compose_project_name(): """Set a consistent project name to enable optional reuse of containers.""" return "pytest-python-gitlab"
0c8ed2e63692fec969c042b4e2e8094459045c5b
72,751
def midi_to_seq( midi_obj, dtype=np.int16, rate=22050, pitch_aug_factor=0, time_aug_factor=1, mode="format", time_shift=0.0125 ): """method for midi_obj. Input: miditoolkit_object, sampling rate Output: note_seq: np.array([pitch1,pitch2....]), which length is equal to note.time*rate ...
ab4f6dad327e1b1c5e7715fb765aaefc33146115
72,752
def units_LexiconFormula(*args): """ * Return a unique instance of LexiconFormula. :rtype: Handle_Units_Lexicon """ return _Units.units_LexiconFormula(*args)
63240baa2e30e3ed0d6fa7ead3768741b57bfb7f
72,753
def stop(backupplan_name, p5_connection=None): """ Syntax: BackupPlan <name> stop Description: Removes the plan <name> from the scheduler Return Values: -On Success: the string "1" (the plan was successfully removed) the string "0" (the plan was not removed or is running) ...
e73dbe04bc0fc8824d144ff12361a03d30ab5c1b
72,754
from twisted.internet import defer def check_eu_vat_id(vatid): """Check an EU VAT ID string (of the form: FI01234567) and return True if it is currently valid. """ def _success(res): vat_valid = False if hasattr(res, 'valid'): if res.valid == 1: return Tru...
8bdd8cb25a549bf597057c761f47030c2db0a576
72,755
def heron(_a, tol, _x0=None, termination_criterion='x'): """ Method for finding the non-negative, square root of a real number. """ def func(_x): return _x**2 - _a def dfunc(_x): return 2*_x if _x0 is None: _x0 = _a return newton(func, dfunc, _x0, tol, ...
f0580093f1fa5b0d008c290c74b3e5403f36aa30
72,756
def shopping_graphplan(): """Solves the shopping problem using GraphPlan""" return GraphPlan(shopping_problem()).execute()
c0a1cf31ebf796ec2b0b879780661113e6691ed9
72,757
from operator import gt def _nodes2dataframe(G: gt.Graph) -> NodeDataFrame: """ Takes a Graph-tool graph object and returns nodes data frame. """ expect_nodes(G) if len(G.vp) != 0: prop_dfs = [] for prop in G.vp: prop_dfs.append(NodeDataFrame({f"{prop}": list(G.vp[f"{pr...
a517e8ee8aaedde3ebaeb4a916eec35260b49352
72,758
def get_config_inifile(filename): """Read configuration from INI file and return a config dict. Arguments: - filename: Name of INI file. """ # SR_TODO: default config parser = SafeConfigParser() parser.optionxform = str # to preserve case parser.read(filename) log.debug("read conf...
426a7f4e30c9a42aea5427d99482185784816dcc
72,759
import bisect def clause_b_1_3_3_T_m_i_beam( I_z_1, I_z_2, I_z_3, I_z_4, I_f_1, I_f_2, I_f_3, I_f_4, alpha, T_z_1, T_z_2, sigma: float = 5.67e-11, *_, **__ ): """ :param I_z: :param I_f: :param alpha: :param sigma: :return: """ ...
9e0b2f32641c905aedb019ec4bb986297371f198
72,760
def _partition(entity, sep): """Python2.4 doesn't have a partition method so we provide our own that mimics str.partition from later releases. Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the...
0172ce09bd0451eb538122bd9566a3e70d0dcc15
72,761
def get_config_bool(name, fallback=False): """Checks if a config value is set to a valid bool value.""" cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX) return cli_config.getboolean('servicefabric', name, fallback)
3e18b97b12dd7446b973ffb3215d823d75857d26
72,762
def get_user_access_rights(username: str, is_vendor: bool = False): """ Query Redis for information about the user by given username. Arguments: :param username (str) authorized user's username :param is_vendor (bool) whether method should return vendor or SDO accessRigt """ ...
90d230129a2a09ea848ef11eb0b7e83cbe8624e8
72,763
def safe_email(email): """Scrub email address before using it.""" if EMAIL_REGEX.match(email) is not None: return not email.startswith(".") and ".." not in email logger.warning("Invalid email address: %s.", email) return False
68868e5bdfb413caf2f94edb096f319292fe064c
72,764
def read_data(byte_data_directory, x_filename, y_filename=None): """ reads in byte date from a list of filenames given in file located at x_filename. if y_filename is supplied labels will be read in and a map will be created as well and a label column added to the returned dataframe """ X_files...
3566963b1f9b27957585f2de561b45b0c5d86915
72,765
def get_region_name(): """ Return EMR cluster region as string :return: """ return get_extraInstanceData()['region']
628a932cb24352b0ca72cc8741172887251ee020
72,766
def split_into_fixed_length_chunks(dataset, fixed_length, min_length=32, keep_residuals=False): """ Splits the sequences into shorter sequences with the same length. Args: dataset (dict): length: keep_residuals: Returns: """ new_data = {} # Detect <key, valu...
4ff93445170060e63ea36cdc4c6aa462b6d0e32a
72,767
def run(args): """Admin function used to set the cluster that will be used to actually perform jobs """ try: authorisation = Authorisation.from_data(args["authorisation"]) except: authorisation = None try: passphrase = str(args["passphrase"]) except: pass...
9bbdf9a618c682ef58a1f8f9e4e62c892362b2f3
72,768
def get_phe_title(db, phename): """ Search bar SciDBnew: res = str(list(phef[phef['description'] == "asthma_diagnosed_by_doctor"]['title'])[0]) """ phef = db.get_phenotype_fields(association_set=str(db.list_association_sets()['name'][0])) if phef.empty: return None else: ...
93ef978e9b79760d0226cc0fd00d827f7b3872ff
72,769
import csv import sys def get_next_arrival_given_route(intent, session): """ Returns the next scheduled bus or train that the user asks for in the utterance. This function is similar to get_next_arrival(). """ card_title = intent['name'] if 'attributes' in session: session_attributes ...
fdc07261f30f284ee09a25dc666bec293c3a3554
72,770
import random def make_graceful(ex: Exception, ex_uuid: UUID) -> str: """ makes the incoming exception graceful Args: ex (Exception): the raised exception to make graceful ex_uuid(UUID): uuid identifying exception in the logs Returns: str: graceful error message """ ...
af53769ec9ac3880cbab4d7c143549d4f5fc3aa5
72,771
def run_model(data, labels, return_coef=False): """ Runs provided LogisticRegressionCV model with the provided data and labels. Parameters: data (pandas.DataFrame): DataFrame of CMTF components labels (pandas.Series): Labels for provided data return_coef (bool, default: False): ...
99eab8e415bbd5e4f26ef5741292b42510a89e8e
72,772
def hpo_disease_file(request): """Get the path to the hpo disease file""" print('') return hpo_phenotype_to_terms_reduced_path
9075f371366428dc8634edf5d35e148ad777652c
72,773
import warnings def check_already_dropped(labels, dropped_cols, name, dropped_by='numeric_only', warn=True): """Check if columns have already been dropped and return only those that haven't. Args: labels (single label or list-like): Column labels to check. droppe...
d584691cf2cd073641625b6358000cbe72f736ae
72,774
import uuid import string def plot(df, map_widget=None, name=None, renderer_type=None, symbol_type=None, symbol_style=None, col=None, colors='jet', alpha=1, **kwargs): """ Plot draws the data on a web map. The user can describe ...
ae9a30a7e5bc0e333ecc96e184739e09610a2085
72,775
import json def LoadWorkerOutput(output): """Load output from worker processes to our internal format. Args: output: list of strings. The stdouts of all worker processes. Returns: A tuple of start_time, latency, size. Each of these is a list of numpy arrays, one array per worker process. start_tim...
554ffd0821764f6ddc312e93575c56713bc45ac2
72,776
import requests import json def req(method, url, headers={}, payload=None, status_code=False, timeout=30): """ Request function with error handlers (output: dict) """ pass_headers = {} const_headers = { 'User-Agent': '{}/{}'.format( __prog__, __version__ ) }...
aca322eaec9df33e870563d3672b002213d13a3f
72,777
def stack(arrays, axis=-1): """ Stack of all arrays from a stream. Generalization of numpy.stack and numpy.concatenate. Parameters ---------- arrays : iterable Stream of NumPy arrays. Arrays must have shapes that broadcast together. axis : int, optional Stacking direction. I...
796df83f2900122ba23c746aa9ca1453fc52effa
72,778
def wrn40_8_cifar10(classes=10, **kwargs): """ WRN-40-8 model for CIFAR-10 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pre...
73214a88ff2b9500326f889278cea7c99ab97fd8
72,779
from typing import List def gen_from_dataframe(df: DataFrame, caption: str = None, header: List[str] = None, line_names: List[str] = None, index: bool = False, index_start: int = 1, horizontal: bool = False) -> str: """ Генерирует таблицу latex из DataFame. Ну...
47c8720ee89def6b616641eca510acedbe8210c5
72,780
def perform_extended_GST_on_data(filename_data_input, filename_target_gateset, filename_fiducials, filename_germs, maxlength_germseq): """Performs extended/long GST on data -------------------------------------------------------------------------...
4ba557ac2e1d9258837660b5949ddcf3c6cb2173
72,781
def custom_x_bounds_max(current_shooting_point: int, n_elements: int, n_shooting: int) -> np.ndarray: """ The custom function for the x bound (this particular one mimics linear interpolation) Parameters ---------- current_shooting_point: int The current point to return the value, it is defi...
7e2faeee8750966674f976be317c0f9a775d51e5
72,782
def compatibility_g_m(gen_1, gen_2, name_1, name_2): """Check compatibility.""" print("Checking compatibility of {} with {}.".format(name_1, name_2)) r_code = 0 for seq in gen_1: if seq not in gen_2: print("FAIL\t{} sequence not found in {}.".format(seq, name_2)) r_code =...
0ce34eb6ebe97bca179425939c95a2a6a19f6e6a
72,783
def review_list(request, resource_type): """ :param request: :param resource_type: The type of resource to generate a review list for. :return: Returns a list of reviews of that particular resource_type. """ resources = Review.objects.filter(resource_type__slug__exact=resource_type.lower()) ...
c4d83b403d1b60c80f61f11998b1f1f4b3fe1e7c
72,784
def meanPtVersusPartonicPt(histFile='./combined.sum.hist.root', trigKey='notrig', subProcess=''): """note: errors are absolutely fake""" f = ROOT.TFile(histFile) m = MiniMcHistos(trigKey, subProcess, f) c = ROOT.TCanvas() m['partonicPt'].GetZaxis().SetRangeUser(m['partonicPt'].GetMinimum(1e-10...
709d9f8624c5115e0a954eb5a51b9a097f4aeb5d
72,785
import sys import subprocess def _GetGitRevision(in_directory): """Returns the git hash tag for the given directory. Args: in_directory: The directory where git is to be run. Returns: The git SHA1 hash string. """ git_exe = 'git.bat' if sys.platform.startswith('win') else 'git' p = subprocess.Po...
4ee7abe93c3d63bec84e478725d7ca086599d74b
72,786
def create_regional_summary (results): """Creates the regional summary Parameters ---------- results : dictionary results from the model, dictionary with each community or project as key Returns ------- DataFrame containing regional results ...
c90d3ac11919ce6330c52a2133f2733193a78373
72,787
import socket def getaddrinfo(host, port=None, family=0, socktype=0, proto=0, flags=0): """return (family, socktype, proto, canonname, sockaddr) >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP) [(2, 1, 6, '', ('82.94.164.162', 80)), (10, 1, 6, '', ('2001:888:2000:d::a2', 80...
5fde1bc04887e002199e119b24cde08227d14c0b
72,788
def scatter_element_add(tensor, index, value, like=None): """In-place addition of a multidimensional value over various indices of a tensor. Args: tensor (tensor_like[float]): Tensor to add the value to index (tuple or list[tuple]): Indices to which to add the value value (float or ...
2bc08d37be6948a820e3b2edd408547b14948516
72,789
from typing import Optional from typing import Sequence def get_volume_backups(compartment_id: Optional[str] = None, display_name: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetVolumeBackupsFilterArgs']]] = None, source_volum...
4cc5d688b2af608b17ea8ecf3d2844be176fa95f
72,790
from os import environ def broadcast_addresses(): """A list if IP adresses to use for name resolution broadcasts""" addresses = [] if "EPICS_CA_AUTO_ADDR_LIST" in environ and \ environ["EPICS_CA_AUTO_ADDR_LIST"] == "NO": pass else: try: addresses += broadcast_addresses_psutil() ...
1c554cc97b5667c2c83480dc09b5acdf795708a0
72,791
def getParam(prompt, default, helpMessage="No help implemented yet!"): """Get a parameter from the user interactively. Also sets a default and displays a help message if a user types "h" or "help". """ print "\n" + bcolors.OKBLUE + helpMessage + bcolors.ENDC + "\n" param = raw_input(prompt) if ...
ed9d2afd663f1c4d1bc36e4470de0f4c15adf2a7
72,792
def showCategories(): """ Display the main catalog page using any of the listed routes.""" lCategories = session.query(Category).order_by(Category.name).all() if len(lCategories)==0: sMsg = "" if 'username' not in login_session: sMsg = "There are currently no categories in the system. " sMsg += "Please ...
f7bd569ba132445e7ea072c136c96d18cec0b0d9
72,793
def docker_registry_username() -> str: """Retrieve the name of the user to use for authentication to the secure registry service.""" return _docker_registry_username(scale_factor=1)[0]
d02a1f870305b6b8c30f69068dbd301b70d7ba55
72,794
def diaresnet110_cifar100(classes=100, **kwargs): """ DIA-ResNet-110 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, defa...
82021a5cc88ec5c3c470fafe6790da6dc1eae387
72,795
import os import torch def load_model(model, optimizer, num_epochs, resume=True): """Load and resume from existing model. :return: model path""" model_name = os.path.join(data_dir, str(model.__class__.__name__)+ '_' + str(optimizer.__class__.__na...
e81ab46e1734f4ef4bd16d69a742b70d09b1df73
72,796
import argparse def parse_args() -> argparse.Namespace: """ Parse the arguments. Returns: The argument namespace. """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'folder', type=str, hel...
5e09d7573fd107c402607d20a29c2fe33a3526e7
72,797
def multiple(op1: int, op2: int) -> int: """ :param op1: :param op2: :return: """ return float(op1 * op2)
c9681de0655ba07c051a8bd64515e826df82a18d
72,798
def dense_layer(x, config): """Configurable dense layer. Supports scale layer. Args: x: Input tensorflow tensor. config: network_config.DenseLayer object. Returns: An output tensor. """ if config.num_outputs < 0: raise ValueError('Please set num_outputs to a positive number:' ...
6b77b50598dd19f0632dbb100c3119bf2793ce25
72,799