content
stringlengths
22
815k
id
int64
0
4.91M
def content_loss_func(sess, model): """Content loss function defined in the paper.""" def _content_loss(p, x): # N is the number of filters at layer 1 N = p.shape[3] # M is the height * width of the feature map at layer 1 M = p.shape[1] * p.shape[2] return (1 / (4 * N * ...
29,900
def Extract_from_DF_kmeans(dfdir,num,mode=True): """ PlaneDFを読み込んで、client_IP毎に該当index番号の羅列をそれぞれのtxtに書き出す modeがFalseのときはシーケンスが既にあっても上書き作成 """ flag = exists("Database/KMeans/km_full_"+dfdir+"_database_name")#namelistが存在するかどうか if(flag and mode):return plane_df = joblib.load("./...
29,901
def get_workspace(workspace_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetWorkspaceResult: """ Resource schema for AWS::IoTTwinMaker::Workspace :param str workspace_id: The ID of the workspace. """ __args__ = dict() __args__['workspaceI...
29,902
def find_open_port(): """ Use socket's built in ability to find an open port. """ sock = socket.socket() sock.bind(('', 0)) host, port = sock.getsockname() return port
29,903
def split_list_round_robin(data: tp.Iterable, chunks_num: int) -> tp.List[list]: """Divide iterable into `chunks_num` lists""" result = [[] for _ in range(chunks_num)] chunk_indexes = itertools.cycle(i for i in range(chunks_num)) for item in data: i = next(chunk_indexes) result[i].appen...
29,904
def calc_Q_loss_FH_d_t(Q_T_H_FH_d_t, r_up): """温水床暖房の放熱損失 Args: Q_T_H_FH_d_t(ndarray): 温水暖房の処理暖房負荷 [MJ/h] r_up(ndarray): 当該住戸の温水床暖房の上面放熱率 [-] Returns: ndarray: 温水床暖房の放熱損失 """ return hwfloor.get_Q_loss_rad(Q_T_H_rad=Q_T_H_FH_d_t, r_up=r_up)
29,905
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" _LOGGER.debug("__init__ async_unload_entry") unload_ok = all( await asyncio.gather( *( hass.config_entries.async_forward_entry_unload(entry, component) ...
29,906
def main(hgt_results_fp, genbank_fp, method, ncbi_nr, darkhorse_low_lpi, darkhorse_high_lpi, darkhorse_output_fp=None): """ Parsing functions for various HGT detection tool outputs. """ output = parse_output(hgt_results_fp=hgt_results_fp, ...
29,907
def t06_ManyGetPuts(C, pks, crypto, server): """Many clients upload many files and their contents are checked.""" clients = [C("c" + str(n)) for n in range(10)] kvs = [{} for _ in range(10)] for _ in range(200): i = random.randint(0, 9) uuid1 = "%08x" % random.randint(0, 100) ...
29,908
def multi_lightness_function_plot(functions=None, **kwargs): """ Plots given *Lightness* functions. Parameters ---------- functions : array_like, optional *Lightness* functions to plot. \*\*kwargs : \*\* Keywords arguments. Returns ------- bool Definition su...
29,909
def delete_notification(request): """ Creates a Notification model based on uer input. """ print request.POST # Notification's PK Notification.objects.get(pk=int(request.POST["pk"])).delete() return JsonResponse({})
29,910
def parse_query_value(query_str): """ Return value for the query string """ try: query_str = str(query_str).strip('"\' ') if query_str == 'now': d = Delorean(timezone=tz) elif query_str.startswith('y'): d = Delorean(Delorean(timezone=tz).midnight) d -=...
29,911
def build_model(): """ Build the model :return: the model """ model = keras.Sequential([ layers.Dense(64, activation='relu', input_shape=[len(train_dataset.keys())]), layers.Dense(64, activation='relu'), layers.Dense(1) ]) optimizer = tf.keras.optimizers.RMSprop(0.00...
29,912
def detect(stream): """Returns True if given stream is a readable excel file.""" try: opendocument.load(BytesIO(stream)) return True except: pass
29,913
def test_invalid_json(): """Test Invalid response Exception""" loop = asyncio.get_event_loop() with aioresponses() as m: m.post('https://api.idex.market/returnTicker', body='<head></html>') async def _run_test(): client = await AsyncClient.create(api_key) with pytes...
29,914
def create_region_file(filename, reg_file): """.""" # Read the OSM file osm_data = np.loadtxt(filename) coords = osm_data[:, 0:2] if (os.path.exists(reg_file)): os.remove(reg_file) file = open(reg_file, 'w') file.write('global color=green dashlist=8 3 width=1 ' 'fon...
29,915
def new_default_channel(): """Create new gRPC channel from settings.""" channel_url = urlparse(format_url(settings.SERVICE_BIND)) return Channel(host=channel_url.hostname, port=channel_url.port)
29,916
def iou(bbox1, bbox2): """ Calculates the intersection-over-union of two bounding boxes. Args: bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. Returns: int: intersection-over-onion o...
29,917
def test_agent_proxy_wait_running_timeout(nsproxy, timeout): """ Check that the `wait_for_running` method times out if the agent is not running after the specified number of seconds. """ AgentProcess('agent').start() time0 = time.time() with pytest.raises(TimeoutError) as error: Pro...
29,918
def seed_request(): """ Adds request seeds to the database. """ today = datetime.utcnow() yesterday = datetime.now() - timedelta(1) before_yesterday = datetime.now() - timedelta(2) way_before_yesterday = datetime.now() - timedelta(3) future_day = datetime.now() + timedelta(20) # Cr...
29,919
def set_keymap_settings(keymap): """Activate certain keymap through Gnome, changing settings directly without delay. The new keymap will be changed for all windows immediately. The keymap parameter must be directly suitable for Gnome, e.g. 'fi', 'us', or 'fi\\tnodeadkeys' (where the separator is a tab...
29,920
def get_version(): """ Obtain the version of the ITU-R P.1511 recommendation currently being used. Returns ------- version: int Version currently being used. """ return __model.__version__
29,921
def sample_filepaths(filepaths_in, filepaths_out, intensity): """ `filepaths_in` is a list of filepaths for in-set examples. `filepaths_out` is a list of lists, where `filepaths_out[i]` is a list of filepaths corresponding to the ith out-of-set class. `intensity` is the number of in-set examples...
29,922
def makekey(s): """ enerates a bitcoin private key from a secret s """ return CBitcoinSecret.from_secret_bytes(sha256(s).digest())
29,923
def shape_broadcast(shape1: tuple, shape2: tuple) -> tuple: """ Broadcast two shapes to create a new union shape. Args: shape1 (tuple) : first shape shape2 (tuple) : second shape Returns: tuple : broadcasted shape Raises: IndexingError : if cannot broadcast """...
29,924
def hash_array(kmer): """Return a hash of a numpy array.""" return xxhash.xxh32_intdigest(kmer.tobytes())
29,925
def GenerateDiskTemplate( lu, template_name, instance_uuid, primary_node_uuid, secondary_node_uuids, disk_info, file_storage_dir, file_driver, base_index, feedback_fn, full_disk_params): """Generate the entire disk layout for a given template type. """ vgname = lu.cfg.GetVGName() disk_count = len(disk_in...
29,926
def check_pc_overlap(pc1, pc2, min_point_num): """ Check if the bounding boxes of the 2 given point clouds overlap """ b1 = get_pc_bbox(pc1) b2 = get_pc_bbox(pc2) b1_c = Polygon(b1) b2_c = Polygon(b2) inter_area = b1_c.intersection(b2_c).area union_area = b1_c.area + b2_c.area - int...
29,927
def build_for_lambda(c, no_clean=False): """ aws lambda 用に executable なコードをビルドする :param c: :param no_clean: :return: """ if not no_clean: clean(c) c.run("mkdir -p {}".format(DIST_PATH)) file_list = [ 'requirements.txt', 'constraints.txt', 'lambda_fu...
29,928
def apply_hypercube(cube: DataCube, context: dict) -> DataCube: """Reduce the time dimension for each tile and compute min, mean, max and sum for each pixel over time. Each raster tile in the udf data object will be reduced by time. Minimum, maximum, mean and sum are computed for each pixel over time. ...
29,929
def main(): """Exercise get_bucket_acl()""" # Assign this value before running the program test_bucket_name = 'BUCKET_NAME' # Set up logging logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(asctime)s: %(message)s') # Retrieve the current bucket ACL ...
29,930
def cli(env, identifier): """Delete an image.""" image_mgr = SoftLayer.ImageManager(env.client) image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image') image_mgr.delete_image(image_id)
29,931
def dateIsBefore(year1, month1, day1, year2, month2, day2): """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False.""" if year1 < year2: return True if year1 == year2: if month1 < month2: return True if month1 == month2: if ...
29,932
def all_stat(x, stat_func=np.mean, upper_only=False, stat_offset=3): """ Generate a matrix that contains the value returned by stat_func for all possible sub-windows of x[stat_offset:]. stat_func is any function that takes a sequence and returns a scalar. if upper_only is False, values are added t...
29,933
def PyCallable_Check(space, w_obj): """Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This function always succeeds.""" return int(space.is_true(space.callable(w_obj)))
29,934
def test_Circular_Aperture_PTP_short(display=False, npix=512, oversample=4, include_wfe=True, display_proper=False): """ Tests plane-to-plane propagation at short distances, by comparison of the results from propagate_ptp and propagate_direct calculations This test also now include wavefront error, so as t...
29,935
def save_nii(obj, outfile, data=None, is_nii=False): """ save a nifti object """ if not is_nii: if data is None: data = obj.get_data() nib.Nifti1Image(data, obj.affine, obj.header)\ .to_filename(outfile) else: obj.to_filename(outfile)
29,936
def _multiclass_metric_evaluator(metric_func: Callable[..., float], n_classes: int, y_test: np.ndarray, y_pred: np.ndarray, **kwargs) -> float: """Calculate the average metric for multiclass classifiers.""" metric = 0 for label in range(n_classes): metric += metric_...
29,937
def TestResumeWatcher(): """Tests and unpauses the watcher. """ master = qa_config.GetMasterNode() AssertCommand(["gnt-cluster", "watcher", "continue"]) cmd = ["gnt-cluster", "watcher", "info"] output = GetCommandOutput(master.primary, utils.ShellQuoteArgs(cmd)) AssertMatch(...
29,938
def insert_phots_into_database(framedir, frameglob='rsub-*-xtrns.fits', photdir=None, photglob='rsub-*-%s.iphot', maxframes=None, overwrite=False, ...
29,939
def idxs_of_duplicates(lst): """ Returns the indices of duplicate values. """ idxs_of = dict({}) dup_idxs = [] for idx, value in enumerate(lst): idxs_of.setdefault(value, []).append(idx) for idxs in idxs_of.values(): if len(idxs) > 1: dup_idxs.extend(idxs) return ...
29,940
def test_get_fitness_value(case_data): """ Test :meth:`.FitnessCalculator.get_fitness_value`. Parameters ---------- case_data : :class:`.CaseData` A test case. Holds the fitness calculator to test and the correct fitness value. Returns ------- None : :class:`NoneType` ...
29,941
async def store_rekey( handle: StoreHandle, wrap_method: str = None, pass_key: str = None, ) -> StoreHandle: """Replace the wrap key on a Store.""" return await do_call_async( "askar_store_rekey", handle, encode_str(wrap_method and wrap_method.lower()), encode_str(pas...
29,942
def prepare_bitbucket_data(data, profile_data, team_name): """ Prepare bitbucket data by extracting information needed if the data contains next page for this team/organisation continue to fetch the next page until the last page """ next_page = False link = None profile_data = append_bi...
29,943
def add(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.add <numpy.add>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in add") # C...
29,944
def aslist(l): """Convenience function to wrap single items and lists, and return lists unchanged.""" if isinstance(l, list): return l else: return [l]
29,945
def form_03(request_data): """ Статистическая форма 066/у Приложение № 5 к приказу Минздрава России от 30 декабря 2002 г. № 413 """ num_dir = request_data["dir_pk"] direction_obj = Napravleniya.objects.get(pk=num_dir) hosp_nums_obj = hosp_get_hosp_direction(num_dir) hosp_nums = f"- {hosp_num...
29,946
def getKeyList(rootFile,pathSplit): """ Get the list of keys of the directory (rootFile,pathSplit), if (rootFile,pathSplit) is not a directory then get the key in a list """ if isDirectory(rootFile,pathSplit): changeDirectory(rootFile,pathSplit) return ROOT.gDirectory.GetListOfKeys()...
29,947
def get_args(): """Parse command line arguments and return namespace object""" parser = argparse.ArgumentParser(description='Transcode some files') parser.add_argument('-c', action="store", dest="config", required=True) parser.add_argument('-l', action="store", dest="limit", type=int, default=None) ...
29,948
def query_from_json(query_json: Any, client: cl.Client = None): """ The function converts a dictionary or json string of Query to a Query object. :param query_json: A dictionary or json string that contains the keys of a Query. :type query_json: Any :param...
29,949
def _write(info, directory, format, name_format): """ Writes the string info Args: directory (str): Path to the directory where to write format (str): Output format name_format (str): The file name """ #pylint: disable=redefined-builtin file_name = name_format file_p...
29,950
def fetch_validation_annotations(): """ Returns the validation annotations Returns: complete_annotations: array of annotation data - [n_annotations, 4] row format is [T, X, Y, Z] """ ann_gen = _annotation_generator() data = [] for annotation in ann_gen: if annotation[0] in...
29,951
def enough_data(train_data, test_data, verbose=False): """Check if train and test sets have any elements.""" if train_data.empty: if verbose: print('Empty training data\n') return False if test_data.empty: if verbose: print('Empty testing data\n') retu...
29,952
def test_authorized_rpc_call2(volttron_instance, build_two_test_agents): """Tests an agent with two capability calling a method that requires those same two capabilites """ agent1, agent2 = build_two_test_agents # Add another required capability agent1.vip.rpc.allow(agent1.foo, 'can_call_foo2')...
29,953
def main(argv): """Go Main Go""" if len(argv) == 2: hr = int(argv[1]) if hr == 12: # Run for the previous UTC day ts = datetime.datetime.utcnow() - datetime.timedelta(days=1) ts = ts.replace(tzinfo=pytz.utc).replace(hour=12, minute=0, ...
29,954
def parse_args(args): """ Parse the arguments to this application, then return the constructed namespace argument. :param args: list of arguments to parse :return: namespace argument """ parser = argparse.ArgumentParser( description="Connects data from F prime flight software to the GDS ...
29,955
def calculate_tidal_offset(TIDE, GM, R, refell): """ Calculates the spherical harmonic offset for a tide system to change from a tide free state where there is no permanent direct and indirect tidal potentials Arguments --------- TIDE: output tidal system R: average radius used ...
29,956
def get_questions(set_id, default_txt=None): """Method to get set of questions list.""" try: cache_key = 'question_list_%s' % (set_id) cache_list = cache.get(cache_key) if cache_list: v_list = cache_list print('FROM Cache %s' % (cache_key)) else: ...
29,957
def _export_photo_uuid_applescript( uuid, dest, filestem=None, original=True, edited=False, live_photo=False, timeout=120, burst=False, ): """ Export photo to dest path using applescript to control Photos If photo is a live photo, exports both the photo and associated .mov fi...
29,958
def get_mms_operation(workspace, operation_id): """ Retrieve the operation payload from MMS. :return: The json encoded content of the reponse. :rtype: dict """ response = make_mms_request(workspace, 'GET', '/operations/' + operation_id, None) return response.json()
29,959
def _check_data_nan(data): """Ensure data compatibility for the series received by the smoother. (Without checking for inf and nans). Returns ------- data : array Checked input. """ data = np.asarray(data) if np.prod(data.shape) == np.max(data.shape): data = data.ravel...
29,960
def function(row, args): """Execute a named function function(arg, arg...) @param row: the HXL data row @param args: the arguments parsed (the first one is the function name) @returns: the result of executing the function on the arguments """ f = FUNCTIONS.get(args[0]) if f: retu...
29,961
def setup_client(public_key: str, secret_key: str, **_): """Create a Culqi client from set-up application keys.""" culqipy.public_key = public_key culqipy.secret_key = secret_key
29,962
def currencyrates(): """ print a sh-friendly set of variables representing todays currency rates for $EXCHANGERATES which is a semicolon- separated list of currencyexchange names from riksbanken.se using daily avg aggregation :return: none """ #print(ratesgroup()) rates = os.environ.get("EX...
29,963
def extract_rfc2822_addresses(text): """Returns a list of valid RFC2822 addresses that can be found in ``source``, ignoring malformed ones and non-ASCII ones. """ if not text: return [] candidates = address_pattern.findall(tools.ustr(text).encode('utf-8')) return filter(try_coerce_asc...
29,964
def set_edge_font_size_mapping(table_column, table_column_values=None, sizes=None, mapping_type='c', default_size=None, style_name=None, network=None, base_url=DEFAULT_BASE_URL): """Map table column values to sizes to set the edge size. Args: table_column (str): Name of C...
29,965
def compute_time_overlap(appointment1, appointment2): """ Compare two appointments on the same day """ assert appointment1.date_ == appointment2.date_ print("Checking for time overlap on \"{}\"...". format(appointment1.date_)) print("Times to check: {}, {}". format(appointmen...
29,966
def set_up_prior(data, params): """ Function to create prior distribution from data Parameters ---------- data: dict catalog dictionary containing bin endpoints, log interim prior, and log interim posteriors params: dict dictionary of parameter values for creation of pri...
29,967
def is_nonincreasing(arr): """ Returns true if the sequence is non-increasing. """ return all([x >= y for x, y in zip(arr, arr[1:])])
29,968
def restore_missing_features(nonmissing_X, missing_features): """Insert columns corresponding to missing features. Parameters ---------- nonmissing_X : array-like, shape (n_samples, n_nonmissing) Array containing data with missing features removed. missing_features : array-like, shape (n_m...
29,969
def fontifyPythonNode(node): """ Syntax color the given node containing Python source code. @return: C{None} """ oldio = cStringIO.StringIO() latex.getLatexText(node, oldio.write, entities={'lt': '<', 'gt': '>', 'amp': '&'}) oldio = cStringIO.StringIO(oldio.getvalue()...
29,970
def get_sample_type_from_recipe(recipe): """Retrieves sample type from recipe Args: recipe: Recipe of the project Returns: sample_type_mapping, dic: Sample type of the project For Example: { TYPE: "RNA" } , { TYPE: "DNA" }, { TYPE: "WGS" } """ return find_mapping(recipe_type_mapping, recipe)
29,971
def _is_download_necessary(path, response): """Check whether a download is necessary. There three criteria. 1. If the file is missing, download it. 2. The following two checks depend on each other. 1. Some files have an entry in the header which specifies when the file was modified l...
29,972
def hash64(s): """Вычисляет хеш - 8 символов (64 бита) """ hex = hashlib.sha1(s.encode("utf-8")).hexdigest() return "{:x}".format(int(hex, 16) % (10 ** 8))
29,973
def test_import(sfinit): """ Test code by importing all available classes for this module. If any of these fails then the module itself has some code error (e.g., syntax errors, inheritance errors). """ sfinit for name in config.NAMES: modules = return_modules()[name] for pac...
29,974
def course_runs(): """Fixture for a set of CourseRuns in the database""" return CourseRunFactory.create_batch(3)
29,975
def _response(data=None, status_code=None): """Build a mocked response for use with the requests library.""" response = MagicMock() if data: response.json = MagicMock(return_value=json.loads(data)) if status_code: response.status_code = status_code response.raise_for_status = MagicMo...
29,976
def test_baked_django_with_custom_issue_template_files(cookies): """Test Django project has custom ISSUE templates generated correctly. Tests that the Custom Issue templates have had the "assignee" generated correctly, and post_gen deleted the standard template. """ default_django = cookies.bake() ...
29,977
def findtailthreshold(v, figpath=None): """ function [f,mns,sds,gmfit] = findtailthreshold(v,wantfig) <v> is a vector of values <wantfig> (optional) is whether to plot a diagnostic figure. Default: 1. Fit a Gaussian Mixture Model (with n=2) to the data and find the point that is greater t...
29,978
async def make_request_and_envelope_response( app: web.Application, method: str, url: URL, headers: Optional[Dict[str, str]] = None, data: Optional[bytes] = None, ) -> web.Response: """ Helper to forward a request to the catalog service """ session = get_client_session(app) try:...
29,979
def tprint(string, indent=4): """Print with indent.""" print indent * ' ' + str(string)
29,980
def _app_node(app_id, existing=True): """Returns node path given app id.""" path = os.path.join(z.SCHEDULED, app_id) if not existing: path = path + '#' return path
29,981
def make_dirs(path): """ Create dir if path does not exist. :param str path: Directory path. """ if not os.path.isdir(path): os.makedirs(path, mode=0o777, exist_ok=True)
29,982
def get_provincial_miif_sets(munis): """ collect set of indicator values for each province, MIIF category and year returns dict of the form { 'cash_coverage': { 'FS': { 'B1': { '2015': [{'result': ...}] } } } } """ prov_sets = defaultdi...
29,983
def create_kernel(radius=2, invert=False): """Define a kernel""" if invert: value = 0 k = np.ones((2*radius+1, 2*radius+1)) else: value = 1 k = np.zeros((2*radius+1, 2*radius+1)) y,x = np.ogrid[-radius:radius+1, -radius:radius+1] mask = x**2 ...
29,984
def edimax_get_power(ip_addr="192.168.178.137"): """ Quelle http://sun-watch.net/index.php/eigenverbrauch/ipschalter/edimax-protokoll/ """ req = """<?xml version="1.0" encoding="UTF8"?><SMARTPLUG id="edimax"><CMD id="get"> <NOW_POWER><Device.System.Power.NowCurrent> </Device.System.Power.No...
29,985
def get_class_inst_data_params_n_optimizer(nr_classes, nr_instances, device): """Returns class and instance level data parameters and their corresponding optimizers. Args: nr_classes (int): number of classes in dataset. nr_instances (int): number of instances in dataset. device (str): d...
29,986
def inc(x): """ Add one to the current value """ return x + 1
29,987
def regionError(df, C, R): """Detects if a selected region is not part of one of the selected countries Parameters: ----------- df : Pandas DataFrame the original dataset C : str list list of selected countries R : str list list of selected regions R...
29,988
def lherzolite(): """ Elastic constants of lherzolite rock (GPa) from Peselnick et al. (1974), in Voigt notation - Abbreviation: ``'LHZ'`` Returns: (tuple): tuple containing: * C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``) * rho (float): Density (3270 ...
29,989
def int_to_bit(x_int, nbits, base=2): """Turn x_int representing numbers into a bitwise (lower-endian) tensor.""" x_l = tf.expand_dims(x_int, axis=-1) x_labels = [] for i in range(nbits): x_labels.append( tf.floormod( tf.floordiv(tf.to_int32(x_l), tf.to_int32(base...
29,990
def create_ldap_external_user_directory_config_content(server=None, roles=None, role_mappings=None, **kwargs): """Create LDAP external user directory configuration file content. """ entries = { "user_directories": { "ldap": { } } } entries["user_directories"]...
29,991
def fasta_iter(fh): """ Given a fasta file. yield tuples of header, sequence Clears description from seq name. From: https://www.biostars.org/p/710/ Updated: 11/09/2018 Version: 0.2 """ # ditch the boolean (x[0]) and just keep the header or sequence since # we know they alternate. faiter = (x[1] for x in gr...
29,992
def intersection(lst1, lst2): """! \details Finds hashes that are common to both lists and stores their location in both documents Finds similarity that is measured by sim(A,B) = number of hashes in intersection of both hash sets divided by minimum of the number of hashes in lst1 and lst2 \param l...
29,993
def apply_colour_to_surface(colour: pygame.Color, shape_surface: pygame.surface.Surface, rect: Union[pygame.Rect, None] = None): """ Apply a colour to a shape surface by multiplication blend. This works best when the shape surface is predominantly whit...
29,994
def allrad2(F_nm, hull, N_sph=None, jobs_count=1): """Loudspeaker signals of All-Round Ambisonic Decoder 2. Parameters ---------- F_nm : ((N_sph+1)**2, S) numpy.ndarray Matrix of spherical harmonics coefficients of spherical function(S). hull : LoudspeakerSetup N_sph : int Decod...
29,995
def run_algorithms(window, size, rows, algorithm, maze_type): """Runs the maze window, where the chosen algorithm can be executed""" grid = assets.board.make_grid(rows, size) if maze_type == "Random": grid = assets.maze.completely_random(grid) if maze_type == "Swirl": grid = assets.maz...
29,996
def match_histogram(reference, image, ref_mask=None, img_mask=None): """Match the histogram of the T2-like anatomical with the EPI.""" import os import numpy as np import nibabel as nb from nipype.utils.filemanip import fname_presuffix from skimage.exposure import match_histograms nii_img =...
29,997
def main(input_data_path, output_data_path, window): """ Convert the Volumetric CT data and mask (in NIfTI format) to a dataset of 2D images in tif and masks in bitmap for the brain extraction. """ # open data info dataframe info_df = pd.read_csv(os.path.join(input_data_path, 'info.csv'), index_col=...
29,998
def outfeed(token, xs): """Outfeeds value `xs` to the host. Experimental. `token` is used to sequence infeed and outfeed effects. """ flat_xs, _ = pytree.flatten(xs) return outfeed_p.bind(token, *flat_xs)
29,999