content
stringlengths
22
815k
id
int64
0
4.91M
def test_load_function(polar, query, qvar): """Make sure the load function works.""" # Loading the same file twice doesn't mess stuff up. filename = Path(__file__).parent / "test_file.polar" polar.load_file(filename) with pytest.raises(exceptions.PolarRuntimeError) as e: polar.load_file(file...
5,287,700
def endswith(stringarr, pat): """ Check whether each element ends with the substring 'pat', and returns a boolean array of the results. For now, 'pat' must be a string literal. """ define_pat = "let pat = {};".format(string_to_weld_literal(pat)) return """ {define_pat} let lenPat ...
5,287,701
def batchnorm_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]: """ This method counts the flops for batch norm. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before batch norm. outputs (li...
5,287,702
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Ukraine Alarm binary sensor entities based on a config entry.""" name = config_entry.data[CONF_NAME] coordinator = hass.data[DOMAIN][config_entry.entry_id] ...
5,287,703
def manifest_licenses(licensestr, dont_want_licenses, canonical_license, d): """Given a license string and dont_want_licenses list, return license string filtered and a list of licenses""" manifest = ManifestVisitor(dont_want_licenses, canonical_license, d) try: elements = manifest.get_eleme...
5,287,704
def app(): """Import the test app""" app = Flask(__name__) app.config["OPA_SECURED"] = True app.config["OPA_URL"] = 'http://localhost:8181/v1/data/examples/allow' app.opa = OPA(app, input_function=parse_input).secured() init_app(app) return app
5,287,705
def regress_array(input, regression): """ Works out coefficients for linear regression on the previous sample, for each axis of the array. @param [in] input The array to be compressed; must contain floats or doubles. @param [in] regression True if we are doing regression; if false, ...
5,287,706
def do_port_show(cc, args): """Show a port.""" try: port = cc.port.get(args.port) except exc.HTTPNotFound: raise exc.CommandError('Port not found: %s' % args.port) else: _print_port_show(port)
5,287,707
def requirements(): """Install all the software requirements that pip can't manage or that don't live in our virtualenv.""" sudo('apt-get install nginx git python3 python3-pip \ postgresql-server-dev-9.4 gettext') sudo('pip3 install virtualenv')
5,287,708
def test_matching_libvirt_domains_from_config_unexisting(build_mock_libvirtconn_filled): """ Test match_domains_from_config with a non existing domain """ conn = build_mock_libvirtconn_filled host_config = {"host": "nonexisting", "disks": ["vda", "vdb"]} matches = matching_libvirt_domains_from_...
5,287,709
def check(file_name_a, file_name_b): """ check if the two input files are considered equal, for the purpose of this specific homework :param file_name_a: output of one run :param file_name_b: output of another run :return: 0 if the files are equal (the content might be not identical) """ re...
5,287,710
def cubic_bezier_spline( p0: float, p1: float, p2: float, p3: float ): """ Create a sigle cubic bezier spline :param p0: starting point :param p1: control point 1 :param p2: control point 2 :param p3: end point :return: a cubic polynomial function that represe...
5,287,711
def parseRaw(data, node): """Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * EvenPageBreak * OddPageBreak * FrameBreak * Spacer width, height * Transition * SetPageCounter * TextAnnotation "text of annotation"...
5,287,712
def yolo_loss(args, anchors, num_classes, rescore_confidence=False, print_loss=False): """YOLO localization loss function. Parameters ---------- yolo_output : tensor Final convolutional layer features. true_boxes : tensor Grou...
5,287,713
def test_indexing_performance(m): """ Tests the performance of converting remote file changes to SyncEvents. """ # generate tree with 5 entries shutil.copytree(resources + "/test_folder", m.test_folder_local + "/test_folder") wait_for_idle(m) m.pause_sync() res = m.client.list_folder("...
5,287,714
def _cleanup_ec2(env): """Clean up any extra files after building. """ env.logger.info("Cleaning up for EC2 AMI creation") fnames = [".bash_history", "/var/log/firstboot.done", ".nx_setup_done", "/var/crash/*", "%s/ec2autorun.py.log" % env.install_dir] for fname in fnames: sudo...
5,287,715
def extract_authorization_token(request): """ Get the access token using Authorization Request Header Field method. Or try getting via GET. See: http://tools.ietf.org/html/rfc6750#section-2.1 Return a string. """ auth_header = request.META.get('HTTP_AUTHORIZATION', '') if re.compile(r'...
5,287,716
def resnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. """ model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], **kwargs) return _create_resnet('resnet101', pretrained, **model_args)
5,287,717
def filter_problematic(features, vcf_file="data/problematic_sites_sarsCov2.vcf", callback=None): """ Apply problematic sites annotation from de Maio et al., https://virological.org/t/issues-with-sars-cov-2-sequencing-data/473 which are published and maintained as a VCF-formatted file. :param featur...
5,287,718
def gen_model_header(env: jinja2.environment.Environment, model: onnx.ModelProto) -> str: """ Generates the header of the script for the given `model` :param env: Jinja environment to load the template files :param model: the onnx model for which the header shall be generated :return: the generated...
5,287,719
async def test_sending_mqtt_rgb_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of RGB command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", ...
5,287,720
def abmag(flux): """ takes flux as nanomaggies, gives AB mag """ # don't take the log of 0! if flux <= 0: return 0 return -2.5 * np.log10(flux) + 22.5
5,287,721
def add_map(new_prot, new_target, map_path, map_type): """Add a Django map obect :param new_prot: the Django protein object :param new_target: the Django target object :param map_path: the path to the map file :param map_type: the two letter code signifyign the type of the map :return: the add ...
5,287,722
def _make_requirements(foldername, virtual_env_obj): """ Function that build the 'requirements.txt' file used to create a virtual environment by the PIPENV, based on :virtual_env_obj: object. """ requirements_filename = os.path.join(foldername, 'requirements.txt') with open(requirements_...
5,287,723
def test_jsd_pmf1(): """ Test the JSD of a distribution with itself """ d1 = [0.5, 0.5] jsd = JSD_pmf([d1, d1]) assert jsd == pytest.approx(0)
5,287,724
def startup(): """Startup event to initialize the IO and LCD display""" # Initialize buzzer IO writePin(BUZZER, True) setPinDir(BUZZER, True) # Send the commands to initialize the display lcd_init() # Initialize timers to configure the real-time clock timer_init(TMR5, WGM_FAS...
5,287,725
def block2(x, filters, kernel_size=3, stride=1, conv_shortcut=False, name=None): """ residual 블록. Parameters ---------- x : [type] 입력 텐서 filters : int bottleneck 레이어의 필터 수. kernel_size : int, optional, default=3 bottleneck 레이어의 커널 크기. stride : int, optional, defa...
5,287,726
def set_converter( target: BasePattern, alias: Optional[str] = None, cover: bool = False, data: Optional[dict] = None ): """ 增加 Alconna 内使用的类型转换器 Args: target: 设置的表达式 alias: 目标类型的别名 cover: 是否覆盖已有的转换器 data: BasePattern的存储字典 """ data = d...
5,287,727
async def test_pubsub_subscription_auth_failure(hass, oauth): """Check flow that creates a pub/sub subscription.""" assert await async_setup_configflow(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) result = await oauth.asy...
5,287,728
def _get_port_v1(port_name, depth=0, selector=None, **kwargs): """ Perform a GET call to retrieve data for a Port table entry :param port_name: Alphanumeric name of the port :param kwargs: keyword s: requests.session object with loaded cookie jar keyword url: URL in main() function ...
5,287,729
def sample_with_replacement(population,len,choose=random.choice): """Sample from a population with replacement Taken from Python Cookbook, 2nd ed, recipe 18.3 """ s = [] for i in xrange(len): s.append(choose(population)) return s
5,287,730
def power_mod(val, power, m_value): """ Calculate power mod the efficent way """ if power <= 100: return (val ** power) % m_value if power % 2 == 0: return (power_mod(val, power // 2, m_value) ** 2) % m_value return (power_mod(val, power // 2, m_value) * power_mod(val, power ...
5,287,731
def kill(name): """Kills all processes that are started by this file.""" os.system(f"taskkill /IM \"{name}.exe\" /F")
5,287,732
def stokes_right_circular(): """Stokes vector for right circular polarized light.""" return np.array([1, 0, 0, 1])
5,287,733
def hello_http(request): """HTTP Cloud Function. Args: request (flask.Request): The request object. <http://flask.pocoo.org/docs/0.12/api/#flask.Request> Returns: The response text, or any set of values that can be turned into a Response object using `make_response` <...
5,287,734
def search_objects(params: dict, results: dict, meta: dict): """ Convert Elasticsearch results into the RPC results conforming to the "search_objects" method """ post_processing = _get_post_processing(params) objects = _get_object_data_from_search_results(results, post_processing) ret = { ...
5,287,735
def web_driver(browser): """ Create ADCMTest object and initialize web driver session Destroy session after test is done :param browser: browser name from pytest_generate_tests hook """ driver = ADCMTest(browser) driver.create_driver() yield driver try: driver.des...
5,287,736
def encode_raw(objs): """ Encode a list of raw data and types to binary wire format Useful for analyzing Protobuf messages with unknown schema """ return RawWire().encode(objs)
5,287,737
def inv_income_weighted_utility(coin_endowments, utilities): """Social welfare, as weighted average utility (weighted by inverse endowment). Args: coin_endowments (ndarray): The array of coin endowments for each of the agents in the simulated economy. utilities (ndarray): The array ...
5,287,738
def refresh_config()->None: """初始化配置文件""" PROJECT_CONFIG = get_configs(CONFIG_PATH) PROJECT_BASE_DIR = PROJECT_CONFIG['dirname'] DIRSETTINGS = os.path.join(PROJECT_BASE_DIR, PROJECT_CONFIG['project_name'], 'settings.py') temp_configs = {} # 全局配置文件待写入 temp_configs['dirname'] = PROJECT_BASE_DIR # ...
5,287,739
def get_full_path(pset, photo): """ Assemble a full path from the photoset and photo titles @param pset: str, photo set name @param photo: str, photo name @return: str, full sanitized path """ return os.path.join(sanitize_filepath(pset), sanitize_filepath(photo))
5,287,740
def new_post(): """ Display and handle form for creating a new blog post. """ form = PostForm() if form.validate_on_submit(): post = Post(pub_date=datetime.date.today()) post.title = form.title.data post.content = form.content.data post.slug = slugify(post.title) ...
5,287,741
def _inv_shift_rows(s: List[List[bytes]]) -> List[List[bytes]]: """ Performs the inverted shift rows transformation as described in the standard :param s: the state matrix :return: the new state matrix with shifted rows """ s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1] ...
5,287,742
def create(dtype, key_len=None, val_len=None): """ Input : Example input dtype=i32:i32 will create an i32_i32 instance. """ k_ty, v_type = None, None try: splitted_words = dtype.split(':') except AttributeError as e: raise TypeError("dtype must be a string") if len(splitted_words) != 2: raise ValueErr...
5,287,743
def test_main_export_nodir(monkeypatch): """Use current directory if targetdir not given""" config = {} args = ['-E', 'csv', '-d', '1s', 'what'] with pytest.raises(SystemExit): main(arglist=args, config=config) llconfig = config['loadlimit'] assert 'export' in llconfig exportconfi...
5,287,744
def read(*filenames, **kwargs): """ Read specified filenames and return contents """ enc = kwargs.get('enc', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: with io.open(filename, encoding=enc) as f: buf.append(f.read()) return sep.join(buf)
5,287,745
def create_drilling_vectors(diameter: float, length: float, p1: point_3d, xl:point_3d) -> int: """Create a drilling from a point and a direction vector. Args: diameter (float): drilling diameter length (float): drilling length p1 (point_3d): start point xl (point_3d): vector di...
5,287,746
def tile_context_feature(feat, max_sequence_size): """ Tile context features to max_sequence_size. Do nothing if sequence feature Parameters ---------- feat: Tensor Feature tensor to be tiled Shape: [batch_size, max_len] or [batch_size, sequence_size, max_len] max_sequence_size:...
5,287,747
def thread_image_file_path(instance, filename): """Generating a file path for avatar image""" ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return os.path.join('uploads/thread/', filename)
5,287,748
def circuit_scheduler_settings(**settings) -> ContextManager[None]: """Set the currently active circuit scheduler settings for this context. Examples: .. jupyter-execute:: from qiskit import pulse from qiskit.test.mock import FakeOpenPulse2Q backend = FakeOpenPulse2Q() w...
5,287,749
def conv_transpose(num_filters, kernel_size=3, activation='relu', conv_order='conv_first', use_batch_norm=True, name=None, **conv_kwargs): """A composite layer for deconvolution with BatchNormalization.""" assert conv_order in ['conv_first', 'conv_last'] def inner(x): conv_first...
5,287,750
def get_id_character_mapping(data, columns): """Creating a mapping between characters and ids given dataframe. Args: data: dataframe that contains characters that need to be converted to ids column: a column of the dataframe that contains characters that need to be converted to ids columns: ...
5,287,751
def topological_sort_as_sets(dependency_graph): """ Variation of Kahn's algorithm (1962) that returns sets. Take a dependency graph as a dictionary of node => dependencies. Yield sets of items in topological order, where the first set contains all nodes without dependencies, and each follow...
5,287,752
def ensure_local_services_are_running() -> int: """Ensure all required services (mysql, redis) are running.""" # NOTE: if you have any problems with this, please contact me # @cmyui#0425/cmyuiosu@gmail.com. i'm interested in knowing # how people are using the software so that i can keep it # in mind...
5,287,753
def estimate_dimension(X, n_neighbors='auto', neighbors_estimator=None): """Estimate intrinsic dimensionality. Based on "Manifold-Adaptive Dimension Estimation" Farahmand, Szepavari, Audibert ICML 2007. Parameters ---------- X : nd-array, shape (n_samples, n_features) Input data. ...
5,287,754
def start(subj, body): """ parse Twitter message """ lines = body.splitlines() for index, line in enumerate(lines): if line in SUBJECTS: text = '\n'.join(lines[index + 1:]) return TITLE + line + '\n' + cut_text(text) if DELIMETER in body: return convert_p...
5,287,755
def get_results(build, issue_id, favourite): """Get build results.""" LOG.debug("Getting build results for issue %s", issue_id) try: handler = BuildHandler(build.get_config()) handler.get_build_results(issue_id, favourite) except Exception: traceback.print_exc() raise cl...
5,287,756
def load_json_files(dirpath): """ Collects process definitions (JSON files) from a local process directory. Parameters ---------- dirpath : str Directory path of the process files (.json) folder. Returns ------- list List of processes decoded as dictionaries. """ ...
5,287,757
def img_collate(imgs): """ Args: imgs: Returns: torch.tensor, (B, 3, H, W) """ w = imgs[0].width h = imgs[0].height tensor = torch.zeros( (len(imgs), 3, h, w), dtype=torch.uint8).contiguous() for i, img in enumerate(imgs): nump_array = np.array(img, dtype...
5,287,758
def _clear_cache(): """Clear the config cache.""" global __config __config = None
5,287,759
async def rpms_rebase_and_build(runtime: Runtime, version: str, release: str, embargoed: bool, scratch: bool, dry_run: bool): """ Attempts to rebase and build rpms for all of the defined rpms in a group. """ exit_code = await _rpms_rebase_and_build(runtime, version=version, release=release, embargoe...
5,287,760
def set_brightness(brightness): """Set a global brightness value. :param brightness: Brightness value from 0.0 to 1.0 """ global _brightness _brightness = brightness
5,287,761
def __args_to_weka_options(args): """ Function that creates list with options (args) in format approperiate for weka. :param args: dictionery with command line input :return: list of command line arguments """ result = [] for k,v in args.items(): if v: result.append(...
5,287,762
def execute( context: cli.CommandContext, verbose: bool = False, as_json: bool = False ) -> Response: """ :return: """ response = context.response settings = environ.package_settings if verbose: data = environ.systems.get_system_data() data['cauldron'] ...
5,287,763
def batch_input_file_validator(value): """ All input files should be valid image files. Supported extensions: ['.jpg','.jpeg','.png','.bmp','.webp'] """ for i in value: if not os.path.isfile(value): raise TypeError("Select a valid input file.") return value
5,287,764
def generate_response(tokenizer, model, chat_round, chat_history_ids, question): """ Generate a response to some user input. """ # Encode user input and End-of-String (EOS) token new_input_ids = tokenizer.encode(">> You: "+ question + tokenizer.eos_token, return_tensors='pt') # Append token...
5,287,765
def test_atomic_date_max_inclusive_4_nistxml_sv_iv_atomic_date_max_inclusive_5_5(mode, save_output, output_format): """ Type atomic/date is restricted by facet maxInclusive with value 2030-12-31. """ assert_bindings( schema="nistData/atomic/date/Schema+Instance/NISTSchema-SV-IV-atomic-date-m...
5,287,766
def response_check_suboption_content(step, resp_rel, subopt_code, opt_code, expect, data_type, expected): """ Some options can include suboptions, we can test them too. For more details please read manual section "Parsing respond" """ dhcpmsg.response_check_suboption_content(subopt_code, opt_code, e...
5,287,767
def gamma_closures(expressions, could_not_close=None): """ Try to compute gamma closure for each of expressions. :param expressions: list of moment expressions, where each expression is a product of powers of moments :param could_not_close: a list that will be filled with expressions that c...
5,287,768
def find_by_history(view: kvstore.View, storage: bool, key: bytes, block_number: int) -> (bytes, bytes): """find_by_history""" if storage: bucket = tables.STORAGE_HISTORY_LABEL else: bucket = tables.ACCOUNTS_HISTORY_LABEL index_chunck_key = history_index.index_chunck_key(key, block_numb...
5,287,769
def hyperopt_report( hyperopt_stats_path: str, output_directory: str = None, file_format: str = 'pdf', **kwargs ) -> None: """ Produces a report about hyperparameter optimization creating one graph per hyperparameter to show the distribution of results and one additional ...
5,287,770
def linear_coeff(x, y): """ This function returns the inclination coeffecient and y axis interception coeffecient m and b. ---------- Parameters ---------- x : Output of the split vector function. y : Output of the split vector function. ------- Returns ------- float numb...
5,287,771
def _package_contents_metadata(origin_label, grouping_label): """Named construct for helping to identify conflicting packaged contents""" return struct( origin = origin_label if origin_label else "<UNKNOWN>", group = grouping_label, )
5,287,772
def str_to_feet(value="0'-0"): """ Returns string converted into decimal feet. Acceptible formats include: 1. 5'-7" 5'-7 1/2" 5'-7 1/2'' 5'-7 5'-7 1/2 2. 7 3/4 -8 The trailing quotation mark can be omitted. ...
5,287,773
async def speech_process_killer_loop(): """Try to kill speech process every 5 mins because for some reason with prolonged used, the output files from the tts process are empty """ while True: restart_speech_process() await asyncio.sleep(60)
5,287,774
def get_dftbp_evol(implargs, database, source, model, datafile='detailed.out', *args, **kwargs): """Get the data from DFTB+ SCC calculation for all models. This is a compound task that augments the source path to include individual local directories for different cell volumes, based ...
5,287,775
def deconstruct_answer( answer_sentence: T5_SENTENCE = '' ) -> Tuple[List[T5_SENTENCE], List[str]]: """Gets individual answer subsentences from the compound answer sentence. Args: answer sentence: a T5 output sentence. Examples: >>> sentence = '[SENT25] [Tipo de Logradouro]: Rua [SENT2...
5,287,776
def distance_modulus(distance): """Given a distance in parsecs, returns the value :math:`m - M`, a characteristic value used to convert from apparent magnitude :math:`m` to absolute magnitude, :math:`M`. Uses the formula from Carroll and Ostlie, where :math:`d` is in parsecs .. math:: m - M = 5 \log_{...
5,287,777
def test_fortify_get_build_name(): """Test the get_build_name function.""" package = Package('unusual-name', os.path.dirname(__file__)) assert ftp_module._get_build_name(package) == \ 'statick-fortify-unusual-name'
5,287,778
def _merge_reasons(m: CommentsCollection, n: CommentsCollection) -> None: """Given 2 dict of {name -> Set(reasons)}, merge n into m. """ for name, new_reasons in n.items(): old_reasons = m.get(name) if not old_reasons: old_reasons = set() m[name] = old_reasons ...
5,287,779
def _serialize_data_asset(asset: DataAsset) -> JSON: """Serialize a DataAsset to JSON.""" return _serialize_asset(asset)
5,287,780
def behroozi10_model_dictionary(redshift=sim_defaults.default_redshift, **kwargs): """ Dictionary that can be passed to the `~halotools.empirical_models.SubhaloModelFactory` to build a subhalo-based composite model using the stellar-to-halo-mass relation published in Behroozi et al. (2010), `arXiv:1...
5,287,781
def listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None): """ Socket server based logging configuration is not enabled """ #if not thread: #pragma: no cover # raise NotImplementedError("listen() needs threading to work") raise NotImplementedError()
5,287,782
def detects(label=None, frac=None): """list of outlier detection algorithms to select from""" algo = {'isoForest': IsolationForest(contamination=frac, random_state=42), 'MCD': EllipticEnvelope(contamination=frac), 'LOF': LocalOutlierFactor(n_neighbors=20, contamination=frac)} return ...
5,287,783
def zpadlist(values: list, inputtype: str, minval: int, maxval: int) -> list: """Return a list of zero padded strings and perform input checks. Returns a list of zero padded strings of day numbers from a list of input days. Invalid month numbers (e.g. outside of 1-31) will raise an exception. Para...
5,287,784
def find_backend(txt): """ Determine the needed background based on a text string Parameters ---------- txt : str name to find in the list Returns ------- b : :class:`~beast.physicsmodel.helpers.gridbackends.GridBackend` subclass corresponding backend class """ ...
5,287,785
def tx_token(ctx, src, symbol, name, owner, decimals, fee, ots_key_index): """ Create Token Transaction, that results into the formation of new token if accepted. """ if not ctx.obj.remote: click.echo('This command is unsupported for local wallets') return initial_balances = [] ...
5,287,786
def _make_gmm(ft_data: pd.DataFrame, n_feature: int, cluster_name: str): """ fit a gaussian model and set subcluster names for each feature. Auxiliary function to process cluster. Parameters ---------- ft_data : DataFrame The mz and rt columns of the cluster DataFrame n_feature : in...
5,287,787
def test_atomic_time_max_inclusive_1_nistxml_sv_iv_atomic_time_max_inclusive_2_5(mode, save_output, output_format): """ Type atomic/time is restricted by facet maxInclusive with value 13:46:08. """ assert_bindings( schema="nistData/atomic/time/Schema+Instance/NISTSchema-SV-IV-atomic-time-max...
5,287,788
async def run_client(client: Jenny) -> None: """A basic encrypted chat application using nio. """ # This is our own custom login function that looks for a pre-existing config # file and, if it exists, logs in using those details. Otherwise it will log # in using a password. await client.login()...
5,287,789
def main(): """ Main func. """ args = docopt(__doc__) # seed the random number generators seed = int(args['--seed']) torch.manual_seed(seed) if args['--cuda']: torch.cuda.manual_seed(seed) np.random.seed(seed * 13 // 7) if args['train']: train(args) elif args['te...
5,287,790
def _set_health_check_defaults(health_check): """Sets default values for any missing attributes in HealthCheck. These defaults need to be kept up to date with the production values in health_check.cc Args: health_check: An instance of appinfo.HealthCheck or None. Returns: An instance of appinfo.Hea...
5,287,791
def singular_values_plot(syslist, omega=None, plot=True, omega_limits=None, omega_num=None, *args, **kwargs): """Singular value plot for a system Plots a Singular Value plot for the system over a (optional) frequency range. Parameters ---------- sy...
5,287,792
def visualize(image, mask, original_image=None, original_mask=None): """ Plot image and masks. If two pairs of images and masks are passes, show both. """ fontsize = 14 class_dict = {0: 'Fish', 1: 'Flower', 2: 'Gravel', 3: 'Sugar'} if original_image is None and original_mask is None: ...
5,287,793
def init_single_subject_wf(subject_id): """ Set-up the preprocessing pipeline for a single subject. It collects and reports information about the subject, and prepares sub-workflows to perform anatomical and diffusion MRI preprocessing. Anatomical preprocessing is performed in a single workflow, r...
5,287,794
def get_known_devices(): """ Using the DBus ObjectManager, yield all known Devices. """ bus = pydbus.SystemBus() manager = bus.get(SERVICE_NAME, "/")[OBJECT_MANAGER_INTERFACE] objs = manager.GetManagedObjects() for path, ifaces in objs.items(): if DEVICE_INTERFACE in ifaces.keys(): ...
5,287,795
def _get_scxdir(scxdir=None): """Retrieve the base secondary directory with error checking. Parameters ---------- scxdir : :class:`str`, optional, defaults to :envvar:`SCND_DIR` Directory containing secondary target files to which to match. If not specified, the directory is taken to be...
5,287,796
def find_spike_from_templates(recording, waveform_extractor, method='simple', method_kwargs={}, **job_kwargs): """Find spike from a recording from given templates. Parameters ---------- recording: RecordingExtractor The recording extractor object. waveform_extr...
5,287,797
def _append_latest_to(self): """Retrieve handle records for replacements until a current dataset is found.""" if not self.obsolete: return if len( self.rec['REPLACED_BY'] ) > 1: print( 'WORKFLOW WARNING: multiple replacements' ) this = self.rec['REPLACED_BY'][-1] this.get() self.re...
5,287,798
def get_metadata(path): """ Find the json metadata file associated with content at `path` (dir or file). """ metadata_filename = get_metadata_file_path(path) if not os.path.exists(metadata_filename): return {} with open(metadata_filename, 'r') as json_file: return json.load(json_...
5,287,799