content
stringlengths
22
815k
id
int64
0
4.91M
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the London Air sensor.""" data = APIData() data.update() sensors = [] for name in config.get(CONF_LOCATIONS): sensors.append(AirSensor(name, data)) add_entities(sensors, True)
5,305,300
def get_sklearn_primitives_names(): """Helper to return names of all sklearn primitives.""" return [x for x in get_primitive_names() if ".SKlearn" in x]
5,305,301
def get_users(): """Retrieve information about users""" return "get users"
5,305,302
def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn): """Upgrade a SAM group. :param samldb: SAM database. :param gid: Group GID :param sid_name_use: SID name use :param nt_name: NT Group Name :param comment: NT Group Comment :param domaindn: Domain DN ""...
5,305,303
def plot_obs(prepped_data, variable, outfile, partition="trn"): """ plot training observations :param prepped_data: [str] path to npz file of prepped data :param variable: [str] which variable to plot, 'flow' or 'temp' :param outfile: [str] where to store the resulting file :return: None """...
5,305,304
def version(silent=False): """NeuroKit2's version. This function is a helper to retrieve the version of the package. Examples --------- >>> import neurokit2 as nk >>> >>> nk.version() """ if silent is False: print( "- OS: " + platform.system(), "(" ...
5,305,305
def _str_to_type(content: str) -> Any: """Get skl2onnx type by string. This is used to parse model defintion to skl2onnx I/O Parameters ---------- content: str The key representation of type. Returns ---------- Any: The type of the string key. """ content = con...
5,305,306
def create_connection(): """ Do tests related to DBTools Connections - Create Connection - Get created connection - Validate Connection. This makes sure that we can use this connection to connect to the ADB-S. """ global connection_id, password_secret_id, vault_key_id print("===DBTools S...
5,305,307
def parse_tls_extension(data): """ This parses one extension from the given data (which may contain multiple extension records). :returns: parsed object along with unparsed data :rtype: 2-element tuple containing a `py:TlsExtension` object and the remaining data which has not yet been parsed """ t = data[0:2]...
5,305,308
def get_postgres_curie_prefix(curie): """The representation in postgres moves things to lowercase, and replaces . with _""" if ':' not in curie: raise ValueError(f'Curies ought to contain a colon: {curie}') prefix = curie.lower().split(':') prefix = '_'.join(prefix[0].split('.')) return pref...
5,305,309
def extract_svc2_features(trace): """ Extract all of the features for the svc model in the [svc.py](../attacks/svc.py) file. @param trace is a trace of loading a web page in the following format `[(time, incoming)]` where outgoing is 1 is incoming and -1 """ features = [] get_packet_st...
5,305,310
def node_attribute_writer(model, target, value): """Write ``value`` to ``target`` node.attrs key on ``model``. """ model.attrs[target] = value
5,305,311
def parse_stations(html): """ Strips JS code, loads JSON """ html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '') html = json.loads(html) return html['suggestions']
5,305,312
def read_template(sitename, docname): """get the source of a specific template""" # moet eigenlijk met read_data maar dan moet ik die eerst geschikt maken with (WEBROOT / sitename / '.templates' / docname).open() as f_in: data = ''.join(f_in.readlines()).replace('\r\n', '\n') return data
5,305,313
def _load_dataset(): """Load data and tidy it a bit""" fnirs_data_folder = mne.datasets.fnirs_motor.data_path() fnirs_raw_dir = os.path.join(fnirs_data_folder, 'Participant-1') raw_intensity = mne.io.read_raw_nirx(fnirs_raw_dir, verbose=True).load_data() raw...
5,305,314
def boxplot( data, order=None, colors=None, at=None, ax=None, showfliers=False, capprops=dict(linewidth=0), boxprops=dict(linewidth=1, linestyle='-'), medianprops=dict(linewidth=2, color='k'), whiskerprops=dict(linewidth=1, linestyle='-'), **box_args ): """Boxplot. ...
5,305,315
def peer(socket_path=None): """ >>> p.peer() >>> try: >>> p.startup() >>> # do something with p >>> finally: >>> p.shutdown() or >>> with peer() as p: >>> # do something with p >>> """ if socket_path not in _instances: _instances[socket_path] = UBusPeer(socket_path) return _instances[s...
5,305,316
def train_images(size,num,learning_rate,layers): """ Trains the neural net for num batches of size number of images in each """ count = 0 os.chdir('..') root = os.getcwd() answer_array = read_answers() average_error = 0 global batches global network if network is None: ...
5,305,317
def actors(request): """ Return list of actors for datalist in app.js. View isn't rendered; only used to return json to app.js. """ search_for = request.GET.get('name', default='').lower() LIMIT = 20 actor_list = [] actors = Name.objects.filter( Q(lowercase_name__startswith=sea...
5,305,318
def get_opt_d(series, ds=None, lag=1, thres=1e-5, max_size=10000, p_thres=1e-2, autolag=None, verbose=1, **kwargs): """Find minimum value of degree of stationary differntial Args: series (pd.Series) ds (array-like, optional): Defaults to np.linspace(0, 1, 100)\ Search ...
5,305,319
def agentPortrayal(agent): """ Función que define como se visualizarán los agentes en pantalla Parámetros: agent - agente(s) que se visualizarán Retorno: portrayal - diccionario con las especificaciones de como se visualizarán los agentes """ portrayal = { "Filled": "tr...
5,305,320
def transform_image_batch(image_batch, input_meta_type, output_meta_type): """.""" output_batch = np.empty(image_batch.shape, dtype=output_meta_type.dtype) for i in range(len(image_batch)): image_with_meta = add_meta_to_image(image_batch[i], meta_type=input_meta_type) output_batch[i] = trans...
5,305,321
def assemble_exterior_slave_facets(b: 'numpy.ndarray[_PETSc.ScalarType]', kernel: ffi.CData, facet_info: 'numpy.ndarray[numpy.int32]', mesh: Tuple['numpy.ndarray[numpy.int32]', 'numpy.ndarray[numpy.int32]', ...
5,305,322
def enrich_structured_wildcat( wildcat: MWC, prestructured_obj_dict: ty.Mapping[ty.Any, ty.Any], Type: type ): """A Wildcat is a Cat (an attrs class) that additionally allows arbitrary key-value access as though it were a dict for data that does not have a defined attribute name on the class (i.e. is no...
5,305,323
def json_to_str(json_obj): """JSONをstr型へ変換""" return json.dumps(json_obj, separators=(",", ":"), ensure_ascii=False)
5,305,324
def get_color(orig_label=None, gt_label=None, target_label=None, adv_label=None, targeted_attack=False): """Get color according to different possible correctness combinations.""" if ((gt_label is None or orig_label == gt_label) and (adv_label is None or ...
5,305,325
def __get_params(ctx): """ Get parameters from config file. :param click.core.Context ctx: Context object of click. :return: parameters :rtype LogParam """ # load parameters from ini file p = params.LogParam() ret = p.read_ini() if not ret: click.echo('ログ取得に使用するパラメータを設定して...
5,305,326
def _create_sub_keys( spec: config_pb2.MetricsSpec ) -> Dict[Optional[metric_types.AggregationType], List[Optional[metric_types.SubKey]]]: """Creates sub keys per aggregation type.""" result = {} if spec.HasField('binarize'): sub_keys = [] if spec.binarize.class_ids.values: for v in sp...
5,305,327
def int2bytes(integer_number: int) -> bytes: """整数还原为原始的二进制字节流, 默认方式: 大端, 和struct功能一致 还原方式从高位按位截取 """ hex_str = int2hex(integer_number) if len(hex_str) % 2 != 0: hex_str = '0%s' % hex_str return binascii.a2b_hex(hex_str)
5,305,328
def pin_window(identifier): """pin window with text <s> in title or handle <n> to all desktops (short: /pwh).""" command([EXE, f'-PinWindow:{identifier}'])
5,305,329
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `VerbaAnonymousUser` is returned. """ user = None try: user_id = request.session[SESSION_KEY] token = request.session[AUTH_TOKEN_SESSION_KE...
5,305,330
def set_mode(): """ Select the game mode """ # This is an error checking version of reading user input # This will be explained in class - pay attention!! # Understanding try/except cases is important for # verifying user input # handle game crashing try: app.write("Please select a s...
5,305,331
def get_comment(pk): """ This method returns a comment by its id. """ try: return Comment.objects.get(pk=pk) except Comment.DoesNotExist: raise NotFound({"error": "Comment not found."})
5,305,332
def _plot_data_to_ax( data_all, ax1, e_unit=None, sed=True, ylabel=None, ulim_opts={}, errorbar_opts={}, ): """ Plots data errorbars and upper limits onto ax. X label is left to plot_data and plot_fit because they depend on whether residuals are plotted. """ if e_unit is...
5,305,333
def inverse_multi_quadratic_rbf(r, kappa): """ Computes the Inverse-Multi-Quadratic Radial Basis Function between two points with distance `r`. Parameters ---------- r : float Distance between point `x1` and `x2`. kappa : float Shape parameter. Returns -----...
5,305,334
def clean_list(dirtylist): """Takes a list of algorithm names as the user put them in. Turns abbreviations in to their non-abbreviated form. Returns a list of the corresponding encoders or encrypters in the same order as given in the input list. Returns an empty list if any of the input...
5,305,335
def _download_RegNetwork( root_dir: Optional[Path] = None, network_type: str = "human" ) -> str: """ Downloads RegNetwork regulatory interactions to the root directory. Returns the filepath. :param root_dir: Path object specifying the location to download RegNetwork to. Default is None which downloads ...
5,305,336
def search_phase(args, base_dir, run_id): """Performs NAS. Code is mostly copied from train_search.py but modified to only work with GAEA PC-DARTS. Best genotype is selected according to training accuracy for single-level search and according to validation accuracy for bi-level search. Args: ...
5,305,337
def days_between(T_begin, T_end): """ 格式如下 :param T_begin: 2018-01-01 :param T_end: 2018-01-01 :return: """ b = datetime.strptime(T_begin, time_format) e = datetime.strptime(T_end, time_format) return (e - b).days
5,305,338
def draw_in_svg_y(file_name, num_max, len, new_data): """图纸大小100*120""" fig = plt.figure(figsize=(100,120)) print('正在Y方向画图...') for i in range(len): """图共6行5列""" ax = fig.add_subplot(6, 5, i + 1) draw(num_max, len, new_data[::,i,::],ax) plt.xlim(-25, 25) plt.ylim(...
5,305,339
def createFirstJob(command, config, memory=None, cpu=None, time=sys.maxint): """Adds the first job to to the jobtree. """ logger.info("Adding the first job") if memory == None or memory == sys.maxint: memory = float(config.attrib["default_memory"]) if cpu == None or cpu == sys.maxint: ...
5,305,340
def read_cpr(path): """Read and parse a CPR file. Return masks, which are (id, RLE data). Note: Python 3.6.4 docs say its XML module is not secure, se we use regexp. """ # Example: <Mask id="123">[12 34 56]</Mask> mask_pattern = r'<Mask\s.*?id="(.*?)".*?>.*?\[(.*?)\].*?</Mask>' text = path.read...
5,305,341
def category_from_dict(category_dictionary: dict): """ The method converts a dictionary of Category to a Category object. :param category_dict: A dictionary that contains the keys of a Category. :type category_dict: dict :rtype: ibmpairs.catalog.Category :raises ...
5,305,342
def test_P(): """ Test locations of fibers in the range P1-1 to P2-12 """ fib = Fiber("P3-1") # self.assertRaises(NameError == pytest.approx( fib.labAngle) with pytest.raises(NameError): fib.labAngle() fib = Fiber("P2-0") # self.assertRaises(NameError == pytest.approx( fib.labAngle) ...
5,305,343
def schaffer6(phenome): """The bare-bones Schaffer function 6.""" sum_of_squares = phenome[0] ** 2 + phenome[1] ** 2 result = math.sin(math.sqrt(sum_of_squares)) ** 2 - 0.5 result /= (1.0 + 0.001 * sum_of_squares) ** 2 result += 0.5 return result
5,305,344
def load_lmc_data(): """ Return LMC star formation history per unit steradian Returns ------- lmc_sfh : np structured array LMC star formation history dtype: [('region','<S10'), ('log_age','<f8'), ('sfh_z008','<f8'), ('sfh_z004','<f8'), ...
5,305,345
def save_final_score_data(data: pd.DataFrame) -> None: """Save final result of Swiss Super League for seasons. Args: data (pd.DataFrame): The dataframe to save. Examples: >>> ssl_data_final = get_final_score_data(['2019-2020', '2020-2021']) >>> save_final_score_data(ssl_data_final)...
5,305,346
def log(message: str, level: int = logging.INFO): """Produce a logging message.""" logger.log(level, message)
5,305,347
def pseudo(flight_data_df, mass, ke, kd, v0, dt=1./25, release_frame=0, units=Units.KM_PER_HOUR): """Return a dataframe of pseudo airspeed and angle given an input dataframe with watts and rise Parameters ---------- flight_data_df: pandas.DataFrame Must have frame, rise, and watts columns conta...
5,305,348
def n_7(x): """Max z_0.5c, z_LE, or z_TE of wing at centreline""" # z_max(LE/TE) = z + abs(c_0/2 * tan(twist_0)) z_le_te = x[1] + np.abs(x[2] / 2 * np.tan(np.radians(x[4]))) # z_max_50% chord = z + 0.5 * t/c * c z_50 = x[1] + 0.5 * x[3] * x[2] # Check if diamond centre is higher than LE/TE ...
5,305,349
def dateobs2night(dateobs): """ Convert DATE-OBS ISO8601 UTC string to YEARMMDD int night of KPNO sunset """ # use astropy to flexibily handle multiple valid ISO8601 variants from astropy.time import Time try: mjd = Time(dateobs).mjd except ValueError: #- only use optional de...
5,305,350
def write_fm_rectangle(path: StrOrPath, dx: Num, dy: Num, x0: Num = 0, x1: Num = 18, y0: Num = 1, y1: Num = 5) -> AnyByStrDict: """Create a rectangular Delft3D flexible mesh grid...
5,305,351
def take_before_exclusive(iterable, predicate): """Yield items up to but excluding including the first match. If no matching item is present, the result is empty. Args: iterable: An iterable series of items. predicate: A function of one argument used to select the last item. Returns:...
5,305,352
def save_config(config: ConfigDict, file: PathLike, Dumper=NXCLDumper, **yaml_kwargs): """ Save config to file. """ yaml_kwargs.setdefault("sort_keys", False) path = Path(file).expanduser() with path.open("w") as f: yaml.dump(config, f, Dumper=Dumper, **yaml_kwargs)
5,305,353
def root_graphql_schema_query(): """ Get the graphql schema. Dig up the introspection query string from file, run it through graphql, and jsonify the result. """ return flask.send_file(flask.current_app.schema_file)
5,305,354
def test_corrupted_file_in_a_directory_is_downloaded_again(mock_dataset_files, dataset_in_fire, fs): """ When the file has been downloaded incorrectly into a directory previously, then it is re-downloaded again. I don't think this happens too often, because an incorrectly downloaded file is always removed ...
5,305,355
def write_vol(model, file_name, data_label, nsteps, file_format): """ Writes out the model as a 3d volume grid Parameters ---------- model : GeologicalModel object Geological model to export file_name : string Name of file that model is exported to, including path, but without t...
5,305,356
def kolibri_version(): """ Returns the major.minor version of Kolibri if it exists """ with open(os.path.join(kolibri_dir, 'VERSION'), 'r') as version_file: # p4a only likes digits and decimals return version_file.read().strip()
5,305,357
def GetJSONRPCCallerIP(): """Retrieve the IP address of the JSON RPC caller. This is a hack that depends on the implementation details of jsonrpclib. We know that JSON-RPC over HTTP requires a SimpleHTTPServer and SimpleJSONRPCRequestHandler dervies from SimpleXMLRPCRequestHandler, which derives from BaseHTT...
5,305,358
def add_default_themes(apps, schema_editor): """add light and dark themes""" db_alias = schema_editor.connection.alias theme_model = apps.get_model("bookwyrm", "Theme") theme_model.objects.using(db_alias).create( name="BookWyrm Light", path="css/themes/bookwyrm-light.scss", ) the...
5,305,359
def _start_redis_instance(executable, session_dir_path, bind_address, port, redis_max_clients=None, num_retries=20, stdout_file=None, stde...
5,305,360
def timestamp_to_datetime(timestamp): """ Parses the given timestamp. The expected timestamp formats are the following: - `2019-04-28T15:14:38+00:00` - `2019-07-17T18:52:50.758993+00:00` - `2019-07-17T18:52:50.758000+00:00` Discord might give timestamps with differe...
5,305,361
def package_versions(): """ Gives version information for dependent packages. returns namedtuple BasemapPackageVersions """ from collections import namedtuple from sys import version as sys_version from matplotlib import __version__ as matplotlib_version from numpy import __version__ a...
5,305,362
def build_received_request(qparams): """"Fills the `receivedRequest` part with the request data""" request = { 'meta': { 'requestedSchemas' : build_requested_schemas(qparams), 'apiVersion' : None, }, # 'query': None } return request
5,305,363
def stdoutpath(): """ Path to output logfile. Returns ------- stdout : str Path to ouput file. """ stdoutfile=pdbid()+".stdout.log" stdout = os.path.join(output_dir(), stdoutfile) return stdout
5,305,364
def stop_terminals(apps: tuple = ("iterm", "terminal")) -> NoReturn: """Stops background processes. Args: apps: Default apps that have to be shutdown when ``deep`` argument is not set. """ for proc in psutil.process_iter(): if any(word in proc.name().lower() for word in apps): ...
5,305,365
def _read_static_tables_eia() -> Dict[str, pd.DataFrame]: """Build dataframes of static EIA tables for use as foreign key constraints. There are many values specified within the data that are essentially constant, but which we need to store for data validation purposes, for use as foreign keys. E.g. t...
5,305,366
def test_generate_streaming_meta_knowledge_graph_via_saved_file(): """ Test generate meta knowledge graph operation... MetaKnowledgeGraph as streaming Transformer.transform Inspector """ input_args = { "filename": [ os.path.join(RESOURCE_DIR, "graph_nodes.tsv"), os.pa...
5,305,367
def test_is_matrix_with_fractional_values_and_unitary_sums(): """Test a non-permutation matrix with fractional values that passes the unitary sum check.""" mat = np.array([[0.5, 0.5], [0.5, 0.5]]) np.testing.assert_equal(is_permutation(mat), False)
5,305,368
def build_filters(tbinfogolden): """ Build for each tb in tbinfo a filter """ filter_return = [] """Each assembler string""" for tb in tbinfogolden["assembler"]: tb_filter = [] """remove first split, as it is empty""" split = tb.split("[ ") """For each line""" ...
5,305,369
def init_dml_stmt( ir_stmt: irast.MutatingStmt, *, ctx: context.CompilerContextLevel, parent_ctx: context.CompilerContextLevel, ) -> DMLParts: """Prepare the common structure of the query representing a DML stmt. Args: ir_stmt: IR of the DML statement. Returns: ...
5,305,370
def DeriveTargetEdge(inp_edge_set): """ the random index will be between 1 to n where n is the set cardinality set does not support indexing so we have to pop the edges one by one until we obtain the desired edge """ # comment - sourya """ rand_index = random.randint(1, len(inp_edge_set)) if (DEBUG_LEVEL...
5,305,371
def extraction(args, companies): """ Launches extraction(s). ----- :param <args>: string ; arguments passed through the command line :param <companies>: list ; list of company tickers """ if len(args.firms) != 0: if args.replace: companies = args.firms else: companies.extend(args.firms) if args.conc...
5,305,372
def ca_stc_get_digest_name_by_id(slot, digest_id): """ Get name of digest by its ID :param slot: slot id :param digest_id: digest id :return: digest name """ h_slot = CK_SLOT_ID(slot) c_digest_id = CK_ULONG(digest_id) c_name_len = CK_BYTE(CRYPTO_NAME_BUFFER_SIZE) c_name = (CK_CH...
5,305,373
def data_root_directory(): """Get a path to the top level data directory. Checks whether you have created the local store of data at the expected location and returns that as default if found, otherwise returns the location on the shared folder Returns: (pathlib Path): A path """ return Pa...
5,305,374
def camera_to_image_space( points: torch.Tensor, focal_x: float, focal_y: float, center_x: float, center_y: float, flip_h: bool = True, height: Optional[int] = None, device: Optional[torch.device] = None, _validate_args: bool = True ) -> torch.Tensor: """Transform 3D points in camera space to image ...
5,305,375
def _compute_average_ranks( matrix, threshold=0.001, precision=4, higher_is_better=True, ): """Compute the average rank of each method. Input ----- matrix : pd.DataFrame Rows are datasets, columns are methods, and values are the compared metric. threshold : float The...
5,305,376
def get_devices(db: Session, skip: int = 0, limit: int = 100): """ Get Device list (default: up to 100 devices) """ return ( db.query(models.Device) .order_by(asc(models.Device.id)) .offset(skip) .limit(limit) .all() )
5,305,377
def _swap_log_prob_and_maybe_grads( pre_swap_replica_results, post_swap_replica_states, inner_kernel, ): """Swap 'target_log_prob' and maybe 'grads_target_log_prob'. After swapping states, the log probs for replicas need to be evaluated at the new points, then tempered. The easiest way to do this is ...
5,305,378
def usermodel_change_form(model, additional_fields): """ Read: https://github.com/openwisp/openwisp-users/blob/master/README.rst#usermodel_change_form """ # Change form fieldsets for field in additional_fields: fieldsets = model.fieldsets[1][1]['fields'][:] model.fieldsets[1][1]...
5,305,379
def exp(x): # real signature unknown; restored from __doc__ """ exp(x) Return the exponential value e**x. """ pass
5,305,380
def shapes_to_labels_masks(img_shape, shapes, label_name_to_value): """Converting shapes in json generated by Labelme to masks and class ids Args: img_shape: Size of mask (height, width) shapes: list of labels and points [{"label":"mouse", "points": [[x1,y1], [x2,y2]...]}, ...
5,305,381
def read_gpm(infile): """ READ_GPM Read HDF5 GPM file with these parameters: - dataQuality - landSurfaceType - flagPrecip - flagBB - heightBB - widthBB - qualityBB - typePrecip - qualityTypePrecip - zFactorCorrected It will reverse direction along the beam for re...
5,305,382
def get_host_name() -> str: """Get the host name. :return: A string value. """ return re.sub(r"\.(?:local|lan)", "", socket.gethostname())
5,305,383
def read_data(data_path): """This function reads in the histogram data from the provided path and returns a pandas dataframe """ gwas_df = pd.read_csv(data_path) return gwas_df
5,305,384
def _second_pass_to_resolve_resulting_class_of_specified_for( symbol_table: SymbolTable, ) -> None: """ Resolve the resulting class of the ``specified_for`` in-place. This is done both for properties and for methods. """ for symbol in symbol_table.symbols: if isinstance(symbol, Enumerat...
5,305,385
def fix_hyphen_commands(raw_cli_arguments): """Update options to match their module names with underscores.""" for i in ['gen-sample', 'run-python', 'run-stacker']: raw_cli_arguments[i.replace('-', '_')] = raw_cli_arguments[i] raw_cli_arguments.pop(i) return raw_cli_arguments
5,305,386
def pspnet(input_size: int, num_classes: int, loss, channels: int = 3) -> Tuple[Model, str]: """ Pyramid Scene Parsing Network https://arxiv.org/abs/1612.01105 https://hszhao.github.io/projects/pspnet/ https://github.com/Vladkryvoruchko/PSPNet-Keras-tensorflow """ inputs = Input((input_size...
5,305,387
def get_data_types(nb_sensors): """ What should be the data type for each sensor (1 - integer, 2 - float) Input nb_sensors -> how many sensors (int) Output data_type_per_sensor -> list of data types for each sensor """ print("Choose data type for each sensor: 1-integer...
5,305,388
def cpgrid_to_rg( volume: xr.Dataset, xyzcorn_df: pd.DataFrame, mapping_dims: Sequence[str] = ("xline", "iline"), depth_dim: Union[str, None] = None, buffer: int = 0, srate: float = 0.1, client: Union[None, Client] = None, ) -> xr.Dataset: """ Args: volume: A dataset with geo...
5,305,389
def get_trip_walking(origin, destin): """ Return trip data between two pois, by default mode of travel is driving """ myconfig_walking = RequestConfig(app.config['OSRM_WALK_ADDRESS']) # service for mode walking coord_start = [float(item) for item in origin] coord_finish = [float(item) for i...
5,305,390
def confidence_threshold(boxes: List[DetectionBox]) -> List[DetectionBox]: """ Filter a list of boxes with a given confidence threshold. :param boxes: A list of boxes. :return: A list of boxes with confidences higher than the threshold. """ return [box for box in boxes if box.detection_score > C...
5,305,391
def get_linear_regression_id(linear_regression): """Returns a linearregression/id. """ return get_resource(c.LINEAR_REGRESSION_PATH, linear_regression)
5,305,392
def _check_factory_signature_and_kwargs(factory, kwargs, strict, special_key): """ Buildins are can be problematic, becuase they may have no signature >>> config_to_instance({'factory': 'dict', 'A': 3}) {'A': 3} >>> config_to_instance({'factory': 'list'}) [] >>> _check_factory_signature_and_...
5,305,393
def _get_appdata_dir(): """Return the path to the Windows AppData directory""" if "%AppData%" in os.environ: return pth.join(os.environ["%AppData%"], "vaayu") return None
5,305,394
def sweepargs(**kwargs): """Decorator function to sweep over a given set of classifiers Parameters ---------- clfs : list of `Classifier` List of classifiers to run method on Often some unittest method can be ran on multiple classifiers. So this decorator aims to do that """ fro...
5,305,395
def main(main_filepath, coi_filepath): """Wrapper to be resilient about file handling.""" db_backup = _backup(main_filepath) # load stuff with open(main_filepath, "rt", encoding="ascii") as fh: main_db = json.load(fh) with open(coi_filepath, "rt", encoding="ascii") as fh: coi_db = j...
5,305,396
def test_shrink_dtypes_excluded(): """Assert that some dtypes are excluded from changing.""" atom = ATOMClassifier(X10_str2, y10, random_state=1) assert atom.dtypes[3].name == "bool" atom.shrink() assert atom.dtypes[3].name == "bool"
5,305,397
def transform_rays_model_cdf_mixture(list_rays, coef_components=1): """ compute the mixture model and transform it into cumulative distribution :param list(list(int)) list_rays: list ray features (distances) :param int coef_components: multiplication for number of components :return any, list(list(int)...
5,305,398
def swaption_vol_smile(asset: Asset, expiration_tenor: str, termination_tenor: str, pricing_date: Optional[GENERIC_DATE] = None, benchmark_type: str = None, floating_rate_tenor: str = None, clearing_house: str = None, location: PricingLocation = None,...
5,305,399