content
stringlengths
22
815k
id
int64
0
4.91M
async def test_direction_oscillating(hass, setup_comp): """Test handling of direction and oscillating attributes.""" hass.states.async_set( LIVING_ROOM_FAN_ENTITY_ID, STATE_ON, { ATTR_SUPPORTED_FEATURES: FULL_SUPPORT_FEATURES, ATTR_OSCILLATING: True, ...
17,300
def torsion_coordinate_names(zma): """ z-matrix torsional coordinate names (currently assumes torsional coordinates generated through x2z) """ name_dct = standard_names(zma) inv_name_dct = dict(map(reversed, name_dct.items())) geo = automol.geom.without_dummy_atoms(geometry(zma)) tors_names...
17,301
def test_get_screen_count(xsession: XSession): """Tests that the number of screens can be retrieved.""" count = xsession.get_screen_count() assert isinstance(count, int) assert count is not None
17,302
def extract_other_creditors_d( page: pdfplumber.pdf.Page, markers: List[Dict], creditors: List ) -> None: """Crop and extract address, key and acct # from the PDf :param page: PDF page :param markers: The top and bottom markers :return: Address, key and account information """ adjust = 0 if...
17,303
async def cancel_futures(*futures: asyncio.Future): """ Cancels given futures and awaits on them in order to reveal exceptions. Used in a process' teardown. """ for future in futures: future.cancel() for future in futures: try: await future except asyncio.Can...
17,304
def coverage(): """Generate test coverage report""" do('FLASK_CONFIG=app.config.TestConfig %s/bin/pytest' % venv_path)
17,305
def attach_server(host, port, cert=None, key=None, chain=None): """Define and attach server, optionally HTTPS""" if sabnzbd.cfg.ipv6_hosting() or "::1" not in host: http_server = cherrypy._cpserver.Server() http_server.bind_addr = (host, port) if cert and key: http_server.ssl...
17,306
def get_dicdirs(mecab_config: str = "mecab-config") -> List[Path]: """Get MeCab dictionary directories. Parameters ---------- mecab_config : str Executable path of mecab-config, by default "mecab-config". Returns ------- List[Path] MeCab dictionary directories. """ ...
17,307
def set_missing_parameters(iot): """Queries Azure for mising parameters like iothub hostname, keys, and connection_string""" if 'hostname' not in iot.config: click.secho("Checking for IoT Hub Host Name") hub_info, err = run_command_with_stderr_json_out( "az iot hub show --resourc...
17,308
def new_instance(settings): """ MAKE A PYTHON INSTANCE `settings` HAS ALL THE `kwargs`, PLUS `class` ATTRIBUTE TO INDICATE THE CLASS TO CREATE """ settings = set_default({}, settings) if not settings["class"]: Log.error("Expecting 'class' attribute with fully qualified class name") ...
17,309
def find_entry(entries, fn): """Find an entry that matches the given filename fn more or less.""" entry = get_entry_by_filename(entries, curr_file) if entry is not None: return entry key = lambda fn: path.splitext(fn)[0] entry = get_entry_by_filename(entries, curr_file, key) if entry i...
17,310
def get_type(k): """Takes a dict. Returns undefined if not keyed, otherwise returns the key type.""" try: v = { 'score': '#text', 'applicant': 'str', 'applicant_sort': 'str', 'author': 'str', 'author_sort': 'str', 'brief': 'boo...
17,311
def al(p): """ Given a quaternion p, return the 4x4 matrix A_L(p) which when multiplied with a column vector q gives the quaternion product pq. Parameters ---------- p : numpy.ndarray 4 elements, represents quaternion Returns ------- numpy.ndarray 4x4 matrix des...
17,312
def build_data_table(row, fields_to_try): """ Create HTML table for one row of data If no fields are valid, returns empty string """ th_class = 'attribute_heading' td_class = 'attribute_value' field_names = pd.read_csv('data/field_names.csv') ...
17,313
def publish_exploration(committer_id, exploration_id): """This is called by the publish_exploration_and_update_user_profiles function in exp_services.py. It publishes an exploration and commits changes. It is the responsibility of the caller to check that the exploration is valid prior to publicati...
17,314
def time_entry_reader(date, configuration): """Read the entries and return a list of entries that are apart of the date provided.""" parser = YAML(typ='rt') date = date.date() try: with open(configuration['filename'], 'r') as data_file: time_entries = parser.load(data_file).get('rec...
17,315
async def test_send_write(event_loop): """Check feed-receive scenarios used in the library.""" STREAM_ID = 'whatever' DATA = b'data' def make_writer(): queue = asyncio.Queue() async def writer(id, data): assert id == STREAM_ID await queue.put(data) retur...
17,316
def width_series(value_series, outer_average_width=5, max_value=None, method='linear'): """ :param value_series: the pd.Series that contain the values :param outer_average_width: the average width of the width series to return :param max_value: value to use as the maximum when normalizing the series (to...
17,317
def unroll_upper_triangular(matrix): """Converts square matrix to vector by unrolling upper triangle.""" rows, cols = matrix.shape assert rows == cols, "Not a square matrix." row_idx, col_idx = np.triu_indices(rows, 1) unrolled = [] for i, j in zip(row_idx, col_idx): unrolled.append(mat...
17,318
def fill_tuples( tuples: Sequence[Any], length: Optional[int] = None, repeat: bool = False, fill_method: str = 'bfill', ) -> Sequence[Tuple]: """Fill tuples so they are all the same length. Parameters ---------- length : int, optional Fill tuples to a fixed length. If None, fill...
17,319
def intersect(connection, items, ttl=30, execute=True): """并集计算""" return _set_common(connection, 'sinterstore', items, ttl, execute)
17,320
def batch_decode(raw_logits, use_random, decode_times): """ tbd """ size = (raw_logits.shape[1] + 7) // 8 logit_lists = [] for i in range(0, raw_logits.shape[1], size): if i + size < raw_logits.shape[1]: logit_lists.append(raw_logits[:, i: i + size, :]) else: ...
17,321
def _load_schemata(obj_type: str) -> dict: """Load the schemata from the package, returning merged results of other schema files if referenced in the file loaded. :raises: FileNotFoundError """ schema_path = pathlib.Path(pkg_resources.resource_filename( 'pglifecycle', 'schemata/{}.yml'.for...
17,322
def test(): """ 单元测试 """ import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(test=tests)
17,323
def waitfor(msg, status = '', spinner = None, log_level = log_levels.INFO): """waitfor(msg, status = '', spinner = None) -> waiter Starts a new progress indicator which includes a spinner if :data:`pwnlib.term.term_mode` is enabled. By default it outputs to loglevel :data:`pwnlib.log_levels.INFO`. ...
17,324
def f(i): """Add 2 to a value Args: i ([int]): integer value Returns: [int]: integer value """ return i + 2
17,325
def show_forecast(cmp_df, num_predictions, num_values, title): """Visualize the forecast.""" def create_go(name, column, num, **kwargs): points = cmp_df.tail(num) args = dict(name=name, x=points.index, y=points[column], mode='lines') args.update(kwargs) return go.Scatter(**a...
17,326
def build_jobs_dict(path): """Build a dictionary of "job_name" : [recipe list] from a directory full of job files.""" jobfiles = nested_glob(path, '.ajp') jobs = {} for jobfile in jobfiles: job_name = os.path.basename(jobfile).strip('.ajp') try: recipe = parse_jobfile(j...
17,327
def cancel_timeout_orders(context, max_m=10): """实盘仿真,撤销挂单时间超过 max_m 分钟的订单。 :param context: :param max_m: 最大允许挂单分钟数 :return: """ for u_order in context.unfinished_orders: if context.ipo_shares and u_order.symbol in context.ipo_shares: # 跳过新股,新股申购订单不能撤 continue ...
17,328
def write_mmcif(out_file, structure, **kwargs): """Write a biopython structure to an mmcif file. This function accepts any viable arguments to Bio.PDB.MMCIFIO.save() as keyword arguments. :param out_file: Path to output mmCIF file. :type out_file: Union[str, Path] :param structure: Biopython object con...
17,329
def get_concepts_from_kmeans(tfidf, kmeans): """Get kmeans cluster centers in term space. Parameters ---------- tfidf : TfidfVectorizer Fitted vectorizer with learned term vocabulary. kmeans : KMeans KMeans fitted to document-term matrix returned by tfidf. Returns -...
17,330
def test_J (): """This test verifies that dJ/dt = 2*H.""" qp = phase_space_coordinates() qp_ = qp.reshape(-1).tolist() x,y,z = qp[0,:] p_x,p_y,p_z = qp[1,:] P_x_ = P_x__(*qp_) P_y_ = P_y__(*qp_) mu_ = mu__(x,y,z)...
17,331
def package_proxy_relationships( db: PartitionedDatabase, tx: Transaction, config, s3, file_manifests: List[FileManifest], ) -> Iterator[PackageProxyRelationship]: """ Yield all proxy package relationships in the dataset Explodes each proxy package into multiple source files. If the pa...
17,332
def streams_to_dataframe(streams, imcs=None, imts=None, event=None): """Extract peak ground motions from list of processed StationStream objects. Note: The PGM columns underneath each channel will be variable depending on the units of the Stream being passed in (velocity sensors can only generate PGV) ...
17,333
def timestamp_diff(time_point_unit: TimePointUnit, time_point1, time_point2) -> Expression: """ Returns the (signed) number of :class:`~pyflink.table.expression.TimePointUnit` between time_point1 and time_point2. For example, `timestamp_diff(TimePointUnit.DAY, lit("2016-06-15").to_date, lit("2016-0...
17,334
def plot_solar_twins_results(star_postfix=''): """Plot results for 17 pairs with q-coefficients for solar twins""" def format_pair_label(pair_label): """Format a pair label for printing with MNRAS ion format. Parameters ---------- pair_label : str A pair label of t...
17,335
def waitVRText(msg='Text', color=[1.0, 1.0, 1.0], distance=2.0, scale=0.05, keys=' ', controller=None): """ Display head-locked message in VR and wait for key press. Args: msg (str): Message text color: RBG 3-tuple of color values distance (float): Z rendering distance from MainView...
17,336
def equalize(pil_img: Image.Image, level: float): """Equalize an image. .. seealso:: :func:`PIL.ImageOps.equalize`. Args: pil_img (Image.Image): The image. level (float): The intensity. """ del level # unused return ImageOps.equalize(pil_img)
17,337
def lightfm_trainer( train: np.ndarray, loss: str, n_components: int, lam: float ) -> None: """Train lightfm models.""" # detect and init the TPU tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect() # instantiate a distribution strategy tpu_strategy = tf.distribute.experimental.TPU...
17,338
def get_wspd_ts(path, storm, res, shpmask): """ Extracts the U and V component and returns the wind speed timeseries of storm_dict Arguments: path (str): Path containing data to load storm (str): Name of storm res (str): Resolution of data Returns: Pandas dataframe with...
17,339
def _read_output_file(path): """Read Stan csv file to ndarray.""" comments = [] data = [] columns = None with open(path, "rb") as f_obj: # read header for line in f_obj: if line.startswith(b"#"): comments.append(line.strip().decode("utf-8")) ...
17,340
def test_get_node_by_attached_volume(get_volume, get_attached_volume): """ Check basic consistency in platform handling. """ worker_id = get_attached_volume logger.info(f"volume is attached to node: {worker_id}")
17,341
async def test_light_turn_on_service(hass, mock_bridge): """Test calling the turn on service on a light.""" mock_bridge.mock_light_responses.append(LIGHT_RESPONSE) await setup_bridge(hass, mock_bridge) light = hass.states.get('light.hue_lamp_2') assert light is not None assert light.state == 'of...
17,342
def run_pull_in_parallel( dry_run: bool, parallelism: int, image_params_list: Union[List[BuildCiParams], List[BuildProdParams]], python_version_list: List[str], verbose: bool, verify_image: bool, tag_as_latest: bool, wait_for_image: bool, extra_pytest_args: Tuple, ): """Run image...
17,343
def combinationShape(*args, **kwargs): """ Flags: - addDriver : add (bool) [] - allDrivers : ald (bool) [] - blendShape : bs (unicode) [] - combinationTargetIndex : cti (int) [] - co...
17,344
def _transform_data(raw_df, cols_config): """ Applies required transformations to the raw dataframe :returns : Trasformed dataframe ready to be exported/loaded """ # Perform column and dtype checks if check_columns(raw_df, cols_config): df = raw_df else: logger.war...
17,345
def dcmToSimpleITK(dcmDirectory): """Return a simple ITK image from a pile of dcm files. The returned sITK image has been rescaled based on the value of the rescale slope on the dicom tag. Array-like data of the 3D image can be obtained with the GetArrayFromImage() method""" list_dcmFiles = [] for d...
17,346
def main(): """Main entry point.""" base_parser = argparse.ArgumentParser(add_help=False) base_parser.add_argument( 'file_name', metavar='FILENAME', type=str, help='spreadsheet file') base_parser.add_argument( '-o', dest='output_handle', metavar='OUTPUT', type=argparse.FileType('...
17,347
def on_new_follower_added(sender, **kwargs): """called when someone is followed""" if kwargs['action'] is "post_add": for person_i_have_followed in kwargs['pk_set']: followers_updated_signal.send(sender=ProfilesSignalSender, who_was_followed=Profile....
17,348
def print_percents(x, y): """Print percentage of x is y""" print(str(y) + ' is ' + str(percents(x, y)) + '% of ' + str(x))
17,349
def mean_and_std(values): """Compute mean standard deviation""" size = len(values) mean = sum(values)/size s = 0.0 for v in values: s += (v - mean)**2 std = math.sqrt((1.0/(size-1)) * s) return mean, std
17,350
def blacken( color: Color, amount: FloatOrFloatIterable ) -> Union[Color, List[Color]]: """ Return a color or colors amount fraction or fractions of the way from `color` to `black`. :param color: The existing color. :param amount: The proportion to blacken by. """ return cross_fade(...
17,351
def deleteAllProxyServers(): """Delete all proxy servers - raises exception on error""" deleteServersOfType( "PROXY_SERVER" )
17,352
def add_line(preso, x1, y1, x2, y2, width="3pt", color="red"): """ Arrow pointing up to right: context.xml: office:automatic-styles/ <style:style style:name="gr1" style:family="graphic" style:parent-style-name="objectwithoutfill"> <style:graphic-properties draw:marker-end="Arrow" draw:...
17,353
def llf_gradient_sigma_neq_gamma(history, sum_less_equal=True): """ Calculate the gradient of the log-likelihood function symbolically. Parameters ---------- sum_less_equal : bool, default: True This arg is passed to :meth:`self.llf_sigma_eq_gamma`. Returns ------- gradient : s...
17,354
def test_base__Calendar__update__1(): """It does nothing. Test is only here to complete test coverage. """ calendar = Calendar(None, None, None) calendar.update()
17,355
def test_unwrap(service): """unwrapping args from XML.""" assert service.unwrap_arguments(DUMMY_VALID_RESPONSE) == { "CurrentLEDState": "On", "Unicode": "μИⅠℂ☺ΔЄ💋", }
17,356
def main(): """ docstring """ loop = asyncio.get_event_loop() task_function1 = asyncio.ensure_future(get_file_extension()) task_function2 = asyncio.ensure_future(get_filenames()) loop.run_forever()
17,357
def selection_support_df(df, combinations, min_support): """ selection combinations with support Parameters ---------- df : pandas.DataFrame data to be selected. for example : = | banana | mango | apple | | 1 | 1 | 1 | ...
17,358
def empty_trie_tree(): """Empty trie tree fixture.""" from trie import TrieTree return TrieTree()
17,359
def check_reference_search_filter_results(response, expected_hits, expected_req_nums): """Check if all expected results are there.""" hits = response.json["hits"]["hits"] reported_hits = int(response.json["hits"]["total"]) req_numbers = [r["number"] for r in response.json["hits"]["hits"]] assert le...
17,360
def bind_context_to_node(context, node): """Give a context a boundnode to retrieve the correct function name or attribute value with from further inference. Do not use an existing context since the boundnode could then be incorrectly propagated higher up in the call stack. :param context: Cont...
17,361
def get_weight_matrix(file_handle): """ Read each line in file_handle and return the weight matrix as a dict, in which each key is the original node name, and each value is a nested dict, whose keys are gene systematic names, and values are weights. """ weight_matrix = dict() for line_num, ...
17,362
def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata): """Get Event Logs""" mgr = SoftLayer.EventLogManager(env.client) usrmgr = SoftLayer.UserManager(env.client) request_filter = mgr.build_filter(date_min, date_max, obj_event, obj_id, obj_type, utc_offset) logs = mgr.g...
17,363
def search_remove(row_id): """Remove a search item""" LOG.debug('Removing search item with ID {}', row_id) G.LOCAL_DB.delete_search_item(row_id) common.json_rpc('Input.Down') # Avoids selection back to the top common.container_refresh()
17,364
def test_primitive_generators_return_consistent_values_when_reset(g): """ Primitive generators produce the same sequence when reset with the same seed. """ g.reset(seed=12345) items1 = list(g.generate(num=10)) g.reset(seed=12345) items2 = list(g.generate(num=10)) g.reset(seed=99999) ...
17,365
def get_uptime(): """ Get uptime """ try: with open('/proc/uptime', 'r') as f: uptime_seconds = float(f.readline().split()[0]) uptime_time = str(timedelta(seconds=uptime_seconds)) data = uptime_time.split('.', 1)[0] except Exception as err: data =...
17,366
def measure_list_for_upcoming_elections_retrieve_api_view(request): # measureListForUpcomingElectionsRetrieve """ Ask for all measures for the elections in google_civic_election_id_list :param request: :return: """ status = "" google_civic_election_id_list = request.GET.getlist('google_civi...
17,367
def check_template_path(path): """ Argument checker, check if template exists and get the content """ try: with open(path) as template: tmp = template.read() return tmp except: raise argparse.ArgumentTypeError("Invalid template path!")
17,368
def get_required_flowlist_fields(): """ Gets required field names for Flow List. :return:list of required fields """ from fedelemflowlist.globals import flow_list_fields required_fields = [] for k, v in flow_list_fields.items(): if v[1]['required']: required_fields.appen...
17,369
def sparse_table_function(*, index, data) -> callable: """ The very simplest Python-ish "sparse matrix", and plenty fast on modern hardware, for the size of tables this module will probably ever see, is an ordinary Python dictionary from <row,column> tuples to significant table entries. There are better ways if you...
17,370
async def _get_db_connection() -> asyncpg.Connection: """ Initialise database connection. On failure, retry multiple times. When the DB starts in parallel with the app (with Compose), it may not yet be ready to take connections. """ log.info("Creating DB connection") n_attempts = 3 for...
17,371
def get_view_content(view): """ Returns view content as string. """ return utils.execute_in_sublime_main_thread(lambda: view.substr(sublime.Region(0, view.size())))
17,372
def signed_byte8(x: IntVar) -> Int8: """Implementation for `SBYTE8`.""" return signed_byte_n(x, 8)
17,373
def join(zma1, zma2, join_key_mat, join_name_mat, join_val_dct): """ join two z-matrices together """ syms1 = symbols(zma1) syms2 = symbols(zma2) natms1 = count(zma1) natms2 = count(zma2) key_mat1 = numpy.array(key_matrix(zma1)) key_mat2 = numpy.array(key_matrix(zma2, shift=natms1)) # n...
17,374
def step_see_named_query_deleted(context): """ Wait to see query deleted. """ wrappers.expect_pager(context, "foo: Deleted\r\n", timeout=1)
17,375
def multi_to_weighted(G: nx.MultiDiGraph): """ Converts a multidigraph into a weighted digraph. """ nG = nx.DiGraph(G) # nG.add_nodes_from(G.nodes) nG.name = G.name + "_weighted_nomulti" edge_weights = {(u, v): 0 for u, v, k in G.edges} for u, v, key in G.edges: edge_weights[(u, ...
17,376
def RetentionInDaysMatch(days): """Test whether the string matches retention in days pattern. Args: days: string to match for retention specified in days format. Returns: Returns a match object if the string matches the retention in days pattern. The match object will contain a 'number' group for th...
17,377
def _extract_result_details(pipx_output: str) -> Tuple[str, str, str]: """ Extracts name and version from pipx's stdout """ match = re.search(r'installed package(.*),(.*)\n.*\n.*?-(.*)', pipx_output) if match: package, python_version, plugin_name = map(str.strip, match.groups()) return plug...
17,378
def plot_2d_comp_multinom(model, data, vmin=None, vmax=None, resid_range=None, fig_num=None, pop_ids=None, residual='Anscombe', adjust=True): """ Mulitnomial comparison between 2d model and data. model: 2-dimensional model SFS ...
17,379
def varatts(w_nc_var, varname, tres, vres): """Add attibutes to the variables, depending on name and time res. Arguments: - w_nc_var: a variable object; - varname: the name of the variable, among ta, ua, va and wap; - tres: the time resolution (daily or annual); - vres: the vertical resolution ...
17,380
def get_pwr_SXT(sxt_los, plasma, emiss, num_pts=100, labels=labels_full): """ """ pwr_int = {} for ll in labels: # Get the appropriate database label filt = ll.split()[1] pix_los = sxt_los[ll] # Get the spatial points along the line of sight num_pixels = ...
17,381
def get_mstp_port(auth): """ Function to get list of mstp port status :param auth: AOSSAuth class object returned by pyarubaoss.auth :return list of mstp port status :rtype dict """ url_mstp_port = "http://" + auth.ipaddr + "/rest/"+auth.version+"/mstp/port" try: r = requests.ge...
17,382
def _process_tree(tree, nstag): """Process XML tree for a record and return a dictionary for our standard """ rec = OrderedDict() for key, tag_, getall, trans1_, transall_ in [ ('author', 'creatorName', True, None, None), ('name', "title[@titleType='AlternativeTitle']", False, None, None...
17,383
def prepare_all_predictions( data, uid_map, iid_map, interactions, model, num_threads, user_features=None, item_features=None, ): """Function to prepare all predictions for evaluation. Args: data (pandas df): dataframe of all users, items and ratings as loaded ui...
17,384
def touch(v: Union[Callable, str], default=None): """ Touch a function or an expression `v`, see if it causes exception. If not, output the result, otherwise, output `default`. Note: Use `default = pycamia.functions.identity_function` (or write one yourself) to return the exceptio...
17,385
def q_mult(q1, q2): """Quaternion multiplication""" w1, x1, y1, z1 = q1 w2, x2, y2, z2 = q2 w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2 x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2 y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2 z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2 return w, x, y, z
17,386
def round_repeats(repeats, global_params): """Calculate module's repeat number of a block based on depth multiplier. Use depth_coefficient of global_params. Args: repeats (int): num_repeat to be calculated. global_params (namedtuple): Global params of the model. Returns: new r...
17,387
def estimate_label_width(labels): """ Given a list of labels, estimate the width in pixels and return in a format accepted by CSS. Necessarily an approximation, since the font is unknown and is usually proportionally spaced. """ max_length = max([len(l) for l in labels]) return "{0}px".f...
17,388
def update_user(user_id): """ :Route: PUT /<user_id>?active=false&admin=true&password=str&first_name=Katrina&last_name=Wijaya&email=mappeningdevx@gmail.com :Description: Updates user with id `user_id`. Updates any optional fields that are set as query parameters. :param user_id: The int ID of a specif...
17,389
def process_record(db_conn, cf_number, reclabel, rectext): """ Process the council file summary information entry; this is a single field label and value from the HTML content. :param db_conn: Active database connection :param cf_number: Council file number, format a zero-padded yy-nnnn :param rec...
17,390
async def test_list_users_without_db_entries(client: AsyncClient, app: FastAPI) -> None: """No users should be returned when the database is empty.""" response = await client.get(app.url_path_for("get_users")) assert response.status_code == 200 users = response.json() assert not users
17,391
def install_package(pkg, directory, python_version, pip_args): """Downloads wheel for a package. Assumes python binary provided has pip and wheel package installed. :param pkg: package name :param directory: destination directory to download the wheel file in :param python: python binary path used ...
17,392
def ssh_encrypt_text(ssh_public_key, text): """Encrypt text with an ssh public key. If text is a Unicode string, encode it to UTF-8. """ if isinstance(text, six.text_type): text = text.encode('utf-8') try: pub_bytes = ssh_public_key.encode('utf-8') pub_key = serialization.lo...
17,393
def add_missing_init_files_from_path( paths: List[str], folders_to_ignore: List[str], source_extensions: List[str], folder_trees_to_ignore: List[str], recursive: bool, ) -> bool: """ Add missing __init__.py files to the specified root directories and subdirectories that contain at least one ...
17,394
def naildown_entity(entity_class, entity_dict, entity, state, module, check_missing=None): """ Ensure that a given entity has a certain state """ changed, changed_entity = False, entity if state == 'present_with_defaults': if entity is None: changed, changed_entity = create_entity(entity...
17,395
def get_all_admins(): """ Returns a queryset of all active admin users. """ current_admins = User.objects.filter(is_admin=True, is_active=True) return current_admins
17,396
def htx_numpy(h, x): """ Convolution of reversed h with each line of u. Numpy implementation. Parameters ---------- h : array, shape (n_time_hrf), HRF x : array, shape (n_samples, n_time), neural activity signals Return ------ h_conv_x : array, shape (n_samples, n_time_valid), convolve...
17,397
def test_start_xql_query_valid(mocker): """ Given: - A valid query to search. When: - Calling start_xql_query function. Then: - Ensure the returned execution_id is correct. """ args = { 'query': 'test_query', 'time_frame': '1 year' } mocker.patch.object(CLIE...
17,398
async def test_loop(): """Test loop usage is handled correctly.""" async with Sonarr(HOST, API_KEY) as sonarr: assert isinstance(sonarr, Sonarr)
17,399