content
stringlengths
22
815k
id
int64
0
4.91M
def readremotenames(repo): """ read the details about the remotenames stored in .hg/logexchange/ and yields a tuple (node, remotepath, name). It does not yields information about whether an entry yielded is branch or bookmark. To get that information, call the respective functions. """ for ...
19,200
def only_t1t2(src, names): """ This function... :param src: :param names: :return: """ if src.endswith("TissueClassify"): # print "Keeping T1/T2!" try: names.remove("t1_average_BRAINSABC.nii.gz") except ValueError: pass try: ...
19,201
def distanceEucl(a, b): """Calcul de la distance euclidienne en dimension quelconque""" dist = np.linalg.norm(a - b) return dist
19,202
def main(): """ Program main """ options = docopt(__doc__) cmd = command.Command(options) for opt in options: if options[opt]: cmd(opt)
19,203
def _search(self, *query): """Search for a match between the query terms and a tensor's Id, Tag, or Description. https://github.com/OpenMined/PySyft/issues/2609 Note that the query is an AND query meaning that every item in the list of strings (query*) must be found somewhere on the tensor in order for it t...
19,204
def cli(ctx): """ Network objects. A Network resource can represent an IP Network and an IP Address. Working with networks is usually done with CIDR notation. Networks can have any number of arbitrary attributes as defined below. """
19,205
def _FindLockNames(locks): """ Finds the ids and descriptions of locks that given locks can block. @type locks: dict of locking level to list @param locks: The locks that gnt-debug delay is holding. @rtype: dict of string to string @return: The lock name to entity name map. For a given set of locks, some...
19,206
def test_md033_bad_inline_html_present(): """ Test to make sure we get the expected behavior after scanning a good file from the test/resources/rules/MD026 directory that has atx headings that do not end with punctuation. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ ...
19,207
def strip_directives(filename, filepath, outpath): """ Read in file, remove all preprocessor directives and output """ # r = re.compile(r"(^#.*$\n)") with open(os.path.join(filepath, filename)) as infile: txt = infile.read() outtxt = re.sub(r"(^#.*$\n)", '', txt, flags=re.M) ...
19,208
def runtime(command: list, show=True, env=None): """Runs the command and returns the runtime.""" print('START:', *command) t_start = time() if show: r = subprocess.run(command, env=env) else: r = subprocess.run(command, stdout=subprocess.PIPE, stderr=subpro...
19,209
def val2str(val): """Writes values to a string. Args: val (any): Any object that should be represented by a string. Returns: valstr (str): String representation of `val`. """ # Return the input if it's a string if isinstance(val,str ): valstr=val # Handle types where sp...
19,210
def save_device_information(device, **kwargs): """Show version to print information users interest Args: Mandatory: device (`obj`) : Device object. Returns: True: Result is PASSED Raises: None Example: >>> save_device_information(device=Device()) """ ...
19,211
def show_grades(grades, format): """ Show the grades received as argument in the format specified. :param grades: grades to show :param format: format of the output """ print('Assessment\'s grades') print(assessment_serializer.serialize_grades(grades, format) + "\n")
19,212
def configure_interface_switchport_mode(device, interface, mode): """ Configures switchport mode on interface Args: device ('obj') : device to use interface ('str') : interface to configure mode ('str') : interface mode Returns: None Ra...
19,213
def test_prepare_input(img, mocker): """Test image preparations.""" img_clone = torch.tensor((1, 3, 4, 4)) img_clone.clone = mocker.Mock(return_value=img) out = _prepare_input(img_clone) img_clone.clone.assert_called_once() img.detach.assert_called_once() img.to.assert_called_once() ass...
19,214
def use_low_level_network(query, env): """ Make a call for variables using the lower level network code """ records = get_block_of_records(query, env=env) process_records("Network example", records)
19,215
def showItems(category_name): """Pulls all the Categories, the specific Category selected by the user from the home page, all the items within that specific Category, and then counts the number of items. All this information is displayed on the items.html page. """ categories = session.query(Cat...
19,216
def date_ranges(): """Build date ranges for current day, month, quarter, and year. """ today = datetime.date.today() quarter = math.floor((today.month - 1) / 3) cycle = current_cycle() return { 'month': ( today.replace(day=1), today.replace(day=calendar.monthrange...
19,217
def FiskJohnsonDiscreteFuncBCKWD(r,F0,T): """Compute reverse Fourier-Bessel transformation via Fisk Johnson procedure. Compute reverse Fourier-Bessel transform (i.e. 0th order reverse Hankel transform) using a rapidly convergent summation of a Fourier-Bessel expansion fol...
19,218
def make_waterfall_horizontal(data, layout): """Function used to flip the figure from vertical to horizontal. """ h_data = list(data) h_data = [] for i_trace, trace in enumerate(list(data)): h_data.append(trace) prov_x = h_data[i_trace]['x'] h_data[i_trace]['x'] = list(h_data...
19,219
def parse_file(producer): """ Given a producer name, return appropriate parse function. :param producer: NMR machine producer. :return: lambda function that reads file according to producer. """ global path_to_directory return { "Agilent": (lambda: ng.agilent.read(dir=path_to_directo...
19,220
def print_glossary(): """ Added by Steven Combs. """ message = "*all-atom = in the case of sampling, synonymous with fine movements and often including side chain information; also referred to as high-resolution \n \ *benchmark = another word for a test of a method, scoring function, algorithm, etc. by...
19,221
def test_similar_pairs_gene_set(similarity_em): """Test defining a gene set for similar pairs.""" # Subsetting genes shouldn't change the results in this case. gene_set_1 = reversed([g for g in similarity_em.genes if int(g.name[-1]) in (0,2,4)]) sps = similarity_em.create_similar_pairs(0, 2, 512, 42, g...
19,222
def get_lon_dim_name_impl(ds: Union[xr.Dataset, xr.DataArray]) -> Optional[str]: """ Get the name of the longitude dimension. :param ds: An xarray Dataset :return: the name or None """ return _get_dim_name(ds, ['lon', 'longitude', 'long'])
19,223
def logout(): """Log out user.""" session.pop('eventbrite_token', None) return redirect(url_for('index'))
19,224
def search(query="", casesense=False, filterout=[], subscribers=0, nsfwmode=2, doreturn=False, sort=None): """ Search for a subreddit by name *str query = The search query "query" = results where "query" is in the name "*query" = results where "query" is at the end of the name "...
19,225
def is_xh(filename): """ Detects if the given file is an XH file. :param filename: The file to check. :type filename: str """ info = detect_format_version_and_endianness(filename) if info is False: return False return True
19,226
def is_parent_process_alive(): """Return if the parent process is alive. This relies on psutil, but is optional.""" parent_pid = os.getppid() if psutil is None: try: os.kill(parent_pid, 0) except OSError: return False else: return True else: ...
19,227
def validate_func_kwargs( kwargs: dict, ) -> Tuple[List[str], List[Union[str, Callable[..., Any]]]]: """ Validates types of user-provided "named aggregation" kwargs. `TypeError` is raised if aggfunc is not `str` or callable. Parameters ---------- kwargs : dict Returns ------- c...
19,228
def gen_test(): """ Test function used for debugging """ train_files, train_steering, train_flip_flags, valid_files, valid_steering, valid_flip_flags = organize_data() for i in range(2): # x, y, flip_flags = (next(generator_v2(valid_files, valid_steering, valid_flip_flags))) start_time = time.time() x, y = ...
19,229
def mni152_to_fslr(img, fslr_density='32k', method='linear'): """ Projects `img` in MNI152 space to fsLR surface Parameters ---------- img : str or os.PathLike or niimg_like Image in MNI152 space to be projected fslr_density : {'32k', '164k'}, optional Desired output density of ...
19,230
def parse_record(raw_record, _mode, dtype): """Parse CIFAR-10 image and label from a raw record.""" # Convert bytes to a vector of uint8 that is record_bytes long. record_vector = tf.io.decode_raw(raw_record, tf.uint8) # The first byte represents the label, which we convert from uint8 to int32 # an...
19,231
def create_sintel_submission(model, iters=32, warm_start=False, output_path='sintel_submission'): """ Create submission for the Sintel leaderboard """ model.eval() for dstype in ['clean', 'final']: test_dataset = datasets.MpiSintel(split='test', aug_params=None, dstype=dstype) flow_...
19,232
def makeSSHTTPClient(paramdict): """Creates a SingleShotHTTPClient for the given URL. Needed for Carousel.""" # get the "url" and "postbody" keys from paramdict to use as the arguments of SingleShotHTTPClient return SingleShotHTTPClient(paramdict.get("url", ""), paramdict.ge...
19,233
def getFiles(regex, camera, mjdToIngest = None, mjdthreshold = None, days = None, atlasroot='/atlas/', options = None): """getFiles. Args: regex: camera: mjdToIngest: mjdthreshold: days: atlasroot: options: """ # If mjdToIngest is defined, ignore ...
19,234
def chain(*args: GradientTransformation) -> GradientTransformation: """Applies a list of chainable update transformations. Given a sequence of chainable transforms, `chain` returns an `init_fn` that constructs a `state` by concatenating the states of the individual transforms, and returns an `update_fn` which ...
19,235
def test_usage_in_dict(): """Test usage_in_dict calculator""" # Tests with absolute moment data assert calculators.usage_in_dict(TEST_USAGE_IN_DICT) == TEST_USAGE_IN_DICT_RESULT assert calculators.usage_in_dict(TEST_USAGE_IN_DICT_2) == TEST_USAGE_IN_DICT_RESULT_2 # Tests with relative data ass...
19,236
def fibonacci_mult_tuple(fib0=2, fib1=3, count=10): """Returns a tuple with a fibonacci sequence using * instead of +.""" return tuple(fibonacci_mult_list(fib0, fib1, count))
19,237
def execute_in_process(f): """ Decorator. Execute the function in thread. """ def wrapper(*args, **kwargs): logging.info("Se ha lanzado un nuevo proceso") process_f = Process(target=f, args=args, kwargs=kwargs) process_f.start() return process_f return wrapper
19,238
def castep_spectral_dispersion(computer, calc_doc, seed): """ Runs a dispersion interpolation on top of a completed SCF calculation, optionally running orbitals2bands and OptaDOS projected dispersion. Parameters: computer (:obj:`matador.compute.ComputeTask`): the object that will be calling CASTEP....
19,239
def return_limit(x): """Returns the standardized values of the series""" dizionario_limite = {'BENZENE': 5, 'NO2': 200, 'O3': 180, 'PM10': 50, 'PM2.5': 25} return dizionario_limite[x]
19,240
def npaths(x, y): """ Count paths recursively. Memoizing makes this efficient. """ if x>0 and y>0: return npaths(x-1, y) + npaths(x, y-1) if x>0: return npaths(x-1, y) if y>0: return npaths(x, y-1) return 1
19,241
def sqlify(obj): """ converts `obj` to its proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) "'t'" >>> sqlify(3) '3' """ # because `1 == True and hash(1) == hash(True)` # we have to do this the hard way... if obj is None:...
19,242
def test_estimator_to_pfa_mixednb(dtypes): """Check that converted PFA is giving the same results as MixedNB""" X, y, types = _classification_task(dtypes=dtypes) is_nominal = [t == 'n' for t in dtypes] estimator = _mixednb(X, y, is_nominal=is_nominal, classes=['a', 'b', 'c']) pfa = sklearn_to_pfa(...
19,243
def create_results_dataframe( list_results, settings, result_classes=None, abbreviate_name=False, format_number=False, ): """ Returns a :class:`pandas.DataFrame`. If *result_classes* is a list of :class:`Result`, only the columns from this result classes will be returned. If ``N...
19,244
def set_config_values(): """ used to set the config values """ sed('/home/ubuntu/learning/learning/settings-production.py', "\[SERVER_NAME\]", host_name, backup='') sed('/home/ubuntu/learning/learning/settings.py', "\[SERVER_NAME\]", host_name, backup='') sed('/home/ubuntu/learn...
19,245
def get_first_model_each_manufacturer(cars=cars): """return a list of matching models (original ordering)""" first = [] for key,item in cars.items(): first.append(item[0]) return(first)
19,246
def white(*N, mean=0, std=1): """ White noise. :param N: Amount of samples. White noise has a constant power density. It's narrowband spectrum is therefore flat. The power in white noise will increase by a factor of two for each octave band, and therefore increases with 3 dB per octave. """ ...
19,247
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)): """Randomly crop src with size. Randomize area and aspect ratio""" h, w, _ = src.shape area = w*h for _ in range(10): new_area = random.uniform(min_area, 1.0) * area new_ratio = random.uniform(*ratio) new_w...
19,248
def analyze_subject(subject_id, A, B, spheres, interpolate, mask, data_dir=None): """ Parameters ---------- subject_id : int unique ID of the subject (index of the fMRI data in the input dataset) A : tuple tuple of (even_trials, odd_trials) for the first condition (A); even/o...
19,249
def joinAges(dataDict): """Merges columns by county, dropping ages""" popColumns = list(dataDict.values())[0].columns.tolist() popColumns = [re.sub("[^0-9]", "", column) for column in popColumns] dictOut = dict() for compartmentName, table in dataDict.items(): table.columns = popColumns ...
19,250
def plot_graph_route(G, route, bbox=None, fig_height=6, fig_width=None, margin=0.02, bgcolor='w', axis_off=True, show=True, save=False, close=True, file_format='png', filename='temp', dpi=300, annotate=False, node_color='#999999', node_...
19,251
def test_dwindle( size, row_limits, col_limits, distributions, weights, max_iter, best_prop, lucky_prop, crossover_prob, mutation_prob, shrinkage, maximise, ): """ Test that the default dwindling method does nothing. """ families = [edo.Family(dist) for dist in d...
19,252
def random_polynomialvector( secpar: int, lp: LatticeParameters, distribution: str, dist_pars: Dict[str, int], num_coefs: int, bti: int, btd: int, const_time_flag: bool = True ) -> PolynomialVector: """ Generate a random PolynomialVector with bounded Polynomial entries. Essentially just instanti...
19,253
def parse_module(file_name, file_reader): """Parses a module, returning a module-level IR. Arguments: file_name: The name of the module's source file. file_reader: A callable that returns either: (file_contents, None) or (None, list_of_error_detail_strings) Returns: (ir, debug_info, ...
19,254
def process_tocdelay(app, doctree): """ Collect all *tocdelay* in the environment. Look for the section or document which contain them. Put them into the variable *tocdelay_all_tocdelay* in the config. """ for node in doctree.traverse(tocdelay_node): node["tdprocessed"] += 1
19,255
def get_glare_value(gray): """ :param gray: cv2.imread(image_path) grayscale image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) :return: numrical value between 0-256 which tells the glare value """ blur = cv2.blur(gray, (3, 3)) # With kernel size depending upon image size mean_blur = cv2....
19,256
def pname(name): """Prints a name out with apple at the end""" try: res = print_name(name) click.echo(click.style(res, bg='blue', fg='white')) except TypeError: click.echo("Must pass in Name")
19,257
def print_result(result_list): """ # printing the result in console """ print("IP\t\t\tMAC ADDRESS\n..........................................................................") for client in result_list: print(client["ip"]+"\t\t"+client["mac"])
19,258
def makeCrops(image, stepSize, windowSize, true_center): """ """ image = image.type(torch.FloatTensor) crops = [] truths = [] c_x, c_y, orient = true_center # TODO: look into otdering, why it's y,x ! margin = 15 # --> is x, but is the column # to slide horizontally, y must come f...
19,259
def generate_n_clusters(object_generator, n_clusters, n_objects_per_cluster, *, rng=None): """ Creates n_clusters of random objects """ rng = np.random.default_rng(rng) object_clusters = [] for i in range(n_clusters): cluster_objects = generate_random_object_cluster(n_objects_per_cluster, object...
19,260
def move_process_data_to_store(repo_path: str, *, remote_operation: bool = False): """Move symlinks to hdf5 files from process directory to store directory In process writes never directly access files in the data directory. Instead, when the file is created is is symlinked to either the remote data or...
19,261
async def run_server(port): """ The main entry point for the server. """ base_context = ConnectionContext() async def responder(conn, recv_channel): """ This task reads results from finished method handlers and sends them back to the client. """ async for request, result in recv_cha...
19,262
def collect(val, collections, default_collections): """Adds keys to a collection. Args: val: The value to add per each key. collections: A collection of keys to add. default_collections: Used if collections is None. """ if collections is None: collections = default_collections for key in coll...
19,263
def disp2vel(wrange, velscale): """ Returns a log-rebinned wavelength dispersion with constant velocity. This code is an adaptation of pPXF's log_rebin routine, simplified to deal with the wavelength dispersion only. Parameters ---------- wrange: list, np.array or astropy.Quantity Inpu...
19,264
def relabel(labels): """ Remaps integer labels based on who is most frequent """ uni_labels, uni_inv, uni_counts = np.unique( labels, return_inverse=True, return_counts=True ) sort_inds = np.argsort(uni_counts)[::-1] new_labels = range(len(uni_labels)) uni_labels_sorted = uni_lab...
19,265
def before_call_example(f, *args, **kwargs): """before_call decorators must always accept f, *args, **kwargs""" print("This is function before_call_example")
19,266
def test_plot(): """Ensure that the plot_micostructures function is run during the tests. """ plot_microstructures(np.arange(4).reshape(2, 2), titles=["test"]) plot_microstructures(np.arange(4).reshape(2, 2), titles="test") plot_microstructures(np.arange(4).reshape(2, 2))
19,267
def precision_at_threshold( weighted_actual_names: List[Tuple[str, float, int]], candidates: np.ndarray, threshold: float, distances: bool = False, ) -> float: """ Return the precision at a threshold for the given weighted-actuals and candidates :param weighted_actual_names: list of [name, w...
19,268
def test_unpack_two_distinct_sets_zip(zip_file_contents: List[Path], test_output_dirs: OutputFolderForTests) -> None: """ Test that a zip file containing two distinct set of files in two folders, but possibly in a series of nesting folders, can be extracted into a folder containing only the files. :par...
19,269
def task_set(repo: Repo, task: Task, args: list, quiet, force): """ set parameters of task, multiple key=value pairs allowed""" try: d = dict(arg.split('=') for arg in args) except ValueError: raise click.BadArgumentUsage('Wrong format for key=value argument') task.upgrade_task() # bump...
19,270
def alias(*alias): """Select a (list of) alias(es).""" valias = [t for t in alias] return {"alias": valias}
19,271
def eval_agent(sess, env, agent): """Evaluate the RL agent through multiple roll-outs. Args: * sess: TensorFlow session * env: environment * agent: RL agent """ reward_ave_list = [] for idx_rlout in range(FLAGS.nb_rlouts_eval): state = env.reset() rewards = np.zeros(FLAGS.rlout_len) tf.log...
19,272
def create_blueprint(request_manager): """ Creates an instance of the blueprint. """ blueprint = Blueprint('requests', __name__, url_prefix='/requests') # pylint: disable=unused-variable @blueprint.route('<request_id>/state') def get_state(request_id): """ Retrieves the stat...
19,273
def parse_smyle(file): """Parser for CESM2 Seasonal-to-Multiyear Large Ensemble (SMYLE)""" try: with xr.open_dataset(file, chunks={}, decode_times=False) as ds: file = pathlib.Path(file) parts = file.parts # Case case = parts[-6] # Extract the ...
19,274
def get_shape(grid, major_ticks=False): """ Infer shape from grid Parameters ---------- grid : ndarray Minor grid nodes array major_ticks : bool, default False If true, infer shape of majr grid nodes Returns ------- shape : tuple Shape of grid ndarray ...
19,275
def lorentz_force_derivative(t, X, qm, Efield, Bfield): """ Useful when using generic integration schemes, such as RK4, which can be compared to Boris-Bunemann """ v = X[3:] E = Efield(X) B = Bfield(X) # Newton-Lorentz acceleration a = qm*E + qm*np.cross(v,B) ydot = np.concaten...
19,276
def test_pytest_sessionfinish(mocked_session): """Test sessionfinish with the configured RP plugin. :param mocked_session: pytest fixture """ mocked_session.config.py_test_service = mock.Mock() mocked_session.config.option.rp_launch_id = None pytest_sessionfinish(mocked_session) assert mock...
19,277
def copy_rate(source, target, tokenize=False): """ Compute copy rate :param source: :param target: :return: """ if tokenize: source = toktok(source) target = toktok(target) source_set = set(source) target_set = set(target) if len(source_set) == 0 or len(target_se...
19,278
def set_maya_transform_attrs(dson_node, mesh_set): """ Record where this transform came from. This makes it easier to figure out what nodes are in later auto-rigging. """ if not dson_node.maya_node: return assert dson_node.maya_node.exists(), dson_node maya_node = dson_n...
19,279
def read_json_info(fname): """ Parse info from the video information file. Returns: Dictionary containing information on podcast episode. """ with open(fname) as fin: return json.load(fin)
19,280
def user_set(): """Sets user.""" global user_name global user_color user_name = name_input.get() user_color = color_input.get() window.destroy()
19,281
def check_subman_version(required_version): """ Verify that the command 'subscription-manager' isn't too old. """ status, _ = check_package_version('subscription-manager', required_version) return status
19,282
def compile_index_template(version_numbers): """Compiles the index""" template = JINJA_ENV.get_template('index.html.j2') rendered_template = template.render( version_numbers=version_numbers ) with open( os.path.join(VERSION_FILES_DIR, '..', 'index.html'), 'w+' ) as final_...
19,283
def create_output_directory(input_directory): """Creates new directory and returns its path""" output_directory = '' increment = 0 done_creating_directory = False while not done_creating_directory: try: if input_directory.endswith('/'): output_directory = input_di...
19,284
def test_list_unsigned_long_max_length_3_nistxml_sv_iv_list_unsigned_long_max_length_4_4(mode, save_output, output_format): """ Type list/unsignedLong is restricted by facet maxLength with value 8. """ assert_bindings( schema="nistData/list/unsignedLong/Schema+Instance/NISTSchema-SV-IV-list-unsi...
19,285
def bigsegment_twocolor(rows, cols, seed=None): """ Form a map from intersecting line segments. """ if seed is not None: random.seed(seed) possible_nhseg = [3,5] possible_nvseg = [1,3,5] gap_probability = random.random() * 0.10 maxdim = max(rows, cols) nhseg = 0 nvseg...
19,286
def first_order_smoothness_loss( image, flow, edge_weighting_fn): """Computes a first-order smoothness loss. Args: image: Image used for the edge-aware weighting [batch, height, width, 2]. flow: Flow field for with to compute the smoothness loss [batch, height, width, 2]. edge_weighting_f...
19,287
def where_is_my_birthdate_in_powers_of_two(date: int) -> int: """ >>> where_is_my_birthdate_in_powers_of_two(160703) <BLANKLINE> Dans la suite des <BLANKLINE> 0 1 3 765 2 , 2 , 2 , …, 2 <BLANKLINE> Ta date de naissance apparaît ici!: <BLANKLINE> …568720026062381...
19,288
def make_df_health_all(datadir): """ Returns full dataframe from health data at specified location """ df_health_all = pd.read_csv(str(datadir) + '/health_data_all.csv') return df_health_all
19,289
def _test_op1(ufunc, almost=False, cmp_op=False, ktol=1.0): """ General framework for testing unary operators on Xrange arrays """ # print("testing function", ufunc) rg = np.random.default_rng(100) n_vec = 500 max_bin_exp = 20 # testing binary operation of reals extended arrays ...
19,290
def run(): """This client pushes PE Files -> ELS Indexer.""" # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Test out PEFile -...
19,291
def lothars_in_cv2image(image, lothars_encoders,fc): """ Given image open with opencv finds lothars in the photo and the corresponding name and encoding """ # init an empty list for selfie and corresponding name lothar_selfies=[] names=[] encodings=[] # rgb image rgb = cv2....
19,292
def approx_nth_prime_upper(n): """ approximate upper limit for the nth prime number. """ return ceil(1.2 * approx_nth_prime(n))
19,293
def wavelength_to_velocity(wavelengths, input_units, center_wavelength=None, center_wavelength_units=None, velocity_units='m/s', convention='optical'): """ Conventions defined here: http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html * Radio V = c (c/l0 - c/l)/(c/l0) f(V) = (c/l0) ( 1...
19,294
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template sensors.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config))
19,295
def gen_api_json(api): """Apply the api literal object to the template.""" api = json.dumps( api, cls=Encoder, sort_keys=True, indent=1, separators=(',', ': ') ) return TEMPLATE_API_DEFINITION % (api)
19,296
def get_massage(): """ Provide extra data massage to solve HTML problems in BeautifulSoup """ # Javascript code in ths page generates HTML markup # that isn't parsed correctly by BeautifulSoup. # To avoid this problem, all document.write fragments are removed my_massage = copy(BeautifulSoup....
19,297
def generate_test_images(): """Generate all test images. Returns ------- results: dict A dictionary mapping test case name to xarray images. """ results = {} for antialias, aa_descriptor in antialias_options: for canvas, canvas_descriptor in canvas_options: for fu...
19,298
def registered_metrics() -> Dict[Text, Type[Metric]]: """Returns standard TFMA metrics.""" return copy.copy(_METRIC_OBJECTS)
19,299