content
stringlengths
22
815k
id
int64
0
4.91M
def barrier(*args, **kargs): """ OpenCL barrier() Example: # workgroup barrier + local memory fence hsa.barrier(hsa.CLK_LOCAL_MEM_FENCE) # workgroup barrier + global memory fence hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) # workgroup barrier + global memory fence ...
74,300
def validate_arxiv_paper_id(paper_id: str) -> None: """ Raise exception if the given paper_id is not a valid arXiv identifier. Current implementation validates paper accepted by arXiv during 2007 to 2029 Ref: https://arxiv.org/help/arxiv_identifier """ error = "Invalid arXiv paper identifier."...
74,301
def _parse_one_service_message(s): """ Parses one service message. :type s: str :rtype: service_message """ b1 = s.index('[') b2 = s.rindex(']', b1) inner = s[b1 + 1:b2].strip() space1 = inner.find(' ') if space1 >= 0: name_len = space1 else: name_len = inner....
74,302
def getPropValue(nm, encrypted=False, cfg=None, dflt=None, skipComplaining=False): """ Return a value from the specified configuration file """ if cfg is None: return None global getPropDict if getPropDict.get(cfg): savedDate = getPropDict[cfg] # trace("getPropValue: sav...
74,303
def sets_main(): """ๅ…จใ‚ซใƒผใƒ‰ใ‚ปใƒƒใƒˆใƒ‡ใƒผใ‚ฟใ‚’ๅ–ๅพ—ใ—ใฆไฟๅญ˜""" url = 'https://api.magicthegathering.io/v1/sets' sets_json = http_json(url) with open('sets/sets.json', 'w') as f: json.dump(sets_json, f, indent='\t', ensure_ascii=False)
74,304
def add_disk_v3_onion_service_auth(onion_service_dir, client_pub_key, client_name=None): """Adds a new client authorization file including the given client public key to the given Tor Onion Service. The filename of the client authorization file is the client name if given, otherwiese the current Unix ti...
74,305
def medidasChars(T): """Medidas de letras TTM formatar para passagem como dicionรกrio""" nchars=len(T) # nspaces=T.count(" ") nletters=sum([t.isalpha() for t in T]) nuppercase=sum([t.isupper() for t in T]) nvowels=sum([t in ("a","e","i","o","u") for t in T]) npunctuations=sum([t in puncts for...
74,306
def visit_runpython_node(self, node): """ What to do when visiting a node @see cl runpython_node the function should have different behaviour, depending on the format, or the setup should specify a different function for each. """ pass
74,307
def read_chl(filename, field_names=None, additional_metadata=None, file_field_names=None, exclude_fields=None, use_file_field_attributes=True): """ Read a CSU-CHILL CHL file. Parameters ---------- filename : str Name of CHL file. field_names : dict, optional ...
74,308
def get_tree(tree_type, cfg, section, option): """Load a tree from file or parse a string. If the provided value is the name of an existing file, read the contents and treat it as a Newick tree specification. Otherwise, assume the provided value is a Newick tree specification. Trees consisting of only...
74,309
def common(first_list, second_list): """Receives two lists, returns True if they have any common objects and false otherwise. Note that this implementation should theoretically work with any container-like object for which the in operator doesn't have a different meaning.""" # iterate over the elements ...
74,310
def base_download_namespace(api_keypath, path_fixtures_base, tmp_path): """Base namespace for the pyani download subcommand.""" return Namespace( outdir=tmp_path / "C_blochmannia", taxon="203804", email="my.email@my.domain", retries=20, batchsize=10000, timeout=10...
74,311
def Correct_Surface_Temp(Surface_temp,Temp_lapse_rate,DEM_resh,Pair,dr,Transm_corr,cos_zn,Sun_elevation,deg2rad,ClipLandsat): """ Function to correct the surface temperature based on the DEM map """ #constants: Gsc = 1367 # Solar constant (W / m2) cos_zenith_flat = np.cos((90...
74,312
def block(ctx, block_number): """Get a block detail""" connect(ctx, ctx.obj['verifier_ip']) if VERBOSE: app_log.info(f"Connected to {ctx.obj['verifier_ip']}:9444") app_log.info(f"block {block_number}") req = BlockRequest(start_height=block_number, end_height=block_number, ...
74,313
def aggregate_unique_objects(edges: Dict[str, Dict[Tuple[str, str], Collection[Any]]]) -> Dict[ str, Dict[Tuple[str, str], Set[Any]]]: """ Performs an aggregation of the occurrences of a given edge in the involved object. Parameters ------------------- edges Edges calculated using the f...
74,314
def deploy_layers_table(): """Copy and partition the layers table""" table_name = f"{BQ_LAYERS_TABLE}" sql_query = f"""CREATE OR REPLACE TABLE `{GCP_PROJECT}.{BQ_TEMP_DATASET}.{table_name}` PARTITION BY layer_partition AS SELECT *, `{GCP_PROJECT}.{BQ_TARGET_DATASET}`.layer_partition(name) a...
74,315
def receive(conn): """Receive a message conn has to be the socket which receive the message A message has to end with the bytestring b'\xDE\xAD\xE1\x1D' """ ip, port = conn.getpeername() logging.info('Receiving a message from '+ip+':'+str(port)) data = b'' while True: tr...
74,316
def test_HTTPVersion_froms_raises(input, expected): """HTTPVersion.from_* should fail to parse invalid HTTP versions.""" with pytest.raises(expected): P.HTTPVersion.from_bytes(input) with pytest.raises(expected): m = P.HTTPVersion.PARSE_VERSION.match(input) P.HTTPVersion.from_match...
74,317
def printHeader(message): """ Helper function to print a noticable divider with text in the console """ print('\n'+'='*len(message)) print(message)
74,318
def test_sign_test_metric_correlation(a, a_worse, b): """Sign_test work for correlation metrics over other dimensions that time_dim.""" sign_test(a, a_worse, b, time_dim="time", dim=["lon", "lat"], metric="pearson_r")
74,319
def _load_trial_data_asvspoof(filelist, feature_dir, skip_spoof=True): """ Preload data for speaker trials for ASVSpoof2019 .trl list. Each line in filelist is four items [claimed_identity, utterance, system, target]. """ trial_list = [] for claimed_identity, utterance_file, system, is_target...
74,320
def lstm(token_embeddings, hid_dim=128, hid_dim2=96): """ LSTM network. """ # lstm layer fc0 = fluid.layers.fc(input=token_embeddings, size=hid_dim * 4) lstm_h, c = fluid.layers.dynamic_lstm( input=fc0, size=hid_dim * 4, is_reverse=False) # max pooling layer lstm_max = fluid.lay...
74,321
def SetVPNClusterPath(ref, args, request): """Sets the vpnConnection.cluster field with a relative resource path. Args: ref: reference to the cluster object. args: command line arguments. request: API request to be issued Returns: modified request """ # Skips if full path of the cluster res...
74,322
def flatten_as_docx(source_dir_path, target_dir_path, recursive=True): """ Given a source directory with a mixture of doc and docx files specified by source_dir_path, for each doc file create a file converted to docx, and for each docx file create a symbolic link to it inside the target directory specif...
74,323
def list_nmmr_option_bitfield(fp, child, sfrname, offset): """ Format a single bitfield of NMMR OPTION pseudo register Input: - index in .pic - register node Notes: - Expected to be used with 12Fs only """ if (child.nodeType == Node.ELEMENT_NODE): if (child.nodeName == "edc:Adjust...
74,324
def qubit_pairs_to_qubit_order(qubit_pairs: Sequence[Sequence['cirq.Qid']]) -> List['cirq.Qid']: """Takes a sequence of qubit pairs and returns a sequence in which every pair is at distance two. Specifically, given pairs (1a, 1b), (2a, 2b), etc. returns (1a, 2a, 1b, 2b, 3a, 4a, 3b, 4b, ...). """ ...
74,325
def calculate_carryover_vector(model, car, last_10_rows): """ calculates carryover vector by iterating over each channel, and running carryover on each channel given the sampled car value """ cv = [] post = model.trace.posterior for idx, channel in enumerate(model.feature_names_in_): ...
74,326
def copy_file_to_tmp(test_case, name): """ Copy file `name` to a new dir in the tmp dir and return its pathname Args: test_case (:obj:`unittest.TestCase`): a test case name (:obj:`str`): the name of a file to copy to tmp; `name` may either be an absolute pathname, or the name of a f...
74,327
def semantic_model(user_preferences, dataset_metadata, data_model): """ This function implements the Semantic Content-based Recommendation Model. Given the user preferences and the entities mapped to the Aviation Data Model for each column of each dataset, the model computes a score (dot product) for e...
74,328
def config_path_option(exists: bool = True) -> Callable: """ A convenience decorator As we'll probably want to be able to specify the config in pretty much every console command """ def decorator(f: Callable) -> Callable: option = click.option( "-p", "--path", ...
74,329
def gabor_filter_parallel(image, mask, parameters=dict(), n_jobs=1, backend='threading'): """ Apply gabor filters to image, done in parallel. Note: on a cluster, where parallelisation of the gabor filters is not possible, use backend="threading" """ if "gabor_frequenci...
74,330
def from_numpy_array(A, create_using=Graph): """ Initializes the graph from numpy array containing adjacency matrix. Parameters ---------- A : numpy.array A Numpy array that contains adjacency information create_using: cugraph.Graph (instance or class), optional (default=Graph) ...
74,331
def _genFlat(vizMTX): """Returns trace of flat surface with intensity as surface elevation and color. Parameters ---------- vizMTX : array_like Matrix holding spherical data for visualization Returns ------- T : plotly_trace Trace of desired surface TODO ---- ...
74,332
def change_ip_status(swis, ip_address, status): """ Change IP status in IPAM IPAM support 4 node statuses: Used Available Reserve Transient """ logging.info("Status IPNode %s changed to %s", ip_address, status) uri = "Invoke/IPAM.SubnetManagement/ChangeIpStatus" p...
74,333
def test_atomic_non_positive_integer_min_exclusive_1_nistxml_sv_iv_atomic_non_positive_integer_min_exclusive_2_5(mode, save_output, output_format): """ Type atomic/nonPositiveInteger is restricted by facet minExclusive with value -482054947069493477. """ assert_bindings( schema="nistData/ato...
74,334
def success_centroid_error(gt_poly, res_poly, thresholds, n_frame): """ :param gt_poly: [Nx8] :param result_bb: :param n_frame: :return: """ success = np.zeros(len(thresholds)) centroids_gt = [] centroids_res = [] for i in range(gt_poly.shape[0]): poly1 = res_poly[i].r...
74,335
def is_path_head(path: str) -> bool: """ Determin if a path string is a path head. >>> is_path_head('path.ext') True >>> is_path_head('/dir/path.ext') False Args: path (str): Path string. Returns: bool: If the path string is a path head. """ return path_head(p...
74,336
def read_tif(file=None): """Read tiff files. Works with 16 bit rgb data""" if file is not None: img = tif.imread(file) return img else: print("No file provided")
74,337
def verify_predictions(predictions): """Ensures that predictions is stored as a numpy array and checks that all values are either 0 or 1. """ # Check that it contains only zeros and ones predictions = np.array(predictions, copy=False) if not np.array_equal(predictions, predictions.astype(bool)):...
74,338
def test_fee(mocker): """ Test to validate the field 'fee' from a transaction """ transaction = Transaction( chain=0, nonce=0, fee=4_294_967_296, value=5_000_000, to_address="1H7NtUENrEbwSVm52fHePzBnu4W3bCqimP", unlock_sig=Config.COINBASE_UNLOCK_SIGNATURE,...
74,339
def merge_bbox(left: Box, right: Box) -> Box: """ Merge bounding boxes in format (xmin, xmax, ymin, ymax) """ return tuple([ f(l, r) for l, r, f in zip(left, right, [min, max, min, max]) ])
74,340
def process_bank_file(inputfile: str, outputfile: str): """์šฐ๋ฆฌ์€ํ–‰ ํŒŒ์ผ ํ”„๋กœ์„ธ์‹ฑ""" # region ===== ํŒŒ์ผ ์ฝ๊ธฐ ===== rwb = xlrd.open_workbook(inputfile, on_demand=True) rws = rwb.sheet_by_index(0) # ํ—ค๋” ์ฝ๊ธฐ header = rws.row_values(3) # ๊ฑฐ๋ž˜ ๋‚ด์—ญ ์ฝ๊ธฐ transactions = [] for row_idx in range(4, rws.nrows)...
74,341
def sumRowDotProdsNEW(origMatrix): """ Makes more sense to use on Jacobian than on Hessian. """ rowNormalized = normRows(origMatrix) n = rowNormalized.shape[0] sumDotProds = sumAllDotProds(rowNormalized[0:n/2]) + sumAllDotProds(rowNormalized[n/2:n]) return sumDotProds
74,342
def img_from_fig() -> Image.Image: """ Convert a Matplotlib figure to a PIL Image and return it. The figure is pulled from the current pyplot context, therefore the figure must be created and then drawn before calling this function. Returns: PIL Image array. """ buf = io.BytesIO() ...
74,343
def get_subscriber_model(): """ Users have the option of specifying a custom subscriber model via the DJSTRIPE_SUBSCRIBER_MODEL setting. This method attempts to pull that model from settings, and falls back to AUTH_USER_MODEL if DJSTRIPE_SUBSCRIBER_MODEL is not set. Note: Django 1.4 support wa...
74,344
def get_mnist(): """ Returns tuple containing the concatenated train and test_images, train and test_labels, the image size, and the test length for the MNIST dataset. """ #pull data (train_images, train_labels), (test_images, test_labels) = tf.contrib.keras.datasets.mnist.load_data('datasets') ...
74,345
def restore(): """restore method""" logAndPrint('Restore needs confirmation...', 'info') print "WARNING: You have chosen to restore the database. This will destroy your current instance and replace it with the given back up." answer = raw_input('Are you sure? yes/no ') logAndPrint('"%s" given as the...
74,346
def PreOpL(op, items): """ Uses algorithm from SecureSCM WP9 deliverable. op must be a binary function that outputs a new register """ k = len(items) logk = int(ceil(log(k,2))) kmax = 2**logk output = list(items) for i in range(logk): for j in range(kmax//(2**...
74,347
def generaGraph (pcapfile, macgraph, ipgraph, pathresults = 'results'): """ Genera graphs for connections between IPs and MAC addresses. This function also can be used to read the MACs and IPs in the .pcap or .pcapng file. :param pcapfile: path to the .pcap or .pcapng file :param pathresulst: path t...
74,348
def Daq_SetTrigger(trigger_source: DaqTrigSource, level: float = 0, direction: DaqTrigDir = DaqTrigDir.DIR_BOTH_EDGES, delay: int = 0) -> None: """Configures the trigger on enabled channels Parameters ---------- trigger_source : DaqTrigSource Trigger source...
74,349
def uploader() -> _Uploader: """An _Uploader object with all of its fields filled in.""" return _UploaderFactory()
74,350
def existingusercheck(userdata): """Checks if the input username is already in the userdata file, and if user entry is in valid format. If valid, returns username, password, and user permissions.""" for line in userdata: if (len(line) > 1 and line.split()[0] == username): if (len(line.split()) == 3): re...
74,351
def calc_linear_crossing(m, left_v, right_v): """ Computes the intersection between two line segments, defined by two common x points, and the values of both segments at both x points Parameters ---------- m : list or np.array, length 2 The two common x coordinates. m[0] < m[1] is assum...
74,352
def getall(site, pages, throttle=True, force=False): """Use Special:Export to bulk-retrieve a group of pages from site Arguments: site = Site object pages = iterable that yields Page objects """ # TODO: why isn't this a Site method? pages = list(pages) # if pages is an iterator, we...
74,353
def run_fresh_full_train_DARTS(epochs,output_path_fulltrain, cell_list = None, sep_conv_list = None): """ Perform model evaluation for DARTS/DARTS+ """ GLOBALS.FIRST_INIT = False #optimizer,scheduler=network_initialize(new_network,train_loader) parser = ArgumentParser(description=__doc__) ...
74,354
def filter_fasta(input_fasta, predictions, output, threshold=0.5, print_potentials=False, precision=3, output_neg=None, confidence_thresh=0.5, output_undef=None, bayes_thresh=None, pred_uncertainty=None): """Filter reads in a fasta file by pathogenic potential.""" filter_paired_fasta(input_fast...
74,355
def test_isolate_nodes(mocker, pusher, puller): """ The method tests that the 'Isolate Nodes' request is sent and received correctly. """ pusher.send_isolate_nodes(['10.0.0.1', '10.0.0.2']) request = puller.receive() assert request == (DeferredRequestHeaders.ISOLATE_NODES.value, ('10.0.0.1', '10.0.0.2')...
74,356
def get_program_no_movement(blending): """Test program with two joint steps no movement in between""" j1 = [58, -70, 107, 64, -60, 43] steps = [ # Step: name, move_type, tcp, pose, blending, speed, accel): Step("1", MoveType.Joint, 0, j1, blending, 0, 0), Step("2", MoveType.Joint, 0,...
74,357
def validate_input(input_string): """ :param str input_string: A string input to the program for validation that it will work wiht the diamond_challenge program. :return: *True* if the string can be used to create a diamond. *False* if cannot be used. """ if not isinstance(input_string, st...
74,358
def _open_csv_file(filename): """Opens a file for writing to CSV, choosing the correct method for the current version of Python """ if version_info.major < 3: out_file = open(filename, 'wb') else: out_file = open(filename, 'w', newline='') return out_file
74,359
def get_public_roles(): """Roles which make a collection to be considered public.""" return [ Role.load_id(Role.SYSTEM_GUEST), Role.load_id(Role.SYSTEM_USER), ]
74,360
def path_type(arg): """ Checks if supplied paths are exist and contain .csv files. """ try: dir = Path(arg) except TypeError as e: logger.exception(e) raise if not dir.is_dir(): msg = f"'{dir}' is not a valid directory" raise argparse.Argume...
74,361
def traverse_dependencies( destination, traversed, git ): """ Clone and update dependencies uniquely and collect links to dependency projects in a destination folder """ if not os.path.isdir( dependency_directory() ): return os.chdir( dependency_directory() ) for dependency in ...
74,362
def data_missing(): """Length-2 array with [NA, Valid]""" variant = Variant( chromosome="chr1", position=123456, id="rs12345", ref="A", alt=["T", "G"] ) genotypes = [variant.make_genotype(), variant.make_genotype("T", "T")] return GenotypeArray(values=genotypes)
74,363
def append(dfs, like="columns"): """ Concat multiple dataFrames columns or rows wise :param dfs: List of DataFrames :param like: concat as columns or rows :return: """ # FIX: Because monotonically_increasing_id can create different # sequence for different dataframes the result could be...
74,364
def event_to_show( event: Event, session: Depends(get_db), user: Optional[User] = None, ) -> Optional[Event]: """Check the given event's privacy and return event/fixed private event/ nothing (hidden) accordingly""" is_owner = check_event_owner(event, session, user) if event.privacy == Privac...
74,365
def test_markdown_with_dash_e_single_by_id_and_non_present_config_file(): """ Test to make sure we get an error if we provide a configuration file that is not in a json format. """ # Arrange scanner = MarkdownScanner() configuration_file = "not-exists" assert not os.path.exists(configur...
74,366
def parse_xml(file_name, check_exists=True): """Returns a parsed xml tree with comments intact.""" error_message = "" if check_exists and not os.path.exists(file_name): return None, f"File does not exist {str(file_name)}" try: tree = galaxy_parse_xml(file_name, remove_comments=False, str...
74,367
def test_iterate_pairs_benzene(): """Check that bonds in rings are not double-counted with _iterate_pairs. This should be fixed by using Topology.nth_degree_neighbors directly""" benzene = Molecule.from_smiles("c1ccccc1") mdtop = md.Topology.from_openmm(benzene.to_topology().to_openmm()) _store_bon...
74,368
def posTag_eval(trainfile, testfile): """่ฏ„ไผฐ่ฏๆ€งๆ ‡ๆณจๆจกๅž‹ Args: trainfile (string): ่ฎญ็ปƒๆ•ฐๆฎ้›†่ทฏๅพ„ testfile (string): ๆต‹่ฏ•ๆ•ฐๆฎ้›†่ทฏๅพ„ Returns: list: ่ฏๆ€งๆ ‡ๆณจ็ป“ๆžœ """ hmm_pos = HmmPosTag.HmmPosTag() hmm_pos.train(trainfile) posTag_res = [] dataset_size = float(os.path.getsize(testfile)) / 10...
74,369
def reduce_group_ndims(operation, tensor, group_ndims, name=None): """ Reduce the last `group_ndims` dimensions in `tensor`, using `operation`. In :class:`~tfsnippet.distributions.Distribution`, when computing the (log-)densities of certain `tensor`, the last few dimensions may represent a group of...
74,370
def test_event_ordering(): """Test event order.""" raw, events = _get_data()[:2] events2 = events.copy()[::-1] Epochs(raw, events, event_id, tmin, tmax, reject=reject, flat=flat) with pytest.warns(RuntimeWarning, match='chronologically'): Epochs(raw, events2, event_id, tmin, tmax, reject=rej...
74,371
def items_id(collection_id, item_id, roles=None): """Retrieve a given feature from a given feature collection. :param collection_id: identifier (name) of a specific collection :param item_id: identifier (name) of a specific item """ item = get_collection_items(collection_id=collection_id, roles=rol...
74,372
def Bi_RNN(vocab_size, embedding_matrix,ckpt_path,max_len,embedding_size): """ bi-RNN + GRU :param vocab_size: :param embedding_matrix: :param ckpt_path: :param max_len: :param embedding_size: :return: """ model = Sequential() model.add(Embedding(len(vocab_size),embedding_size,input_length=max_len)) model.a...
74,373
def check_for_pull_request(config, topic_branch): """ Check to make sure pull request for topic branch exists on Github. Uses Github owner/repository information and base branch from the application configuration to check Github to make sure an open pull request exists for the topic branch against the ...
74,374
def sample_patch_multiscale(im, pos, scales, image_sz, mode: str='replicate', max_scale_change=None): """Extract image patches at multiple scales. args: im: Image. pos: Center position for extraction. scales: Image scales to extract image patches from. image_sz: Size to resize th...
74,375
def make_accumulate_client_votes_fn(round_num, discovered_prefixes_table, possible_prefix_extensions_table): """Returns a reduce function that is used to accumulate client votes. This function creates an accumulate_client_votes reduce function that can be consumed by a tf.data...
74,376
def octave_to_frequency(octave: float) -> float: """Converts an octave to its corresponding frequency value (in Hz). By convention, the 0th octave is 125Hz. Parameters ---------- octave : float The octave to put on a frequency scale. Returns ------- float The frequency value c...
74,377
def clause_tensor(l, q=2, g=oror, m=0, dtype=int): """ Return tensorization of the truth table of gate g. Generally, g is a l-ary relation in the constraint language of a (weighted) CSP and this function returns a tensor representation of the relation g. """ d = [q] * l t = zeros(d, ...
74,378
def export_fasta(df, output_dir, output_file_name="X.fasta", filters = {}, id_column='gi', seq_column='Sequence'): """ Construct fasta file from dataframe INPUT: dataframe, output directory and filename, id and seq columns, filter dict OUTPUT: fasta_dict, fasta ...
74,379
def predictions_wavfile(data, model_type): """ Takes the embeddings of wav file and runs the predictions on it """ # call the model and load the weights model = create_keras_model() if model_type == "Motor": model.load_weights("../predictions/binary_relevance_model/Binary_Relevance_Mode...
74,380
def test_get_route_class(): """Should return RouteResult class.""" klass = get_route_class() assert klass == RouteResult
74,381
def _trim_endpoint_api_version(url): """Trim API version and trailing slash from endpoint.""" return re.sub(_API_VERSION_RE, '', url)
74,382
def get_mmp(option, maps=None, out_put=None, target_id=None, extra=None): """Function to find the MMP comparison Takes a pk of the MMP comparison Returns the SD block of that data""" mmp = MMPComparison.objects.get(pk=option) return mmp.sdf_info
74,383
def insertion(word1, word2): """ Args: word1: String, a double occurrence word. word2: String, a double occurrence word. Returns: A boolean indicating whether word2 can be constructed by inserting a repeat word or return word into word1. If it can, then the two indi...
74,384
def consolidate_trcks(x, include_end=False): """ Consolidates all midi.events in a midi.Pattern into a single track """ if isinstance(x, midi.Pattern): old_ptrn = x else: old_ptrn = midi.Pattern(format=1, resolution=480, tick_relative=True,) for trck in x: if isin...
74,385
def calculate_curtailment_time_series(scenario): """Calculate hourly curtailment for each renewable generator. :param powersimdata.scenario.scenario.Scenario scenario: scenario instance. :return: (*pandas.DataFrame*) -- time series of curtailment. """ _check_scenario_is_in_analyze_state(scenario) ...
74,386
def barchart_by_target(df, path): """ Saves barchart figure generated with df in <out_filepath>_barchart_by_target.png Parameters ---------- df : pd.DataFrame data path : string the path/file prefix where output file will be saved Returns ------- None """ df...
74,387
def index(): """List archived parties.""" parties = party_service.get_archived_parties_for_brand(g.brand_id) parties = [p for p in parties if not p.canceled] return { 'parties': parties, }
74,388
def get_ext_paths(root_dir, exclude_files): """get filepaths for compilation""" paths = [] for root, dirs, files in os.walk(root_dir): for filename in files: if os.path.splitext(filename)[1] != '.pyx': continue file_path = os.path.join(root, filename) ...
74,389
def getMessageLength(imageArray): """gets the message length out of the first 8 pixels""" length = "" for i in range(8): for j in range(3): length += str(imageArray[i][j] % 2) if doLogOutput: print(f"Binary length: {str(length)}") print(f"Decimal length: {str(int(len...
74,390
def find_orbitals_from_statelines(out_info_dict): """ This function reads in all the state_lines, that is, the lines describing which atomic states, taken from the pseudopotential, are used for the projection. Then it converts these state_lines into a set of orbitals. :param out_info_dict: contains...
74,391
def EI(model, _, X, xi=0.0): """ Expected improvement policy with an exploration parameter of `xi`. """ model = model.copy() target = model.predict(X)[0].max() + xi def index(X, grad=False): """EI policy instance.""" return model.get_improvement(target, X, grad) return inde...
74,392
def test_1_3_keto_enol_enumeration(): """Enumerate 1,3 keto/enol tautomer.""" assert enumerate_tautomer("C1(=CCCCC1)O") == {"OC1=CCCCC1", "O=C1CCCCC1"} assert enumerate_tautomer("C1(CCCCC1)=O") == {"OC1=CCCCC1", "O=C1CCCCC1"}
74,393
def scoring(es_doc): """Return the final scored instance as an elasticsearch-format document.""" doc = {"_source": es_doc[1], "_id": es_doc[0], "_index": get_index_name(), "_type": get_type_name() } result = score_instance(doc) return (es_doc[0], result["...
74,394
def TFlt_GetMegaStr(*args): """ TFlt_GetMegaStr(double const & Val) -> TStr Parameters: Val: double const & """ return _snap.TFlt_GetMegaStr(*args)
74,395
def format_metrics_map(metrics_map): """Properly format iterable `metrics_map` to contain instances of :class:`Metric` Parameters ---------- metrics_map: Dict, List Iterable describing the metrics to be recorded, along with a means to compute the value of each metric. Should be of one o...
74,396
def add_categories(user_id): """This route handles posting categories""" if request.method == "POST": name = str(request.data.get('name')).strip() name = re.sub(' +',' ', name) resultn = valid_category(name) if resultn: return jsonify(resultn), 400 name = nam...
74,397
def test_https_h1(https_test_server_fixture): """ Runs the CLI configured to use HTTP/1 over https against our test server, and sanity checks statistics from both client and server. """ parsed_json, _ = https_test_server_fixture.runNighthawkClient([ https_test_server_fixture.getTestServerRootUri(), "--c...
74,398
def WV_WI(bands: dict) -> xr.DataArray: """ WorldView-Water (WV-WI) Useful for detecting standing, flowing water, or shadow in VNIR imagery WV_WI = ((B8-B1)/(B8+B1)) https://resources.maxar.com/optical-imagery/multispectral-reference-guide Args: bands (dict): Bands as {band_name: xr.Da...
74,399