content
stringlengths
22
815k
id
int64
0
4.91M
def run_on_patches( image, model, conf_threshold, nms_threshold, batch_size=128, z_unit="micro", toggle_eval=False, device="cuda", plot_result=False, ): """ Runs input image as 448x448 patches through model and returns resulting particle predictions :param im...
75,600
def mbar_hessian(u_kn, N_k, f_k): """Hessian of MBAR objective function. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The numbe...
75,601
def runCommand(userhome, userconfig, argv): """ Run program with supplied configuration base directory, configuration directory and command arguments. This is called by main function (below), and also by test suite routines. Returns exit status. """ options = parseCommandArgs(argv[1:]) ...
75,602
def shape_dim_for_plot(iter_avg, n_runs, data, run): """Go from shape: (:, data) → (-1, iter_avg) → (-1) (average over data) → (n_runs, 250) Example: (5000,) → (250, 20) → (250, ) → (1, 250)""" data = np.asarray(data) shape_other_dims = data.shape[:-1] data = data.reshape(shape_other_dims + (-1, ite...
75,603
def wasserstein_matching(dgm1, dgm2, matching, labels=["dgm1", "dgm2"], ax=None): """ Visualize bottleneck matching between two diagrams Parameters =========== dgm1: array A diagram dgm2: array A diagram matching: ndarray(Mx+Nx, 3) A list of correspondences in an optima...
75,604
def set_default_for_instance(instance, sender): """ Just set default is somehow default value was deleted. """ if not instance.is_default: return categories = sender.objects \ .filter(workspace=instance.workspace, project=instance.project) if not categories.exists() or categories.filter(is_default=True...
75,605
def parseIctXML(source, keepResponseData=False): """ Parse the 2015 ICT observables xml string for each block. The 2015 Science ICT follows a precursor of the SBT data format, where most of the observable events are saved in the Response data table, as a "response" associated with an AccNum. This f...
75,606
def getW(D, K, Mu = 0.5): """ Return affinity matrix :param D: Self-similarity matrix :param K: Number of nearest neighbors :param Mu: Nearest neighbor hyperparameter (default 0.5) """ #W(i, j) = exp(-Dij^2/(mu*epsij)) DSym = 0.5*(D + D.T) np.fill_diagonal(DSym, 0) Neighbs = np....
75,607
def update_vocabulary( vocabulary_name, language_code, transcribe_client, phrases=None, table_uri=None): """ Updates an existing custom vocabulary. The entire vocabulary is replaced with the contents of the update. :param vocabulary_name: The name of the vocabulary to update. :param...
75,608
def get_account_output(min_tls_version: Optional[pulumi.Input[Optional[str]]] = None, name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[Optional[str]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.O...
75,609
def save_model(model, model_filepath): """ Save machine learning model. Args: model: Model for evaluation. model_filepath: File path to save model to. """ pickle.dump(model, open(model_filepath, 'wb'))
75,610
def handle(f): """Handles exception in wrapped function and writes to LOG.""" @func.wraps(f) def f_handle(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: LOG.exception(e) return f_handle
75,611
def test_cs_save_registration_document(session): """Assert that saving a registration verification statement to google cloud storage works as expected.""" raw_data = None with open(TEST_REGISTRATION_DATAFILE, 'rb') as data_file: raw_data = data_file.read() data_file.close() response = G...
75,612
def renamePath(src, dst, extension=None, force=False): """ Rename the given source path to the given destination path. :type src: str :type dst: str :type extension: str :type force: bool :rtype: str """ dirname = os.path.dirname(src) if "/" not in dst: dst = os.path.jo...
75,613
def tess_flux_to_mag(flux): """Convert flux from TESS observation to magnitude.""" # Based on https://heasarc.gsfc.nasa.gov/docs/tess/observing-technical.html#saturation # TESS CCDs produce 15000 e/s for magnitude 10 light source if isinstance(flux, u.Quantity): flux_raw = flux.to(u.electron / ...
75,614
def to_tuple( value: str, split_re: str = r"[\s,]+", converter: Callable[[str], Any] = str, max_split: int = 0, ) -> Tuple[Any, ...]: """Convert value to a tuple""" return tuple( converter(s) for s in re.split(split_re, str(value), maxsplit=max_split) if s )
75,615
def geodetic2ecef( lat: ndarray, lon: ndarray, alt: ndarray, ell: Ellipsoid = None, deg: bool = True, ) -> Tuple[ndarray, ndarray, ndarray]: """ point transformation from Geodetic of specified ellipsoid (default WGS-84) to ECEF Parameters ---------- lat : float target ...
75,616
def calc_bv(mag_pars): """Calculate a B-V colour from stellar parameters. Calculate B-V colour from stellar parameters [EEP, log10(age, yrs), feh, distance (in parsecs) and extinction] using MIST isochrones. Args: mag_pars (list): A list containing EEP, log10(age) in years, metalli...
75,617
def find_packages(path, base="" ): """ Find all packages in path """ packages = {} for item in os.listdir(path): dir = os.path.join(path, item) if is_package( dir ): if base: module_name = "%(base)s.%(item)s" % vars() else: module_name ...
75,618
def jsonext_loads(data: Union[str, bytes]) -> Any: """Deserializes a json representation of known objects into those objects. Parameters ---------- data : str or bytes The byte-serialized JSON blob. Returns ------- Any The deserialized Python objects. """ return js...
75,619
def test_calc_difference(): """Test difference command with valid inputs.""" from app.cli import difference runner = CliRunner() result = runner.invoke(difference, ["1", "0.2", "0.3"]) assert result.exit_code == 0 assert pytest.approx(float(result.output)) == 0.5
75,620
def _add_tests_command(subparsers): """ :param subparser: :return: """ parser_tests = subparsers.add_parser('tests', help='Run unit tests', description='This command executes all unit tests, among them is an ' ...
75,621
def tail_log(config_file, lines=50): """Tails the log""" cfg = helper.get_config(config_file) for host_config in cfg['hosts']: env.host_string = helper.get_env_host_string(host_config) env.user = helper.get_env_user(host_config) env.key_filename = helper.get_env_key_filename(host_co...
75,622
def lu(variables, t): """Lu, Jinhu, and Guanrong Chen. "A NEW CHAOTIC ATTRACTOR COINED." International Journal of Bifurcation and Chaos 12.3 (2002): 659-661. DOI: 10.1142/S0218127402004620 """ x, y, z = variables a = 36 b = 3 c = 20 dx = -a*x+a*y dy = c*y-x*z dz = x*y-b...
75,623
def get_server(url=None, port=None, keyfile=None, certfile=None,verbose=False): """ returns an xmlrpc connection to the service a the specified address """ if url: url_parts = url.split(":") if len(url_parts) >1: pass else: url = "http://%(url)s:%(por...
75,624
def test_cumsum(): """ test cumsum threshold = 1.5 input is [[1, 1], [2, 3], [4, 5]] axis = 0 expect is [[1, 1], [3, 4], [7, 9]] :return: """ main_program = fluid.Program() startup_program = fluid.Program() with fluid.unique_name.guard(): with fluid.program_guard( ...
75,625
def prepareECOCLossOutputs(net, ds, ecoc_table, input_name, output_names, splits=['train', 'val', 'test']): """ :param net: :param ds: :param ecoc_table: :param input_name: :param output_names: :param splits: :return: """ # Insert ecoc_table in net if 'additional_data' not i...
75,626
def vector_info(map, layer=1): """Return information about a vector map (interface to `v.info`). Example: >>> vector_info('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE {'comment': '', 'projection': 'Lambert Conformal Conic' ... 'south': 10875.8272320917} :param str map: map name :para...
75,627
def distance_xy(p1, p2): """Calculates 2D distance between p1 and p2. p1 and p2 are vectors of length >= 2.""" return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5
75,628
def set_image_spec(spec): """ Writes new specification for images manipulated or created when needed :param spec: :return: """ output_spec = ImageSpec() output_spec.set_format(OpenImageIO.UINT8) output_spec.width = spec['resolution'][0] output_spec.height = spec['resolution'][0] ...
75,629
def test_assert_dict_subset_not_equal(): """Test that assert_dict_subset correctly identifies when expected is not a subset of actual.""" actual = { "key": "value", "key2": "value2", "parent_key": { "nested_key": "nested_value", "nested_key2": "nested_value2", ...
75,630
def from_numpy(m): """ If m.ndim == 1, returns a Vector if m.ndim == 2, returns a Matrix if m.ndim > 2, raises an error dtype is inferred from m.dtype """ if m.ndim > 2: raise GraphblasException("m.ndim must be <= 2") try: from scipy.sparse import coo_array, csr_array ...
75,631
def percentile_normalize_torch(img: torch.Tensor) -> torch.Tensor: """ 1-99 percentile normalization per image channel. Numpy version Args: ----------- img (torch.Tensor): Input image to be normalized. Shape (C, H, W) Returns: ----------- torch.Tensor. Normaliz...
75,632
def Session(access_token=None, env=os.environ): """Returns an HTTP session. :param access_token: Mapbox access token string (optional). :param env: a dict. """ access_token = ( access_token or env.get('MapboxAccessToken') or env.get('MAPBOX_ACCESS_TOKEN')) session = requ...
75,633
def make_layer(basic_block, num_basic_block, **kwarg): """Make layers by stacking the same blocks. Args: basic_block (nn.module): nn.module class for basic block. num_basic_block (int): number of blocks. Returns: nn.Sequential: Stacked blocks in nn.Sequential. """ lay...
75,634
def _cli_start(debug, quiet): """ Initial setup for CLI commands. Returns ``start_time`` (datetime timestamp) """ if debug: click.secho(_get_version()) if debug: verbosity = "debug" log_solver = True else: if quiet: verbosity = "warning" ...
75,635
def get_unique_candidate_list(csv_data): """ Returns the unique list of candidates in a dictionary, where key is the candidate name and value is the number of votes. The votes will all be 0 to begin. :param csv_data: :return: """ candidate_dict = {} for row in csv_data: candidate...
75,636
def _to_slugs(d): """Return structured slugs spec. """ f = _slugs_str return ( _format_slugs_vars(d['env_vars'], 'INPUT') + _format_slugs_vars(d['sys_vars'], 'OUTPUT') + f(d['env_safety'], 'ENV_TRANS') + f(d['env_prog'], 'ENV_LIVENESS') + f(d['env_init'], 'ENV_IN...
75,637
def has_extension_md(filename): """Check whether a filename has a valid Markdown extension. :Example: >>> has_extension_md('filename.md') True >>> has_extension_md('filename.mDown') True >>> has_extension_md('filename.rst') False """ return has_extensions(filename, ['.md', '...
75,638
def test_docs(): """Test that the documentation examples work as expected""" grader = FormulaGrader( answers='1+x^2+y', variables=['x', 'y'] ) assert grader(None, '1+x^2+y')['ok'] grader = FormulaGrader( answers='1+x^2+y+z/2', variables=['x', 'y', 'z'], sampl...
75,639
def generate_1609_spdu(bsm: bytes, private_key: int) -> bytes: """Create a bytes object representing an IEEE 1609.2 SPDU :param bsm: a bytes object containing the BSM data for this message :type bsm: bytes :param private_key: an ECDSA private key to use for signing the SPDU :type private_key: int ...
75,640
def client(requests_mock, capfd): """Client fixture.""" from RubrikPolaris import MyClient data = { "access_token": "dummy_token", "mfa_token": "dummy_token" } requests_mock.post(BASE_URL_SESSION, json=data) capfd.close() client_obj = MyClient( domain="rubrik-se-beta"...
75,641
def main(input_file): """Solve puzzle and connect part 1 with part 2 if needed.""" # part 1 inp = read_input(input_file) p1 = part_1_and_2(inp, 3) print(f"Solution to part 1: {p1}") # part 2 inp = read_input(input_file) p2 = part_1_and_2(inp, 4) print(f"Solution to part 2: {p2}") ...
75,642
def pooling_overlap(mat, ksize, stride=None, method='max', pad=False): """Overlaping pooling""" m, n = mat.shape[:2] ky, kx = ksize if stride is None: stride = (ky, kx) sx, sy = stride _ceil = lambda x, y : int(np.ceil(x/float(y))) if pad: ny = _ceil(m, sy) ...
75,643
def img_query(iurl): """ Download an image file from a URL. Returns the bytes object with the raw image data if successful and None if image couldn't be downloaded. This function does NOT perform retries. It only performs one attempt, without any delays. Use isbndb_query() for the full querying protocol...
75,644
def ver_fecha_hora(): """:return Cadena de hora y fecha local (-6)""" formato = "%B %d, %Y %H:%M:%S" zona_horaria = datetime.timezone(datetime.timedelta(hours=-6)) fecha_actual = datetime.datetime.now(zona_horaria) fecha_formateada = fecha_actual.strftime(formato) print("La fecha y la hora ex...
75,645
def login(): """ Login User ---------- first if user is already logged in, we redirect them to main page after extract email and password from login form; we check if the email is in db or not, otherwise app flashes a message also we compare the given password with decoded hash that is in da...
75,646
def test_read_XML_04(): """Test XML file import: Includes duplicate reaction.""" rc = chemkin.ReactionRate() try: f = rc.read_XML('./data/rxns_test/rxns_test_04.xml') return f except NotImplementedError as err: assert(type(err) == NotImplementedError)
75,647
def vectorMagnitude(vector = None): """Calculates the length of the vector""" return math.sqrt(pow(vector[0],2) + pow(vector[1],2) + pow(vector[2], 2))
75,648
def create_input(job): """Create the lammps input file""" content = _generate_input(job) with open(job.fn("in.lammps"), "w") as f: f.write(content)
75,649
def find_vx_vy_new(m): """ Given three points (origin, v1, v2), finds out which of v1, v2 is vx and vy. Input: A 2x3 matrix (origin, v1, v2) Output: A 2x3 matrix (origin, vx, vy) """ # The standard coordinate system positive_x = np.array([1,0]) positive_y = np.array([0,1]) ...
75,650
def get_stops(): """Return stops suggestion by name.""" query = request.args.get("query", "") limit = request.args.get("limit", type=int, default=10) stops = Stops.get_stops_by_text(query, limit) if isinstance(stops, list) and len(stops) == 0: stops = Stops.get_stops_by_text_regex(query, li...
75,651
def task(func, **config): """Declare a function or method to be a Yaz task @yaz.task def talk(message: str = "Hello World!"): return message Or... group multiple tasks together class Tools(yaz.Plugin): @yaz.task def say(self, message: str = "Hello World!"): ret...
75,652
def Vabrms_calc(va,vb): """Inverter terminal voltage - line to line RMS""" return abs(va-vb)/math.sqrt(2)
75,653
def test_get_networkx_graph(): """test_get_networkx_graph.""" c1 = BaseComponent("c1") c2 = BaseComponent("c2") c3 = BaseComponent("c3") c2.parent_component_list = [c1] c2.child_component_list = [c3] product = BaseProduct([c3, c2, c1]) product.get_networkx_graph() # TODO # assert...
75,654
def get_common_movies(your_list: List) -> Union[str, List]: """ Checks if two characters were detected on the SWAPI database; if the result is positive, then it returns the common movies where both characters appeared. """ if len(your_list) in [0, 1]: result_nochar = "| RESULT | -> One...
75,655
def set_precision(precision): """Set the precision used by geometric maps. Parameters ---------- precision : float The precision as a floating point number. For example, ``0.0001``. Notes ----- This function converts the floating point number to a string formatting spec...
75,656
def get_settings_md5(settings): """Produces an md5 hash of the settings dict""" flat_settings = flatten_settings(settings) settings_str = json.dumps(flat_settings, allow_nan=False, sort_keys=True) h = hashlib.md5() h.update(settings_str.encode()) return h.hexdigest()
75,657
def parallel_gibbs_server(models=None, start_tick=None, end_tick=None, start_voice_index=None, end_voice_index=None, chorale_metas=None, num_iterations=1000, timesteps=16, ...
75,658
def get_value(text, regex, value_type=float): """Dump a value from a file based on a regex passed in.""" pattern = re.compile(regex, re.MULTILINE) results = pattern.search(text) if results: return value_type(results.group(1)) else: print("Could not find the value {}, in the text prov...
75,659
def concat(*arrays): """ Concatenate a sequence of (up to 2D) array-like objects along a given axis. """ array_list = [] for ia, array in enumerate(arrays): arrdim = np.ndim(array) if arrdim == 1: array = np.asarray(array)[None,...] array_list.append(array) re...
75,660
def ca_migration_continue_session_negotiation( target_session, input_step, input_data, input_session_ouid=None ): """ Runs CA_MigrationContinueSessionNegotiation :param int target_session: Session handle :param int input_step: TBD :param bytes input_data: TBD :param bytes session_ouid: Sess...
75,661
def numberofdupes(string, idx): """return the number of times in a row the letter at index idx is duplicated""" # "abccdefgh", 2 returns 1 initial_idx = idx last = string[idx] while idx+1 < len(string) and string[idx+1] == last: idx += 1 return idx-initial_idx
75,662
def contribute() -> None: """ Contribute to DICE """ rich.print("[blue]Contribute[/]:") rich.print("[blue] DICE CLI[/]: [red]https://github.com/uobdic/dice-cli[/]") rich.print("[blue] DICE LIB[/]: [red]https://github.com/uobdic/dice-lib[/]") rich.print("[blue] DICE WIKI[/]: [red]https://w...
75,663
def test_searcher_get_control_genes(): """Try to get the list of control genes. Check a known control gene.""" searcher = search.Searcher() controls = searcher.get_control_genes(0.6) # check AP3S2 in control genes assert "ENSG00000157823" in controls
75,664
def _test_partition_states( scheduler_commands, cluster_name, region, active_partition, inactive_partition, num_static_nodes, num_dynamic_nodes, dynamic_instance_type, ): """Partition states INACTIVE and UP are processed.""" logging.info("Testing that INACTIVE partiton are cleane...
75,665
def f_monitor_saves(save_path=None, stop_event: threading.Event = None): """ Monitor the save path for new files, and maintain the corresponding plot data. :param save_path: Override for the path defined in the config.CONFIG object. :param stop_event: Signals that the program is shutting down. :ret...
75,666
def loadOneDotPinchvalues(od, outputdir, verbose=1): """ Load the pinch-off values for a one-dot Arguments --------- od : dict one-dot structure outputdir : string location of the data """ print('analyse data for 1-dot: %s' % od['name']) gg = od['gates']...
75,667
def check_timestamp(value): """ Checks that the value is a valid HL7 timestamp :param value: the value to check :return: `True` if the value is correct, `False` otherwise """ try: get_timestamp_info(value) except ValueError: return False return True
75,668
def ensure_cls(cls, *containers, key_converter=None): """If the attribute is an instance of cls, pass, else try constructing.""" def converter(val): val = val if isinstance(val, cls) else cls(**val) return val def converter_list(converter, val): return [converter(item) for item in v...
75,669
def make_plot( df, x_variable, y_variable, x_label, y_label, output_prefix, plot_kind, palette, file_names, output_folder_name, variable1_name, variable2_name, dependent_variable, mean=False, ): """function to make and save plot""" # allow colour codes in ...
75,670
def parameter_parser(): """ A method to parse up command line parameters. By default it trains on the Cora dataset. The default hyperparameters give a good quality representation without grid search. """ parser = argparse.ArgumentParser(description = "Run MixHop/N-GCN.") parser.add_argument("-...
75,671
def perform_line_profile_calculation(Rmin=Rmin_default, Rmax=Rmax_default, lam_min=lam_min_default, lam_max=lam_max_default, lam_line=lam_line_default, tau_sobolev=tau_sobo...
75,672
def loadCompareDirs(directories, runparamname='runparams.json'): """ Loads final results and run parameters of two comparison directories """ runPars = loadRunPars(directories, runparamname) paramnames = [p.get('paramname', None) for p in runPars] fs = loadResults(directories, paramnames...
75,673
def mock_is_virtual_env(): """Mock enable logging.""" with patch( "homeassistant.bootstrap.is_virtual_env", return_value=False ) as is_virtual_env: yield is_virtual_env
75,674
def peuple_regions(): """ Peupler les regions et les departements pour l'IDF :return: """ for semaine in range(10, 22): region_semaine = ClesRegion(semaine_de_vaccination=semaine, numero_region=6) region_semaine.save() # Bon c'est un hack for dept in [76, 78, 79, 92, ...
75,675
def sort(_list, base=10): """ Radix Sort :param _list: array to sort :param base: base radix number :return: sorted list """ # TODO: comment this result_list = [] power = 0 while _list: bs = [[] for _ in range(base)] for x in _list: bs[x // base ...
75,676
def get_info(mid): """ 获取粉丝数量 :param mid: 用户ID :return: 返回关注数量和粉丝数量 """ headers = { 'Connection': 'keep-alive', 'Cookie': COOKIE, 'Host': 'api.bilibili.com', 'Referer': 'https://space.bilibili.com/' + str(mid), 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; W...
75,677
def _advapi32_encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext via CryptoAPI :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: ...
75,678
def process(request): """processes the input url and sends the date to web page for rendering """ try: url = request.POST['url'].strip() title, data = process_utility.get_data(url) return render(request,constants.FEEDS_TEMPLATE, {"title":title,"data":data}) except Exception...
75,679
def print_brokers(cluster_config, brokers): """Print the list of brokers that will be restarted. :param cluster_config: the cluster configuration :type cluster_config: map :param brokers: the brokers that will be restarted :type brokers: map of broker ids and host names """ print("Will rest...
75,680
async def test_make_async_request(mocker, mailchimp_list): """Tests the make_async_request function.""" client_session_mock = CoroutineMock() client_session_mock.get.return_value.__aenter__.return_value.status = 200 client_session_mock.get.return_value.__aenter__.return_value.text = ( CoroutineM...
75,681
def rotscan(proj, N_steps, slice_mode = False): """ The function combines rotaxis_rough() and rotaxis_precise() It does three iterations to find the best match for the rotation axis It also finds the inclination of the rotation axis Parameters __________ projections: 3D array 0 d...
75,682
def init_synsets(scene_graph, synset_file): """ Convert synsets in a scene graph from strings to Synset objects. """ syn_data = json.load(open(synset_file, 'r')) syn_class = {s['synset_name']: Synset( s['synset_name'], s['synset_definition']) for s in syn_data} for obj in scene_graph.ob...
75,683
def bundle_config(tmp_path): """Provide a config class with an extra set method for the test to change it.""" class TestConfig(config_module.Config, frozen=False): """The Config, but with a method to set test values.""" def set(self, prime=None, **kwargs): # prime is special, so we...
75,684
def write_matches(matches: List[compare.Match], output_file: str): """Collapse the matches into a single table.""" with open(output_file, 'w') as out: csv_writer = csv.writer(out, lineterminator='\n') header_1 = list(matches[0]['record_1'].keys()) header_2 = list(matches[0]['record_2'].k...
75,685
def apex_settings(key=None, default=None): """ Gets an apex setting if the key is set. If no key it set, returns all the apex settings. Some settings have issue with a Nonetype value error, you can set the default to fix this issue. """ settings = get_current_registry().settings ...
75,686
def linear_curve(t, a, b): """ fit data to linear model """ return a*t + b
75,687
def impute(df, col, strategy = 'value', val = 0): """ Impute missing values (NaN) based on the following strategy: - Fill all missing value with a designate value: val - Fill all missing value with "mean" - Fill all missing value with "median" - Fill all missing ...
75,688
def _get_channel_setting() -> dict: """Default config format for each channel :return dict channel_setting : Default config format for each channel """ channel_setting = { "block_versions": { "0.1a": 0 }, "hash_versions": { "genesis": 1, "0x2"...
75,689
def test_type_ascii_over_max(): """ ASCII message type is required and over max is provided """ spec["h"]["data_enc"] = "ascii" spec["h"]["len_type"] = 0 spec["h"]["max_len"] = 6 spec["t"]["data_enc"] = "ascii" spec["p"]["data_enc"] = "b" doc_dec = {"h": "header", "t": "02101"} ...
75,690
def main(argv=None): """The entry point of the application.""" if argv is None: argv = sys.argv[1:] usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:]) version = 'Nosey ' + __version__ # Parse options args = docopt(usage, argv=argv, version=version) # Execute return watch(args['...
75,691
def serialize(iterable, encoding=None): """Serializes an iterable of key value pairs into a stream of string chunks. If an encoding is provided, it will be encoded into that. This is primarily used by the editor to write back data to a source file. """ def _produce(item, escape=False): if ...
75,692
def test_list_iterator_behaviour(client, response): """Verify the behaviour of the List object in iterator circumstances.""" response.get("https://api.mollie.com/v2/methods", "methods_list") methods = client.methods.list() assert isinstance(methods, List) # walk the list using next() iterated ...
75,693
def do_load_variables( site_db: BaseDatabase, user_configuration: RAMSTKUserConfiguration ) -> None: """Load the RAMSTKUserConfiguration global variables from the site db. :param site_db: the RAMSTK Site Database to read the values of the global variables. :param user_configuration: the RAMSTKU...
75,694
def test_pre_rescaling_integration(is_invertible, model): """Test the pre-scaling feature""" def forward(x): return np.log(x), -np.log(x) def inv(x): return np.exp(x), x.copy() reparam = RescaleToBounds( parameters='x', prior_bounds={'x': [1.0, np.e]}, pre_resc...
75,695
def test_delete_eks_with_no_releases(aws, helm, users): """ If there are no releases associated with the user, don't try to delete with an empty list of releases. Helm 3 version. """ user = users['normal_user'] helm.list_releases.return_value = [] with patch("controlpanel.api.aws.settings.EK...
75,696
def DLSI_updateD(D, E, F, A, lambda1, iterations=100): """ def DLSI_updateD(D, E, F, A, lambda1, verbose = False, iterations = 100): problem: `D = argmin_D -2trace(ED') + trace(FD'*D) + lambda *||A*D||F^2,` subject to: `||d_i||_2^2 <= 1` where F is a positive semidefinite matrix ========= aproac...
75,697
def test_importing_api(): """Test importing the definitions found in the api.py file. """ from exopy.app.dependencies import api assert api.__all__
75,698
def dispatch_requests( requests: Union[Request, Iterable[Request]], methods: Methods, *, extra: Optional[Any] = None, serialize: Callable = default_serialize, ) -> Response: """ Impure (public) version of dispatch_requests_pure - has default values. """ return dispatch_requests_pure(...
75,699