content
stringlengths
22
815k
id
int64
0
4.91M
def aggregate_metrics_by_nodesets(df, nodelists, nodeset_names=None, weightlists=None, level_name="node", use_metrics=None, print_looptime=True): """Aggregates a dataframe by nodes (into nodesets), returning a data frame with same structure but with nodesets instead of nodes. ...
32,900
def zero_pad(data, window_size): """ Pads with window_size / 2 zeros the given input. Args: data (numpy.ndarray): data to be padded. window_size (int): parameter that controls the size of padding. Returns: numpy.ndarray: padded data. """ pad_width = ceil(window_size / 2) padded = np.pad(data...
32,901
def test_recorder_setup_failure(): """Test some exceptions.""" hass = get_test_home_assistant() with patch.object(Recorder, "_setup_connection") as setup, patch( "homeassistant.components.recorder.time.sleep" ): setup.side_effect = ImportError("driver not found") rec = Recorder(...
32,902
def get_results(url_id): """Get the scanned results of a URL""" r = requests.get('https://webcookies.org/api2/urls/%s' % url_id, headers=headers) return r.json()
32,903
def assert_equal( actual: Tuple[numpy.ndarray, numpy.ndarray], desired: List[Union[float, int]] ): """ usage.scipy: 1 """ ...
32,904
def build_dense_constraint(base_name, v_vars, u_exprs, pos, ap_x): """Alias for :func:`same_act`""" return same_act (base_name, v_vars, u_exprs, pos, ap_x)
32,905
def list_snapshots(client, data_args) -> Tuple[str, dict, Union[list, dict]]: """ List all snapshots at the system. :type client: ``Client`` :param client: client which connects to api. :type data_args: ``dict`` :param data_args: request arguments. :return: human readable f...
32,906
def data_context_path_computation_context_pathuuid_linktopology_uuidlink_uuid_get(uuid, topology_uuid, link_uuid): # noqa: E501 """data_context_path_computation_context_pathuuid_linktopology_uuidlink_uuid_get returns tapi.topology.LinkRef # noqa: E501 :param uuid: Id of path :type uuid: str :para...
32,907
def ipfs_qm_hash_to_32_bytes(ipfs_qm: str) -> str: """ Transform IPFS base58 Qm... hash to a 32 bytes sting (without 2 heading '0x' bytes). :param ipfs_qm: IPFS base58 Qm... hash. :return: 32 bytes sting (without 2 heading bytes). """ return f"0x{b58decode(ipfs_qm).hex()[4:]}"
32,908
def get_service_state(scheduler): """Return the current state of the job service.""" return {"state": get_service_state_str(scheduler)}, 200
32,909
def test_create_branch_with_bad_start_ref(mock_repo): """ GIVEN GitRepo is initialized with a path and repo WHEN branch.create is called with a valid name and invalid start_ref THEN a ReferenceNotFoundException is raised """ repo = GitRepo(repo=mock_repo) with patch('git.repo.fun.name_to_ob...
32,910
def tst_insert_read_left1(dut): """ expected output : 5 6 7 8 9 895 test when only one element left 10 clock cycles wait before getting last element. """ cocotb.fork(Clock(dut.clk, 6.4, 'ns').start()) tb = axistream_fifo_TB(dut) yield tb.async_rst() tb.insertContinuousBatch(5, 5) tb....
32,911
def determine_file_type(filename): """ :param filename: str :rtype: FileType """ if filename.endswith('.cls'): return FileType.CLS elif filename.endswith('.java'): return FileType.JAVA elif filename.endswith('.js'): return FileType.JAVASCRIPT elif filename.endswi...
32,912
def sanitise_text(text): """When we process text before saving or executing, we sanitise it by changing all CR/LF pairs into LF, and then nuking all remaining CRs. This consistency also ensures that the files we save have the correct line-endings depending on the operating system we are running on. ...
32,913
def create_regression( n_samples=settings["make_regression"]["n_samples"] ) -> pd.DataFrame: """Creates a fake regression dataset with 20 features Parameters ---------- n_samples : int number of samples to generate Returns ------- pd.DataFrame of features and targets: f...
32,914
def _divide_no_nan(x, y, epsilon=1e-8): """Equivalent to tf.math.divide_no_nan but supports bfloat16.""" # need manual broadcast... safe_y = tf.where( tf.logical_and(tf.greater_equal(y, -epsilon), tf.less_equal(y, epsilon)), tf.ones_like(y), y) return tf.where( tf.logical_and( tf.gre...
32,915
def write_json_file(compositions, filename:str, path:str=None): """ Write one or more `Compositions <Composition>` and associated objects to file in the `general JSON format <JSON_Model_Specification>` .. _JSON_Write_Multiple_Compositions_Note: .. note:: At present, if m...
32,916
def make_release(t, **params_or_funcs): """Create particle release table to be used for testing""" t = np.array(t) i = np.arange(len(t)) params = { k: (p(i, t) if callable(p) else p) + np.zeros_like(t) for k, p in params_or_funcs.items() } start_date = np.datetime64("2000-01-0...
32,917
def upgrade_v21_to_v22(db: 'DBHandler') -> None: """Upgrades the DB from v21 to v22 Changes the ETH2 deposit table to properly name the deposit index column and deletes all old data so they can be populated again. """ cursor = db.conn.cursor() # delete old table and create new one cursor.ex...
32,918
def get_apartment_divs(driver): """Scrapes the url the driver is pointing at and extract any divs with "listitems". Those divs are used as apartment objects at Immowelt. Args: driver (Webdriver): A Webdriver instance. Returns: list: returns a list of all divs of class listitem... ...
32,919
def smart_apply(tensor, static_fn, dynamic_fn): """ Apply transformation on `tensor`, with either `static_fn` for static tensors (e.g., Numpy arrays, numbers) or `dynamic_fn` for dynamic tensors. Args: tensor: The tensor to be transformed. static_fn: Static transformation function. ...
32,920
def new_scan(host, publish = "off", start_new = "on", all = "done", ignoreMismatch = "on"): """This function requests SSL Labs to run new scan for the target domain.""" if helpers.is_ip(host): print(red("[!] Your target host must be a domain, not an IP address! \ SSL Labs will onyl scan domains.")) ...
32,921
def removeBubbles(I, kernelSize = (11,11)): """remove bright spots (mostly bubbles) in retardance images. Need to add a size filter Parameters ---------- I kernelSize Returns ------- """ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, kernelSize) Bg = cv2.morphologyEx(I...
32,922
def test_categories_type_in_kwargs(df_categorical): """ Raise TypeError if the wrong argument is supplied to the `categories` parameter in kwargs. """ with pytest.raises(TypeError): df_categorical.encode_categorical(col1=({1: 2, 3: 3}, None))
32,923
def setchances(): """ Sets the number of ``chances`` the player gets per question. """ global chances chances = input("How many chances would you like per question: ") while not chances.isdigit() or int(chances) < 1: chances = input("Please enter a number that is greater than 0: ") chance...
32,924
def assert_json_response(response, status_code, body, headers=None, body_cmp=operator.eq): """Assert JSON response has the expected status_code, body, and headers. Asserts that the response's content-type is application/json. body_cmp is a callable that takes the JSON-decoded response body and expecte...
32,925
def test_frame_attribute_descriptor(): """ Unit tests of the Attribute descriptor """ from astropy.coordinates.attributes import Attribute class TestAttributes(metaclass=OrderedDescriptorContainer): attr_none = Attribute() attr_2 = Attribute(default=2) attr_3_attr2 = Attribute(defau...
32,926
def variable(value, dtype=None, name=None, constraint=None): """Instantiates a variable and returns it. # Arguments value: Numpy array, initial value of the tensor. dtype: Tensor type. name: Optional name string for the tensor. constraint: Optional projection function to be ...
32,927
def autoprotocol_protocol(protocol_id): """Get autoprotocol-python representation of a protocol.""" current_protocol = Protocol.query.filter_by(id=protocol_id).first() if not current_protocol: flash('No such specification!', 'danger') return redirect('.') if current_protocol.public: ...
32,928
def test_block_quotes_213b(): """ Test case 213b: variation of 213 with an extra list line and all three lines in the block quote """ # Arrange source_markdown = """> - foo > - bar > - bar""" expected_tokens = [ "[block-quote(1,1)::> \n> \n> ]", "[ulist(1,3):-::4: ]", ...
32,929
def tensor_to_P(tensor, wig3j = None): """ Transform an arbitray SO(3) tensor into real P which transforms under the irreducible representation with l = 1. Wigner-3j symbols can be provided or calculated on the fly for faster evaluation. If providedn, wig3j should be an array with indexing [l1,l2,m,...
32,930
def _print_projects(): """ Print the list of projects (uses the folder names) """ project_dir = projects_path() print(' '.join( ['aeriscloud'] + [ pro for pro in os.listdir(project_dir) if os.path.exists(os.path.join(project_dir, pro, ...
32,931
def createNotificationMail(request, *args, **kwargs): """Appengine task that sends mail to the subscribed users. Expects the following to be present in the POST dict: comment_key: Specifies the comment id for which to send the notifications task_key: Specifies the task key name for which the comment belong...
32,932
def mergediscnodes(tree): """Reverse transformation of ``splitdiscnodes()``.""" treeclass = tree.__class__ for node in tree.subtrees(): merge = defaultdict(list) # a series of queues of nodes # e.g. merge['VP_2*'] = [Tree('VP_2', []), ...] # when origin is present (index after *), the node is moved to where ...
32,933
def main(): # type: () -> typing.Any """Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message. """ colorama.init(strip=not sys.stdout.isatty()) doc ...
32,934
def count_go_nogo_trials(eventcode): """ :param eventcode: list of event codes from operant conditioning file :return: number of go and no go trials in the go/no go tasks """ lever_on = get_events_indices(eventcode, ['RLeverOn', 'LLeverOn']) (go_trials, nogo_trials) = (0, 0) for lever in le...
32,935
def getScriptExecutionContext(): """ Returns the repository description instance and the set of items selected on script action execution. @return: Script execution context. @rtype: L{ScriptExecutionContext<datafinder.gui.user.script_api.ScriptExecutionContext>} """ script...
32,936
def electrondensity_spin(ccdata, volume, mocoeffslist): """Calculate the magnitude of the electron density at every point in a volume for either up or down spin Inputs: ccdata -- ccData object volume -- Volume object (will not be altered) mocoeffslist -- list of molecular orbital ...
32,937
def create_missing_dataframe(nrows, ncols, density=.9, random_state=None, index_type=None, freq=None): """Create a Pandas dataframe with random missingness. Parameters ---------- nrows : int Number of rows ncols : int Number of columns density: float Amount of availa...
32,938
def __check_waiting_time(waiting_time): """ 校验窗口配置项:等待时间 :param waiting_time: 等待时间 """ # 校验等待时间(单位:s) if waiting_time not in [0, 10, 30, 60, 180, 300, 600]: raise StreamWindowConfigCheckError(_("属性[%s] 目前只支持 %s") % ("waiting_time", "[0, 10, 30, 60, 180, 300, 600]"))
32,939
def lint(session): """Run flake8. Returns a failure if flake8 finds linting errors or sufficiently serious code quality issues. """ session.install('yapf') session.run('python3', '-m', 'yapf', '--diff', '-r', '.')
32,940
def console(endpoint, admin_secret): """ Opens the Hasura console Note: requires installing the Hasura CLI. See https://docs.hasura.io/graphql/manual/hasura-cli/install-hasura-cli.html """ try: cmd = shlex.split( f"hasura console --endpoint {endpoint} --admin-secret {admin_secr...
32,941
def decode_name_value_pairs(buffer): """ Decode a name-value pair list from a buffer. :param bytearray buffer: a buffer containing a FastCGI name-value pair list :raise ProtocolError: if the buffer contains incomplete data :return: a list of (name, value) tuples where both elements are unicode stri...
32,942
def host_is_local(host: str) -> bool: """ Tells whether given host is local. :param host: host name or address :return: True if host is local otherwise False """ local_names = { "localhost", "127.0.0.1", } is_local = any(local_name in host for local_name in local_names...
32,943
def find_in_path(name, path): """Search PATH for a binary. Args: name: the filename to search for path: the path ['./', './path/to/stuff'] Returns: The abspath to the fie or None if not found. """ for dir in path: binpath = os.path.join(dir, name) if os.path.exi...
32,944
def sigma_function(coeff_matU, coeff_matX, order, V_slack): """ :param coeff_matU: array with voltage coefficients :param coeff_matX: array with inverse conjugated voltage coefficients :param order: should be prof - 1 :param V_slack: slack bus voltage vector. Must contain only 1 slack bus :retu...
32,945
def get_logger(verbose=0): """ set up logging according to the verbose level given on the command line """ global LOGGER if LOGGER is None: LOGGER = logging.getLogger(sys.argv[0]) stderr = logging.StreamHandler() level = logging.WARNING lformat = "%(message)s" if ...
32,946
def get_dbs(db_names: List[str], db_file: str = "./db_info.pub.json") -> List: """Read the db_file and get the databases corresponding to <<db_name>> Args: db_name (List[str]): A list of names of the database we want db_file (str): The db_file we are reading from Returns: Mongogran...
32,947
def knn_threshold(data, column, threshold=15, k=3): """ Cluster rare samples in data[column] with frequency less than threshold with one of k-nearest clusters Args: data - pandas.DataFrame containing colums: latitude, longitude, column column - the name of the column to threshold ...
32,948
def _render_helper(scene, spp=None, sensor_index=0): """ Internally used function: render the specified Mitsuba scene and return a floating point array containing RGB values and AOVs, if applicable """ from mitsuba.core import (Float, UInt32, UInt64, Vector2f, is_monoch...
32,949
def format_formula(formula): """Converts str of chemical formula into latex format for labelling purposes Parameters ---------- formula: str Chemical formula """ formatted_formula = "" number_format = "" for i, s in enumerate(formula): if s.isdigit(): if ...
32,950
def test_get_run_no_actions(subject: RunStore) -> None: """It can get a previously stored run entry.""" run = RunResource( run_id="run-id", protocol_id=None, created_at=datetime(year=2021, month=1, day=1, tzinfo=timezone.utc), actions=[], is_current=False, ) subje...
32,951
def ParseQuery(query): """Parses the entire query. Arguments: query: The command the user sent that needs to be parsed. Returns: Dictionary mapping clause names to their arguments. Raises: bigquery_client.BigqueryInvalidQueryError: When invalid query is given. """ clause_arguments = { '...
32,952
def _bundle_assets(assets_directory, zip_file): """Bundle the assets directory :param assets_directory: path to the assets directory :type assets_directory: str :param zip_file: zip file object :type zip_file: zipfile.ZipFile :rtype: None """ for filename in sorted(os.listdir(assets_di...
32,953
def check_special_status(char, combat_handler, winner = None): """ Checks whether the combatant was trying to rescue, flee, or shift targets at the time, and processes that accordingly with the round. """ RESCUE_COST = 2 FLEE_COST = 3 SHIFT_COST = 2 scripts = char.scripts.all() dbre...
32,954
def primary_astigmatism_00(rho, phi): """Zernike primary astigmatism 0°.""" return rho**2 * e.cos(2 * phi)
32,955
def lpt_prototype(mesh, nc=FLAGS.nc, bs=FLAGS.box_size, batch_size=FLAGS.batch_size, a0=FLAGS.a0, a=FLAGS.af, nsteps=FLAGS.nsteps): """ Prototype of function computing LPT deplacement. Returns output t...
32,956
def in_collision(box1: OrientedBox, box2: OrientedBox) -> bool: """ Check for collision between two boxes. First do a quick check by approximating each box with a circle, if there is an overlap, check for the exact intersection using geometry Polygon :param box1: Oriented box (e.g., of ego) :param b...
32,957
def process_embedded_query_expr(input_string): """ This function scans through the given script and identify any path/metadata expressions. For each expression found, an unique python variable name will be generated. The expression is then substituted by the variable name. :param str input_string: ...
32,958
def format_elemwise(vars_): """Formats all the elementwise cones for the solver. Parameters ---------- vars_ : list A list of the LinOp expressions in the elementwise cones. Returns ------- list A list of LinLeqConstr that represent all the elementwise cones. """ # ...
32,959
def extract_stars(image, noise_threshold): """ Extract all star from the given image Returns a list of rectangular images """ roi_list = [] image_list = [] # Threshold to remove background noise image = image.copy() image[image < noise_threshold] = 0.0 # Create binary image by...
32,960
def lovasz_hinge(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) """ if len(labels) == 0: # only void pixels, the gradients should be 0 retu...
32,961
def extract_metadata(url: str, body: BeautifulSoup) -> Website: """ Extract metadata from a site and put it into a `Website object`. """ try: name = body.title.get_text().strip() except AttributeError: name = url try: description = ( body.find(attrs={"name": ...
32,962
def markContinuing(key, idea, oldest_idea_id, oldest_idea_detect_time, accum): """ Mark IDEA as continuing event. :return: marked key, IDEA """ # If idea is present if idea: # Equality of ID's in tuple and idea, if true mark will be added if oldest_idea_id != idea.id: ...
32,963
def box1_in_box2(corners1:torch.Tensor, corners2:torch.Tensor): """check if corners of box1 lie in box2 Convention: if a corner is exactly on the edge of the other box, it's also a valid point Args: corners1 (torch.Tensor): (B, N, 4, 2) corners2 (torch.Tensor): (B, N, 4, 2) Returns: ...
32,964
def in_line_rate(line, container_line): """一个线段和另一个线段的重合部分,占该线段总长的占比""" inter = intersection_line(line, container_line) return inter / (line[1] - line[0])
32,965
def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1)
32,966
def test_arbitrary_loader_module_not_found(): """Raise when loader not found.""" with pytest.raises(PyModuleNotFoundError): pipeline_cache.clear() pypyr.moduleloader.set_working_directory('arb/dir') pypyr.pipelinerunner.load_and_run_pipeline( pipeline_name='arb pipe', ...
32,967
def test_cli_requires(): """Test to ensure your can add requirements to a CLI""" def requires_fail(**kwargs): return {'requirements': 'not met'} @hug.cli(output=str, requires=requires_fail) def cli_command(name: str, value: int): return (name, value) assert cli_command('Testing', 1...
32,968
def tab_printer(args): """ Function to print the logs in a nice tabular format. :param args: Parameters used for the model. """ args = vars(args) t = Texttable() t.add_rows([["Parameter", "Value"]] + [[k.replace("_"," ").capitalize(),v] for k,v in args.iteritems()]) print t.draw()
32,969
def comm_for_pid(pid): """Retrieve the process name for a given process id.""" try: return slurp('/proc/%d/comm' % pid) except IOError: return None
32,970
def get_machine_type_from_run_num(run_num): """these are the values to be used in config for machine dependent settings""" id_to_machine = { 'MS001': 'miseq', 'NS001': 'nextseq', 'HS001': 'hiseq 2500 rapid', 'HS002': 'hiseq 2500', 'HS003': 'hiseq 2500', 'HS004': '...
32,971
def crawler(address_list): """ A list of addresses is provided to this method and it goes and downloads those articles. E.g an Element of the given list can be this: https://www.jyi.org/2019-march/2019/3/1/the-implication-of-the-corticotropin-releasing-factor-in-nicotine-dependence-and-significance-for-p...
32,972
def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provid...
32,973
def twisted_sleep(time): """ Return a deferred that will be triggered after the specified amount of time passes """ return task.deferLater(reactor, time, lambda: None)
32,974
def setup(): """ extension: setup the archive/experiment directory. input: None output: None notes: creates an empty directory for storing data """ global finished_setup global archive_path if finished_setup is True: logger.warn( 'archive setup called again. Ignoring' ) ...
32,975
async def async_load_cache( filename: str, ) -> dict[str, str | dict[str, dict[str, dict[str, dict[str, str]]]]]: """Load cache from file.""" async with aiofiles.open(filename, "rb") as file: pickled_foo = await file.read() return pickle.loads(pickled_foo)
32,976
def do_scrape(): """ Runs the craigslist scraper, and posts data to slack. """ # Create a slack client. sc = SlackClient(settings.SLACK_TOKEN) # Get all the results from craigslist. all_results = [] for area in settings.AREAS: print area all_results += scrape_area(area)...
32,977
def make_function(function, name, arity): """Make a function node, a representation of a mathematical relationship. This factory function creates a function node, one of the core nodes in any program. The resulting object is able to be called with NumPy vectorized arguments and return a resulting vecto...
32,978
def data_type_validator(type_name='data type'): """ Makes sure that the field refers to a valid data type, whether complex or primitive. Used with the :func:`field_validator` decorator for the ``type`` fields in :class:`PropertyDefinition`, :class:`AttributeDefinition`, :class:`ParameterDefinition`, ...
32,979
def list_challenge_topics(account_name, challenge_name): # noqa: E501 """List stargazers Lists the challenge topics. # noqa: E501 :param account_name: The name of the account that owns the challenge :type account_name: str :param challenge_name: The name of the challenge :type challenge_name:...
32,980
def ee_reg2(x_des, quat_des, sim, ee_index, kp=None, kv=None, ndof=12): """ same as ee_regulation, but now also accepting quat_des. """ kp = np.eye(len(sim.data.body_xpos[ee_index]))*10 if kp is None else kp kv = np.eye(len(sim.data.body_xpos[ee_index]))*1 if kv is None else kv jacp,jacr=jac(sim, ee_index, ndof)...
32,981
def test_tc1(): """ Test T of parity distributions """ for n in range(3, 7): d = n_mod_m(n, 2) yield assert_almost_equal, T(d), 1.0
32,982
def _default_clipping( inner_factory: factory.AggregationFactory) -> factory.AggregationFactory: """The default adaptive clipping wrapper.""" # Adapts relatively quickly to a moderately high norm. clipping_norm = quantile_estimation.PrivateQuantileEstimationProcess.no_noise( initial_estimate=1.0, targe...
32,983
def make_pred_multilabel(data_transforms, model, PATH_TO_IMAGES, epoch_loss, CHROMOSOME): """ Gives predictions for test fold and calculates AUCs using previously trained model Args: data_transforms: torchvision transforms to preprocess raw images; same as validation transforms model: dense...
32,984
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up a config entry for solarlog.""" hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True
32,985
def test_board_group_board_by_unknown() -> None: """Test that the boards property throws an exception with unknown indices.""" board_group = BoardGroup.get_board_group(MockBoard, OneBoardMockBackend) with pytest.raises(TypeError): board_group[0] # type: ignore with pytest.raises(KeyError): ...
32,986
def SqueezeNet_v1(include_top=True, input_tensor=None, input_shape=None, classes=10): """Instantiates the SqueezeNet architecture. """ input_shape = _obtain_input_shape(input_shape, default_size=32, ...
32,987
def sigterm_hndlr(args, sigterm_def, signum, frame): """Signal wrapper for the shutdown function.""" if args.verbose >= INFO: print() print(f'Signal {repr(signum)} caught.') shutdown(args) if sigterm_def != signal.SIG_DFL: sigterm_def(signum, frame) else: sys.exit(EXI...
32,988
def xcafdoc_ColorRefGUID(*args): """ * Return GUIDs for TreeNode representing specified types of colors :param type: :type type: XCAFDoc_ColorType :rtype: Standard_GUID """ return _XCAFDoc.xcafdoc_ColorRefGUID(*args)
32,989
def green_on_yellow(string, *funcs, **additional): """Text color - green on background color - yellow. (see _combine()).""" return _combine(string, code.GREEN, *funcs, attributes=(code.BG_YELLOW,))
32,990
def _register_models(format_str, cls, forward=True): """Registers reward models of type cls under key formatted by format_str.""" forwards = {"Forward": {"forward": forward}, "Backward": {"forward": not forward}} control = {"WithCtrl": {}, "NoCtrl": {"ctrl_coef": 0.0}} res = {} for k1, cfg1 in forw...
32,991
def configure_pseudolabeler(pseudolabel: bool, pseudolabeler_builder, pseudolabeler_builder_args): """Pass in a class that can build a pseudolabeler (implementing __call__) or a builder function that returns a pseudolabeling function. """ if pseudolabel: return globals()[pseudolabeler_builder](*...
32,992
def get_encoders(filename=None): """Get an ordered list of all encoders. If a `filename` is provided, encoders supporting that extension will be ordered first in the list. """ encoders = [] if filename: extension = os.path.splitext(filename)[1].lower() encoders += _encoder_extensions...
32,993
def _is_id_in_allowable_range( nodes_or_links: str, project_name: str, subject_id: int, range_in_use: dict, ): """ Checks if the new node or link id is in the allowable range defined in the config file Args: nodes_or_links (str): "node" or "link", which is used in error message ...
32,994
def test_compute_timeseries(): """ test the compute_timeseries function """ reduced_potentials = np.random.rand(100) data = compute_timeseries(reduced_potentials) assert len(data[3]) <= len(reduced_potentials), f"the length of uncorrelated data is at most the length of the raw data"
32,995
def flip_dict(dict, unique_items=False, force_list_values=False): """Swap keys and values in a dictionary Parameters ---------- dict: dictionary dictionary object to flip unique_items: bool whether to assume that all items in dict are unique, potential speedup but repeated items wil...
32,996
def randn(N, R, var = 1.0, dtype = tn.float64, device = None): """ A torchtt.TT tensor of shape N = [N1 x ... x Nd] and rank R is returned. The entries of the fuill tensor are alomst normal distributed with the variance var. Args: N (list[int]): the shape. R (list[int]): the rank. ...
32,997
def test_invalid_repository(invalid_repository, change_dir_main_fixtures): """Validate correct response if `cookiecutter.json` file not exist.""" assert not repository_has_tackle_file(invalid_repository)
32,998
def flatten_all_dimensions_but_first(a): """ Flattens all dimensions but the first of a multidimensional array. Parameters ---------- a : ndarray Array to be flattened. Returns ------- b : ndarray Result of flattening, two-dimensional. """ s = a.shape s_fla...
32,999