content
stringlengths
22
815k
id
int64
0
4.91M
def construct_fid_mask(catalog): """ Constructs the fidelity mask based off my results, not Robertos :param catalog: :return: """ line_widths = [i for i in range(3, 21, 2)] fid_catalog = load_table("fidelity_snr.out", start=0) fid_limit = 0.4 six_fids = [] for width in line_widt...
5,346,700
def get_template(filename): """ return html mail template """ current_dir = os.path.dirname(__file__) tpl = read_file(os.path.join(current_dir,'templates',filename)) if not tpl: _log('Mailer error: could not load file "%s"'%filename) sys.exit(1) return tpl
5,346,701
def _run_job(tgt, fun, arg, kwarg, tgt_type, timeout, retry): """ Helper function to send execution module command using ``client.run_job`` method and collect results using ``client.get_event_iter_returns``. Implements basic retry mechanism. If ``client.get_event_iter_returns`` return no results, `...
5,346,702
def _set_rank_colorbar(ax, img, norm): """ Set color bar for rankshow on the right of the ax """ divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(img, cax=cax) y_tick_values = cax.get_yticks() boundary_means = [np.mean((y_tick_values[...
5,346,703
def yield_checksumfiles(queryset: Union[QuerySet, List[ChecksumFile]], directory: str): """Checkout a queryset of ChecksumFile records under a single directory. This will use the `name` field of each of the files as their relative path under the temporary directory. Please note that this uses a contex...
5,346,704
def destination(stub: str) -> Optional[Path]: """Determine stub path Only handle micropython stubs, ignoring any cPython stdlib equivalents. """ prefix, _, suffix = stub.partition(".") if importlib.util.find_spec(prefix): # type: ignore return # in cPython stdlib, skip prefix = ...
5,346,705
def is_gafqmc_result_dir(D, files=None, dirs=None, file_pattern=None, parse_file=True): """Tests whether the directory D, containing `files' (and softlinks) and directories `dirs' is a result directory for a GAFQMC-type calculation. Returns the score of the test, where higher score mean...
5,346,706
def train_IPCA(X,n_dims,batch_size,model='ipca'): """ name: train_IPCA Linear dimensionality reduction using Singular Value Decomposition of centered data, keeping only the most significant singular vectors to project the data to a lower dimensional space. returns: the transformer model """...
5,346,707
def _str_cell(cell: Cell) -> str: """Строковое представление клетки. Данной строкой клетка будет выводится на экран. """ if cell.is_open: if cell.is_empty: return " " elif cell.value: return f" {cell.value} " elif cell.is_flagged: return "[F]" e...
5,346,708
def mvw_ledoit_wolf(prices, weight_bounds=(0.,1.), rf = 0., options = None): """ Calculates the mean-variance weights given a DataFrame of returns. Wraps mean_var_weights with ledoit_wolf covariance calculation method Args: * prices (...
5,346,709
def _PadLabels3d(logits, labels): """Pads or slices 3-d labels to match logits. Covers the case of 2-d softmax output, when labels is [batch, height, width] and logits is [batch, height, width, onehot] Args: logits: 4-d Pre-softmax fully-connected output. labels: 3-d, but not necessarily matching in si...
5,346,710
def intx(): """Returns the default int type, as a string. (e.g. 'int16', 'int32', 'int64'). # Returns String, the current default int type. """ return _INTX
5,346,711
def dev_end_hardware_script() -> Response: """Designate the end of a hardware script in flask log. Can be invoked by: curl http://localhost:4567/development/end_hardware_script """ return Response(json.dumps({}), mimetype="application/json")
5,346,712
def heappush(heap, item): # real signature unknown; restored from __doc__ """ heappush(heap, item) -> None. Push item onto heap, maintaining the heap invariant. """ pass
5,346,713
def _init_train(opt): """Common initilization stuff for all training process.""" ArgumentParser.validate_prepare_opts(opt) if opt.train_from: # Load checkpoint if we resume from a previous training. checkpoint = load_checkpoint(ckpt_path=opt.train_from) fields = load_fields(opt.save...
5,346,714
def main(wf): """Run workflow script.""" opts = docopt.docopt(__doc__, argv=wf.args, version=wf.version) if opts['list']: return list_actions(opts) dry_run = opts['--nothing'] log.info('=' * 50) log.debug('opts=%r', opts) log.info('looking for workflows using an outdated version ' ...
5,346,715
def compare(isamAppliance1, isamAppliance2): """ Compare Update Servers between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) for obj in ret_obj1['data']: del obj['uuid'] for obj in ret_obj2['data']: del obj['uuid'] return ibms...
5,346,716
def rasterize(feature, grid, id_column=None, include_ids=None, crs=None, epsg=None, proj4=None, dtype=np.float32, **kwargs): """Rasterize a feature onto the model grid, using the rasterio.features.rasterize method. Features are intersected if they contain the cell c...
5,346,717
def get_random(): """ Retrieves the current issue of XKCD, chooses an issue 1 - current issue #, and returns a json object. Returns null if an requests error occurs. """ return get_issue(random.randint(1, int(get_current()["num"])))
5,346,718
def get_elements(): #elements = driver.find_elements(By.XPATH, '//div[@class="view-items-wrp"]/a') """ driver.find_elements(By.XPATH, '//div[@class="view-items-wrp"]/a') """ heading3 = driver.find_elements_by_tag_name("h3") elements = driver.find_elements_by_tag_name("a") updatedLength = len(headin...
5,346,719
def model_to_model_2x_wide(model_from: tf.Module, model_to: tf.Module, epsilon: float = 0.1): """Expands a model to a wider version. Also makes sure that the output of the model is not changed after expanding. For example: ``` model_narrow = tf.keras.Sequ...
5,346,720
def run_script(args, script): """ Run the script with the arguments provided """ # check for visualization script visualization_script = utilities.get_package_file(script, "Rscript") if not visualization_script: sys.exit("ERROR: Unable to find script "+script) try: command = [...
5,346,721
def get_fasta_readlengths(fasta_file): """ Get a sorted list of contig lengths :return: (tuple) """ lens = [] with open_fasta_reader(fasta_file) as f: for record in f: lens.append(len(record.sequence)) lens.sort() return lens
5,346,722
def postprocess(p, gt, width_and_height, p_binary, false_positives=False, false_negatives=False): """ This function does matching and then postprocessing of p's and gt's :param p: the objects given from rcnn :param gt: the objects we get from the ground truth :param width_and_height: the width and h...
5,346,723
def deg(x): """ Convert an array of torsion angles in radians to torsion degrees ranging from -180 to 180. @param x: array of angles @type x: numpy array @rtype: numpy array """ from csb.bio.structure import TorsionAngles func = numpy.vectorize(TorsionAngles.deg) ret...
5,346,724
def run_median_trial(): """Generate table for Median Trial.""" tbl = DataTable([10,15,15],['N', 'median_time', 'sort_median']) trials = [2**k+1 for k in range(8,20)] for n in trials: t_med = 1000*min(timeit.repeat(stmt='assert(linear_median(a) == {}//2)'.format(n), ...
5,346,725
def regroup(X, N): """ Regroups the rows and columns of X such that rows/cols that are N apart in X, are adjeacent in Y. If N is a 2 element vector, N[0] is used for rows and N[1] is used for columns. Parameters: X: m by n matrix to be regrouped. N: Integer or two element vector...
5,346,726
def return_estimators(n_components): """Returns all of the estimators that can be used to generate models. A larger selection of possible estimators have been commented out, but could be uncommented.""" estimators = [ ('PCArandom', decomposition.PCA(n_components=n_components, svd_solve...
5,346,727
def _check_type_picks(picks): """helper to guarantee type integrity of picks""" err_msg = 'picks must be None, a list or an array of integers' if picks is None: pass elif isinstance(picks, list): if not all(isinstance(i, int) for i in picks): raise ValueError(err_msg) ...
5,346,728
def get_test_standard_scaler_str(): """ Get a pandas projection code str """ test_code = cleandoc(""" standard_scaler = StandardScaler() encoded_data = standard_scaler.fit_transform(df) """) return test_code
5,346,729
def add_command( command_list: List[Tuple[re.Pattern, callable]], func: callable, command_str: str ) -> List[Tuple[re.Pattern, callable]]: """Add a function and the command pattern to the command list. Args: func: Function it will be called command_str: command string that specifies the pat...
5,346,730
def get_clusters_and_critical_nodes(G, k, rho_star, phi_in): """ The implementation of the main body of the partitioning Algorithm. The main while-loop of the algorithm is executed as long as a refinement is still possible. :param phi_in: An algorithm parameter used to lower bound the inner conductance...
5,346,731
def scatter_row_inplace(data, row_index, value): """Write the value into the data tensor using the row index inplace. This is an inplace write so it will break the autograd. Parameters ---------- data : Tensor The data tensor to be updated. row_index : Tensor A 1-D integer tens...
5,346,732
def get_edges_out_for_vertex(edges: list, vertex: int) -> list: """Get a sublist of edges that have the specified vertex as first element :param edges: edges of the graph :param vertex: vertex of which we want to find the corresponding edges :return: selected edges """ return [e for e in edge...
5,346,733
def pellet_plot_multi_unaligned(FEDs, shade_dark, lights_on, lights_off,**kwargs): """ FED3 Viz: Plot cumulaive pellet retrieval for multiple FEDs, keeping the x-axis to show absolute time. Parameters ---------- FEDs : list of FED3_File objects FED3 files...
5,346,734
def print_results(results, num_tests): """ Prints the results of regression tests. results -- a list of all testing results """ if par.format_for_diff: failed = sum([item.split(" ")[0] == par.format_for_diff.split(" ")[0] for item in results]) else: failed = sum([item.split(":")[0] == "Error" for item in re...
5,346,735
def generateMostProbesPerDay(database): """Generate the Top 20 most probes per day from the MySQL Database""" try: conn = pymysql.connect(host=conf.MYSQL_HOST, port=conf.MYSQL_PORT, user=conf.MYSQL_USER, passwd=conf.MYSQL_PWD, db=database) except pymysql.MySQLError as e: print e.args[1] ...
5,346,736
def collect_ocs_logs(dir_name, ocp=True, ocs=True, mcg=False): """ Collects OCS logs Args: dir_name (str): directory name to store OCS logs. Logs will be stored in dir_name suffix with _ocs_logs. ocp (bool): Whether to gather OCP logs ocs (bool): Whether to gather OCS lo...
5,346,737
def sync_via_mrmsdtw(f_chroma1: np.ndarray, f_chroma2: np.ndarray, f_DLNCO1: np.ndarray = None, f_DLNCO2: np.ndarray = None, input_feature_rate: float = 50, step_sizes: np.ndarray = np.array([[1, 0], [0, 1], [1, 1]]...
5,346,738
def test_key_usage(crypto_protocol_name: str) -> None: """Generate keys, sign and verify previously created signature.""" private_key = generate_private_key(crypto_protocol_name) public_key = private_key.public_key() data = b"Some randome data we would like to sign" signature = private_key.sign(data...
5,346,739
def simulate_beta_binomial( K, D, sigma2, theta, mu=0, invlink=logistic, seed=None): """Simulates from binomial Gaussian process with Beta latent noise. Args: K: Cell-state kernel, for example as generated by create_linear_kernel or create_rbf_kernel. D: Array of total counts. ...
5,346,740
def convert_to_floats(tsi): """ A helper function that tax all of the fields of a TaxSaveInputs model and converts them to floats, or list of floats """ def numberfy_one(x): if isinstance(x, float): return x else: return float(x) def numberfy(x): ...
5,346,741
def properties_filter(mol): """ Calculates the properties that contain logP, MW, HBA, HBD, TPSA, NRB """ #frag = Chem.rdmolops.GetMolFrags(mol) # remove '.' #if len(frag) > 1: #return False MW_s = Descriptors.MolWt(mol) # MW if MW_s < 250 or MW_s > 750: return False A...
5,346,742
def _create_certificate_chain(): """ Construct and return a chain of certificates. 1. A new self-signed certificate authority certificate (cacert) 2. A new intermediate certificate signed by cacert (icert) 3. A new server certificate signed by icert (scert) """ caext = X509Exten...
5,346,743
async def async_recorder_block_till_done( opp: OpenPeerPower, instance: recorder.Recorder, ) -> None: """Non blocking version of recorder.block_till_done().""" await opp.async_add_executor_job(instance.block_till_done)
5,346,744
def make_constant_raster_from_base_uri( base_dataset_uri, constant_value, out_uri, nodata_value=None, dataset_type=gdal.GDT_Float32): """Create new gdal raster filled with uniform values. A helper function that creates a new gdal raster from base, and fills it with the constant value provid...
5,346,745
async def test_simple_properties(hass: HomeAssistant): """Test that simple properties work as intended.""" state = hass.states.get(VAC_ENTITY_ID) registry = await hass.helpers.entity_registry.async_get_registry() entity = registry.async_get(VAC_ENTITY_ID) assert entity assert state assert s...
5,346,746
def build_job_spec_name(file_name, version="develop"): """ :param file_name: :param version: :return: str, ex. job-hello_world:develop """ name = file_name.split('.')[-1] job_name = 'job-%s:%s' % (name, version) return job_name
5,346,747
def draw_mask(im: torch.Tensor, mask: torch.Tensor, t=0.2, color=(255, 255, 255), visualize_instances=True): """ Visualize mask where mask = 0. Supports multiple instances. mask shape: [N, C, H, W], where C is different instances in same image. """ assert len(mask.shape) in (3, 4), m...
5,346,748
def view_about(): """ shows the about page :return: :rtype: """ return render_template('about.html', title="About Flask AWS Template")
5,346,749
def validate_is_mergeable(tc, *python_schema): """ Raises an error if the column names in the given schema conflict """ scala_schema_list = [] for schema in python_schema: if not isinstance(schema, list): schema = [schema] scala_schema_list.append(schema_to_scala(tc.sc, ...
5,346,750
def viterbi(observed_values, transition_probabilities, emission_probabilities, initial_distribution, file_name, log=True): """Calculates the viterbi-path for a given hidden-markov-model, heavily inspired by Abhisek Janas Blogpost "Implement Viterbi Alg...
5,346,751
def extract_psf_fitting_names(psf): """ Determine the names of the x coordinate, y coordinate, and flux from a model. Returns (xname, yname, fluxname) """ if hasattr(psf, 'xname'): xname = psf.xname elif 'x_0' in psf.param_names: xname = 'x_0' else: raise ValueError...
5,346,752
def primes(): """ Generate prime numbers """ primes = [] for n in count(2): found_prime = True for p in primes: if p*p > n: break if n % p == 0: found_prime = False break if found_prime: prime...
5,346,753
def parseargs(p): """ Add arguments and `func` to `p`. :param p: ArgumentParser :return: ArgumentParser """ # TODO: Implement --date, --time and -t p.set_defaults(func=func) p.description = ( "Update the access and modification times of each " + "FILE to the current tim...
5,346,754
def config_check_conformance(cookie, dn): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("ConfigCheckConformance") method.cookie = cookie method.dn = dn xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
5,346,755
def get_dist_to_port(geotiff): """ Extract "truth" dist_to_port from geotiff """ with Geotiff(geotiff) as tif: dist_to_port = tif.values return dist_to_port
5,346,756
def build_dataset_exporter( dataset_type, strip_none=True, warn_unused=True, **kwargs ): """Builds the :class:`DatasetExporter` instance for the given parameters. Args: dataset_type: the :class:`fiftyone.types.dataset_types.Dataset` type strip_none (True): whether to exclude None-valued ite...
5,346,757
def conditions(x): """ This function will check whether the constraints that apply to our optimization are met or not. """ if ( (10/x[0]) > 66.0 ): return False elif ( (10/x[0] + 12/x[1]) > 88.0 ): return False elif ( (10/x[0] + 12/x[1] + 7/x[2]) > 107.0 ): ...
5,346,758
def _write_report( report_filename, supervision_modes, counters, ): """Creates the report_filename file containing statistics about conversion.""" contents = [] contents.append('\t'.join(('Total', 'Valid', 'Failed', 'File'))) for dataset, counter in counters.items(): failed = counter.pop('failed...
5,346,759
def clear_SystemInfo() -> None: # noqa """Clear OsInfo singleton.""" SystemInfo.clear_singleton()
5,346,760
def step_impl(context): """ Now we call the different internal methods and save their values internally in the world parameter """ with mock.patch('requests.get') as requests_get: requests_get.return_value = APIHelperCallAPI(ASSET_LIST_GET) world.client_assets = world.client.assets...
5,346,761
def Tcolloc2X1S(outf, (prefixes,topics,segments), IFflag=False): """non-linguistic context topics topics can generate exactly one topical collocation topical collocations contain exactly one topical word""" outf.write("1 1 Colloc2s --> Colloc2s Colloc2\n") for topic in topics: if topic...
5,346,762
def load_reco_param(source): """Load reco parameterisation (energy-dependent) from file or dictionary. Parameters ---------- source : string or mapping Source of the parameterization. If string, treat as file path or resource location and load from the file; this must yield a mapping. I...
5,346,763
def face_palm(text, message): """<nick> - Expresses your frustration with <Nick>. Code located in reactions.py""" face_palmer = text.strip() message('Dammit {} {}'.format(face_palmer, random.choice(reaction_macros['facepalm_macros'])))
5,346,764
def get_commit_ancestors_graph(refenv, starting_commit): """returns a DAG of all commits starting at some hash pointing to the repo root. Parameters ---------- refenv : lmdb.Environment lmdb environment where the commit refs are stored starting_commit : string commit hash to start c...
5,346,765
def is_verification_handshake(rjson): """ Determines if the request is the Slack application APIs verification handshake :rtype: bool """ # Check body contains the right keys for x in ['token', 'challenge', 'type']: if x not in rjson: return False # Check type is correct...
5,346,766
def template_node(scope_key): """ Create and return a new template node. Parameters ---------- scope_key : object The key for the local scope in the local storage maps. Returns ------- result : TemplateNode A new compiler template node. """ node = TemplateNode() ...
5,346,767
def _add_unit_and_content(unit, result): """Adds the score dimensions for units and its lessons and questions.""" # The content of an assessment is indicated by a lesson_id of None. # Inside that lesson we can find all the questions added directly # to the assessment. unit_dict = { DIM_TYPE:...
5,346,768
def alarm(state_doc, rds_session): """"alarm: something went wrong we are going to scream about it.""" logger.error(datadog_dbsnap_verify_status_check(state_doc, "CRITICAL")) logger.info(datadog_dbsnap_verify_set_count(state_doc, "dbsnap_verify.failed"))
5,346,769
def run_command(args): """Calls the program using the specified command.""" if args.project_id is None: print('You must specify a project ID or set the ' '"GOOGLE_CLOUD_PROJECT" environment variable.') return elif args.command == 'create-fhir-store': create_fhir_store(...
5,346,770
def test_get_id_info_invalid_arg_in_str(): """ Test to see if get_id_info raises the correct exception when an incorrect type for the in_str arg is passed. """ sa_id_book = SAIDBook() with pytest.raises(TypeError): sa_id_book.get_id_info(['not legit'])
5,346,771
def GetAutoResult(chroot_path, buildbucket_id): """Returns the conversion of the result of 'cros buildresult'.""" # Calls 'cros buildresult' to get the status of the tryjob. build_result = GetStatusFromCrosBuildResult(chroot_path, buildbucket_id) # The string returned by 'cros buildresult' might not be in the...
5,346,772
def abort(message: str) -> typing.NoReturn: """Print an error message and raise an Exit exception""" sprint(f"[error]{message}") raise typer.Exit(1)
5,346,773
def rft(x): """ Real Fourier Transform """ # XXX figure out what exactly this is doing... s = x.shape[-1] xp = np.zeros(x.shape,dtype="complex64") xp[...,1:s/2] = x[...,1:-1:2]+x[...,2::2]*1.j xp[...,0] = x[...,0]/2. xp[...,s/2] = x[...,-1]/2. return np.array(nmr_reorder(np.fft...
5,346,774
def yam_path(manifestsdir): """Bundletracker manifest.""" return join(manifestsdir, 'yam.json')
5,346,775
def single_from(iterable): """Check that an iterable contains one unique value, and return it.""" unique_vals = set(iterable) if len(unique_vals) != 1: raise ValueError('multiple unique values found') return unique_vals.pop()
5,346,776
def create(engine): """Create new dB""" Base.metadata.create_all(bind=engine)
5,346,777
def vthash(filehash: str): """Returns the analysis data class for a file in VirusTotal's database""" endpoint_path = f'/files/{filehash}' endpoint = f"{api_base_url}{endpoint_path}" r = requests.get(endpoint, headers=header) if r.status_code == 404 and r.json()['error']['code'] == 'NotFoundError'...
5,346,778
def add(ctx, file_, directory, es, username, password, ignore_certs): """add data to system""" if all([file_ is None, directory is None]): raise click.ClickException('Missing --file/-f or --dir/-d option') conn_config = configure_es_connection(es, username, password, ignore_certs) files_to_pr...
5,346,779
def non_credibility_index3(sol, ref_sol, evalgrid): """Compute a variant of the non-credibility index.""" raise NotImplementedError
5,346,780
def prod(x, axis=None, keepdims=False): """ product of all element in the array Parameters ---------- x : tensor_like input array axis : int, tuple of ints axis or axes along which a product is performed keepdims : bool keep dimensionality or not Returns ---...
5,346,781
def menu(queue: List[str] = None): """Fred Menu""" fred_controller = FredController(queue) an_input = "HELP_ME" while True: # There is a command in the queue if fred_controller.queue and len(fred_controller.queue) > 0: # If the command is quitting the menu we want to return ...
5,346,782
def load_line( file: str, separator: Union[None, str] = None, max_split: int = -1, deduplication: bool = False, line_processor: Callable = repeat, open_method: str = 'open', ) -> Iterator: """ 按行读入文件,会去掉每行末尾的换行符 :param file: 文件路径 :param separator: 用separat...
5,346,783
def generic_repr(name, obj, deferred): """ Generic pretty printer for NDTable and NDArray. Output is of the form:: Array(3, int32) values := [Numpy(ptr=60597776, dtype=int64, shape=(3,))]; metadata := [contigious] layout := Identity; [1 2 3] """ ...
5,346,784
def build_model(X, y, ann_hidden_dim, num_passes=20000): """ :param ann_hidden_dim: Number of nodes in the hidden layer :param num_passes: Number of passes through the training data for gradient descent :return: returns the parameters of artificial neural network for prediction using forward propagation...
5,346,785
def g_square_dis(dm, x, y, s): """G square test for discrete data. Args: dm: the data matrix to be used (as a numpy.ndarray). x: the first node (as an integer). y: the second node (as an integer). s: the set of neibouring nodes of x and y (as a set()). levels: levels of ...
5,346,786
def start(name): """ Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> """ cmd = "/usr/sbin/svcadm enable -s -t {0}".format(name) retcode = __salt__["cmd.retcode"](cmd, python_shell=False) if not retcode: return True ...
5,346,787
def line_coloring(num_vertices) -> Dict: """ Creates an edge coloring of the line graph, corresponding to the optimal line swap strategy, given as a dictionary where the keys correspond to the different colors and the values are lists of edges (where edges are specified as tuples). The graph colorin...
5,346,788
def flatten_outputs(predictions, number_of_classes): """Flatten the prediction batch except the prediction dimensions""" logits_permuted = predictions.permute(0, 2, 3, 1) logits_permuted_cont = logits_permuted.contiguous() outputs_flatten = logits_permuted_cont.view(-1, number_of_classes) return out...
5,346,789
def pytest_sessionstart(session): """ Called after the Session object has been created and before performing collection and entering the run test loop. """ "session start" if session.config.getoption("--cache-requests"): requests_cache.install_cache( os.path.join(tempfile.get...
5,346,790
def get_r_vals(cell_obj): """Get radial distances for inner and outer membranes for the cell object""" r_i = cell_obj.coords.calc_rc(cell_obj.data.data_dict['storm_inner']['x'], cell_obj.data.data_dict['storm_inner']['y']) r_o = cell_obj.coords.calc_rc(cell_obj.data.dat...
5,346,791
def test_patch_accessor(api_rf, km_user_accessor_factory): """ Sending a PATCH request to the view should update the accessor with the given ID. """ accessor = km_user_accessor_factory(is_admin=False) data = {"is_admin": True} api_rf.user = accessor.km_user.user request = api_rf.patch(...
5,346,792
def get_all_migrations(ctxt, inactive=0): """Get all non-deleted source hypervisors. Pass true as argument if you want deleted sources returned also. """ return db.migration_get_all(ctxt, inactive)
5,346,793
def extract(input_data: str) -> tuple: """take input data and return the appropriate data structure""" rules = input_data.split('\n') graph = dict() reverse_graph = dict() for rule in rules: container, contents = rule.split('contain') container = ' '.join(container.split()[:2]) ...
5,346,794
def test_send_control_c_windows(): """Test send control c on Windows.""" process = Popen( # nosec ["timeout" if platform.system() == "Windows" else "sleep", "5"] ) time.sleep(0.001) pid = process.pid with patch("aea.helpers.base.signal") as mock_signal: mock_signal.CTRL_C_EVENT ...
5,346,795
def get_total_indemnity(date_of_joining, to_date): """To Calculate the total Indemnity of an employee based on employee's Joining date. Args: date_of_joining ([date]): Employee's Joining Date to_date ([data]): up until date Returns: total_allocation: Total Indemnity Allocation calc...
5,346,796
def run_species_phylogeny_iqtree(roary_folder, collection_dir, threads=8, overwrite=False, timing_log=None): """ Run iqtree to create phylogeny tree from core gene alignment. If the list of samples has not changed, and none of the samples has changed, the existing tree will be kept unless overwrite is s...
5,346,797
def api_2_gamma_oil(value): """ converts density in API(American Petroleum Institute gravity) to gamma_oil (oil relative density by water) :param value: density in API(American Petroleum Institute gravity) :return: oil relative density by water """ return (value + 131.5) / 141.5
5,346,798
def compute_metrics(pred, label): """Compute metrics like True/False Positive, True/False Negative.` MUST HAVE ONLY 2 CLASSES: BACKGROUND, OBJECT. Args: pred (numpy.ndarray): Prediction, one-hot encoded. Shape: [2, H, W], dtype: uint8 label (numpy.ndarray): Ground Truth, one-hot encoded....
5,346,799