content
stringlengths
22
815k
id
int64
0
4.91M
def tf_tol(): """Numerical tolerance for equality tests.""" return float(os.environ.get("TF_TOL", TF_TOL))
5,301,600
def _read_reaction_gpr_from_sbml(reaction, mass_notes, f_replace): """Read the GPR information from SBMLDocument and return as a string. Warnings -------- This method is intended for internal use only. """ reaction_fbc = reaction.getPlugin("fbc") if reaction_fbc: # GPR rules ...
5,301,601
def add_attribute(db_ip, db_user, db_pass, db_name, attr_id, attr_name, log_object): """ Add attribute to database """ from my_library import test_socket, ClassDB if test_socket(db_ip, 3306, log_object) == 0: o_db = ClassDB('mysql', (db_ip, '3306', db_user, db_pass, db_name), log_object) o_...
5,301,602
def conv_block(x, nfeat, strides=1, name=None): """ Specific convolutional block followed by leakyrelu for unet. """ ndims = len(x.get_shape()) - 2 assert ndims in (1, 2, 3), 'ndims should be one of 1, 2, or 3. found: %d' % ndims Conv = getattr(KL, 'Conv%dD' % ndims) convolved = Conv(nfeat,...
5,301,603
def sample_from_discretized_mix_logistic(y, log_scale_min=None): """ https://github.com/fatchord/WaveRNN/blob/master/utils/distribution.py Sample from discretized mixture of logistic distributions Args: y (Tensor): B x C x T log_scale_min (float): Log scale minimum value Returns: ...
5,301,604
def min_dist_conformer_zma(dist_name, cnf_save_fs): """ locators for minimum energy conformer """ cnf_locs_lst = cnf_save_fs[-1].existing() cnf_zmas = [] for locs in cnf_locs_lst: zma_fs = autofile.fs.zmatrix(cnf_save_fs[-1].path(locs)) cnf_zmas.append(zma_fs[-1].file.zmatrix.read([0])) ...
5,301,605
def array_offset(x): """Get offset of array data from base data in bytes.""" if x.base is None: return 0 base_start = x.base.__array_interface__["data"][0] start = x.__array_interface__["data"][0] return start - base_start
5,301,606
def get_kernelf(config, context={}): """Get a kernel function.""" return _from_config(config, classes=classes, context=context)
5,301,607
def solve_evolutionary_op(problem, save_results=True, return_history=False, step_hook=None, post_process_hook=None, nls_status=None): """TODO return_history""" step_args = problem, nls_status time_solver = problem.get_time_s...
5,301,608
def validate_dynamodb(table_name, table_meta): """ Performs check of DynamoDB resources. :param table_name: name of resource :param table_meta: resource definition :raises AssertionError in case of invalidity. :return: None """ # check hash key _assert_key(meta=table_meta, ...
5,301,609
def layer_ogc_request(request, layername): """Provide one OGC server per layer, with their own GetCapabilities. :param layername: The layer name in Geonode. :type layername: basestring :return: The HTTPResponse with the response from QGIS Server. """ layer = get_object_or_404(Layer, name=layer...
5,301,610
def _demo_inputs_pair(img_shape=(64, 64), batch_size=1, cuda=False): """ Create a superset of inputs needed to run backbone. Args: img_shape (tuple): shape of the input image. batch_size (int): batch size of the input batch. cuda (bool): whether transfer input into gpu. """ ...
5,301,611
def check_transaction(): """ CLI to check the validity of a transaction :return: """ blockchain = BlockChain() blockchain.print_cli() print("Vérification d'une transaction") trans_nb = input("Numéro de la transaction à vérifier : ") if trans_nb == 'q': return trans_nb =...
5,301,612
def get_song(song_name): """Return information about a song. Parameters ---------- song_name : str The song name. Returns ------- dict name - The song name. files - Dictionary with downloaded files for this song. """ song = cache.get(song_name) if song ...
5,301,613
def message_create(request, slug, topic_id, template_name='groups/message_form.html'): """ Returns a group message form. Templates: ``groups/message_form.html`` Context: form GroupMessageForm object """ group = get_object_or_404(Group, slug=slug) topic = get_object_or_40...
5,301,614
def index(): """ Simple Home Page """ module_name = deployment_settings.modules[module].name_nice return dict(module_name=module_name)
5,301,615
def player_team(replay_json): """ Returns a list of names of the players on the replay recorder's team """ own_team = get_own_team(replay_json) return [v['name'] for v in replay_json['first']['vehicles'].values() if v['team'] == own_team]
5,301,616
def get_image_writer_set(): """Return the set of installed image writers. The set is returned as a dictionary where names of the image writers are the keys, and the image writer class objects are the values. """ return ImageWriterLoader().loader.get_object_set()
5,301,617
def test_get_countries_by_language(south_africa, nigeria, kenya): """ Test that countries can be retrieved by language. """ countries = rapi.get_countries_by_language("en") assert countries == [south_africa, nigeria, kenya]
5,301,618
def write_df_in_table(conn, df, schema_name, table_name): """write pandas dataframe in table Args: conn: a pSQL databse connection object df: a pandas dataframe to write to the database schema_name: name of the schema for the table table_name: name of the table """ # wri...
5,301,619
def simbad(stars, output): """Function to make script for Simbad. Takes a list of stars :stars: A list of stars :returns: An output file called SimbadQuery.txt for Simbad to read """ with open(output, 'wb') as f: f.write('\n'.join(stars)) with open('SimbadQuery.txt', 'wb') as result:...
5,301,620
def get_image(location, request_timeout=60, http_max_retries=2, http_retry_interval=3): """Wrapper function that routes to appropriate utility to get image data. Args: location: location of source image data. This can be a URL, local file location, or possibly other location types w...
5,301,621
def get_flags(source): """Gets flags from a source file. Args: source (str): Path to the source file (could be any extension). Returns: list[dict[str, _]]: List of maps with keys "type", "name", "default", and "descr" for the respective fields corresponding to the flag. """...
5,301,622
def convert_to_distributed_tensor(tensor: torch.Tensor) -> Tuple[torch.Tensor, str]: """ For some backends, such as NCCL, communication only works if the tensor is on the GPU. This helper function converts to the correct device and returns the tensor + original device. """ orig_device = "cpu" if...
5,301,623
def main(): """ Main method. """ cli_configuration = parse_cli_arguments(sys.argv[1:]) returncode, stdout, stderr = run(cli_configuration) if stdout is not None: sys.stdout.write(stdout) if stderr is not None: sys.stderr.write(stderr) exit(returncode)
5,301,624
def update_global_variable(): """ 修改全集变量(global关键字) :return: """ global count count = 10 return count
5,301,625
def cancelReserve(request): """ 알림톡/친구톡 전송요청시 발급받은 접수번호(receiptNum)로 예약전송건을 취소합니다. - 예약취소는 예약전송시간 10분전까지만 가능합니다. - https://docs.popbill.com/kakao/python/api#CancelReserve """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 예약 알림톡/친구톡 전송 접수번호 receiptNum = "0180...
5,301,626
def _staircase_ecdf(p, data, complementary=False, q_axis="x", line_kwargs={}): """ Create a plot of an ECDF. Parameters ---------- p : bokeh.plotting.Figure instance, or None (default) If None, create a new figure. Otherwise, populate the existing figure `p`. data : array_like ...
5,301,627
def _ssh_cli_test(): """Private function to test RPC on the command line with ssh. """ # this gets the source from a loaded module runner = inspect.getsource(remote_multicall_template) # strip out comments runner_str = "\n".join(l for l in runner.splitlines() if not l.strip().startswith('#')) ...
5,301,628
def GenerateConfig(context): """Generates the route config""" resources = [ { 'name': context.env["name"], 'type': 'pubsub.v1.topic', 'properties': { 'topic': context.env["name"] }, 'accessControl': { 'gcpIamPolicy': MergeCallingServiceAccountWithAdminPermissionsIntoBindings(context.env, c...
5,301,629
def get_programs(x_gw_ims_org_id, authorization, x_api_key): # noqa: E501 """Lists Programs Returns all programs that the requesting user has access to # noqa: E501 :param x_gw_ims_org_id: IMS organization ID that the request is being made under. :type x_gw_ims_org_id: str :param authorization: B...
5,301,630
def get_non_lib(functions): """ Get all non-library functions @param functions: List of db_DataTypes.dbFunction objects @return: a subset list of db_DataTypes.dbFunction objects that are not library functions. """ return [f for f in functions if not f.is_lib_func]
5,301,631
def _check_duplicates(data, name): """Checks if `data` has duplicates. Parameters ---------- data : pd.core.series.Series name : str Name of the column (extracted from geopandas.GeoDataFrame) to check duplicates. Returns ------- bool : True if no duplicates in data. """ ...
5,301,632
def path_surroundings(md, path, *, radius_pix=130, maxwidth_pix=1000, maxheight_pix=800, maxdist_pix=500, path_color=(255, 100, 0), shorten_by_rotating=True): """Create a generator of ...
5,301,633
def _has_textframe(obj): """ Check if placeholder has TextFrame """ return hasattr(obj, 'TextFrame') and hasattr(obj.TextFrame, 'TextRange')
5,301,634
def get_mapping(combinable_list): """Determine the mapping from acceptance_id to the register id that can be used to index into an array. """ result = {} array_index = 0 while len(combinable_list) != 0: # Allways, try to combine the largest combinable set first. k ...
5,301,635
def read_sbs_from_vcf(vcf_file): """ Only reads the chrom, pos, ref and alts from the VCF file. Not strict about checking the headers, and will not filter any mutations. Lines with multiple alts will be split into one mutation for each alt. Non-single-base-substitutions (e.g. deletions, indels, MNPs...
5,301,636
def test_remove_mechfile_entry(load_mock, save_mock): """Test remove_mechfile_entry.""" assert mech.utils.remove_mechfile_entry('first', True) load_mock.assert_called_once() save_mock.assert_called_once()
5,301,637
def get_path(abs_url, **kwargs): """ """ if abs_url is None: return None return urlparse(abs_url, **kwargs).path
5,301,638
def test_preprocessor_codefolding(): """Test codefolding preprocessor.""" # check import shortcut from jupyter_contrib_nbextensions.nbconvert_support import CodeFoldingPreprocessor # noqa notebook_node = nbf.new_notebook(cells=[ nbf.new_code_cell(source='\n'.join(["# Codefolding test 1", ...
5,301,639
def clean_chamber_input(chamber): """ Turns ambiguous chamber information into tuple (int, str) with chamber id and chamber name """ if type(chamber) == str: if chamber == '1': chamber = 1 elif chamber == '2': chamber = 2 elif chamber == 'GA': chamber ...
5,301,640
def test_split(): """Run with good and bad arguments, expect split.""" good, bad = fyrd.options.split_keywords( {'cores': 2, 'memory': '4GB', 'bob': 'dylan'} ) assert good == {'cores': 2, 'mem': 4096} assert bad == {'bob': 'dylan'}
5,301,641
def search_for_letters(phrase: str = 'life, the universe, and everything', letters: str = 'forty two') -> set: """Display any 'letters' found in a 'phrase'.""" return set(letters).intersection(set(phrase))
5,301,642
def attached_cli(): """ Attaches the local dcos-cli to the clusters. This assumes that DCOS_URL, DCOS_PASSWORD and DCOS_USERNAME are set. The CLI setup command should be idempotent. So it is save to call this method multiple times. """ cmd = 'cluster setup {} --no-check '.format(dcos_url()) ru...
5,301,643
def normalize_versor(anglevec): """Normalize a vector of 3D angles to versors.""" assert len(anglevec) % 3 == 0 for startpos in range(0, len(anglevec), 3): rep = anglevec[startpos:startpos + 3] angle = _np.linalg.norm(rep) vec = rep / angle quat = _np.array([_np.cos(angle / 2...
5,301,644
def loadyaml(file, default={}): """Utility function to load from yaml file""" try: with open(file, "r", encoding="utf-8") as f: t = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: t = default return t
5,301,645
def log_flags(FLAGS): """ Log all variables defined in FLAGS and their values. """ param_list = [] #for k, v in FLAGS.__flags.items(): for k in FLAGS: v = FLAGS[k].value param_list.append("'--{}': {}".format(k, v)) logging.info('Parameters:\n' + '\n'.join(param_list))
5,301,646
def main(args: argparse.Namespace) -> int: """This functions splits a PDF document using the Document AI API""" if not args.project_id: _, project_id = google.auth.default() args.project_id = project_id parent = f"projects/{args.project_id}/locations/{args.multi_region_location}" client ...
5,301,647
def load_fitresult(fit_dir): """ Load a fitresult into a fitting_torch.TorchSingleFitResult or :class:`~pyhdx.fitting_torch.TorchBatchFitResult` object The fit result must be in the format as generated by saving a fit result with `save_fitresult`. Parameters ---------- fir_dir :obj:`str` or :c...
5,301,648
def secret(prompt=None, empty=False, default=None): """Prompt a string without echoing. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. default : float, optional Value to return if response is empty....
5,301,649
def update_note(store, note, path): """Update a note from the content in a local file """ ext = utils.get_file_ext(path) processor_cls = note_processors.get(ext) processor = processor_cls(path) note.title = processor.get_title() note.content = processor.get_content() note.updated = os.pa...
5,301,650
async def test_form_other_problem(hass, mock_smile): """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) mock_smile.connect.side_effect = TimeoutError mock_smile.gateway_id = "0a636a4fc1704ab...
5,301,651
def parse_station_list_to_csv(filepath_or_buffer) -> str: """ Return CSV-formatted data """ return _parse_station_list(filepath_or_buffer).to_csv()
5,301,652
def pipelines_name_version_get(name, version): # noqa: E501 """pipelines_name_version_get Return pipeline description and parameters # noqa: E501 :param name: :type name: str :param version: :type version: str :rtype: None """ try: logger.debug( "GET on /pipel...
5,301,653
def govuk_url(path): """ :returns: url to the GOV.UK Pay endpoint defined by `path` :param path: path without leading `/` e.g. `payments` """ return urllib.parse.urljoin(settings.GOVUK_PAY_URL, path)
5,301,654
def _any_sat(bdd, u, l): """ Recursive part of any_sat """ #Base Cases if u in [0,1]: return l var = _get_var_name(bdd, u) #Arbitrarily consider lower branch if bdd["t_table"][u][1] == 0: l.append("%s" % var) new_u = bdd["t_table"][u][2] else: l...
5,301,655
def map_mean_of_horizontal_active_links_to_node(grid, var_name, out=None): """Map the mean of active links in the x direction touching node to the node. map_mean_of_horizontal_active_links_to_node takes an array *at the links* and finds the average of all horizontal (x-direction) link neighbor values ...
5,301,656
def majorityPrediction (testset, count=1000): """ Majority Prediction """ tick = time.time() correctPredictions = 0 totalPredictions = 0 for data in json_reader(testset, count): prediction = 5 totalPredictions += 1 if (prediction == data['rating']): corre...
5,301,657
def gmm_density_centered(x, std): """ Assumes dim=-1 is the component dimension and dim=-2 is feature dimension. Rest are sample dimension. """ if x.dim() == std.dim() - 1: x = x.unsqueeze(-1) elif not (x.dim() == std.dim() and x.shape[-1] == 1): raise ValueError('Last dimension must...
5,301,658
def process_pairs_vg(alns_tuple): """ Finds the pairs in alignments of one read :param alns_tuple: alignments of one read in as a tuple :return: read_id, AS pairs, mapq, metric scores """ read_id, alignments, mapqs, obs_max, end = alns_tuple return read_id, alignments, mapqs, calc_scores((re...
5,301,659
def test_run_action_store_from_parser_normal(fxtr_rmdir_opt, fxtr_setup_empty_db_and_inbox): """Test RUN_ACTION_STORE_FROM_PARSER - normal.""" cfg.glob.logger.debug(cfg.glob.LOGGER_START) # ------------------------------------------------------------------------- pytest.helpers.copy_files_4_pytest_2_di...
5,301,660
def params_from_yaml(args): """Extract the parameters for preparation from a yaml file and return a dict""" # Check the path exists try: config_file_path = Path(args.config) assert config_file_path.exists() except Exception: logging.error(f"Could not find config file at {args.con...
5,301,661
def register(services): """ Registers the test runners in this module. """ services.register('test-runner.unittest', UnitTestRunner, singleton=True)
5,301,662
def get_task_monitor(node, uri): """Get a TaskMonitor for a node. :param node: an Ironic node object :param uri: the URI of a TaskMonitor :raises: RedfishConnectionError when it fails to connect to Redfish :raises: RedfishError when the TaskMonitor is not available in Redfish """ try: ...
5,301,663
def get_user_ids_from_assigned_location_ids(domain, location_ids): """ Returns {user_id: [location_id, location_id, ...], ...} """ result = ( UserES() .domain(domain) .location(location_ids) .non_null('assigned_location_ids') .fields(['assigned_location_ids', '_id...
5,301,664
def extract_sift(fn, extractor, detector): """提取图像特征""" im = cv2.imread(fn, cv2.IMREAD_GRAYSCALE) # SIFT检测器可以检测特征,而基于SIFT的提取器可以提取特征并返回它们 return extractor.compute(im, detector.detect(im))[1]
5,301,665
def is_operator_or_function(term): """ Checks if the term is a LaTeX mathematical operator or function. Source: http://web.ift.uib.no/Teori/KURS/WRK/TeX/symALL.html Args: term: string to be checked. Returns: True if the term is a mathematical operator, False otherwise. """ ...
5,301,666
async def update_pointing_list(message, nats_handler, shared_storage, logger): """ Updates the list of other satellites pointing at itself in order to determine whether they can communicate or not. Args: message (Message): incoming message with current pointing target of the sender nats_han...
5,301,667
def getGasDensity(x=None, y=None, z=None, grid=None, ppar=None): """Calculates the gas density Parameters ---------- x : ndarray Coordinate of the cell centers in the first dimension y : ndarray Coordinate of the cell centers in the second dimension y ...
5,301,668
def extract_table_delimiter_data(data_path: Text, target_path: Text) -> None: """Extracts training data for table segmentation.""" image_paths = table_annotator.io.list_images(data_path) image_paths = [os.path.join(data_path, ip) for ip in image_paths] os.makedirs(target_path, exist_ok=True) heig...
5,301,669
def load_embeds(text_embed, img_embed, dcca_embed): """ Load image and sentence embeddings and create a concatenated version :param text_embed: pickle file containing the sentence embeddings :param img_embed: pickle file containing the image embeddings :param dcca_embed: pickle file containing the deep...
5,301,670
def serialize(settings, exclude=None): """Return a consistent, human-readable string serialization of settings.""" if exclude is None: exclude = [] sdict = dict(_variables(settings)) sdict = { k: v for k, v in sdict.items() if k not in exclude } sstr = dumps(sdict, sort_keys=True, indent=4, ...
5,301,671
def test_sann(): """Test SANN model.""" # Print parameters used for the model dh.tab_printer(args, logger) # Load word2vec model word2idx, embedding_matrix = dh.load_word2vec_matrix(args.word2vec_file) # Load data logger.info("Loading data...") logger.info("Data processing...") tes...
5,301,672
def list_or_first(x: List[str]) -> Union[List[str], str]: """ Returns a list if the number of elements is greater than 1 else returns the first element of that list """ return x if len(x) > 1 else x[0]
5,301,673
def new_raster_from_base_uri( base_uri, output_uri, gdal_format, nodata, datatype, fill_value=None, n_rows=None, n_cols=None, dataset_options=None): """Create a new, empty GDAL raster dataset with the spatial references, geotranforms of the base GDAL raster dataset. A wrapper for the functi...
5,301,674
def parse_version(version_str): """'10.6' => [10, 6]""" return [int(s) for s in re.findall(r'(\d+)', version_str)]
5,301,675
def user(): """Get user details depending on friendship. If you are friends, sensitive data will be shown aswell. Returns: JSON reponse with the basic and sensitive user details. """ username = request.args.get('username') if username is None or username == '': username = auth...
5,301,676
def display_selected_patient_info(MRI): """ Get a patient's latest information and ECG trace image As a very important functionality of the server, the function sends a 'GET' request to the server, get a string that includes all patient's latest info and ECG image b64 string. Then it splits eac...
5,301,677
def idle(): """The idle state.""" pixels.fill(0) state_from_orientation()
5,301,678
def test_corrupted_file_in_a_directory_is_downloaded_again(file_in_fire, fs): """ When the file has been downloaded incorrectly into a directory previously, then it is re-downloaded again. I don't think this happens too often, because an incorrectly downloaded file is always removed (or at least, it sho...
5,301,679
def circ(x, y, d=1): """ Generation of a circular aperture. Args: | x (np.array[N,M]): x-grid, metres | y (np.array[N,M]): y-grid, metres | d (float): diameter in metres. | comment (string): the symbol used to comment out lines, default value is None. | delimiter (string...
5,301,680
def idle(): """ Gates the clock to the CPU, useful to reduce power consumption at any time during short or long periods. Peripherals continue working and execution resumes as soon as any interrupt is triggered (on many ports this includes system timer interrupt occurring at regular intervals on the order of mil...
5,301,681
def vb_with_err(mean_list, cov_list, Nsamples): """ Calculate latitudinal velocities with uncertainties. Args: mean_list (list): A list of arrays of astrometric data. [ra, dec, plx, pmra, pmdec] cov_list (array): A list of all the uncertainties and covariances: [ra_e...
5,301,682
def labels( adata: AnnData, label_filepath: str = None, index_col: int = 0, sep: str = "\t", copy: bool = False, ) -> Optional[AnnData]: """Add label transfer results into AnnData object Parameters ---------- adata: AnnData The data object to add L-R info into label_fil...
5,301,683
def evaluate_all(): """ Fetch metrics overall. :return: """ # TODO return
5,301,684
def mpBirailCtx(*args, **kwargs): """ Flags: - activeNodes : anq (bool) [] - autoCreate : ac (bool) [] - bldProfileFirst : bpf (bool) [] - bldProfileLast : bpl (bool) [] - bldProf...
5,301,685
def _initialize_blueprints(app: Flask) -> None: """Register Flask blueprints""" from app.routes.health_check import health_check from app.routes.sentiment_analysis import sentiment_analysis app.register_blueprint(health_check) app.register_blueprint(sentiment_analysis)
5,301,686
def test_pipe(cli): """Verify piping stdin within a command works correctly.""" res = subprocess.run( "python -m build_magic --verbose --plain 'ps -ef | grep python'", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, ) output = res.stdout.decode('utf-8') as...
5,301,687
def test_dump_json_to_string(): """ Test dumping data to a JSON formatted string. This test demonstrates how to use `jsonio` to dump data to a JSON formatted string. Note: This method is similar to the `json.dumps` method. """ data = {"foo": "bar"} text = jsonio.dumps(data, ind...
5,301,688
def contains_common_item_2(arr1, arr2): """ loop through first array and create dictionary object where the keys are the items in the array loop through the second array and check if item in second array exists in the created dictionary """ array1_dict = {} for item in arr1: array1_dict[...
5,301,689
def complex_function(z): """ The complex function to plot. *You can write any function here*. :param z: a numpy 2d array of complex numbers. """ return (z - 1) / (z + 1)
5,301,690
def save_png2pdf(fig, path, **args): """Save as a .png and use unix `convert` to convert to PDF.""" if not path: print("[save_png2pdf:]".ljust(15, " ") + " No path provided, I'll pass...") return import os fig.savefig(path + ".png", **args) os.system("convert %s.png %s.pdf" % (pat...
5,301,691
def write_summary_file(input_folder: Union[Path, str], output_folder: Union[Path, str] = None, geocode_helper: str = None) -> Path: """ Create a new ``.xlsx`` summary file. This file has two tabs: - ``Summary`` contains a single line-item for each TMC ...
5,301,692
def generate_lists(image_dir, subdir): """ 80 images per class in total and 256 classes. Generate a list of lists. Each list contains 256*5 images. :return: a list of lists. Each list contains 256*5 images. """ # last 20 images are for test. index = range(1, 81, 1) # np.random.shuffle(index...
5,301,693
def test_target_psi(tmpdir, request, H0, H1, L1, L2, pop1, pop2): """Test that we can add another 'target' state to the config file""" filename = request.module.__file__ test_dir, _ = os.path.splitext(filename) psi = np.array([0, 1, 1, 0], dtype=np.complex128) / np.sqrt(2.0) pulse = AnalyticalPulse...
5,301,694
def get_embed(input_data, vocab_size, embed_dim): """ word embedding 输入. :param input_data: 输入. :param vocab_size: 总词语数. :param embed_dim: w2v 维数 :return: Embedded input. """ #embedding 初始化,这边不采用预先训练的embeding,边训练边调参数 embedding = tf.Variable(tf.random_uniform((vocab_size,embed_dim),-...
5,301,695
def encrypt(text, parola): """ Derives a 256-bit key using the PBKDF2 key derivation algorithm from the password. It uses a random password derivation salt (128-bit). This salt should be stored in the output, together with the ciphertext, because without it the decryption key cannot be der...
5,301,696
def gList(question, items, returnsIndex): """ Returns an item or its index from a list based on user input. :param question: String containing prompt to be displayed. :param items: List of items of which user should choose from. :param returnsIndex: Boolean indicating whether the function should return the item o...
5,301,697
def get_fuselage(dirname: str, isurface: int, surface: Body, yduplicate: bool, nodes: List[np.ndarray], unused_line_elements: List[np.ndarray], quad_elements: List[np.ndarray], surfaces: List[Union[Surface, Body]], ...
5,301,698
def _get_helper(json_expecting_func, **kwargs): """ Helper function used by several functions below """ try: payload = json_expecting_func(**kwargs) response, status_code, mimetype = json.dumps(payload), 200, "application/json" except exceptions.BadRequest as exc: response, s...
5,301,699