content
stringlengths
22
815k
id
int64
0
4.91M
def quicksort(data, leftmark, rightmark): """Quicksort implementation. QUICKSORT(A, p, r) if p<r q = PARTITION(A, p, r) QUICKSORT(A, p, q-1) QUICKSORT(A, q+1, r) Args: data (list): array to be sorted leftmark (int): starting index rightmark (int): ending...
75,700
def circular_consistency_test(inchi_str): """Perform conversion from ``InChI`` string to ``Molfile`` and back to ``InChI`` string. :param str inchi_str: ``InChI`` string. :return: None :rtype: :py:obj:`None` """ original_inchi_str = inchi_str.strip() with tempfile.NamedTemporaryFile(mo...
75,701
def completing_polygon(xs: Iterable[float], ys: Iterable[float]) -> Any: """ xs: is a list of accending numbers ys: is either 0 or 1 """ # Extending: [(xs[0], 0), *zip(xs, region), (xs[-1], 0)] x_, y_ = xs[0], ys[0] # type: ignore yield x_, 0 for x, y in zip(xs, ys): if y != y_...
75,702
def to_geopotential_height(z: pint.Quantity) -> pint.Quantity: """Convert altitude to geopotential height. Parameters ---------- z: quantity Altitude. Returns ------- quantity Geopotential height. """ return R0 * z / (R0 + z)
75,703
def run(args_dict: dict = {}, databuilder_config_path: str = databuilder_config['databuilder_config_save_path']) -> None: """ Runs training. :param args_dict: training arguments dictionary :param databuilder_config_path: path to databuilder config """ # Asserting databuilder config pat...
75,704
def parse_kind(key): """Extract kind from colorbrewer.json .. note:: This can be None if key is not seq, div or qual """ if key == "seq": return Kind.SEQUENTIAL elif key == "div": return Kind.DIVERGING elif key == "qual": return Kind.QUALITATIVE
75,705
def is_bad(text): """ Returns true iff the given text looks like it contains mojibake. This can be faster than `badness`, because it returns when the first match is found to a regex instead of counting matches. Note that as strings get longer, they have a higher chance of returning True for `is_bad...
75,706
def new_chunk_init(self, nbt_data: nbt.NBTFile): """ Override of anvil chunk constructor for version 1.18+ """ try: self.version = nbt_data['DataVersion'].value except KeyError: self.version = None if self.version > 2800: self.data = nbt_data else: self.data = nbt_data['Level'] self.t...
75,707
def show_pushing_progress(ret, start_time): """ Args: ret: json message from URL(/install/:id) """ if ret is None: print("No progress") return total = ret.get('totalSize', 0) if total == 0: print("Total size 0") return copied = ret.get('copiedSize', 0)...
75,708
def math_eval(expression, variables=None, functions=None): """Evaluate a mathematical expression with variables. All the functions in the standard module math are available together with - step(x) : Heaviside step function (1.0 for x=0) - step_hm(x) : Heaviside step function with half-maximum conventio...
75,709
def DBPossibleAddressWrites(reg, cst, constraint, assertion, n=1): """ Return the list of [addr_reg, addr_cst] such than mem(addr_reg, addr_cst) <- reg+cst """ return db.possibleAddressWrites(reg, cst, constraint, assertion, n)
75,710
def _decline(di, t, qoi, b): """Arp's equation for general decline in a well - qoi: initial rate of production - di: initial decline rate - b: curvature (b=0 exponential) """ return qoi / ((1 + b * di * t) ** (1 / b))
75,711
def connect_vm(tenant_id, vm_image_id, service_instance_id, *args): """ Starts a VMs and is connected to southbound network """ l2db.initialize() client = Client(HOST, PORT, USE_SSL, format='json', tenant=tenant_id) print (_("Connecting %(vm_image_id)s to Service " "%(service_instan...
75,712
def su_calculation(f1, f2): """ This function calculates the symmetrical uncertainty, where su(f1,f2) = 2*IG(f1,f2)/(H(f1)+H(f2)) Input ----- f1: {numpy array}, shape (n_samples,) f2: {numpy array}, shape (n_samples,) Output ------ su: {float} su is the symmetrical uncertai...
75,713
def _close_xml_tags(xml): """ Automagically takes an input xml string and returns that string with all of the xml tags properly closed. It can even handle when the open tag is in the middle of the string and not the end. """ output = [] stack = [] xml_chars = deque(list(xml)) ...
75,714
def screenshot_entry_primary(): """ Get screenshot for a entry """ style = Style() window = style.master window.title('ttkbootstrap') color = 'primary' ss = Screenshot(window, f'../images/entry_{color}.png') f5 = ttk.Frame(window, padding=5) f5.pack(fill='both', side='left', exp...
75,715
def print_err(*args, **kwargs): """ Print to stderr """ print(*args, **kwargs, file=sys.stderr)
75,716
def ps5_gen(x: List[int]) -> Generator[List[int], List[int], None]: """PS5 perturbation scheme: A subsequence is reversed [1]""" n = len(x) i_range = range(1, n) for i in sample(i_range, len(i_range)): j_range = range(i + 2, n + 1) for j in sample(j_range, len(j_range)): xn ...
75,717
def export_as_csv(host, user, password, file_path, db_name, tb_name): """ Writes table data into csv file. :param host: host name :param user: user name :param password: password :param file_path: file path to save csv file :param db_name: name of the pydb from where data will be exported ...
75,718
def NetPDF(addr): """ Retrieves a PDF from a remote address. :param addr: URI. PDF must be stored in JSON format :returns: A PDF object :Example: >>> u = NetPDF('http://foo.com/myproject/parameters/density') """ from jpickle import NetObj p = NetObj(addr) if not isinstance(p, ...
75,719
def gen_robohash(s, size=200): """Return URL for robohash pic for sha1 hash of string ``s``""" h = hashlib.sha1(s).hexdigest() return ('http://robohash.org/{0}.png?size={1}x{1}&bgset=bg2&set=set1' .format(h, size))
75,720
def quarks_pairwise_same_flavor(unbarred,barred): """Check if a list of quarks and list of anti-quarks have same flavor order :param unbarred: list of quarks. :param barred: list of anti-quarks. :return: True if flavors match in order, false otherwise. """ if(len(unbarred)!=len(barred)): ...
75,721
def prepare_cmd_args(parser= None): """ parse the command line arguments """ if parser is None: parser = argparse.ArgumentParser(prog=sys.argv[0], description='Train the models over a distributed cluster.') #parser.add_argument('--chief_host', type=str, default="localhost:2222", help='chief worker server...
75,722
def test_get_valid_ffmpeg_path(paths, ffmpeg_download_paths, results): """ Testing FFmpeg excutables validation and correction: """ _windows = True if os.name == 'nt' else False try: output = get_valid_ffmpeg_path(custom_ffmpeg = paths, is_windows = _windows, ffmpeg_download_path = ffmpeg_download_paths, ...
75,723
def upload_folder_to_obj(directory, resource_obj, resource_label, remove=False, removeall=False, extract=True): """ Upload all of the files in a folder based on the pyxnat EObject passed :param directory: Full path of the directory to upload :param resource_obj: pyxnat EObject ...
75,724
def infer_type_names(model: SystemModel, ul: UserLevel) -> TypeNameMap: """Generates a list of unique type names for all typedefs depending on the user levels. Args: model (SystemModel): A DeCoP system model. ul (UserLevel): The highest user level for which code will be generated. Returns:...
75,725
def detect_text(img): """Detects text in the file.""" with io.open(img, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.text_detection(image=image) # returns TextAnnotation df = pd.DataFrame(columns=['description']) te...
75,726
def preproccess_image(image): """ this function applies some basic image processings to the original images :param image: original image :return: processed image """ # covert BGR image to RGB space image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # print(image.shape) # covert RGB ima...
75,727
def setup_fig(title, x_label, y_label): """ set-up the figure for the the plots pre-conditions: title: <string> the title of the plot x_label: <string> x axis label y_label: <string> y axis label post-conditions: returns the figure and the axes """ fig, axes...
75,728
def remember_first_logged(client, bucket, key, key_first_logged): """record the key of the first object logged""" try: client.get_object(Bucket=bucket, Key=key_first_logged) except ibm_botocore.exceptions.ClientError as ex: response_error_code = ex.response["Error"]["Code"] if respon...
75,729
def post_comments_corrections(pmids_wanted): # noqa: C901 """ :param pmids_wanted: :return: """ logger.info(pmids_wanted) api_port = environ.get("API_PORT") base_path = environ.get("XML_PATH") token = get_authentication_token() headers = generate_headers(token) allowed_com_...
75,730
def version_is_greater(current, minimum): """Compare two 'vv.nn.pp' versions. Return True is the current version string is greater or equal to the minimum string. Assumes that each string is of type vv.nn.pp, with vv, nn and pp being integers.""" return version.parse(current) >= version.parse(minimum)
75,731
def _set_logger(level='info'): """Configure logging for application.""" if level == 'warning': num = 30 fmt = '%(message)s' elif level == 'info': num = 20 fmt = '%(message)s' elif level == 'debug': num = 10 fmt = '%(name)s:%(levelname)s: %(message)s' ...
75,732
def worker(problem, response_vars, case_queue, response_queue, worker_id): # pragma: no cover """This is used to run parallel DOEs using multprocessing. It takes a case off of the case_queue, runs it, then puts responses on the response_queue. """ # set env var so comps/recorders know they're running in...
75,733
def test_lagrangian_tids(): """Build and test lagrangian linear and time-invariant ds """ q0[...] = [1, 2, 3] v0[...] = [4, 5, 6] mass = np.asarray(np.diag([1, 2, 3]), dtype=np.float64) stiffness = np.zeros((ndof, ndof), dtype=np.float64) stiffness.flat[...] = np.arange(9) damping = np....
75,734
def info(node_or_path, max_rows=DEFAULT_MAX_ROWS, max_cols=DEFAULT_MAX_COLS, show_values=DEFAULT_SHOW_VALUES): """ Print a rendering of an ASDF tree or sub-tree to stdout. Parameters ---------- node_or_path : str, pathlib.Path, asdf.asdf.AsdfFile, or any \ ASDF tree node ...
75,735
def _combine_sample_regions_batch(batch, items): """Combine sample regions within a group of batched samples. """ config = items[0]["config"] work_dir = utils.safe_makedir(os.path.join(items[0]["dirs"]["work"], "regions")) analysis_file = os.path.join(work_dir, "%s-analysis_blocks.bed" % batch) ...
75,736
def reset_clearance(usr: User, save: bool = False): """ Resets a user's clearance. If a user is the CEO of its corporation, then a clearance level of 2 is granted. If its corporation is the executor of the alliance, then a level of 4 is granted instead. If the user is root or has a clearance level ...
75,737
def logq(x, q=1): """ Calculates the `q`-logarithm of x. Parameters ---------- x : float, array Real number or array containing real numbers. q : float Tsallis's `q` parameter (default: 1). Returns ------- : float or array Value or array of values containing...
75,738
def wrap_deepmind(env_id, episode_life=True, clip_rewards=True, frame_stack=4, scale=False, warp_frame=True): """Configure environment for DeepMind-style Atari. The observation is channel-first: (c, h, w) instead of (h, w, c). :param str env_id: the atari environment id. :param bool e...
75,739
def batch_intersection_union(output, target, nclass): """mIoU""" # inputs are numpy array, output 4D, target 3D mini = 1 maxi = nclass nbins = nclass predict = np.argmax(output.astype(np.float32), 1) + 1 target = target.astype(np.float32) + 1 predict = predict.astype(np.float32) * (targ...
75,740
def send_password_reset_email(sender, reset_password_token, *args, **kwargs): """ When the password reset signal is triggered, send an email to the associated address with a password reset link. """ user = reset_password_token.user request = kwargs['instance'].request context = { '...
75,741
async def _async_get_ws_formatted_events( hass: HomeAssistant, msg_id: int, start_time: dt, end_time: dt, formatter: Callable[[int, Any], dict[str, Any]], event_processor: EventProcessor, ) -> tuple[str, dt | None]: """Async wrapper around _ws_formatted_get_events.""" return await get_in...
75,742
def laplace_ptr(boundary, trace, nb, matrix=False): """ μ, c, θ = laplace_ptr(boundary, trace, nb, matrix=False) The PTR method for the Laplace problem. Parameters ---------- boundary : Boundary Boundary object trace : function the function θ ↦ f(θ) the source term of the B...
75,743
def _popen(cmd, data_in, data_out=PIPE): """ Helper function subprocess.popen replaces os.system - gives better input/output process control usage: pass <data_in> to process <cmd> and return results based on rgbeimage.py (Thomas Bleicher 2010) """ cmd = str(cmd) # gets rid of unicode odditie...
75,744
def reduce_min(attrs, inputs, proto_obj): """Reduce the array along a given axis by mean value""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'}) return 'min', new_attrs, inputs
75,745
def fake_get_value(name, default=None): """ Method for getting configuration override values for a fake site. """ return FAKE_SITE.get(name, default)
75,746
def save_clusters(clusters, zoom): """ The output function provided to ClusterLizard should be a function that takes 'clusters', a set of clusters, and 'zoom', the integer Google zoom level. """ for cluster in clusters: lat, long = mercator_to_latlong(*cluster.mean) ClusteredPoin...
75,747
def render_component( component_name: Text, data: Union[List[Dict[Text, Union[Dict[Text, Any], Text]]], Dict[Text, List[Union[Text, float, List[float]]]]], config: Dict[Text, Union[Dict[Text, Dict[Text, Text]], Text, bool]], event_handlers: Optional[ Callable[[Dict[Text, Union[Te...
75,748
def check_statement(statement): """Given a single line of code expected to be a valid 'statement', that is a line which could be part of a larger source of code and contains no unmatched brackets and would not end with the continuation character, it is potentially modified to include some required '...
75,749
def hinter_sampling(min_n_pts, radius=1.0): """Samples 3D points on a sphere surface by refining an icosahedron, as in: Hinterstoisser et al., Simultaneous Recognition and Homography Extraction of Local Patches with a Simple Linear Classifier, BMVC 2008. :param min_n_pts: The minimum number of points t...
75,750
def test_wpas_ap_dfs(dev): """wpa_supplicant AP mode - DFS""" if dev[0].get_mcc() > 1: raise HwsimSkip("DFS is not supported with multi channel contexts") try: _test_wpas_ap_dfs(dev) finally: set_country("00") dev[0].request("SET country 00") dev[1].flush_scan_ca...
75,751
def _load_md(rec,keys): """ Helper for load ensemble. Extracts metadata defined by keys list and posts to a Metadata container that is returned. """ # do this stupid for now without error handlers md=Metadata() for k in keys: x=rec[k] md.put(k,x) return md
75,752
def node_stats(ctx): """Get stats for a node.""" try: data = ctx.obj['node'].get_stats() except TimeoutError as e: logger.error('Error: %s' % e) exit(1) data = [[k, v] for k, v in data.items()] click.echo(generate_table(['KEY', 'VALUE'], data, sort='KEY', plain=ctx.obj['plai...
75,753
def start(): """\\A: Match the start of the text.""" regex = re.compile(r'\Aa', flags=re.MULTILINE) match_start = regex.search("album") match_starting_newline = regex.search("\nart") return match_start and not match_starting_newline and match_start.string
75,754
def variance(y): """ Return the sample variance of y. >>> y = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] >>> variance(y) 1.3720238095238095 """ av = mean(y) ss = sum((x-av)**2 for x in y) return ss/(len(y)-1)
75,755
def get_text_preprocessor(func: str) -> Callable[[str], str]: """ Given a string descriptor of the function, return the requested preprocessing function. Args: func: Function name. Returns: Text preprocessing function. """ if func == TextPreprocessing.BERT_PAPER: ...
75,756
def initialize_warnings_in_workers(show_warnings): """ Small helper function to initialize warnings module in multiprocessing workers. On Windows, Python spawns fresh processes which do not inherit from warnings state, so warnings must be enabled/disabled before running computations. :param show_w...
75,757
def test_orc_scan_with_aggregate_pushdown(spark_tmp_path, aggregate): """ Spark(330,_) allows aggregate pushdown on ORC by enabling spark.sql.orc.aggregatePushdown. When the spark configuration is enabled we check the following: ---------------------------+ | Aggregate | FallBack CPU | +--------...
75,758
def test_bad(test_input, expected): """Put a placeholder.""" parser = sm_protocol() args, train_args = parser.parse_known_args(test_input) args, train_args = parser.parse_known_args(test_input) hyperopts = to_kwargs(train_args) result = actual_train(args.model_dir, args.train, **hyperopts) ...
75,759
def BM_spectrum(E, I, B, ph_energy, hor_acc_mrad=1.0): """ Calculates the emitted spectrum of a Bending Magnet (vertically integrated) whithin a horizontal acceptance\n Units: [ph/s/0.1%bw]\n :E: Storage Ring energy [GeV] :I: Storage Ring current [A] :B: Magnetic Field value [T] :ph_ener...
75,760
def test_wiki_text_2_sample(capsys) -> None: """Must correctly sample data points of :py:class:`lmp.dset.WikiText2Dset`.""" lmp.script.sample_dset.main(argv=[WikiText2Dset.dset_name]) captured = capsys.readouterr() assert 'Senjō no Valkyria 3 : [unk] Chronicles ( Japanese : 戦場のヴァルキュリア3 , lit .' in captured.out...
75,761
def test(): """ Python 没有内置对数组的支持,但可以使用 Python 列表代替。 """ # 定义数组 cars = ["Porsche", "Volvo", "BMW"] print("cars = %s" % cars) # 获取值 x = cars[0] print("第一个元素[%s]" % x) # 修改 cars[0] = "Audi" print("cars = %s" % cars) # 获取长度 x = len(cars) print("cars 长度 %d" % x...
75,762
def finite_zeroth_d(grid): """ Gives the zeroth derivative operator on the function f(grid), so simply returns the identity matrix... XD """ return identity(len(grid))
75,763
def set_gdx_path(path): """Set file path of active GDX file.""" global ACTIVE_GDX ACTIVE_GDX = Gdx(path) logger.info(f"ACTIVE_GDX set to {ACTIVE_GDX.abs_path}") return f"Active gdx set to {ACTIVE_GDX.abs_path}"
75,764
def process_reqs(reqs): """ Add all egg-containing links to list #1 and egg information plus package names to list #2. Note: we rely on dependency links, support for which will be removed in future versions of pip. TODO: migrate to custom pip repo. """ pkg_reqs = [] dep_links = [] f...
75,765
def test_dns_cache_negative(urlextract, dns_resolver): """ Testing negative results are not cached """ if ExceptionCachingResolver: assert dns_resolver.__class__ == ExceptionCachingResolver # https://github.com/rthalley/dnspython/pull/238 isnt merged results = urlextract.find_urls("http...
75,766
def plot_embeddings(data_path, outpath): """ Plot 2-D latent embeddings for Brn2, Ebf2 and Onecut2. Parameters: data_path: Input file paths (N rows * 2 columns) storing the 2-D co-ordinates for each binding site in the latent space. The embeddings must be derived using latent_embedd...
75,767
def member_invite( *, group_id: str, user: ParsedIdentity, provision_identity: bool, role: str, login_manager: LoginManager, ): """ Invite a user to a group. The USER argument may be an identity ID or username (whereas the group must be specified with an ID). """ auth_cl...
75,768
def Tweet(tw, config): """Create Tweet object """ logme.debug(__name__+':Tweet') t = tweet() t.id = int(tw["data-item-id"]) t.id_str = tw["data-item-id"] t.conversation_id = tw["data-conversation-id"] t.datetime = int(tw.find("span", "_timestamp")["data-time-ms"]) t.datestamp = strft...
75,769
def bfs(problem, stype): """ Breadth-first search :param problem: problem :param stype: type of search: graph or tree (graph_search or tree_search) :return: (path, stats): solution as a path and stats The stats are a tuple of (time, expc, maxstates): elapsed time, number of expansions, max state...
75,770
def users(): """ puts a snapshot of the users into mongo """ refresh(types=['users'])
75,771
def stock_valuation_n_period(discount_rate ,LT_growth_rate, dividends): """ Summary: Given an array of dividends, estimate the stock price using an n-period model. PARA discount_rate: The discount rate used to calculate the NPV & PV calcs. PARA type: float PARA LT_growth_rate: The long-ter...
75,772
def calculate_wer_per_cat(df,category='category', id='', kind=False): """ Calculates the WER for every unique value for a certain column Args: df: the pandas dataframe category: name of a column in the pandas data frame, for each unique in this column value we return the wer. kind: name ...
75,773
def two_versions(app, identity_simple, input_data, service): """Create 2 versions.""" # NOTE: We use app fixture to create/teardown the index only once for # this module. record = _create_and_publish(service, input_data, identity_simple) recid = record.id draft = service.new_version(recid,...
75,774
def prepare_simulation(a,b,c, n): """ prepare simulation :return: :rtype: """ f_f = ForceField(linear=True, amplitude=20) f_f.origin = b print(f_f) # cell = CubicCell(a, b, c) cell = ForceCubicCell(a,b,c, f_f) print(cell) print(cell.get_center()) print("the force o...
75,775
def handle_code_freeze_cur_branch(merge_item): """If branch is in code freeze send an email if commit was made to it, otherwise do not merge into it. Args: merge_item: Details of commit to be merged. """ if is_code_freeze(merge_item[KEY_CURRENT_BRANCH], mergeconf.BRANCHE...
75,776
def flatten_list(lst): """ :param lst: original list :return: flattened list """ from itertools import chain return list(chain(*lst))
75,777
def checkwait(space, w_sock, writing): """If the socket has a timeout, do a select()/poll() on the socket. The argument writing indicates the direction. Returns one of the possibilities in the timeout_state enum (above).""" w_timeout = space.call_method(w_sock, "gettimeout") if space.is_w(w_timeout...
75,778
async def test_device_class(hass, remote): """Test for device_class property.""" await setup_samsungtv(hass, MOCK_CONFIG) state = hass.states.get(ENTITY_ID) assert state.attributes[ATTR_DEVICE_CLASS] is MediaPlayerDeviceClass.TV.value
75,779
def sample_user( username='tesuser', email='test@test.com', password='Testpassword_123' ): """Create a sample user""" return get_user_model().objects.create_user(username, email, password,)
75,780
def example_two(): """ - Running factorize in parallel - what's surprising is that this takes even longer. >>> Took 0.246 seconds """ start = time() threads = [] for number in numbers: thread = FactorizeThread(number) thread.start() threads.append(thread) ...
75,781
def min_date_nan(dates): """Find the earliest date from a series that may contain NaNs. Find the earliest date from a pandas series of datetime.dates that may contain NaNs. NaN dates are considered earlier than all others. """ if dates.isna().any(): return np.NaN else: return...
75,782
def to_utctimestamp(a_datetime): """ Calculate number of seconds from UTC 1970-01-01 00:00:00. When: - dt doesn't have tzinfo: assume it's a utc time. - dt has tzinfo: use tzinfo. WARNING, if your datetime object doens't have ``tzinfo``, make sure it's a UTC time, but **NOT a LOCAL TIME**...
75,783
def link_fileset(test): """ link primaryFset provided in configuration file Args: param1: test : contents of configuration file Returns: None Raises: None """ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) fileset_link = "https://"+test["gui...
75,784
def function_with_cpp_args_kwargs(a, b, c=None, d=3, e=(None, "test")): """this is a doctring """ __cpp__ = """ return Py_BuildValue("(O,O,O,O,O)", a, b, c, d, e); """ return None
75,785
def find_keyword( contains=None, startswith=None, endswith=None, directory="./", ): """ Find the specified keyword and reorder the thesaurus to reflect the search. """ thesaurus_file = join(directory, "keywords.txt") if isfile(thesaurus_file): th = load_file_as_dict(thesaur...
75,786
def test_mamba_create(mock_popen, mock_cpopen): """Test running ``edgetest`` with ``mamba``.""" mock_popen.return_value.communicate.return_value = (PIP_LIST_MAMBA, "error") type(mock_popen.return_value).returncode = PropertyMock(return_value=0) mock_cpopen.return_value.communicate.return_value = ("outpu...
75,787
def validated() -> Any: """Decorate an entity to handle validation. This will let ``attrs`` manage the class, using slots for fields, and forcing attributes to be passed as named arguments (this allows to not have to defined all required fields first, then optional ones, and resolves problems with inhe...
75,788
def load_data_command(): """Load minimal data for manual local testing.""" load_data() click.echo("Loaded data.")
75,789
async def test_missing_configuration( hass: HomeAssistant, ) -> None: """Test can't configure when no authentication source is available.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result.get("type") == "abort" a...
75,790
def create_vendor(config): """ POST request to create a Vendor in QBO Refer here for other Vendor fields: https://developer.intuit.com/docs/api/accounting/vendor """ url = config['qbo_base_url'] + '/v3/company/' + config['realm_id'] + '/vendor?minorversion=12' vendor = { ...
75,791
def mean_match_accuracy(predicted, target): """Computes mean of number of matches between some target and some predicted values. Both 'predicted' and 'target' can be either scalars or sequences, but have to be of the same length. """ return np.mean(prediction_target_matches(predicted, target))
75,792
def download_data_and_compare_same(hostname=["http://192.168.50.139:8081/api/","http://192.168.50.139:8080/api/"], dirpath="/opt/lavector/absa/", jsonfile=["192.168.50.139_500_8081_0129.json","192.168.50.139_500_8080_0129.json"], isabsa=True): """ 对比相同的hostname的数据 从label_studio的某个hostname下载数据,然后预测,最后给出结果 ...
75,793
def getDecoderClass(typ): """ Return Decoder class for the PK type. """ for cls in (CentralDirEntry, LocalFileHeader, EndOfCentralDir, DataDescriptor, Zip64EndOfDir, Zip64EndOfDirLocator, ArchiveExtraDataEntry, ArchiveSignature, ): if cls.MagicNumber == typ: return cls
75,794
def connex(vertices: np.ndarray) -> list: """Connection array to build vertex edges for vispy LineVisual. Notes ----- See http://api.vispy.org/en/latest/visuals.html#vispy.visuals.LineVisual """ return [True] * (vertices.shape[0] - 1) + [False]
75,795
def messages_overflow(): """Keeps last 300 messages in database every 10 minutes.""" if os.path.exists('./data.sqlite3'): connection = create_connection("data.sqlite3") delete_old_messages = "DELETE from messages WHERE id not in " \ "(SELECT id FROM messages ORDER...
75,796
def clean_metering_env(cred_json=None, ws_admin=None, product_name=None): """ Clean floating related residues """ if product_name is None: product_name = 'drm_1activator' # Clear metering request from WS DB (not to hit the limit) if (ws_admin is not None) and (cred_json is not None): ...
75,797
def plot_aggregate_features(panels, gff, rad=99, binsize=500): """Plot aggregate Hi-C signal and insulation score for a genomic feature set Plots the aggregate (sum/mean) Hi-C score around a set of features supplied in a gff file, and uses the score feature of the gff to split the features into thi...
75,798
def __parse_options(config_file, section, options): """ Parse the section options :type config_file: ConfigParser object :param config_file: The config file object to use :type section: str :param section: Which section to read in the configuration file :type options: list of dicts :param o...
75,799