file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
client.go
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package pd import ( "github.com/juju/errors" "github.com/ngaut/log" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" ) // Client is a PD (Placement Driver) client. // It should not be used after calling Close(). type Client interface { // GetTS gets a timestamp from PD. GetTS() (int64, int64, error) // GetRegion gets a region and its leader Peer from PD by key. // The region may expire after split. Caller is responsible for caching and // taking care of region change. // Also it may return nil if PD finds no Region for the key temporarily, // client should retry later. GetRegion(key []byte) (*metapb.Region, *metapb.Peer, error) // GetStore gets a store from PD by store id. // The store may expire later. Caller is responsible for caching and taking care // of store change. GetStore(storeID uint64) (*metapb.Store, error) // Close closes the client. Close() } type client struct { worker *rpcWorker } // NewClient creates a PD client. func NewClient(pdAddrs []string, clusterID uint64) (Client, error) { log.Infof("[pd] create pd client with endpoints %v", pdAddrs) client := &client{ worker: newRPCWorker(pdAddrs, clusterID), } return client, nil } func (c *client) Close() { c.worker.stop(errors.New("[pd] pd-client closing")) } func (c *client) GetTS() (int64, int64, error) { req := &tsoRequest{ done: make(chan error, 1), } c.worker.requests <- req
func (c *client) GetRegion(key []byte) (*metapb.Region, *metapb.Peer, error) { req := &regionRequest{ pbReq: &pdpb.GetRegionRequest{ RegionKey: key, }, done: make(chan error, 1), } c.worker.requests <- req err := <-req.done if err != nil { return nil, nil, errors.Trace(err) } return req.pbResp.GetRegion(), req.pbResp.GetLeader(), nil } func (c *client) GetStore(storeID uint64) (*metapb.Store, error) { req := &storeRequest{ pbReq: &pdpb.GetStoreRequest{ StoreId: storeID, }, done: make(chan error, 1), } c.worker.requests <- req err := <-req.done if err != nil { return nil, errors.Trace(err) } store := req.pbResp.GetStore() if store == nil { return nil, errors.New("[pd] store field in rpc response not set") } if store.GetState() == metapb.StoreState_Tombstone { return nil, nil } return store, nil }
err := <-req.done return req.physical, req.logical, err }
test.rs
// Copyright (c) Aptos
use super::*; use proptest::prelude::*; use schemadb::{schema::fuzzing::assert_encode_decode, test_no_panic_decoding}; proptest! { #[test] fn test_encode_decode( event_key in any::<EventKey>(), seq_num in any::<u64>(), version in any::<Version>(), index in any::<u64>(), ) { assert_encode_decode::<EventByVersionSchema>(&(event_key, version, seq_num), &index); } } test_no_panic_decoding!(EventByVersionSchema);
// SPDX-License-Identifier: Apache-2.0
test_datastore_execute.py
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import tempfile import unittest import numpy as np import pandas as pd import mars.dataframe as md from mars.config import option_context from mars.dataframe import DataFrame from mars.deploy.local.core import new_cluster from mars.session import new_session from mars.tests.core import TestBase, flaky try: import vineyard except ImportError: vineyard = None try: import sqlalchemy except ImportError: sqlalchemy = None try: import pyarrow as pa except ImportError: pa = None try: import fastparquet except ImportError: fastparquet = None _exec_timeout = 120 if 'CI' in os.environ else -1 class Test(TestBase): def setUp(self): super().setUp() self.ctx, self.executor = self._create_test_context() def testToCSVExecution(self): index = pd.RangeIndex(100, 0, -1, name='index') raw = pd.DataFrame({ 'col1': np.random.rand(100), 'col2': np.random.choice(['a', 'b', 'c'], (100,)), 'col3': np.arange(100) }, index=index) df = DataFrame(raw, chunk_size=33) with tempfile.TemporaryDirectory() as base_path: # DATAFRAME TESTS # test one file with dataframe path = os.path.join(base_path, 'out.csv') r = df.to_csv(path) self.executor.execute_dataframe(r) result = pd.read_csv(path, dtype=raw.dtypes.to_dict()) result.set_index('index', inplace=True) pd.testing.assert_frame_equal(result, raw) # test multi files with dataframe path = os.path.join(base_path, 'out-*.csv') r = df.to_csv(path) self.executor.execute_dataframe(r) dfs = [pd.read_csv(os.path.join(base_path, f'out-{i}.csv'), dtype=raw.dtypes.to_dict()) for i in range(4)] result = pd.concat(dfs, axis=0) result.set_index('index', inplace=True) pd.testing.assert_frame_equal(result, raw) pd.testing.assert_frame_equal(dfs[1].set_index('index'), raw.iloc[33: 66]) with self.ctx: # test df with unknown shape df2 = DataFrame(raw, chunk_size=(50, 2)) df2 = df2[df2['col1'] < 1] path2 = os.path.join(base_path, 'out2.csv') r = df2.to_csv(path2) self.executor.execute_dataframes([r]) result = pd.read_csv(path2, dtype=raw.dtypes.to_dict()) result.set_index('index', inplace=True) pd.testing.assert_frame_equal(result, raw) # SERIES TESTS series = md.Series(raw.col1, chunk_size=33) # test one file with series path = os.path.join(base_path, 'out.csv') r = series.to_csv(path) self.executor.execute_dataframe(r) result = pd.read_csv(path, dtype=raw.dtypes.to_dict()) result.set_index('index', inplace=True) pd.testing.assert_frame_equal(result, raw.col1.to_frame()) # test multi files with series path = os.path.join(base_path, 'out-*.csv') r = series.to_csv(path) self.executor.execute_dataframe(r) dfs = [pd.read_csv(os.path.join(base_path, f'out-{i}.csv'), dtype=raw.dtypes.to_dict()) for i in range(4)] result = pd.concat(dfs, axis=0) result.set_index('index', inplace=True) pd.testing.assert_frame_equal(result, raw.col1.to_frame()) pd.testing.assert_frame_equal(dfs[1].set_index('index'), raw.col1.to_frame().iloc[33: 66]) @unittest.skipIf(sqlalchemy is None, 'sqlalchemy not installed') def testToSQL(self): index = pd.RangeIndex(100, 0, -1, name='index') raw = pd.DataFrame({ 'col1': np.random.rand(100), 'col2': np.random.choice(['a', 'b', 'c'], (100,)), 'col3': np.arange(100).astype('int64'), }, index=index) with tempfile.TemporaryDirectory() as d: table_name1 = 'test_table' table_name2 = 'test_table2' uri = 'sqlite:///' + os.path.join(d, 'test.db') engine = sqlalchemy.create_engine(uri) # test write dataframe df = DataFrame(raw, chunk_size=33) r = df.to_sql(table_name1, con=engine) self.executor.execute_dataframe(r) written = pd.read_sql(table_name1, con=engine, index_col='index') \ .sort_index(ascending=False) pd.testing.assert_frame_equal(raw, written) # test write with existing table with self.assertRaises(ValueError): df.to_sql(table_name1, con=uri).execute() # test write series series = md.Series(raw.col1, chunk_size=33) with engine.connect() as conn: r = series.to_sql(table_name2, con=conn) self.executor.execute_dataframe(r) written = pd.read_sql(table_name2, con=engine, index_col='index') \ .sort_index(ascending=False) pd.testing.assert_frame_equal(raw.col1.to_frame(), written) @unittest.skipIf(vineyard is None, 'vineyard not installed') @flaky(max_runs=3) def
(self): def run_with_given_session(session, **kw): ipc_socket = os.environ.get('VINEYARD_IPC_SOCKET', '/tmp/vineyard/vineyard.sock') with option_context({'vineyard.socket': ipc_socket}): df1 = DataFrame(pd.DataFrame(np.arange(12).reshape(3, 4), columns=['a', 'b', 'c', 'd']), chunk_size=2) object_id = df1.to_vineyard().execute(session=session, **kw).fetch(session=session) df2 = md.from_vineyard(object_id) df1_value = df1.execute(session=session, **kw).fetch(session=session) df2_value = df2.execute(session=session, **kw).fetch(session=session) pd.testing.assert_frame_equal( df1_value.reset_index(drop=True), df2_value.reset_index(drop=True)) with new_session().as_default() as session: run_with_given_session(session) with new_cluster(scheduler_n_process=2, worker_n_process=2, shared_memory='20M', web=False) as cluster: with new_session(cluster.endpoint).as_default() as session: run_with_given_session(session, timeout=_exec_timeout) @unittest.skipIf(pa is None, 'pyarrow not installed') def testToParquetArrowExecution(self): raw = pd.DataFrame({ 'col1': np.random.rand(100), 'col2': np.arange(100), 'col3': np.random.choice(['a', 'b', 'c'], (100,)), }) df = DataFrame(raw, chunk_size=33) with tempfile.TemporaryDirectory() as base_path: # DATAFRAME TESTS path = os.path.join(base_path, 'out-*.parquet') r = df.to_parquet(path) self.executor.execute_dataframe(r) read_df = md.read_parquet(path) result = self.executor.execute_dataframe(read_df, concat=True)[0] result = result.sort_index() pd.testing.assert_frame_equal(result, raw) read_df = md.read_parquet(path) result = self.executor.execute_dataframe(read_df, concat=True)[0] result = result.sort_index() pd.testing.assert_frame_equal(result, raw) # test read_parquet then to_parquet read_df = md.read_parquet(path) r = read_df.to_parquet(path) self.executor.execute_dataframes([r]) # test partition_cols path = os.path.join(base_path, 'out-partitioned') r = df.to_parquet(path, partition_cols=['col3']) self.executor.execute_dataframe(r) read_df = md.read_parquet(path) result = self.executor.execute_dataframe(read_df, concat=True)[0] result['col3'] = result['col3'].astype('object') pd.testing.assert_frame_equal(result.sort_values('col1').reset_index(drop=True), raw.sort_values('col1').reset_index(drop=True)) @unittest.skipIf(fastparquet is None, 'fastparquet not installed') def testToParquetFastParquetExecution(self): raw = pd.DataFrame({ 'col1': np.random.rand(100), 'col2': np.arange(100), 'col3': np.random.choice(['a', 'b', 'c'], (100,)), }) df = DataFrame(raw, chunk_size=33) with tempfile.TemporaryDirectory() as base_path: # test fastparquet path = os.path.join(base_path, 'out-fastparquet-*.parquet') r = df.to_parquet(path, engine='fastparquet', compression='gzip') self.executor.execute_dataframe(r)
testToVineyard
check.go
package states import ( "bytes" addr "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "golang.org/x/xerrors" "github.com/filecoin-project/specs-actors/v7/actors/builtin/power" "github.com/filecoin-project/specs-actors/v7/actors/builtin" "github.com/filecoin-project/specs-actors/v7/actors/builtin/account" "github.com/filecoin-project/specs-actors/v7/actors/builtin/cron" init_ "github.com/filecoin-project/specs-actors/v7/actors/builtin/init" "github.com/filecoin-project/specs-actors/v7/actors/builtin/market" "github.com/filecoin-project/specs-actors/v7/actors/builtin/miner" "github.com/filecoin-project/specs-actors/v7/actors/builtin/multisig" "github.com/filecoin-project/specs-actors/v7/actors/builtin/paych" "github.com/filecoin-project/specs-actors/v7/actors/builtin/reward" "github.com/filecoin-project/specs-actors/v7/actors/builtin/verifreg" ) // Within this code, Go errors are not expected, but are often converted to messages so that execution // can continue to find more errors rather than fail with no insight. // Only errors thar are particularly troublesome to recover from should propagate as Go errors. func CheckStateInvariants(tree *Tree, expectedBalanceTotal abi.TokenAmount, priorEpoch abi.ChainEpoch) (*builtin.MessageAccumulator, error) { acc := &builtin.MessageAccumulator{} totalFIl := big.Zero() var initSummary *init_.StateSummary var cronSummary *cron.StateSummary var verifregSummary *verifreg.StateSummary var marketSummary *market.StateSummary var rewardSummary *reward.StateSummary var accountSummaries []*account.StateSummary var powerSummary *power.StateSummary var paychSummaries []*paych.StateSummary var multisigSummaries []*multisig.StateSummary minerSummaries := make(map[addr.Address]*miner.StateSummary) if err := tree.ForEach(func(key addr.Address, actor *Actor) error { acc := acc.WithPrefix("%v ", key) // Intentional shadow if key.Protocol() != addr.ID { acc.Addf("unexpected address protocol in state tree root: %v", key) } totalFIl = big.Add(totalFIl, actor.Balance) switch actor.Code { case builtin.SystemActorCodeID: case builtin.InitActorCodeID: var st init_.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := init_.CheckStateInvariants(&st, tree.Store) acc.WithPrefix("init: ").AddAll(msgs) initSummary = summary case builtin.CronActorCodeID: var st cron.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := cron.CheckStateInvariants(&st, tree.Store) acc.WithPrefix("cron: ").AddAll(msgs) cronSummary = summary case builtin.AccountActorCodeID: var st account.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := account.CheckStateInvariants(&st, key) acc.WithPrefix("account: ").AddAll(msgs) accountSummaries = append(accountSummaries, summary) case builtin.StoragePowerActorCodeID: var st power.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := power.CheckStateInvariants(&st, tree.Store) acc.WithPrefix("power: ").AddAll(msgs) powerSummary = summary case builtin.StorageMinerActorCodeID: var st miner.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := miner.CheckStateInvariants(&st, tree.Store, actor.Balance) acc.WithPrefix("miner: ").AddAll(msgs) minerSummaries[key] = summary case builtin.StorageMarketActorCodeID: var st market.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := market.CheckStateInvariants(&st, tree.Store, actor.Balance, priorEpoch) acc.WithPrefix("market: ").AddAll(msgs) marketSummary = summary case builtin.PaymentChannelActorCodeID: var st paych.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := paych.CheckStateInvariants(&st, tree.Store, actor.Balance) acc.WithPrefix("paych: ").AddAll(msgs) paychSummaries = append(paychSummaries, summary) case builtin.MultisigActorCodeID: var st multisig.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := multisig.CheckStateInvariants(&st, tree.Store) acc.WithPrefix("multisig: ").AddAll(msgs) multisigSummaries = append(multisigSummaries, summary) case builtin.RewardActorCodeID: var st reward.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := reward.CheckStateInvariants(&st, tree.Store, priorEpoch, actor.Balance) acc.WithPrefix("reward: ").AddAll(msgs) rewardSummary = summary case builtin.VerifiedRegistryActorCodeID: var st verifreg.State if err := tree.Store.Get(tree.Store.Context(), actor.Head, &st); err != nil { return err } summary, msgs := verifreg.CheckStateInvariants(&st, tree.Store) acc.WithPrefix("verifreg: ").AddAll(msgs) verifregSummary = summary default: return xerrors.Errorf("unexpected actor code CID %v for address %v", actor.Code, key) } return nil }); err != nil { return nil, err } // // Perform cross-actor checks from state summaries here. // CheckMinersAgainstPower(acc, minerSummaries, powerSummary) CheckDealStatesAgainstSectors(acc, minerSummaries, marketSummary) _ = initSummary _ = verifregSummary _ = cronSummary _ = marketSummary _ = rewardSummary if !totalFIl.Equals(expectedBalanceTotal) { acc.Addf("total token balance is %v, expected %v", totalFIl, expectedBalanceTotal) } return acc, nil } func CheckMinersAgainstPower(acc *builtin.MessageAccumulator, minerSummaries map[addr.Address]*miner.StateSummary, powerSummary *power.StateSummary) { for addr, minerSummary := range minerSummaries { // nolint:nomaprange // check claim claim, ok := powerSummary.Claims[addr] acc.Require(ok, "miner %v has no power claim", addr)
acc.Require(minerSummary.WindowPoStProofType == claim.WindowPoStProofType, "miner seal proof type %d does not match claim proof type %d", minerSummary.WindowPoStProofType, claim.WindowPoStProofType) } // check crons crons, ok := powerSummary.Crons[addr] if !ok { // with deferred and discontinued crons it is normal for a miner actor to have no cron events continue } var payload miner.CronEventPayload var provingPeriodCron *power.MinerCronEvent for _, event := range crons { err := payload.UnmarshalCBOR(bytes.NewReader(event.Payload)) acc.Require(err == nil, "miner %v registered cron at epoch %d with wrong or corrupt payload", addr, event.Epoch) acc.Require(payload.EventType == miner.CronEventProcessEarlyTerminations || payload.EventType == miner.CronEventProvingDeadline, "miner %v has unexpected cron event type %v", addr, payload.EventType) if payload.EventType == miner.CronEventProvingDeadline { if provingPeriodCron != nil { acc.Require(false, "miner %v has duplicate proving period crons at epoch %d and %d", addr, provingPeriodCron.Epoch, event.Epoch) } provingPeriodCron = &event } } hasProvingPeriodCron := provingPeriodCron != nil acc.Require(hasProvingPeriodCron == minerSummary.DeadlineCronActive, "miner %v has invalid DeadlineCronActive (%t) for hasProvingPeriodCron status (%t)", addr, minerSummary.DeadlineCronActive, hasProvingPeriodCron) acc.Require(provingPeriodCron != nil, "miner %v has no proving period cron", addr) } } func CheckDealStatesAgainstSectors(acc *builtin.MessageAccumulator, minerSummaries map[addr.Address]*miner.StateSummary, marketSummary *market.StateSummary) { // Check that all active deals are included within a non-terminated sector. // We cannot check that all deals referenced within a sector are in the market, because deals // can be terminated independently of the sector in which they are included. for dealID, deal := range marketSummary.Deals { // nolint:nomaprange if deal.SectorStartEpoch == abi.ChainEpoch(-1) { // deal hasn't been activated yet, make no assertions about sector state continue } minerSummary, found := minerSummaries[deal.Provider] if !found { acc.Addf("provider %v for deal %d not found among miners", deal.Provider, dealID) continue } sectorDeal, found := minerSummary.Deals[dealID] if !found { acc.Require(deal.SlashEpoch >= 0, "un-slashed deal %d not referenced in active sectors of miner %v", dealID, deal.Provider) continue } acc.Require(deal.SectorStartEpoch == sectorDeal.SectorStart, "deal state start %d does not match sector start %d for miner %v", deal.SectorStartEpoch, sectorDeal.SectorStart, deal.Provider) acc.Require(deal.SectorStartEpoch <= sectorDeal.SectorExpiration, "deal state start %d activated after sector expiration %d for miner %v", deal.SectorStartEpoch, sectorDeal.SectorExpiration, deal.Provider) acc.Require(deal.LastUpdatedEpoch <= sectorDeal.SectorExpiration, "deal state update at %d after sector expiration %d for miner %v", deal.LastUpdatedEpoch, sectorDeal.SectorExpiration, deal.Provider) acc.Require(deal.SlashEpoch <= sectorDeal.SectorExpiration, "deal state slashed at %d after sector expiration %d for miner %v", deal.SlashEpoch, sectorDeal.SectorExpiration, deal.Provider) } }
if ok { claimPower := miner.NewPowerPair(claim.RawBytePower, claim.QualityAdjPower) acc.Require(minerSummary.ActivePower.Equals(claimPower), "miner %v computed active power %v does not match claim %v", addr, minerSummary.ActivePower, claimPower)
coinwallet.go
// Copyright (c) 2013-2015 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package main import ( "io/ioutil" "net" "net/http" _ "net/http/pprof" "os" "path/filepath" "runtime" "sync" "github.com/coinsuite/coinwallet/chain" "github.com/coinsuite/coinwallet/rpc/legacyrpc" "github.com/coinsuite/coinwallet/wallet" "github.com/coinsuite/coinwallet/walletdb" "github.com/coinsuite/neutrino" ) var ( cfg *config ) func main() { // Use all processor cores. runtime.GOMAXPROCS(runtime.NumCPU()) // Work around defer not working after os.Exit. if err := walletMain(); err != nil { os.Exit(1) } } // walletMain is a work-around main function that is required since deferred // functions (such as log flushing) are not called with calls to os.Exit. // Instead, main runs this function and checks for a non-nil error, at which // point any defers have already run, and if the error is non-nil, the program // can be exited with an error exit status. func walletMain() error { // Load configuration and parse command line. This function also // initializes logging and configures it accordingly. tcfg, _, err := loadConfig() if err != nil { return err } cfg = tcfg defer func() { if logRotator != nil { logRotator.Close() } }() // Show version at startup. log.Infof("Version %s", version()) if cfg.Profile != "" { go func() { listenAddr := net.JoinHostPort("", cfg.Profile) log.Infof("Profile server listening on %s", listenAddr) profileRedirect := http.RedirectHandler("/debug/pprof", http.StatusSeeOther) http.Handle("/", profileRedirect) log.Errorf("%v", http.ListenAndServe(listenAddr, nil)) }() } dbDir := networkDir(cfg.AppDataDir.Value, activeNet.Params) loader := wallet.NewLoader(activeNet.Params, dbDir, 250) // Create and start HTTP server to serve wallet client connections. // This will be updated with the wallet and chain server RPC client // created below after each is created. rpcs, legacyRPCServer, err := startRPCServers(loader) if err != nil { log.Errorf("Unable to create RPC servers: %v", err) return err } // Create and start chain RPC client so it's ready to connect to // the wallet when loaded later. if !cfg.NoInitialLoad { go rpcClientConnectLoop(legacyRPCServer, loader) } loader.RunAfterLoad(func(w *wallet.Wallet) { startWalletRPCServices(w, rpcs, legacyRPCServer) }) if !cfg.NoInitialLoad { // Load the wallet database. It must have been created already // or this will return an appropriate error. _, err = loader.OpenExistingWallet([]byte(cfg.WalletPass), true) if err != nil { log.Error(err) return err } } // Add interrupt handlers to shutdown the various process components // before exiting. Interrupt handlers run in LIFO order, so the wallet // (which should be closed last) is added first. addInterruptHandler(func() { err := loader.UnloadWallet() if err != nil && err != wallet.ErrNotLoaded { log.Errorf("Failed to close wallet: %v", err) } }) if rpcs != nil { addInterruptHandler(func() { // TODO: Does this need to wait for the grpc server to // finish up any requests? log.Warn("Stopping RPC server...") rpcs.Stop() log.Info("RPC server shutdown") }) } if legacyRPCServer != nil { addInterruptHandler(func() { log.Warn("Stopping legacy RPC server...") legacyRPCServer.Stop() log.Info("Legacy RPC server shutdown") }) go func() { <-legacyRPCServer.RequestProcessShutdown() simulateInterrupt() }() } <-interruptHandlersDone log.Info("Shutdown complete") return nil } // rpcClientConnectLoop continuously attempts a connection to the consensus RPC // server. When a connection is established, the client is used to sync the // loaded wallet, either immediately or when loaded at a later time. // // The legacy RPC is optional. If set, the connected RPC client will be // associated with the server for RPC passthrough and to enable additional // methods. func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Loader) { var certs []byte if !cfg.UseSPV { certs = readCAFile() } for { var ( chainClient chain.Interface err error ) if cfg.UseSPV { var ( chainService *neutrino.ChainService spvdb walletdb.DB ) netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params) spvdb, err = walletdb.Create("bdb", filepath.Join(netDir, "neutrino.db")) defer spvdb.Close() if err != nil { log.Errorf("Unable to create Neutrino DB: %s", err) continue } chainService, err = neutrino.NewChainService( neutrino.Config{ DataDir: netDir, Database: spvdb, ChainParams: *activeNet.Params, ConnectPeers: cfg.ConnectPeers, AddPeers: cfg.AddPeers, }) if err != nil { log.Errorf("Couldn't create Neutrino ChainService: %s", err) continue } chainClient = chain.NewNeutrinoClient(activeNet.Params, chainService) err = chainClient.Start() if err != nil { log.Errorf("Couldn't start Neutrino client: %s", err) } } else { chainClient, err = startChainRPC(certs) if err != nil { log.Errorf("Unable to open connection to consensus RPC server: %v", err) continue } } // Rather than inlining this logic directly into the loader // callback, a function variable is used to avoid running any of // this after the client disconnects by setting it to nil. This // prevents the callback from associating a wallet loaded at a // later time with a client that has already disconnected. A // mutex is used to make this concurrent safe. associateRPCClient := func(w *wallet.Wallet) { w.SynchronizeRPC(chainClient) if legacyRPCServer != nil { legacyRPCServer.SetChainServer(chainClient) } } mu := new(sync.Mutex) loader.RunAfterLoad(func(w *wallet.Wallet) { mu.Lock() associate := associateRPCClient mu.Unlock() if associate != nil { associate(w) } }) chainClient.WaitForShutdown() mu.Lock() associateRPCClient = nil mu.Unlock() loadedWallet, ok := loader.LoadedWallet() if ok { // Do not attempt a reconnect when the wallet was // explicitly stopped. if loadedWallet.ShuttingDown() { return } loadedWallet.SetChainSynced(false) // TODO: Rework the wallet so changing the RPC client // does not require stopping and restarting everything. loadedWallet.Stop() loadedWallet.WaitForShutdown() loadedWallet.Start() } } } func readCAFile() []byte { // Read certificate file if TLS is not disabled. var certs []byte if !cfg.DisableClientTLS { var err error certs, err = ioutil.ReadFile(cfg.CAFile.Value) if err != nil { log.Warnf("Cannot open CA file: %v", err) // If there's an error reading the CA file, continue // with nil certs and without the client connection. certs = nil } } else { log.Info("Chain server RPC TLS is disabled") } return certs } // startChainRPC opens a RPC client connection to a btcd server for blockchain // services. This function uses the RPC options from the global config and // there is no recovery in case the server is not available or if there is an // authentication error. Instead, all requests to the client will simply error. func
(certs []byte) (*chain.RPCClient, error) { log.Infof("Attempting RPC client connection to %v", cfg.RPCConnect) rpcc, err := chain.NewRPCClient(activeNet.Params, cfg.RPCConnect, cfg.BtcdUsername, cfg.BtcdPassword, certs, cfg.DisableClientTLS, 0) if err != nil { return nil, err } err = rpcc.Start() return rpcc, err }
startChainRPC
gdcvault.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( HEADRequest, sanitized_Request, urlencode_postdata, ) class GDCVaultIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?' _NETRC_MACHINE = 'gdcvault' _TESTS = [ { 'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple', 'md5': '7ce8388f544c88b7ac11c7ab1b593704', 'info_dict': { 'id': '1019721', 'display_id': 'Doki-Doki-Universe-Sweet-Simple', 'ext': 'mp4', 'title': 'Doki-Doki Universe: Sweet, Simple and Genuine (GDC Next 10)' } }, { 'url': 'http://www.gdcvault.com/play/1015683/Embracing-the-Dark-Art-of', 'info_dict': { 'id': '1015683', 'display_id': 'Embracing-the-Dark-Art-of', 'ext': 'flv', 'title': 'Embracing the Dark Art of Mathematical Modeling in AI' }, 'params': { 'skip_download': True, # Requires rtmpdump } }, { 'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or', 'md5': 'a5eb77996ef82118afbbe8e48731b98e', 'info_dict': { 'id': '1015301', 'display_id': 'Thexder-Meets-Windows-95-or', 'ext': 'flv', 'title': 'Thexder Meets Windows 95, or Writing Great Games in the Windows 95 Environment', }, 'skip': 'Requires login', }, { 'url': 'http://gdcvault.com/play/1020791/', 'only_matching': True, }, { # Hard-coded hostname 'url': 'http://gdcvault.com/play/1023460/Tenacious-Design-and-The-Interface', 'md5': 'a8efb6c31ed06ca8739294960b2dbabd', 'info_dict': { 'id': '1023460', 'ext': 'mp4', 'display_id': 'Tenacious-Design-and-The-Interface', 'title': 'Tenacious Design and The Interface of \'Destiny\'', }, }, { # Multiple audios 'url': 'http://www.gdcvault.com/play/1014631/Classic-Game-Postmortem-PAC', 'info_dict': { 'id': '1014631', 'ext': 'flv', 'title': 'How to Create a Good Game - From My Experience of Designing Pac-Man', }, 'params': { 'skip_download': True, # Requires rtmpdump 'format': 'jp', # The japanese audio } }, { # gdc-player.html 'url': 'http://www.gdcvault.com/play/1435/An-American-engine-in-Tokyo', 'info_dict': { 'id': '1435', 'display_id': 'An-American-engine-in-Tokyo', 'ext': 'flv', 'title': 'An American Engine in Tokyo:/nThe collaboration of Epic Games and Square Enix/nFor THE LAST REMINANT', }, 'params': { 'skip_download': True, # Requires rtmpdump }, }, ] def _login(self, webpage_url, display_id): (username, password) = self._get_login_info() if username is None or password is None: self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.') return None mobj = re.match(r'(?P<root_url>https?://.*?/).*', webpage_url) login_url = mobj.group('root_url') + 'api/login.php' logout_url = mobj.group('root_url') + 'logout' login_form = { 'email': username, 'password': password, } request = sanitized_Request(login_url, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') self._download_webpage(request, display_id, 'Logging in') start_page = self._download_webpage(webpage_url, display_id, 'Getting authenticated video page') self._download_webpage(logout_url, display_id, 'Logging out') return start_page def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('name') or video_id webpage_url = 'http://www.gdcvault.com/play/' + video_id start_page = self._download_webpage(webpage_url, display_id) direct_url = self._search_regex( r's1\.addVariable\("file",\s*encodeURIComponent\("(/[^"]+)"\)\);', start_page, 'url', default=None) if direct_url: title = self._html_search_regex( r'<td><strong>Session Name</strong></td>\s*<td>(.*?)</td>', start_page, 'title') video_url = 'http://www.gdcvault.com' + direct_url # resolve the url so that we can detect the correct extension head = self._request_webpage(HEADRequest(video_url), video_id) video_url = head.geturl() return { 'id': video_id, 'display_id': display_id, 'url': video_url, 'title': title, } PLAYER_REGEX = r'<iframe src="(?P<xml_root>.+?)/(?:gdc-)?player.*?\.html.*?".*?</iframe>' xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root', default=None) if xml_root is None: # Probably need to authenticate login_res = self._login(webpage_url, display_id) if login_res is None: self.report_warning('Could not login.') else: start_page = login_res # Grab the url from the authenticated page xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root') xml_name = self._html_search_regex( r'<iframe src=".*?\?xml=(.+?\.xml).*?".*?</iframe>', start_page, 'xml filename', default=None) if xml_name is None: # Fallback to the older format xml_name = self._html_search_regex(
start_page, 'xml filename') return { '_type': 'url_transparent', 'id': video_id, 'display_id': display_id, 'url': '%s/xml/%s' % (xml_root, xml_name), 'ie_key': 'DigitallySpeaking', }
r'<iframe src=".*?\?xmlURL=xml/(?P<xml_file>.+?\.xml).*?".*?</iframe>',
python_systems.py
"""Example systems created in Python """ import numpy as np from pysim.cythonsystem import Sys class VanDerPol(Sys): """Simple example of a class representing a VanDerPol oscillator. """ def __init__(self): self.add_state_scalar("x", "dx") self.add_state_scalar("y", "dy") self.add_input_scalar("a") self.add_input_scalar("b") self.inputs.a = 1.0 self.inputs.b = 1.0 self.states.x = 1.0 self.states.y = 0.0 def do_step(self,dummy): """Perform a timestep by implmenting the VanDerPol equations""" a = self.inputs.a b = self.inputs.b x = self.states.x y = self.states.y self.ders.dx = a*x*(b-y*y)-y self.ders.dy = x class MassSpringDamper(Sys): """Simple class for testing the mass-spring-damper simulations with a cython system""" def __init__(self): """Setup two states (one dimensional vectors for now). Initial conditions are simular to those in the build in c++ system""" self.add_state_scalar("x1", "dx1") self.add_state_scalar("x2", "dx2") self.states.x1 = 1 self.states.x2 = 0 def do_step(self,dummy): """Perform a step using default constants, same as those in the cpp system""" m = 100.0 b = 1.0 k = 50.0 f = 0.0 x1 = self.states.x1 x2 = self.states.x2 self.ders.dx1 = x2 self.ders.dx2 =-k/m*x1-b/m*x2+1/m*f class
(Sys): """Python representation of the cpp InOutTestSystem Used for testing that the cpp system behaves as the python system with regards to the input output handling """ def __init__(self): self.add_input_scalar("input_scalar") self.add_input_vector("input_vector",3) self.add_input_matrix("input_matrix",3,3) self.add_state_scalar("state_scalar","der_scalar") self.add_state_vector("state_vector","der_vector", 3) self.add_state_matrix("state_matrix","der_matrix", 3, 3) self.add_output_scalar("input_output_scalar") self.add_output_vector("input_output_vector",3) self.add_output_matrix("input_output_matrix",3,3) self.add_output_scalar("state_output_scalar") self.add_output_vector("state_output_vector",3) self.add_output_matrix("state_output_matrix",3,3) self.inputs.input_scalar = 0.0 self.inputs.input_vector = [0.0, 0.0, 0.0] self.inputs.input_matrix = np.zeros((3,3)) self.outputs.input_output_scalar = 0.0 self.outputs.input_output_vector = [0.0, 0.0, 0.0] self.outputs.input_output_matrix = np.zeros((3,3)) self.outputs.state_output_scalar = 0.0 self.outputs.state_output_vector = [0.0, 0.0, 0.0] self.outputs.state_output_matrix = np.zeros((3,3)) self.states.state_scalar = 1.23 self.states.state_vector = np.ones(3)*4.56 self.states.state_matrix = np.ones((3,3))*7.89 self.ders.der_scalar = 0 self.ders.der_vector = np.zeros(3) self.ders.der_matrix = np.zeros((3,3)) def do_step(self,dummy): """During a timestep we set the outputs to their respective inputs""" self.outputs.input_output_scalar = self.inputs.input_scalar self.outputs.input_output_vector = self.inputs.input_vector self.outputs.input_output_matrix = self.inputs.input_matrix self.outputs.state_output_scalar = self.states.state_scalar self.outputs.state_output_vector = self.states.state_vector self.outputs.state_output_matrix = self.states.state_matrix
InOutTestSystem
guardConfig.js
const GuardConfig = { registerMethods: ['email'], loginMethods: ['password'], mode: 'modal',
logo: 'https://static.nicegoodthings.com/project/ext/wb.logo.png', title: 'Webrowse', socialConnections: ['github', 'google'], appHost: "https://portal-lite-china.authing.cn", lang: 'en-US' }; const appId = '6034a70af621af721e5320b9' export { appId, GuardConfig } export default GuardConfig
oauth2.test.js
// Copyright 2018, Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const test = require(`ava`); const sinon = require(`sinon`); const request = require(`supertest`); const proxyquire = require(`proxyquire`).noPreserveCache(); const getPassportMock = () => { return { initialize: sinon.stub().returns((req, res, next) => { next(); }), session: sinon.stub().returns((req, res, next) => { next(); }), use: sinon.stub(), serializeUser: sinon.stub(), deserializeUser: sinon.stub(), authenticate: sinon.stub().returns((req, res, next) => { req.session.oauth2return = `/another/path`; next(); }), }; }; test.cb(`should start authorization`, t => { const passportMock = getPassportMock(); passportMock.authenticate = sinon.stub().returns((req, res) => { t.is(req.session.oauth2return, `/some/path`); res.redirect(`/auth/google/callback?code=foo`); }); const app = proxyquire(`../app`, { passport: passportMock, './lib/oauth2': proxyquire(`../lib/oauth2`, { passport: passportMock, }), }); request(app) .get(`/auth/login?return=%2Fsome%2Fpath`) .expect(302) .expect(response => { const text = response.text; t.regex(text, /Redirecting to \/auth\/google\/callback\?code=foo/); t.true(passportMock.initialize.calledOnce); t.true(passportMock.session.calledOnce); t.true(passportMock.use.calledOnce); t.true(passportMock.serializeUser.calledOnce); t.true(passportMock.deserializeUser.calledOnce); t.true(passportMock.authenticate.calledTwice); t.is(passportMock.authenticate.firstCall.args[0], `google`); t.deepEqual(passportMock.authenticate.firstCall.args[1], { scope: [`email`, `profile`], }); t.is(passportMock.authenticate.secondCall.args[0], `google`); t.is(passportMock.authenticate.secondCall.args[1], undefined); }) .end(t.end); }); test.cb(`should finish authorization`, t => { const passportMock = getPassportMock(); const oauth2 = proxyquire(`../lib/oauth2`, { passport: passportMock, }); const app = proxyquire(`../app`, { passport: passportMock, './lib/oauth2': oauth2, }); request(app) .get(`/auth/google/callback?code=foo`) .expect(302) .expect(response => { const text = response.text; t.regex(text, /Redirecting to \/another\/path/); t.true(passportMock.initialize.calledOnce); t.true(passportMock.session.calledOnce); t.true(passportMock.use.calledOnce); t.true(passportMock.serializeUser.calledOnce); t.true(passportMock.deserializeUser.calledOnce); t.true(passportMock.authenticate.calledTwice); t.is(passportMock.authenticate.firstCall.args[0], `google`); t.deepEqual(passportMock.authenticate.firstCall.args[1], { scope: [`email`, `profile`], }); t.is(passportMock.authenticate.secondCall.args[0], `google`); t.is(passportMock.authenticate.secondCall.args[1], undefined); t.deepEqual( oauth2.extractProfile({
}), { id: 1, displayName: `Joe Developer`, image: `image.jpg`, } ); const serializeUser = passportMock.serializeUser.firstCall.args[0]; const deserializeUser = passportMock.deserializeUser.firstCall.args[0]; const user = {}; const obj = {}; serializeUser(user, (err, _user) => { t.is(err, null); t.is(_user, user); }); deserializeUser(obj, (err, _obj) => { t.is(err, null); t.is(_obj, obj); }); }) .end(t.end); }); test.cb(`should logout`, t => { const passportMock = getPassportMock(); const app = proxyquire(`../app`, { passport: passportMock, './lib/oauth2': proxyquire(`../lib/oauth2`, { passport: passportMock, }), }); request(app) .get(`/auth/logout`) .expect(302) .expect(response => { const text = response.text; t.regex(text, /Redirecting to \//); t.true(passportMock.initialize.calledOnce); t.true(passportMock.session.calledOnce); t.true(passportMock.use.calledOnce); t.true(passportMock.serializeUser.calledOnce); t.true(passportMock.deserializeUser.calledOnce); t.true(passportMock.authenticate.calledTwice); t.is(passportMock.authenticate.firstCall.args[0], `google`); t.deepEqual(passportMock.authenticate.firstCall.args[1], { scope: [`email`, `profile`], }); t.is(passportMock.authenticate.secondCall.args[0], `google`); t.is(passportMock.authenticate.secondCall.args[1], undefined); }) .end(t.end); }); test(`should require authentication`, t => { const passportMock = getPassportMock(); const oauth2 = proxyquire(`../lib/oauth2`, { passport: passportMock, }); const req = { originalUrl: `/some/path`, user: {}, session: {}, }; const res = { redirect: sinon.stub(), }; const next = sinon.stub(); oauth2.required(req, res, next); t.true(next.calledOnce); req.user = undefined; oauth2.required(req, res, next); t.true(next.calledOnce); t.is(req.session.oauth2return, req.originalUrl); t.true(res.redirect.calledOnce); t.is(res.redirect.firstCall.args[0], `/auth/login`); }); test(`should add template variables`, t => { const passportMock = getPassportMock(); const oauth2 = proxyquire(`../lib/oauth2`, { passport: passportMock, }); const req = { originalUrl: `/some/path`, user: { id: 1, displayName: `Joe Developer`, image: `image.jpg`, }, }; const res = { locals: {}, }; const next = sinon.stub(); oauth2.template(req, res, next); t.true(next.calledOnce); t.is(res.locals.profile, req.user); t.is( res.locals.login, `/auth/login?return=${encodeURIComponent(req.originalUrl)}` ); t.is( res.locals.logout, `/auth/logout?return=${encodeURIComponent(req.originalUrl)}` ); });
photos: [{value: `image.jpg`}], id: 1, displayName: `Joe Developer`,
.eslintrc.js
module.exports = { env: { es6: true, node: true, }, extends: [ 'airbnb-base', 'plugin:jest/recommended', ], globals: { Atomics: 'readonly', SharedArrayBuffer: 'readonly', }, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', }, rules: {
'no-param-reassign': 0, 'no-unused-expressions': 0, }, };
authentication_ts.js
function
() { var err = false; var data = new Object(); var div = document.getElementById("content"); var form = document.getElementById("authentication"); var inputs = div.getElementsByTagName("INPUT"); console.log(inputs); for (var i = inputs.length - 1; i >= 0; i--) { var key = inputs[i].name; var value = inputs[i].value; if (value.length == 0) { inputs[i].style.borderColor = "red"; err = true; } data[key] = value; } if (err == true) { data = new Object(); return; } if (data.hasOwnProperty("confirm")) { if (data["confirm"] != data["password"]) { alert("sdafsd"); document.getElementById('password').style.borderColor = "red"; document.getElementById('confirm').style.borderColor = "red"; document.getElementById("err").innerHTML = "{{.account.failed}}"; return; } } console.log(data); form.submit(); }
login
OapiSmartdeviceBatcheventPostRequest.py
''' Created by auto_sdk on 2020.11.25 ''' from dingtalk.api.base import RestApi class OapiSmartdeviceBatcheventPostRequest(RestApi): def __init__(self,url=None): RestApi.__init__(self,url) self.device_event_vos = None def
(self): return 'POST' def getapiname(self): return 'dingtalk.oapi.smartdevice.batchevent.post'
getHttpMethod
help_el.js
/** @license * Copyright (c) 2013-2017 Ephox Corp. All rights reserved. * This software is provided "AS IS," without a warranty of any kind. */
!function(){var a=function(a){return function(){return a}},b=function(a,b){var c=a.src.indexOf("?");return a.src.indexOf(b)+b.length===c},c=function(a){for(var b=a.split("."),c=window,d=0;d<b.length&&void 0!==c&&null!==c;++d)c=c[b[d]];return c},d=function(a,b){if(a){var d=a.getAttribute("data-main");if(d){a.removeAttribute("data-main");var e=c(d);if("function"==typeof e)return e;console.warn("attribute on "+b+" does not reference a global method")}else console.warn("no data-main attribute found on "+b+" script tag")}};!function(a,c){var e=d(document.currentScript,c);if(e)return e;for(var f=document.getElementsByTagName("script"),g=0;g<f.length;g++)if(b(f[g],a)){var h=d(f[g],c);if(h)return h}throw"cannot locate "+c+" script tag"}("help_el.js","help for language el")({version:"2.4.0",about:a('\ufeff<div role=presentation class="ephox-polish-help-article ephox-polish-help-about">\n <div class="ephox-polish-help-h1" role="heading" aria-level="1">\u03a0\u03bb\u03b7\u03c1\u03bf\u03c6\u03bf\u03c1\u03af\u03b5\u03c2</div>\n <p>\u03a4\u03bf Textbox.io \u03b5\u03af\u03bd\u03b1\u03b9 \u03ad\u03bd\u03b1 \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03bf WYSIWYG \u03b3\u03b9\u03b1 \u03c4\u03b7 \u03b4\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03af\u03b1 \u03c0\u03b5\u03c1\u03b9\u03b5\u03c7\u03bf\u03bc\u03ad\u03bd\u03bf\u03c5 \u03bc\u03b5 \u03c9\u03c1\u03b1\u03af\u03b1 \u03b5\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7 \u03c3\u03b5 online \u03b5\u03c6\u03b1\u03c1\u03bc\u03bf\u03b3\u03ad\u03c2. \u0395\u03af\u03c4\u03b5 \u03c0\u03c1\u03cc\u03ba\u03b5\u03b9\u03c4\u03b1\u03b9 \u03b3\u03b9\u03b1 \u03ba\u03bf\u03b9\u03bd\u03cc\u03c4\u03b7\u03c4\u03b5\u03c2 \u03ba\u03bf\u03b9\u03bd\u03c9\u03bd\u03b9\u03ba\u03ae\u03c2 \u03b4\u03b9\u03ba\u03c4\u03cd\u03c9\u03c3\u03b7\u03c2, \u03b9\u03c3\u03c4\u03bf\u03bb\u03cc\u03b3\u03b9\u03b1 (blog), \u03b7\u03bb\u03b5\u03ba\u03c4\u03c1\u03bf\u03bd\u03b9\u03ba\u03ae \u03b1\u03bb\u03bb\u03b7\u03bb\u03bf\u03b3\u03c1\u03b1\u03c6\u03af\u03b1 (email), \u03ae \u03bf\u03c4\u03b9\u03b4\u03ae\u03c0\u03bf\u03c4\u03b5 \u03c0\u03b1\u03c1\u03cc\u03bc\u03bf\u03b9\u03bf, \u03c4\u03bf Textbox.io \u03b5\u03c0\u03b9\u03c4\u03c1\u03ad\u03c0\u03b5\u03b9 \u03c3\u03c4\u03bf\u03c5\u03c2 \u03b1\u03bd\u03b8\u03c1\u03ce\u03c0\u03bf\u03c5\u03c2 \u03bd\u03b1 \u03b5\u03ba\u03c6\u03c1\u03ac\u03b6\u03bf\u03bd\u03b1\u03b9 \u03c3\u03c4\u03bf web.</p>\n <p>&nbsp;</p>\n <p>Textbox.io @@FULL_VERSION@@</p>\n <p>\u0394\u03cc\u03bc\u03b7\u03c3\u03b7 \u03c0\u03c1\u03bf\u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03bf\u03c2 \u03c0\u03b5\u03bb\u03ac\u03c4\u03b7 @@CLIENT_VERSION@@</p>\n <p class="ephox-polish-help-integration">\u039f\u03bb\u03bf\u03ba\u03bb\u03ae\u03c1\u03c9\u03c3\u03b7 \u03b3\u03b9\u03b1 @@INTEGRATION_TYPE@@, \u03ad\u03ba\u03b4\u03bf\u03c3\u03b7 @@INTEGRATION_VERSION@@</p>\n <p>&nbsp;</p>\n <p>\u03a0\u03bd\u03b5\u03c5\u03bc\u03b1\u03c4\u03b9\u03ba\u03ac \u03b4\u03b9\u03ba\u03b1\u03b9\u03ce\u03bc\u03b1\u03c4\u03b1 2017 Ephox Corporation. \u039c\u03b5 \u03b5\u03c0\u03b9\u03c6\u03cd\u03bb\u03b1\u03be\u03b7 \u03ba\u03ac\u03b8\u03b5 \u03bd\u03cc\u03bc\u03b9\u03bc\u03bf\u03c5 \u03b4\u03b9\u03ba\u03b1\u03b9\u03ce\u03bc\u03b1\u03c4\u03bf\u03c2.</p>\n <p><a href="javascript:void(0)" class="ephox-license-link">\u0386\u03b4\u03b5\u03b9\u03b5\u03c2 \u03c7\u03c1\u03ae\u03c3\u03b7\u03c2 \u03c4\u03c1\u03af\u03c4\u03c9\u03bd</a></p>\n</div>'), accessibility:a('\ufeff<div role=presentation class="ephox-polish-help-article">\n <div role="heading" aria-level="1" class="ephox-polish-help-h1">\u03a0\u03bb\u03bf\u03ae\u03b3\u03b7\u03c3\u03b7 \u03bc\u03ad\u03c3\u03c9 \u03c0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03af\u03bf\u03c5</div>\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u0395\u03bd\u03b5\u03c1\u03b3\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7 \u03c4\u03b7\u03c2 \u03c0\u03bb\u03bf\u03ae\u03b3\u03b7\u03c3\u03b7s \u03bc\u03ad\u03c3\u03c9 \u03c0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03af\u03bf\u03c5</div>\n <p>\u0393\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03bd\u03b5\u03c1\u03b3\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03c0\u03bb\u03bf\u03ae\u03b3\u03b7\u03c3\u03b7 \u03bc\u03ad\u03c3\u03c9 \u03c0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03af\u03bf\u03c5 \u03c3\u03c4\u03b7 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03c9\u03bd, \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 F10 \u03c3\u03c4\u03b1 Windows \u03ae ALT + F10 \u03c3\u03c4\u03bf Mac OSX. \u03a4\u03bf \u03c0\u03c1\u03ce\u03c4\u03bf \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf \u03c4\u03b7\u03c2 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae\u03c2 \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03c9\u03bd \u03b8\u03b1 \u03b5\u03c0\u03b9\u03c3\u03b7\u03bc\u03b1\u03bd\u03b8\u03b5\u03af \u03bc\u03b5 \u03ad\u03bd\u03b1 \u03bc\u03c0\u03bb\u03b5 \u03c0\u03b5\u03c1\u03af\u03b3\u03c1\u03b1\u03bc\u03bc\u03b1 \u03c0\u03bf\u03c5 \u03b4\u03b7\u03bb\u03ce\u03bd\u03b5\u03b9 \u03bc\u03b9\u03b1 \u03b5\u03c0\u03b9\u03bb\u03b5\u03b3\u03bc\u03ad\u03bd\u03b7 \u03ba\u03b1\u03c4\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7. </p>\n\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u039c\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7 \u03bc\u03b5\u03c4\u03b1\u03be\u03cd \u03bf\u03bc\u03ac\u03b4\u03c9\u03bd</div>\n <p>\u03a4\u03b1 \u03ba\u03bf\u03c5\u03bc\u03c0\u03b9\u03ac \u03c3\u03c4\u03b7 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03c9\u03bd \u03b5\u03af\u03bd\u03b1\u03b9 \u03b4\u03b9\u03b1\u03c7\u03c9\u03c1\u03b9\u03c3\u03bc\u03ad\u03bd\u03b1 \u03c3\u03b5 \u03bf\u03bc\u03ac\u03b4\u03b5\u03c2 \u03c0\u03b1\u03c1\u03cc\u03bc\u03bf\u03b9\u03c9\u03bd \u03b5\u03bd\u03b5\u03c1\u03b3\u03b5\u03b9\u03ce\u03bd. \u038c\u03c4\u03b1\u03bd \u03b7 \u03c0\u03bb\u03bf\u03ae\u03b3\u03b7\u03c3\u03b7 \u03bc\u03ad\u03c3\u03c9 \u03c0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03af\u03bf\u03c5 \u03b5\u03af\u03bd\u03b1\u03b9 \u03b5\u03bd\u03b5\u03c1\u03b3\u03ae, \u03c0\u03b1\u03c4\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf Tab \u03b8\u03b1 \u03bc\u03b5\u03c4\u03b1\u03ba\u03b9\u03bd\u03ae\u03c3\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03b5\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03c3\u03c4\u03b7\u03bd \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03b7 \u03bf\u03bc\u03ac\u03b4\u03b1 \u03b5\u03bd\u03ce \u03bc\u03b5 Shift + Tab \u03b8\u03b1 \u03b5\u03c0\u03b1\u03bd\u03b1\u03c6\u03ad\u03c1\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03b5\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03b7\u03b3\u03bf\u03cd\u03bc\u03b5\u03bd\u03b7 \u03bf\u03bc\u03ac\u03b4\u03b1. \u0391\u03bd \u03c0\u03b1\u03c4\u03ae\u03c3\u03b5\u03c4\u03b5 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf Tab \u03c3\u03c4\u03b7\u03bd \u03c4\u03b5\u03bb\u03b5\u03c5\u03c4\u03b1\u03af\u03b1 \u03bf\u03bc\u03ac\u03b4\u03b1 \u03b8\u03b1 \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c8\u03b5\u03c4\u03b5 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03ce\u03c4\u03b7 \u03bf\u03bc\u03ac\u03b4\u03b1 \u03ba\u03bf\u03c5\u03bc\u03c0\u03b9\u03ce\u03bd.</p>\n\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u039c\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7 \u03bc\u03b5\u03c4\u03b1\u03be\u03cd \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03c9\u03bd \u03ae \u03ba\u03bf\u03c5\u03bc\u03c0\u03b9\u03ce\u03bd</div>\n <p>\u0393\u03b9\u03b1 \u03bd\u03b1 \u03bc\u03b5\u03c4\u03b1\u03ba\u03b9\u03bd\u03b7\u03b8\u03b5\u03af\u03c4\u03b5 \u03b5\u03bc\u03c0\u03c1\u03cc\u03c2 \u03ba\u03b1\u03b9 \u03c0\u03af\u03c3\u03c9 \u03bc\u03b5\u03c4\u03b1\u03be\u03cd \u03c4\u03c9\u03bd \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03c9\u03bd, \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03c4\u03b5 \u03c4\u03b1 \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03b1 \u03b2\u03ad\u03bb\u03bf\u03c5\u03c2. \u03a4\u03b1 \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03b1 \u03b8\u03b1 \u03b1\u03bd\u03b1\u03ba\u03c5\u03ba\u03bb\u03ce\u03bd\u03bf\u03bd\u03c4\u03b1\u03b9 \u03bc\u03ad\u03c3\u03b1 \u03c3\u03c4\u03b9\u03c2 \u03bf\u03bc\u03ac\u03b4\u03b5\u03c2 \u03c4\u03bf\u03c5\u03c2, \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03bc\u03b5\u03c4\u03b1\u03b2\u03b5\u03af\u03c4\u03b5 \u03c3\u03c4\u03b7\u03bd \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03b7 \u03bf\u03bc\u03ac\u03b4\u03b1 \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf Tab \u03ba\u03b1\u03b9 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03c4\u03b5 \u03c4\u03b1 \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03b1 \u03b2\u03ad\u03bb\u03bf\u03c5\u03c2 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b4\u03b9\u03b1\u03c4\u03c1\u03ad\u03be\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03bf\u03bc\u03ac\u03b4\u03b1.</p>\n\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u0395\u03ba\u03c4\u03ad\u03bb\u03b5\u03c3\u03b7 \u03b5\u03bd\u03c4\u03bf\u03bb\u03ce\u03bd</div>\n <p>\u0393\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03ba\u03c4\u03b5\u03bb\u03ad\u03c3\u03b5\u03c4\u03b5 \u03bc\u03b9\u03b1 \u03b5\u03bd\u03c4\u03bf\u03bb\u03ae, \u03bc\u03b5\u03c4\u03b1\u03c6\u03ad\u03c1\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03b5\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03c3\u03c4\u03bf \u03b5\u03c0\u03b9\u03b8\u03c5\u03bc\u03b7\u03c4\u03cc \u03ba\u03bf\u03c5\u03bc\u03c0\u03af \u03ba\u03b1\u03b9 \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf \u03b4\u03b9\u03b1\u03c3\u03c4\u03ae\u03bc\u03b1\u03c4\u03bf\u03c2 \u03ae \u03c4\u03bf Enter.</p>\n\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u0386\u03bd\u03bf\u03b9\u03b3\u03bc\u03b1, \u03c0\u03bb\u03bf\u03ae\u03b3\u03b7\u03c3\u03b7 \u03ba\u03b1\u03b9 \u03ba\u03bb\u03b5\u03af\u03c3\u03b9\u03bc\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd</div>\n <p>\u038c\u03c4\u03b1\u03bd \u03ad\u03bd\u03b1 \u03ba\u03bf\u03c5\u03bc\u03c0\u03af \u03c4\u03b7\u03c2 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae\u03c2 \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03c9\u03bd \u03c0\u03b5\u03c1\u03b9\u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03b5\u03b9 \u03ad\u03bd\u03b1 \u03bc\u03b5\u03bd\u03bf\u03cd, \u03bc\u03c0\u03bf\u03c1\u03b5\u03af\u03c4\u03b5 \u03bd\u03b1 \u03b1\u03bd\u03bf\u03af\u03be\u03b5\u03c4\u03b5 \u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd \u03c0\u03b1\u03c4\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf \u03b4\u03b9\u03b1\u03c3\u03c4\u03ae\u03bc\u03b1\u03c4\u03bf\u03c2 \u03ae \u03c4\u03bf Enter. \u038c\u03c4\u03b1\u03bd \u03b1\u03bd\u03bf\u03af\u03be\u03b5\u03b9 \u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd \u03b8\u03b1 \u03b5\u03af\u03bd\u03b1\u03b9 \u03b5\u03c0\u03b9\u03bb\u03b5\u03b3\u03bc\u03ad\u03bd\u03bf \u03c4\u03bf \u03c0\u03c1\u03ce\u03c4\u03bf \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf, \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03c4\u03b5 \u03c4\u03b1 \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03b1 \u03b2\u03ad\u03bb\u03bf\u03c5\u03c2 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03c0\u03bb\u03bf\u03b7\u03b3\u03b7\u03b8\u03b5\u03af\u03c4\u03b5 \u03c3\u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd. \u0393\u03b9\u03b1 \u03bd\u03b1 \u03bc\u03b5\u03c4\u03b1\u03ba\u03b9\u03bd\u03b7\u03b8\u03b5\u03af\u03c4\u03b5 \u03c0\u03c1\u03bf\u03c2 \u03c4\u03b1 \u03c0\u03ac\u03bd\u03c9 \u03ae \u03c0\u03c1\u03bf\u03c2 \u03c4\u03b1 \u03ba\u03ac\u03c4\u03c9 \u03c3\u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd, \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c4\u03bf \u03c0\u03ac\u03bd\u03c9 \u03ae \u03ba\u03ac\u03c4\u03c9 \u03b2\u03ad\u03bb\u03bf\u03c2 \u03b1\u03bd\u03c4\u03af\u03c3\u03c4\u03bf\u03b9\u03c7\u03b1 - \u03b1\u03c5\u03c4\u03cc \u03b9\u03c3\u03c7\u03cd\u03b5\u03b9 \u03ba\u03b1\u03b9 \u03b3\u03b9\u03b1 \u03c4\u03b1 \u03c5\u03c0\u03bf\u03bc\u03b5\u03bd\u03bf\u03cd.</p>\n\n <p>\u03a4\u03b1 \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03b1 \u03bc\u03b5\u03bd\u03bf\u03cd \u03c0\u03bf\u03c5 \u03ad\u03c7\u03bf\u03c5\u03bd \u03c5\u03c0\u03bf\u03bc\u03b5\u03bd\u03bf\u03cd \u03b4\u03b7\u03bb\u03ce\u03bd\u03bf\u03bd\u03c4\u03b1\u03b9 \u03b1\u03c0\u03cc \u03ad\u03bd\u03b1 \u03c3\u03cd\u03bc\u03b2\u03bf\u03bb\u03bf Chevron. \u03a7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf \u03b2\u03ad\u03bb\u03bf\u03c5\u03c2 \u03c0\u03bf\u03c5 \u03b1\u03bd\u03c4\u03b9\u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af \u03c3\u03c4\u03b7\u03bd \u03ba\u03b1\u03c4\u03b5\u03cd\u03b8\u03c5\u03bd\u03c3\u03b7 \u03c4\u03bf\u03c5 \u03c3\u03c5\u03bc\u03b2\u03cc\u03bb\u03bf\u03c5 Chevron \u03b8\u03b1 \u03b1\u03bd\u03b1\u03c0\u03c4\u03cd\u03be\u03b5\u03c4\u03b5 \u03c4\u03bf \u03c5\u03c0\u03bf\u03bc\u03b5\u03bd\u03bf\u03cd, \u03b5\u03bd\u03ce \u03bc\u03b5 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf \u03b2\u03ad\u03bb\u03bf\u03c5\u03c2 \u03c0\u03c1\u03bf\u03c2 \u03c4\u03b7\u03bd \u03b1\u03bd\u03c4\u03af\u03b8\u03b5\u03c4\u03b7 \u03ba\u03b1\u03c4\u03b5\u03cd\u03b8\u03c5\u03bd\u03c3\u03b7 \u03b8\u03b1 \u03ba\u03bb\u03b5\u03af\u03c3\u03b5\u03c4\u03b5 \u03c4\u03bf \u03c5\u03c0\u03bf\u03bc\u03b5\u03bd\u03bf\u03cd.</p>\n\n <p>\u0393\u03b9\u03b1 \u03bd\u03b1 \u03ba\u03bb\u03b5\u03af\u03c3\u03b5\u03c4\u03b5 \u03bf\u03c0\u03bf\u03b9\u03bf\u03b4\u03ae\u03c0\u03bf\u03c4\u03b5 \u03b5\u03bd\u03b5\u03c1\u03b3\u03cc \u03bc\u03b5\u03bd\u03bf\u03cd, \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf Esc. \u038c\u03c4\u03b1\u03bd \u03ba\u03bb\u03b5\u03af\u03bd\u03b5\u03b9 \u03ad\u03bd\u03b1 \u03bc\u03b5\u03bd\u03bf\u03cd, \u03b7 \u03b5\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03b5\u03c0\u03b1\u03bd\u03ad\u03c1\u03c7\u03b5\u03c4\u03b1\u03b9 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03b7\u03b3\u03bf\u03cd\u03bc\u03b5\u03bd\u03b7 \u03ba\u03b1\u03c4\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7.</p>\n\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u0395\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03af\u03b1 \u03ae \u03ba\u03b1\u03c4\u03ac\u03c1\u03b3\u03b7\u03c3\u03b7 \u03c5\u03c0\u03b5\u03c1\u03c3\u03c5\u03bd\u03b4\u03ad\u03c3\u03b5\u03c9\u03bd</div>\n\n <p>\u0393\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03c0\u03b5\u03be\u03c1\u03b3\u03b1\u03c3\u03c4\u03b5\u03b9\u03c4\u03b5 \u03ae \u03bd\u03b1 \u03ba\u03b1\u03c4\u03b1\u03c1\u03b3\u03ae\u03c3\u03b5\u03c4\u03b5 \u03bc\u03b9\u03b1 \u03c3\u03cd\u03bd\u03b4\u03b5\u03c3\u03b7, \u03bc\u03b5\u03c4\u03b1\u03b2\u03b5\u03af\u03c4\u03b5 \u03c3\u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd \u0395\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae \u03ba\u03b1\u03b9 \u03b5\u03c0\u03b9\u03bb\u03ad\u03be\u03c4\u03b5 \u0395\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae \u03c3\u03cd\u03bd\u03b4\u03b5\u03c3\u03b7\u03c2. \u039f \u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03ae\u03c2 \u03b5\u03bc\u03c6\u03b1\u03bd\u03af\u03b6\u03b5\u03b9 \u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5 \u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03af\u03b1\u03c2 \u03c3\u03cd\u03bd\u03b4\u03b5\u03c3\u03b7\u03c2. </p>\n\n <p>\u0395\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03b5\u03af\u03c4\u03b5 \u03c4\u03b7 \u03c3\u03cd\u03bd\u03b4\u03b5\u03c3\u03b7 \u03b5\u03b9\u03c3\u03ac\u03b3\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03b7 \u03bd\u03ad\u03b1 \u03b4\u03b9\u03b5\u03cd\u03b8\u03c5\u03bd\u03c3\u03b7 URL \u03c3\u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b5\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae\u03c2 \u03b5\u03bd\u03b7\u03bc\u03b5\u03c1\u03c9\u03bc\u03ad\u03bd\u03b7\u03c2 \u03c3\u03cd\u03bd\u03b4\u03b5\u03c3\u03b7\u03c2 \u03ba\u03b1\u03b9 \u03c0\u03b1\u03c4\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf Enter. \u039a\u03b1\u03c4\u03b1\u03c1\u03b3\u03ae\u03c3\u03c4\u03b5 \u03c4\u03b7 \u03c3\u03cd\u03bd\u03b4\u03b5\u03c3\u03b7 \u03b1\u03c0\u03cc \u03c4\u03bf \u03ad\u03b3\u03b3\u03c1\u03b1\u03c6\u03bf \u03b5\u03c0\u03b9\u03bb\u03ad\u03b3\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf \u03ba\u03bf\u03c5\u03bc\u03c0\u03af \u039a\u03b1\u03c4\u03ac\u03c1\u03b3\u03b7\u03c3\u03b7. \u0393\u03b9\u03b1 \u03bd\u03b1 \u03b2\u03b3\u03b5\u03af\u03c4\u03b5 \u03b1\u03c0\u03cc \u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5 \u03c7\u03c9\u03c1\u03af\u03c2 \u03bd\u03b1 \u03ba\u03ac\u03bd\u03b5\u03c4\u03b5 \u03b1\u03bb\u03bb\u03b1\u03b3\u03ad\u03c2 \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 Esc.</p>\n\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u0391\u03bb\u03bb\u03b1\u03b3\u03ae \u03bc\u03b5\u03b3\u03b5\u03b8\u03ce\u03bd \u03b3\u03c1\u03b1\u03bc\u03bc\u03b1\u03c4\u03bf\u03c3\u03b5\u03b9\u03c1\u03ce\u03bd \u03ba\u03b1\u03b9 \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03bf\u03c2 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1</div>\n\n <p>\u0391\u03bb\u03bb\u03ac\u03be\u03c4\u03b5 \u03c4\u03b1 \u03bc\u03b5\u03b3\u03ad\u03b8\u03b7 \u03c4\u03c9\u03bd \u03b3\u03c1\u03b1\u03bc\u03bc\u03b1\u03c4\u03bf\u03c3\u03b5\u03b9\u03c1\u03ce\u03bd \u03bc\u03b5\u03c4\u03b1\u03b2\u03b1\u03af\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c3\u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd \u0393\u03c1\u03b1\u03bc\u03bc\u03b1\u03c4\u03bf\u03c3\u03b5\u03b9\u03c1\u03ac \u03ba\u03b1\u03b9 \u03b5\u03c0\u03b9\u03bb\u03ad\u03b3\u03bf\u03bd\u03c4\u03b1\u03c2 \u039c\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03b3\u03c1\u03b1\u03bc\u03bc\u03b1\u03c4\u03bf\u03c3\u03b5\u03b9\u03c1\u03ac\u03c2. \u039f \u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03ae\u03c2 \u03b5\u03bc\u03c6\u03b1\u03bd\u03af\u03b6\u03b5\u03b9 \u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5 \u03b3\u03b9\u03b1 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c3\u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd \u03ba\u03b1\u03b9 \u03c1\u03c5\u03b8\u03bc\u03af\u03b6\u03b5\u03b9 \u03c4\u03b7\u03bd \u03b5\u03c3\u03c4\u03af\u03b1\u03c3\u03b7 \u03c3\u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5.</p>\n\n <p>\u0391\u03bb\u03bb\u03ac\u03be\u03c4\u03b5 \u03c4\u03b1 \u03bc\u03b5\u03b3\u03ad\u03b8\u03b7 \u03c4\u03c9\u03bd \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03bc\u03bc\u03ac\u03c4\u03c9\u03bd \u03bc\u03b5\u03c4\u03b1\u03b2\u03b1\u03af\u03bd\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c3\u03c4\u03bf \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03bf\u03c2 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1 \u03c3\u03c4\u03b7 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03c9\u03bd \u03ba\u03b1\u03b9 \u03b5\u03c0\u03b9\u03bb\u03ad\u03b3\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03bf\u03c2 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1 . \u039f \u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03ae\u03c2 \u03b5\u03bc\u03c6\u03b1\u03bd\u03af\u03b6\u03b5\u03b9 \u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5 \u03b3\u03b9\u03b1 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c3\u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd \u03ba\u03b1\u03b9 \u03c1\u03c5\u03b8\u03bc\u03af\u03b6\u03b5\u03b9 \u03c4\u03b7\u03bd \u03b5\u03c3\u03c4\u03af\u03b1\u03c3\u03b7 \u03c3\u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5. \u03a3\u03b7\u03bc\u03b5\u03af\u03c9\u03c3\u03b7: \u03a4\u03bf \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03bc\u03bc\u03b1\u03c4\u03bf\u03c2 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1 \u03c3\u03c4\u03b7 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03c9\u03bd \u03b5\u03af\u03bd\u03b1\u03b9 \u03b4\u03b9\u03b1\u03b8\u03ad\u03c3\u03b9\u03bc\u03bf \u03bc\u03cc\u03bd\u03bf\u03bd \u03cc\u03c4\u03b1\u03bd \u03bf \u03b4\u03b5\u03af\u03ba\u03c4\u03b7\u03c2 \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03ad\u03c3\u03b1 \u03c3\u03c4\u03bf\u03bd \u03c0\u03af\u03bd\u03b1\u03ba\u03b1.</p>\n\n <p>\u039c\u03ad\u03c3\u03b1 \u03c3\u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5 \u03b3\u03b9\u03b1 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2, \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf Tab \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03bc\u03b5\u03c4\u03b1\u03ba\u03b9\u03bd\u03ae\u03c3\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03b5\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03c3\u03c4\u03bf \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03bf \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf \u03b5\u03bb\u03ad\u03b3\u03c7\u03bf\u03c5. \u03a0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 Shift+Tab \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03bc\u03b5\u03c4\u03b1\u03ba\u03b9\u03bd\u03ae\u03c3\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03b5\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03c3\u03c4\u03bf \u03c0\u03c1\u03bf\u03b7\u03b3\u03bf\u03cd\u03bc\u03b5\u03bd\u03bf \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf \u03b5\u03bb\u03ad\u03b3\u03c7\u03bf\u03c5.</p>\n\n <p>\u03a4\u03c1\u03bf\u03c0\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03c4\u03b5 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03b5\u03b9\u03c3\u03ac\u03b3\u03bf\u03bd\u03c4\u03b1\u03c2 \u03c4\u03b7 \u03bd\u03ad\u03b1 \u03c4\u03b9\u03bc\u03ae \u03c3\u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b5\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae\u03c2 \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2. \u0393\u03b9\u03b1 \u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3\u03bc\u03b1, 14px \u03ae 1em. \u0393\u03b9\u03b1 \u03c5\u03c0\u03bf\u03b2\u03bf\u03bb\u03ae \u03b1\u03bb\u03bb\u03b1\u03b3\u03ce\u03bd, \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c4\u03bf Enter. \u03a3\u03b7\u03bc\u03b5\u03b9\u03ce\u03c3\u03c4\u03b5 \u03cc\u03c4\u03b9 \u03c4\u03bf \u03c0\u03ac\u03c4\u03b7\u03bc\u03b1 \u03c4\u03bf\u03c5 \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf\u03c5 Enter \u03ba\u03bb\u03b5\u03af\u03bd\u03b5\u03b9 \u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5 \u03ba\u03b1\u03b9 \u03b7 \u03b5\u03c3\u03c4\u03af\u03b1\u03c3\u03b7 \u03b5\u03c0\u03b9\u03c3\u03c4\u03c1\u03ad\u03c6\u03b5\u03b9 \u03c3\u03c4\u03bf \u03ad\u03b3\u03b3\u03c1\u03b1\u03c6\u03bf.</p>\n\n <p>\u0391\u03bb\u03bb\u03ac\u03be\u03c4\u03b5 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c7\u03c9\u03c1\u03af\u03c2 \u03bd\u03b1 \u03b2\u03b3\u03b5\u03af\u03c4\u03b5 \u03b1\u03c0\u03cc \u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5, \u03b5\u03bd\u03b5\u03c1\u03b3\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03b1 \u03ba\u03bf\u03c5\u03bc\u03c0\u03b9\u03ac \u03b1\u03cd\u03be\u03b7\u03c3\u03b7\u03c2 \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2 \u03ae \u03bc\u03b5\u03af\u03c9\u03c3\u03b7\u03c2 \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2. \u0397 \u03b1\u03bb\u03bb\u03b1\u03b3\u03ae \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2 \u03bc\u03b5 \u03c4\u03b1 \u03ba\u03bf\u03c5\u03bc\u03c0\u03b9\u03ac \u03b1\u03cd\u03be\u03b7\u03c3\u03b7\u03c2 \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2 \u03ae \u03bc\u03b5\u03af\u03c9\u03c3\u03b7\u03c2 \u03bc\u03b5\u03b3\u03ad\u03b8\u03bf\u03c5\u03c2 \u03b8\u03b1 \u03b1\u03bb\u03bb\u03ac\u03be\u03b5\u03b9 \u03b1\u03bc\u03ad\u03c3\u03c9\u03c2 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c4\u03bf\u03c5 \u03b5\u03c0\u03b9\u03bb\u03b5\u03b3\u03bc\u03ad\u03bd\u03bf\u03c5 \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf\u03c5 \u03b4\u03b9\u03b1\u03c4\u03b7\u03c1\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03b7\u03bd \u03c4\u03c1\u03ad\u03c7\u03bf\u03c5\u03c3\u03b1 \u03c4\u03b9\u03bc\u03ae \u03bc\u03bf\u03bd\u03ac\u03b4\u03b1\u03c2. \u0392\u03b3\u03b5\u03af\u03c4\u03b5 \u03b1\u03c0\u03cc \u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5 \u03b3\u03b9\u03b1 \u03c4\u03bf \u03bc\u03ad\u03b3\u03b5\u03b8\u03bf\u03c2 \u03c0\u03b1\u03c4\u03ce\u03bd\u03c4\u03b1\u03c2 Esc.</p>\n\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u03a0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1\u03c2</div>\n\n <p>\u0393\u03b9\u03b1 \u03bd\u03b1 \u03b1\u03c0\u03bf\u03ba\u03c4\u03ae\u03c3\u03b5\u03c4\u03b5 \u03c0\u03c1\u03cc\u03c3\u03b2\u03b1\u03c3\u03b7 \u03c3\u03c4\u03b7 \u03bb\u03b5\u03b9\u03c4\u03bf\u03c5\u03c1\u03b3\u03af\u03b1 \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae\u03c2, \u03b5\u03c0\u03b9\u03bb\u03ad\u03be\u03c4\u03b5 \u03bc\u03b9\u03b1 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03bc\u03c6\u03b1\u03bd\u03b9\u03c3\u03c4\u03bf\u03cd\u03bd \u03bf\u03b9 \u03bb\u03b5\u03b9\u03c4\u03bf\u03c5\u03c1\u03b3\u03af\u03b5\u03c2 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1\u03c2 \u03c3\u03c4\u03b7 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03c9\u03bd. \u0391\u03c5\u03c4\u03ad\u03c2 \u03bf\u03b9 \u03bb\u03b5\u03b9\u03c4\u03bf\u03c5\u03c1\u03b3\u03af\u03b5\u03c2 \u03b5\u03af\u03bd\u03b1\u03b9 \u03b5\u03c0\u03af\u03c3\u03b7\u03c2 \u03b4\u03b9\u03b1\u03b8\u03ad\u03c3\u03b9\u03bc\u03b5\u03c2 \u03c3\u03c4\u03bf \u03bc\u03b5\u03bd\u03bf\u03cd \u03c0\u03b5\u03c1\u03b9\u03b2\u03ac\u03bb\u03bb\u03bf\u03bd\u03c4\u03bf\u03c2. \u039c\u03cc\u03bb\u03b9\u03c2 \u03b5\u03bd\u03b5\u03c1\u03b3\u03bf\u03c0\u03bf\u03b9\u03b7\u03b8\u03b5\u03af \u03b7 \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae, \u03bc\u03b9\u03b1 \u03bc\u03ac\u03c3\u03ba\u03b1 \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae\u03c2 \u03b8\u03b1 \u03c4\u03bf\u03c0\u03bf\u03b8\u03b5\u03c4\u03b7\u03b8\u03b5\u03af \u03c0\u03ac\u03bd\u03c9 \u03c3\u03c4\u03b7\u03bd \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1 \u03ba\u03b1\u03b9 \u03b7 \u03b5\u03c0\u03ac\u03bd\u03c9 \u03b1\u03c1\u03b9\u03c3\u03c4\u03b5\u03c1\u03ae \u03b3\u03c9\u03bd\u03af\u03b1 \u03c4\u03b7\u03c2 \u03b8\u03b1 \u03b5\u03af\u03bd\u03b1\u03b9 \u03b5\u03c0\u03b9\u03bb\u03b5\u03b3\u03bc\u03ad\u03bd\u03b7.</p>\n\n <p>\u03a0\u03bb\u03bf\u03b7\u03b3\u03b7\u03b8\u03b5\u03af\u03c4\u03b5 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ce\u03bd\u03c4\u03b1\u03c2 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf Tab. \u039a\u03b1\u03b8\u03b5\u03bc\u03af\u03b1 \u03b1\u03c0\u03cc \u03c4\u03b9\u03c2 4 \u03b3\u03c9\u03bd\u03af\u03b5\u03c2 \u03bc\u03c0\u03bf\u03c1\u03b5\u03af \u03bd\u03b1 \u03b5\u03c0\u03b9\u03bb\u03b5\u03b3\u03b5\u03b9, \u03ba\u03b1\u03b8\u03ce\u03c2 \u03ba\u03b1\u03b9 \u03bf\u03bb\u03cc\u03ba\u03bb\u03b7\u03c1\u03bf \u03c4\u03bf \u03c0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03c4\u03b7\u03c2 \u03bc\u03ac\u03c3\u03ba\u03b1\u03c2 \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae\u03c2. \u039a\u03ac\u03b8\u03b5 \u03b3\u03c9\u03bd\u03af\u03b1 \u03bc\u03c0\u03bf\u03c1\u03b5\u03af \u03bd\u03b1 \u03c4\u03bf\u03c0\u03bf\u03b8\u03b5\u03c4\u03b7\u03b8\u03b5\u03af \u03c7\u03c9\u03c1\u03b9\u03c3\u03c4\u03ac \u03ae \u03cc\u03bb\u03b5\u03c2 \u03bf\u03b9 \u03b3\u03c9\u03bd\u03af\u03b5\u03c2 \u03bc\u03c0\u03bf\u03c1\u03bf\u03cd\u03bd \u03bd\u03b1 \u03bc\u03b5\u03c4\u03b1\u03ba\u03b9\u03bd\u03b7\u03b8\u03bf\u03cd\u03bd \u03c4\u03b1\u03c5\u03c4\u03cc\u03c7\u03c1\u03bf\u03bd\u03b1 \u03bc\u03ad\u03c3\u03c9 \u03c4\u03b7\u03c2 \u03bc\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7\u03c2 \u03bf\u03bb\u03cc\u03ba\u03bb\u03b7\u03c1\u03bf\u03c5 \u03c4\u03bf\u03c5 \u03c0\u03bb\u03b1\u03b9\u03c3\u03af\u03bf\u03c5 \u03c4\u03b7\u03c2 \u03bc\u03ac\u03c3\u03ba\u03b1\u03c2 \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae\u03c2.</p>\n\n <p>\u0397 \u03bc\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7 \u03c4\u03b7\u03c2 \u03b5\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae\u03c2 \u03c3\u03c4\u03b7\u03bd \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1 \u03c0\u03c1\u03b1\u03b3\u03bc\u03b1\u03c4\u03bf\u03c0\u03bf\u03b9\u03b5\u03af\u03c4\u03b1\u03b9 \u03bc\u03b5 \u03c4\u03b1 \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03b1 \u03b2\u03ad\u03bb\u03bf\u03c5\u03c2. \u039a\u03ac\u03b8\u03b5 \u03c0\u03ac\u03c4\u03b7\u03bc\u03b1 \u03b5\u03bd\u03cc\u03c2 \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf\u03c5 \u03b2\u03ad\u03bb\u03bf\u03c5\u03c2 \u03c0\u03c1\u03bf\u03ba\u03b1\u03bb\u03b5\u03af \u03bc\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7 \u03ba\u03b1\u03c4\u03ac 10 pixel, \u03b3\u03b9\u03b1 \u03bc\u03b9\u03ba\u03c1\u03cc\u03c4\u03b5\u03c1\u03b5\u03c2 \u03bc\u03b5\u03c4\u03b1\u03ba\u03b9\u03bd\u03ae\u03c3\u03b5\u03b9\u03c2 \u03ba\u03c1\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c0\u03b1\u03c4\u03b7\u03bc\u03ad\u03bd\u03bf \u03c4\u03bf Shift \u03ba\u03b1\u03b8\u03ce\u03c2 \u03c0\u03b1\u03c4\u03ac\u03c4\u03b5 \u03ad\u03bd\u03b1 \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf \u03b2\u03ad\u03bb\u03bf\u03c5\u03c2 \u03b3\u03b9\u03b1 \u03bc\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7 \u03ba\u03b1\u03c4\u03ac \u03ad\u03bd\u03b1 pixel.</p>\n\n <p>\u0393\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03c6\u03b1\u03c1\u03bc\u03cc\u03c3\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae \u03c3\u03c4\u03b7\u03bd \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1, \u03c0\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 Enter.</p>\n\n <p>\u0393\u03b9\u03b1 \u03bd\u03b1 \u03b1\u03ba\u03c5\u03c1\u03ce\u03c3\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae \u03c7\u03c9\u03c1\u03af\u03c2 \u03b5\u03c0\u03af\u03b4\u03c1\u03b1\u03c3\u03b7 \u03c3\u03c4\u03b7\u03bd \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1, \u03c0\u03b1\u03c4\u03b7\u03c3\u03c4\u03b5 \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf ESC.</p>\n\n <table aria-readonly="true" cellpadding="0" cellspacing="0" class="ephox-polish-tabular ephox-polish-help-table ephox-polish-help-table-shortcuts">\n <caption>\u03a0\u03bb\u03bf\u03ae\u03b3\u03b7\u03c3\u03b7 \u03bc\u03ad\u03c3\u03c9 \u03c0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03af\u03bf\u03c5</caption>\n <thead>\n <tr>\n <th scope="col">\u0395\u03bd\u03ad\u03c1\u03b3\u03b5\u03b9\u03b1</th>\n <th scope="col">Windows</th>\n <th scope="col">Mac OS</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\u0395\u03bd\u03b5\u03c1\u03b3\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae\u03c2 \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03c9\u03bd</td>\n <td>F10</td>\n <td>ALT + F10</td>\n </tr>\n <tr>\n <td>\u039a\u03bf\u03c5\u03bc\u03c0\u03af \u03b5\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae\u03c2 \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03b7\u03c2/\u03c0\u03c1\u03bf\u03b7\u03b3\u03bf\u03cd\u03bc\u03b5\u03bd\u03b7\u03c2 \u03bf\u03bc\u03ac\u03b4\u03b1\u03c2</td>\n <td>\u2190 \u03ae \u2192</td>\n <td>\u2190 \u03ae \u2192</td>\n </tr>\n <tr>\n <td>\u039c\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7 \u03c3\u03c4\u03b7\u03bd \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03b7 \u03bf\u03bc\u03ac\u03b4\u03b1</td>\n <td>TAB</td>\n <td>TAB</td>\n </tr>\n <tr>\n <td>\u039c\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7 \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03b7\u03b3\u03bf\u03cd\u03bc\u03b5\u03bd\u03b7 \u03bf\u03bc\u03ac\u03b4\u03b1</td>\n <td>SHIFT + TAB</td>\n <td>SHIFT + TAB</td>\n </tr>\n <tr>\n <td>\u0395\u03ba\u03c4\u03ad\u03bb\u03b5\u03c3\u03b7 \u03b5\u03bd\u03c4\u03bf\u03bb\u03ae\u03c2</td>\n <td>\u0394\u0399\u0391\u03a3\u03a4\u0397\u039c\u0391 \u03ae ENTER</td>\n <td>\u0394\u0399\u0391\u03a3\u03a4\u0397\u039c\u0391 \u03ae ENTER</td>\n </tr>\n <tr>\n <td>\u0386\u03bd\u03bf\u03b9\u03b3\u03bc\u03b1 \u03ba\u03cd\u03c1\u03b9\u03bf\u03c5 \u03bc\u03b5\u03bd\u03bf\u03cd</td>\n <td>\u0394\u0399\u0391\u03a3\u03a4\u0397\u039c\u0391 \u03ae ENTER</td>\n <td>\u0394\u0399\u0391\u03a3\u03a4\u0397\u039c\u0391 \u03ae ENTER</td>\n </tr>\n <tr>\n <td>\u0386\u03bd\u03bf\u03b9\u03b3\u03bc\u03b1/\u0391\u03bd\u03ac\u03c0\u03c4\u03c5\u03be\u03b7 \u03c5\u03c0\u03bf\u03bc\u03b5\u03bd\u03bf\u03cd</td>\n <td>\u0394\u0399\u0391\u03a3\u03a4\u0397\u039c\u0391 \u03ae ENTER \u03ae \u2192</td>\n <td>\u0394\u0399\u0391\u03a3\u03a4\u0397\u039c\u0391 \u03ae ENTER \u03ae \u2192</td>\n </tr>\n <tr>\n <td>\u0395\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03bf\u03c5/\u03c0\u03c1\u03bf\u03b7\u03b3\u03bf\u03cd\u03bc\u03b5\u03bd\u03bf\u03c5 \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03bf\u03c5 \u03bc\u03b5\u03bd\u03bf\u03cd</td>\n <td>\u2193 \u03ae \u2191</td>\n <td>\u2193 \u03ae \u2191</td>\n </tr>\n <tr>\n <td>\u039c\u03b5\u03bd\u03bf\u03cd \u03ba\u03bb\u03b5\u03b9\u03c3\u03af\u03bc\u03b1\u03c4\u03bf\u03c2</td>\n <td>ESC</td>\n <td>ESC</td>\n </tr>\n <tr>\n <td>\u039a\u03bb\u03b5\u03af\u03c3\u03b9\u03bc\u03bf/\u03a3\u03cd\u03bc\u03c0\u03c4\u03c5\u03be\u03b7 \u03c5\u03c0\u03bf\u03bc\u03b5\u03bd\u03bf\u03cd</td>\n <td>ESC \u03ae \u2190</td>\n <td>ESC \u03ae \u2190</td>\n </tr>\n <tr>\n <td>\u0395\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03bc\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7\u03c2 \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae\u03c2 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1\u03c2</td>\n <td>\u2190 \u03ae \u2192 \u03ae \u2193 \u03ae \u2191</td>\n <td>\u2190 \u03ae \u2192 \u03ae \u2193 \u03ae \u2191</td>\n </tr>\n <tr>\n <td>\u0395\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03bc\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7\u03c2 \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae\u03c2 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1\u03c2 \u03bc\u03b5 \u03b1\u03ba\u03c1\u03af\u03b2\u03b5\u03b9\u03b1</td>\n <td>\u039a\u03c1\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c0\u03b1\u03c4\u03b7\u03bc\u03ad\u03bd\u03bf \u03c4\u03bf SHIFT \u03ba\u03b1\u03c4\u03ac \u03c4\u03b7 \u03bc\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7</td>\n <td>\u039a\u03c1\u03b1\u03c4\u03ae\u03c3\u03c4\u03b5 \u03c0\u03b1\u03c4\u03b7\u03bc\u03ad\u03bd\u03bf \u03c4\u03bf SHIFT \u03ba\u03b1\u03c4\u03ac \u03c4\u03b7 \u03bc\u03b5\u03c4\u03b1\u03ba\u03af\u03bd\u03b7\u03c3\u03b7</td>\n </tr>\n <tr>\n <td>\u0395\u03c6\u03b1\u03c1\u03bc\u03bf\u03b3\u03ae \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae\u03c2</td>\n <td>ENTER</td>\n <td>ENTER</td>\n </tr>\n <tr>\n <td>\u0391\u03ba\u03cd\u03c1\u03c9\u03c3\u03b7 \u03c0\u03b5\u03c1\u03b9\u03ba\u03bf\u03c0\u03ae\u03c2</td>\n <td>ESC</td>\n <td>ESC</td>\n </tr>\n </tbody>\n </table>\n</div>\n'), a11ycheck:a('\ufeff<div role=presentation class="ephox-polish-help-article">\n <div role="heading" aria-level="1" class="ephox-polish-help-h1">\u0388\u03bb\u03b5\u03b3\u03c7\u03bf\u03c2 \u03c0\u03c1\u03bf\u03c3\u03b2\u03b1\u03c3\u03b9\u03bc\u03cc\u03c4\u03b7\u03c4\u03b1\u03c2</div>\n <p>\u03a4\u03bf \u03b5\u03c1\u03b3\u03b1\u03bb\u03b5\u03af\u03bf \u0388\u03bb\u03b5\u03b3\u03c7\u03bf\u03c2 \u03c0\u03c1\u03bf\u03c3\u03b2\u03b1\u03c3\u03b9\u03bc\u03cc\u03c4\u03b7\u03c4\u03b1\u03c2 (\u03b1\u03bd \u03b5\u03af\u03bd\u03b1\u03b9 \u03b5\u03bd\u03b5\u03c1\u03b3\u03bf\u03c0\u03bf\u03b9\u03b7\u03bc\u03ad\u03bd\u03bf) \u03bc\u03c0\u03bf\u03c1\u03b5\u03af \u03bd\u03b1 \u03b1\u03bd\u03b1\u03b3\u03bd\u03c9\u03c1\u03af\u03c3\u03b5\u03b9 \u03c4\u03b1 \u03c0\u03b1\u03c1\u03b1\u03ba\u03ac\u03c4\u03c9 \u03b8\u03ad\u03bc\u03b1\u03c4\u03b1 \u03c0\u03c1\u03bf\u03c3\u03b2\u03b1\u03c3\u03b9\u03bc\u03cc\u03c4\u03b7\u03c4\u03b1\u03c2 \u03c3\u03b5 \u03ad\u03b3\u03b3\u03c1\u03b1\u03c6\u03b1 HTML.</p>\n <table aria-readonly="true" cellpadding="0" cellspacing="0" class="ephox-polish-tabular ephox-polish-a11ycheck-table">\n <caption>\u039f\u03c1\u03b9\u03c3\u03bc\u03bf\u03af \u03b8\u03b5\u03bc\u03ac\u03c4\u03c9\u03bd</caption>\n <thead>\n <tr>\n <th scope="col">\u0398\u03ad\u03bc\u03b1</th>\n <th scope="col">WCAG</th>\n <th scope="col">\u03a0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\u039f\u03b9 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b5\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bd \u03bc\u03b9\u03b1 \u03b5\u03bd\u03b1\u03bb\u03bb\u03b1\u03ba\u03c4\u03b9\u03ba\u03ae \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03ae \u03ba\u03b5\u03b9\u03bc\u03ad\u03bd\u03bf\u03c5</td>\n <td>1.1.1</td>\n <td>\u039f\u03b9 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b5\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bd \u03ba\u03b1\u03b8\u03bf\u03c1\u03b9\u03c3\u03bc\u03ad\u03bd\u03b7 \u03bc\u03b9\u03b1 \u03b5\u03bd\u03b1\u03bb\u03bb\u03b1\u03ba\u03c4\u03b9\u03ba\u03ae \u03c4\u03b9\u03bc\u03ae \u03ba\u03b5\u03b9\u03bc\u03ad\u03bd\u03bf\u03c5, \u03b7 \u03bf\u03c0\u03bf\u03af\u03b1 \u03b8\u03b1 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03c6\u03b5\u03b9 \u03c4\u03bf \u03b8\u03ad\u03bc\u03b1 \u03c4\u03b7\u03c2 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1\u03c2 \u03c3\u03c4\u03bf\u03c5\u03c2 \u03c7\u03c1\u03ae\u03c3\u03c4\u03b5\u03c2 \u03bc\u03b5 \u03c0\u03c1\u03bf\u03b2\u03bb\u03ae\u03bc\u03b1\u03c4\u03b1 \u03cc\u03c1\u03b1\u03c3\u03b7\u03c2. </td>\n </tr>\n <tr>\n <td>\u03a4\u03bf \u03b5\u03bd\u03b1\u03bb\u03bb\u03b1\u03ba\u03c4\u03b9\u03ba\u03cc \u03ba\u03b5\u03af\u03bc\u03b5\u03bd\u03bf \u03b4\u03b5\u03bd \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b5\u03af\u03bd\u03b1\u03b9 \u03af\u03b4\u03b9\u03bf \u03bc\u03b5 \u03c4\u03bf \u03cc\u03bd\u03bf\u03bc\u03b1 \u03b1\u03c1\u03c7\u03b5\u03af\u03bf\u03c5 \u03c4\u03b7\u03c2 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1\u03c2</td>\n <td>1.1.1</td>\n <td>\u0391\u03c0\u03bf\u03c6\u03b5\u03cd\u03b3\u03b5\u03c4\u03b5 \u03c4\u03b7 \u03c7\u03c1\u03ae\u03c3\u03b7 \u03c4\u03bf\u03c5 \u03bf\u03bd\u03cc\u03bc\u03b1\u03c4\u03bf\u03c2 \u03b1\u03c1\u03c7\u03b5\u03af\u03bf\u03c5 \u03c4\u03b7\u03c2 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1\u03c2 \u03c3\u03c4\u03b7\u03bd \u03b5\u03bd\u03b1\u03bb\u03bb\u03b1\u03ba\u03c4\u03b9\u03ba\u03ae \u03c4\u03b9\u03bc\u03ae \u03ba\u03b5\u03b9\u03bc\u03ad\u03bd\u03bf\u03c5. \u0395\u03c0\u03b9\u03bb\u03ad\u03be\u03c4\u03b5 \u03bc\u03b9\u03b1 \u03b5\u03bd\u03b1\u03bb\u03bb\u03b1\u03ba\u03c4\u03b9\u03ba\u03ae \u03c4\u03b9\u03bc\u03ae \u03ba\u03b5\u03b9\u03bc\u03ad\u03bd\u03bf\u03c5 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03c6\u03b5\u03b9 \u03c4\u03bf \u03b8\u03ad\u03bc\u03b1 \u03c4\u03b7\u03c2 \u03b5\u03b9\u03ba\u03cc\u03bd\u03b1\u03c2.</td>\n </tr>\n <tr>\n <td>\u039f\u03b9 \u03c0\u03af\u03bd\u03b1\u03ba\u03b5\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bd \u03bb\u03b5\u03b6\u03ac\u03bd\u03c4\u03b5\u03c2</td>\n <td>1.3.1</td>\n <td>\u039f\u03b9 \u03c0\u03af\u03bd\u03b1\u03ba\u03b5\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bd \u03ad\u03bd\u03b1 \u03c3\u03cd\u03bd\u03c4\u03bf\u03bc\u03bf \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03b1\u03c6\u03b9\u03ba\u03cc \u03ba\u03b5\u03af\u03bc\u03b5\u03bd\u03bf \u03c0\u03bf\u03c5 \u03b4\u03b7\u03bb\u03ce\u03bd\u03b5\u03b9 \u03c4\u03b1 \u03c0\u03b5\u03c1\u03b9\u03b5\u03c7\u03cc\u03bc\u03b5\u03bd\u03b1 \u03c4\u03bf\u03c5 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1.</td>\n </tr>\n <tr>\n <td>\u039f\u03b9 \u03c3\u03cd\u03bd\u03b8\u03b5\u03c4\u03bf\u03b9 \u03c0\u03af\u03bd\u03b1\u03ba\u03b5\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bd \u03c0\u03b5\u03c1\u03b9\u03bb\u03ae\u03c8\u03b5\u03b9\u03c2</td>\n <td>1.3.1</td>\n <td>\u039f\u03b9 \u03c0\u03af\u03bd\u03b1\u03ba\u03b5\u03c2 \u03bc\u03b5 \u03c3\u03cd\u03bd\u03b8\u03b5\u03c4\u03b5\u03c2 \u03b4\u03bf\u03bc\u03ad\u03c2 (\u03c4\u03b1 \u03ba\u03b5\u03bb\u03b9\u03ac \u03b5\u03ba\u03c4\u03b5\u03af\u03bd\u03bf\u03bd\u03c4\u03b1\u03b9 \u03c3\u03b5 \u03c0\u03bf\u03bb\u03bb\u03ad\u03c2 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ad\u03c2 \u03ae \u03c3\u03c4\u03ae\u03bb\u03b5\u03c2) \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03c0\u03b5\u03c1\u03b9\u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03bf\u03c5\u03bd \u03bc\u03b9\u03b1 \u03c0\u03b5\u03c1\u03af\u03bb\u03b7\u03c8\u03b7 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03c6\u03b5\u03b9 \u03c4\u03b7 \u03b4\u03bf\u03bc\u03ae \u03c4\u03bf\u03c5 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1. </td>\n </tr>\n <tr>\n <td>\u0397 \u03bb\u03b5\u03b6\u03ac\u03bd\u03c4\u03b1 \u03ba\u03b1\u03b9 \u03b7 \u03c0\u03b5\u03c1\u03af\u03bb\u03b7\u03c8\u03b7 \u03b5\u03bd\u03cc\u03c2 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1 \u03b4\u03b5\u03bd \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bd \u03c4\u03b7\u03bd \u03af\u03b4\u03b9\u03b1 \u03c4\u03b9\u03bc\u03ae</td>\n <td>1.3.1</td>\n <td>\u0397 \u03bb\u03b5\u03b6\u03ac\u03bd\u03c4\u03b1 \u03c4\u03bf\u03c5 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03c6\u03b5\u03b9 \u03c4\u03b1 \u03c0\u03b5\u03c1\u03b9\u03b5\u03c7\u03cc\u03bc\u03b5\u03bd\u03b1 \u03c4\u03bf\u03c5 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1, \u03b5\u03bd\u03ce \u03b7 \u03c0\u03b5\u03c1\u03af\u03bb\u03b7\u03c8\u03b7 \u03c4\u03bf\u03c5 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03c6\u03b5\u03b9 \u03c4\u03b7 \u03b4\u03bf\u03bc\u03ae \u03c4\u03c9\u03bd \u03c3\u03cd\u03bd\u03b8\u03b5\u03c4\u03c9\u03bd \u03c0\u03b9\u03bd\u03ac\u03ba\u03c9\u03bd. </td>\n </tr>\n <tr>\n <td>\u039f\u03b9 \u03c0\u03af\u03bd\u03b1\u03ba\u03b5\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bd \u03c4\u03bf\u03c5\u03bb\u03ac\u03c7\u03b9\u03c3\u03c4\u03bf\u03bd \u03ad\u03bd\u03b1 \u03ba\u03b5\u03bb\u03af \u03c9\u03c2 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1</td>\n <td>1.3.1</td>\n <td>\u039f\u03b9 \u03c0\u03af\u03bd\u03b1\u03ba\u03b5\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03c0\u03b5\u03c1\u03b9\u03bb\u03b1\u03bc\u03b2\u03ac\u03bd\u03bf\u03c5\u03bd \u03c4\u03b9\u03c2 \u03ba\u03b1\u03c4\u03ac\u03bb\u03bb\u03b7\u03bb\u03b5\u03c2 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b5\u03c2 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ce\u03bd \u03ae \u03c3\u03c4\u03b7\u03bb\u03ce\u03bd \u03bf\u03b9 \u03bf\u03c0\u03bf\u03af\u03b5\u03c2 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5\u03bd \u03c4\u03b1 \u03c0\u03c1\u03b9\u03c7\u03cc\u03bc\u03b5\u03bd\u03b1 \u03c4\u03c9\u03bd \u03b3\u03c1\u03b1\u03bc\u03bc\u03ce\u03bd \u03ae \u03c4\u03c9\u03bd \u03c3\u03c4\u03b7\u03bb\u03ce\u03bd.<br/><a href="http://webaim.org/techniques/tables/data#th" target="_blank">\u03a0\u03b5\u03c1\u03b9\u03c3\u03c3\u03cc\u03c4\u03b5\u03c1\u03b5\u03c2 \u03c0\u03bb\u03b7\u03c1\u03bf\u03c6\u03bf\u03c1\u03af\u03b5\u03c2 \u03b3\u03b9\u03b1 \u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03b8\u03ad\u03bc\u03b1 (webaim.org).</a> </td>\n </tr>\n <tr>\n <td>\u039f\u03b9 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b5\u03c2 \u03c4\u03bf\u03c5 \u03c0\u03af\u03bd\u03b1\u03ba\u03b1 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b5\u03c6\u03b1\u03c1\u03bc\u03cc\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9 \u03c3\u03b5 \u03bc\u03b9\u03b1 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ae \u03ae \u03c3\u03b5 \u03bc\u03b9\u03b1 \u03c3\u03c4\u03ae\u03bb\u03b7</td>\n <td>1.3.1</td>\n <td>\u039f\u03b9 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b5\u03c2 \u03c4\u03c9\u03bd \u03c0\u03b9\u03bd\u03ac\u03ba\u03c9\u03bd \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03c3\u03c5\u03c3\u03c7\u03b5\u03c4\u03af\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9 \u03bc\u03b5 \u03c4\u03b9\u03c2 \u03b3\u03c1\u03b1\u03bc\u03bc\u03ad\u03c2 \u03ae \u03c4\u03b9\u03c2 \u03c3\u03c4\u03ae\u03bb\u03b5\u03c2 \u03c0\u03bf\u03c5 \u03c0\u03b5\u03c1\u03b9\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5\u03bd.<br/><a href="http://webaim.org/techniques/tables/data#th" target="_blank">\u03a0\u03b5\u03c1\u03b9\u03c3\u03c3\u03cc\u03c4\u03b5\u03c1\u03b5\u03c2 \u03c0\u03bb\u03b7\u03c1\u03bf\u03c6\u03bf\u03c1\u03af\u03b5\u03c2 \u03b3\u03b9\u03b1 \u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03b8\u03ad\u03bc\u03b1 (webaim.org).</a> </td>\n </tr>\n <tr>\n <td>\u0391\u03c5\u03c4\u03ae \u03b7 \u03c0\u03b1\u03c1\u03ac\u03b3\u03c1\u03b1\u03c6\u03bf\u03c2 \u03bc\u03bf\u03b9\u03ac\u03b6\u03b5\u03b9 \u03bc\u03b5 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1. \u0391\u03bd \u03b5\u03af\u03bd\u03b1\u03b9 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1, \u03b5\u03c0\u03b9\u03bb\u03ad\u03be\u03c4\u03b5 \u03ad\u03bd\u03b1 \u03b5\u03c0\u03af\u03c0\u03b5\u03b4\u03bf \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1\u03c2.</td>\n <td>1.3.1</td>\n <td>\u03a7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03b5\u03af\u03c4\u03b5 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b5\u03c2 \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b4\u03b9\u03b1\u03c7\u03c9\u03c1\u03af\u03b6\u03b5\u03c4\u03b5 \u03c4\u03b1 \u03ad\u03b3\u03b3\u03c1\u03b1\u03c6\u03b1 \u03c3\u03b5 \u03b5\u03bd\u03cc\u03c4\u03b7\u03c4\u03b5\u03c2. \u0391\u03c0\u03bf\u03c6\u03b5\u03cd\u03b3\u03b5\u03c4\u03b5 \u03bd\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03b5\u03af\u03c4\u03b5 \u03bc\u03bf\u03c1\u03c6\u03bf\u03c0\u03bf\u03b9\u03b7\u03bc\u03ad\u03bd\u03b5\u03c2 \u03c0\u03b1\u03c1\u03b1\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5\u03c2 \u03c3\u03c4\u03b9\u03c2 \u03b8\u03ad\u03c3\u03b5\u03b9\u03c2 \u03c4\u03c9\u03bd \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03c9\u03bd.<br/><a href="http://webaim.org/techniques/semanticstructure/#correctly" target="_blank">\u03a0\u03b5\u03c1\u03b9\u03c3\u03c3\u03cc\u03c4\u03b5\u03c1\u03b5\u03c2 \u03c0\u03bb\u03b7\u03c1\u03bf\u03c6\u03bf\u03c1\u03af\u03b5\u03c2 \u03b3\u03b9\u03b1 \u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03b8\u03ad\u03bc\u03b1 (webaim.org).</a> </td>\n </tr>\n <tr>\n <td>\u039f\u03b9 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b5\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b5\u03c6\u03b1\u03c1\u03bc\u03cc\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9 \u03c3\u03b5 \u03b4\u03b9\u03b1\u03b4\u03bf\u03c7\u03b9\u03ba\u03ae \u03c3\u03b5\u03b9\u03c1\u03ac. \u0393\u03b9\u03b1 \u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3\u03bc\u03b1: \u0397 \u0395\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1 1 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b1\u03ba\u03bf\u03bb\u03bf\u03c5\u03b8\u03b5\u03af\u03c4\u03b1\u03b9 \u03b1\u03c0\u03cc \u03c4\u03b7\u03bd \u0395\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1 2, \u03cc\u03c7\u03b9 \u03b1\u03c0\u03cc \u03c4\u03b7\u03bd \u0395\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1 3.</td>\n <td>1.3.1</td>\n <td>\u039f\u03b9 \u03b5\u03c0\u03cc\u03bc\u03b5\u03bd\u03b5\u03c2 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b5\u03c2 \u03c4\u03bf\u03c5 \u03b5\u03b3\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03b5\u03bc\u03c6\u03b1\u03bd\u03af\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9 \u03b9\u03b5\u03c1\u03b1\u03c1\u03c7\u03b9\u03ba\u03ac, \u03c3\u03b5 \u03b1\u03cd\u03be\u03bf\u03c5\u03c3\u03b1 \u03ae \u03b9\u03c3\u03bf\u03b4\u03cd\u03bd\u03b1\u03bc\u03b7 \u03c3\u03b5\u03b9\u03c1\u03ac.<br/><a href="http://webaim.org/techniques/semanticstructure/#contentstructure" target="_blank">\u03a0\u03b5\u03c1\u03b9\u03c3\u03c3\u03cc\u03c4\u03b5\u03c1\u03b5\u03c2 \u03c0\u03bb\u03b7\u03c1\u03bf\u03c6\u03bf\u03c1\u03af\u03b5\u03c2 \u03b3\u03b9\u03b1 \u03b1\u03c5\u03c4\u03cc \u03c4\u03bf \u03b8\u03ad\u03bc\u03b1 (webaim.org).</a> </td>\n </tr>\n <tr>\n <td>\u03a7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03b5\u03af\u03c4\u03b5 \u03c3\u03ae\u03bc\u03b1\u03bd\u03c3\u03b7 \u03bb\u03af\u03c3\u03c4\u03b1\u03c2 \u03b3\u03b9\u03b1 \u03c4\u03b9\u03c2 \u03bb\u03af\u03c3\u03c4\u03b5\u03c2</td>\n <td>1.3.1</td>\n <td>\u0392\u03b5\u03b2\u03b1\u03b9\u03c9\u03b8\u03b5\u03af\u03c4\u03b5 \u03cc\u03c4\u03b9 \u03bf\u03b9 \u03bb\u03af\u03c3\u03c4\u03b5\u03c2 \u03c3\u03c4\u03bf\u03b9\u03c7\u03b5\u03af\u03c9\u03bd \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03bf\u03cd\u03bd \u03c4\u03b7 \u03b4\u03bf\u03bc\u03ae \u03c4\u03c9\u03bd \u03bb\u03b9\u03c3\u03c4\u03ce\u03bd HTML \u03b3\u03b9\u03b1 \u03bd\u03b1 \u03b5\u03bc\u03c6\u03b1\u03bd\u03af\u03b6\u03bf\u03bd\u03c4\u03b1\u03b9 \u03c9\u03c2 \u03bb\u03af\u03c3\u03c4\u03b5\u03c2 (<code>&lt;ul&gt;</code> \u03ae <code>&lt;ol&gt;</code> &amp; <code>&lt;li&gt;</code>).</td>\n </tr>\n <tr>\n <td>\u03a4\u03bf \u03ba\u03b5\u03af\u03bc\u03b5\u03bd\u03bf \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03b5\u03b9 \u03bb\u03cc\u03b3\u03bf \u03b1\u03bd\u03c4\u03af\u03b8\u03b5\u03c3\u03b7\u03c2 4,5:1</td>\n <td>1.4.3</td>\n <td>\u03a4\u03bf \u03ba\u03b5\u03af\u03bc\u03b5\u03bd\u03bf \u03ba\u03b1\u03b9 \u03c4\u03bf \u03c6\u03cc\u03bd\u03c4\u03bf \u03c4\u03bf\u03c5 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03ad\u03c7\u03bf\u03c5\u03bd \u03c4\u03ad\u03c4\u03bf\u03b9\u03bf \u03bb\u03cc\u03b3\u03bf \u03b1\u03bd\u03c4\u03af\u03b8\u03b5\u03c3\u03b7\u03c2 \u03c0\u03bf\u03c5 \u03bd\u03b1 \u03bc\u03c0\u03bf\u03c1\u03b5\u03af \u03bd\u03b1 \u03b4\u03b9\u03b1\u03b2\u03b1\u03c3\u03c4\u03b5\u03af \u03b1\u03c0\u03cc \u03b1\u03bd\u03b8\u03c1\u03ce\u03c0\u03bf\u03c5\u03c2 \u03bc\u03b5 \u03bc\u03ad\u03c4\u03c1\u03b9\u03b1 \u03c7\u03b1\u03bc\u03b7\u03bb\u03ae \u03cc\u03c1\u03b1\u03c3\u03b7.</td>\n </tr>\n <tr>\n <td>\u039f\u03b9 \u03b3\u03b5\u03b9\u03c4\u03bf\u03bd\u03b9\u03ba\u03ad\u03c2 \u03c3\u03c5\u03bd\u03b4\u03ad\u03c3\u03b5\u03b9\u03c2 \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03c3\u03c5\u03b3\u03c7\u03c9\u03bd\u03b5\u03cd\u03bf\u03bd\u03c4\u03b1\u03b9.</td>\n <td>2.4.4</td>\n <td>\u039f\u03b9 \u03b3\u03b5\u03b9\u03c4\u03bf\u03bd\u03b9\u03ba\u03ad\u03c2 \u03c5\u03c0\u03b5\u03c1\u03c3\u03c5\u03bd\u03b4\u03ad\u03c3\u03b5\u03b9\u03c2 \u03c0\u03bf\u03c5 \u03b4\u03b5\u03af\u03c7\u03bd\u03bf\u03c5\u03bd \u03c3\u03c4\u03b7\u03bd \u03af\u03b4\u03b9\u03b1 \u03c0\u03b7\u03b3\u03ae \u03c0\u03c1\u03ad\u03c0\u03b5\u03b9 \u03bd\u03b1 \u03c3\u03c5\u03b3\u03c7\u03c9\u03bd\u03b5\u03cd\u03bf\u03bd\u03c4\u03b1\u03b9 \u03c3\u03b5 \u03bc\u03af\u03b1 \u03c5\u03c0\u03b5\u03c1\u03c3\u03cd\u03bd\u03b4\u03b5\u03c3\u03b7.</td>\n </tr>\n </tbody>\n </table>\n <div role="heading" aria-level="2" class="ephox-polish-help-h2">\u03a0\u03b5\u03c1\u03b9\u03c3\u03c3\u03cc\u03c4\u03b5\u03c1\u03b5\u03c2 \u03c0\u03bb\u03b7\u03c1\u03bf\u03c6\u03bf\u03c1\u03af\u03b5\u03c2</div>\n <p>\n <a href="http://webaim.org/intro/" target="_blank">\u0395\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae \u03c3\u03c4\u03b7\u03bd \u03c0\u03c1\u03bf\u03c3\u03b2\u03b1\u03c3\u03b9\u03bc\u03cc\u03c4\u03b7\u03c4\u03b1 \u03c3\u03c4\u03bf web (webaim.org)</a> <br/>\n <a href="http://www.w3.org/WAI/intro/wcag" target="_blank">\u0395\u03b9\u03c3\u03b1\u03b3\u03c9\u03b3\u03ae \u03c3\u03c4\u03bf WCAG 2.0 (w3.org)</a> <br/>\n <a href="http://www.section508.gov/" target="_blank">\u0395\u03bd\u03cc\u03c4\u03b7\u03c4\u03b1 508 \u03c4\u03bf\u03c5 \u039d\u03cc\u03bc\u03bf\u03c5 \u03c4\u03c9\u03bd \u0397\u03a0\u0391 \u03c0\u03b5\u03c1\u03af \u0391\u03c0\u03bf\u03ba\u03b1\u03c4\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7\u03c2 (section508.gov)</a>\n </p>\n</div>'),markdown:a('\ufeff<div role=presentation class="ephox-polish-help-article">\n <div class="ephox-polish-help-h1" role="heading" aria-level="1">\u039c\u03bf\u03c1\u03c6\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7 Markdown</div>\n <p>\u0397 Markdown \u03b5\u03af\u03bd\u03b1\u03b9 \u03bc\u03b9\u03b1 \u03c3\u03cd\u03bd\u03c4\u03b1\u03be\u03b7 \u03b3\u03b9\u03b1 \u03c4\u03b7 \u03b4\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03af\u03b1 \u03b4\u03bf\u03bc\u03ce\u03bd HTML \u03ba\u03b1\u03b9 \u03c4\u03b7 \u03bc\u03bf\u03c1\u03c6\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7 \u03c7\u03c9\u03c1\u03af\u03c2 \u03bd\u03b1 \u03b1\u03c0\u03b1\u03b9\u03c4\u03b5\u03af\u03c4\u03b1\u03b9 \u03b7 \u03c7\u03c1\u03ae\u03c3\u03b7 \u03c3\u03c5\u03bd\u03c4\u03bf\u03bc\u03b5\u03cd\u03c3\u03b5\u03c9\u03bd \u03c0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03af\u03bf\u03c5 \u03ae \u03bc\u03b5\u03bd\u03bf\u03cd \u03c0\u03c1\u03cc\u03c3\u03b2\u03b1\u03c3\u03b7\u03c2. \u0393\u03b9\u03b1 \u03bd\u03b1 \u03c7\u03c1\u03b7\u03c3\u03b9\u03bc\u03bf\u03c0\u03bf\u03b9\u03ae\u03c3\u03b5\u03c4\u03b5 \u03c4\u03b7 \u03bc\u03bf\u03c1\u03c6\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7 markdown, \u03b5\u03b9\u03c3\u03b1\u03b3\u03ac\u03b3\u03b5\u03c4\u03b5 \u03c4\u03b7\u03bd \u03b5\u03c0\u03b9\u03b8\u03c5\u03bc\u03b7\u03c4\u03ae \u03c3\u03cd\u03bd\u03c4\u03b1\u03be\u03b7 \u03b1\u03ba\u03bf\u03bb\u03bf\u03c5\u03b8\u03bf\u03cd\u03bc\u03b5\u03bd\u03b7 \u03b1\u03c0\u03cc \u03c4\u03bf \u03c0\u03bb\u03ae\u03ba\u03c4\u03c1\u03bf \u03b4\u03b9\u03b1\u03c3\u03c4\u03ae\u03bc\u03b1\u03c4\u03bf\u03c2 \u03ae enter.</p>\n <table cellpadding="0" cellspacing="0" class="ephox-polish-tabular ephox-polish-help-table ephox-polish-help-table-markdown" aria-readonly="true">\n <caption>\u03a3\u03cd\u03bd\u03c4\u03b1\u03be\u03b7 \u03bc\u03bf\u03c1\u03c6\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7\u03c2 \u03c0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03af\u03bf\u03c5</caption>\n <thead>\n <tr>\n <th scope="col">\u03a3\u03cd\u03bd\u03c4\u03b1\u03be\u03b7</th>\n <th scope="col">\u0391\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1 HTML</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td><pre># \u039c\u03ad\u03b3\u03b9\u03c3\u03c4\u03b7 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1</pre></td>\n <td><pre>&lt;h1&gt; \u039c\u03ad\u03b3\u03b9\u03c3\u03c4\u03b7 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1&lt;/h1&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>## \u039c\u03b5\u03b3\u03b1\u03bb\u03cd\u03c4\u03b5\u03c1\u03b7 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1</pre></td>\n <td><pre>&lt;h2&gt;\u039c\u03b5\u03b3\u03b1\u03bb\u03cd\u03c4\u03b5\u03c1\u03b7 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1&lt;/h2&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>### \u039c\u03b5\u03b3\u03ac\u03bb\u03b7 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1</pre></td>\n <td><pre>&lt;h3&gt;\u039c\u03b5\u03b3\u03ac\u03bb\u03b7 \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1&lt;/h3&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>#### \u0395\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1</pre></td>\n <td><pre>&lt;h4&gt;\u0395\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1&lt;/h4&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>##### \u039c\u03b9\u03ba\u03c1\u03ae \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1</pre></td>\n <td><pre>&lt;h5&gt;\u039c\u03b9\u03ba\u03c1\u03ae \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1&lt;/h5&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>###### \u0397 \u03c0\u03b9\u03bf \u03bc\u03b9\u03ba\u03c1\u03ae \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1</pre></td>\n <td><pre>&lt;h6&gt;\u0397 \u03c0\u03b9\u03bf \u03bc\u03b9\u03ba\u03c1\u03ae \u03b5\u03c0\u03b9\u03ba\u03b5\u03c6\u03b1\u03bb\u03af\u03b4\u03b1&lt;/h6&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>* \u039c\u03b7 \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03b7\u03bc\u03ad\u03bd\u03b7 \u03bb\u03af\u03c3\u03c4\u03b1</pre></td>\n <td><pre>&lt;ul&gt;&lt;li&gt;\u039c\u03b7 \u03c4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03b7\u03bc\u03ad\u03bd\u03b7 \u03bb\u03af\u03c3\u03c4\u03b1&lt;/li&gt;&lt;/ul&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>1. \u03a4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03b7\u03bc\u03ad\u03bd\u03b7 \u03bb\u03af\u03c3\u03c4\u03b1</pre></td>\n <td><pre>&lt;ol&gt;&lt;li&gt;\u03a4\u03b1\u03be\u03b9\u03bd\u03bf\u03bc\u03b7\u03bc\u03ad\u03bd\u03b7 \u03bb\u03af\u03c3\u03c4\u03b1&lt;/li&gt;&lt;/ol&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>*\u03a0\u03bb\u03ac\u03b3\u03b9\u03b1 \u03b3\u03c1\u03b1\u03c6\u03ae*</pre></td>\n <td><pre>&lt;em&gt;\u03a0\u03bb\u03ac\u03b3\u03b9\u03b1 \u03b3\u03c1\u03b1\u03c6\u03ae&lt;/em&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>**\u0388\u03bd\u03c4\u03bf\u03bd\u03b7 \u03b3\u03c1\u03b1\u03c6\u03ae**</pre></td>\n <td><pre>&lt;strong&gt;\u0388\u03bd\u03c4\u03bf\u03bd\u03b7 \u03b3\u03c1\u03b1\u03c6\u03ae&lt;/strong&gt;</pre></td>\n </tr>\n <tr>\n <td><pre>---</pre></td>\n <td><pre>&lt;hr/&gt;</pre></td>\n </tr>\n </tbody>\n </table>\n</div>'),shortcuts:a('\ufeff<div role=presentation class="ephox-polish-help-article">\n <div role="heading" aria-level="1" class="ephox-polish-help-h1">\u03a3\u03c5\u03bd\u03c4\u03bf\u03bc\u03b5\u03cd\u03c3\u03b5\u03b9\u03c2 \u03c0\u03bb\u03b7\u03ba\u03c4\u03c1\u03bf\u03bb\u03bf\u03b3\u03af\u03bf\u03c5</div>\n <table aria-readonly="true" cellpadding="0" cellspacing="0" class="ephox-polish-tabular ephox-polish-help-table ephox-polish-help-table-shortcuts">\n <caption>\u0395\u03bd\u03c4\u03bf\u03bb\u03ad\u03c2 \u03b5\u03c0\u03b5\u03be\u03b5\u03c1\u03b3\u03b1\u03c3\u03c4\u03ae \u03ba\u03b5\u03b9\u03bc\u03ad\u03bd\u03bf\u03c5</caption>\n <thead>\n <tr>\n <th scope="col">\u0395\u03bd\u03ad\u03c1\u03b3\u03b5\u03b9\u03b1</th>\n <th scope="col">Windows</th>\n <th scope="col">Mac OS</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\u0391\u03bd\u03b1\u03af\u03c1\u03b5\u03c3\u03b7</td>\n <td>CTRL + Z</td>\n <td>\u2318Z</td>\n </tr>\n <tr>\n <td>\u0395\u03c0\u03b1\u03bd\u03ac\u03bb\u03b7\u03c8\u03b7</td>\n <td>CTRL + Y</td>\n <td>\u2318\u21e7Z</td>\n </tr>\n <tr>\n <td>\u0388\u03bd\u03c4\u03bf\u03bd\u03b7 \u03b3\u03c1\u03b1\u03c6\u03ae</td>\n <td>CTRL + B</td>\n <td>\u2318B</td>\n </tr>\n <tr>\n <td>\u03a0\u03bb\u03ac\u03b3\u03b9\u03b1 \u03b3\u03c1\u03b1\u03c6\u03ae</td>\n <td>CTRL + I</td>\n <td>\u2318I</td>\n </tr>\n <tr>\n <td>\u03a5\u03c0\u03bf\u03b3\u03c1\u03ac\u03bc\u03bc\u03b9\u03c3\u03b7</td>\n <td>CTRL + U</td>\n <td>\u2318U</td>\n </tr>\n <tr>\n <td>\u0395\u03c3\u03bf\u03c7\u03ae</td>\n <td>CTRL + ]</td>\n <td>\u2318]</td>\n </tr>\n <tr>\n <td>\u039c\u03b5\u03af\u03c9\u03c3\u03b7 \u03b5\u03c3\u03bf\u03c7\u03ae\u03c2</td>\n <td>CTRL + [</td>\n <td>\u2318[</td>\n </tr>\n <tr>\n <td>\u03a0\u03c1\u03bf\u03c3\u03b8\u03ae\u03ba\u03b7 \u03c3\u03cd\u03bd\u03b4\u03b5\u03c3\u03b7\u03c2</td>\n <td>CTRL + K</td>\n <td>\u2318K</td>\n </tr>\n <tr>\n <td>\u0395\u03cd\u03c1\u03b5\u03c3\u03b7</td>\n <td>CTRL + F</td>\n <td>\u2318F</td>\n </tr>\n <tr>\n <td>\u039b\u03b5\u03b9\u03c4\u03bf\u03c5\u03c1\u03b3\u03af\u03b1 \u03c0\u03bb\u03ae\u03c1\u03bf\u03c5\u03c2 \u03bf\u03b8\u03cc\u03bd\u03b7\u03c2 (\u0395\u03bd\u03b1\u03bb\u03bb\u03b1\u03b3\u03ae)</td>\n <td>CTRL + SHIFT + F</td>\n <td>\u2318\u21e7F</td>\n </tr>\n <tr>\n <td>\u03a0\u03bb\u03b1\u03af\u03c3\u03b9\u03bf \u03b4\u03b9\u03b1\u03bb\u03cc\u03b3\u03bf\u03c5 \u0392\u03bf\u03ae\u03b8\u03b5\u03b9\u03b1\u03c2 (\u0386\u03bd\u03bf\u03b9\u03b3\u03bc\u03b1)</td>\n <td>CTRL + SHIFT + H</td>\n <td>\u2303\u2325H</td>\n </tr>\n <tr>\n <td>\u039c\u03b5\u03bd\u03bf\u03cd \u03c0\u03b5\u03c1\u03b9\u03b2\u03ac\u03bb\u03bb\u03bf\u03bd\u03c4\u03bf\u03c2 (\u0386\u03bd\u03bf\u03b9\u03b3\u03bc\u03b1)</td>\n <td>SHIFT + F10</td>\n <td>\u21e7F10\u200e\u200f</td>\n </tr>\n <tr>\n <td>\u0391\u03c5\u03c4\u03cc\u03bc\u03b1\u03c4\u03b7 \u03c3\u03c5\u03bc\u03c0\u03bb\u03ae\u03c1\u03c9\u03c3\u03b7 \u03ba\u03ce\u03b4\u03b9\u03ba\u03b1</td>\n <td>CTRL + \u0394\u03b9\u03ac\u03c3\u03c4\u03b7\u03bc\u03b1</td>\n <td>\u2303\u0394\u03b9\u03ac\u03c3\u03c4\u03b7\u03bc\u03b1</td>\n </tr>\n <tr>\n <td>\u03a0\u03c1\u03bf\u03b2\u03bf\u03bb\u03ae \u03c0\u03c1\u03bf\u03c3\u03b2\u03ac\u03c3\u03b9\u03bc\u03bf\u03c5 \u03ba\u03ce\u03b4\u03b9\u03ba\u03b1</td>\n <td>CTRL + SHIFT + U</td>\n <td>\u2318\u2325U</td>\n </tr>\n </tbody>\n </table>\n <div class="ephox-polish-help-note" role="note">*\u03a3\u03b7\u03bc\u03b5\u03af\u03c9\u03c3\u03b7: \u039f\u03c1\u03b9\u03c3\u03bc\u03ad\u03bd\u03b5\u03c2 \u03b4\u03c5\u03bd\u03b1\u03c4\u03cc\u03c4\u03b7\u03c4\u03b5\u03c2 \u03bc\u03c0\u03bf\u03c1\u03bf\u03cd\u03bd \u03bd\u03b1 \u03b1\u03c0\u03b5\u03bd\u03b5\u03c1\u03b3\u03bf\u03c0\u03bf\u03b9\u03b7\u03b8\u03bf\u03cd\u03bd \u03b1\u03c0\u03cc \u03c4\u03bf \u03b4\u03b9\u03b1\u03c7\u03b5\u03b9\u03c1\u03b9\u03c3\u03c4\u03ae \u03c3\u03b1\u03c2.</div>\n</div>\n')})}();
main.go
package main import ( "context" "fmt" "io" "os" "time" "github.com/dustin/go-humanize" "github.com/go-faster/ch" "github.com/go-faster/ch/proto" "github.com/go-faster/errors" ) func
(ctx context.Context) error { c, err := ch.Dial(ctx, "localhost:9000", ch.Options{ Compression: ch.CompressionLZ4, }) if err != nil { return errors.Wrap(err, "dial") } defer func() { _ = c.Close() }() if err := c.Do(ctx, ch.Query{ Body: "CREATE TABLE IF NOT EXISTS test_table (id UInt64) ENGINE = Null", }); err != nil { return err } start := time.Now() const ( totalBlocks = 5000 rowsInBlock = 60_000 totalRows = totalBlocks * rowsInBlock totalBytes = totalRows * (64 / 8) ) var ( idColumns proto.ColUInt64 blocks int ) for i := 0; i < rowsInBlock; i++ { idColumns = append(idColumns, 1) } if err := c.Do(ctx, ch.Query{ Body: "INSERT INTO test_table VALUES", OnInput: func(ctx context.Context) error { blocks++ if blocks >= totalBlocks { return io.EOF } return nil }, Input: []proto.InputColumn{ {Name: "id", Data: idColumns}, }, }); err != nil { return err } duration := time.Since(start) fmt.Println(duration.Round(time.Millisecond), totalRows, "rows", humanize.Bytes(totalBytes), humanize.Bytes(uint64(float64(totalBytes)/duration.Seconds()))+"/s", ) return nil } func main() { if err := run(context.Background()); err != nil { fmt.Fprintf(os.Stderr, "Error: %+v\n", err) os.Exit(2) } }
run
mod.rs
use hecs::World; use std::collections::HashMap; use crate::{RefExtractor, ResourceTuple, SystemContext}; mod builder; use builder::DummyHandle; pub use builder::ExecutorBuilder; #[cfg(not(feature = "parallel"))] mod sequential; #[cfg(not(feature = "parallel"))] use sequential::ExecutorSequential; #[cfg(feature = "parallel")] mod parallel; #[cfg(feature = "parallel")] use crate::TypeSet; #[cfg(feature = "parallel")] use parallel::ExecutorParallel; type SystemClosure<'closure, Cells> = dyn FnMut(SystemContext, &Cells) + Send + Sync + 'closure; #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub struct SystemId(pub(crate) usize); /// A sealed container for systems that may be executed in parallel. /// /// Systems can be any closure or function that return nothing and have these 3 arguments: /// - [`SystemContext`](struct.SystemContext.html), /// - any tuple (up to 16) or a single one of "resources": references or mutable references /// to `Send + Sync` values not contained in a [`hecs::World`](../hecs/struct.World.html) /// that the system will be accessing, /// - any tuple (up to 16) or a single one of [`QueryMarker`](struct.QueryMarker.html) that /// represent the queries the system will be making. /// /// Additionally, closures may mutably borrow from their environment for the lifetime `'closures` /// of the executor, but must be `Send + Sync`. If none of the systems make any borrows from the /// environment, said lifetime can simply be `'static`. /// /// The generic parameter `Resources` of the executor must be a superset tuple of all resource set /// tuples of the contained systems. Any type in `Resources` must appear no more than once, /// however, any number of systems in the executor may have either an immutable or a mutable /// reference of said type in their signature. For example: if any number of systems require /// a `&f32` or a `&mut f32`, `Resources` must contain `f32`. /// /// It's possible to define an order of execution of the systems by building up a dependency /// graph when building the executor, see [`ExecutorBuilder::system_with_handle()`][swh]. /// /// [swh]: struct.ExecutorBuilder.html#method.system_with_handle /// /// Executors are relatively costly to instantiate, and should be cached whenever possible. /// /// Executors are not intended to house any and all behavior of the program, they work best /// when treated as a sort of [`yaks::batch()`](fn.batch.html) for systems; e.g., /// make one only when the systems in it may actually benefit from being ran concurrently /// and prefer several small executors over a single large one. /// /// See [`::run()`](#method.run), crate examples, and documentation for other items in the library /// for more details and specific demos. pub struct Executor<'closures, Resources> where Resources: ResourceTuple, { pub(crate) borrows: Resources::BorrowTuple, #[cfg(feature = "parallel")] pub(crate) inner: ExecutorParallel<'closures, Resources>, #[cfg(not(feature = "parallel"))] pub(crate) inner: ExecutorSequential<'closures, Resources>, } impl<'closures, Resources> Executor<'closures, Resources> where Resources: ResourceTuple, { /// Creates a new [`ExecutorBuilder`](struct.ExecutorBuilder.html). pub fn
() -> ExecutorBuilder<'closures, Resources> { ExecutorBuilder::<'closures, Resources, DummyHandle> { systems: HashMap::new(), handles: HashMap::with_capacity(0), #[cfg(feature = "parallel")] all_component_types: TypeSet::new(), } } pub(crate) fn build<Handle>(builder: ExecutorBuilder<'closures, Resources, Handle>) -> Self { Self { borrows: Resources::instantiate_borrows(), #[cfg(feature = "parallel")] inner: ExecutorParallel::build(builder), #[cfg(not(feature = "parallel"))] inner: ExecutorSequential::build(builder), } } /// Forces the executor to forget stored [`hecs::ArchetypesGeneration`][1], see /// [`hecs::World::archetypes_generation()`][2]. /// /// **Must** be called before using the executor with a different [`hecs::World`][3] than /// it was used with earlier - not doing so may cause a panic when a query makes it's borrows. /// In all other cases, calling this function is unnecessary and detrimental to performance. /// /// [1]: ../hecs/struct.ArchetypesGeneration.html /// [2]: ../hecs/struct.World.html#method.archetypes_generation /// [3]: ../hecs/struct.World.html /// /// # Example /// ```rust /// # let mut executor = yaks::Executor::<()>::builder().build(); /// # let world_a = hecs::World::new(); /// # let world_b = hecs::World::new(); /// executor.run(&world_a, ()); /// executor.run(&world_a, ()); /// executor.force_archetype_recalculation(); /// executor.run(&world_b, ()); /// executor.run(&world_b, ()); /// executor.force_archetype_recalculation(); /// executor.run(&world_a, ()); /// ``` pub fn force_archetype_recalculation(&mut self) { self.inner.force_archetype_recalculation(); } /// Executes all of the contained systems once, running as much of them at the same time /// as their resource use, queries, and dependencies allow. /// /// The exact order of execution is not guaranteed, except for systems with defined /// dependencies (see [`ExecutorBuilder::system_with_handle()`][swh]), or if the default /// `parallel` feature is disabled (in which case the systems will be executed in order /// of their insertion into the builder). /// /// [swh]: struct.ExecutorBuilder.html#method.system_with_handle /// /// The `resources` argument when calling this function must be a tuple of exclusive references /// to values of types specified by the generic parameter `Resources` of the executor: /// ```rust /// # use yaks::Executor; /// # let world = hecs::World::new(); /// let mut executor = Executor::<(f32, u32)>::builder().build(); /// let mut some_f32 = 0f32; /// let mut some_u32 = 0u32; /// executor.run(&world, (&mut some_f32, &mut some_u32)); /// /// let mut executor = Executor::<(f32, )>::builder().build(); /// executor.run(&world, (&mut some_f32, )); /// /// // Single resource type is also special-cased for convenience. /// let mut executor = Executor::<(f32, )>::builder().build(); /// executor.run(&world, &mut some_f32); /// /// let mut executor = Executor::<()>::builder().build(); /// executor.run(&world, ()); /// ``` /// In the future, exclusivity requirement might be relaxed for resources that aren't mutated /// by any of the systems, but doing that as of writing is unfeasible. /// /// This function can be called inside a /// [`rayon::ThreadPool::install()`](../rayon/struct.ThreadPool.html#method.install) block /// to use that thread pool instead of the global one: /// ```rust /// # use yaks::Executor; /// # let world = hecs::World::new(); /// # #[cfg(feature = "parallel")] /// # let thread_pool = /// # { /// # rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap() /// # }; /// # #[cfg(not(feature = "parallel"))] /// # let thread_pool = /// # { /// # struct DummyPool; /// # impl DummyPool { /// # fn install(&self, mut closure: impl FnMut()) { /// # closure(); /// # } /// # } /// # DummyPool /// # }; /// # let mut executor = Executor::<()>::builder().build(); /// thread_pool.install(|| executor.run(&world, ())); /// ``` /// Doing so will cause all [`yaks::batch()`](fn.batch.html) calls inside systems /// to also use said thread pool. /// /// # Panics /// This function will panic if: /// - a system within the executor has resource requirements that are incompatible with itself, /// e.g. `(&mut SomeResource, &SomeResource)`. /// /// Additionally, it *may* panic if: /// - a different [`hecs::World`](../hecs/struct.World.html) is supplied than /// in a previous call, without first calling /// [`::force_archetype_recalculation()`](#method.force_archetype_recalculation). pub fn run<RefSource>(&mut self, world: &World, resources: RefSource) where Resources: RefExtractor<RefSource>, { Resources::extract_and_run(self, world, resources); } }
builder
payments.service.ts
import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {utilitiesUrls, paymentsUrls} from '../../services/app-http/backendUrlStrings'; import {CurrencyService} from '../../services/currencies/currency.service'; import {AuthserviceService} from '../../public/authservice.service'; // import {Order, Invoice, Item} from '../services/interfaces/payments.interface'; export interface OrderToPay { orderId: number; payingAmount: number; } export interface PayMtnMomoBasic { currency: string; orderId: number; phoneNumber: string; } export interface PayPayCash { orderId: number; password: string; } export interface PayVoucher { orderId: number; voucherCode: string; } @Injectable({ providedIn: 'root' }) export class PaymentsService { orderId = 0; payingAmount = 0.0; constructor(private http: HttpClient, private currencyService: CurrencyService, private authService: AuthserviceService) { } getOrders(registered: boolean) { // for non registered customers // show them their registration orders only // for registered customers show all pending orders return registered ? this.getPendingOrders() : this.getRegistrationOrders(); } getRegistrationOrders() { return this.http.get(paymentsUrls.GET_REGISTRATION_ORDERS); } getPendingOrders() { return this.http.get(paymentsUrls.GET_PENDING_ORDERS); } getPaymentChannels() { return this.http.get(paymentsUrls.GET_PAYMENT_CHANNELS); } getOrderToPay(): OrderToPay { return (this.orderId === 0 || this.payingAmount === 0.0) ? null : {orderId: this.orderId, payingAmount: this.payingAmount}; } setOrderToPay(order: OrderToPay) { this.orderId = order.orderId; this.payingAmount = order.payingAmount; } clearOrderToPay() { this.orderId = 0; this.payingAmount = 0.0; } storePaymentChannels(channels: any) { localStorage.setItem('paymentChannels', JSON.stringify(channels)); } retrievePaymentChannels() { return JSON.parse(localStorage.getItem('paymentChannels')); } payWithPayCash(payPayCash: PayPayCash) { return this.http.post(paymentsUrls.PAY_WITH_PAYCASH, payPayCash); } payWithVoucher(payVoucher: PayVoucher) { return this.http.post(paymentsUrls.PAY_WITH_VOUCHER, payVoucher); } payWithMtnMomoBasic(payMtnMomoBasic: PayMtnMomoBasic) { return this.http.post(paymentsUrls.PAY_WITH_MTN_MOMO_BASIC, payMtnMomoBasic); } getAvailableCurrencies() {
} getCurrencyObj() { return this.currencyService.getCurrencyObj(); } getExchangeCurrency(exchangeCurrencyStr: string) { return this.currencyService.getExchangeCurrency(exchangeCurrencyStr); } createVoucher(voucher: {amount: Number, password: string}) { return this.http.post(paymentsUrls.CREATE_VOUCHER, voucher); } createMakerAccount(password: string) { return this.http.post(paymentsUrls.CREATE_MAKER_ACCOUNT, {password: password}); } refreshCustomerDetails() { this.authService.startRefreshTokenTimeout(); } }
return this.currencyService.getCurrencyObj();
ParsingUtils.ts
import { CoveredNode, Event, EventType, Model, ParsedModel, ParsedRun, ParsedSuite, Suite } from "../api/api"; import distinct from "./ArrayUtils"; export const getDistinctIds = (events: Event[], type: EventType): string[] => ( events .filter(event => event.type === type) .map(event => event.definitionKey) .filter(distinct()) ); export const parseSuites = (suites: Suite[], models: Model[]): ParsedSuite[] => ( suites.map(suite => { const modelKeys = suite.runs .flatMap(run => run.events) .map(event => event.modelKey) .filter(distinct()); const parsedModels: ParsedModel[] = modelKeys .map(modelKey => { const model = models.find(m => m.key === modelKey); if (!model) { throw new Error(`Could not find required model with key ${modelKey}`); } const runs: ParsedRun[] = suite.runs.map(run => { const events = run.events.filter(event => event.modelKey === modelKey); const coveredFlows = getDistinctIds(events, "TAKE"); const startedNodes = getDistinctIds(events, "START"); const endedNodes = getDistinctIds(events, "END"); const coveredNodes: CoveredNode[] = startedNodes.map(id => ({ id: id, ended: endedNodes.indexOf(id) !== -1 })); return { id: run.id, name: run.name, totalElementCount: model.totalElementCount, coveredNodes: coveredNodes, coveredNodeCount: coveredNodes.length, coveredSequenceFlows: coveredFlows, coveredSequenceFlowCount: coveredFlows.length, coverage: (coveredNodes.length + coveredFlows.length) / model.totalElementCount }; }); const coveredFlows = runs .flatMap(run => run.coveredSequenceFlows) .filter(distinct()); const coveredNodes = runs .flatMap(run => run.coveredNodes) .filter(distinct((item: CoveredNode) => item.id)); return {
id: model.id, key: model.key, xml: model.xml, runs: runs, coveredSequenceFlows: coveredFlows, coveredSequenceFlowCount: coveredFlows.length, coveredNodes: coveredNodes, coveredNodeCount: coveredNodes.length, totalElementCount: model.totalElementCount, coverage: (coveredNodes.length + coveredFlows.length) / model.totalElementCount }; }); const coveredFlows = parsedModels .flatMap(run => run.coveredSequenceFlows) .filter(distinct()); const coveredNodes = parsedModels .flatMap(run => run.coveredNodes) .filter(distinct((item: CoveredNode) => item.id)); const totalElementCount = parsedModels.reduce( (prev, cur) => prev + cur.totalElementCount, 0 ); return { id: suite.id, name: suite.name, models: parsedModels, coveredSequenceFlows: coveredFlows, coveredSequenceFlowCount: coveredFlows.length, coveredNodes: coveredNodes, coveredNodeCount: coveredNodes.length, totalElementCount: totalElementCount, coverage: (coveredNodes.length + coveredFlows.length) / totalElementCount }; }) );
listas.py
#Packages import os os.system("cls") lista=[] #Functions def llenar_lista(x):
#def validacion_lista(): # print("Validación :") #def mostrar_lista(): # print("Mostrar") #Main num=int(input("Ingrese No: ")) op=int(input("::::Desea Agregar un nuevo Número a la Lista : \n1. Si\n2. No : ")) if op =="s" or op =="S" or op == "1": llenar_lista(num) else: print("opción incorrecta") # validacion_lista()
lista.append(x)
tracing.go
package servicebus // MIT License // // Copyright (c) Microsoft Corporation. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE import ( "context" "net/http" "os" "github.com/devigned/tab" ) func (ns *Namespace) startSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := tab.StartSpan(ctx, operationName) applyComponentInfo(span) return ctx, span } func (m *Message) startSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := tab.StartSpan(ctx, operationName) applyComponentInfo(span) attrs := []tab.Attribute{tab.StringAttribute("amqp.message.id", m.ID)} if m.SessionID != nil { attrs = append(attrs, tab.StringAttribute("amqp.session.id", *m.SessionID)) } if m.GroupSequence != nil { attrs = append(attrs, tab.Int64Attribute("amqp.sequence_number", int64(*m.GroupSequence))) } span.AddAttributes(attrs...) return ctx, span } func (em *entityManager) startSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := tab.StartSpan(ctx, operationName) applyComponentInfo(span) span.AddAttributes(tab.StringAttribute("span.kind", "client")) return ctx, span } func applyRequestInfo(span tab.Spanner, req *http.Request) { span.AddAttributes( tab.StringAttribute("http.url", req.URL.String()), tab.StringAttribute("http.method", req.Method), ) } func applyResponseInfo(span tab.Spanner, res *http.Response)
func (e *entity) startSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := tab.StartSpan(ctx, operationName) applyComponentInfo(span) span.AddAttributes(tab.StringAttribute("message_bus.destination", e.ManagementPath())) return ctx, span } func (si sessionIdentifiable) startSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := tab.StartSpan(ctx, operationName) applyComponentInfo(span) return ctx, span } func (s *Sender) startProducerSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := tab.StartSpan(ctx, operationName) applyComponentInfo(span) span.AddAttributes( tab.StringAttribute("span.kind", "producer"), tab.StringAttribute("message_bus.destination", s.getFullIdentifier()), ) return ctx, span } func (r *Receiver) startConsumerSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := startConsumerSpanFromContext(ctx, operationName) span.AddAttributes(tab.StringAttribute("message_bus.destination", r.entityPath)) return ctx, span } func (r *rpcClient) startSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := startConsumerSpanFromContext(ctx, operationName) span.AddAttributes(tab.StringAttribute("message_bus.destination", r.ec.ManagementPath())) return ctx, span } func (r *rpcClient) startProducerSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := tab.StartSpan(ctx, operationName) applyComponentInfo(span) span.AddAttributes( tab.StringAttribute("span.kind", "producer"), tab.StringAttribute("message_bus.destination", r.ec.ManagementPath()), ) return ctx, span } func startConsumerSpanFromContext(ctx context.Context, operationName string) (context.Context, tab.Spanner) { ctx, span := tab.StartSpan(ctx, operationName) applyComponentInfo(span) span.AddAttributes(tab.StringAttribute("span.kind", "consumer")) return ctx, span } func applyComponentInfo(span tab.Spanner) { span.AddAttributes( tab.StringAttribute("component", "github.com/Azure/azure-service-bus-go"), tab.StringAttribute("version", Version), ) applyNetworkInfo(span) } func applyNetworkInfo(span tab.Spanner) { hostname, err := os.Hostname() if err == nil { span.AddAttributes( tab.StringAttribute("peer.hostname", hostname), ) } }
{ if res != nil { span.AddAttributes(tab.Int64Attribute("http.status_code", int64(res.StatusCode))) } }
test_completion.py
# Copyright 2017-2020 Palantir Technologies, Inc. # Copyright 2021- Python Language Server Contributors. import math import os import sys from pathlib import Path from typing import NamedTuple, Dict import pytest from pylsp import uris, lsp from pylsp.workspace import Document from pylsp.plugins.jedi_completion import pylsp_completions as pylsp_jedi_completions from pylsp.plugins.jedi_completion import pylsp_completion_item_resolve as pylsp_jedi_completion_item_resolve from pylsp.plugins.rope_completion import pylsp_completions as pylsp_rope_completions from pylsp._utils import JEDI_VERSION PY2 = sys.version[0] == '2' LINUX = sys.platform.startswith('linux') CI = os.environ.get('CI') LOCATION = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__)) ) DOC_URI = uris.from_fs_path(__file__) DOC = """import os print os.path.isabs("/tmp") def hello(): pass def _a_hello(): pass class Hello(): @property def world(self): return None def everyone(self, a, b, c=None, d=2): pass print Hello().world print Hello().every def documented_hello(): \"\"\"Sends a polite greeting\"\"\" pass """ def test_rope_import_completion(config, workspace): com_position = {'line': 0, 'character': 7} doc = Document(DOC_URI, workspace, DOC) items = pylsp_rope_completions(config, workspace, doc, com_position) assert items is None class TypeCase(NamedTuple): document: str position: dict label: str expected: lsp.CompletionItemKind TYPE_CASES: Dict[str, TypeCase] = { 'variable': TypeCase( document='test = 1\ntes', position={'line': 1, 'character': 3}, label='test', expected=lsp.CompletionItemKind.Variable ), 'function': TypeCase( document='def test():\n pass\ntes', position={'line': 2, 'character': 3}, label='test()', expected=lsp.CompletionItemKind.Function ), 'keyword': TypeCase( document='fro', position={'line': 0, 'character': 3}, label='from', expected=lsp.CompletionItemKind.Keyword ), 'file': TypeCase( document='"' + __file__[:-2].replace('"', '\\"') + '"', position={'line': 0, 'character': len(__file__) - 2}, label=Path(__file__).name + '"', expected=lsp.CompletionItemKind.File ), 'module': TypeCase( document='import statis', position={'line': 0, 'character': 13}, label='statistics', expected=lsp.CompletionItemKind.Module ), 'class': TypeCase( document='KeyErr', position={'line': 0, 'character': 6}, label='KeyError', expected=lsp.CompletionItemKind.Class ), 'property': TypeCase( document=( 'class A:\n' ' @property\n' ' def test(self):\n' ' pass\n' 'A().tes' ), position={'line': 4, 'character': 5}, label='test', expected=lsp.CompletionItemKind.Property ) } @pytest.mark.parametrize('case', list(TYPE_CASES.values()), ids=list(TYPE_CASES.keys())) def test_jedi_completion_type(case, config, workspace): # property support was introduced in 0.18 if case.expected == lsp.CompletionItemKind.Property and JEDI_VERSION.startswith('0.17'): return doc = Document(DOC_URI, workspace, case.document) items = pylsp_jedi_completions(config, doc, case.position) items = {i['label']: i for i in items} assert items[case.label]['kind'] == case.expected def test_jedi_completion(config, workspace): # Over 'i' in os.path.isabs(...) com_position = {'line': 1, 'character': 15} doc = Document(DOC_URI, workspace, DOC) items = pylsp_jedi_completions(config, doc, com_position) assert items labels = [i['label'] for i in items] assert 'isfile(path)' in labels # Test we don't throw with big character pylsp_jedi_completions(config, doc, {'line': 1, 'character': 1000}) def test_jedi_completion_item_resolve(config, workspace): # Over the blank line com_position = {'line': 8, 'character': 0} doc = Document(DOC_URI, workspace, DOC) config.update({'plugins': {'jedi_completion': {'resolve_at_most': math.inf}}}) completions = pylsp_jedi_completions(config, doc, com_position) items = {c['label']: c for c in completions} documented_hello_item = items['documented_hello()'] assert 'documentation' not in documented_hello_item assert 'detail' not in documented_hello_item resolved_documented_hello = pylsp_jedi_completion_item_resolve( completion_item=documented_hello_item, document=doc ) assert 'Sends a polite greeting' in resolved_documented_hello['documentation'] def test_jedi_completion_with_fuzzy_enabled(config, workspace): # Over 'i' in os.path.isabs(...) config.update({'plugins': {'jedi_completion': {'fuzzy': True}}}) com_position = {'line': 1, 'character': 15} doc = Document(DOC_URI, workspace, DOC) items = pylsp_jedi_completions(config, doc, com_position) assert items expected = 'commonprefix(m)' if JEDI_VERSION == '0.18.0': expected = 'commonprefix(list)' assert items[0]['label'] == expected # Test we don't throw with big character pylsp_jedi_completions(config, doc, {'line': 1, 'character': 1000}) def test_jedi_completion_resolve_at_most(config, workspace): # Over 'i' in os.path.isabs(...) com_position = {'line': 1, 'character': 15} doc = Document(DOC_URI, workspace, DOC) # Do not resolve any labels config.update({'plugins': {'jedi_completion': {'resolve_at_most': 0}}}) items = pylsp_jedi_completions(config, doc, com_position) labels = {i['label'] for i in items} assert 'isabs' in labels # Resolve all items config.update({'plugins': {'jedi_completion': {'resolve_at_most': math.inf}}}) items = pylsp_jedi_completions(config, doc, com_position) labels = {i['label'] for i in items} assert 'isfile(path)' in labels def test_rope_completion(config, workspace): # Over 'i' in os.path.isabs(...) com_position = {'line': 1, 'character': 15} workspace.put_document(DOC_URI, source=DOC) doc = workspace.get_document(DOC_URI) items = pylsp_rope_completions(config, workspace, doc, com_position) assert items assert items[0]['label'] == 'isabs' def test_jedi_completion_ordering(config, workspace): # Over the blank line com_position = {'line': 8, 'character': 0} doc = Document(DOC_URI, workspace, DOC) config.update({'plugins': {'jedi_completion': {'resolve_at_most': math.inf}}}) completions = pylsp_jedi_completions(config, doc, com_position) items = {c['label']: c['sortText'] for c in completions} # And that 'hidden' functions come after unhidden ones assert items['hello()'] < items['_a_hello()'] def test_jedi_property_completion(config, workspace): # Over the 'w' in 'print Hello().world' com_position = {'line': 18, 'character': 15} doc = Document(DOC_URI, workspace, DOC) completions = pylsp_jedi_completions(config, doc, com_position) items = {c['label']: c['sortText'] for c in completions} # Ensure we can complete the 'world' property assert 'world' in list(items.keys())[0] def test_jedi_method_completion(config, workspace): # Over the 'y' in 'print Hello().every' com_position = {'line': 20, 'character': 19} doc = Document(DOC_URI, workspace, DOC) config.capabilities['textDocument'] = {'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completion': {'include_params': True}}}) completions = pylsp_jedi_completions(config, doc, com_position) everyone_method = [completion for completion in completions if completion['label'] == 'everyone(a, b, c, d)'][0] # Ensure we only generate snippets for positional args assert everyone_method['insertTextFormat'] == lsp.InsertTextFormat.Snippet assert everyone_method['insertText'] == 'everyone(${1:a}, ${2:b})$0' # Disable param snippets config.update({'plugins': {'jedi_completion': {'include_params': False}}}) completions = pylsp_jedi_completions(config, doc, com_position) everyone_method = [completion for completion in completions if completion['label'] == 'everyone(a, b, c, d)'][0] assert 'insertTextFormat' not in everyone_method assert everyone_method['insertText'] == 'everyone' @pytest.mark.skipif(PY2 or (sys.platform.startswith('linux') and os.environ.get('CI') is not None), reason="Test in Python 3 and not on CIs on Linux because wheels don't work on them.") def test_pyqt_completion(config, workspace): # Over 'QA' in 'from PyQt5.QtWidgets import QApplication' doc_pyqt = "from PyQt5.QtWidgets import QA" com_position = {'line': 0, 'character': len(doc_pyqt)} doc = Document(DOC_URI, workspace, doc_pyqt) completions = pylsp_jedi_completions(config, doc, com_position) assert completions is not None def test_numpy_completions(config, workspace): doc_numpy = "import numpy as np; np." com_position = {'line': 0, 'character': len(doc_numpy)} doc = Document(DOC_URI, workspace, doc_numpy) items = pylsp_jedi_completions(config, doc, com_position) assert items assert any('array' in i['label'] for i in items) def test_pandas_completions(config, workspace): doc_pandas = "import pandas as pd; pd." com_position = {'line': 0, 'character': len(doc_pandas)} doc = Document(DOC_URI, workspace, doc_pandas) items = pylsp_jedi_completions(config, doc, com_position) assert items assert any('DataFrame' in i['label'] for i in items) def test_matplotlib_completions(config, workspace): doc_mpl = "import matplotlib.pyplot as plt; plt." com_position = {'line': 0, 'character': len(doc_mpl)} doc = Document(DOC_URI, workspace, doc_mpl) items = pylsp_jedi_completions(config, doc, com_position) assert items assert any('plot' in i['label'] for i in items) def test_snippets_completion(config, workspace):
def test_snippets_completion_at_most(config, workspace): doc_snippets = 'from collections import defaultdict \na=defaultdict' doc = Document(DOC_URI, workspace, doc_snippets) config.capabilities['textDocument'] = { 'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completion': {'include_params': True}}}) config.update({'plugins': {'jedi_completion': {'resolve_at_most': 0}}}) com_position = {'line': 1, 'character': len(doc_snippets)} completions = pylsp_jedi_completions(config, doc, com_position) assert completions[0]['insertText'] == 'defaultdict' assert not completions[0].get('insertTextFormat', None) def test_completion_with_class_objects(config, workspace): doc_text = 'class FOOBAR(Object): pass\nFOOB' com_position = {'line': 1, 'character': 4} doc = Document(DOC_URI, workspace, doc_text) config.capabilities['textDocument'] = { 'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completion': { 'include_params': True, 'include_class_objects': True, }}}) completions = pylsp_jedi_completions(config, doc, com_position) assert len(completions) == 2 assert completions[0]['label'] == 'FOOBAR' assert completions[0]['kind'] == lsp.CompletionItemKind.Class assert completions[1]['label'] == 'FOOBAR object' assert completions[1]['kind'] == lsp.CompletionItemKind.TypeParameter def test_snippet_parsing(config, workspace): doc = 'divmod' completion_position = {'line': 0, 'character': 6} doc = Document(DOC_URI, workspace, doc) config.capabilities['textDocument'] = { 'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completion': {'include_params': True}}}) completions = pylsp_jedi_completions(config, doc, completion_position) out = 'divmod(${1:x}, ${2:y})$0' if JEDI_VERSION == '0.18.0': out = 'divmod(${1:a}, ${2:b})$0' assert completions[0]['insertText'] == out def test_multiline_import_snippets(config, workspace): document = 'from datetime import(\n date,\n datetime)\na=date' doc = Document(DOC_URI, workspace, document) config.capabilities['textDocument'] = { 'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completion': {'include_params': True}}}) position = {'line': 1, 'character': 5} completions = pylsp_jedi_completions(config, doc, position) assert completions[0]['insertText'] == 'date' position = {'line': 2, 'character': 9} completions = pylsp_jedi_completions(config, doc, position) assert completions[0]['insertText'] == 'datetime' def test_multiline_snippets(config, workspace): document = 'from datetime import\\\n date,\\\n datetime \na=date' doc = Document(DOC_URI, workspace, document) config.capabilities['textDocument'] = { 'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completion': {'include_params': True}}}) position = {'line': 1, 'character': 5} completions = pylsp_jedi_completions(config, doc, position) assert completions[0]['insertText'] == 'date' position = {'line': 2, 'character': 9} completions = pylsp_jedi_completions(config, doc, position) assert completions[0]['insertText'] == 'datetime' def test_multistatement_snippet(config, workspace): config.capabilities['textDocument'] = { 'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completion': {'include_params': True}}}) document = 'a = 1; from datetime import date' doc = Document(DOC_URI, workspace, document) position = {'line': 0, 'character': len(document)} completions = pylsp_jedi_completions(config, doc, position) assert completions[0]['insertText'] == 'date' document = 'from math import fmod; a = fmod' doc = Document(DOC_URI, workspace, document) position = {'line': 0, 'character': len(document)} completions = pylsp_jedi_completions(config, doc, position) assert completions[0]['insertText'] == 'fmod(${1:x}, ${2:y})$0' def test_jedi_completion_extra_paths(tmpdir, workspace): # Create a tempfile with some content and pass to extra_paths temp_doc_content = ''' def spam(): pass ''' p = tmpdir.mkdir("extra_path") extra_paths = [str(p)] p = p.join("foo.py") p.write(temp_doc_content) # Content of doc to test completion doc_content = """import foo foo.s""" doc = Document(DOC_URI, workspace, doc_content) # After 'foo.s' without extra paths com_position = {'line': 1, 'character': 5} completions = pylsp_jedi_completions(doc._config, doc, com_position) assert completions is None # Update config extra paths settings = {'pylsp': {'plugins': {'jedi': {'extra_paths': extra_paths}}}} doc.update_config(settings) # After 'foo.s' with extra paths com_position = {'line': 1, 'character': 5} completions = pylsp_jedi_completions(doc._config, doc, com_position) assert completions[0]['label'] == 'spam()' @pytest.mark.skipif(PY2 or not LINUX or not CI, reason="tested on linux and python 3 only") def test_jedi_completion_environment(workspace): # Content of doc to test completion doc_content = '''import logh ''' doc = Document(DOC_URI, workspace, doc_content) # After 'import logh' with default environment com_position = {'line': 0, 'character': 11} assert os.path.isdir('/tmp/pyenv/') settings = {'pylsp': {'plugins': {'jedi': {'environment': None}}}} doc.update_config(settings) completions = pylsp_jedi_completions(doc._config, doc, com_position) assert completions is None # Update config extra environment env_path = '/tmp/pyenv/bin/python' settings = {'pylsp': {'plugins': {'jedi': {'environment': env_path}}}} doc.update_config(settings) # After 'import logh' with new environment completions = pylsp_jedi_completions(doc._config, doc, com_position) assert completions[0]['label'] == 'loghub' resolved = pylsp_jedi_completion_item_resolve(completions[0], doc) assert 'changelog generator' in resolved['documentation'].lower() def test_document_path_completions(tmpdir, workspace_other_root_path): # Create a dummy module out of the workspace's root_path and try to get # completions for it in another file placed next to it. module_content = ''' def foo(): pass ''' p = tmpdir.join("mymodule.py") p.write(module_content) # Content of doc to test completion doc_content = """import mymodule mymodule.f""" doc_path = str(tmpdir) + os.path.sep + 'myfile.py' doc_uri = uris.from_fs_path(doc_path) doc = Document(doc_uri, workspace_other_root_path, doc_content) com_position = {'line': 1, 'character': 10} completions = pylsp_jedi_completions(doc._config, doc, com_position) assert completions[0]['label'] == 'foo()'
doc_snippets = 'from collections import defaultdict \na=defaultdict' com_position = {'line': 0, 'character': 35} doc = Document(DOC_URI, workspace, doc_snippets) config.capabilities['textDocument'] = { 'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completion': {'include_params': True}}}) completions = pylsp_jedi_completions(config, doc, com_position) assert completions[0]['insertText'] == 'defaultdict' com_position = {'line': 1, 'character': len(doc_snippets)} completions = pylsp_jedi_completions(config, doc, com_position) assert completions[0]['insertText'] == 'defaultdict($0)' assert completions[0]['insertTextFormat'] == lsp.InsertTextFormat.Snippet
app.po.ts
import { browser, by, element } from 'protractor'; export class
{ navigateTo(): Promise<unknown> { return browser.get(browser.baseUrl) as Promise<unknown>; } getTitleText(): Promise<string> { return element( by.css('app-root .content span'), ).getText() as Promise<string>; } }
AppPage
appsender_server.go
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. package appsender import ( "context" "github.com/ava-labs/avalanchego/api/proto/appsenderproto" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" "google.golang.org/protobuf/types/known/emptypb" ) var _ appsenderproto.AppSenderServer = &Server{} type Server struct { appsenderproto.UnimplementedAppSenderServer appSender common.AppSender } // NewServer returns a messenger connected to a remote channel func
(appSender common.AppSender) *Server { return &Server{appSender: appSender} } func (s *Server) SendAppRequest(_ context.Context, req *appsenderproto.SendAppRequestMsg) (*emptypb.Empty, error) { nodeIDs := ids.NewShortSet(len(req.NodeIds)) for _, nodeIDBytes := range req.NodeIds { nodeID, err := ids.ToShortID(nodeIDBytes) if err != nil { return nil, err } nodeIDs.Add(nodeID) } err := s.appSender.SendAppRequest(nodeIDs, req.RequestId, req.Request) return &emptypb.Empty{}, err } func (s *Server) SendAppResponse(_ context.Context, req *appsenderproto.SendAppResponseMsg) (*emptypb.Empty, error) { nodeID, err := ids.ToShortID(req.NodeId) if err != nil { return nil, err } err = s.appSender.SendAppResponse(nodeID, req.RequestId, req.Response) return &emptypb.Empty{}, err } func (s *Server) SendAppGossip(_ context.Context, req *appsenderproto.SendAppGossipMsg) (*emptypb.Empty, error) { err := s.appSender.SendAppGossip(req.Msg) return &emptypb.Empty{}, err } func (s *Server) SendAppGossipSpecific(_ context.Context, req *appsenderproto.SendAppGossipSpecificMsg) (*emptypb.Empty, error) { nodeIDs := ids.NewShortSet(len(req.NodeIds)) for _, nodeIDBytes := range req.NodeIds { nodeID, err := ids.ToShortID(nodeIDBytes) if err != nil { return nil, err } nodeIDs.Add(nodeID) } err := s.appSender.SendAppGossipSpecific(nodeIDs, req.Msg) return &emptypb.Empty{}, err }
NewServer
source_worker_thread.rs
// This file is part of https://github.com/SpringQL/SpringQL which is licensed under MIT OR Apache-2.0. See file LICENSE-MIT or LICENSE-APACHE for full license details. use std::sync::Arc; use crate::stream_engine::autonomous_executor::{ event_queue::{ event::{BlockingEventTag, EventTag, NonBlockingEventTag}, non_blocking_event_queue::NonBlockingEventQueue, }, memory_state_machine::MemoryStateTransition, performance_metrics::{ metrics_update_command::metrics_update_by_task_execution::MetricsUpdateByTaskExecutionOrPurge, performance_metrics_summary::PerformanceMetricsSummary, PerformanceMetrics, }, pipeline_derivatives::PipelineDerivatives, task_executor::{ scheduler::source_scheduler::SourceScheduler, task_worker_thread_handler::{ TaskWorkerLoopState, TaskWorkerThreadArg, TaskWorkerThreadHandler, }, }, worker::{worker_handle::WorkerSetupCoordinator, worker_thread::WorkerThread}, }; /// Runs a worker thread. #[derive(Debug)] pub(super) struct SourceWorkerThread; impl WorkerThread for SourceWorkerThread { const THREAD_NAME: &'static str = "SourceWorker"; type ThreadArg = TaskWorkerThreadArg; type LoopState = TaskWorkerLoopState<SourceScheduler>; fn setup_ready(worker_setup_coordinator: Arc<WorkerSetupCoordinator>) { worker_setup_coordinator.ready_source_worker() } fn event_subscription() -> Vec<EventTag> { vec![ EventTag::Blocking(BlockingEventTag::UpdatePipeline), EventTag::NonBlocking(NonBlockingEventTag::ReplacePerformanceMetrics), ] } fn main_loop_cycle( current_state: Self::LoopState, thread_arg: &Self::ThreadArg, event_queue: &NonBlockingEventQueue, ) -> Self::LoopState { TaskWorkerThreadHandler::main_loop_cycle::<SourceScheduler>( current_state, thread_arg, event_queue, ) } fn ev_update_pipeline( current_state: Self::LoopState, pipeline_derivatives: Arc<PipelineDerivatives>, thread_arg: &Self::ThreadArg, _event_queue: Arc<NonBlockingEventQueue>, ) -> Self::LoopState { log::debug!( "[SourceWorker#{}] got UpdatePipeline event", thread_arg.worker_id ); let mut state = current_state; state.pipeline_derivatives = Some(pipeline_derivatives); state } fn ev_replace_performance_metrics( current_state: Self::LoopState, metrics: Arc<PerformanceMetrics>, thread_arg: &Self::ThreadArg, _event_queue: Arc<NonBlockingEventQueue>, ) -> Self::LoopState { log::debug!( "[SourceWorker#{}] got ReplacePerformanceMetrics event", thread_arg.worker_id ); let mut state = current_state; state.metrics = Some(metrics); state } fn ev_transit_memory_state( _current_state: Self::LoopState, _memory_state_transition: Arc<MemoryStateTransition>, _thread_arg: &Self::ThreadArg, _event_queue: Arc<NonBlockingEventQueue>, ) -> Self::LoopState { unreachable!(); } fn ev_incremental_update_metrics( _current_state: Self::LoopState, _metrics: Arc<MetricsUpdateByTaskExecutionOrPurge>, _thread_arg: &Self::ThreadArg, _event_queue: Arc<NonBlockingEventQueue>, ) -> Self::LoopState { unreachable!() } fn ev_report_metrics_summary( _current_state: Self::LoopState, _metrics_summary: Arc<PerformanceMetricsSummary>, _thread_arg: &Self::ThreadArg, _event_queue: Arc<NonBlockingEventQueue>, ) -> Self::LoopState
}
{ unreachable!() }
InAppBrowserViewController.d.ts
import { WebAuthOptions } from './../auth0-common'; export declare class
extends UIViewController { private navigationBar; private webView; private _userContentController; private url; private options; private redirectUri; private navigationDelegate; private _hud; viewDidLoad(): void; loadUrl(url: NSURL): void; setOptions(options: WebAuthOptions): void; private includeInitJavascript; setDefaults(remember: boolean, dni?: string, usercode?: string, name?: string): void; cancel(sender: UIButton): void; authCancel(): void; dispose(): void; authOk(url: NSURL): void; static ObjCExposedMethods: { "cancel": { returns: interop.Type<void>; params: (typeof UIButton)[]; }; }; _onLoadFinished(url: string, error?: string): void; getRememberScript(): string; getRememberScriptDelimiter(): string; setRedirectUri(uri: string): void; getRedirectUri(): string; getCallbackCancelUri(): string; }
InAppBrowserViewController
generate-contributions.ts
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ import { JSONSchema6 } from 'json-schema'; import { allCommands, allDebugTypes, AutoAttachMode, Commands, Configuration, Contributions, DebugType, IConfigurationTypes, } from '../common/contributionUtils'; import { knownToolToken } from '../common/knownTools'; import { sortKeys, walkObject } from '../common/objUtils'; import { AnyLaunchConfiguration, baseDefaults, breakpointLanguages, chromeAttachConfigDefaults, chromeLaunchConfigDefaults, edgeAttachConfigDefaults, edgeLaunchConfigDefaults, extensionHostConfigDefaults, IBaseConfiguration, IChromeAttachConfiguration, IChromeLaunchConfiguration, IChromiumBaseConfiguration, IEdgeAttachConfiguration, IEdgeLaunchConfiguration, IExtensionHostLaunchConfiguration, IMandatedConfiguration, INodeAttachConfiguration, INodeBaseConfiguration, INodeLaunchConfiguration, ITerminalLaunchConfiguration, nodeAttachConfigDefaults, nodeLaunchConfigDefaults, OutputSource, ResolvingConfiguration, terminalBaseDefaults, } from '../configuration'; import strings from './strings'; const appInsightsKey = 'AIF-d9b70cd4-b9f9-4d70-929b-a071c400b217'; type OmittedKeysFromAttributes = | keyof IMandatedConfiguration | 'rootPath' | '__breakOnConditionalError' | '__workspaceFolder' | '__workspaceCachePath' | '__autoExpandGetters' | '__remoteFilePrefix' | '__sessionId'; type DescribedAttribute<T> = JSONSchema6 & Described & { default: T; enum?: Array<T>; enumDescriptions?: MappedReferenceString[]; }; type ConfigurationAttributes<T> = { [K in keyof Omit<T, OmittedKeysFromAttributes>]: DescribedAttribute<T[K]>; }; type Described = | { description: MappedReferenceString } | { enumDescriptions: MappedReferenceString[] } | { markdownDescription: MappedReferenceString }; type Menus = { [menuId: string]: { command: Commands; title?: MappedReferenceString; when?: string; group?: 'navigation' | 'inline'; }[]; }; const forSomeDebugTypes = ( types: Iterable<string>, contextKey: string, andExpr: string | undefined, ) => [...types].map(d => `${contextKey} == ${d}` + (andExpr ? ` && ${andExpr}` : '')).join(' || '); const forAnyDebugType = (contextKey: string, andExpr?: string) => forSomeDebugTypes(allDebugTypes, contextKey, andExpr); const forBrowserDebugType = (contextKey: string, andExpr?: string) => forSomeDebugTypes([DebugType.Chrome, DebugType.Edge], contextKey, andExpr); /** * Opaque type for a string passed through refString, ensuring all templates * are defined as NLS strings. */ type MappedReferenceString = { __opaque: true } & string; // eslint-disable-next-line const refString = (str: keyof typeof strings): MappedReferenceString => `%${str}%` as any; /** * Type definition for a debugger section. VSCode doesn't publish these types, * and we want to bind them more tightly to the types from the configuration anyway. */ interface IDebugger<T extends AnyLaunchConfiguration> { type: T['type']; request: T['request']; label: MappedReferenceString; program?: string; runtime?: string; languages?: string[]; variables?: { [key: string]: Commands }; required?: (keyof T)[]; configurationSnippets: ({ label: MappedReferenceString; body: ResolvingConfiguration<T & { preLaunchTask?: string }>; } & Described)[]; configurationAttributes: ConfigurationAttributes<T>; defaults: T; } const baseConfigurationAttributes: ConfigurationAttributes<IBaseConfiguration> = { resolveSourceMapLocations: { type: ['array', 'null'], description: refString('node.resolveSourceMapLocations.description'), default: null, items: { type: 'string', }, }, outFiles: { type: ['array'], description: refString('outFiles.description'), default: baseDefaults.outFiles, items: { type: 'string', }, }, pauseForSourceMap: { type: 'boolean', markdownDescription: refString('node.pauseForSourceMap.description'), default: false, }, showAsyncStacks: { description: refString('node.showAsyncStacks.description'), default: true, oneOf: [ { type: 'boolean', }, { type: 'object', required: ['onAttach'], properties: { onAttach: { type: 'number', default: 32, }, }, }, { type: 'object', required: ['onceBreakpointResolved'], properties: { onceBreakpointResolved: { type: 'number', default: 32, }, }, }, ], }, skipFiles: { type: 'array', description: refString('browser.skipFiles.description'), default: ['<node_internals>/**'], }, smartStep: { type: 'boolean', description: refString('smartStep.description'), default: true, }, sourceMaps: { type: 'boolean', description: refString('browser.sourceMaps.description'), default: true, }, sourceMapPathOverrides: { type: 'object', description: refString('node.sourceMapPathOverrides.description'), default: { 'webpack://?:*/*': '${workspaceFolder}/*', 'webpack:///./~/*': '${workspaceFolder}/node_modules/*', 'meteor://💻app/*': '${workspaceFolder}/*', }, }, timeout: { type: 'number', description: refString('node.timeout.description'), default: 10000, }, timeouts: { type: 'object', description: refString('timeouts.generalDescription'), default: {}, properties: { sourceMapMinPause: { type: 'number', description: refString('timeouts.sourceMaps.sourceMapMinPause.description'), default: 1000, }, sourceMapCumulativePause: { type: 'number', description: refString('timeouts.sourceMaps.sourceMapCumulativePause.description'), default: 1000, },
additionalProperties: false, markdownDescription: refString('timeouts.generalDescription.markdown'), }, trace: { description: refString('trace.description'), default: true, oneOf: [ { type: 'boolean', description: refString('trace.boolean.description'), }, { type: 'object', additionalProperties: false, properties: { console: { type: 'boolean', description: refString('trace.stdio.description'), }, stdio: { type: 'boolean', description: refString('trace.console.description'), }, level: { enum: ['fatal', 'error', 'warn', 'info', 'verbose'], description: refString('trace.level.description'), }, logFile: { type: ['string', 'null'], description: refString('trace.logFile.description'), }, tags: { type: 'array', description: refString('trace.tags.description'), items: { enum: ['cdp', 'dap', 'runtime'], }, }, }, }, ], }, outputCapture: { enum: [OutputSource.Console, OutputSource.Stdio], markdownDescription: refString('node.launch.outputCapture.description'), default: OutputSource.Console, }, enableContentValidation: { default: true, type: 'boolean', description: refString('enableContentValidation.description'), }, customDescriptionGenerator: { type: 'string', default: undefined, description: refString('customDescriptionGenerator.description'), }, cascadeTerminateToConfigurations: { type: 'array', items: { type: 'string', uniqueItems: true, }, default: [], description: refString('base.cascadeTerminateToConfigurations.label'), }, }; /** * Shared Node.js configuration. */ const nodeBaseConfigurationAttributes: ConfigurationAttributes<INodeBaseConfiguration> = { ...baseConfigurationAttributes, resolveSourceMapLocations: { ...baseConfigurationAttributes.resolveSourceMapLocations, default: ['${workspaceFolder}/**', '!**/node_modules/**'], }, cwd: { type: 'string', description: refString('node.launch.cwd.description'), default: '${workspaceFolder}', }, localRoot: { type: ['string', 'null'], description: refString('node.localRoot.description'), default: null, }, remoteRoot: { type: ['string', 'null'], description: refString('node.remoteRoot.description'), default: null, }, autoAttachChildProcesses: { type: 'boolean', description: refString('node.launch.autoAttachChildProcesses.description'), default: true, }, env: { type: 'object', additionalProperties: { type: ['string', 'null'], }, markdownDescription: refString('node.launch.env.description'), default: {}, }, envFile: { type: 'string', description: refString('node.launch.envFile.description'), default: '${workspaceFolder}/.env', }, runtimeSourcemapPausePatterns: { type: 'array', items: { type: 'string', }, markdownDescription: refString('node.launch.runtimeSourcemapPausePatterns'), default: [], }, nodeVersionHint: { type: 'number', minimum: 8, description: refString('node.versionHint.description'), default: 12, }, }; /** * Node attach configuration. */ const nodeAttachConfig: IDebugger<INodeAttachConfiguration> = { type: DebugType.Node, request: 'attach', label: refString('node.label'), variables: { PickProcess: Commands.PickProcess, }, configurationSnippets: [ { label: refString('node.snippet.attach.label'), description: refString('node.snippet.attach.description'), body: { type: DebugType.Node, request: 'attach', name: '${1:Attach}', port: 9229, skipFiles: ['<node_internals>/**'], }, }, { label: refString('node.snippet.remoteattach.label'), description: refString('node.snippet.remoteattach.description'), body: { type: DebugType.Node, request: 'attach', name: '${1:Attach to Remote}', address: '${2:TCP/IP address of process to be debugged}', port: 9229, localRoot: '^"\\${workspaceFolder}"', remoteRoot: '${3:Absolute path to the remote directory containing the program}', skipFiles: ['<node_internals>/**'], }, }, { label: refString('node.snippet.attachProcess.label'), description: refString('node.snippet.attachProcess.description'), body: { type: DebugType.Node, request: 'attach', name: '${1:Attach by Process ID}', processId: '^"\\${command:PickProcess}"', skipFiles: ['<node_internals>/**'], }, }, ], configurationAttributes: { ...nodeBaseConfigurationAttributes, address: { type: 'string', description: refString('node.address.description'), default: 'localhost', }, port: { type: 'number', description: refString('node.port.description'), default: 9229, }, websocketAddress: { type: 'string', description: refString('node.websocket.address.description'), default: undefined, }, restart: { description: refString('node.attach.restart.description'), default: true, oneOf: [ { type: 'boolean', }, { type: 'object', properties: { delay: { type: 'number', minimum: 0, default: 1000 }, maxAttempts: { type: 'number', minimum: 0, default: 10 }, }, }, ], }, processId: { type: 'string', description: refString('node.attach.processId.description'), default: '${command:PickProcess}', }, attachExistingChildren: { type: 'boolean', description: refString('node.attach.attachExistingChildren.description'), default: false, }, continueOnAttach: { type: 'boolean', markdownDescription: refString('node.attach.continueOnAttach'), default: true, }, }, defaults: nodeAttachConfigDefaults, }; /** * Node attach configuration. */ const nodeLaunchConfig: IDebugger<INodeLaunchConfiguration> = { type: DebugType.Node, request: 'launch', label: refString('node.label'), variables: { PickProcess: Commands.PickProcess, }, configurationSnippets: [ { label: refString('node.snippet.launch.label'), description: refString('node.snippet.launch.description'), body: { type: DebugType.Node, request: 'launch', name: '${2:Launch Program}', program: '^"\\${workspaceFolder}/${1:app.js}"', skipFiles: ['<node_internals>/**'], }, }, { label: refString('node.snippet.npm.label'), markdownDescription: refString('node.snippet.npm.description'), body: { type: DebugType.Node, request: 'launch', name: '${1:Launch via NPM}', runtimeExecutable: 'npm', runtimeArgs: ['run-script', 'debug'], skipFiles: ['<node_internals>/**'], }, }, { label: refString('node.snippet.nodemon.label'), description: refString('node.snippet.nodemon.description'), body: { type: DebugType.Node, request: 'launch', name: 'nodemon', runtimeExecutable: 'nodemon', program: '^"\\${workspaceFolder}/${1:app.js}"', restart: true, console: 'integratedTerminal', internalConsoleOptions: 'neverOpen', skipFiles: ['<node_internals>/**'], }, }, { label: refString('node.snippet.mocha.label'), description: refString('node.snippet.mocha.description'), body: { type: DebugType.Node, request: 'launch', name: 'Mocha Tests', program: '^"\\${workspaceFolder}/node_modules/mocha/bin/_mocha"', args: ['-u', 'tdd', '--timeout', '999999', '--colors', '^"\\${workspaceFolder}/${1:test}"'], internalConsoleOptions: 'openOnSessionStart', skipFiles: ['<node_internals>/**'], }, }, { label: refString('node.snippet.yo.label'), markdownDescription: refString('node.snippet.yo.description'), body: { type: DebugType.Node, request: 'launch', name: 'Yeoman ${1:generator}', program: '^"\\${workspaceFolder}/node_modules/yo/lib/cli.js"', args: ['${1:generator}'], console: 'integratedTerminal', internalConsoleOptions: 'neverOpen', skipFiles: ['<node_internals>/**'], }, }, { label: refString('node.snippet.gulp.label'), description: refString('node.snippet.gulp.description'), body: { type: DebugType.Node, request: 'launch', name: 'Gulp ${1:task}', program: '^"\\${workspaceFolder}/node_modules/gulp/bin/gulp.js"', args: ['${1:task}'], skipFiles: ['<node_internals>/**'], }, }, { label: refString('node.snippet.electron.label'), description: refString('node.snippet.electron.description'), body: { type: DebugType.Node, request: 'launch', name: 'Electron Main', runtimeExecutable: '^"\\${workspaceFolder}/node_modules/.bin/electron"', program: '^"\\${workspaceFolder}/main.js"', skipFiles: ['<node_internals>/**'], }, }, ], configurationAttributes: { ...nodeBaseConfigurationAttributes, cwd: { type: 'string', description: refString('node.launch.cwd.description'), default: '${workspaceFolder}', }, program: { type: 'string', description: refString('node.launch.program.description'), default: '', }, stopOnEntry: { type: ['boolean', 'string'], description: refString('node.stopOnEntry.description'), default: true, }, console: { type: 'string', enum: ['internalConsole', 'integratedTerminal', 'externalTerminal'], enumDescriptions: [ refString('node.launch.console.internalConsole.description'), refString('node.launch.console.integratedTerminal.description'), refString('node.launch.console.externalTerminal.description'), ], description: refString('node.launch.console.description'), default: 'internalConsole', }, args: { type: 'array', description: refString('node.launch.args.description'), items: { type: 'string', }, default: [], }, restart: { description: refString('node.launch.restart.description'), ...nodeAttachConfig.configurationAttributes.restart, }, runtimeExecutable: { type: ['string', 'null'], markdownDescription: refString('node.launch.runtimeExecutable.description'), default: 'node', }, runtimeVersion: { type: 'string', markdownDescription: refString('node.launch.runtimeVersion.description'), default: 'default', }, runtimeArgs: { type: 'array', description: refString('node.launch.runtimeArgs.description'), items: { type: 'string', }, default: [], }, profileStartup: { type: 'boolean', description: refString('node.profileStartup.description'), default: true, }, attachSimplePort: { type: 'integer', description: refString('node.attachSimplePort.description'), default: 9229, }, }, defaults: nodeLaunchConfigDefaults, }; const nodeTerminalConfiguration: IDebugger<ITerminalLaunchConfiguration> = { type: DebugType.Terminal, request: 'launch', label: refString('debug.terminal.label'), languages: [], configurationSnippets: [ { label: refString('debug.terminal.snippet.label'), description: refString('debug.terminal.snippet.label'), body: { type: DebugType.Terminal, request: 'launch', name: 'Run npm start', command: 'npm start', }, }, ], configurationAttributes: { ...nodeBaseConfigurationAttributes, command: { type: ['string', 'null'], description: refString('debug.terminal.program.description'), default: 'npm start', }, }, defaults: terminalBaseDefaults, }; /** * Shared Chrome configuration. */ const chromiumBaseConfigurationAttributes: ConfigurationAttributes<IChromiumBaseConfiguration> = { ...baseConfigurationAttributes, disableNetworkCache: { type: 'boolean', description: refString('browser.disableNetworkCache.description'), default: true, }, pathMapping: { type: 'object', description: refString('browser.pathMapping.description'), default: {}, }, webRoot: { type: 'string', description: refString('browser.webRoot.description'), default: '${workspaceFolder}', }, urlFilter: { type: 'string', description: refString('browser.urlFilter.description'), default: '', }, url: { type: 'string', description: refString('browser.url.description'), default: 'http://localhost:8080', }, inspectUri: { type: ['string', 'null'], description: refString('browser.inspectUri.description'), default: null, }, vueComponentPaths: { type: 'array', description: refString('browser.vueComponentPaths'), default: ['${workspaceFolder}/**/*.vue'], }, server: { oneOf: [ { type: 'object', description: refString('browser.server.description'), additionalProperties: false, default: { program: 'node my-server.js' }, properties: nodeLaunchConfig.configurationAttributes, }, { type: 'object', description: refString('debug.terminal.label'), additionalProperties: false, default: { program: 'npm start' }, properties: nodeTerminalConfiguration.configurationAttributes, }, ], // eslint-disable-next-line } as any, perScriptSourcemaps: { type: 'string', default: 'auto', enum: ['yes', 'no', 'auto'], description: refString('browser.perScriptSourcemaps.description'), }, }; /** * Shared Chrome attach. */ const chromiumAttachConfigurationAttributes: ConfigurationAttributes<IChromeAttachConfiguration> = { ...chromiumBaseConfigurationAttributes, address: { type: 'string', description: refString('browser.address.description'), default: 'localhost', }, port: { type: 'number', description: refString('browser.attach.port.description'), default: 9229, }, restart: { type: 'boolean', markdownDescription: refString('browser.restart'), default: false, }, targetSelection: { type: 'string', markdownDescription: refString('browser.targetSelection'), enum: ['pick', 'automatic'], default: 'automatic', }, browserAttachLocation: { description: refString('browser.browserAttachLocation.description'), default: null, oneOf: [ { type: 'null', }, { type: 'string', enum: ['ui', 'workspace'], }, ], }, }; const chromeLaunchConfig: IDebugger<IChromeLaunchConfiguration> = { type: DebugType.Chrome, request: 'launch', label: refString('chrome.label'), configurationSnippets: [ { label: refString('chrome.launch.label'), description: refString('chrome.launch.description'), body: { type: DebugType.Chrome, request: 'launch', name: 'Launch Chrome', url: 'http://localhost:8080', webRoot: '^"${2:\\${workspaceFolder\\}}"', }, }, ], configurationAttributes: { ...chromiumBaseConfigurationAttributes, port: { type: 'number', description: refString('browser.launch.port.description'), default: 0, }, file: { type: 'string', description: refString('browser.file.description'), default: '${workspaceFolder}/index.html', }, userDataDir: { type: ['string', 'boolean'], description: refString('browser.userDataDir.description'), default: true, }, includeDefaultArgs: { type: 'boolean', description: refString('browser.includeDefaultArgs.description'), default: true, }, runtimeExecutable: { type: ['string', 'null'], description: refString('browser.runtimeExecutable.description'), default: 'stable', }, runtimeArgs: { type: 'array', description: refString('browser.runtimeArgs.description'), items: { type: 'string', }, default: [], }, env: { type: 'object', description: refString('browser.env.description'), default: {}, }, cwd: { type: 'string', description: refString('browser.cwd.description'), default: null, }, profileStartup: { type: 'boolean', description: refString('browser.profileStartup.description'), default: true, }, cleanUp: { type: 'string', enum: ['wholeBrowser', 'onlyTab'], description: refString('browser.cleanUp.description'), default: 'wholeBrowser', }, browserLaunchLocation: { description: refString('browser.browserLaunchLocation.description'), default: null, oneOf: [ { type: 'null', }, { type: 'string', enum: ['ui', 'workspace'], }, ], }, }, defaults: chromeLaunchConfigDefaults, }; const chromeAttachConfig: IDebugger<IChromeAttachConfiguration> = { type: DebugType.Chrome, request: 'attach', label: refString('chrome.label'), configurationSnippets: [ { label: refString('chrome.attach.label'), description: refString('chrome.attach.description'), body: { type: DebugType.Chrome, request: 'attach', name: 'Attach to Chrome', port: 9222, webRoot: '^"${2:\\${workspaceFolder\\}}"', }, }, ], configurationAttributes: chromiumAttachConfigurationAttributes, defaults: chromeAttachConfigDefaults, }; const extensionHostConfig: IDebugger<IExtensionHostLaunchConfiguration> = { type: DebugType.ExtensionHost, request: 'launch', label: refString('extensionHost.label'), required: ['args'], configurationSnippets: [ { label: refString('extensionHost.snippet.launch.label'), description: refString('extensionHost.snippet.launch.description'), body: { type: DebugType.ExtensionHost, request: 'launch', name: refString('extensionHost.launch.config.name'), args: ['^"--extensionDevelopmentPath=\\${workspaceFolder}"'], outFiles: ['^"\\${workspaceFolder}/out/**/*.js"'], preLaunchTask: 'npm', }, }, ], configurationAttributes: { ...nodeBaseConfigurationAttributes, args: { type: 'array', description: refString('node.launch.args.description'), items: { type: 'string', }, default: ['--extensionDevelopmentPath=${workspaceFolder}'], }, runtimeExecutable: { type: ['string', 'null'], markdownDescription: refString('extensionHost.launch.runtimeExecutable.description'), default: 'node', }, debugWebviews: { markdownDescription: refString('extensionHost.launch.debugWebviews'), default: true, type: ['boolean'], }, debugWebWorkerHost: { markdownDescription: refString('extensionHost.launch.debugWebWorkerHost'), default: true, type: ['boolean'], }, rendererDebugOptions: { markdownDescription: refString('extensionHost.launch.rendererDebugOptions'), type: 'object', default: { webRoot: '${workspaceFolder}', }, properties: chromiumAttachConfigurationAttributes as { [key: string]: JSONSchema6 }, }, }, defaults: extensionHostConfigDefaults, }; const edgeLaunchConfig: IDebugger<IEdgeLaunchConfiguration> = { type: DebugType.Edge, request: 'launch', label: refString('edge.launch.label'), configurationSnippets: [ { label: refString('edge.launch.label'), description: refString('edge.launch.description'), body: { type: DebugType.Edge, request: 'launch', name: 'Launch Edge', url: 'http://localhost:8080', webRoot: '^"${2:\\${workspaceFolder\\}}"', }, }, ], configurationAttributes: { ...chromeLaunchConfig.configurationAttributes, runtimeExecutable: { type: ['string', 'null'], description: refString('browser.runtimeExecutable.edge.description'), default: 'stable', }, useWebView: { type: 'boolean', description: refString('edge.useWebView.description'), default: false, }, address: { type: 'string', description: refString('edge.address.description'), default: 'localhost', }, port: { type: 'number', description: refString('edge.port.description'), default: 9229, }, }, defaults: edgeLaunchConfigDefaults, }; const edgeAttachConfig: IDebugger<IEdgeAttachConfiguration> = { type: DebugType.Edge, request: 'attach', label: refString('edge.label'), configurationSnippets: [ { label: refString('edge.attach.label'), description: refString('edge.attach.description'), body: { type: DebugType.Edge, request: 'attach', name: 'Attach to Edge', port: 9222, webRoot: '^"${2:\\${workspaceFolder\\}}"', }, }, ], configurationAttributes: { ...chromiumAttachConfigurationAttributes, useWebView: { type: 'boolean', description: refString('edge.useWebView.description'), default: false, }, }, defaults: edgeAttachConfigDefaults, }; export const debuggers = [ nodeAttachConfig, nodeLaunchConfig, nodeTerminalConfiguration, extensionHostConfig, chromeLaunchConfig, chromeAttachConfig, edgeLaunchConfig, edgeAttachConfig, ]; function buildDebuggers() { // eslint-disable-next-line const output: any[] = []; for (const d of debuggers) { let entry = output.find(o => o.type === d.type); if (!entry) { // eslint-disable-next-line const { request, configurationAttributes, required, defaults, ...rest } = d; entry = { languages: ['javascript', 'typescript', 'javascriptreact', 'typescriptreact'], ...rest, aiKey: appInsightsKey, configurationAttributes: {}, configurationSnippets: [], }; output.push(entry); } entry.configurationSnippets.push(...d.configurationSnippets); entry.configurationAttributes[d.request] = { required: d.required, properties: d.configurationAttributes, }; } return walkObject(output, sortKeys); } const configurationSchema: ConfigurationAttributes<IConfigurationTypes> = { [Configuration.UsePreviewDebugger]: { type: 'boolean', default: true, description: refString('configuration.usePreview'), }, [Configuration.NpmScriptLens]: { enum: ['top', 'all', 'never'], default: 'top', description: refString('configuration.npmScriptLensLocation'), }, [Configuration.TerminalDebugConfig]: { type: 'object', description: refString('configuration.terminalOptions'), default: {}, properties: nodeTerminalConfiguration.configurationAttributes as { [key: string]: JSONSchema6 }, }, [Configuration.SuggestPrettyPrinting]: { type: 'boolean', description: refString('configuration.suggestPrettyPrinting'), default: true, }, [Configuration.AutoServerTunnelOpen]: { type: 'boolean', description: refString('configuration.automaticallyTunnelRemoteServer'), default: true, }, [Configuration.DebugByLinkOptions]: { default: 'on', description: refString('configuration.debugByLinkOptions'), oneOf: [ { type: 'string', enum: ['on', 'off', 'always'], }, { type: 'object', properties: { ...chromeLaunchConfig.configurationAttributes, enabled: { type: 'string', enum: ['on', 'off', 'always'], }, } as { [key: string]: JSONSchema6 }, }, ], }, [Configuration.PickAndAttachDebugOptions]: { type: 'object', default: {}, markdownDescription: refString('configuration.pickAndAttachOptions'), properties: nodeAttachConfig.configurationAttributes as { [key: string]: JSONSchema6 }, }, [Configuration.AutoExpandGetters]: { type: 'boolean', default: false, markdownDescription: refString('configuration.autoExpandGetters'), }, [Configuration.AutoAttachMode]: { type: 'string', default: AutoAttachMode.Disabled, enum: [ AutoAttachMode.Always, AutoAttachMode.Smart, AutoAttachMode.OnlyWithFlag, AutoAttachMode.Disabled, ], enumDescriptions: [ refString('configuration.autoAttachMode.always'), refString('configuration.autoAttachMode.smart'), refString('configuration.autoAttachMode.explicit'), refString('configuration.autoAttachMode.disabled'), ], markdownDescription: refString('configuration.autoAttachMode'), }, [Configuration.AutoAttachSmartPatterns]: { type: 'array', items: { type: 'string', }, default: ['!**/{node_modules,npm-global,.yarn,.nvm}/**', `**/${knownToolToken}/**`], markdownDescription: refString('configuration.autoAttachSmartPatterns'), }, [Configuration.BreakOnConditionalError]: { type: 'boolean', default: false, markdownDescription: refString('configuration.breakOnConditionalError'), }, [Configuration.UnmapMissingSources]: { type: 'boolean', default: false, description: refString('configuration.unmapMissingSources'), }, }; const commands: ReadonlyArray<{ command: Commands; title: MappedReferenceString; category?: string; icon?: string; }> = [ { command: Commands.PrettyPrint, title: refString('pretty.print.script'), category: 'Debug', }, { command: Commands.ToggleSkipping, title: refString('toggle.skipping.this.file'), category: 'Debug', }, { command: Commands.AddCustomBreakpoints, title: refString('add.browser.breakpoint'), icon: '$(add)', }, { command: Commands.RemoveCustomBreakpoint, title: refString('remove.browser.breakpoint'), icon: '$(remove)', }, { command: Commands.RemoveAllCustomBreakpoints, title: refString('remove.browser.breakpoint.all'), icon: '$(close-all)', }, { command: Commands.AttachProcess, title: refString('attach.node.process'), category: 'Debug', }, { command: Commands.DebugNpmScript, title: refString('debug.npm.script'), category: 'Debug', }, { command: Commands.CreateDebuggerTerminal, title: refString('debug.terminal.label'), category: 'Debug', }, { command: Commands.StartProfile, title: refString('profile.start'), category: 'Debug', icon: '$(record)', }, { command: Commands.StopProfile, title: refString('profile.stop'), category: 'Debug', icon: 'resources/dark/stop-profiling.svg', }, { command: Commands.RevealPage, title: refString('browser.revealPage'), category: 'Debug', }, { command: Commands.DebugLink, title: refString('debugLink.label'), category: 'Debug', }, { command: Commands.CreateDiagnostics, title: refString('createDiagnostics.label'), category: 'Debug', }, ]; const menus: Menus = { commandPalette: [ { command: Commands.PrettyPrint, title: refString('pretty.print.script'), when: forAnyDebugType('debugType', 'inDebugMode'), }, { command: Commands.StartProfile, title: refString('profile.start'), when: forAnyDebugType('debugType', 'inDebugMode && !jsDebugIsProfiling'), }, { command: Commands.StopProfile, title: refString('profile.stop'), when: forAnyDebugType('debugType', 'inDebugMode && jsDebugIsProfiling'), }, { command: Commands.RevealPage, when: 'false', }, { command: Commands.DebugLink, title: refString('debugLink.label'), }, { command: Commands.CreateDiagnostics, title: refString('createDiagnostics.label'), when: forAnyDebugType('debugType', 'inDebugMode'), }, ], 'debug/callstack/context': [ { command: Commands.RevealPage, group: 'navigation', when: forBrowserDebugType('debugType', `callStackItemType == 'session'`), }, { command: Commands.ToggleSkipping, group: 'navigation', when: forAnyDebugType('debugType', `callStackItemType == 'session'`), }, { command: Commands.StartProfile, group: 'navigation', when: forAnyDebugType('debugType', `!jsDebugIsProfiling && callStackItemType == 'session'`), }, { command: Commands.StopProfile, group: 'navigation', when: forAnyDebugType('debugType', `jsDebugIsProfiling && callStackItemType == 'session'`), }, { command: Commands.StartProfile, group: 'inline', when: forAnyDebugType('debugType', '!jsDebugIsProfiling'), }, { command: Commands.StopProfile, group: 'inline', when: forAnyDebugType('debugType', 'jsDebugIsProfiling'), }, ], 'debug/toolBar': [ { command: Commands.StopProfile, when: forAnyDebugType('debugType', 'jsDebugIsProfiling'), }, ], 'view/title': [ { command: Commands.AddCustomBreakpoints, when: 'view == jsBrowserBreakpoints', }, { command: Commands.RemoveAllCustomBreakpoints, when: 'view == jsBrowserBreakpoints', }, ], 'view/item/context': [ { command: Commands.RemoveCustomBreakpoint, when: 'view == jsBrowserBreakpoints', group: 'inline', }, { command: Commands.AddCustomBreakpoints, when: 'view == jsBrowserBreakpoints', }, { command: Commands.RemoveCustomBreakpoint, when: 'view == jsBrowserBreakpoints', }, ], }; if (require.main === module) { process.stdout.write( JSON.stringify({ activationEvents: [ ...[...allCommands].map(cmd => `onCommand:${cmd}`), ...debuggers.map(dbg => `onDebugResolve:${dbg.type}`), `onWebviewPanel:${Contributions.DiagnosticsView}`, ], contributes: { menus, breakpoints: breakpointLanguages.map(language => ({ language })), debuggers: buildDebuggers(), commands, configuration: { title: 'JavaScript Debugger', properties: configurationSchema, }, }, }), ); }
},
lib.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The arena, a fast but limited type of allocator. //! //! Arenas are a type of allocator that destroy the objects within, all at //! once, once the arena itself is destroyed. They do not support deallocation //! of individual objects while the arena itself is still alive. The benefit //! of an arena is very fast allocation; just a pointer bump. //! //! This crate implements `TypedArena`, a simple arena that can only hold //! objects of a single type. #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://doc.rust-lang.org/favicon.ico", html_root_url = "https://doc.rust-lang.org/nightly/", test(no_crate_inject, attr(deny(warnings))))] #![feature(alloc)] #![feature(core_intrinsics)] #![feature(dropck_eyepatch)] #![cfg_attr(test, feature(test))] #![allow(deprecated)] extern crate alloc; extern crate rustc_data_structures; use rustc_data_structures::sync::MTLock; use std::cell::{Cell, RefCell}; use std::cmp; use std::intrinsics; use std::marker::{PhantomData, Send}; use std::mem; use std::ptr; use std::slice; use alloc::raw_vec::RawVec; /// An arena that can hold objects of only one type. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. ptr: Cell<*mut T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*mut T>, /// A vector of arena chunks. chunks: RefCell<Vec<TypedArenaChunk<T>>>, /// Marker indicating that dropping the arena causes its owned /// instances of `T` to be dropped. _own: PhantomData<T>, } struct TypedArenaChunk<T> { /// The raw storage for the arena chunk. storage: RawVec<T>, } impl<T> TypedArenaChunk<T> { #[inline] unsafe fn new(capacity: usize) -> TypedArenaChunk<T> { TypedArenaChunk { storage: RawVec::with_capacity(capacity), } } /// Destroys this arena chunk. #[inline] unsafe fn destroy(&mut self, len: usize) { // The branch on needs_drop() is an -O1 performance optimization. // Without the branch, dropping TypedArena<u8> takes linear time. if mem::needs_drop::<T>() { let mut start = self.start(); // Destroy all allocated objects. for _ in 0..len { ptr::drop_in_place(start); start = start.offset(1); } } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *mut T { self.storage.ptr() } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *mut T { unsafe { if mem::size_of::<T>() == 0 { // A pointer as large as possible for zero-sized elements. !0 as *mut T } else { self.start().offset(self.storage.cap() as isize) } } } } const PAGE: usize = 4096; impl<T> TypedArena<T> { /// Creates a new `TypedArena`. #[inline] pub fn new() -> TypedArena<T> { TypedArena { // We set both `ptr` and `end` to 0 so that the first call to // alloc() will trigger a grow(). ptr: Cell::new(0 as *mut T), end: Cell::new(0 as *mut T), chunks: RefCell::new(vec![]), _own: PhantomData, } } /// Allocates an object in the `TypedArena`, returning a reference to it. #[inline] pub fn alloc(&self, object: T) -> &mut T { if self.ptr == self.end { self.grow(1) } unsafe { if mem::size_of::<T>() == 0 { self.ptr .set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1) as *mut T); let ptr = mem::align_of::<T>() as *mut T; // Don't drop the object. This `write` is equivalent to `forget`. ptr::write(ptr, object); &mut *ptr } else { let ptr = self.ptr.get(); // Advance the pointer. self.ptr.set(self.ptr.get().offset(1)); // Write into uninitialized memory. ptr::write(ptr, object); &mut *ptr } } } /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable /// reference to it. Will panic if passed a zero-sized types. /// /// Panics: /// /// - Zero-sized types /// - Zero-length slices #[inline] pub fn alloc_slice(&self, slice: &[T]) -> &mut [T] where T: Copy, { assert!(mem::size_of::<T>() != 0); assert!(slice.len() != 0); let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize; let at_least_bytes = slice.len() * mem::size_of::<T>(); if available_capacity_bytes < at_least_bytes { self.grow(slice.len()); } unsafe { let start_ptr = self.ptr.get(); let arena_slice = slice::from_raw_parts_mut(start_ptr, slice.len()); self.ptr.set(start_ptr.offset(arena_slice.len() as isize)); arena_slice.copy_from_slice(slice); arena_slice } } /// Grows the arena. #[inline(never)] #[cold] fn grow(&self, n: usize) { unsafe { let mut chunks = self.chunks.borrow_mut(); let (chunk, mut new_capacity); if let Some(last_chunk) = chunks.last_mut() { let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize; let currently_used_cap = used_bytes / mem::size_of::<T>(); if last_chunk.storage.reserve_in_place(currently_used_cap, n) { self.end.set(last_chunk.end()); return; } else { new_capacity = last_chunk.storage.cap(); loop { new_capacity = new_capacity.checked_mul(2).unwrap(); if new_capacity >= currently_used_cap + n { break; } } } } else { let elem_size = cmp::max(1, mem::size_of::<T>()); new_capacity = cmp::max(n, PAGE / elem_size); } chunk = TypedArenaChunk::<T>::new(new_capacity); self.ptr.set(chunk.start()); self.end.set(chunk.end()); chunks.push(chunk); } } /// Clears the arena. Deallocates all but the longest chunk which may be reused. pub fn clear(&mut self) { unsafe { // Clear the last chunk, which is partially filled. let mut chunks_borrow = self.chunks.borrow_mut(); if let Some(mut last_chunk) = chunks_borrow.pop() { self.clear_last_chunk(&mut last_chunk); // If `T` is ZST, code below has no effect. for mut chunk in chunks_borrow.drain(..) { let cap = chunk.storage.cap(); chunk.destroy(cap); } chunks_borrow.push(last_chunk); } } } // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other // chunks. fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) { // Determine how much was filled. let start = last_chunk.start() as usize; // We obtain the value of the pointer to the first uninitialized element. let end = self.ptr.get() as usize; // We then calculate the number of elements to be dropped in the last chunk, // which is the filled area's length. let diff = if mem::size_of::<T>() == 0 { // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get // the number of zero-sized values in the last and only chunk, just out of caution. // Recall that `end` was incremented for each allocated value. end - start } else { (end - start) / mem::size_of::<T>() }; // Pass that to the `destroy` method. unsafe { last_chunk.destroy(diff); } // Reset the chunk. self.ptr.set(last_chunk.start()); } } unsafe impl<#[may_dangle] T> Drop for TypedArena<T> { fn drop(&mut self) { unsafe { // Determine how much was filled. let mut chunks_borrow = self.chunks.borrow_mut(); if let Some(mut last_chunk) = chunks_borrow.pop() { // Drop the contents of the last chunk. self.clear_last_chunk(&mut last_chunk); // The last chunk will be dropped. Destroy all other chunks. for chunk in chunks_borrow.iter_mut() { let cap = chunk.storage.cap(); chunk.destroy(cap); } } // RawVec handles deallocation of `last_chunk` and `self.chunks`. } } } unsafe impl<T: Send> Send for TypedArena<T> {} pub struct DroplessArena { /// A pointer to the next object to be allocated. ptr: Cell<*mut u8>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. end: Cell<*mut u8>, /// A vector of arena chunks. chunks: RefCell<Vec<TypedArenaChunk<u8>>>, } unsafe impl Send for DroplessArena {} impl DroplessArena { pub fn new() -> DroplessArena { DroplessArena { ptr: Cell::new(0 as *mut u8), end: Cell::new(0 as *mut u8), chunks: RefCell::new(vec![]), } } pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool { let ptr = ptr as *const u8 as *mut u8; for chunk in &*self.chunks.borrow() { if chunk.start() <= ptr && ptr < chunk.end() { return true; } } false } fn align_for<T>(&self) { let align = mem::align_of::<T>(); let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1); self.ptr.set(final_address as *mut u8); assert!(self.ptr <= self.end); } #[inline(never)] #[cold] fn grow<T>(&self, n: usize) { let needed_bytes = n * mem::size_of::<T>(); unsafe { let mut chunks = self.chunks.borrow_mut(); let (chunk, mut new_capacity); if let Some(last_chunk) = chunks.last_mut() { let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize; if last_chunk .storage .reserve_in_place(used_bytes, needed_bytes) { self.end.set(last_chunk.end()); return; } else { new_capacity = last_chunk.storage.cap(); loop { new_capacity = new_capacity.checked_mul(2).unwrap(); if new_capacity >= used_bytes + needed_bytes { break; } } } } else { new_capacity = cmp::max(needed_bytes, PAGE); } chunk = TypedArenaChunk::<u8>::new(new_capacity); self.ptr.set(chunk.start()); self.end.set(chunk.end()); chunks.push(chunk); } } #[inline] pub fn alloc<T>(&self, object: T) -> &mut T { unsafe { assert!(!mem::needs_drop::<T>()); assert!(mem::size_of::<T>() != 0); self.align_for::<T>(); let future_end = intrinsics::arith_offset(self.ptr.get(), mem::size_of::<T>() as isize); if (future_end as *mut u8) >= self.end.get() { self.grow::<T>(1) } let ptr = self.ptr.get(); // Set the pointer past ourselves self.ptr.set( intrinsics::arith_offset(self.ptr.get(), mem::size_of::<T>() as isize) as *mut u8, ); // Write into uninitialized memory. ptr::write(ptr as *mut T, object); &mut *(ptr as *mut T) } } /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable /// reference to it. Will panic if passed a zero-sized type. /// /// Panics: /// /// - Zero-sized types /// - Zero-length slices #[inline] pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T] where T: Copy, { assert!(!mem::needs_drop::<T>()); assert!(mem::size_of::<T>() != 0); assert!(slice.len() != 0); self.align_for::<T>(); let future_end = unsafe { intrinsics::arith_offset(self.ptr.get(), (slice.len() * mem::size_of::<T>()) as isize) }; if (future_end as *mut u8) >= self.end.get() { self.grow::<T>(slice.len()); } unsafe { let arena_slice = slice::from_raw_parts_mut(self.ptr.get() as *mut T, slice.len()); self.ptr.set(intrinsics::arith_offset( self.ptr.get(), (slice.len() * mem::size_of::<T>()) as isize, ) as *mut u8); arena_slice.copy_from_slice(slice); arena_slice } } } pub struct SyncTypedArena<T> { lock: MTLock<TypedArena<T>>, } impl<T> SyncTypedArena<T> { #[inline(always)] pub fn new() -> SyncTypedArena<T> { SyncTypedArena { lock: MTLock::new(TypedArena::new()) } } #[inline(always)] pub fn alloc(&self, object: T) -> &mut T { // Extend the lifetime of the result since it's limited to the lock guard unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) } } #[inline(always)] pub fn alloc_slice(&self, slice: &[T]) -> &mut [T] where T: Copy, { // Extend the lifetime of the result since it's limited to the lock guard unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) } } #[inline(always)] pub fn clear(&mut self) { self.lock.get_mut().clear(); } } pub struct SyncDroplessArena { lock: MTLock<DroplessArena>, } impl SyncDroplessArena { #[inline(always)] pub fn new() -> SyncDroplessArena { SyncDroplessArena { lock: MTLock::new(DroplessArena::new()) } } #[inline(always)] pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool { self.lock.lock().in_arena(ptr) } #[inline(always)] pub fn alloc<T>(&self, object: T) -> &mut T { // Extend the lifetime of the result since it's limited to the lock guard unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) } } #[inline(always)] pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T] where T: Copy, { // Extend the lifetime of the result since it's limited to the lock guard unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) } } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use super::TypedArena; use std::cell::Cell; #[allow(dead_code)] #[derive(Debug, Eq, PartialEq)] struct Point { x: i32, y: i32, z: i32, } #[test] pub fn test_unused() { let arena: TypedArena<Point> = TypedArena::new(); assert!(arena.chunks.borrow().is_empty()); } #[test] fn test_arena_alloc_nested() { struct Inner { value: u8, } struct Outer<'a> { inner: &'a Inner, } enum EI<'e> { I(Inner), O(Outer<'e>), } struct Wrap<'a>(TypedArena<EI<'a>>); impl<'a> Wrap<'a> { fn alloc_inner<F: Fn() -> Inner>(&self, f: F) -> &Inner { let r: &EI = self.0.alloc(EI::I(f())); if let &EI::I(ref i) = r { i } else { panic!("mismatch"); } } fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer { let r: &EI = self.0.alloc(EI::O(f())); if let &EI::O(ref o) = r { o } else { panic!("mismatch"); } } } let arena = Wrap(TypedArena::new()); let result = arena.alloc_outer(|| Outer { inner: arena.alloc_inner(|| Inner { value: 10 }),
assert_eq!(result.inner.value, 10); } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(Point { x: 1, y: 2, z: 3 }); } } #[bench] pub fn bench_copy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 })) } #[bench] pub fn bench_copy_nonarena(b: &mut Bencher) { b.iter(|| { let _: Box<_> = Box::new(Point { x: 1, y: 2, z: 3 }); }) } #[allow(dead_code)] struct Noncopy { string: String, array: Vec<i32>, } #[test] pub fn test_noncopy() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec![1, 2, 3, 4, 5], }); } } #[test] pub fn test_typed_arena_zero_sized() { let arena = TypedArena::new(); for _ in 0..100000 { arena.alloc(()); } } #[test] pub fn test_typed_arena_clear() { let mut arena = TypedArena::new(); for _ in 0..10 { arena.clear(); for _ in 0..10000 { arena.alloc(Point { x: 1, y: 2, z: 3 }); } } } // Drop tests struct DropCounter<'a> { count: &'a Cell<u32>, } impl<'a> Drop for DropCounter<'a> { fn drop(&mut self) { self.count.set(self.count.get() + 1); } } #[test] fn test_typed_arena_drop_count() { let counter = Cell::new(0); { let arena: TypedArena<DropCounter> = TypedArena::new(); for _ in 0..100 { // Allocate something with drop glue to make sure it doesn't leak. arena.alloc(DropCounter { count: &counter }); } }; assert_eq!(counter.get(), 100); } #[test] fn test_typed_arena_drop_on_clear() { let counter = Cell::new(0); let mut arena: TypedArena<DropCounter> = TypedArena::new(); for i in 0..10 { for _ in 0..100 { // Allocate something with drop glue to make sure it doesn't leak. arena.alloc(DropCounter { count: &counter }); } arena.clear(); assert_eq!(counter.get(), i * 100 + 100); } } thread_local! { static DROP_COUNTER: Cell<u32> = Cell::new(0) } struct SmallDroppable; impl Drop for SmallDroppable { fn drop(&mut self) { DROP_COUNTER.with(|c| c.set(c.get() + 1)); } } #[test] fn test_typed_arena_drop_small_count() { DROP_COUNTER.with(|c| c.set(0)); { let arena: TypedArena<SmallDroppable> = TypedArena::new(); for _ in 0..100 { // Allocate something with drop glue to make sure it doesn't leak. arena.alloc(SmallDroppable); } // dropping }; assert_eq!(DROP_COUNTER.with(|c| c.get()), 100); } #[bench] pub fn bench_noncopy(b: &mut Bencher) { let arena = TypedArena::new(); b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), array: vec![1, 2, 3, 4, 5], }) }) } #[bench] pub fn bench_noncopy_nonarena(b: &mut Bencher) { b.iter(|| { let _: Box<_> = Box::new(Noncopy { string: "hello world".to_string(), array: vec![1, 2, 3, 4, 5], }); }) } }
});
auth-guard.ts
import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router'; import { UserLoginService } from '../user/user-login/user-login.service'; @Injectable() export class
implements CanActivate { constructor( private router: Router, public userLoginService: UserLoginService) { } canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean { //这里可以调用真实的服务进行验证 // this.userLoginService.currentUser // .subscribe( // data => { // }, // error => console.error(error) // ); return true; } }
AuthGuard
token_source.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package transport import ( "fmt" "io/ioutil" "net/http" "strings" "sync" "time" "golang.org/x/oauth2" "k8s.io/klog/v2" ) // TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens // authentication from an oauth2.TokenSource. func
(ts oauth2.TokenSource) func(http.RoundTripper) http.RoundTripper { return func(rt http.RoundTripper) http.RoundTripper { return &tokenSourceTransport{ base: rt, ort: &oauth2.Transport{ Source: ts, Base: rt, }, } } } // NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a // file at a specified path and periodically reloads it. func NewCachedFileTokenSource(path string) oauth2.TokenSource { return &cachingTokenSource{ now: time.Now, leeway: 10 * time.Second, base: &fileTokenSource{ path: path, // This period was picked because it is half of the duration between when the kubelet // refreshes a projected service account token and when the original token expires. // Default token lifetime is 10 minutes, and the kubelet starts refreshing at 80% of lifetime. // This should induce re-reading at a frequency that works with the token volume source. period: time.Minute, }, } } // NewCachedTokenSource returns a oauth2.TokenSource reads a token from a // designed TokenSource. The ts would provide the source of token. func NewCachedTokenSource(ts oauth2.TokenSource) oauth2.TokenSource { return &cachingTokenSource{ now: time.Now, base: ts, } } type tokenSourceTransport struct { base http.RoundTripper ort http.RoundTripper } func (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error) { // This is to allow --token to override other bearer token providers. if req.Header.Get("Authorization") != "" { return tst.base.RoundTrip(req) } return tst.ort.RoundTrip(req) } func (tst *tokenSourceTransport) CancelRequest(req *http.Request) { if req.Header.Get("Authorization") != "" { tryCancelRequest(tst.base, req) return } tryCancelRequest(tst.ort, req) } type fileTokenSource struct { path string period time.Duration } var _ = oauth2.TokenSource(&fileTokenSource{}) func (ts *fileTokenSource) Token() (*oauth2.Token, error) { tokb, err := ioutil.ReadFile(ts.path) if err != nil { return nil, fmt.Errorf("failed to read token file %q: %v", ts.path, err) } tok := strings.TrimSpace(string(tokb)) if len(tok) == 0 { return nil, fmt.Errorf("read empty token from file %q", ts.path) } return &oauth2.Token{ AccessToken: tok, Expiry: time.Now().Add(ts.period), }, nil } type cachingTokenSource struct { base oauth2.TokenSource leeway time.Duration sync.RWMutex tok *oauth2.Token // for testing now func() time.Time } var _ = oauth2.TokenSource(&cachingTokenSource{}) func (ts *cachingTokenSource) Token() (*oauth2.Token, error) { now := ts.now() // fast path ts.RLock() tok := ts.tok ts.RUnlock() if tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) { return tok, nil } // slow path ts.Lock() defer ts.Unlock() if tok := ts.tok; tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) { return tok, nil } tok, err := ts.base.Token() if err != nil { if ts.tok == nil { return nil, err } klog.Errorf("Unable to rotate token: %v", err) return ts.tok, nil } ts.tok = tok return tok, nil }
TokenSourceWrapTransport
base.py
import os import platform import socket from abc import ABCMeta, abstractmethod from copy import deepcopy from ..wptcommandline import require_arg # noqa: F401 here = os.path.dirname(__file__) def inherit(super_module, child_globals, product_name): super_wptrunner = super_module.__wptrunner__ child_globals["__wptrunner__"] = child_wptrunner = deepcopy(super_wptrunner) child_wptrunner["product"] = product_name for k in ("check_args", "browser", "browser_kwargs", "executor_kwargs", "env_extras", "env_options", "timeout_multiplier"): attr = super_wptrunner[k] child_globals[attr] = getattr(super_module, attr) for v in super_module.__wptrunner__["executor"].values(): child_globals[v] = getattr(super_module, v) if "run_info_extras" in super_wptrunner: attr = super_wptrunner["run_info_extras"] child_globals[attr] = getattr(super_module, attr) def cmd_arg(name, value=None): prefix = "-" if platform.system() == "Windows" else "--" rv = prefix + name if value is not None: rv += "=" + value return rv def maybe_add_args(required_args, current_args): for required_arg in required_args: # If the arg is in the form of "variable=value", only add it if # no arg with another value for "variable" is already there. if "=" in required_arg: required_arg_prefix = "%s=" % required_arg.split("=")[0] if not any(item.startswith(required_arg_prefix) for item in current_args): current_args.append(required_arg) else: if required_arg not in current_args: current_args.append(required_arg) return current_args def certificate_domain_list(list_of_domains, certificate_file): """Build a list of domains where certificate_file should be used""" cert_list = [] for domain in list_of_domains: cert_list.append({"host": domain, "certificateFile": certificate_file}) return cert_list def get_free_port(): """Get a random unbound port""" while True: s = socket.socket() try:
return s.getsockname()[1] finally: s.close() def get_timeout_multiplier(test_type, run_info_data, **kwargs): if kwargs["timeout_multiplier"] is not None: return kwargs["timeout_multiplier"] return 1 def browser_command(binary, args, debug_info): if debug_info: if debug_info.requiresEscapedArgs: args = [item.replace("&", "\\&") for item in args] debug_args = [debug_info.path] + debug_info.args else: debug_args = [] command = [binary] + args return debug_args, command class BrowserError(Exception): pass class Browser(object): """Abstract class serving as the basis for Browser implementations. The Browser is used in the TestRunnerManager to start and stop the browser process, and to check the state of that process. This class also acts as a context manager, enabling it to do browser-specific setup at the start of the testrun and cleanup after the run is complete. :param logger: Structured logger to use for output. """ __metaclass__ = ABCMeta process_cls = None init_timeout = 30 def __init__(self, logger): self.logger = logger def __enter__(self): self.setup() return self def __exit__(self, *args, **kwargs): self.cleanup() def setup(self): """Used for browser-specific setup that happens at the start of a test run""" pass def settings(self, test): """Dictionary of metadata that is constant for a specific launch of a browser. This is used to determine when the browser instance configuration changes, requiring a relaunch of the browser. The test runner calls this method for each test, and if the returned value differs from that for the previous test, the browser is relaunched. """ return {} @abstractmethod def start(self, group_metadata, **kwargs): """Launch the browser object and get it into a state where is is ready to run tests""" pass @abstractmethod def stop(self, force=False): """Stop the running browser process.""" pass @abstractmethod def pid(self): """pid of the browser process or None if there is no pid""" pass @abstractmethod def is_alive(self): """Boolean indicating whether the browser process is still running""" pass def cleanup(self): """Browser-specific cleanup that is run after the testrun is finished""" pass def executor_browser(self): """Returns the ExecutorBrowser subclass for this Browser subclass and the keyword arguments with which it should be instantiated""" return ExecutorBrowser, {} def maybe_parse_tombstone(self): """Possibly parse tombstones on Android device for Android target""" pass def check_crash(self, process, test): """Check if a crash occured and output any useful information to the log. Returns a boolean indicating whether a crash occured.""" return False class NullBrowser(Browser): def __init__(self, logger, **kwargs): super(NullBrowser, self).__init__(logger) def start(self, **kwargs): """No-op browser to use in scenarios where the TestRunnerManager shouldn't actually own the browser process (e.g. Servo where we start one browser per test)""" pass def stop(self, force=False): pass def pid(self): return None def is_alive(self): return True def on_output(self, line): raise NotImplementedError class ExecutorBrowser(object): """View of the Browser used by the Executor object. This is needed because the Executor runs in a child process and we can't ship Browser instances between processes on Windows. Typically this will have a few product-specific properties set, but in some cases it may have more elaborate methods for setting up the browser from the runner process. """ def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v)
s.bind(("127.0.0.1", 0)) except socket.error: continue else:
webhook.pb.go
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0 // protoc v3.13.0 // source: google/cloud/dialogflow/cx/v3beta1/webhook.proto package cx import ( context "context" reflect "reflect" sync "sync" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" durationpb "google.golang.org/protobuf/types/known/durationpb" emptypb "google.golang.org/protobuf/types/known/emptypb" fieldmaskpb "google.golang.org/protobuf/types/known/fieldmaskpb" structpb "google.golang.org/protobuf/types/known/structpb" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 // Defines merge behavior for `messages`. type WebhookResponse_FulfillmentResponse_MergeBehavior int32 const ( // Not specified. `APPEND` will be used. WebhookResponse_FulfillmentResponse_MERGE_BEHAVIOR_UNSPECIFIED WebhookResponse_FulfillmentResponse_MergeBehavior = 0 // `messages` will be appended to the list of messages waiting to be sent // to the user. WebhookResponse_FulfillmentResponse_APPEND WebhookResponse_FulfillmentResponse_MergeBehavior = 1 // `messages` will replace the list of messages waiting to be sent to the // user. WebhookResponse_FulfillmentResponse_REPLACE WebhookResponse_FulfillmentResponse_MergeBehavior = 2 ) // Enum value maps for WebhookResponse_FulfillmentResponse_MergeBehavior. var ( WebhookResponse_FulfillmentResponse_MergeBehavior_name = map[int32]string{ 0: "MERGE_BEHAVIOR_UNSPECIFIED", 1: "APPEND", 2: "REPLACE", } WebhookResponse_FulfillmentResponse_MergeBehavior_value = map[string]int32{ "MERGE_BEHAVIOR_UNSPECIFIED": 0, "APPEND": 1, "REPLACE": 2, } ) func (x WebhookResponse_FulfillmentResponse_MergeBehavior) Enum() *WebhookResponse_FulfillmentResponse_MergeBehavior { p := new(WebhookResponse_FulfillmentResponse_MergeBehavior) *p = x return p } func (x WebhookResponse_FulfillmentResponse_MergeBehavior) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (WebhookResponse_FulfillmentResponse_MergeBehavior) Descriptor() protoreflect.EnumDescriptor { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_enumTypes[0].Descriptor() } func (WebhookResponse_FulfillmentResponse_MergeBehavior) Type() protoreflect.EnumType { return &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_enumTypes[0] } func (x WebhookResponse_FulfillmentResponse_MergeBehavior) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use WebhookResponse_FulfillmentResponse_MergeBehavior.Descriptor instead. func (WebhookResponse_FulfillmentResponse_MergeBehavior) EnumDescriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{8, 0, 0} } // Represents the state of a parameter. type PageInfo_FormInfo_ParameterInfo_ParameterState int32 const ( // Not specified. This value should be never used. PageInfo_FormInfo_ParameterInfo_PARAMETER_STATE_UNSPECIFIED PageInfo_FormInfo_ParameterInfo_ParameterState = 0 // Indicates that the parameter does not have a value. PageInfo_FormInfo_ParameterInfo_EMPTY PageInfo_FormInfo_ParameterInfo_ParameterState = 1 // Indicates that the parameter value is invalid. This field can be used // by the webhook to invalidate the parameter and ask the server to // collect it from the user again. PageInfo_FormInfo_ParameterInfo_INVALID PageInfo_FormInfo_ParameterInfo_ParameterState = 2 // Indicates that the parameter has a value. PageInfo_FormInfo_ParameterInfo_FILLED PageInfo_FormInfo_ParameterInfo_ParameterState = 3 ) // Enum value maps for PageInfo_FormInfo_ParameterInfo_ParameterState. var ( PageInfo_FormInfo_ParameterInfo_ParameterState_name = map[int32]string{ 0: "PARAMETER_STATE_UNSPECIFIED", 1: "EMPTY", 2: "INVALID", 3: "FILLED", } PageInfo_FormInfo_ParameterInfo_ParameterState_value = map[string]int32{ "PARAMETER_STATE_UNSPECIFIED": 0, "EMPTY": 1, "INVALID": 2, "FILLED": 3, } ) func (x PageInfo_FormInfo_ParameterInfo_ParameterState) Enum() *PageInfo_FormInfo_ParameterInfo_ParameterState { p := new(PageInfo_FormInfo_ParameterInfo_ParameterState) *p = x return p } func (x PageInfo_FormInfo_ParameterInfo_ParameterState) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (PageInfo_FormInfo_ParameterInfo_ParameterState) Descriptor() protoreflect.EnumDescriptor { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_enumTypes[1].Descriptor() } func (PageInfo_FormInfo_ParameterInfo_ParameterState) Type() protoreflect.EnumType { return &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_enumTypes[1] } func (x PageInfo_FormInfo_ParameterInfo_ParameterState) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use PageInfo_FormInfo_ParameterInfo_ParameterState.Descriptor instead. func (PageInfo_FormInfo_ParameterInfo_ParameterState) EnumDescriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{9, 0, 0, 0} } // Webhooks host the developer's business logic. During a session, webhooks // allow the developer to use the data extracted by Dialogflow's natural // language processing to generate dynamic responses, validate collected data, // or trigger actions on the backend. type Webhook struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The unique identifier of the webhook. // Required for the // [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook] // method. // [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook] // populates the name automatically. Format: `projects/<Project // ID>/locations/<Location ID>/agents/<Agent ID>/webhooks/<Webhook ID>`. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The human-readable name of the webhook, unique within the agent. DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // Required. The webhook configuration. // // Types that are assignable to Webhook: // *Webhook_GenericWebService_ Webhook isWebhook_Webhook `protobuf_oneof:"webhook"` // Webhook execution timeout. Execution is considered failed if Dialogflow // doesn't receive a response from webhook at the end of the timeout period. // Defaults to 5 seconds, maximum allowed timeout is 30 seconds. Timeout *durationpb.Duration `protobuf:"bytes,6,opt,name=timeout,proto3" json:"timeout,omitempty"` // Indicates whether the webhook is disabled. Disabled bool `protobuf:"varint,5,opt,name=disabled,proto3" json:"disabled,omitempty"` } func (x *Webhook) Reset() { *x = Webhook{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Webhook) String() string { return protoimpl.X.MessageStringOf(x) } func (*Webhook) ProtoMessage() {} func (x *Webhook) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Webhook.ProtoReflect.Descriptor instead. func (*Webhook) Descriptor() ([]byte, []int) {
if x != nil { return x.Name } return "" } func (x *Webhook) GetDisplayName() string { if x != nil { return x.DisplayName } return "" } func (m *Webhook) GetWebhook() isWebhook_Webhook { if m != nil { return m.Webhook } return nil } func (x *Webhook) GetGenericWebService() *Webhook_GenericWebService { if x, ok := x.GetWebhook().(*Webhook_GenericWebService_); ok { return x.GenericWebService } return nil } func (x *Webhook) GetTimeout() *durationpb.Duration { if x != nil { return x.Timeout } return nil } func (x *Webhook) GetDisabled() bool { if x != nil { return x.Disabled } return false } type isWebhook_Webhook interface { isWebhook_Webhook() } type Webhook_GenericWebService_ struct { // Configuration for a generic web service. GenericWebService *Webhook_GenericWebService `protobuf:"bytes,4,opt,name=generic_web_service,json=genericWebService,proto3,oneof"` } func (*Webhook_GenericWebService_) isWebhook_Webhook() {} // The request message for // [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. type ListWebhooksRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. The agent to list all webhooks for. // Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>`. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of items to return in a single page. By default 100 and // at most 1000. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` // The next_page_token value returned from a previous list request. PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` } func (x *ListWebhooksRequest) Reset() { *x = ListWebhooksRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ListWebhooksRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListWebhooksRequest) ProtoMessage() {} func (x *ListWebhooksRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListWebhooksRequest.ProtoReflect.Descriptor instead. func (*ListWebhooksRequest) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{1} } func (x *ListWebhooksRequest) GetParent() string { if x != nil { return x.Parent } return "" } func (x *ListWebhooksRequest) GetPageSize() int32 { if x != nil { return x.PageSize } return 0 } func (x *ListWebhooksRequest) GetPageToken() string { if x != nil { return x.PageToken } return "" } // The response message for // [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. type ListWebhooksResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The list of webhooks. There will be a maximum number of items returned // based on the page_size field in the request. Webhooks []*Webhook `protobuf:"bytes,1,rep,name=webhooks,proto3" json:"webhooks,omitempty"` // Token to retrieve the next page of results, or empty if there are no more // results in the list. NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` } func (x *ListWebhooksResponse) Reset() { *x = ListWebhooksResponse{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ListWebhooksResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ListWebhooksResponse) ProtoMessage() {} func (x *ListWebhooksResponse) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ListWebhooksResponse.ProtoReflect.Descriptor instead. func (*ListWebhooksResponse) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{2} } func (x *ListWebhooksResponse) GetWebhooks() []*Webhook { if x != nil { return x.Webhooks } return nil } func (x *ListWebhooksResponse) GetNextPageToken() string { if x != nil { return x.NextPageToken } return "" } // The request message for // [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook]. type GetWebhookRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. The name of the webhook. // Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent // ID>/webhooks/<Webhook ID>`. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } func (x *GetWebhookRequest) Reset() { *x = GetWebhookRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GetWebhookRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetWebhookRequest) ProtoMessage() {} func (x *GetWebhookRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetWebhookRequest.ProtoReflect.Descriptor instead. func (*GetWebhookRequest) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{3} } func (x *GetWebhookRequest) GetName() string { if x != nil { return x.Name } return "" } // The request message for // [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook]. type CreateWebhookRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. The agent to create a webhook for. // Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>`. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The webhook to create. Webhook *Webhook `protobuf:"bytes,2,opt,name=webhook,proto3" json:"webhook,omitempty"` } func (x *CreateWebhookRequest) Reset() { *x = CreateWebhookRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CreateWebhookRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*CreateWebhookRequest) ProtoMessage() {} func (x *CreateWebhookRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CreateWebhookRequest.ProtoReflect.Descriptor instead. func (*CreateWebhookRequest) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{4} } func (x *CreateWebhookRequest) GetParent() string { if x != nil { return x.Parent } return "" } func (x *CreateWebhookRequest) GetWebhook() *Webhook { if x != nil { return x.Webhook } return nil } // The request message for // [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook]. type UpdateWebhookRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. The webhook to update. Webhook *Webhook `protobuf:"bytes,1,opt,name=webhook,proto3" json:"webhook,omitempty"` // The mask to control which fields get updated. If the mask is not present, // all fields will be updated. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } func (x *UpdateWebhookRequest) Reset() { *x = UpdateWebhookRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *UpdateWebhookRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*UpdateWebhookRequest) ProtoMessage() {} func (x *UpdateWebhookRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use UpdateWebhookRequest.ProtoReflect.Descriptor instead. func (*UpdateWebhookRequest) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{5} } func (x *UpdateWebhookRequest) GetWebhook() *Webhook { if x != nil { return x.Webhook } return nil } func (x *UpdateWebhookRequest) GetUpdateMask() *fieldmaskpb.FieldMask { if x != nil { return x.UpdateMask } return nil } // The request message for // [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook]. type DeleteWebhookRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. The name of the webhook to delete. // Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent // ID>/webhooks/<Webhook ID>`. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // This field has no effect for webhook not being used. // For webhooks that are used by pages/flows/transition route groups: // // * If `force` is set to false, an error will be returned with message // indicating the referenced resources. // * If `force` is set to true, Dialogflow will remove the webhook, as well // as any references to the webhook (i.e. // [Webhook][google.cloud.dialogflow.cx.v3beta1.Fulfillment.webhook] and // [tag][google.cloud.dialogflow.cx.v3beta1.Fulfillment.tag]in fulfillments // that point to this webhook will be removed). Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } func (x *DeleteWebhookRequest) Reset() { *x = DeleteWebhookRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DeleteWebhookRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*DeleteWebhookRequest) ProtoMessage() {} func (x *DeleteWebhookRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DeleteWebhookRequest.ProtoReflect.Descriptor instead. func (*DeleteWebhookRequest) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{6} } func (x *DeleteWebhookRequest) GetName() string { if x != nil { return x.Name } return "" } func (x *DeleteWebhookRequest) GetForce() bool { if x != nil { return x.Force } return false } // The request message for a webhook call. type WebhookRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Always present. The unique identifier of the // [DetectIntentResponse][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse] // that will be returned to the API caller. DetectIntentResponseId string `protobuf:"bytes,1,opt,name=detect_intent_response_id,json=detectIntentResponseId,proto3" json:"detect_intent_response_id,omitempty"` // Always present. Information about the fulfillment that triggered this // webhook call. FulfillmentInfo *WebhookRequest_FulfillmentInfo `protobuf:"bytes,6,opt,name=fulfillment_info,json=fulfillmentInfo,proto3" json:"fulfillment_info,omitempty"` // Information about the last matched intent. IntentInfo *WebhookRequest_IntentInfo `protobuf:"bytes,3,opt,name=intent_info,json=intentInfo,proto3" json:"intent_info,omitempty"` // Information about page status. PageInfo *PageInfo `protobuf:"bytes,4,opt,name=page_info,json=pageInfo,proto3" json:"page_info,omitempty"` // Information about session status. SessionInfo *SessionInfo `protobuf:"bytes,5,opt,name=session_info,json=sessionInfo,proto3" json:"session_info,omitempty"` // The list of rich message responses to present to the user. Webhook can // choose to append or replace this list in // [WebhookResponse.fulfillment_response][google.cloud.dialogflow.cx.v3beta1.WebhookResponse.fulfillment_response]; Messages []*ResponseMessage `protobuf:"bytes,7,rep,name=messages,proto3" json:"messages,omitempty"` // Custom data set in // [QueryParameters.payload][google.cloud.dialogflow.cx.v3beta1.QueryParameters.payload]. Payload *structpb.Struct `protobuf:"bytes,8,opt,name=payload,proto3" json:"payload,omitempty"` } func (x *WebhookRequest) Reset() { *x = WebhookRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WebhookRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhookRequest) ProtoMessage() {} func (x *WebhookRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhookRequest.ProtoReflect.Descriptor instead. func (*WebhookRequest) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{7} } func (x *WebhookRequest) GetDetectIntentResponseId() string { if x != nil { return x.DetectIntentResponseId } return "" } func (x *WebhookRequest) GetFulfillmentInfo() *WebhookRequest_FulfillmentInfo { if x != nil { return x.FulfillmentInfo } return nil } func (x *WebhookRequest) GetIntentInfo() *WebhookRequest_IntentInfo { if x != nil { return x.IntentInfo } return nil } func (x *WebhookRequest) GetPageInfo() *PageInfo { if x != nil { return x.PageInfo } return nil } func (x *WebhookRequest) GetSessionInfo() *SessionInfo { if x != nil { return x.SessionInfo } return nil } func (x *WebhookRequest) GetMessages() []*ResponseMessage { if x != nil { return x.Messages } return nil } func (x *WebhookRequest) GetPayload() *structpb.Struct { if x != nil { return x.Payload } return nil } // The response message for a webhook call. type WebhookResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The fulfillment response to send to the user. This field can be omitted by // the webhook if it does not intend to send any response to the user. FulfillmentResponse *WebhookResponse_FulfillmentResponse `protobuf:"bytes,1,opt,name=fulfillment_response,json=fulfillmentResponse,proto3" json:"fulfillment_response,omitempty"` // Information about page status. This field can be omitted by the webhook if // it does not intend to modify page status. PageInfo *PageInfo `protobuf:"bytes,2,opt,name=page_info,json=pageInfo,proto3" json:"page_info,omitempty"` // Information about session status. This field can be omitted by the webhook // if it does not intend to modify session status. SessionInfo *SessionInfo `protobuf:"bytes,3,opt,name=session_info,json=sessionInfo,proto3" json:"session_info,omitempty"` // Value to append directly to // [QueryResult.webhook_payloads][google.cloud.dialogflow.cx.v3beta1.QueryResult.webhook_payloads]. Payload *structpb.Struct `protobuf:"bytes,4,opt,name=payload,proto3" json:"payload,omitempty"` // The target to transition to. This can be set optionally to indicate an // immediate transition to a different page in the same host flow, or a // different flow in the same agent. // // Types that are assignable to Transition: // *WebhookResponse_TargetPage // *WebhookResponse_TargetFlow Transition isWebhookResponse_Transition `protobuf_oneof:"transition"` } func (x *WebhookResponse) Reset() { *x = WebhookResponse{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WebhookResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhookResponse) ProtoMessage() {} func (x *WebhookResponse) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhookResponse.ProtoReflect.Descriptor instead. func (*WebhookResponse) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{8} } func (x *WebhookResponse) GetFulfillmentResponse() *WebhookResponse_FulfillmentResponse { if x != nil { return x.FulfillmentResponse } return nil } func (x *WebhookResponse) GetPageInfo() *PageInfo { if x != nil { return x.PageInfo } return nil } func (x *WebhookResponse) GetSessionInfo() *SessionInfo { if x != nil { return x.SessionInfo } return nil } func (x *WebhookResponse) GetPayload() *structpb.Struct { if x != nil { return x.Payload } return nil } func (m *WebhookResponse) GetTransition() isWebhookResponse_Transition { if m != nil { return m.Transition } return nil } func (x *WebhookResponse) GetTargetPage() string { if x, ok := x.GetTransition().(*WebhookResponse_TargetPage); ok { return x.TargetPage } return "" } func (x *WebhookResponse) GetTargetFlow() string { if x, ok := x.GetTransition().(*WebhookResponse_TargetFlow); ok { return x.TargetFlow } return "" } type isWebhookResponse_Transition interface { isWebhookResponse_Transition() } type WebhookResponse_TargetPage struct { // The target page to transition to. // Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent // ID>/flows/<Flow ID>/pages/<Page ID>`. TargetPage string `protobuf:"bytes,5,opt,name=target_page,json=targetPage,proto3,oneof"` } type WebhookResponse_TargetFlow struct { // The target flow to transition to. // Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent // ID>/flows/<Flow ID>`. TargetFlow string `protobuf:"bytes,6,opt,name=target_flow,json=targetFlow,proto3,oneof"` } func (*WebhookResponse_TargetPage) isWebhookResponse_Transition() {} func (*WebhookResponse_TargetFlow) isWebhookResponse_Transition() {} // Represents page information communicated to and from the webhook. type PageInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Always present for // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. // Ignored for // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. The // unique identifier of the current page. Format: `projects/<Project // ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>/pages/<Page // ID>`. CurrentPage string `protobuf:"bytes,1,opt,name=current_page,json=currentPage,proto3" json:"current_page,omitempty"` // Optional for both // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] and // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. // Information about the form. FormInfo *PageInfo_FormInfo `protobuf:"bytes,3,opt,name=form_info,json=formInfo,proto3" json:"form_info,omitempty"` } func (x *PageInfo) Reset() { *x = PageInfo{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PageInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*PageInfo) ProtoMessage() {} func (x *PageInfo) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PageInfo.ProtoReflect.Descriptor instead. func (*PageInfo) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{9} } func (x *PageInfo) GetCurrentPage() string { if x != nil { return x.CurrentPage } return "" } func (x *PageInfo) GetFormInfo() *PageInfo_FormInfo { if x != nil { return x.FormInfo } return nil } // Represents session information communicated to and from the webhook. type SessionInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Always present for // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. // Ignored for // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. The // unique identifier of the // [session][google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest.session]. // This field can be used by the webhook to identify a user. Format: // `projects/<Project ID>/locations/<Location ID>/agents/<Agent // ID>/sessions/<Session ID>`. Session string `protobuf:"bytes,1,opt,name=session,proto3" json:"session,omitempty"` // Optional for // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. // Optional for // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. All // parameters collected from forms and intents during the session. Parameters // can be created, updated, or removed by the webhook. To remove a parameter // from the session, the webhook should explicitly set the parameter value to // null in // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. The // map is keyed by parameters' display names. Parameters map[string]*structpb.Value `protobuf:"bytes,2,rep,name=parameters,proto3" json:"parameters,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } func (x *SessionInfo) Reset() { *x = SessionInfo{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SessionInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*SessionInfo) ProtoMessage() {} func (x *SessionInfo) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SessionInfo.ProtoReflect.Descriptor instead. func (*SessionInfo) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{10} } func (x *SessionInfo) GetSession() string { if x != nil { return x.Session } return "" } func (x *SessionInfo) GetParameters() map[string]*structpb.Value { if x != nil { return x.Parameters } return nil } // Represents configuration for a generic web service. type Webhook_GenericWebService struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. The webhook URI for receiving POST requests. It must use https // protocol. Uri string `protobuf:"bytes,1,opt,name=uri,proto3" json:"uri,omitempty"` // The user name for HTTP Basic authentication. // // Deprecated: Do not use. Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` // The password for HTTP Basic authentication. // // Deprecated: Do not use. Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"` // The HTTP request headers to send together with webhook // requests. RequestHeaders map[string]string `protobuf:"bytes,4,rep,name=request_headers,json=requestHeaders,proto3" json:"request_headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } func (x *Webhook_GenericWebService) Reset() { *x = Webhook_GenericWebService{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Webhook_GenericWebService) String() string { return protoimpl.X.MessageStringOf(x) } func (*Webhook_GenericWebService) ProtoMessage() {} func (x *Webhook_GenericWebService) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[11] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Webhook_GenericWebService.ProtoReflect.Descriptor instead. func (*Webhook_GenericWebService) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{0, 0} } func (x *Webhook_GenericWebService) GetUri() string { if x != nil { return x.Uri } return "" } // Deprecated: Do not use. func (x *Webhook_GenericWebService) GetUsername() string { if x != nil { return x.Username } return "" } // Deprecated: Do not use. func (x *Webhook_GenericWebService) GetPassword() string { if x != nil { return x.Password } return "" } func (x *Webhook_GenericWebService) GetRequestHeaders() map[string]string { if x != nil { return x.RequestHeaders } return nil } // Represents fulfillment information communicated to the webhook. type WebhookRequest_FulfillmentInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Always present. The tag used to identify which fulfillment is being // called. Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` } func (x *WebhookRequest_FulfillmentInfo) Reset() { *x = WebhookRequest_FulfillmentInfo{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WebhookRequest_FulfillmentInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhookRequest_FulfillmentInfo) ProtoMessage() {} func (x *WebhookRequest_FulfillmentInfo) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[13] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhookRequest_FulfillmentInfo.ProtoReflect.Descriptor instead. func (*WebhookRequest_FulfillmentInfo) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{7, 0} } func (x *WebhookRequest_FulfillmentInfo) GetTag() string { if x != nil { return x.Tag } return "" } // Represents intent information communicated to the webhook. type WebhookRequest_IntentInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Always present. The unique identifier of the last matched // [intent][google.cloud.dialogflow.cx.v3beta1.Intent]. Format: // `projects/<Project ID>/locations/<Location ID>/agents/<Agent // ID>/intents/<Intent ID>`. LastMatchedIntent string `protobuf:"bytes,1,opt,name=last_matched_intent,json=lastMatchedIntent,proto3" json:"last_matched_intent,omitempty"` // Parameters identified as a result of intent matching. This is a map of // the name of the identified parameter to the value of the parameter // identified from the user's utterance. All parameters defined in the // matched intent that are identified will be surfaced here. Parameters map[string]*WebhookRequest_IntentInfo_IntentParameterValue `protobuf:"bytes,2,rep,name=parameters,proto3" json:"parameters,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } func (x *WebhookRequest_IntentInfo) Reset() { *x = WebhookRequest_IntentInfo{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WebhookRequest_IntentInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhookRequest_IntentInfo) ProtoMessage() {} func (x *WebhookRequest_IntentInfo) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[14] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhookRequest_IntentInfo.ProtoReflect.Descriptor instead. func (*WebhookRequest_IntentInfo) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{7, 1} } func (x *WebhookRequest_IntentInfo) GetLastMatchedIntent() string { if x != nil { return x.LastMatchedIntent } return "" } func (x *WebhookRequest_IntentInfo) GetParameters() map[string]*WebhookRequest_IntentInfo_IntentParameterValue { if x != nil { return x.Parameters } return nil } // Represents a value for an intent parameter. type WebhookRequest_IntentInfo_IntentParameterValue struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Always present. Original text value extracted from user utterance. OriginalValue string `protobuf:"bytes,1,opt,name=original_value,json=originalValue,proto3" json:"original_value,omitempty"` // Always present. Structured value for the parameter extracted from user // utterance. ResolvedValue *structpb.Value `protobuf:"bytes,2,opt,name=resolved_value,json=resolvedValue,proto3" json:"resolved_value,omitempty"` } func (x *WebhookRequest_IntentInfo_IntentParameterValue) Reset() { *x = WebhookRequest_IntentInfo_IntentParameterValue{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WebhookRequest_IntentInfo_IntentParameterValue) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhookRequest_IntentInfo_IntentParameterValue) ProtoMessage() {} func (x *WebhookRequest_IntentInfo_IntentParameterValue) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[15] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhookRequest_IntentInfo_IntentParameterValue.ProtoReflect.Descriptor instead. func (*WebhookRequest_IntentInfo_IntentParameterValue) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{7, 1, 0} } func (x *WebhookRequest_IntentInfo_IntentParameterValue) GetOriginalValue() string { if x != nil { return x.OriginalValue } return "" } func (x *WebhookRequest_IntentInfo_IntentParameterValue) GetResolvedValue() *structpb.Value { if x != nil { return x.ResolvedValue } return nil } // Represents a fulfillment response to the user. type WebhookResponse_FulfillmentResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The list of rich message responses to present to the user. Messages []*ResponseMessage `protobuf:"bytes,1,rep,name=messages,proto3" json:"messages,omitempty"` // Merge behavior for `messages`. MergeBehavior WebhookResponse_FulfillmentResponse_MergeBehavior `protobuf:"varint,2,opt,name=merge_behavior,json=mergeBehavior,proto3,enum=google.cloud.dialogflow.cx.v3beta1.WebhookResponse_FulfillmentResponse_MergeBehavior" json:"merge_behavior,omitempty"` } func (x *WebhookResponse_FulfillmentResponse) Reset() { *x = WebhookResponse_FulfillmentResponse{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WebhookResponse_FulfillmentResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhookResponse_FulfillmentResponse) ProtoMessage() {} func (x *WebhookResponse_FulfillmentResponse) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[17] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhookResponse_FulfillmentResponse.ProtoReflect.Descriptor instead. func (*WebhookResponse_FulfillmentResponse) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{8, 0} } func (x *WebhookResponse_FulfillmentResponse) GetMessages() []*ResponseMessage { if x != nil { return x.Messages } return nil } func (x *WebhookResponse_FulfillmentResponse) GetMergeBehavior() WebhookResponse_FulfillmentResponse_MergeBehavior { if x != nil { return x.MergeBehavior } return WebhookResponse_FulfillmentResponse_MERGE_BEHAVIOR_UNSPECIFIED } // Represents form information. type PageInfo_FormInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Optional for both // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] and // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. // The parameters contained in the form. Note that the webhook cannot add // or remove any form parameter. ParameterInfo []*PageInfo_FormInfo_ParameterInfo `protobuf:"bytes,2,rep,name=parameter_info,json=parameterInfo,proto3" json:"parameter_info,omitempty"` } func (x *PageInfo_FormInfo) Reset() { *x = PageInfo_FormInfo{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PageInfo_FormInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*PageInfo_FormInfo) ProtoMessage() {} func (x *PageInfo_FormInfo) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[18] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PageInfo_FormInfo.ProtoReflect.Descriptor instead. func (*PageInfo_FormInfo) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{9, 0} } func (x *PageInfo_FormInfo) GetParameterInfo() []*PageInfo_FormInfo_ParameterInfo { if x != nil { return x.ParameterInfo } return nil } // Represents parameter information. type PageInfo_FormInfo_ParameterInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Always present for // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. // Required for // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. // The human-readable name of the parameter, unique within the form. This // field cannot be modified by the webhook. DisplayName string `protobuf:"bytes,1,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // Optional for both // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] and // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. // Indicates whether the parameter is required. Optional parameters will // not trigger prompts; however, they are filled if the user specifies // them. Required parameters must be filled before form filling concludes. Required bool `protobuf:"varint,2,opt,name=required,proto3" json:"required,omitempty"` // Always present for // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. // Required for // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. // The state of the parameter. This field can be set to // [INVALID][google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo.ParameterState.INVALID] // by the webhook to invalidate the parameter; other values set by the // webhook will be ignored. State PageInfo_FormInfo_ParameterInfo_ParameterState `protobuf:"varint,3,opt,name=state,proto3,enum=google.cloud.dialogflow.cx.v3beta1.PageInfo_FormInfo_ParameterInfo_ParameterState" json:"state,omitempty"` // Optional for both // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] and // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. // The value of the parameter. This field can be set by the webhook to // change the parameter value. Value *structpb.Value `protobuf:"bytes,4,opt,name=value,proto3" json:"value,omitempty"` // Optional for // [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. // Ignored for // [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. // Indicates if the parameter value was just collected on the last // conversation turn. JustCollected bool `protobuf:"varint,5,opt,name=just_collected,json=justCollected,proto3" json:"just_collected,omitempty"` } func (x *PageInfo_FormInfo_ParameterInfo) Reset() { *x = PageInfo_FormInfo_ParameterInfo{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PageInfo_FormInfo_ParameterInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*PageInfo_FormInfo_ParameterInfo) ProtoMessage() {} func (x *PageInfo_FormInfo_ParameterInfo) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[19] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PageInfo_FormInfo_ParameterInfo.ProtoReflect.Descriptor instead. func (*PageInfo_FormInfo_ParameterInfo) Descriptor() ([]byte, []int) { return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{9, 0, 0} } func (x *PageInfo_FormInfo_ParameterInfo) GetDisplayName() string { if x != nil { return x.DisplayName } return "" } func (x *PageInfo_FormInfo_ParameterInfo) GetRequired() bool { if x != nil { return x.Required } return false } func (x *PageInfo_FormInfo_ParameterInfo) GetState() PageInfo_FormInfo_ParameterInfo_ParameterState { if x != nil { return x.State } return PageInfo_FormInfo_ParameterInfo_PARAMETER_STATE_UNSPECIFIED } func (x *PageInfo_FormInfo_ParameterInfo) GetValue() *structpb.Value { if x != nil { return x.Value } return nil } func (x *PageInfo_FormInfo_ParameterInfo) GetJustCollected() bool { if x != nil { return x.JustCollected } return false } var File_google_cloud_dialogflow_cx_v3beta1_webhook_proto protoreflect.FileDescriptor var file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDesc = []byte{ 0x0a, 0x30, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x63, 0x78, 0x2f, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x22, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x39, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x63, 0x78, 0x2f, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb1, 0x05, 0x0a, 0x07, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x26, 0x0a, 0x0c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x0b, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x6f, 0x0a, 0x13, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x5f, 0x77, 0x65, 0x62, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x3d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x57, 0x65, 0x62, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x48, 0x00, 0x52, 0x11, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x57, 0x65, 0x62, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x33, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x1a, 0xa9, 0x02, 0x0a, 0x11, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x57, 0x65, 0x62, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x15, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x03, 0x75, 0x72, 0x69, 0x12, 0x1e, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x02, 0x18, 0x01, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1e, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x42, 0x02, 0x18, 0x01, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x7a, 0x0a, 0x0f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x51, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x57, 0x65, 0x62, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0e, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x1a, 0x41, 0x0a, 0x13, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x3a, 0x71, 0xea, 0x41, 0x6e, 0x0a, 0x21, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x12, 0x49, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x7b, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x7d, 0x2f, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x2f, 0x7b, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x7d, 0x42, 0x09, 0x0a, 0x07, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x22, 0x94, 0x01, 0x0a, 0x13, 0x4c, 0x69, 0x73, 0x74, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x41, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x23, 0x12, 0x21, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x87, 0x01, 0x0a, 0x14, 0x4c, 0x69, 0x73, 0x74, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x47, 0x0a, 0x08, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x08, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x52, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x3d, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x23, 0x0a, 0x21, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0xa5, 0x01, 0x0a, 0x14, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x41, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x23, 0x12, 0x21, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x4a, 0x0a, 0x07, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x07, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x22, 0x9f, 0x01, 0x0a, 0x14, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x4a, 0x0a, 0x07, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x07, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x12, 0x3b, 0x0a, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x73, 0x6b, 0x22, 0x6b, 0x0a, 0x14, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x3d, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x23, 0x0a, 0x21, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6f, 0x72, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x66, 0x6f, 0x72, 0x63, 0x65, 0x22, 0xc9, 0x08, 0x0a, 0x0e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x39, 0x0a, 0x19, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x16, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x49, 0x64, 0x12, 0x6d, 0x0a, 0x10, 0x66, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x42, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x46, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0f, 0x66, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x5e, 0x0a, 0x0b, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x3d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0a, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x49, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x52, 0x0a, 0x0c, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0b, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x4f, 0x0a, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x12, 0x31, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x1a, 0x23, 0x0a, 0x0f, 0x46, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x61, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x74, 0x61, 0x67, 0x1a, 0xe4, 0x03, 0x0a, 0x0a, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x55, 0x0a, 0x13, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x25, 0xfa, 0x41, 0x22, 0x0a, 0x20, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x11, 0x6c, 0x61, 0x73, 0x74, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x6d, 0x0a, 0x0a, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x4d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0a, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x1a, 0x7c, 0x0a, 0x14, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x3d, 0x0a, 0x0e, 0x72, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, 0x64, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x6c, 0x76, 0x65, 0x64, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x91, 0x01, 0x0a, 0x0f, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x68, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x52, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xae, 0x06, 0x0a, 0x0f, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x7a, 0x0a, 0x14, 0x66, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x47, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x46, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x13, 0x66, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x49, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x52, 0x0a, 0x0c, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0b, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x31, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x46, 0x0a, 0x0b, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, 0xfa, 0x41, 0x20, 0x0a, 0x1e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x50, 0x61, 0x67, 0x65, 0x48, 0x00, 0x52, 0x0a, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x50, 0x61, 0x67, 0x65, 0x12, 0x46, 0x0a, 0x0b, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x66, 0x6c, 0x6f, 0x77, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, 0xfa, 0x41, 0x20, 0x0a, 0x1e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x46, 0x6c, 0x6f, 0x77, 0x48, 0x00, 0x52, 0x0a, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x46, 0x6c, 0x6f, 0x77, 0x1a, 0xae, 0x02, 0x0a, 0x13, 0x46, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4f, 0x0a, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x12, 0x7c, 0x0a, 0x0e, 0x6d, 0x65, 0x72, 0x67, 0x65, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x55, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x46, 0x75, 0x6c, 0x66, 0x69, 0x6c, 0x6c, 0x6d, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x4d, 0x65, 0x72, 0x67, 0x65, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x52, 0x0d, 0x6d, 0x65, 0x72, 0x67, 0x65, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x22, 0x48, 0x0a, 0x0d, 0x4d, 0x65, 0x72, 0x67, 0x65, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x12, 0x1e, 0x0a, 0x1a, 0x4d, 0x45, 0x52, 0x47, 0x45, 0x5f, 0x42, 0x45, 0x48, 0x41, 0x56, 0x49, 0x4f, 0x52, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x41, 0x50, 0x50, 0x45, 0x4e, 0x44, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x52, 0x45, 0x50, 0x4c, 0x41, 0x43, 0x45, 0x10, 0x02, 0x42, 0x0c, 0x0a, 0x0a, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x86, 0x05, 0x0a, 0x08, 0x50, 0x61, 0x67, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x46, 0x0a, 0x0c, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, 0xfa, 0x41, 0x20, 0x0a, 0x1e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x50, 0x61, 0x67, 0x65, 0x52, 0x0b, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x65, 0x12, 0x52, 0x0a, 0x09, 0x66, 0x6f, 0x72, 0x6d, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x46, 0x6f, 0x72, 0x6d, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x08, 0x66, 0x6f, 0x72, 0x6d, 0x49, 0x6e, 0x66, 0x6f, 0x1a, 0xdd, 0x03, 0x0a, 0x08, 0x46, 0x6f, 0x72, 0x6d, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x6a, 0x0a, 0x0e, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x43, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x46, 0x6f, 0x72, 0x6d, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0d, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x1a, 0xe4, 0x02, 0x0a, 0x0d, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x12, 0x68, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x52, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x46, 0x6f, 0x72, 0x6d, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x12, 0x2c, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x6a, 0x75, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x6a, 0x75, 0x73, 0x74, 0x43, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x55, 0x0a, 0x0e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x1f, 0x0a, 0x1b, 0x50, 0x41, 0x52, 0x41, 0x4d, 0x45, 0x54, 0x45, 0x52, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x4d, 0x50, 0x54, 0x59, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x46, 0x49, 0x4c, 0x4c, 0x45, 0x44, 0x10, 0x03, 0x22, 0x87, 0x02, 0x0a, 0x0b, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x40, 0x0a, 0x07, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x26, 0xfa, 0x41, 0x23, 0x0a, 0x21, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x07, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x5f, 0x0a, 0x0a, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0a, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x1a, 0x55, 0x0a, 0x0f, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x2c, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x32, 0xfd, 0x08, 0x0a, 0x08, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x12, 0xce, 0x01, 0x0a, 0x0c, 0x4c, 0x69, 0x73, 0x74, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x12, 0x37, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x4b, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3c, 0x12, 0x3a, 0x2f, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xbb, 0x01, 0x0a, 0x0a, 0x47, 0x65, 0x74, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x12, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x22, 0x49, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3c, 0x12, 0x3a, 0x2f, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0xd4, 0x01, 0x0a, 0x0d, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x12, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x22, 0x5c, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x45, 0x22, 0x3a, 0x2f, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x3a, 0x07, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0xda, 0x41, 0x0e, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x2c, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x12, 0xe1, 0x01, 0x0a, 0x0d, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x12, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x22, 0x69, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x4d, 0x32, 0x42, 0x2f, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x2e, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x07, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0xda, 0x41, 0x13, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x2c, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x12, 0xac, 0x01, 0x0a, 0x0d, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x12, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x22, 0x49, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3c, 0x2a, 0x3a, 0x2f, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x77, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x1a, 0x78, 0xca, 0x41, 0x19, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x59, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2d, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2c, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x42, 0xab, 0x01, 0x0a, 0x26, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x63, 0x78, 0x2e, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x0c, 0x57, 0x65, 0x62, 0x68, 0x6f, 0x6f, 0x6b, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x44, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x64, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x63, 0x78, 0x2f, 0x76, 0x33, 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, 0x63, 0x78, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x02, 0x44, 0x46, 0xaa, 0x02, 0x22, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x44, 0x69, 0x61, 0x6c, 0x6f, 0x67, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x43, 0x78, 0x2e, 0x56, 0x33, 0x42, 0x65, 0x74, 0x61, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescOnce sync.Once file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescData = file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDesc ) func file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP() []byte { file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescOnce.Do(func() { file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescData) }) return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescData } var file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes = make([]protoimpl.MessageInfo, 21) var file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_goTypes = []interface{}{ (WebhookResponse_FulfillmentResponse_MergeBehavior)(0), // 0: google.cloud.dialogflow.cx.v3beta1.WebhookResponse.FulfillmentResponse.MergeBehavior (PageInfo_FormInfo_ParameterInfo_ParameterState)(0), // 1: google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo.ParameterState (*Webhook)(nil), // 2: google.cloud.dialogflow.cx.v3beta1.Webhook (*ListWebhooksRequest)(nil), // 3: google.cloud.dialogflow.cx.v3beta1.ListWebhooksRequest (*ListWebhooksResponse)(nil), // 4: google.cloud.dialogflow.cx.v3beta1.ListWebhooksResponse (*GetWebhookRequest)(nil), // 5: google.cloud.dialogflow.cx.v3beta1.GetWebhookRequest (*CreateWebhookRequest)(nil), // 6: google.cloud.dialogflow.cx.v3beta1.CreateWebhookRequest (*UpdateWebhookRequest)(nil), // 7: google.cloud.dialogflow.cx.v3beta1.UpdateWebhookRequest (*DeleteWebhookRequest)(nil), // 8: google.cloud.dialogflow.cx.v3beta1.DeleteWebhookRequest (*WebhookRequest)(nil), // 9: google.cloud.dialogflow.cx.v3beta1.WebhookRequest (*WebhookResponse)(nil), // 10: google.cloud.dialogflow.cx.v3beta1.WebhookResponse (*PageInfo)(nil), // 11: google.cloud.dialogflow.cx.v3beta1.PageInfo (*SessionInfo)(nil), // 12: google.cloud.dialogflow.cx.v3beta1.SessionInfo (*Webhook_GenericWebService)(nil), // 13: google.cloud.dialogflow.cx.v3beta1.Webhook.GenericWebService nil, // 14: google.cloud.dialogflow.cx.v3beta1.Webhook.GenericWebService.RequestHeadersEntry (*WebhookRequest_FulfillmentInfo)(nil), // 15: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.FulfillmentInfo (*WebhookRequest_IntentInfo)(nil), // 16: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo (*WebhookRequest_IntentInfo_IntentParameterValue)(nil), // 17: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo.IntentParameterValue nil, // 18: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo.ParametersEntry (*WebhookResponse_FulfillmentResponse)(nil), // 19: google.cloud.dialogflow.cx.v3beta1.WebhookResponse.FulfillmentResponse (*PageInfo_FormInfo)(nil), // 20: google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo (*PageInfo_FormInfo_ParameterInfo)(nil), // 21: google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo nil, // 22: google.cloud.dialogflow.cx.v3beta1.SessionInfo.ParametersEntry (*durationpb.Duration)(nil), // 23: google.protobuf.Duration (*fieldmaskpb.FieldMask)(nil), // 24: google.protobuf.FieldMask (*ResponseMessage)(nil), // 25: google.cloud.dialogflow.cx.v3beta1.ResponseMessage (*structpb.Struct)(nil), // 26: google.protobuf.Struct (*structpb.Value)(nil), // 27: google.protobuf.Value (*emptypb.Empty)(nil), // 28: google.protobuf.Empty } var file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_depIdxs = []int32{ 13, // 0: google.cloud.dialogflow.cx.v3beta1.Webhook.generic_web_service:type_name -> google.cloud.dialogflow.cx.v3beta1.Webhook.GenericWebService 23, // 1: google.cloud.dialogflow.cx.v3beta1.Webhook.timeout:type_name -> google.protobuf.Duration 2, // 2: google.cloud.dialogflow.cx.v3beta1.ListWebhooksResponse.webhooks:type_name -> google.cloud.dialogflow.cx.v3beta1.Webhook 2, // 3: google.cloud.dialogflow.cx.v3beta1.CreateWebhookRequest.webhook:type_name -> google.cloud.dialogflow.cx.v3beta1.Webhook 2, // 4: google.cloud.dialogflow.cx.v3beta1.UpdateWebhookRequest.webhook:type_name -> google.cloud.dialogflow.cx.v3beta1.Webhook 24, // 5: google.cloud.dialogflow.cx.v3beta1.UpdateWebhookRequest.update_mask:type_name -> google.protobuf.FieldMask 15, // 6: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.fulfillment_info:type_name -> google.cloud.dialogflow.cx.v3beta1.WebhookRequest.FulfillmentInfo 16, // 7: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.intent_info:type_name -> google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo 11, // 8: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.page_info:type_name -> google.cloud.dialogflow.cx.v3beta1.PageInfo 12, // 9: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.session_info:type_name -> google.cloud.dialogflow.cx.v3beta1.SessionInfo 25, // 10: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.messages:type_name -> google.cloud.dialogflow.cx.v3beta1.ResponseMessage 26, // 11: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.payload:type_name -> google.protobuf.Struct 19, // 12: google.cloud.dialogflow.cx.v3beta1.WebhookResponse.fulfillment_response:type_name -> google.cloud.dialogflow.cx.v3beta1.WebhookResponse.FulfillmentResponse 11, // 13: google.cloud.dialogflow.cx.v3beta1.WebhookResponse.page_info:type_name -> google.cloud.dialogflow.cx.v3beta1.PageInfo 12, // 14: google.cloud.dialogflow.cx.v3beta1.WebhookResponse.session_info:type_name -> google.cloud.dialogflow.cx.v3beta1.SessionInfo 26, // 15: google.cloud.dialogflow.cx.v3beta1.WebhookResponse.payload:type_name -> google.protobuf.Struct 20, // 16: google.cloud.dialogflow.cx.v3beta1.PageInfo.form_info:type_name -> google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo 22, // 17: google.cloud.dialogflow.cx.v3beta1.SessionInfo.parameters:type_name -> google.cloud.dialogflow.cx.v3beta1.SessionInfo.ParametersEntry 14, // 18: google.cloud.dialogflow.cx.v3beta1.Webhook.GenericWebService.request_headers:type_name -> google.cloud.dialogflow.cx.v3beta1.Webhook.GenericWebService.RequestHeadersEntry 18, // 19: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo.parameters:type_name -> google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo.ParametersEntry 27, // 20: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo.IntentParameterValue.resolved_value:type_name -> google.protobuf.Value 17, // 21: google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo.ParametersEntry.value:type_name -> google.cloud.dialogflow.cx.v3beta1.WebhookRequest.IntentInfo.IntentParameterValue 25, // 22: google.cloud.dialogflow.cx.v3beta1.WebhookResponse.FulfillmentResponse.messages:type_name -> google.cloud.dialogflow.cx.v3beta1.ResponseMessage 0, // 23: google.cloud.dialogflow.cx.v3beta1.WebhookResponse.FulfillmentResponse.merge_behavior:type_name -> google.cloud.dialogflow.cx.v3beta1.WebhookResponse.FulfillmentResponse.MergeBehavior 21, // 24: google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.parameter_info:type_name -> google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo 1, // 25: google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo.state:type_name -> google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo.ParameterState 27, // 26: google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo.value:type_name -> google.protobuf.Value 27, // 27: google.cloud.dialogflow.cx.v3beta1.SessionInfo.ParametersEntry.value:type_name -> google.protobuf.Value 3, // 28: google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks:input_type -> google.cloud.dialogflow.cx.v3beta1.ListWebhooksRequest 5, // 29: google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook:input_type -> google.cloud.dialogflow.cx.v3beta1.GetWebhookRequest 6, // 30: google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook:input_type -> google.cloud.dialogflow.cx.v3beta1.CreateWebhookRequest 7, // 31: google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook:input_type -> google.cloud.dialogflow.cx.v3beta1.UpdateWebhookRequest 8, // 32: google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook:input_type -> google.cloud.dialogflow.cx.v3beta1.DeleteWebhookRequest 4, // 33: google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks:output_type -> google.cloud.dialogflow.cx.v3beta1.ListWebhooksResponse 2, // 34: google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook:output_type -> google.cloud.dialogflow.cx.v3beta1.Webhook 2, // 35: google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook:output_type -> google.cloud.dialogflow.cx.v3beta1.Webhook 2, // 36: google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook:output_type -> google.cloud.dialogflow.cx.v3beta1.Webhook 28, // 37: google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook:output_type -> google.protobuf.Empty 33, // [33:38] is the sub-list for method output_type 28, // [28:33] is the sub-list for method input_type 28, // [28:28] is the sub-list for extension type_name 28, // [28:28] is the sub-list for extension extendee 0, // [0:28] is the sub-list for field type_name } func init() { file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_init() } func file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_init() { if File_google_cloud_dialogflow_cx_v3beta1_webhook_proto != nil { return } file_google_cloud_dialogflow_cx_v3beta1_response_message_proto_init() if !protoimpl.UnsafeEnabled { file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Webhook); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ListWebhooksRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ListWebhooksResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetWebhookRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CreateWebhookRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*UpdateWebhookRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DeleteWebhookRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WebhookRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WebhookResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PageInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SessionInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Webhook_GenericWebService); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WebhookRequest_FulfillmentInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WebhookRequest_IntentInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WebhookRequest_IntentInfo_IntentParameterValue); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WebhookResponse_FulfillmentResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PageInfo_FormInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PageInfo_FormInfo_ParameterInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[0].OneofWrappers = []interface{}{ (*Webhook_GenericWebService_)(nil), } file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes[8].OneofWrappers = []interface{}{ (*WebhookResponse_TargetPage)(nil), (*WebhookResponse_TargetFlow)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDesc, NumEnums: 2, NumMessages: 21, NumExtensions: 0, NumServices: 1, }, GoTypes: file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_goTypes, DependencyIndexes: file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_depIdxs, EnumInfos: file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_enumTypes, MessageInfos: file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_msgTypes, }.Build() File_google_cloud_dialogflow_cx_v3beta1_webhook_proto = out.File file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDesc = nil file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_goTypes = nil file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_depIdxs = nil } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // WebhooksClient is the client API for Webhooks service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type WebhooksClient interface { // Returns the list of all webhooks in the specified agent. ListWebhooks(ctx context.Context, in *ListWebhooksRequest, opts ...grpc.CallOption) (*ListWebhooksResponse, error) // Retrieves the specified webhook. GetWebhook(ctx context.Context, in *GetWebhookRequest, opts ...grpc.CallOption) (*Webhook, error) // Creates a webhook in the specified agent. CreateWebhook(ctx context.Context, in *CreateWebhookRequest, opts ...grpc.CallOption) (*Webhook, error) // Updates the specified webhook. UpdateWebhook(ctx context.Context, in *UpdateWebhookRequest, opts ...grpc.CallOption) (*Webhook, error) // Deletes the specified webhook. DeleteWebhook(ctx context.Context, in *DeleteWebhookRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) } type webhooksClient struct { cc grpc.ClientConnInterface } func NewWebhooksClient(cc grpc.ClientConnInterface) WebhooksClient { return &webhooksClient{cc} } func (c *webhooksClient) ListWebhooks(ctx context.Context, in *ListWebhooksRequest, opts ...grpc.CallOption) (*ListWebhooksResponse, error) { out := new(ListWebhooksResponse) err := c.cc.Invoke(ctx, "/google.cloud.dialogflow.cx.v3beta1.Webhooks/ListWebhooks", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *webhooksClient) GetWebhook(ctx context.Context, in *GetWebhookRequest, opts ...grpc.CallOption) (*Webhook, error) { out := new(Webhook) err := c.cc.Invoke(ctx, "/google.cloud.dialogflow.cx.v3beta1.Webhooks/GetWebhook", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *webhooksClient) CreateWebhook(ctx context.Context, in *CreateWebhookRequest, opts ...grpc.CallOption) (*Webhook, error) { out := new(Webhook) err := c.cc.Invoke(ctx, "/google.cloud.dialogflow.cx.v3beta1.Webhooks/CreateWebhook", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *webhooksClient) UpdateWebhook(ctx context.Context, in *UpdateWebhookRequest, opts ...grpc.CallOption) (*Webhook, error) { out := new(Webhook) err := c.cc.Invoke(ctx, "/google.cloud.dialogflow.cx.v3beta1.Webhooks/UpdateWebhook", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *webhooksClient) DeleteWebhook(ctx context.Context, in *DeleteWebhookRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { out := new(emptypb.Empty) err := c.cc.Invoke(ctx, "/google.cloud.dialogflow.cx.v3beta1.Webhooks/DeleteWebhook", in, out, opts...) if err != nil { return nil, err } return out, nil } // WebhooksServer is the server API for Webhooks service. type WebhooksServer interface { // Returns the list of all webhooks in the specified agent. ListWebhooks(context.Context, *ListWebhooksRequest) (*ListWebhooksResponse, error) // Retrieves the specified webhook. GetWebhook(context.Context, *GetWebhookRequest) (*Webhook, error) // Creates a webhook in the specified agent. CreateWebhook(context.Context, *CreateWebhookRequest) (*Webhook, error) // Updates the specified webhook. UpdateWebhook(context.Context, *UpdateWebhookRequest) (*Webhook, error) // Deletes the specified webhook. DeleteWebhook(context.Context, *DeleteWebhookRequest) (*emptypb.Empty, error) } // UnimplementedWebhooksServer can be embedded to have forward compatible implementations. type UnimplementedWebhooksServer struct { } func (*UnimplementedWebhooksServer) ListWebhooks(context.Context, *ListWebhooksRequest) (*ListWebhooksResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ListWebhooks not implemented") } func (*UnimplementedWebhooksServer) GetWebhook(context.Context, *GetWebhookRequest) (*Webhook, error) { return nil, status.Errorf(codes.Unimplemented, "method GetWebhook not implemented") } func (*UnimplementedWebhooksServer) CreateWebhook(context.Context, *CreateWebhookRequest) (*Webhook, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateWebhook not implemented") } func (*UnimplementedWebhooksServer) UpdateWebhook(context.Context, *UpdateWebhookRequest) (*Webhook, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateWebhook not implemented") } func (*UnimplementedWebhooksServer) DeleteWebhook(context.Context, *DeleteWebhookRequest) (*emptypb.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method DeleteWebhook not implemented") } func RegisterWebhooksServer(s *grpc.Server, srv WebhooksServer) { s.RegisterService(&_Webhooks_serviceDesc, srv) } func _Webhooks_ListWebhooks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListWebhooksRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WebhooksServer).ListWebhooks(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/google.cloud.dialogflow.cx.v3beta1.Webhooks/ListWebhooks", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WebhooksServer).ListWebhooks(ctx, req.(*ListWebhooksRequest)) } return interceptor(ctx, in, info, handler) } func _Webhooks_GetWebhook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetWebhookRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WebhooksServer).GetWebhook(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/google.cloud.dialogflow.cx.v3beta1.Webhooks/GetWebhook", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WebhooksServer).GetWebhook(ctx, req.(*GetWebhookRequest)) } return interceptor(ctx, in, info, handler) } func _Webhooks_CreateWebhook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CreateWebhookRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WebhooksServer).CreateWebhook(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/google.cloud.dialogflow.cx.v3beta1.Webhooks/CreateWebhook", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WebhooksServer).CreateWebhook(ctx, req.(*CreateWebhookRequest)) } return interceptor(ctx, in, info, handler) } func _Webhooks_UpdateWebhook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UpdateWebhookRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WebhooksServer).UpdateWebhook(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/google.cloud.dialogflow.cx.v3beta1.Webhooks/UpdateWebhook", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WebhooksServer).UpdateWebhook(ctx, req.(*UpdateWebhookRequest)) } return interceptor(ctx, in, info, handler) } func _Webhooks_DeleteWebhook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteWebhookRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(WebhooksServer).DeleteWebhook(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/google.cloud.dialogflow.cx.v3beta1.Webhooks/DeleteWebhook", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(WebhooksServer).DeleteWebhook(ctx, req.(*DeleteWebhookRequest)) } return interceptor(ctx, in, info, handler) } var _Webhooks_serviceDesc = grpc.ServiceDesc{ ServiceName: "google.cloud.dialogflow.cx.v3beta1.Webhooks", HandlerType: (*WebhooksServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "ListWebhooks", Handler: _Webhooks_ListWebhooks_Handler, }, { MethodName: "GetWebhook", Handler: _Webhooks_GetWebhook_Handler, }, { MethodName: "CreateWebhook", Handler: _Webhooks_CreateWebhook_Handler, }, { MethodName: "UpdateWebhook", Handler: _Webhooks_UpdateWebhook_Handler, }, { MethodName: "DeleteWebhook", Handler: _Webhooks_DeleteWebhook_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "google/cloud/dialogflow/cx/v3beta1/webhook.proto", }
return file_google_cloud_dialogflow_cx_v3beta1_webhook_proto_rawDescGZIP(), []int{0} } func (x *Webhook) GetName() string {
crypto_verifier.rs
/* Copyright (c) 2018-present evan GmbH. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pub mod verifier { extern crate ursa; use crate::application::datatypes::{ CredentialDefinition, CredentialSchema, ProofPresentation, ProofRequest, RevocationRegistryDefinition, }; use std::{collections::HashMap, error::Error}; use ursa::cl::{ issuer::Issuer as CryptoIssuer, verifier::Verifier as CryptoVerifier, Proof as CryptoProof, RevocationKeyPublic, RevocationRegistry, SubProof, SubProofRequest, }; // Mediator class to broker between the high-level vade-evan application verifier and the Ursa verifier class pub struct CredVerifier {} impl CredVerifier { pub fn new() -> CredVerifier { CredVerifier {} } pub fn request_proof(attributes: Vec<&str>) -> Result<SubProofRequest, Box<dyn Error>> { let mut sub_proof_request_builder = CryptoVerifier::new_sub_proof_request_builder() .map_err(|e| format!("could not create sub proof request builder; {}", &e))?; for attribute in &attributes { sub_proof_request_builder .add_revealed_attr(&attribute) .map_err(|e| format!("could not add revealed attribute; {}", &e))?; } let sub_proof_request = sub_proof_request_builder .finalize() .map_err(|e| format!("could not finalize sub proof request; {}", &e))?; Ok(sub_proof_request) } pub fn verify_proof( presented_proof: &ProofPresentation, proof_request: &ProofRequest, credential_definitions: &HashMap<String, CredentialDefinition>, credential_schemas: &HashMap<String, CredentialSchema>, revocation_registry_definition: &HashMap<String, Option<RevocationRegistryDefinition>>, ) -> Result<(), Box<dyn Error>>
} impl Default for CredVerifier { fn default() -> Self { Self::new() } } }
{ let mut proof_verifier = CryptoVerifier::new_proof_verifier() .map_err(|e| format!("could not create proof verifier; {}", &e))?; let mut non_credential_schema_builder = CryptoIssuer::new_non_credential_schema_builder().map_err(|e| { format!("could not create non credential schema builder; {}", &e) })?; non_credential_schema_builder .add_attr("master_secret") .map_err(|e| { format!( "could not add master secret to non credential schema; {}", &e ) })?; let non_credential_schema = non_credential_schema_builder .finalize() .map_err(|e| format!("could not finalize non credential schema; {}", &e))?; let mut pub_key; let mut credential_schema_builder; let mut sub_proof_request_builder; for sub_proof_request in &proof_request.sub_proof_requests { credential_schema_builder = CryptoIssuer::new_credential_schema_builder().map_err(|e| { format!("could not create new credential schema builder; {}", &e) })?; for property in credential_schemas .get(&sub_proof_request.schema) .ok_or("could not get credential schema for sub proof request")? .properties .keys() { credential_schema_builder .add_attr(property) .map_err(|e| format!("could not add credential schema; {}", &e))?; } sub_proof_request_builder = CryptoVerifier::new_sub_proof_request_builder() .map_err(|e| format!("could not create sub proof request builder; {}", &e))?; for property in &sub_proof_request.revealed_attributes { sub_proof_request_builder .add_revealed_attr(&property) .map_err(|e| { format!( "could not add revealed attribute to sub proof request; {}", &e ) })?; credential_schema_builder.add_attr(property).map_err(|e| { format!("could not add attribute to credential schema; {}", &e) })?; } let mut key: Option<RevocationKeyPublic> = None; let mut registry: Option<RevocationRegistry> = None; let reg_def = revocation_registry_definition .get(&sub_proof_request.schema) .ok_or("could not get sub proof request schema from revocation registry def")?; if reg_def.is_some() { key = Some( reg_def .as_ref() .ok_or("could not get registry registry definition reference")? .revocation_public_key .clone(), ); registry = Some(serde_json::from_str(&serde_json::to_string( &reg_def .as_ref() .ok_or("could not get registry definition as reference")? .registry, )?)?); } pub_key = &credential_definitions .get(&sub_proof_request.schema) .ok_or("could not get sub proof request schema")? .public_key; proof_verifier .add_sub_proof_request( &sub_proof_request_builder .finalize() .map_err(|e| format!("could not finalize sub proof request; {}", &e))?, &credential_schema_builder .finalize() .map_err(|e| format!("could not finalize credential schema; {}", &e))?, &non_credential_schema, &pub_key, key.as_ref(), registry.as_ref(), ) .map_err(|e| format!("could not add sub proof request; {}", &e))?; } // Create Ursa proof object let mut sub_proofs: Vec<SubProof> = Vec::new(); for vc in &presented_proof.verifiable_credential { sub_proofs.push(serde_json::from_str(&vc.proof.proof)?); } let serialized = format!( r###"{{ "proofs": {}, "aggregated_proof": {} }}"###, serde_json::to_string(&sub_proofs)?, &presented_proof.proof.aggregated_proof ); let ursa_proof: CryptoProof = serde_json::from_str(&serialized)?; if proof_verifier .verify(&ursa_proof, &presented_proof.proof.nonce) .map_err(|e| format!("could not verify proof; {}", &e))? { Ok(()) } else { Err(From::from("Proof verification failed")) } }
config_extractor.py
from __future__ import unicode_literals import logging from urllib import urlencode from urlparse import parse_qsl, urlparse, urlunparse def rewrite_location_header(name, value, params): """ Rewrite "Location" header to append params to the URL's query string. Returns other headers unmodified. :param name: HTTP header name :param value: HTTP header value :param params: dict of params to add to the URL's query string :return: Modified (name, value) pair """ if name.lower() != 'location': return (name, value) try: parsed_url = urlparse(value) parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True) for k, v in params.items(): parsed_query.append((k, v)) updated_query = urlencode(parsed_query) updated_url = urlunparse((parsed_url.scheme, parsed_url.netloc, parsed_url.path, parsed_url.params, updated_query, parsed_url.fragment))
return (name, updated_url) except Exception: logging.warn('Failed to parse "Location" header: {}'.format(value)) return (name, value) def pop_query_params_with_prefix(environ, prefix): """ Extract and remove query string parameters beginning with ``prefix``. :param environ: WSGI environ dict :param prefix: Prefix to match :return: A dict of query param / value pairs """ orig_qs = environ['QUERY_STRING'] parsed_query_items = parse_qsl(orig_qs, keep_blank_values=True) popped_params = {} updated_query_items = [] for key, value in parsed_query_items: if key.startswith(prefix): popped_params[key] = value else: updated_query_items.append((key, value)) updated_qs = urlencode(updated_query_items) environ['QUERY_STRING'] = updated_qs environ['REQUEST_URI'] = environ['REQUEST_URI'][:-len(orig_qs)] + updated_qs return popped_params class ConfigExtractor(object): """ WSGI middleware which extracts client configuration params from the URL. Client configuration is supplied via "via."-prefixed query parameters, which are removed from the URL passed along to the proxy server. These parameters are then used to populate the parameters exposed to rendered templates. This middleware also rewrites redirect responses from the upstream app to preserve "via."-prefixed parameters from the original request. Note that this only works for server-side redirects. Client-side redirects will still "lose" these parameters. """ def __init__(self, application): self._application = application def __call__(self, environ, start_response): template_params = environ.get('pywb.template_params', {}) via_params = pop_query_params_with_prefix(environ, 'via.') if 'via.request_config_from_frame' in via_params: template_params['h_request_config'] = via_params['via.request_config_from_frame'] if 'via.open_sidebar' in via_params: template_params['h_open_sidebar'] = True environ['pywb.template_params'] = template_params # A wrapper which intercepts redirects and adds any params from `via_params` # to the query string in the URL in the "Location" header. # # This ensures that client configuration is preserved if the user requests # a URL which immediately redirects. def start_response_wrapper(status, headers, exc_info=None): code_str, _ = status.split(' ', 1) code = int(code_str) if code >= 300 and code < 400: headers = [rewrite_location_header(k, v, via_params) for k, v in headers] return start_response(status, headers, exc_info) return self._application(environ, start_response_wrapper)
index.ts
export * from './multer-config.loader';
export * from './interfaces'; export * from './constants';
export * from './multer-extended.module'; export * from './interceptors';
app.js
import React from "react"; import { graphql } from "react-apollo"; import gql from "graphql-tag"; function
({ data: { ideas, refetch } }) { return ( <div> <button onClick={() => refetch()}>Refresh</button> <ul>{ideas && ideas.map(idea => <li key={idea.id}>{idea.text}</li>)}</ul> </div> ); } export default graphql(gql` query IdeaAppQuery { idea @live { id text } } `)(BrighterApp);
BrighterApp
lib.rs
extern crate napi; #[macro_use] extern crate napi_derive; #[cfg(target_os = "macos")] #[global_allocator] static GLOBAL: jemallocator::Jemalloc = jemallocator::Jemalloc; use napi::{CallContext, JsObject, JsString, Result}; #[js_function(3)] fn say_hello(ctx: CallContext) -> Result<JsString>
#[module_exports] fn init(mut exports: JsObject) -> Result<()> { exports.create_named_method("say_hello", say_hello)?; Ok(()) }
{ let name = ctx.get::<JsString>(0)?.into_utf8()?; let name = name.as_str()?; let s = ctx.env.create_string_from_std(format!("Hello, {}!", name))?; Ok(s) }
genSymbolImg.py
import cv2 import numpy as np from random import randint, uniform import string, random def
(image): row,col = image.shape s_vs_p = 0.4 amount = 0.01 out = np.copy(image) # Salt mode num_salt = np.ceil(amount * image.size * s_vs_p) coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape] out[tuple(coords)] = 1 # Pepper mode num_pepper = np.ceil(amount* image.size * (1. - s_vs_p)) coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape] out[tuple(coords)] = 0 return out # def addLines(img): # for i in range(randint(0,2)): # y1 = randint(0, img.shape[0]) # y2 = randint(0, img.shape[0]) # cv2.line(img, (0, y1), (img.shape[1], y2), 0, 1) def addBlur(img, kw, kh): return cv2.blur(img, (kw, kh)) def text_generator(chars, size = 8): return ''.join(random.choice(chars) for _ in range(size)) def addText(img, chars, font, size, line_size): text = text_generator(chars, 1) cv2.putText(img, text, (0, img.shape[0]-4), font, size, (0, 0, 255), line_size, cv2.LINE_AA) return text sizes = [(70,58),(40,35),(75,70),(70,70),(70,70),(50,50)] def genSymbolImg(chars = string.ascii_uppercase + string.digits, font = None, line_size = None, blur = None, kw = None, kh = None): if font is None: font = randint(0, 5) # if size is None: # size = uniform(2.5, 3.5) if line_size is None: line_size = randint(1, 3) if blur is None: blur = randint(0, 1) if kw is None: kw = randint(3, 9) if kh is None: kh = randint(3, 9) genImg = np.full(sizes[font], 255, dtype= np.uint8) text = addText(genImg, chars, font, 3, line_size) if randint(0, 1): genImg = addNoise(genImg) # if lines: # addLines(genImg) if blur: genImg = addBlur(genImg, kw, kh) return genImg, text if __name__ == '__main__': for i in xrange(10000): img, text = genSymbolImg(kw = 5, kh = 5, blur = 1) print(text) cv2.imshow("W", img) k = cv2.waitKey(0) if k == 27: break
addNoise
test_RDSMultiAZEnabled.py
import os import unittest from checkov.cloudformation.checks.resource.aws.RDSMultiAZEnabled import check from checkov.cloudformation.runner import Runner from checkov.runner_filter import RunnerFilter class TestRDSMultiAZEnabled(unittest.TestCase):
if __name__ == '__main__': unittest.main()
def test_summary(self): runner = Runner() current_dir = os.path.dirname(os.path.realpath(__file__)) test_files_dir = current_dir + "/example_RDSMultiAZEnabled" report = runner.run(root_folder=test_files_dir, runner_filter=RunnerFilter(checks=[check.id])) summary = report.get_summary() passing_resources = { "AWS::RDS::DBInstance.MyDBEnabled", } failing_resources = { "AWS::RDS::DBInstance.MyDBDefault", "AWS::RDS::DBInstance.MyDBDisabled", } passed_check_resources = set([c.resource for c in report.passed_checks]) failed_check_resources = set([c.resource for c in report.failed_checks]) self.assertEqual(summary['passed'], 1) self.assertEqual(summary['failed'], 2) self.assertEqual(summary['skipped'], 0) self.assertEqual(summary['parsing_errors'], 0) self.assertEqual(passing_resources, passed_check_resources) self.assertEqual(failing_resources, failed_check_resources)
requestOptions.js
"use strict"; var assign = require('object-assign'); var projectHeader = 'X-Sanity-Project-ID'; module.exports = function (config) { var overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var headers = {}; var token = overrides.token || config.token; if (token) { headers.Authorization = "Bearer ".concat(token); } if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) { headers[projectHeader] = config.projectId; } var withCredentials = Boolean(typeof overrides.withCredentials === 'undefined' ? config.token || config.withCredentials : overrides.withCredentials); var timeout = typeof overrides.timeout === 'undefined' ? config.timeout : overrides.timeout; return assign({}, overrides, { headers: assign({}, headers, overrides.headers || {}), timeout: typeof timeout === 'undefined' ? 5 * 60 * 1000 : timeout,
};
json: true, withCredentials: withCredentials });
server.rs
// Copyright 2016 Mozilla Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::cache::{storage_from_config, Storage}; use crate::compiler::{ get_compiler_info, CacheControl, CompileResult, Compiler, CompilerArguments, CompilerHasher, CompilerKind, CompilerProxy, DistType, MissType, }; #[cfg(feature = "dist-client")] use crate::config; use crate::config::Config; use crate::dist; use crate::jobserver::Client; use crate::mock_command::{CommandCreatorSync, ProcessCommandCreator}; use crate::protocol::{Compile, CompileFinished, CompileResponse, Request, Response}; use crate::util; use crate::util::fs::metadata; #[cfg(feature = "dist-client")] use anyhow::Context as _; use bytes::{buf::ext::BufMutExt, Bytes, BytesMut}; use filetime::FileTime; use futures::channel::mpsc; use futures::future::FutureExt; use futures::{future, stream, Sink, SinkExt, Stream, StreamExt, TryFutureExt}; use futures_locks::RwLock; use number_prefix::NumberPrefix; use std::collections::HashMap; use std::env; use std::ffi::{OsStr, OsString}; use std::future::Future; use std::io::{self, Write}; use std::marker::Unpin; #[cfg(feature = "dist-client")] use std::mem; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use std::path::PathBuf; use std::pin::Pin; use std::process::{ExitStatus, Output}; use std::sync::Arc; use std::sync::Mutex; use std::task::{Context, Poll, Waker}; use std::time::Duration; #[cfg(feature = "dist-client")] use std::time::Instant; use std::u64; use tokio::runtime::Runtime; use tokio::{ io::{AsyncRead, AsyncWrite}, net::TcpListener, time::{self, delay_for, Delay}, }; use tokio_serde::Framed; use tokio_util::codec::{length_delimited, LengthDelimitedCodec}; use tower::Service; use crate::errors::*; /// If the server is idle for this many seconds, shut down. const DEFAULT_IDLE_TIMEOUT: u64 = 600; /// If the dist client couldn't be created, retry creation at this number /// of seconds from now (or later) #[cfg(feature = "dist-client")] const DIST_CLIENT_RECREATE_TIMEOUT: Duration = Duration::from_secs(30); /// Result of background server startup. #[derive(Debug, Serialize, Deserialize)] pub enum ServerStartup { /// Server started successfully on `port`. Ok { port: u16 }, /// Server Addr already in suse AddrInUse, /// Timed out waiting for server startup. TimedOut, /// Server encountered an error. Err { reason: String }, } /// Get the time the server should idle for before shutting down. fn get_idle_timeout() -> u64 { // A value of 0 disables idle shutdown entirely. env::var("SCCACHE_IDLE_TIMEOUT") .ok() .and_then(|s| s.parse().ok()) .unwrap_or(DEFAULT_IDLE_TIMEOUT) } fn notify_server_startup_internal<W: Write>(mut w: W, status: ServerStartup) -> Result<()> { util::write_length_prefixed_bincode(&mut w, status) } #[cfg(unix)] fn notify_server_startup(name: &Option<OsString>, status: ServerStartup) -> Result<()> { use std::os::unix::net::UnixStream; let name = match *name { Some(ref s) => s, None => return Ok(()), }; debug!("notify_server_startup({:?})", status); let stream = UnixStream::connect(name)?; notify_server_startup_internal(stream, status) } #[cfg(windows)] fn notify_server_startup(name: &Option<OsString>, status: ServerStartup) -> Result<()> { use crate::util::fs::OpenOptions; let name = match *name { Some(ref s) => s, None => return Ok(()), }; let pipe = OpenOptions::new().write(true).read(true).open(name)?; notify_server_startup_internal(pipe, status) } #[cfg(unix)] fn get_signal(status: ExitStatus) -> i32 { use std::os::unix::prelude::*; status.signal().expect("must have signal") } #[cfg(windows)] fn get_signal(_status: ExitStatus) -> i32 { panic!("no signals on windows") } pub struct DistClientContainer { // The actual dist client state #[cfg(feature = "dist-client")] state: Mutex<DistClientState>, } #[cfg(feature = "dist-client")] struct DistClientConfig { // Reusable items tied to an SccacheServer instance pool: tokio::runtime::Handle, // From the static dist configuration scheduler_url: Option<config::HTTPUrl>, auth: config::DistAuth, cache_dir: PathBuf, toolchain_cache_size: u64, toolchains: Vec<config::DistToolchainConfig>, rewrite_includes_only: bool, } #[cfg(feature = "dist-client")] enum DistClientState { #[cfg(feature = "dist-client")] Some(Box<DistClientConfig>, Arc<dyn dist::Client>), #[cfg(feature = "dist-client")] FailWithMessage(Box<DistClientConfig>, String), #[cfg(feature = "dist-client")] RetryCreateAt(Box<DistClientConfig>, Instant), Disabled, } #[cfg(not(feature = "dist-client"))] impl DistClientContainer { #[cfg(not(feature = "dist-client"))] fn new(config: &Config, _: &tokio::runtime::Handle) -> Self { if config.dist.scheduler_url.is_some() { warn!("Scheduler address configured but dist feature disabled, disabling distributed sccache") } Self {} } pub fn new_disabled() -> Self { Self {} } pub fn reset_state(&self) {} pub async fn get_status(&self) -> DistInfo { DistInfo::Disabled("dist-client feature not selected".to_string()) } fn get_client(&self) -> Result<Option<Arc<dyn dist::Client>>> { Ok(None) } } #[cfg(feature = "dist-client")] impl DistClientContainer { fn new(config: &Config, pool: &tokio::runtime::Handle) -> Self { let config = DistClientConfig { pool: pool.clone(), scheduler_url: config.dist.scheduler_url.clone(), auth: config.dist.auth.clone(), cache_dir: config.dist.cache_dir.clone(), toolchain_cache_size: config.dist.toolchain_cache_size, toolchains: config.dist.toolchains.clone(), rewrite_includes_only: config.dist.rewrite_includes_only, }; let state = Self::create_state(config); Self { state: Mutex::new(state), } } pub fn new_disabled() -> Self { Self { state: Mutex::new(DistClientState::Disabled), } } pub fn reset_state(&self) { let mut guard = self.state.lock(); let state = guard.as_mut().unwrap(); let state: &mut DistClientState = &mut **state; match mem::replace(state, DistClientState::Disabled) { DistClientState::Some(cfg, _) | DistClientState::FailWithMessage(cfg, _) | DistClientState::RetryCreateAt(cfg, _) => { warn!("State reset. Will recreate"); *state = DistClientState::RetryCreateAt(cfg, Instant::now() - Duration::from_secs(1)); } DistClientState::Disabled => (), } } pub fn get_status(&self) -> impl Future<Output = DistInfo> { // This function can't be wholly async because we can't hold mutex guard // across the yield point - instead, either return an immediately ready // future or perform async query with the client cloned beforehand. let mut guard = self.state.lock(); let state = guard.as_mut().unwrap(); let state: &mut DistClientState = &mut **state; let (client, scheduler_url) = match state { DistClientState::Disabled => { return Either::Left(future::ready(DistInfo::Disabled("disabled".to_string()))) } DistClientState::FailWithMessage(cfg, _) => { return Either::Left(future::ready(DistInfo::NotConnected( cfg.scheduler_url.clone(), "enabled, auth not configured".to_string(), ))) } DistClientState::RetryCreateAt(cfg, _) => { return Either::Left(future::ready(DistInfo::NotConnected( cfg.scheduler_url.clone(), "enabled, not connected, will retry".to_string(), ))) } DistClientState::Some(cfg, client) => (Arc::clone(client), cfg.scheduler_url.clone()), }; Either::Right(Box::pin(async move { match client.do_get_status().await { Ok(res) => DistInfo::SchedulerStatus(scheduler_url.clone(), res), Err(_) => DistInfo::NotConnected( scheduler_url.clone(), "could not communicate with scheduler".to_string(), ), } })) } fn get_client(&self) -> Result<Option<Arc<dyn dist::Client>>> { let mut guard = self.state.lock(); let state = guard.as_mut().unwrap(); let state: &mut DistClientState = &mut **state; Self::maybe_recreate_state(state); let res = match state { DistClientState::Some(_, dc) => Ok(Some(dc.clone())), DistClientState::Disabled | DistClientState::RetryCreateAt(_, _) => Ok(None), DistClientState::FailWithMessage(_, msg) => Err(anyhow!(msg.clone())), }; if res.is_err() { let config = match mem::replace(state, DistClientState::Disabled) { DistClientState::FailWithMessage(config, _) => config, _ => unreachable!(), }; // The client is most likely mis-configured, make sure we // re-create on our next attempt. *state = DistClientState::RetryCreateAt(config, Instant::now() - Duration::from_secs(1)); } res } fn maybe_recreate_state(state: &mut DistClientState) { if let DistClientState::RetryCreateAt(_, instant) = *state { if instant > Instant::now() { return; } let config = match mem::replace(state, DistClientState::Disabled) { DistClientState::RetryCreateAt(config, _) => config, _ => unreachable!(), }; info!("Attempting to recreate the dist client"); *state = Self::create_state(*config) } } // Attempt to recreate the dist client fn create_state(config: DistClientConfig) -> DistClientState { macro_rules! try_or_retry_later { ($v:expr) => {{ match $v { Ok(v) => v, Err(e) => { // `{:?}` prints the full cause chain and backtrace. error!("{:?}", e); return DistClientState::RetryCreateAt( Box::new(config), Instant::now() + DIST_CLIENT_RECREATE_TIMEOUT, ); } } }}; } macro_rules! try_or_fail_with_message { ($v:expr) => {{ match $v { Ok(v) => v, Err(e) => { // `{:?}` prints the full cause chain and backtrace. let errmsg = format!("{:?}", e); error!("{}", errmsg); return DistClientState::FailWithMessage( Box::new(config), errmsg.to_string(), ); } } }}; } match config.scheduler_url { Some(ref addr) => { let url = addr.to_url(); info!("Enabling distributed sccache to {}", url); let auth_token = match &config.auth { config::DistAuth::Token { token } => Ok(token.to_owned()), config::DistAuth::Oauth2CodeGrantPKCE { auth_url, .. } | config::DistAuth::Oauth2Implicit { auth_url, .. } => { Self::get_cached_config_auth_token(auth_url) } }; let auth_token = try_or_fail_with_message!(auth_token .context("could not load client auth token, run |sccache --dist-auth|")); let dist_client = dist::http::Client::new( &config.pool, url, &config.cache_dir.join("client"), config.toolchain_cache_size, &config.toolchains, auth_token, config.rewrite_includes_only, ); let dist_client = try_or_retry_later!(dist_client.context("failure during dist client creation")); use crate::dist::Client; match config.pool.block_on(dist_client.do_get_status()) { Ok(res) => { info!( "Successfully created dist client with {:?} cores across {:?} servers", res.num_cpus, res.num_servers ); DistClientState::Some(Box::new(config), Arc::new(dist_client)) } Err(_) => { warn!("Scheduler address configured, but could not communicate with scheduler"); DistClientState::RetryCreateAt( Box::new(config), Instant::now() + DIST_CLIENT_RECREATE_TIMEOUT, ) } } } None => { info!("No scheduler address configured, disabling distributed sccache"); DistClientState::Disabled } } } fn get_cached_config_auth_token(auth_url: &str) -> Result<String> { let cached_config = config::CachedConfig::reload()?; cached_config .with(|c| c.dist.auth_tokens.get(auth_url).map(String::to_owned)) .with_context(|| format!("token for url {} not present in cached config", auth_url)) } } /// Start an sccache server, listening on `port`. /// /// Spins an event loop handling client connections until a client /// requests a shutdown. pub fn start_server(config: &Config, port: u16) -> Result<()> { info!("start_server: port: {}", port); let client = unsafe { Client::new() }; let runtime = tokio::runtime::Builder::new() .enable_all() .threaded_scheduler() .core_threads(std::cmp::max(20, 2 * num_cpus::get())) .build()?; let pool = runtime.handle().clone(); let dist_client = DistClientContainer::new(config, &pool); let storage = storage_from_config(config, &pool); let res = SccacheServer::<ProcessCommandCreator>::new(port, runtime, client, dist_client, storage); let notify = env::var_os("SCCACHE_STARTUP_NOTIFY"); match res { Ok(srv) => { let port = srv.port(); info!("server started, listening on port {}", port); notify_server_startup(&notify, ServerStartup::Ok { port })?; srv.run(future::pending::<()>())?; Ok(()) } Err(e) => { error!("failed to start server: {}", e); match e.downcast_ref::<io::Error>() { Some(io_err) if io::ErrorKind::AddrInUse == io_err.kind() => { notify_server_startup(&notify, ServerStartup::AddrInUse)?; } _ => { let reason = e.to_string(); notify_server_startup(&notify, ServerStartup::Err { reason })?; } }; Err(e) } } } pub struct SccacheServer<C: CommandCreatorSync> { runtime: Runtime, listener: TcpListener, rx: mpsc::Receiver<ServerMessage>, timeout: Duration, service: SccacheService<C>, wait: WaitUntilZero, } impl<C: CommandCreatorSync> SccacheServer<C> { pub fn new( port: u16, mut runtime: Runtime, client: Client, dist_client: DistClientContainer, storage: Arc<dyn Storage>, ) -> Result<SccacheServer<C>> { let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port); let listener = runtime.block_on(TcpListener::bind(&SocketAddr::V4(addr)))?; // Prepare the service which we'll use to service all incoming TCP // connections. let (tx, rx) = mpsc::channel(1); let (wait, info) = WaitUntilZero::new(); let pool = runtime.handle().clone(); let service = SccacheService::new(dist_client, storage, &client, pool, tx, info); Ok(SccacheServer { runtime, listener, rx, service, timeout: Duration::from_secs(get_idle_timeout()), wait, }) } /// Configures how long this server will be idle before shutting down. #[allow(dead_code)] pub fn set_idle_timeout(&mut self, timeout: Duration) { self.timeout = timeout; } /// Set the storage this server will use. #[allow(dead_code)] pub fn set_storage(&mut self, storage: Arc<dyn Storage>) { self.service.storage = storage; }
#[allow(dead_code)] pub fn pool(&self) -> &tokio::runtime::Handle { &self.service.rt } /// Returns a reference to the command creator this server will use #[allow(dead_code)] pub fn command_creator(&self) -> &C { &self.service.creator } /// Returns the port that this server is bound to #[allow(dead_code)] pub fn port(&self) -> u16 { self.listener.local_addr().unwrap().port() } /// Runs this server to completion. /// /// If the `shutdown` future resolves then the server will be shut down, /// otherwise the server may naturally shut down if it becomes idle for too /// long anyway. pub fn run<F>(self, shutdown: F) -> io::Result<()> where F: Future, C: Send, { let SccacheServer { mut runtime, listener, rx, service, timeout, wait, } = self; // Create our "server future" which will simply handle all incoming // connections in separate tasks. let server = listener.try_for_each(move |socket| { trace!("incoming connection"); let conn = service.clone().bind(socket).map_err(|res| { error!("Failed to bind socket: {}", res); }); // We're not interested if the task panicked; immediately process // another connection let _ = tokio::spawn(conn); async { Ok(()) } }); // Right now there's a whole bunch of ways to shut down this server for // various purposes. These include: // // 1. The `shutdown` future above. // 2. An RPC indicating the server should shut down // 3. A period of inactivity (no requests serviced) // // These are all encapsulated wih the future that we're creating below. // The `ShutdownOrInactive` indicates the RPC or the period of // inactivity, and this is then select'd with the `shutdown` future // passed to this function. let shutdown = shutdown.map(|_| { info!("shutting down due to explicit signal"); }); let shutdown_idle = async { ShutdownOrInactive { rx, timeout: if timeout != Duration::new(0, 0) { Some(delay_for(timeout)) } else { None }, timeout_dur: timeout, } .await; info!("shutting down due to being idle or request"); }; runtime.block_on(async { futures::select! { server = server.fuse() => server, _res = shutdown.fuse() => Ok(()), _res = shutdown_idle.fuse() => Ok(()), } })?; const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); info!( "moving into the shutdown phase now, waiting at most {} seconds \ for all client requests to complete", SHUTDOWN_TIMEOUT.as_secs() ); // Once our server has shut down either due to inactivity or a manual // request we still need to give a bit of time for all active // connections to finish. This `wait` future will resolve once all // instances of `SccacheService` have been dropped. // // Note that we cap the amount of time this can take, however, as we // don't want to wait *too* long. runtime.block_on(async { time::timeout(SHUTDOWN_TIMEOUT, wait).await })?; info!("ok, fully shutting down now"); Ok(()) } } /// Maps a compiler proxy path to a compiler proxy and its last modification time type CompilerProxyMap<C> = HashMap<PathBuf, (Box<dyn CompilerProxy<C>>, FileTime)>; /// Maps a compiler path to a compiler cache entry type CompilerMap<C> = HashMap<PathBuf, Option<CompilerCacheEntry<C>>>; /// entry of the compiler cache struct CompilerCacheEntry<C> { /// compiler argument trait obj pub compiler: Box<dyn Compiler<C>>, /// modification time of the compilers executable file pub mtime: FileTime, /// distributed compilation extra info pub dist_info: Option<(PathBuf, FileTime)>, } impl<C> CompilerCacheEntry<C> { fn new( compiler: Box<dyn Compiler<C>>, mtime: FileTime, dist_info: Option<(PathBuf, FileTime)>, ) -> Self { Self { compiler, mtime, dist_info, } } } /// Service implementation for sccache #[derive(Clone)] struct SccacheService<C> where C: Send, { /// Server statistics. stats: Arc<RwLock<ServerStats>>, /// Distributed sccache client dist_client: Arc<DistClientContainer>, /// Cache storage. storage: Arc<dyn Storage>, /// A cache of known compiler info. compilers: Arc<RwLock<CompilerMap<C>>>, /// map the cwd with compiler proxy path to a proxy resolver, which /// will dynamically resolve the input compiler for the current context /// (usually file or current working directory) /// the associated `FileTime` is the modification time of /// the compiler proxy, in order to track updates of the proxy itself compiler_proxies: Arc<RwLock<CompilerProxyMap<C>>>, /// Task pool for blocking (used mostly for disk I/O-bound tasks) and // non-blocking tasks rt: tokio::runtime::Handle, /// An object for creating commands. /// /// This is mostly useful for unit testing, where we /// can mock this out. creator: C, /// Message channel used to learn about requests received by this server. /// /// Note that messages sent along this channel will keep the server alive /// (reset the idle timer) and this channel can also be used to shut down /// the entire server immediately via a message. tx: mpsc::Sender<ServerMessage>, /// Information tracking how many services (connected clients) are active. info: ActiveInfo, } type SccacheRequest = Message<Request, Body<()>>; type SccacheResponse = Message<Response, Body<Response>>; /// Messages sent from all services to the main event loop indicating activity. /// /// Whenever a request is receive a `Request` message is sent which will reset /// the idle shutdown timer, and otherwise a `Shutdown` message indicates that /// a server shutdown was requested via an RPC. pub enum ServerMessage { /// A message sent whenever a request is received. Request, /// Message sent whenever a shutdown request is received. Shutdown, } impl<C> Service<SccacheRequest> for Arc<SccacheService<C>> where C: CommandCreatorSync + Send + Sync + 'static, { type Response = SccacheResponse; type Error = Error; type Future = Pin<Box<dyn Future<Output = Result<Self::Response>> + Send + 'static>>; fn call(&mut self, req: SccacheRequest) -> Self::Future { trace!("handle_client"); // Opportunistically let channel know that we've received a request. We // ignore failures here as well as backpressure as it's not imperative // that every message is received. drop(self.tx.clone().start_send(ServerMessage::Request)); let me = self.clone(); Box::pin(async move { match req.into_inner() { Request::Compile(compile) => { debug!("handle_client: compile"); me.stats.write().await.compile_requests += 1; me.handle_compile(compile).await } Request::GetStats => { debug!("handle_client: get_stats"); me.get_info() .await .map(|i| Response::Stats(Box::new(i))) .map(Message::WithoutBody) } Request::DistStatus => { debug!("handle_client: dist_status"); me.get_dist_status() .await .map(Response::DistStatus) .map(Message::WithoutBody) } Request::ZeroStats => { debug!("handle_client: zero_stats"); me.zero_stats().await; me.get_info() .await .map(|i| Response::Stats(Box::new(i))) .map(Message::WithoutBody) } Request::Shutdown => { debug!("handle_client: shutdown"); let mut tx = me.tx.clone(); future::try_join( async { let _ = tx.send(ServerMessage::Shutdown).await; Ok(()) }, me.get_info(), ) .await .map(move |(_, info)| { Message::WithoutBody(Response::ShuttingDown(Box::new(info))) }) } } }) } fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<()>> { Poll::Ready(Ok(())) } } use futures::future::Either; use futures::TryStreamExt; impl<C> SccacheService<C> where C: CommandCreatorSync + Clone + Send + Sync + 'static, { pub fn new( dist_client: DistClientContainer, storage: Arc<dyn Storage>, client: &Client, rt: tokio::runtime::Handle, tx: mpsc::Sender<ServerMessage>, info: ActiveInfo, ) -> SccacheService<C> { SccacheService { stats: Arc::new(RwLock::new(ServerStats::default())), dist_client: Arc::new(dist_client), storage, compilers: Arc::new(RwLock::new(HashMap::new())), compiler_proxies: Arc::new(RwLock::new(HashMap::new())), rt, creator: C::new(client), tx, info, } } fn bind<T>(self, socket: T) -> impl Future<Output = Result<()>> + Send + Sized + 'static where T: AsyncRead + AsyncWrite + Unpin + Send + 'static, { let mut builder = length_delimited::Builder::new(); if let Ok(max_frame_length_str) = env::var("SCCACHE_MAX_FRAME_LENGTH") { if let Ok(max_frame_length) = max_frame_length_str.parse::<usize>() { builder.max_frame_length(max_frame_length); } else { warn!("Content of SCCACHE_MAX_FRAME_LENGTH is not a valid number, using default"); } } let io = builder.new_framed(socket); let (sink, stream) = SccacheTransport { inner: Framed::new(io.sink_err_into().err_into(), BincodeCodec), } .split(); let sink = sink.sink_err_into::<Error>(); let me = Arc::new(self); stream .err_into::<Error>() .and_then(move |input| me.clone().call(input)) .and_then(move |message| async move { let fut = match message { Message::WithoutBody(message) => { let stream = stream::once(async move { Ok(Frame::Message { message }) }); Either::Left(stream) } Message::WithBody(message, body) => { let stream = stream::once(async move { Ok(Frame::Message { message }) }) .chain(body.map_ok(|chunk| Frame::Body { chunk: Some(chunk) })) .chain(stream::once(async move { Ok(Frame::Body { chunk: None }) })); Either::Right(stream) } }; Ok(Box::pin(fut)) }) .try_flatten() .forward(sink) } /// Get dist status. async fn get_dist_status(&self) -> Result<DistInfo> { Ok(self.dist_client.get_status().await) } /// Get info and stats about the cache. async fn get_info(&self) -> Result<ServerInfo> { let stats = self.stats.read().await.clone(); let cache_location = self.storage.location(); futures::try_join!(self.storage.current_size(), self.storage.max_size()).map( move |(cache_size, max_cache_size)| ServerInfo { stats, cache_location, cache_size, max_cache_size, }, ) } /// Zero stats about the cache. async fn zero_stats(&self) { *self.stats.write().await = ServerStats::default(); } /// Handle a compile request from a client. /// /// This will handle a compile request entirely, generating a response with /// the inital information and an optional body which will eventually /// contain the results of the compilation. async fn handle_compile(&self, compile: Compile) -> Result<SccacheResponse> { let exe = compile.exe; let cmd = compile.args; let cwd: PathBuf = compile.cwd.into(); let env_vars = compile.env_vars; let me = self.clone(); let info = self.compiler_info(exe.into(), cwd.clone(), &env_vars).await; Ok(me.check_compiler(info, cmd, cwd, env_vars).await) } /// Look up compiler info from the cache for the compiler `path`. /// If not cached, determine the compiler type and cache the result. async fn compiler_info( &self, path: PathBuf, cwd: PathBuf, env: &[(OsString, OsString)], ) -> Result<Box<dyn Compiler<C>>> { trace!("compiler_info"); let me = self.clone(); let me1 = self.clone(); // lookup if compiler proxy exists for the current compiler path let path2 = path.clone(); let path1 = path.clone(); let env = env.to_vec(); let resolved_with_proxy = { let compiler_proxies_borrow = self.compiler_proxies.read().await; // Create an owned future - compiler proxy is not Send so we can't // really await while borrowing the proxy since rustc is too conservative let resolve_proxied_executable = compiler_proxies_borrow .get(&path) .map(|(compiler_proxy, _filetime)| { compiler_proxy.resolve_proxied_executable( self.creator.clone(), cwd.clone(), env.as_slice(), ) }); match resolve_proxied_executable { Some(fut) => fut.await.ok(), None => None, } }; // use the supplied compiler path as fallback, lookup its modification time too let (resolved_compiler_path, mtime) = match resolved_with_proxy { Some(x) => x, // TODO resolve the path right away _ => { // fallback to using the path directly metadata(&path2) .map(|attr| FileTime::from_last_modification_time(&attr)) .ok() .map(move |filetime| (path2, filetime)) .expect("Must contain sane data, otherwise mtime is not avail") } }; let dist_info = match me1.dist_client.get_client() { Ok(Some(ref client)) => { if let Some(archive) = client.get_custom_toolchain(&resolved_compiler_path) { match metadata(&archive) .map(|attr| FileTime::from_last_modification_time(&attr)) { Ok(mtime) => Some((archive, mtime)), _ => None, } } else { None } } _ => None, }; let opt = match me1.compilers.read().await.get(&resolved_compiler_path) { // It's a hit only if the mtime and dist archive data matches. Some(&Some(ref entry)) => { if entry.mtime == mtime && entry.dist_info == dist_info { Some(entry.compiler.box_clone()) } else { None } } _ => None, }; match opt { Some(info) => { trace!("compiler_info cache hit"); Ok(info) } None => { trace!("compiler_info cache miss"); // Check the compiler type and return the result when // finished. This generally involves invoking the compiler, // so do it asynchronously. // the compiler path might be compiler proxy, so it is important to use // `path` (or its clone `path1`) to resolve using that one, not using `resolved_compiler_path` let info = get_compiler_info::<C>( me.creator.clone(), &path1, &cwd, env.as_slice(), &me.rt, dist_info.clone().map(|(p, _)| p), ) .await; let (c, proxy) = match info { Ok((c, proxy)) => (c.clone(), proxy.clone()), Err(err) => { trace!("Inserting PLAIN cache map info for {:?}", &path); me.compilers.write().await.insert(path, None); return Err(err); } }; // register the proxy for this compiler, so it will be used directly from now on // and the true/resolved compiler will create table hits in the hash map // based on the resolved path if let Some(proxy) = proxy { trace!( "Inserting new path proxy {:?} @ {:?} -> {:?}", &path, &cwd, resolved_compiler_path ); me.compiler_proxies .write() .await .insert(path, (proxy, mtime)); } // TODO add some safety checks in case a proxy exists, that the initial `path` is not // TODO the same as the resolved compiler binary // cache let map_info = CompilerCacheEntry::new(c.clone(), mtime, dist_info); trace!( "Inserting POSSIBLY PROXIED cache map info for {:?}", &resolved_compiler_path ); me.compilers .write() .await .insert(resolved_compiler_path, Some(map_info)); // drop the proxy information, response is compiler only Ok(c) } } } /// Check that we can handle and cache `cmd` when run with `compiler`. /// If so, run `start_compile_task` to execute it. async fn check_compiler( &self, compiler: Result<Box<dyn Compiler<C>>>, cmd: Vec<OsString>, cwd: PathBuf, env_vars: Vec<(OsString, OsString)>, ) -> SccacheResponse { let mut stats = self.stats.write().await; match compiler { Err(e) => { debug!("check_compiler: Unsupported compiler: {}", e.to_string()); stats.requests_unsupported_compiler += 1; return Message::WithoutBody(Response::Compile( CompileResponse::UnsupportedCompiler(OsString::from(e.to_string())), )); } Ok(c) => { debug!("check_compiler: Supported compiler"); // Now check that we can handle this compiler with // the provided commandline. match c.parse_arguments(&cmd, &cwd) { CompilerArguments::Ok(hasher) => { debug!("parse_arguments: Ok: {:?}", cmd); stats.requests_executed += 1; let (tx, rx) = Body::pair(); self.start_compile_task(c, hasher, cmd, cwd, env_vars, tx); let res = CompileResponse::CompileStarted; return Message::WithBody(Response::Compile(res), rx); } CompilerArguments::CannotCache(why, extra_info) => { if let Some(extra_info) = extra_info { debug!( "parse_arguments: CannotCache({}, {}): {:?}", why, extra_info, cmd ) } else { debug!("parse_arguments: CannotCache({}): {:?}", why, cmd) } stats.requests_not_cacheable += 1; *stats.not_cached.entry(why.to_string()).or_insert(0) += 1; } CompilerArguments::NotCompilation => { debug!("parse_arguments: NotCompilation: {:?}", cmd); stats.requests_not_compile += 1; } } } } let res = CompileResponse::UnhandledCompile; Message::WithoutBody(Response::Compile(res)) } /// Given compiler arguments `arguments`, look up /// a compile result in the cache or execute the compilation and store /// the result in the cache. fn start_compile_task( &self, compiler: Box<dyn Compiler<C>>, hasher: Box<dyn CompilerHasher<C>>, arguments: Vec<OsString>, cwd: PathBuf, env_vars: Vec<(OsString, OsString)>, mut tx: mpsc::Sender<Result<Response>>, ) { let force_recache = env_vars .iter() .any(|&(ref k, ref _v)| k.as_os_str() == OsStr::new("SCCACHE_RECACHE")); let cache_control = if force_recache { CacheControl::ForceRecache } else { CacheControl::Default }; let out_pretty = hasher.output_pretty().into_owned(); let color_mode = hasher.color_mode(); let me = self.clone(); let kind = compiler.kind(); let dist_client = self.dist_client.get_client(); let creator = self.creator.clone(); let storage = self.storage.clone(); let pool = self.rt.clone(); let task = async move { let result = match dist_client { Ok(client) => { hasher .get_cached_or_compile( client, creator, storage, arguments, cwd, env_vars, cache_control, pool, ) .await } Err(e) => Err(e), }; let mut cache_write = None; let mut res = CompileFinished { color_mode, ..Default::default() }; match result { Ok((compiled, out)) => { let mut stats = me.stats.write().await; match compiled { CompileResult::Error => { stats.cache_errors.increment(&kind); } CompileResult::CacheHit(duration) => { stats.cache_hits.increment(&kind); stats.cache_read_hit_duration += duration; } CompileResult::CacheMiss(miss_type, dist_type, duration, future) => { match dist_type { DistType::NoDist => {} DistType::Ok(id) => { let server = id.addr().to_string(); let server_count = stats.dist_compiles.entry(server).or_insert(0); *server_count += 1; } DistType::Error => stats.dist_errors += 1, } match miss_type { MissType::Normal => {} MissType::ForcedRecache => { stats.forced_recaches += 1; } MissType::TimedOut => { stats.cache_timeouts += 1; } MissType::CacheReadError => { stats.cache_errors.increment(&kind); } } stats.cache_misses.increment(&kind); stats.cache_read_miss_duration += duration; cache_write = Some(future); } CompileResult::NotCacheable => { stats.cache_misses.increment(&kind); stats.non_cacheable_compilations += 1; } CompileResult::CompileFailed => { stats.compile_fails += 1; } }; let Output { status, stdout, stderr, } = out; trace!("CompileFinished retcode: {}", status); match status.code() { Some(code) => res.retcode = Some(code), None => res.signal = Some(get_signal(status)), }; res.stdout = stdout; res.stderr = stderr; } Err(err) => { let mut stats = me.stats.write().await; match err.downcast::<ProcessError>() { Ok(ProcessError(output)) => { debug!("Compilation failed: {:?}", output); stats.compile_fails += 1; match output.status.code() { Some(code) => res.retcode = Some(code), None => res.signal = Some(get_signal(output.status)), }; res.stdout = output.stdout; res.stderr = output.stderr; } Err(err) => match err.downcast::<HttpClientError>() { Ok(HttpClientError(msg)) => { me.dist_client.reset_state(); let errmsg = format!("[{:?}] http error status: {}", out_pretty, msg); error!("{}", errmsg); res.retcode = Some(1); res.stderr = errmsg.as_bytes().to_vec(); } Err(err) => { use std::fmt::Write; error!("[{:?}] fatal error: {}", out_pretty, err); let mut error = "sccache: encountered fatal error\n".to_string(); let _ = writeln!(error, "sccache: error: {}", err); for e in err.chain() { error!("[{:?}] \t{}", out_pretty, e); let _ = writeln!(error, "sccache: caused by: {}", e); } stats.cache_errors.increment(&kind); //TODO: figure out a better way to communicate this? res.retcode = Some(-2); res.stderr = error.into_bytes(); } }, } } }; let send = tx .send(Ok(Response::CompileFinished(res))) .map_err(|e| anyhow!("send on finish failed").context(e)); let me = me.clone(); let cache_write = async move { if let Some(cache_write) = cache_write { match cache_write.await { Err(e) => { debug!("Error executing cache write: {}", e); me.stats.write().await.cache_write_errors += 1; } //TODO: save cache stats! Ok(info) => { debug!( "[{}]: Cache write finished in {}", info.object_file_pretty, util::fmt_duration_as_secs(&info.duration) ); let mut stats = me.stats.write().await; stats.cache_writes += 1; stats.cache_write_duration += info.duration; } } } Ok(()) }; futures::future::try_join(send, cache_write).await?; Ok::<_, Error>(()) }; self.rt.spawn(async move { task.await .unwrap_or_else(|e| warn!("Failed to execute task: {:?}", e)); }); } } #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct PerLanguageCount { counts: HashMap<String, u64>, } impl PerLanguageCount { fn increment(&mut self, kind: &CompilerKind) { let key = kind.lang_kind(); let count = self.counts.entry(key).or_insert(0); *count += 1; } pub fn all(&self) -> u64 { self.counts.values().sum() } pub fn get(&self, key: &str) -> Option<&u64> { self.counts.get(key) } pub fn new() -> PerLanguageCount { Self::default() } } /// Statistics about the server. #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ServerStats { /// The count of client compile requests. pub compile_requests: u64, /// The count of client requests that used an unsupported compiler. pub requests_unsupported_compiler: u64, /// The count of client requests that were not compilation. pub requests_not_compile: u64, /// The count of client requests that were not cacheable. pub requests_not_cacheable: u64, /// The count of client requests that were executed. pub requests_executed: u64, /// The count of errors handling compile requests (per language). pub cache_errors: PerLanguageCount, /// The count of cache hits for handled compile requests (per language). pub cache_hits: PerLanguageCount, /// The count of cache misses for handled compile requests (per language). pub cache_misses: PerLanguageCount, /// The count of cache misses because the cache took too long to respond. pub cache_timeouts: u64, /// The count of errors reading cache entries. pub cache_read_errors: u64, /// The count of compilations which were successful but couldn't be cached. pub non_cacheable_compilations: u64, /// The count of compilations which forcibly ignored the cache. pub forced_recaches: u64, /// The count of errors writing to cache. pub cache_write_errors: u64, /// The number of successful cache writes. pub cache_writes: u64, /// The total time spent writing cache entries. pub cache_write_duration: Duration, /// The total time spent reading cache hits. pub cache_read_hit_duration: Duration, /// The total time spent reading cache misses. pub cache_read_miss_duration: Duration, /// The count of compilation failures. pub compile_fails: u64, /// Counts of reasons why compiles were not cached. pub not_cached: HashMap<String, usize>, /// The count of compilations that were successfully distributed indexed /// by the server that ran those compilations. pub dist_compiles: HashMap<String, usize>, /// The count of compilations that were distributed but failed and had to be re-run locally pub dist_errors: u64, } /// Info and stats about the server. #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ServerInfo { pub stats: ServerStats, pub cache_location: String, pub cache_size: Option<u64>, pub max_cache_size: Option<u64>, } /// Status of the dist client. #[derive(Serialize, Deserialize, Clone, Debug)] pub enum DistInfo { Disabled(String), #[cfg(feature = "dist-client")] NotConnected(Option<config::HTTPUrl>, String), #[cfg(feature = "dist-client")] SchedulerStatus(Option<config::HTTPUrl>, dist::SchedulerStatusResult), } impl Default for ServerStats { fn default() -> ServerStats { ServerStats { compile_requests: u64::default(), requests_unsupported_compiler: u64::default(), requests_not_compile: u64::default(), requests_not_cacheable: u64::default(), requests_executed: u64::default(), cache_errors: PerLanguageCount::new(), cache_hits: PerLanguageCount::new(), cache_misses: PerLanguageCount::new(), cache_timeouts: u64::default(), cache_read_errors: u64::default(), non_cacheable_compilations: u64::default(), forced_recaches: u64::default(), cache_write_errors: u64::default(), cache_writes: u64::default(), cache_write_duration: Duration::new(0, 0), cache_read_hit_duration: Duration::new(0, 0), cache_read_miss_duration: Duration::new(0, 0), compile_fails: u64::default(), not_cached: HashMap::new(), dist_compiles: HashMap::new(), dist_errors: u64::default(), } } } impl ServerStats { /// Print stats to stdout in a human-readable format. /// /// Return the formatted width of each of the (name, value) columns. fn print(&self) -> (usize, usize) { macro_rules! set_stat { ($vec:ident, $var:expr, $name:expr) => {{ // name, value, suffix length $vec.push(($name.to_string(), $var.to_string(), 0)); }}; } macro_rules! set_lang_stat { ($vec:ident, $var:expr, $name:expr) => {{ $vec.push(($name.to_string(), $var.all().to_string(), 0)); let mut sorted_stats: Vec<_> = $var.counts.iter().collect(); sorted_stats.sort_by_key(|v| v.0); for (lang, count) in sorted_stats.iter() { $vec.push((format!("{} ({})", $name, lang), count.to_string(), 0)); } }}; } macro_rules! set_duration_stat { ($vec:ident, $dur:expr, $num:expr, $name:expr) => {{ let s = if $num > 0 { $dur / $num as u32 } else { Default::default() }; // name, value, suffix length $vec.push(($name.to_string(), util::fmt_duration_as_secs(&s), 2)); }}; } let mut stats_vec = vec![]; //TODO: this would be nice to replace with a custom derive implementation. set_stat!(stats_vec, self.compile_requests, "Compile requests"); set_stat!( stats_vec, self.requests_executed, "Compile requests executed" ); set_lang_stat!(stats_vec, self.cache_hits, "Cache hits"); set_lang_stat!(stats_vec, self.cache_misses, "Cache misses"); set_stat!(stats_vec, self.cache_timeouts, "Cache timeouts"); set_stat!(stats_vec, self.cache_read_errors, "Cache read errors"); set_stat!(stats_vec, self.forced_recaches, "Forced recaches"); set_stat!(stats_vec, self.cache_write_errors, "Cache write errors"); set_stat!(stats_vec, self.compile_fails, "Compilation failures"); set_lang_stat!(stats_vec, self.cache_errors, "Cache errors"); set_stat!( stats_vec, self.non_cacheable_compilations, "Non-cacheable compilations" ); set_stat!( stats_vec, self.requests_not_cacheable, "Non-cacheable calls" ); set_stat!( stats_vec, self.requests_not_compile, "Non-compilation calls" ); set_stat!( stats_vec, self.requests_unsupported_compiler, "Unsupported compiler calls" ); set_duration_stat!( stats_vec, self.cache_write_duration, self.cache_writes, "Average cache write" ); set_duration_stat!( stats_vec, self.cache_read_miss_duration, self.cache_misses.all(), "Average cache read miss" ); set_duration_stat!( stats_vec, self.cache_read_hit_duration, self.cache_hits.all(), "Average cache read hit" ); set_stat!( stats_vec, self.dist_errors, "Failed distributed compilations" ); let name_width = stats_vec .iter() .map(|&(ref n, _, _)| n.len()) .max() .unwrap(); let stat_width = stats_vec .iter() .map(|&(_, ref s, _)| s.len()) .max() .unwrap(); for (name, stat, suffix_len) in stats_vec { println!( "{:<name_width$} {:>stat_width$}", name, stat, name_width = name_width, stat_width = stat_width + suffix_len ); } if !self.dist_compiles.is_empty() { println!("\nSuccessful distributed compiles"); let mut counts: Vec<_> = self.dist_compiles.iter().collect(); counts.sort_by(|(_, c1), (_, c2)| c1.cmp(c2).reverse()); for (reason, count) in counts { println!( " {:<name_width$} {:>stat_width$}", reason, count, name_width = name_width - 2, stat_width = stat_width ); } } if !self.not_cached.is_empty() { println!("\nNon-cacheable reasons:"); let mut counts: Vec<_> = self.not_cached.iter().collect(); counts.sort_by(|(_, c1), (_, c2)| c1.cmp(c2).reverse()); for (reason, count) in counts { println!( "{:<name_width$} {:>stat_width$}", reason, count, name_width = name_width, stat_width = stat_width ); } println!(); } (name_width, stat_width) } } impl ServerInfo { /// Print info to stdout in a human-readable format. pub fn print(&self) { let (name_width, stat_width) = self.stats.print(); println!( "{:<name_width$} {}", "Cache location", self.cache_location, name_width = name_width ); for &(name, val) in &[ ("Cache size", &self.cache_size), ("Max cache size", &self.max_cache_size), ] { if let Some(val) = *val { let (val, suffix) = match NumberPrefix::binary(val as f64) { NumberPrefix::Standalone(bytes) => (bytes.to_string(), "bytes".to_string()), NumberPrefix::Prefixed(prefix, n) => { (format!("{:.0}", n), format!("{}B", prefix)) } }; println!( "{:<name_width$} {:>stat_width$} {}", name, val, suffix, name_width = name_width, stat_width = stat_width ); } } } } enum Frame<R, R1> { Body { chunk: Option<R1> }, Message { message: R }, } struct Body<R> { receiver: mpsc::Receiver<Result<R>>, } impl<R> Body<R> { fn pair() -> (mpsc::Sender<Result<R>>, Self) { let (tx, rx) = mpsc::channel(0); (tx, Body { receiver: rx }) } } impl<R> futures::Stream for Body<R> { type Item = Result<R>; fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> std::task::Poll<Option<Self::Item>> { Pin::new(&mut self.receiver).poll_next(cx) } } enum Message<R, B> { WithBody(R, B), WithoutBody(R), } impl<R, B> Message<R, B> { fn into_inner(self) -> R { match self { Message::WithBody(r, _) => r, Message::WithoutBody(r) => r, } } } struct BincodeCodec; impl<T> tokio_serde::Serializer<T> for BincodeCodec where T: serde::Serialize, { type Error = Error; fn serialize(self: Pin<&mut Self>, item: &T) -> std::result::Result<Bytes, Self::Error> { let mut bytes = BytesMut::new(); bincode::serialize_into((&mut bytes).writer(), item)?; Ok(bytes.freeze()) } } impl<T> tokio_serde::Deserializer<T> for BincodeCodec where T: serde::de::DeserializeOwned, { type Error = Error; fn deserialize(self: Pin<&mut Self>, buf: &BytesMut) -> std::result::Result<T, Self::Error> { let ret = bincode::deserialize(buf)?; Ok(ret) } } /// Implementation of `Stream + Sink` that tokio-proto is expecting /// /// This type is composed of a few layers: /// /// * First there's `I`, the I/O object implementing `AsyncRead` and /// `AsyncWrite` /// * Next that's framed using the `length_delimited` module in tokio-io giving /// us a `Sink` and `Stream` of `BytesMut`. /// * Next that sink/stream is wrapped in `ReadBincode` which will cause the /// `Stream` implementation to switch from `BytesMut` to `Request` by parsing /// the bytes bincode. /// * Finally that sink/stream is wrapped in `WriteBincode` which will cause the /// `Sink` implementation to switch from `BytesMut` to `Response` meaning that /// all `Response` types pushed in will be converted to `BytesMut` and pushed /// below. struct SccacheTransport<I: AsyncRead + AsyncWrite + Unpin> { inner: Framed< futures::stream::ErrInto< futures::sink::SinkErrInto< tokio_util::codec::Framed<I, LengthDelimitedCodec>, Bytes, Error, >, Error, >, Request, Response, BincodeCodec, >, } impl<I: AsyncRead + AsyncWrite + Unpin> Stream for SccacheTransport<I> { type Item = Result<Message<Request, Body<()>>>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { Pin::new(&mut self.inner) .poll_next(cx) .map(|r| r.map(|s| s.map(Message::WithoutBody))) } } impl<I: AsyncRead + AsyncWrite + Unpin> Sink<Frame<Response, Response>> for SccacheTransport<I> { type Error = Error; fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> { Pin::new(&mut self.inner).poll_ready(cx) } fn start_send(mut self: Pin<&mut Self>, item: Frame<Response, Response>) -> Result<()> { match item { Frame::Message { message } => Pin::new(&mut self.inner).start_send(message), Frame::Body { chunk: Some(chunk) } => Pin::new(&mut self.inner).start_send(chunk), Frame::Body { chunk: None } => Ok(()), } } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> { Pin::new(&mut self.inner).poll_flush(cx) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> { Pin::new(&mut self.inner).poll_close(cx) } } struct ShutdownOrInactive { rx: mpsc::Receiver<ServerMessage>, timeout: Option<Delay>, timeout_dur: Duration, } impl Future for ShutdownOrInactive { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { loop { match Pin::new(&mut self.rx).poll_next(cx) { Poll::Pending => break, // Shutdown received! Poll::Ready(Some(ServerMessage::Shutdown)) => return Poll::Ready(()), Poll::Ready(Some(ServerMessage::Request)) => { if self.timeout_dur != Duration::new(0, 0) { self.timeout = Some(delay_for(self.timeout_dur)); } } // All services have shut down, in theory this isn't possible... Poll::Ready(None) => return Poll::Ready(()), } } match self.timeout { None => Poll::Pending, Some(ref mut timeout) => Pin::new(timeout).poll(cx), } } } /// Helper future which tracks the `ActiveInfo` below. This future will resolve /// once all instances of `ActiveInfo` have been dropped. struct WaitUntilZero { info: std::sync::Weak<Mutex<Info>>, } #[derive(Clone)] struct ActiveInfo { info: Arc<Mutex<Info>>, } struct Info { waker: Option<Waker>, } impl Drop for Info { fn drop(&mut self) { if let Some(waker) = self.waker.as_ref() { waker.wake_by_ref(); } } } impl WaitUntilZero { #[rustfmt::skip] fn new() -> (WaitUntilZero, ActiveInfo) { let info = Arc::new(Mutex::new(Info { waker: None })); (WaitUntilZero { info: Arc::downgrade(&info) }, ActiveInfo { info }) } } impl std::future::Future for WaitUntilZero { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll<Self::Output> { match self.info.upgrade() { None => std::task::Poll::Ready(()), Some(arc) => { let mut info = arc.lock().expect("we can't panic when holding lock"); info.waker = Some(cx.waker().clone()); std::task::Poll::Pending } } } } #[test] fn waits_until_zero() { let (wait, _active) = WaitUntilZero::new(); assert_eq!(wait.now_or_never(), None); let (wait, active) = WaitUntilZero::new(); let _active2 = active.clone(); drop(active); assert_eq!(wait.now_or_never(), None); let (wait, _) = WaitUntilZero::new(); assert_eq!(wait.now_or_never(), Some(())); let (wait, active) = WaitUntilZero::new(); let active2 = active.clone(); drop(active); drop(active2); assert_eq!(wait.now_or_never(), Some(())); }
/// Returns a reference to a thread pool to run work on
_distn_infrastructure.py
# # Author: Travis Oliphant 2002-2011 with contributions from # SciPy Developers 2004-2011 # from scipy._lib._util import getfullargspec_no_self as _getfullargspec import sys import keyword import re import types import warnings import inspect from itertools import zip_longest from collections import namedtuple from scipy._lib import doccer from scipy._lib._util import _lazywhere from ._distr_params import distcont, distdiscrete from scipy._lib._util import check_random_state from scipy.special import (comb, chndtr, entr, xlogy, ive) # for root finding for continuous distribution ppf, and max likelihood # estimation from scipy import optimize # for functions of continuous distributions (e.g. moments, entropy, cdf) from scipy import integrate # to approximate the pdf of a continuous distribution given its cdf from scipy.misc import derivative # for scipy.stats.entropy. Attempts to import just that function or file # have cause import problems from scipy import stats from numpy import (arange, putmask, ravel, ones, shape, ndarray, zeros, floor, logical_and, log, sqrt, place, argmax, vectorize, asarray, nan, inf, isinf, NINF, empty) import numpy as np from ._constants import _XMAX # These are the docstring parts used for substitution in specific # distribution docstrings docheaders = {'methods': """\nMethods\n-------\n""", 'notes': """\nNotes\n-----\n""", 'examples': """\nExamples\n--------\n"""} _doc_rvs = """\ rvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None) Random variates. """ _doc_pdf = """\ pdf(x, %(shapes)s, loc=0, scale=1) Probability density function. """ _doc_logpdf = """\ logpdf(x, %(shapes)s, loc=0, scale=1) Log of the probability density function. """ _doc_pmf = """\ pmf(k, %(shapes)s, loc=0, scale=1) Probability mass function. """ _doc_logpmf = """\ logpmf(k, %(shapes)s, loc=0, scale=1) Log of the probability mass function. """ _doc_cdf = """\ cdf(x, %(shapes)s, loc=0, scale=1) Cumulative distribution function. """ _doc_logcdf = """\ logcdf(x, %(shapes)s, loc=0, scale=1) Log of the cumulative distribution function. """ _doc_sf = """\ sf(x, %(shapes)s, loc=0, scale=1) Survival function (also defined as ``1 - cdf``, but `sf` is sometimes more accurate). """ _doc_logsf = """\ logsf(x, %(shapes)s, loc=0, scale=1) Log of the survival function. """ _doc_ppf = """\ ppf(q, %(shapes)s, loc=0, scale=1) Percent point function (inverse of ``cdf`` --- percentiles). """ _doc_isf = """\ isf(q, %(shapes)s, loc=0, scale=1) Inverse survival function (inverse of ``sf``). """ _doc_moment = """\ moment(order, %(shapes)s, loc=0, scale=1) Non-central moment of the specified order. """ _doc_stats = """\ stats(%(shapes)s, loc=0, scale=1, moments='mv') Mean('m'), variance('v'), skew('s'), and/or kurtosis('k'). """ _doc_entropy = """\ entropy(%(shapes)s, loc=0, scale=1) (Differential) entropy of the RV. """ _doc_fit = """\ fit(data) Parameter estimates for generic data. See `scipy.stats.rv_continuous.fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.fit.html#scipy.stats.rv_continuous.fit>`__ for detailed documentation of the keyword arguments. """ _doc_expect = """\ expect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds) Expected value of a function (of one argument) with respect to the distribution. """ _doc_expect_discrete = """\ expect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False) Expected value of a function (of one argument) with respect to the distribution. """ _doc_median = """\ median(%(shapes)s, loc=0, scale=1) Median of the distribution. """ _doc_mean = """\ mean(%(shapes)s, loc=0, scale=1) Mean of the distribution. """ _doc_var = """\ var(%(shapes)s, loc=0, scale=1) Variance of the distribution. """ _doc_std = """\ std(%(shapes)s, loc=0, scale=1) Standard deviation of the distribution. """ _doc_interval = """\ interval(confidence, %(shapes)s, loc=0, scale=1) Confidence interval with equal areas around the median. """ _doc_allmethods = ''.join([docheaders['methods'], _doc_rvs, _doc_pdf, _doc_logpdf, _doc_cdf, _doc_logcdf, _doc_sf, _doc_logsf, _doc_ppf, _doc_isf, _doc_moment, _doc_stats, _doc_entropy, _doc_fit, _doc_expect, _doc_median, _doc_mean, _doc_var, _doc_std, _doc_interval]) _doc_default_longsummary = """\ As an instance of the `rv_continuous` class, `%(name)s` object inherits from it a collection of generic methods (see below for the full list), and completes them with details specific for this particular distribution. """ _doc_default_frozen_note = """ Alternatively, the object may be called (as a function) to fix the shape, location, and scale parameters returning a "frozen" continuous RV object: rv = %(name)s(%(shapes)s, loc=0, scale=1) - Frozen RV object with the same methods but holding the given shape, location, and scale fixed. """ _doc_default_example = """\ Examples -------- >>> from scipy.stats import %(name)s >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Calculate the first four moments: %(set_vals_stmt)s >>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk') Display the probability density function (``pdf``): >>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s), ... %(name)s.ppf(0.99, %(shapes)s), 100) >>> ax.plot(x, %(name)s.pdf(x, %(shapes)s), ... 'r-', lw=5, alpha=0.6, label='%(name)s pdf') Alternatively, the distribution object can be called (as a function) to fix the shape, location and scale parameters. This returns a "frozen" RV object holding the given parameters fixed. Freeze the distribution and display the frozen ``pdf``: >>> rv = %(name)s(%(shapes)s) >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') Check accuracy of ``cdf`` and ``ppf``: >>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s) >>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s)) True Generate random numbers: >>> r = %(name)s.rvs(%(shapes)s, size=1000) And compare the histogram: >>> ax.hist(r, density=True, histtype='stepfilled', alpha=0.2) >>> ax.legend(loc='best', frameon=False) >>> plt.show() """ _doc_default_locscale = """\ The probability density above is defined in the "standardized" form. To shift and/or scale the distribution use the ``loc`` and ``scale`` parameters. Specifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with ``y = (x - loc) / scale``. Note that shifting the location of a distribution does not make it a "noncentral" distribution; noncentral generalizations of some distributions are available in separate classes. """ _doc_default = ''.join([_doc_default_longsummary, _doc_allmethods, '\n', _doc_default_example]) _doc_default_before_notes = ''.join([_doc_default_longsummary, _doc_allmethods]) docdict = { 'rvs': _doc_rvs, 'pdf': _doc_pdf, 'logpdf': _doc_logpdf, 'cdf': _doc_cdf, 'logcdf': _doc_logcdf, 'sf': _doc_sf, 'logsf': _doc_logsf, 'ppf': _doc_ppf, 'isf': _doc_isf, 'stats': _doc_stats, 'entropy': _doc_entropy, 'fit': _doc_fit, 'moment': _doc_moment, 'expect': _doc_expect, 'interval': _doc_interval, 'mean': _doc_mean, 'std': _doc_std, 'var': _doc_var, 'median': _doc_median, 'allmethods': _doc_allmethods, 'longsummary': _doc_default_longsummary, 'frozennote': _doc_default_frozen_note, 'example': _doc_default_example, 'default': _doc_default, 'before_notes': _doc_default_before_notes, 'after_notes': _doc_default_locscale } # Reuse common content between continuous and discrete docs, change some # minor bits. docdict_discrete = docdict.copy() docdict_discrete['pmf'] = _doc_pmf docdict_discrete['logpmf'] = _doc_logpmf docdict_discrete['expect'] = _doc_expect_discrete _doc_disc_methods = ['rvs', 'pmf', 'logpmf', 'cdf', 'logcdf', 'sf', 'logsf', 'ppf', 'isf', 'stats', 'entropy', 'expect', 'median', 'mean', 'var', 'std', 'interval'] for obj in _doc_disc_methods: docdict_discrete[obj] = docdict_discrete[obj].replace(', scale=1', '') _doc_disc_methods_err_varname = ['cdf', 'logcdf', 'sf', 'logsf'] for obj in _doc_disc_methods_err_varname: docdict_discrete[obj] = docdict_discrete[obj].replace('(x, ', '(k, ') docdict_discrete.pop('pdf') docdict_discrete.pop('logpdf') _doc_allmethods = ''.join([docdict_discrete[obj] for obj in _doc_disc_methods]) docdict_discrete['allmethods'] = docheaders['methods'] + _doc_allmethods docdict_discrete['longsummary'] = _doc_default_longsummary.replace( 'rv_continuous', 'rv_discrete') _doc_default_frozen_note = """ Alternatively, the object may be called (as a function) to fix the shape and location parameters returning a "frozen" discrete RV object: rv = %(name)s(%(shapes)s, loc=0) - Frozen RV object with the same methods but holding the given shape and location fixed. """ docdict_discrete['frozennote'] = _doc_default_frozen_note _doc_default_discrete_example = """\ Examples -------- >>> from scipy.stats import %(name)s >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Calculate the first four moments: %(set_vals_stmt)s >>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk') Display the probability mass function (``pmf``): >>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s), ... %(name)s.ppf(0.99, %(shapes)s)) >>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf') >>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5) Alternatively, the distribution object can be called (as a function) to fix the shape and location. This returns a "frozen" RV object holding the given parameters fixed. Freeze the distribution and display the frozen ``pmf``: >>> rv = %(name)s(%(shapes)s) >>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1, ... label='frozen pmf') >>> ax.legend(loc='best', frameon=False) >>> plt.show() Check accuracy of ``cdf`` and ``ppf``: >>> prob = %(name)s.cdf(x, %(shapes)s) >>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s)) True Generate random numbers: >>> r = %(name)s.rvs(%(shapes)s, size=1000) """ _doc_default_discrete_locscale = """\ The probability mass function above is defined in the "standardized" form. To shift distribution use the ``loc`` parameter. Specifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically equivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``. """ docdict_discrete['example'] = _doc_default_discrete_example docdict_discrete['after_notes'] = _doc_default_discrete_locscale _doc_default_before_notes = ''.join([docdict_discrete['longsummary'], docdict_discrete['allmethods']]) docdict_discrete['before_notes'] = _doc_default_before_notes _doc_default_disc = ''.join([docdict_discrete['longsummary'], docdict_discrete['allmethods'], docdict_discrete['frozennote'], docdict_discrete['example']]) docdict_discrete['default'] = _doc_default_disc # clean up all the separate docstring elements, we do not need them anymore for obj in [s for s in dir() if s.startswith('_doc_')]: exec('del ' + obj) del obj def _moment(data, n, mu=None): if mu is None: mu = data.mean() return ((data - mu)**n).mean() def _moment_from_stats(n, mu, mu2, g1, g2, moment_func, args): if (n == 0): return 1.0 elif (n == 1): if mu is None: val = moment_func(1, *args) else: val = mu elif (n == 2): if mu2 is None or mu is None: val = moment_func(2, *args) else: val = mu2 + mu*mu elif (n == 3): if g1 is None or mu2 is None or mu is None: val = moment_func(3, *args) else: mu3 = g1 * np.power(mu2, 1.5) # 3rd central moment val = mu3+3*mu*mu2+mu*mu*mu # 3rd non-central moment elif (n == 4): if g1 is None or g2 is None or mu2 is None or mu is None: val = moment_func(4, *args) else: mu4 = (g2+3.0)*(mu2**2.0) # 4th central moment mu3 = g1*np.power(mu2, 1.5) # 3rd central moment val = mu4+4*mu*mu3+6*mu*mu*mu2+mu*mu*mu*mu else: val = moment_func(n, *args) return val def _skew(data): """ skew is third central moment / variance**(1.5) """ data = np.ravel(data) mu = data.mean() m2 = ((data - mu)**2).mean() m3 = ((data - mu)**3).mean() return m3 / np.power(m2, 1.5) def _kurtosis(data): """kurtosis is fourth central moment / variance**2 - 3.""" data = np.ravel(data) mu = data.mean() m2 = ((data - mu)**2).mean() m4 = ((data - mu)**4).mean() return m4 / m2**2 - 3 def _fit_determine_optimizer(optimizer): if not callable(optimizer) and isinstance(optimizer, str): if not optimizer.startswith('fmin_'): optimizer = "fmin_"+optimizer if optimizer == 'fmin_': optimizer = 'fmin' try: optimizer = getattr(optimize, optimizer) except AttributeError as e: raise ValueError("%s is not a valid optimizer" % optimizer) from e return optimizer # Frozen RV class class rv_frozen: def __init__(self, dist, *args, **kwds): self.args = args self.kwds = kwds # create a new instance self.dist = dist.__class__(**dist._updated_ctor_param()) shapes, _, _ = self.dist._parse_args(*args, **kwds) self.a, self.b = self.dist._get_support(*shapes) @property def random_state(self): return self.dist._random_state @random_state.setter def random_state(self, seed): self.dist._random_state = check_random_state(seed) def cdf(self, x): return self.dist.cdf(x, *self.args, **self.kwds) def logcdf(self, x): return self.dist.logcdf(x, *self.args, **self.kwds) def ppf(self, q): return self.dist.ppf(q, *self.args, **self.kwds) def isf(self, q): return self.dist.isf(q, *self.args, **self.kwds) def rvs(self, size=None, random_state=None): kwds = self.kwds.copy() kwds.update({'size': size, 'random_state': random_state}) return self.dist.rvs(*self.args, **kwds) def sf(self, x): return self.dist.sf(x, *self.args, **self.kwds) def logsf(self, x): return self.dist.logsf(x, *self.args, **self.kwds) def stats(self, moments='mv'): kwds = self.kwds.copy() kwds.update({'moments': moments}) return self.dist.stats(*self.args, **kwds) def median(self): return self.dist.median(*self.args, **self.kwds) def mean(self): return self.dist.mean(*self.args, **self.kwds) def var(self): return self.dist.var(*self.args, **self.kwds) def std(self): return self.dist.std(*self.args, **self.kwds) def moment(self, order=None, **kwds): return self.dist.moment(order, *self.args, **self.kwds, **kwds) def entropy(self): return self.dist.entropy(*self.args, **self.kwds) def interval(self, confidence=None, **kwds): return self.dist.interval(confidence, *self.args, **self.kwds, **kwds) def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds): # expect method only accepts shape parameters as positional args # hence convert self.args, self.kwds, also loc/scale # See the .expect method docstrings for the meaning of # other parameters. a, loc, scale = self.dist._parse_args(*self.args, **self.kwds) if isinstance(self.dist, rv_discrete): return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds) else: return self.dist.expect(func, a, loc, scale, lb, ub, conditional, **kwds) def
(self): return self.dist.support(*self.args, **self.kwds) class rv_discrete_frozen(rv_frozen): def pmf(self, k): return self.dist.pmf(k, *self.args, **self.kwds) def logpmf(self, k): # No error return self.dist.logpmf(k, *self.args, **self.kwds) class rv_continuous_frozen(rv_frozen): def pdf(self, x): return self.dist.pdf(x, *self.args, **self.kwds) def logpdf(self, x): return self.dist.logpdf(x, *self.args, **self.kwds) def argsreduce(cond, *args): """Clean arguments to: 1. Ensure all arguments are iterable (arrays of dimension at least one 2. If cond != True and size > 1, ravel(args[i]) where ravel(condition) is True, in 1D. Return list of processed arguments. Examples -------- >>> rng = np.random.default_rng() >>> A = rng.random((4, 5)) >>> B = 2 >>> C = rng.random((1, 5)) >>> cond = np.ones(A.shape) >>> [A1, B1, C1] = argsreduce(cond, A, B, C) >>> A1.shape (4, 5) >>> B1.shape (1,) >>> C1.shape (1, 5) >>> cond[2,:] = 0 >>> [A1, B1, C1] = argsreduce(cond, A, B, C) >>> A1.shape (15,) >>> B1.shape (1,) >>> C1.shape (15,) """ # some distributions assume arguments are iterable. newargs = np.atleast_1d(*args) # np.atleast_1d returns an array if only one argument, or a list of arrays # if more than one argument. if not isinstance(newargs, list): newargs = [newargs, ] if np.all(cond): # broadcast arrays with cond *newargs, cond = np.broadcast_arrays(*newargs, cond) return [arg.ravel() for arg in newargs] s = cond.shape # np.extract returns flattened arrays, which are not broadcastable together # unless they are either the same size or size == 1. return [(arg if np.size(arg) == 1 else np.extract(cond, np.broadcast_to(arg, s))) for arg in newargs] parse_arg_template = """ def _parse_args(self, %(shape_arg_str)s %(locscale_in)s): return (%(shape_arg_str)s), %(locscale_out)s def _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None): return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size) def _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'): return (%(shape_arg_str)s), %(locscale_out)s, moments """ # Both the continuous and discrete distributions depend on ncx2. # The function name ncx2 is an abbreviation for noncentral chi squared. def _ncx2_log_pdf(x, df, nc): # We use (xs**2 + ns**2)/2 = (xs - ns)**2/2 + xs*ns, and include the # factor of exp(-xs*ns) into the ive function to improve numerical # stability at large values of xs. See also `rice.pdf`. df2 = df/2.0 - 1.0 xs, ns = np.sqrt(x), np.sqrt(nc) res = xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2 corr = ive(df2, xs*ns) / 2.0 # Return res + np.log(corr) avoiding np.log(0) return _lazywhere( corr > 0, (res, corr), f=lambda r, c: r + np.log(c), fillvalue=-np.inf) def _ncx2_pdf(x, df, nc): # Copy of _ncx2_log_pdf avoiding np.log(0) when corr = 0 df2 = df/2.0 - 1.0 xs, ns = np.sqrt(x), np.sqrt(nc) res = xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2 corr = ive(df2, xs*ns) / 2.0 return np.exp(res) * corr def _ncx2_cdf(x, df, nc): return chndtr(x, df, nc) class rv_generic: """Class which encapsulates common functionality between rv_discrete and rv_continuous. """ def __init__(self, seed=None): super().__init__() # figure out if _stats signature has 'moments' keyword sig = _getfullargspec(self._stats) self._stats_has_moments = ((sig.varkw is not None) or ('moments' in sig.args) or ('moments' in sig.kwonlyargs)) self._random_state = check_random_state(seed) # For historical reasons, `size` was made an attribute that was read # inside _rvs(). The code is being changed so that 'size' # is an argument # to self._rvs(). However some external (non-SciPy) distributions # have not # been updated. Maintain backwards compatibility by checking if # the self._rvs() signature has the 'size' keyword, or a **kwarg, # and if not set self._size inside self.rvs() # before calling self._rvs(). argspec = inspect.getfullargspec(self._rvs) self._rvs_uses_size_attribute = (argspec.varkw is None and 'size' not in argspec.args and 'size' not in argspec.kwonlyargs) # Warn on first use only self._rvs_size_warned = False @property def random_state(self): """Get or set the generator object for generating random variates. If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. """ return self._random_state @random_state.setter def random_state(self, seed): self._random_state = check_random_state(seed) def __setstate__(self, state): try: self.__dict__.update(state) # attaches the dynamically created methods on each instance. # if a subclass overrides rv_generic.__setstate__, or implements # it's own _attach_methods, then it must make sure that # _attach_argparser_methods is called. self._attach_methods() except ValueError: # reconstitute an old pickle scipy<1.6, that contains # (_ctor_param, random_state) as state self._ctor_param = state[0] self._random_state = state[1] self.__init__() def _attach_methods(self): """Attaches dynamically created methods to the rv_* instance. This method must be overridden by subclasses, and must itself call _attach_argparser_methods. This method is called in __init__ in subclasses, and in __setstate__ """ raise NotImplementedError def _attach_argparser_methods(self): """ Generates the argument-parsing functions dynamically and attaches them to the instance. Should be called from `_attach_methods`, typically in __init__ and during unpickling (__setstate__) """ ns = {} exec(self._parse_arg_template, ns) # NB: attach to the instance, not class for name in ['_parse_args', '_parse_args_stats', '_parse_args_rvs']: setattr(self, name, types.MethodType(ns[name], self)) def _construct_argparser( self, meths_to_inspect, locscale_in, locscale_out): """Construct the parser string for the shape arguments. This method should be called in __init__ of a class for each distribution. It creates the `_parse_arg_template` attribute that is then used by `_attach_argparser_methods` to dynamically create and attach the `_parse_args`, `_parse_args_stats`, `_parse_args_rvs` methods to the instance. If self.shapes is a non-empty string, interprets it as a comma-separated list of shape parameters. Otherwise inspects the call signatures of `meths_to_inspect` and constructs the argument-parsing functions from these. In this case also sets `shapes` and `numargs`. """ if self.shapes: # sanitize the user-supplied shapes if not isinstance(self.shapes, str): raise TypeError('shapes must be a string.') shapes = self.shapes.replace(',', ' ').split() for field in shapes: if keyword.iskeyword(field): raise SyntaxError('keywords cannot be used as shapes.') if not re.match('^[_a-zA-Z][_a-zA-Z0-9]*$', field): raise SyntaxError( 'shapes must be valid python identifiers') else: # find out the call signatures (_pdf, _cdf etc), deduce shape # arguments. Generic methods only have 'self, x', any further args # are shapes. shapes_list = [] for meth in meths_to_inspect: shapes_args = _getfullargspec(meth) # NB does not contain self args = shapes_args.args[1:] # peel off 'x', too if args: shapes_list.append(args) # *args or **kwargs are not allowed w/automatic shapes if shapes_args.varargs is not None: raise TypeError( '*args are not allowed w/out explicit shapes') if shapes_args.varkw is not None: raise TypeError( '**kwds are not allowed w/out explicit shapes') if shapes_args.kwonlyargs: raise TypeError( 'kwonly args are not allowed w/out explicit shapes') if shapes_args.defaults is not None: raise TypeError('defaults are not allowed for shapes') if shapes_list: shapes = shapes_list[0] # make sure the signatures are consistent for item in shapes_list: if item != shapes: raise TypeError('Shape arguments are inconsistent.') else: shapes = [] # have the arguments, construct the method from template shapes_str = ', '.join(shapes) + ', ' if shapes else '' # NB: not None dct = dict(shape_arg_str=shapes_str, locscale_in=locscale_in, locscale_out=locscale_out, ) # this string is used by _attach_argparser_methods self._parse_arg_template = parse_arg_template % dct self.shapes = ', '.join(shapes) if shapes else None if not hasattr(self, 'numargs'): # allows more general subclassing with *args self.numargs = len(shapes) def _construct_doc(self, docdict, shapes_vals=None): """Construct the instance docstring with string substitutions.""" tempdict = docdict.copy() tempdict['name'] = self.name or 'distname' tempdict['shapes'] = self.shapes or '' if shapes_vals is None: shapes_vals = () vals = ', '.join('%.3g' % val for val in shapes_vals) tempdict['vals'] = vals tempdict['shapes_'] = self.shapes or '' if self.shapes and self.numargs == 1: tempdict['shapes_'] += ',' if self.shapes: tempdict['set_vals_stmt'] = '>>> %s = %s' % (self.shapes, vals) else: tempdict['set_vals_stmt'] = '' if self.shapes is None: # remove shapes from call parameters if there are none for item in ['default', 'before_notes']: tempdict[item] = tempdict[item].replace( "\n%(shapes)s : array_like\n shape parameters", "") for i in range(2): if self.shapes is None: # necessary because we use %(shapes)s in two forms (w w/o ", ") self.__doc__ = self.__doc__.replace("%(shapes)s, ", "") try: self.__doc__ = doccer.docformat(self.__doc__, tempdict) except TypeError as e: raise Exception("Unable to construct docstring for " "distribution \"%s\": %s" % (self.name, repr(e))) from e # correct for empty shapes self.__doc__ = self.__doc__.replace('(, ', '(').replace(', )', ')') def _construct_default_doc(self, longname=None, extradoc=None, docdict=None, discrete='continuous'): """Construct instance docstring from the default template.""" if longname is None: longname = 'A' if extradoc is None: extradoc = '' if extradoc.startswith('\n\n'): extradoc = extradoc[2:] self.__doc__ = ''.join(['%s %s random variable.' % (longname, discrete), '\n\n%(before_notes)s\n', docheaders['notes'], extradoc, '\n%(example)s']) self._construct_doc(docdict) def freeze(self, *args, **kwds): """Freeze the distribution for the given arguments. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution. Should include all the non-optional arguments, may include ``loc`` and ``scale``. Returns ------- rv_frozen : rv_frozen instance The frozen distribution. """ if isinstance(self, rv_continuous): return rv_continuous_frozen(self, *args, **kwds) else: return rv_discrete_frozen(self, *args, **kwds) def __call__(self, *args, **kwds): return self.freeze(*args, **kwds) __call__.__doc__ = freeze.__doc__ # The actual calculation functions (no basic checking need be done) # If these are defined, the others won't be looked at. # Otherwise, the other set can be defined. def _stats(self, *args, **kwds): return None, None, None, None # Noncentral moments (also known as the moment about the origin). # Expressed in LaTeX, munp would be $\mu'_{n}$, i.e. "mu-sub-n-prime". # The primed mu is a widely used notation for the noncentral moment. def _munp(self, n, *args): # Silence floating point warnings from integration. with np.errstate(all='ignore'): vals = self.generic_moment(n, *args) return vals def _argcheck_rvs(self, *args, **kwargs): # Handle broadcasting and size validation of the rvs method. # Subclasses should not have to override this method. # The rule is that if `size` is not None, then `size` gives the # shape of the result (integer values of `size` are treated as # tuples with length 1; i.e. `size=3` is the same as `size=(3,)`.) # # `args` is expected to contain the shape parameters (if any), the # location and the scale in a flat tuple (e.g. if there are two # shape parameters `a` and `b`, `args` will be `(a, b, loc, scale)`). # The only keyword argument expected is 'size'. size = kwargs.get('size', None) all_bcast = np.broadcast_arrays(*args) def squeeze_left(a): while a.ndim > 0 and a.shape[0] == 1: a = a[0] return a # Eliminate trivial leading dimensions. In the convention # used by numpy's random variate generators, trivial leading # dimensions are effectively ignored. In other words, when `size` # is given, trivial leading dimensions of the broadcast parameters # in excess of the number of dimensions in size are ignored, e.g. # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]], size=3) # array([ 1.00104267, 3.00422496, 4.99799278]) # If `size` is not given, the exact broadcast shape is preserved: # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]]) # array([[[[ 1.00862899, 3.00061431, 4.99867122]]]]) # all_bcast = [squeeze_left(a) for a in all_bcast] bcast_shape = all_bcast[0].shape bcast_ndim = all_bcast[0].ndim if size is None: size_ = bcast_shape else: size_ = tuple(np.atleast_1d(size)) # Check compatibility of size_ with the broadcast shape of all # the parameters. This check is intended to be consistent with # how the numpy random variate generators (e.g. np.random.normal, # np.random.beta) handle their arguments. The rule is that, if size # is given, it determines the shape of the output. Broadcasting # can't change the output size. # This is the standard broadcasting convention of extending the # shape with fewer dimensions with enough dimensions of length 1 # so that the two shapes have the same number of dimensions. ndiff = bcast_ndim - len(size_) if ndiff < 0: bcast_shape = (1,)*(-ndiff) + bcast_shape elif ndiff > 0: size_ = (1,)*ndiff + size_ # This compatibility test is not standard. In "regular" broadcasting, # two shapes are compatible if for each dimension, the lengths are the # same or one of the lengths is 1. Here, the length of a dimension in # size_ must not be less than the corresponding length in bcast_shape. ok = all([bcdim == 1 or bcdim == szdim for (bcdim, szdim) in zip(bcast_shape, size_)]) if not ok: raise ValueError("size does not match the broadcast shape of " "the parameters. %s, %s, %s" % (size, size_, bcast_shape)) param_bcast = all_bcast[:-2] loc_bcast = all_bcast[-2] scale_bcast = all_bcast[-1] return param_bcast, loc_bcast, scale_bcast, size_ # These are the methods you must define (standard form functions) # NB: generic _pdf, _logpdf, _cdf are different for # rv_continuous and rv_discrete hence are defined in there def _argcheck(self, *args): """Default check for correct values on args and keywords. Returns condition array of 1's where arguments are correct and 0's where they are not. """ cond = 1 for arg in args: cond = logical_and(cond, (asarray(arg) > 0)) return cond def _get_support(self, *args, **kwargs): """Return the support of the (unscaled, unshifted) distribution. *Must* be overridden by distributions which have support dependent upon the shape parameters of the distribution. Any such override *must not* set or change any of the class members, as these members are shared amongst all instances of the distribution. Parameters ---------- arg1, arg2, ... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- a, b : numeric (float, or int or +/-np.inf) end-points of the distribution's support for the specified shape parameters. """ return self.a, self.b def _support_mask(self, x, *args): a, b = self._get_support(*args) with np.errstate(invalid='ignore'): return (a <= x) & (x <= b) def _open_support_mask(self, x, *args): a, b = self._get_support(*args) with np.errstate(invalid='ignore'): return (a < x) & (x < b) def _rvs(self, *args, size=None, random_state=None): # This method must handle size being a tuple, and it must # properly broadcast *args and size. size might be # an empty tuple, which means a scalar random variate is to be # generated. # Use basic inverse cdf algorithm for RV generation as default. U = random_state.uniform(size=size) Y = self._ppf(U, *args) return Y def _logcdf(self, x, *args): with np.errstate(divide='ignore'): return log(self._cdf(x, *args)) def _sf(self, x, *args): return 1.0-self._cdf(x, *args) def _logsf(self, x, *args): with np.errstate(divide='ignore'): return log(self._sf(x, *args)) def _ppf(self, q, *args): return self._ppfvec(q, *args) def _isf(self, q, *args): return self._ppf(1.0-q, *args) # use correct _ppf for subclasses # These are actually called, and should not be overwritten if you # want to keep error checking. def rvs(self, *args, **kwds): """Random variates of given type. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). scale : array_like, optional Scale parameter (default=1). size : int or tuple of ints, optional Defining number of random variates (default is 1). random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Returns ------- rvs : ndarray or scalar Random variates of given `size`. """ discrete = kwds.pop('discrete', None) rndm = kwds.pop('random_state', None) args, loc, scale, size = self._parse_args_rvs(*args, **kwds) cond = logical_and(self._argcheck(*args), (scale >= 0)) if not np.all(cond): message = ("Domain error in arguments. The `scale` parameter must " "be positive for all distributions; see the " "distribution documentation for other restrictions.") raise ValueError(message) if np.all(scale == 0): return loc*ones(size, 'd') # extra gymnastics needed for a custom random_state if rndm is not None: random_state_saved = self._random_state random_state = check_random_state(rndm) else: random_state = self._random_state # Maintain backwards compatibility by setting self._size # for distributions that still need it. if self._rvs_uses_size_attribute: if not self._rvs_size_warned: warnings.warn( f'The signature of {self._rvs} does not contain ' f'a "size" keyword. Such signatures are deprecated.', np.VisibleDeprecationWarning) self._rvs_size_warned = True self._size = size self._random_state = random_state vals = self._rvs(*args) else: vals = self._rvs(*args, size=size, random_state=random_state) vals = vals * scale + loc # do not forget to restore the _random_state if rndm is not None: self._random_state = random_state_saved # Cast to int if discrete if discrete: if size == (): vals = int(vals) else: vals = vals.astype(np.int64) return vals def stats(self, *args, **kwds): """Some statistics of the given RV. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional (continuous RVs only) scale parameter (default=1) moments : str, optional composed of letters ['mvsk'] defining which moments to compute: 'm' = mean, 'v' = variance, 's' = (Fisher's) skew, 'k' = (Fisher's) kurtosis. (default is 'mv') Returns ------- stats : sequence of requested moments. """ args, loc, scale, moments = self._parse_args_stats(*args, **kwds) # scale = 1 by construction for discrete RVs loc, scale = map(asarray, (loc, scale)) args = tuple(map(asarray, args)) cond = self._argcheck(*args) & (scale > 0) & (loc == loc) output = [] default = np.full(shape(cond), fill_value=self.badvalue) # Use only entries that are valid in calculation if np.any(cond): goodargs = argsreduce(cond, *(args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] if self._stats_has_moments: mu, mu2, g1, g2 = self._stats(*goodargs, **{'moments': moments}) else: mu, mu2, g1, g2 = self._stats(*goodargs) if 'm' in moments: if mu is None: mu = self._munp(1, *goodargs) out0 = default.copy() place(out0, cond, mu * scale + loc) output.append(out0) if 'v' in moments: if mu2 is None: mu2p = self._munp(2, *goodargs) if mu is None: mu = self._munp(1, *goodargs) # if mean is inf then var is also inf with np.errstate(invalid='ignore'): mu2 = np.where(~np.isinf(mu), mu2p - mu**2, np.inf) out0 = default.copy() place(out0, cond, mu2 * scale * scale) output.append(out0) if 's' in moments: if g1 is None: mu3p = self._munp(3, *goodargs) if mu is None: mu = self._munp(1, *goodargs) if mu2 is None: mu2p = self._munp(2, *goodargs) mu2 = mu2p - mu * mu with np.errstate(invalid='ignore'): mu3 = (-mu*mu - 3*mu2)*mu + mu3p g1 = mu3 / np.power(mu2, 1.5) out0 = default.copy() place(out0, cond, g1) output.append(out0) if 'k' in moments: if g2 is None: mu4p = self._munp(4, *goodargs) if mu is None: mu = self._munp(1, *goodargs) if mu2 is None: mu2p = self._munp(2, *goodargs) mu2 = mu2p - mu * mu if g1 is None: mu3 = None else: # (mu2**1.5) breaks down for nan and inf mu3 = g1 * np.power(mu2, 1.5) if mu3 is None: mu3p = self._munp(3, *goodargs) with np.errstate(invalid='ignore'): mu3 = (-mu * mu - 3 * mu2) * mu + mu3p with np.errstate(invalid='ignore'): mu4 = ((-mu**2 - 6*mu2) * mu - 4*mu3)*mu + mu4p g2 = mu4 / mu2**2.0 - 3.0 out0 = default.copy() place(out0, cond, g2) output.append(out0) else: # no valid args output = [default.copy() for _ in moments] if len(output) == 1: return output[0] else: return tuple(output) def entropy(self, *args, **kwds): """Differential entropy of the RV. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). scale : array_like, optional (continuous distributions only). Scale parameter (default=1). Notes ----- Entropy is defined base `e`: >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5))) >>> np.allclose(drv.entropy(), np.log(2.0)) True """ args, loc, scale = self._parse_args(*args, **kwds) # NB: for discrete distributions scale=1 by construction in _parse_args loc, scale = map(asarray, (loc, scale)) args = tuple(map(asarray, args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) output = zeros(shape(cond0), 'd') place(output, (1-cond0), self.badvalue) goodargs = argsreduce(cond0, scale, *args) goodscale = goodargs[0] goodargs = goodargs[1:] place(output, cond0, self.vecentropy(*goodargs) + log(goodscale)) return output def moment(self, order=None, *args, **kwds): """non-central moment of distribution of specified order. .. deprecated:: 1.9.0 Parameter `n` is replaced by parameter `order` to avoid name collisions with the shape parameter `n` of several distributions. Parameter `n` will be removed in SciPy 1.11.0. Parameters ---------- order : int, order >= 1 Order of moment. arg1, arg2, arg3,... : float The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) """ # This function was originally written with parameter `n`, but `n` # is also the name of many distribution shape parameters. # This block allows the function to accept both `n` and its # replacement `order` during a deprecation period; it can be removed # in the second release after 1.9.0. # The logic to provide a DeprecationWarning only when `n` is passed # as a keyword, accept the new keyword `order`, and otherwise be # backward-compatible deserves explanation. We need to look out for # the following: # * Does the distribution have a shape named `n`? # * Is `order` provided? It doesn't matter whether it is provided as a # positional or keyword argument; it will be used as the order of the # moment rather than a distribution shape parameter because: # - The first positional argument of `moment` has always been the # order of the moment. # - The keyword `order` is new, so it's unambiguous that it refers to # the order of the moment. # * Is `n` provided as a keyword argument? It _does_ matter whether it # is provided as a positional or keyword argument. # - The first positional argument of `moment` has always been the # order of moment, but # - if `n` is provided as a keyword argument, its meaning depends # on whether the distribution accepts `n` as a shape parameter. has_shape_n = (self.shapes is not None and "n" in (self.shapes.split(", "))) got_order = order is not None got_keyword_n = kwds.get("n", None) is not None # These lead to the following cases. # Case A: If the distribution _does_ accept `n` as a shape # 1. If both `order` and `n` are provided, this is now OK: # it is unambiguous that `order` is the order of the moment and `n` # is the shape parameter. Previously, this would have caused an # error because `n` was provided both as a keyword argument and # as the first positional argument. I don't think it is credible for # users to rely on this error in their code, though, so I don't see # this as a backward compatibility break. # 2. If only `n` is provided (as a keyword argument), this would have # been an error in the past because `n` would have been treated as # the order of the moment while the shape parameter would be # missing. It is still the same type of error, but for a different # reason: now, `n` is treated as the shape parameter while the # order of the moment is missing. # 3. If only `order` is provided, no special treament is needed. # Clearly this value is intended to be the order of the moment, # and the rest of the function will determine whether `n` is # available as a shape parameter in `args`. # 4. If neither `n` nor `order` is provided, this would have been an # error (order of the moment is not provided) and it is still an # error for the same reason. # Case B: the distribution does _not_ accept `n` as a shape # 1. If both `order` and `n` are provided, this was an error, and it # still is an error: two values for same parameter. # 2. If only `n` is provided (as a keyword argument), this was OK and # is still OK, but there shold now be a `DeprecationWarning`. The # value of `n` should be removed from `kwds` and stored in `order`. # 3. If only `order` is provided, there was no problem before providing # only the first argument of `moment`, and there is no problem with # that now. # 4. If neither `n` nor `order` is provided, this would have been an # error (order of the moment is not provided), and it is still an # error for the same reason. if not got_order and ((not got_keyword_n) # A4 and B4 or (got_keyword_n and has_shape_n)): # A2 message = ("moment() missing 1 required " "positional argument: `order`") raise TypeError(message) if got_keyword_n and not has_shape_n: if got_order: # B1 # this will change to "moment got unexpected argument n" message = "moment() got multiple values for first argument" raise TypeError(message) else: # B2 message = ("Use of keyword argument `n` for method " "`moment` is deprecated. Use first positional " "argument or keyword argument `order` instead.") order = kwds.pop("n") warnings.warn(message, DeprecationWarning, stacklevel=2) n = order # No special treatment of A1, A3, or B3 is needed because the order # of the moment is now in variable `n` and the shape parameter, if # needed, will be fished out of `args` or `kwds` by _parse_args # A3 might still cause an error if the shape parameter called `n` # is not found in `args`. shapes, loc, scale = self._parse_args(*args, **kwds) args = np.broadcast_arrays(*(*shapes, loc, scale)) *shapes, loc, scale = args i0 = np.logical_and(self._argcheck(*shapes), scale > 0) i1 = np.logical_and(i0, loc == 0) i2 = np.logical_and(i0, loc != 0) args = argsreduce(i0, *shapes, loc, scale) *shapes, loc, scale = args if (floor(n) != n): raise ValueError("Moment must be an integer.") if (n < 0): raise ValueError("Moment must be positive.") mu, mu2, g1, g2 = None, None, None, None if (n > 0) and (n < 5): if self._stats_has_moments: mdict = {'moments': {1: 'm', 2: 'v', 3: 'vs', 4: 'vk'}[n]} else: mdict = {} mu, mu2, g1, g2 = self._stats(*shapes, **mdict) val = np.empty(loc.shape) # val needs to be indexed by loc val[...] = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, shapes) # Convert to transformed X = L + S*Y # E[X^n] = E[(L+S*Y)^n] = L^n sum(comb(n, k)*(S/L)^k E[Y^k], k=0...n) result = zeros(i0.shape) place(result, ~i0, self.badvalue) if i1.any(): res1 = scale[loc == 0]**n * val[loc == 0] place(result, i1, res1) if i2.any(): mom = [mu, mu2, g1, g2] arrs = [i for i in mom if i is not None] idx = [i for i in range(4) if mom[i] is not None] if any(idx): arrs = argsreduce(loc != 0, *arrs) j = 0 for i in idx: mom[i] = arrs[j] j += 1 mu, mu2, g1, g2 = mom args = argsreduce(loc != 0, *shapes, loc, scale, val) *shapes, loc, scale, val = args res2 = zeros(loc.shape, dtype='d') fac = scale / loc for k in range(n): valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp, shapes) res2 += comb(n, k, exact=True)*fac**k * valk res2 += fac**n * val res2 *= loc**n place(result, i2, res2) if result.ndim == 0: return result.item() return result def median(self, *args, **kwds): """Median of the distribution. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional Location parameter, Default is 0. scale : array_like, optional Scale parameter, Default is 1. Returns ------- median : float The median of the distribution. See Also -------- rv_discrete.ppf Inverse of the CDF """ return self.ppf(0.5, *args, **kwds) def mean(self, *args, **kwds): """Mean of the distribution. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- mean : float the mean of the distribution """ kwds['moments'] = 'm' res = self.stats(*args, **kwds) if isinstance(res, ndarray) and res.ndim == 0: return res[()] return res def var(self, *args, **kwds): """Variance of the distribution. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- var : float the variance of the distribution """ kwds['moments'] = 'v' res = self.stats(*args, **kwds) if isinstance(res, ndarray) and res.ndim == 0: return res[()] return res def std(self, *args, **kwds): """Standard deviation of the distribution. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- std : float standard deviation of the distribution """ kwds['moments'] = 'v' res = sqrt(self.stats(*args, **kwds)) return res def interval(self, confidence=None, *args, **kwds): """Confidence interval with equal areas around the median. .. deprecated:: 1.9.0 Parameter `alpha` is replaced by parameter `confidence` to avoid name collisions with the shape parameter `alpha` of some distributions. Parameter `alpha` will be removed in SciPy 1.11.0. Parameters ---------- confidence : array_like of float Probability that an rv will be drawn from the returned range. Each value should be in the range [0, 1]. arg1, arg2, ... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional location parameter, Default is 0. scale : array_like, optional scale parameter, Default is 1. Returns ------- a, b : ndarray of float end-points of range that contain ``100 * alpha %`` of the rv's possible values. """ # This function was originally written with parameter `alpha`, but # `alpha` is also the name of a shape parameter of two distributions. # This block allows the function to accept both `alpha` and its # replacement `confidence` during a deprecation period; it can be # removed in the second release after 1.9.0. # See description of logic in `moment` method. has_shape_alpha = (self.shapes is not None and "alpha" in (self.shapes.split(", "))) got_confidence = confidence is not None got_keyword_alpha = kwds.get("alpha", None) is not None if not got_confidence and ((not got_keyword_alpha) or (got_keyword_alpha and has_shape_alpha)): message = ("interval() missing 1 required positional argument: " "`confidence`") raise TypeError(message) if got_keyword_alpha and not has_shape_alpha: if got_confidence: # this will change to "interval got unexpected argument alpha" message = "interval() got multiple values for first argument" raise TypeError(message) else: message = ("Use of keyword argument `alpha` for method " "`interval` is deprecated. Use first positional " "argument or keyword argument `confidence` " "instead.") confidence = kwds.pop("alpha") warnings.warn(message, DeprecationWarning, stacklevel=2) alpha = confidence alpha = asarray(alpha) if np.any((alpha > 1) | (alpha < 0)): raise ValueError("alpha must be between 0 and 1 inclusive") q1 = (1.0-alpha)/2 q2 = (1.0+alpha)/2 a = self.ppf(q1, *args, **kwds) b = self.ppf(q2, *args, **kwds) return a, b def support(self, *args, **kwargs): """Support of the distribution. Parameters ---------- arg1, arg2, ... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional location parameter, Default is 0. scale : array_like, optional scale parameter, Default is 1. Returns ------- a, b : array_like end-points of the distribution's support. """ args, loc, scale = self._parse_args(*args, **kwargs) arrs = np.broadcast_arrays(*args, loc, scale) args, loc, scale = arrs[:-2], arrs[-2], arrs[-1] cond = self._argcheck(*args) & (scale > 0) _a, _b = self._get_support(*args) if cond.all(): return _a * scale + loc, _b * scale + loc elif cond.ndim == 0: return self.badvalue, self.badvalue # promote bounds to at least float to fill in the badvalue _a, _b = np.asarray(_a).astype('d'), np.asarray(_b).astype('d') out_a, out_b = _a * scale + loc, _b * scale + loc place(out_a, 1-cond, self.badvalue) place(out_b, 1-cond, self.badvalue) return out_a, out_b def nnlf(self, theta, x): """Negative loglikelihood function. Notes ----- This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the parameters (including loc and scale). """ loc, scale, args = self._unpack_loc_scale(theta) if not self._argcheck(*args) or scale <= 0: return inf x = asarray((x-loc) / scale) n_log_scale = len(x) * log(scale) if np.any(~self._support_mask(x, *args)): return inf return self._nnlf(x, *args) + n_log_scale def _nnlf(self, x, *args): return -np.sum(self._logpxf(x, *args), axis=0) def _nnlf_and_penalty(self, x, args): cond0 = ~self._support_mask(x, *args) n_bad = np.count_nonzero(cond0, axis=0) if n_bad > 0: x = argsreduce(~cond0, x)[0] logpxf = self._logpxf(x, *args) finite_logpxf = np.isfinite(logpxf) n_bad += np.sum(~finite_logpxf, axis=0) if n_bad > 0: penalty = n_bad * log(_XMAX) * 100 return -np.sum(logpxf[finite_logpxf], axis=0) + penalty return -np.sum(logpxf, axis=0) def _penalized_nnlf(self, theta, x): """Penalized negative loglikelihood function. i.e., - sum (log pdf(x, theta), axis=0) + penalty where theta are the parameters (including loc and scale) """ loc, scale, args = self._unpack_loc_scale(theta) if not self._argcheck(*args) or scale <= 0: return inf x = asarray((x-loc) / scale) n_log_scale = len(x) * log(scale) return self._nnlf_and_penalty(x, args) + n_log_scale class _ShapeInfo: def __init__(self, name, integrality=False, domain=(-np.inf, np.inf), inclusive=(True, True)): self.name = name self.integrality = integrality domain = list(domain) if np.isfinite(domain[0]) and not inclusive[0]: domain[0] = np.nextafter(domain[0], np.inf) if np.isfinite(domain[1]) and not inclusive[1]: domain[1] = np.nextafter(domain[1], -np.inf) self.domain = domain def _get_fixed_fit_value(kwds, names): """ Given names such as `['f0', 'fa', 'fix_a']`, check that there is at most one non-None value in `kwds` associaed with those names. Return that value, or None if none of the names occur in `kwds`. As a side effect, all occurrences of those names in `kwds` are removed. """ vals = [(name, kwds.pop(name)) for name in names if name in kwds] if len(vals) > 1: repeated = [name for name, val in vals] raise ValueError("fit method got multiple keyword arguments to " "specify the same fixed parameter: " + ', '.join(repeated)) return vals[0][1] if vals else None # continuous random variables: implement maybe later # # hf --- Hazard Function (PDF / SF) # chf --- Cumulative hazard function (-log(SF)) # psf --- Probability sparsity function (reciprocal of the pdf) in # units of percent-point-function (as a function of q). # Also, the derivative of the percent-point function. class rv_continuous(rv_generic): """A generic continuous random variable class meant for subclassing. `rv_continuous` is a base class to construct specific distribution classes and instances for continuous random variables. It cannot be used directly as a distribution. Parameters ---------- momtype : int, optional The type of generic moment calculation to use: 0 for pdf, 1 (default) for ppf. a : float, optional Lower bound of the support of the distribution, default is minus infinity. b : float, optional Upper bound of the support of the distribution, default is plus infinity. xtol : float, optional The tolerance for fixed point calculation for generic ppf. badvalue : float, optional The value in a result arrays that indicates a value that for which some argument restriction is violated, default is np.nan. name : str, optional The name of the instance. This string is used to construct the default example for distributions. longname : str, optional This string is used as part of the first line of the docstring returned when a subclass has no docstring of its own. Note: `longname` exists for backwards compatibility, do not use for new subclasses. shapes : str, optional The shape of the distribution. For example ``"m, n"`` for a distribution that takes two integers as the two shape arguments for all its methods. If not provided, shape parameters will be inferred from the signature of the private methods, ``_pdf`` and ``_cdf`` of the instance. extradoc : str, optional, deprecated This string is used as the last part of the docstring returned when a subclass has no docstring of its own. Note: `extradoc` exists for backwards compatibility, do not use for new subclasses. seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Methods ------- rvs pdf logpdf cdf logcdf sf logsf ppf isf moment stats entropy expect median mean std var interval __call__ fit fit_loc_scale nnlf support Notes ----- Public methods of an instance of a distribution class (e.g., ``pdf``, ``cdf``) check their arguments and pass valid arguments to private, computational methods (``_pdf``, ``_cdf``). For ``pdf(x)``, ``x`` is valid if it is within the support of the distribution. Whether a shape parameter is valid is decided by an ``_argcheck`` method (which defaults to checking that its arguments are strictly positive.) **Subclassing** New random variables can be defined by subclassing the `rv_continuous` class and re-defining at least the ``_pdf`` or the ``_cdf`` method (normalized to location 0 and scale 1). If positive argument checking is not correct for your RV then you will also need to re-define the ``_argcheck`` method. For most of the scipy.stats distributions, the support interval doesn't depend on the shape parameters. ``x`` being in the support interval is equivalent to ``self.a <= x <= self.b``. If either of the endpoints of the support do depend on the shape parameters, then i) the distribution must implement the ``_get_support`` method; and ii) those dependent endpoints must be omitted from the distribution's call to the ``rv_continuous`` initializer. Correct, but potentially slow defaults exist for the remaining methods but for speed and/or accuracy you can over-ride:: _logpdf, _cdf, _logcdf, _ppf, _rvs, _isf, _sf, _logsf The default method ``_rvs`` relies on the inverse of the cdf, ``_ppf``, applied to a uniform random variate. In order to generate random variates efficiently, either the default ``_ppf`` needs to be overwritten (e.g. if the inverse cdf can expressed in an explicit form) or a sampling method needs to be implemented in a custom ``_rvs`` method. If possible, you should override ``_isf``, ``_sf`` or ``_logsf``. The main reason would be to improve numerical accuracy: for example, the survival function ``_sf`` is computed as ``1 - _cdf`` which can result in loss of precision if ``_cdf(x)`` is close to one. **Methods that can be overwritten by subclasses** :: _rvs _pdf _cdf _sf _ppf _isf _stats _munp _entropy _argcheck _get_support There are additional (internal and private) generic methods that can be useful for cross-checking and for debugging, but might work in all cases when directly called. A note on ``shapes``: subclasses need not specify them explicitly. In this case, `shapes` will be automatically deduced from the signatures of the overridden methods (`pdf`, `cdf` etc). If, for some reason, you prefer to avoid relying on introspection, you can specify ``shapes`` explicitly as an argument to the instance constructor. **Frozen Distributions** Normally, you must provide shape parameters (and, optionally, location and scale parameters to each call of a method of a distribution. Alternatively, the object may be called (as a function) to fix the shape, location, and scale parameters returning a "frozen" continuous RV object: rv = generic(<shape(s)>, loc=0, scale=1) `rv_frozen` object with the same methods but holding the given shape, location, and scale fixed **Statistics** Statistics are computed using numerical integration by default. For speed you can redefine this using ``_stats``: - take shape parameters and return mu, mu2, g1, g2 - If you can't compute one of these, return it as None - Can also be defined with a keyword argument ``moments``, which is a string composed of "m", "v", "s", and/or "k". Only the components appearing in string should be computed and returned in the order "m", "v", "s", or "k" with missing values returned as None. Alternatively, you can override ``_munp``, which takes ``n`` and shape parameters and returns the n-th non-central moment of the distribution. Examples -------- To create a new Gaussian distribution, we would do the following: >>> from scipy.stats import rv_continuous >>> class gaussian_gen(rv_continuous): ... "Gaussian distribution" ... def _pdf(self, x): ... return np.exp(-x**2 / 2.) / np.sqrt(2.0 * np.pi) >>> gaussian = gaussian_gen(name='gaussian') ``scipy.stats`` distributions are *instances*, so here we subclass `rv_continuous` and create an instance. With this, we now have a fully functional distribution with all relevant methods automagically generated by the framework. Note that above we defined a standard normal distribution, with zero mean and unit variance. Shifting and scaling of the distribution can be done by using ``loc`` and ``scale`` parameters: ``gaussian.pdf(x, loc, scale)`` essentially computes ``y = (x - loc) / scale`` and ``gaussian._pdf(y) / scale``. """ def __init__(self, momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None): super().__init__(seed) if extradoc is not None: warnings.warn("extradoc is deprecated and will be removed in " "SciPy 1.11.0", DeprecationWarning) # save the ctor parameters, cf generic freeze self._ctor_param = dict( momtype=momtype, a=a, b=b, xtol=xtol, badvalue=badvalue, name=name, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan if name is None: name = 'Distribution' self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -inf if b is None: self.b = inf self.xtol = xtol self.moment_type = momtype self.shapes = shapes self.extradoc = extradoc self._construct_argparser(meths_to_inspect=[self._pdf, self._cdf], locscale_in='loc=0, scale=1', locscale_out='loc, scale') self._attach_methods() if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " else: hstr = "A " longname = hstr + name if sys.flags.optimize < 2: # Skip adding docstrings if interpreter is run with -OO if self.__doc__ is None: self._construct_default_doc(longname=longname, extradoc=extradoc, docdict=docdict, discrete='continuous') else: dct = dict(distcont) self._construct_doc(docdict, dct.get(self.name)) def __getstate__(self): dct = self.__dict__.copy() # these methods will be remade in __setstate__ # _random_state attribute is taken care of by rv_generic attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs", "_cdfvec", "_ppfvec", "vecentropy", "generic_moment"] [dct.pop(attr, None) for attr in attrs] return dct def _attach_methods(self): """ Attaches dynamically created methods to the rv_continuous instance. """ # _attach_methods is responsible for calling _attach_argparser_methods self._attach_argparser_methods() # nin correction self._ppfvec = vectorize(self._ppf_single, otypes='d') self._ppfvec.nin = self.numargs + 1 self.vecentropy = vectorize(self._entropy, otypes='d') self._cdfvec = vectorize(self._cdf_single, otypes='d') self._cdfvec.nin = self.numargs + 1 if self.moment_type == 0: self.generic_moment = vectorize(self._mom0_sc, otypes='d') else: self.generic_moment = vectorize(self._mom1_sc, otypes='d') # Because of the *args argument of _mom0_sc, vectorize cannot count the # number of arguments correctly. self.generic_moment.nin = self.numargs + 1 def _updated_ctor_param(self): """Return the current version of _ctor_param, possibly updated by user. Used by freezing. Keep this in sync with the signature of __init__. """ dct = self._ctor_param.copy() dct['a'] = self.a dct['b'] = self.b dct['xtol'] = self.xtol dct['badvalue'] = self.badvalue dct['name'] = self.name dct['shapes'] = self.shapes dct['extradoc'] = self.extradoc return dct def _ppf_to_solve(self, x, q, *args): return self.cdf(*(x, )+args)-q def _ppf_single(self, q, *args): factor = 10. left, right = self._get_support(*args) if np.isinf(left): left = min(-factor, right) while self._ppf_to_solve(left, q, *args) > 0.: left, right = left * factor, left # left is now such that cdf(left) <= q # if right has changed, then cdf(right) > q if np.isinf(right): right = max(factor, left) while self._ppf_to_solve(right, q, *args) < 0.: left, right = right, right * factor # right is now such that cdf(right) >= q return optimize.brentq(self._ppf_to_solve, left, right, args=(q,)+args, xtol=self.xtol) # moment from definition def _mom_integ0(self, x, m, *args): return x**m * self.pdf(x, *args) def _mom0_sc(self, m, *args): _a, _b = self._get_support(*args) return integrate.quad(self._mom_integ0, _a, _b, args=(m,)+args)[0] # moment calculated using ppf def _mom_integ1(self, q, m, *args): return (self.ppf(q, *args))**m def _mom1_sc(self, m, *args): return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0] def _pdf(self, x, *args): return derivative(self._cdf, x, dx=1e-5, args=args, order=5) # Could also define any of these def _logpdf(self, x, *args): p = self._pdf(x, *args) with np.errstate(divide='ignore'): return log(p) def _logpxf(self, x, *args): # continuous distributions have PDF, discrete have PMF, but sometimes # the distinction doesn't matter. This lets us use `_logpxf` for both # discrete and continuous distributions. return self._logpdf(x, *args) def _cdf_single(self, x, *args): _a, _b = self._get_support(*args) return integrate.quad(self._pdf, _a, x, args=args)[0] def _cdf(self, x, *args): return self._cdfvec(x, *args) # generic _argcheck, _logcdf, _sf, _logsf, _ppf, _isf, _rvs are defined # in rv_generic def pdf(self, x, *args, **kwds): """Probability density function at x of the given RV. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- pdf : ndarray Probability density function evaluated at x """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._support_mask(x, *args) & (scale > 0) cond = cond0 & cond1 output = zeros(shape(cond), dtyp) putmask(output, (1-cond0)+np.isnan(x), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args+(scale,))) scale, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._pdf(*goodargs) / scale) if output.ndim == 0: return output[()] return output def logpdf(self, x, *args, **kwds): """Log of the probability density function at x of the given RV. This uses a more numerically accurate calculation if available. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- logpdf : array_like Log of the probability density function evaluated at x """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._support_mask(x, *args) & (scale > 0) cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) putmask(output, (1-cond0)+np.isnan(x), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args+(scale,))) scale, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._logpdf(*goodargs) - log(scale)) if output.ndim == 0: return output[()] return output def cdf(self, x, *args, **kwds): """ Cumulative distribution function of the given RV. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- cdf : ndarray Cumulative distribution function evaluated at `x` """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = (x >= np.asarray(_b)) & cond0 cond = cond0 & cond1 output = zeros(shape(cond), dtyp) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 1.0) if np.any(cond): # call only if at least 1 entry goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._cdf(*goodargs)) if output.ndim == 0: return output[()] return output def logcdf(self, x, *args, **kwds): """Log of the cumulative distribution function at x of the given RV. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- logcdf : array_like Log of the cumulative distribution function evaluated at x """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = (x >= _b) & cond0 cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) place(output, (1-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue) place(output, cond2, 0.0) if np.any(cond): # call only if at least 1 entry goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._logcdf(*goodargs)) if output.ndim == 0: return output[()] return output def sf(self, x, *args, **kwds): """Survival function (1 - `cdf`) at x of the given RV. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- sf : array_like Survival function evaluated at x """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = cond0 & (x <= _a) cond = cond0 & cond1 output = zeros(shape(cond), dtyp) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 1.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._sf(*goodargs)) if output.ndim == 0: return output[()] return output def logsf(self, x, *args, **kwds): """Log of the survival function of the given RV. Returns the log of the "survival function," defined as (1 - `cdf`), evaluated at `x`. Parameters ---------- x : array_like quantiles arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- logsf : ndarray Log of the survival function evaluated at `x`. """ args, loc, scale = self._parse_args(*args, **kwds) x, loc, scale = map(asarray, (x, loc, scale)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) dtyp = np.find_common_type([x.dtype, np.float64], []) x = np.asarray((x - loc)/scale, dtype=dtyp) cond0 = self._argcheck(*args) & (scale > 0) cond1 = self._open_support_mask(x, *args) & (scale > 0) cond2 = cond0 & (x <= _a) cond = cond0 & cond1 output = empty(shape(cond), dtyp) output.fill(NINF) place(output, (1-cond0)+np.isnan(x), self.badvalue) place(output, cond2, 0.0) if np.any(cond): goodargs = argsreduce(cond, *((x,)+args)) place(output, cond, self._logsf(*goodargs)) if output.ndim == 0: return output[()] return output def ppf(self, q, *args, **kwds): """Percent point function (inverse of `cdf`) at q of the given RV. Parameters ---------- q : array_like lower tail probability arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- x : array_like quantile corresponding to the lower tail probability q. """ args, loc, scale = self._parse_args(*args, **kwds) q, loc, scale = map(asarray, (q, loc, scale)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) cond1 = (0 < q) & (q < 1) cond2 = cond0 & (q == 0) cond3 = cond0 & (q == 1) cond = cond0 & cond1 output = np.full(shape(cond), fill_value=self.badvalue) lower_bound = _a * scale + loc upper_bound = _b * scale + loc place(output, cond2, argsreduce(cond2, lower_bound)[0]) place(output, cond3, argsreduce(cond3, upper_bound)[0]) if np.any(cond): # call only if at least 1 entry goodargs = argsreduce(cond, *((q,)+args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] place(output, cond, self._ppf(*goodargs) * scale + loc) if output.ndim == 0: return output[()] return output def isf(self, q, *args, **kwds): """Inverse survival function (inverse of `sf`) at q of the given RV. Parameters ---------- q : array_like upper tail probability arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional location parameter (default=0) scale : array_like, optional scale parameter (default=1) Returns ------- x : ndarray or scalar Quantile corresponding to the upper tail probability q. """ args, loc, scale = self._parse_args(*args, **kwds) q, loc, scale = map(asarray, (q, loc, scale)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc) cond1 = (0 < q) & (q < 1) cond2 = cond0 & (q == 1) cond3 = cond0 & (q == 0) cond = cond0 & cond1 output = np.full(shape(cond), fill_value=self.badvalue) lower_bound = _a * scale + loc upper_bound = _b * scale + loc place(output, cond2, argsreduce(cond2, lower_bound)[0]) place(output, cond3, argsreduce(cond3, upper_bound)[0]) if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(scale, loc))) scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] place(output, cond, self._isf(*goodargs) * scale + loc) if output.ndim == 0: return output[()] return output def _unpack_loc_scale(self, theta): try: loc = theta[-2] scale = theta[-1] args = tuple(theta[:-2]) except IndexError as e: raise ValueError("Not enough input arguments.") from e return loc, scale, args def _fitstart(self, data, args=None): """Starting point for fit (shape arguments + loc + scale).""" if args is None: args = (1.0,)*self.numargs loc, scale = self._fit_loc_scale_support(data, *args) return args + (loc, scale) def _reduce_func(self, args, kwds, data=None): """ Return the (possibly reduced) function to optimize in order to find MLE estimates for the .fit method. """ # Convert fixed shape parameters to the standard numeric form: e.g. for # stats.beta, shapes='a, b'. To fix `a`, the caller can give a value # for `f0`, `fa` or 'fix_a'. The following converts the latter two # into the first (numeric) form. shapes = [] if self.shapes: shapes = self.shapes.replace(',', ' ').split() for j, s in enumerate(shapes): key = 'f' + str(j) names = [key, 'f' + s, 'fix_' + s] val = _get_fixed_fit_value(kwds, names) if val is not None: kwds[key] = val args = list(args) Nargs = len(args) fixedn = [] names = ['f%d' % n for n in range(Nargs - 2)] + ['floc', 'fscale'] x0 = [] for n, key in enumerate(names): if key in kwds: fixedn.append(n) args[n] = kwds.pop(key) else: x0.append(args[n]) methods = {"mle", "mm"} method = kwds.pop('method', "mle").lower() if method == "mm": n_params = len(shapes) + 2 - len(fixedn) exponents = (np.arange(1, n_params+1))[:, np.newaxis] data_moments = np.sum(data[None, :]**exponents/len(data), axis=1) def objective(theta, x): return self._moment_error(theta, x, data_moments) elif method == "mle": objective = self._penalized_nnlf else: raise ValueError("Method '{0}' not available; must be one of {1}" .format(method, methods)) if len(fixedn) == 0: func = objective restore = None else: if len(fixedn) == Nargs: raise ValueError( "All parameters fixed. There is nothing to optimize.") def restore(args, theta): # Replace with theta for all numbers not in fixedn # This allows the non-fixed values to vary, but # we still call self.nnlf with all parameters. i = 0 for n in range(Nargs): if n not in fixedn: args[n] = theta[i] i += 1 return args def func(theta, x): newtheta = restore(args[:], theta) return objective(newtheta, x) return x0, func, restore, args def _moment_error(self, theta, x, data_moments): loc, scale, args = self._unpack_loc_scale(theta) if not self._argcheck(*args) or scale <= 0: return inf dist_moments = np.array([self.moment(i+1, *args, loc=loc, scale=scale) for i in range(len(data_moments))]) if np.any(np.isnan(dist_moments)): raise ValueError("Method of moments encountered a non-finite " "distribution moment and cannot continue. " "Consider trying method='MLE'.") return (((data_moments - dist_moments) / np.maximum(np.abs(data_moments), 1e-8))**2).sum() def fit(self, data, *args, **kwds): """ Return estimates of shape (if applicable), location, and scale parameters from data. The default estimation method is Maximum Likelihood Estimation (MLE), but Method of Moments (MM) is also available. Starting estimates for the fit are given by input arguments; for any arguments not provided with starting estimates, ``self._fitstart(data)`` is called to generate such. One can hold some parameters fixed to specific values by passing in keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters) and ``floc`` and ``fscale`` (for location and scale parameters, respectively). Parameters ---------- data : array_like Data to use in estimating the distribution parameters. arg1, arg2, arg3,... : floats, optional Starting value(s) for any shape-characterizing arguments (those not provided will be determined by a call to ``_fitstart(data)``). No default value. **kwds : floats, optional - `loc`: initial guess of the distribution's location parameter. - `scale`: initial guess of the distribution's scale parameter. Special keyword arguments are recognized as holding certain parameters fixed: - f0...fn : hold respective shape parameters fixed. Alternatively, shape parameters to fix can be specified by name. For example, if ``self.shapes == "a, b"``, ``fa`` and ``fix_a`` are equivalent to ``f0``, and ``fb`` and ``fix_b`` are equivalent to ``f1``. - floc : hold location parameter fixed to specified value. - fscale : hold scale parameter fixed to specified value. - optimizer : The optimizer to use. The optimizer must take ``func``, and starting position as the first two arguments, plus ``args`` (for extra arguments to pass to the function to be optimized) and ``disp=0`` to suppress output as keyword arguments. - method : The method to use. The default is "MLE" (Maximum Likelihood Estimate); "MM" (Method of Moments) is also available. Returns ------- parameter_tuple : tuple of floats Estimates for any shape parameters (if applicable), followed by those for location and scale. For most random variables, shape statistics will be returned, but there are exceptions (e.g. ``norm``). Notes ----- With ``method="MLE"`` (default), the fit is computed by minimizing the negative log-likelihood function. A large, finite penalty (rather than infinite negative log-likelihood) is applied for observations beyond the support of the distribution. With ``method="MM"``, the fit is computed by minimizing the L2 norm of the relative errors between the first *k* raw (about zero) data moments and the corresponding distribution moments, where *k* is the number of non-fixed parameters. More precisely, the objective function is:: (((data_moments - dist_moments) / np.maximum(np.abs(data_moments), 1e-8))**2).sum() where the constant ``1e-8`` avoids division by zero in case of vanishing data moments. Typically, this error norm can be reduced to zero. Note that the standard method of moments can produce parameters for which some data are outside the support of the fitted distribution; this implementation does nothing to prevent this. For either method, the returned answer is not guaranteed to be globally optimal; it may only be locally optimal, or the optimization may fail altogether. If the data contain any of ``np.nan``, ``np.inf``, or ``-np.inf``, the `fit` method will raise a ``RuntimeError``. Examples -------- Generate some data to fit: draw random variates from the `beta` distribution >>> from scipy.stats import beta >>> a, b = 1., 2. >>> x = beta.rvs(a, b, size=1000) Now we can fit all four parameters (``a``, ``b``, ``loc`` and ``scale``): >>> a1, b1, loc1, scale1 = beta.fit(x) We can also use some prior knowledge about the dataset: let's keep ``loc`` and ``scale`` fixed: >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1) >>> loc1, scale1 (0, 1) We can also keep shape parameters fixed by using ``f``-keywords. To keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or, equivalently, ``fa=1``: >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1) >>> a1 1 Not all distributions return estimates for the shape parameters. ``norm`` for example just returns estimates for location and scale: >>> from scipy.stats import norm >>> x = norm.rvs(a, b, size=1000, random_state=123) >>> loc1, scale1 = norm.fit(x) >>> loc1, scale1 (0.92087172783841631, 2.0015750750324668) """ data = np.asarray(data) method = kwds.get('method', "mle").lower() # memory for method of moments Narg = len(args) if Narg > self.numargs: raise TypeError("Too many input arguments.") if not np.isfinite(data).all(): raise RuntimeError("The data contains non-finite values.") start = [None]*2 if (Narg < self.numargs) or not ('loc' in kwds and 'scale' in kwds): # get distribution specific starting locations start = self._fitstart(data) args += start[Narg:-2] loc = kwds.pop('loc', start[-2]) scale = kwds.pop('scale', start[-1]) args += (loc, scale) x0, func, restore, args = self._reduce_func(args, kwds, data=data) optimizer = kwds.pop('optimizer', optimize.fmin) # convert string to function in scipy.optimize optimizer = _fit_determine_optimizer(optimizer) # by now kwds must be empty, since everybody took what they needed if kwds: raise TypeError("Unknown arguments: %s." % kwds) # In some cases, method of moments can be done with fsolve/root # instead of an optimizer, but sometimes no solution exists, # especially when the user fixes parameters. Minimizing the sum # of squares of the error generalizes to these cases. vals = optimizer(func, x0, args=(ravel(data),), disp=0) obj = func(vals, data) if restore is not None: vals = restore(args, vals) vals = tuple(vals) loc, scale, shapes = self._unpack_loc_scale(vals) if not (np.all(self._argcheck(*shapes)) and scale > 0): raise Exception("Optimization converged to parameters that are " "outside the range allowed by the distribution.") if method == 'mm': if not np.isfinite(obj): raise Exception("Optimization failed: either a data moment " "or fitted distribution moment is " "non-finite.") return vals def _fit_loc_scale_support(self, data, *args): """Estimate loc and scale parameters from data accounting for support. Parameters ---------- data : array_like Data to fit. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- Lhat : float Estimated location parameter for the data. Shat : float Estimated scale parameter for the data. """ data = np.asarray(data) # Estimate location and scale according to the method of moments. loc_hat, scale_hat = self.fit_loc_scale(data, *args) # Compute the support according to the shape parameters. self._argcheck(*args) _a, _b = self._get_support(*args) a, b = _a, _b support_width = b - a # If the support is empty then return the moment-based estimates. if support_width <= 0: return loc_hat, scale_hat # Compute the proposed support according to the loc and scale # estimates. a_hat = loc_hat + a * scale_hat b_hat = loc_hat + b * scale_hat # Use the moment-based estimates if they are compatible with the data. data_a = np.min(data) data_b = np.max(data) if a_hat < data_a and data_b < b_hat: return loc_hat, scale_hat # Otherwise find other estimates that are compatible with the data. data_width = data_b - data_a rel_margin = 0.1 margin = data_width * rel_margin # For a finite interval, both the location and scale # should have interesting values. if support_width < np.inf: loc_hat = (data_a - a) - margin scale_hat = (data_width + 2 * margin) / support_width return loc_hat, scale_hat # For a one-sided interval, use only an interesting location parameter. if a > -np.inf: return (data_a - a) - margin, 1 elif b < np.inf: return (data_b - b) + margin, 1 else: raise RuntimeError def fit_loc_scale(self, data, *args): """ Estimate loc and scale parameters from data using 1st and 2nd moments. Parameters ---------- data : array_like Data to fit. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- Lhat : float Estimated location parameter for the data. Shat : float Estimated scale parameter for the data. """ mu, mu2 = self.stats(*args, **{'moments': 'mv'}) tmp = asarray(data) muhat = tmp.mean() mu2hat = tmp.var() Shat = sqrt(mu2hat / mu2) Lhat = muhat - Shat*mu if not np.isfinite(Lhat): Lhat = 0 if not (np.isfinite(Shat) and (0 < Shat)): Shat = 1 return Lhat, Shat def _entropy(self, *args): def integ(x): val = self._pdf(x, *args) return entr(val) # upper limit is often inf, so suppress warnings when integrating _a, _b = self._get_support(*args) with np.errstate(over='ignore'): h = integrate.quad(integ, _a, _b)[0] if not np.isnan(h): return h else: # try with different limits if integration problems low, upp = self.ppf([1e-10, 1. - 1e-10], *args) if np.isinf(_b): upper = upp else: upper = _b if np.isinf(_a): lower = low else: lower = _a return integrate.quad(integ, lower, upper)[0] def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds): """Calculate expected value of a function with respect to the distribution by numerical integration. The expected value of a function ``f(x)`` with respect to a distribution ``dist`` is defined as:: ub E[f(x)] = Integral(f(x) * dist.pdf(x)), lb where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)`` distribution. If the bounds ``lb`` and ``ub`` correspond to the support of the distribution, e.g. ``[-inf, inf]`` in the default case, then the integral is the unrestricted expectation of ``f(x)``. Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0`` outside a finite interval in which case the expectation is calculated within the finite range ``[lb, ub]``. Parameters ---------- func : callable, optional Function for which integral is calculated. Takes only one argument. The default is the identity mapping f(x) = x. args : tuple, optional Shape parameters of the distribution. loc : float, optional Location parameter (default=0). scale : float, optional Scale parameter (default=1). lb, ub : scalar, optional Lower and upper bound for integration. Default is set to the support of the distribution. conditional : bool, optional If True, the integral is corrected by the conditional probability of the integration interval. The return value is the expectation of the function, conditional on being in the given interval. Default is False. Additional keyword arguments are passed to the integration routine. Returns ------- expect : float The calculated expected value. Notes ----- The integration behavior of this function is inherited from `scipy.integrate.quad`. Neither this function nor `scipy.integrate.quad` can verify whether the integral exists or is finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and ``cauchy(0).expect()`` returns ``0.0``. The function is not vectorized. Examples -------- To understand the effect of the bounds of integration consider >>> from scipy.stats import expon >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0) 0.6321205588285578 This is close to >>> expon(1).cdf(2.0) - expon(1).cdf(0.0) 0.6321205588285577 If ``conditional=True`` >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True) 1.0000000000000002 The slight deviation from 1 is due to numerical integration. """ lockwds = {'loc': loc, 'scale': scale} self._argcheck(*args) _a, _b = self._get_support(*args) if func is None: def fun(x, *args): return x * self.pdf(x, *args, **lockwds) else: def fun(x, *args): return func(x) * self.pdf(x, *args, **lockwds) if lb is None: lb = loc + _a * scale if ub is None: ub = loc + _b * scale if conditional: invfac = (self.sf(lb, *args, **lockwds) - self.sf(ub, *args, **lockwds)) else: invfac = 1.0 kwds['args'] = args # Silence floating point warnings from integration. with np.errstate(all='ignore'): vals = integrate.quad(fun, lb, ub, **kwds)[0] / invfac return vals def _param_info(self): shape_info = self._shape_info() loc_info = _ShapeInfo("loc", False, (-np.inf, np.inf), (False, False)) scale_info = _ShapeInfo("scale", False, (0, np.inf), (False, False)) param_info = shape_info + [loc_info, scale_info] return param_info # Helpers for the discrete distributions def _drv2_moment(self, n, *args): """Non-central moment of discrete distribution.""" def fun(x): return np.power(x, n) * self._pmf(x, *args) _a, _b = self._get_support(*args) return _expect(fun, _a, _b, self.ppf(0.5, *args), self.inc) def _drv2_ppfsingle(self, q, *args): # Use basic bisection algorithm _a, _b = self._get_support(*args) b = _b a = _a if isinf(b): # Be sure ending point is > q b = int(max(100*q, 10)) while 1: if b >= _b: qb = 1.0 break qb = self._cdf(b, *args) if (qb < q): b += 10 else: break else: qb = 1.0 if isinf(a): # be sure starting point < q a = int(min(-100*q, -10)) while 1: if a <= _a: qb = 0.0 break qa = self._cdf(a, *args) if (qa > q): a -= 10 else: break else: qa = self._cdf(a, *args) while 1: if (qa == q): return a if (qb == q): return b if b <= a+1: if qa > q: return a else: return b c = int((a+b)/2.0) qc = self._cdf(c, *args) if (qc < q): if a != c: a = c else: raise RuntimeError('updating stopped, endless loop') qa = qc elif (qc > q): if b != c: b = c else: raise RuntimeError('updating stopped, endless loop') qb = qc else: return c # Must over-ride one of _pmf or _cdf or pass in # x_k, p(x_k) lists in initialization class rv_discrete(rv_generic): """A generic discrete random variable class meant for subclassing. `rv_discrete` is a base class to construct specific distribution classes and instances for discrete random variables. It can also be used to construct an arbitrary distribution defined by a list of support points and corresponding probabilities. Parameters ---------- a : float, optional Lower bound of the support of the distribution, default: 0 b : float, optional Upper bound of the support of the distribution, default: plus infinity moment_tol : float, optional The tolerance for the generic calculation of moments. values : tuple of two array_like, optional ``(xk, pk)`` where ``xk`` are integers and ``pk`` are the non-zero probabilities between 0 and 1 with ``sum(pk) = 1``. ``xk`` and ``pk`` must have the same shape. inc : integer, optional Increment for the support of the distribution. Default is 1. (other values have not been tested) badvalue : float, optional The value in a result arrays that indicates a value that for which some argument restriction is violated, default is np.nan. name : str, optional The name of the instance. This string is used to construct the default example for distributions. longname : str, optional This string is used as part of the first line of the docstring returned when a subclass has no docstring of its own. Note: `longname` exists for backwards compatibility, do not use for new subclasses. shapes : str, optional The shape of the distribution. For example "m, n" for a distribution that takes two integers as the two shape arguments for all its methods If not provided, shape parameters will be inferred from the signatures of the private methods, ``_pmf`` and ``_cdf`` of the instance. extradoc : str, optional, deprecated This string is used as the last part of the docstring returned when a subclass has no docstring of its own. Note: `extradoc` exists for backwards compatibility, do not use for new subclasses. seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Methods ------- rvs pmf logpmf cdf logcdf sf logsf ppf isf moment stats entropy expect median mean std var interval __call__ support Notes ----- This class is similar to `rv_continuous`. Whether a shape parameter is valid is decided by an ``_argcheck`` method (which defaults to checking that its arguments are strictly positive.) The main differences are: - the support of the distribution is a set of integers - instead of the probability density function, ``pdf`` (and the corresponding private ``_pdf``), this class defines the *probability mass function*, `pmf` (and the corresponding private ``_pmf``.) - scale parameter is not defined. To create a new discrete distribution, we would do the following: >>> from scipy.stats import rv_discrete >>> class poisson_gen(rv_discrete): ... "Poisson distribution" ... def _pmf(self, k, mu): ... return exp(-mu) * mu**k / factorial(k) and create an instance:: >>> poisson = poisson_gen(name="poisson") Note that above we defined the Poisson distribution in the standard form. Shifting the distribution can be done by providing the ``loc`` parameter to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)`` delegates the work to ``poisson._pmf(x-loc, mu)``. **Discrete distributions from a list of probabilities** Alternatively, you can construct an arbitrary discrete rv defined on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the ``values`` keyword argument to the `rv_discrete` constructor. Examples -------- Custom made discrete distribution: >>> from scipy import stats >>> xk = np.arange(7) >>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2) >>> custm = stats.rv_discrete(name='custm', values=(xk, pk)) >>> >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) >>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r') >>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4) >>> plt.show() Random number generation: >>> R = custm.rvs(size=100) """ def __new__(cls, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): if values is not None: # dispatch to a subclass return super(rv_discrete, cls).__new__(rv_sample) else: # business as usual return super(rv_discrete, cls).__new__(cls) def __init__(self, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): super().__init__(seed) if extradoc is not None: warnings.warn("extradoc is deprecated and will be removed in " "SciPy 1.11.0", DeprecationWarning) # cf generic freeze self._ctor_param = dict( a=a, b=b, name=name, badvalue=badvalue, moment_tol=moment_tol, values=values, inc=inc, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan self.badvalue = badvalue self.a = a self.b = b self.moment_tol = moment_tol self.inc = inc self.shapes = shapes if values is not None: raise ValueError("rv_discrete.__init__(..., values != None, ...)") self._construct_argparser(meths_to_inspect=[self._pmf, self._cdf], locscale_in='loc=0', # scale=1 for discrete RVs locscale_out='loc, 1') self._attach_methods() self._construct_docstrings(name, longname, extradoc) def __getstate__(self): dct = self.__dict__.copy() # these methods will be remade in __setstate__ attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs", "_cdfvec", "_ppfvec", "generic_moment"] [dct.pop(attr, None) for attr in attrs] return dct def _attach_methods(self): """Attaches dynamically created methods to the rv_discrete instance.""" self._cdfvec = vectorize(self._cdf_single, otypes='d') self.vecentropy = vectorize(self._entropy) # _attach_methods is responsible for calling _attach_argparser_methods self._attach_argparser_methods() # nin correction needs to be after we know numargs # correct nin for generic moment vectorization _vec_generic_moment = vectorize(_drv2_moment, otypes='d') _vec_generic_moment.nin = self.numargs + 2 self.generic_moment = types.MethodType(_vec_generic_moment, self) # correct nin for ppf vectorization _vppf = vectorize(_drv2_ppfsingle, otypes='d') _vppf.nin = self.numargs + 2 self._ppfvec = types.MethodType(_vppf, self) # now that self.numargs is defined, we can adjust nin self._cdfvec.nin = self.numargs + 1 def _construct_docstrings(self, name, longname, extradoc): if name is None: name = 'Distribution' self.name = name self.extradoc = extradoc # generate docstring for subclass instances if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " else: hstr = "A " longname = hstr + name if sys.flags.optimize < 2: # Skip adding docstrings if interpreter is run with -OO if self.__doc__ is None: self._construct_default_doc(longname=longname, extradoc=extradoc, docdict=docdict_discrete, discrete='discrete') else: dct = dict(distdiscrete) self._construct_doc(docdict_discrete, dct.get(self.name)) # discrete RV do not have the scale parameter, remove it self.__doc__ = self.__doc__.replace( '\n scale : array_like, ' 'optional\n scale parameter (default=1)', '') def _updated_ctor_param(self): """Return the current version of _ctor_param, possibly updated by user. Used by freezing. Keep this in sync with the signature of __init__. """ dct = self._ctor_param.copy() dct['a'] = self.a dct['b'] = self.b dct['badvalue'] = self.badvalue dct['moment_tol'] = self.moment_tol dct['inc'] = self.inc dct['name'] = self.name dct['shapes'] = self.shapes dct['extradoc'] = self.extradoc return dct def _nonzero(self, k, *args): return floor(k) == k def _pmf(self, k, *args): return self._cdf(k, *args) - self._cdf(k-1, *args) def _logpmf(self, k, *args): return log(self._pmf(k, *args)) def _logpxf(self, k, *args): # continuous distributions have PDF, discrete have PMF, but sometimes # the distinction doesn't matter. This lets us use `_logpxf` for both # discrete and continuous distributions. return self._logpmf(k, *args) def _unpack_loc_scale(self, theta): try: loc = theta[-1] scale = 1 args = tuple(theta[:-1]) except IndexError as e: raise ValueError("Not enough input arguments.") from e return loc, scale, args def _cdf_single(self, k, *args): _a, _b = self._get_support(*args) m = arange(int(_a), k+1) return np.sum(self._pmf(m, *args), axis=0) def _cdf(self, x, *args): k = floor(x) return self._cdfvec(k, *args) # generic _logcdf, _sf, _logsf, _ppf, _isf, _rvs defined in rv_generic def rvs(self, *args, **kwargs): """Random variates of given type. Parameters ---------- arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). size : int or tuple of ints, optional Defining number of random variates (Default is 1). Note that `size` has to be given as keyword, not as positional argument. random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Returns ------- rvs : ndarray or scalar Random variates of given `size`. """ kwargs['discrete'] = True return super().rvs(*args, **kwargs) def pmf(self, k, *args, **kwds): """Probability mass function at k of the given RV. Parameters ---------- k : array_like Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information) loc : array_like, optional Location parameter (default=0). Returns ------- pmf : array_like Probability mass function evaluated at k """ args, loc, _ = self._parse_args(*args, **kwds) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k <= _b) & self._nonzero(k, *args) cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, (1-cond0) + np.isnan(k), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._pmf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logpmf(self, k, *args, **kwds): """Log of the probability mass function at k of the given RV. Parameters ---------- k : array_like Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter. Default is 0. Returns ------- logpmf : array_like Log of the probability mass function evaluated at k. """ args, loc, _ = self._parse_args(*args, **kwds) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k <= _b) & self._nonzero(k, *args) cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logpmf(*goodargs)) if output.ndim == 0: return output[()] return output def cdf(self, k, *args, **kwds): """Cumulative distribution function of the given RV. Parameters ---------- k : array_like, int Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- cdf : ndarray Cumulative distribution function evaluated at `k`. """ args, loc, _ = self._parse_args(*args, **kwds) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k >= _b) cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, cond2*(cond0 == cond0), 1.0) place(output, (1-cond0) + np.isnan(k), self.badvalue) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._cdf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logcdf(self, k, *args, **kwds): """Log of the cumulative distribution function at k of the given RV. Parameters ---------- k : array_like, int Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- logcdf : array_like Log of the cumulative distribution function evaluated at k. """ args, loc, _ = self._parse_args(*args, **kwds) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) k = asarray((k-loc)) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k >= _b) cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2*(cond0 == cond0), 0.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logcdf(*goodargs)) if output.ndim == 0: return output[()] return output def sf(self, k, *args, **kwds): """Survival function (1 - `cdf`) at k of the given RV. Parameters ---------- k : array_like Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- sf : array_like Survival function evaluated at k. """ args, loc, _ = self._parse_args(*args, **kwds) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) k = asarray(k-loc) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k < _a) & cond0 cond = cond0 & cond1 output = zeros(shape(cond), 'd') place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2, 1.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, np.clip(self._sf(*goodargs), 0, 1)) if output.ndim == 0: return output[()] return output def logsf(self, k, *args, **kwds): """Log of the survival function of the given RV. Returns the log of the "survival function," defined as 1 - `cdf`, evaluated at `k`. Parameters ---------- k : array_like Quantiles. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- logsf : ndarray Log of the survival function evaluated at `k`. """ args, loc, _ = self._parse_args(*args, **kwds) k, loc = map(asarray, (k, loc)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) k = asarray(k-loc) cond0 = self._argcheck(*args) cond1 = (k >= _a) & (k < _b) cond2 = (k < _a) & cond0 cond = cond0 & cond1 output = empty(shape(cond), 'd') output.fill(NINF) place(output, (1-cond0) + np.isnan(k), self.badvalue) place(output, cond2, 0.0) if np.any(cond): goodargs = argsreduce(cond, *((k,)+args)) place(output, cond, self._logsf(*goodargs)) if output.ndim == 0: return output[()] return output def ppf(self, q, *args, **kwds): """Percent point function (inverse of `cdf`) at q of the given RV. Parameters ---------- q : array_like Lower tail probability. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- k : array_like Quantile corresponding to the lower tail probability, q. """ args, loc, _ = self._parse_args(*args, **kwds) q, loc = map(asarray, (q, loc)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) cond0 = self._argcheck(*args) & (loc == loc) cond1 = (q > 0) & (q < 1) cond2 = (q == 1) & cond0 cond = cond0 & cond1 output = np.full(shape(cond), fill_value=self.badvalue, dtype='d') # output type 'd' to handle nin and inf place(output, (q == 0)*(cond == cond), _a-1 + loc) place(output, cond2, _b + loc) if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(loc,))) loc, goodargs = goodargs[-1], goodargs[:-1] place(output, cond, self._ppf(*goodargs) + loc) if output.ndim == 0: return output[()] return output def isf(self, q, *args, **kwds): """Inverse survival function (inverse of `sf`) at q of the given RV. Parameters ---------- q : array_like Upper tail probability. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). loc : array_like, optional Location parameter (default=0). Returns ------- k : ndarray or scalar Quantile corresponding to the upper tail probability, q. """ args, loc, _ = self._parse_args(*args, **kwds) q, loc = map(asarray, (q, loc)) args = tuple(map(asarray, args)) _a, _b = self._get_support(*args) cond0 = self._argcheck(*args) & (loc == loc) cond1 = (q > 0) & (q < 1) cond2 = (q == 1) & cond0 cond3 = (q == 0) & cond0 cond = cond0 & cond1 # same problem as with ppf; copied from ppf and changed output = np.full(shape(cond), fill_value=self.badvalue, dtype='d') # output type 'd' to handle nin and inf lower_bound = _a - 1 + loc upper_bound = _b + loc place(output, cond2*(cond == cond), lower_bound) place(output, cond3*(cond == cond), upper_bound) # call place only if at least 1 valid argument if np.any(cond): goodargs = argsreduce(cond, *((q,)+args+(loc,))) loc, goodargs = goodargs[-1], goodargs[:-1] # PB same as ticket 766 place(output, cond, self._isf(*goodargs) + loc) if output.ndim == 0: return output[()] return output def _entropy(self, *args): if hasattr(self, 'pk'): return stats.entropy(self.pk) else: _a, _b = self._get_support(*args) return _expect(lambda x: entr(self.pmf(x, *args)), _a, _b, self.ppf(0.5, *args), self.inc) def expect(self, func=None, args=(), loc=0, lb=None, ub=None, conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32): """ Calculate expected value of a function with respect to the distribution for discrete distribution by numerical summation. Parameters ---------- func : callable, optional Function for which the expectation value is calculated. Takes only one argument. The default is the identity mapping f(k) = k. args : tuple, optional Shape parameters of the distribution. loc : float, optional Location parameter. Default is 0. lb, ub : int, optional Lower and upper bound for the summation, default is set to the support of the distribution, inclusive (``lb <= k <= ub``). conditional : bool, optional If true then the expectation is corrected by the conditional probability of the summation interval. The return value is the expectation of the function, `func`, conditional on being in the given interval (k such that ``lb <= k <= ub``). Default is False. maxcount : int, optional Maximal number of terms to evaluate (to avoid an endless loop for an infinite sum). Default is 1000. tolerance : float, optional Absolute tolerance for the summation. Default is 1e-10. chunksize : int, optional Iterate over the support of a distributions in chunks of this size. Default is 32. Returns ------- expect : float Expected value. Notes ----- For heavy-tailed distributions, the expected value may or may not exist, depending on the function, `func`. If it does exist, but the sum converges slowly, the accuracy of the result may be rather low. For instance, for ``zipf(4)``, accuracy for mean, variance in example is only 1e-5. increasing `maxcount` and/or `chunksize` may improve the result, but may also make zipf very slow. The function is not vectorized. """ if func is None: def fun(x): # loc and args from outer scope return (x+loc)*self._pmf(x, *args) else: def fun(x): # loc and args from outer scope return func(x+loc)*self._pmf(x, *args) # used pmf because _pmf does not check support in randint and there # might be problems(?) with correct self.a, self.b at this stage maybe # not anymore, seems to work now with _pmf _a, _b = self._get_support(*args) if lb is None: lb = _a else: lb = lb - loc # convert bound for standardized distribution if ub is None: ub = _b else: ub = ub - loc # convert bound for standardized distribution if conditional: invfac = self.sf(lb-1, *args) - self.sf(ub, *args) else: invfac = 1.0 if isinstance(self, rv_sample): res = self._expect(fun, lb, ub) return res / invfac # iterate over the support, starting from the median x0 = self.ppf(0.5, *args) res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize) return res / invfac def _param_info(self): shape_info = self._shape_info() loc_info = _ShapeInfo("loc", True, (-np.inf, np.inf), (False, False)) param_info = shape_info + [loc_info] return param_info def _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10, chunksize=32): """Helper for computing the expectation value of `fun`.""" # short-circuit if the support size is small enough if (ub - lb) <= chunksize: supp = np.arange(lb, ub+1, inc) vals = fun(supp) return np.sum(vals) # otherwise, iterate starting from x0 if x0 < lb: x0 = lb if x0 > ub: x0 = ub count, tot = 0, 0. # iterate over [x0, ub] inclusive for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc): count += x.size delta = np.sum(fun(x)) tot += delta if abs(delta) < tolerance * x.size: break if count > maxcount: warnings.warn('expect(): sum did not converge', RuntimeWarning) return tot # iterate over [lb, x0) for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc): count += x.size delta = np.sum(fun(x)) tot += delta if abs(delta) < tolerance * x.size: break if count > maxcount: warnings.warn('expect(): sum did not converge', RuntimeWarning) break return tot def _iter_chunked(x0, x1, chunksize=4, inc=1): """Iterate from x0 to x1 in chunks of chunksize and steps inc. x0 must be finite, x1 need not be. In the latter case, the iterator is infinite. Handles both x0 < x1 and x0 > x1. In the latter case, iterates downwards (make sure to set inc < 0.) >>> [x for x in _iter_chunked(2, 5, inc=2)] [array([2, 4])] >>> [x for x in _iter_chunked(2, 11, inc=2)] [array([2, 4, 6, 8]), array([10])] >>> [x for x in _iter_chunked(2, -5, inc=-2)] [array([ 2, 0, -2, -4])] >>> [x for x in _iter_chunked(2, -9, inc=-2)] [array([ 2, 0, -2, -4]), array([-6, -8])] """ if inc == 0: raise ValueError('Cannot increment by zero.') if chunksize <= 0: raise ValueError('Chunk size must be positive; got %s.' % chunksize) s = 1 if inc > 0 else -1 stepsize = abs(chunksize * inc) x = x0 while (x - x1) * inc < 0: delta = min(stepsize, abs(x - x1)) step = delta * s supp = np.arange(x, x + step, inc) x += step yield supp class rv_sample(rv_discrete): """A 'sample' discrete distribution defined by the support and values. The ctor ignores most of the arguments, only needs the `values` argument. """ def __init__(self, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8, values=None, inc=1, longname=None, shapes=None, extradoc=None, seed=None): super(rv_discrete, self).__init__(seed) if extradoc is not None: warnings.warn("extradoc is deprecated and will be removed in " "SciPy 1.11.0", DeprecationWarning) if values is None: raise ValueError("rv_sample.__init__(..., values=None,...)") # cf generic freeze self._ctor_param = dict( a=a, b=b, name=name, badvalue=badvalue, moment_tol=moment_tol, values=values, inc=inc, longname=longname, shapes=shapes, extradoc=extradoc, seed=seed) if badvalue is None: badvalue = nan self.badvalue = badvalue self.moment_tol = moment_tol self.inc = inc self.shapes = shapes self.vecentropy = self._entropy xk, pk = values if np.shape(xk) != np.shape(pk): raise ValueError("xk and pk must have the same shape.") if np.less(pk, 0.0).any(): raise ValueError("All elements of pk must be non-negative.") if not np.allclose(np.sum(pk), 1): raise ValueError("The sum of provided pk is not 1.") indx = np.argsort(np.ravel(xk)) self.xk = np.take(np.ravel(xk), indx, 0) self.pk = np.take(np.ravel(pk), indx, 0) self.a = self.xk[0] self.b = self.xk[-1] self.qvals = np.cumsum(self.pk, axis=0) self.shapes = ' ' # bypass inspection self._construct_argparser(meths_to_inspect=[self._pmf], locscale_in='loc=0', # scale=1 for discrete RVs locscale_out='loc, 1') self._attach_methods() self._construct_docstrings(name, longname, extradoc) def __getstate__(self): dct = self.__dict__.copy() # these methods will be remade in rv_generic.__setstate__, # which calls rv_generic._attach_methods attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs"] [dct.pop(attr, None) for attr in attrs] return dct def _attach_methods(self): """Attaches dynamically created argparser methods.""" self._attach_argparser_methods() def _get_support(self, *args): """Return the support of the (unscaled, unshifted) distribution. Parameters ---------- arg1, arg2, ... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- a, b : numeric (float, or int or +/-np.inf) end-points of the distribution's support. """ return self.a, self.b def _pmf(self, x): return np.select([x == k for k in self.xk], [np.broadcast_arrays(p, x)[0] for p in self.pk], 0) def _cdf(self, x): xx, xxk = np.broadcast_arrays(x[:, None], self.xk) indx = np.argmax(xxk > xx, axis=-1) - 1 return self.qvals[indx] def _ppf(self, q): qq, sqq = np.broadcast_arrays(q[..., None], self.qvals) indx = argmax(sqq >= qq, axis=-1) return self.xk[indx] def _rvs(self, size=None, random_state=None): # Need to define it explicitly, otherwise .rvs() with size=None # fails due to explicit broadcasting in _ppf U = random_state.uniform(size=size) if size is None: U = np.array(U, ndmin=1) Y = self._ppf(U)[0] else: Y = self._ppf(U) return Y def _entropy(self): return stats.entropy(self.pk) def generic_moment(self, n): n = asarray(n) return np.sum(self.xk**n[np.newaxis, ...] * self.pk, axis=0) def _expect(self, fun, lb, ub, *args, **kwds): # ignore all args, just do a brute force summation supp = self.xk[(lb <= self.xk) & (self.xk <= ub)] vals = fun(supp) return np.sum(vals) def _check_shape(argshape, size): """ This is a utility function used by `_rvs()` in the class geninvgauss_gen. It compares the tuple argshape to the tuple size. Parameters ---------- argshape : tuple of integers Shape of the arguments. size : tuple of integers or integer Size argument of rvs(). Returns ------- The function returns two tuples, scalar_shape and bc. scalar_shape : tuple Shape to which the 1-d array of random variates returned by _rvs_scalar() is converted when it is copied into the output array of _rvs(). bc : tuple of booleans bc is an tuple the same length as size. bc[j] is True if the data associated with that index is generated in one call of _rvs_scalar(). """ scalar_shape = [] bc = [] for argdim, sizedim in zip_longest(argshape[::-1], size[::-1], fillvalue=1): if sizedim > argdim or (argdim == sizedim == 1): scalar_shape.append(sizedim) bc.append(True) else: bc.append(False) return tuple(scalar_shape[::-1]), tuple(bc[::-1]) def get_distribution_names(namespace_pairs, rv_base_class): """Collect names of statistical distributions and their generators. Parameters ---------- namespace_pairs : sequence A snapshot of (name, value) pairs in the namespace of a module. rv_base_class : class The base class of random variable generator classes in a module. Returns ------- distn_names : list of strings Names of the statistical distributions. distn_gen_names : list of strings Names of the generators of the statistical distributions. Note that these are not simply the names of the statistical distributions, with a _gen suffix added. """ distn_names = [] distn_gen_names = [] for name, value in namespace_pairs: if name.startswith('_'): continue if name.endswith('_gen') and issubclass(value, rv_base_class): distn_gen_names.append(name) if isinstance(value, rv_base_class): distn_names.append(name) return distn_names, distn_gen_names
support
_constants.py
from typing import (Any, Dict, Generic, Hashable, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union, cast, overload) from ._compatibility.typing import final, Protocol from ._internal import API from ._internal.utils import AbstractMeta, Default, FinalImmutable, FinalMeta, debug_repr from ._internal.utils.immutable import Immutable, ImmutableGenericMeta from ._providers.lazy import Lazy from .core import Container, DependencyDebug, DependencyValue, Scope T = TypeVar('T') if TYPE_CHECKING: from .constants import Constants # TODO: Once Python 3.6 support drops, fix this. # We're lying to Mypy here. That's not how the actual descriptor, even though it's # somewhat close. But inheriting Generic implies not being final anymore in Python 3.6, # until PEP 560, and internally there's no need for Generic. class Const(Generic[T]): __slots__ = () @overload def __get__(self, # noqa: E704 instance: 'Constants', owner: 'Type[Constants]') -> T: ... # pragma: no cover @overload def __get__(self, # noqa: E704 instance: None, owner: 'Type[Constants]') -> 'Const[T]': ... # pragma: no cover def __get__(self, instance: 'Optional[Constants]', owner: 'Type[Constants]') -> object: # pragma: no cover pass @API.private @final class MakeConst(metaclass=FinalMeta): def __call__(self, __arg: Optional[object] = None, *, default: Any = Default.sentinel) -> Const[object]: # Not true yet, but will be changed by ConstantsMeta return cast(Const[object], LazyConstToDo(__arg, None, default)) def __getitem__(self, tpe: Type[T]) -> 'MakeTypedConst[T]': return MakeTypedConst(tpe) @API.private @final class MakeTypedConst(Immutable, Generic[T], metaclass=ImmutableGenericMeta): __slots__ = ('__type',) __type: Type[T] def __call__(self, __arg: Optional[object] = None, *, default: Union[T, Default] = Default.sentinel) -> Const[T]: if not isinstance(default, (self.__type, Default)): raise TypeError(f"default is not an instance of {self.__type}, " f"but {type(default)}") # Not true yet, but will be changed by ConstantsMeta return cast(Const[T], LazyConstToDo(__arg, self.__type, default)) @API.private @final class LazyConstToDo(FinalImmutable): __slots__ = ('arg', 'type_', 'default') arg: Optional[object] type_: Optional[type] default: object @API.private class ConstantsMeta(AbstractMeta): def __new__(mcs: 'Type[ConstantsMeta]', name: str, bases: Tuple[type, ...], namespace: Dict[str, object], **kwargs: object ) -> 'ConstantsMeta': cls = cast( ConstantsMeta, super().__new__(mcs, name, bases, namespace, **kwargs) # type: ignore ) if not kwargs.get('abstract'): _configure_constants(cls) return cls @API.private def _configure_constants(cls: ConstantsMeta) -> None: from .constants import Constants from .service import service conf = getattr(cls, '__antidote__', None) if not isinstance(conf, Constants.Conf): raise TypeError(f"Constants configuration (__antidote__) is expected to be a " f"{Constants.Conf}, not a {type(conf)}") cls = service(cls, singleton=True, wiring=conf.wiring) for name, v in list(cls.__dict__.items()): if isinstance(v, LazyConstToDo): setattr(cls, name, LazyConstDescriptor( name=name, dependency=cls, method_name=Constants.provide_const.__name__, arg=v.arg, default=v.default, type_=v.type_ or object, auto_cast=v.type_ is not None and v.type_ in conf.auto_cast)) @API.private @final class LazyConstDescriptor(FinalImmutable): __slots__ = ('name', 'dependency', 'method_name', 'arg', 'default', 'type_', 'auto_cast', '_cache') name: str dependency: Hashable method_name: str arg: object default: object type_: type auto_cast: bool _cache: str def __init__(self, *, name: str, dependency: Hashable, method_name: str, arg: object, default: object, type_: type,
name=name, dependency=dependency, method_name=method_name, arg=arg, default=default, type_=type_, auto_cast=auto_cast, _cache=f"__antidote_dependency_{hex(id(self))}" ) def __get__(self, instance: object, owner: type) -> object: if instance is None: try: return getattr(owner, self._cache) except AttributeError: dependency = LazyConst(self) setattr(owner, self._cache, dependency) return dependency try: value = getattr(instance, self.method_name)(name=self.name, arg=self.arg) except LookupError: if self.default is not Default.sentinel: return self.default raise if self.auto_cast: value = self.type_(value) if not isinstance(value, self.type_): raise TypeError(f"Constant {self.name} is not an instance of {self.type_}, " f"but {type(value)}") return value @API.private @final class LazyConst(FinalImmutable, Lazy): __slots__ = ('descriptor',) descriptor: LazyConstDescriptor def __init__(self, descriptor: LazyConstDescriptor) -> None: super().__init__(descriptor=descriptor) def debug_info(self) -> DependencyDebug: descriptor = cast(LazyConstDescriptor, self.descriptor) cls = cast(type, descriptor.dependency) return DependencyDebug(f"{debug_repr(cls)}.{descriptor.name}", scope=Scope.singleton(), # TODO: Would be great if the first argument of the method # didn't show as unknown as it's always provided. wired=[getattr(cls, descriptor.method_name), cls]) def provide(self, container: Container) -> DependencyValue: # TODO: Waiting for a fix: https://github.com/python/mypy/issues/6910 descriptor = cast(LazyConstDescriptor, self.descriptor) return DependencyValue( descriptor.__get__( container.get(descriptor.dependency), None # type: ignore ), scope=Scope.singleton() )
auto_cast: bool ): assert isinstance(default, (Default, type_)) super().__init__(
index.ts
export * from './types' export * from './actions'
user.entity.ts
import { ApiProperty } from "@nestjs/swagger"; import { Entity, Column, BaseEntity, CreateDateColumn, PrimaryGeneratedColumn, } from "typeorm"; @Entity('users') export class
extends BaseEntity { @ApiProperty({ description: 'id of user', example: 1 }) @PrimaryGeneratedColumn({ type: 'int', unsigned: true }) id: number; @ApiProperty({ description: 'Name of user', example: 'Mohammad Hossein' }) @Column({ type: 'varchar', length: 255 }) name: string; @ApiProperty({ description: 'Mobile number of user', example: '09309998516' }) @Column({ type: 'varchar', length: 255 }) mobile: string; static async validateUser(name: string, mobile: string): Promise<any> { const user = await this.findOne({ name, mobile }); if (user) { return user; } return null; } }
User
pit.py
""" Pooling-based Vision Transformer (PiT) in PyTorch A PyTorch implement of Pooling-based Vision Transformers as described in 'Rethinking Spatial Dimensions of Vision Transformers' - https://arxiv.org/abs/2103.16302 This code was adapted from the original version at https://github.com/naver-ai/pit, original copyright below. Modifications for timm by / Copyright 2020 Ross Wightman """ # PiT # Copyright 2021-present NAVER Corp. # Apache License v2.0 import math import re from functools import partial from typing import Tuple import torch from torch import nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from .helpers import build_model_with_cfg from .layers import trunc_normal_, to_2tuple from .registry import register_model from .vision_transformer import Block def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True, 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'patch_embed.conv', 'classifier': 'head', **kwargs } default_cfgs = { # deit models (FB weights) 'pit_ti_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_ti_730.pth'), 'pit_xs_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_xs_781.pth'), 'pit_s_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_s_809.pth'), 'pit_b_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_b_820.pth'), 'pit_ti_distilled_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_ti_distill_746.pth', classifier=('head', 'head_dist')), 'pit_xs_distilled_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_xs_distill_791.pth', classifier=('head', 'head_dist')), 'pit_s_distilled_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_s_distill_819.pth', classifier=('head', 'head_dist')), 'pit_b_distilled_224': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-pit-weights/pit_b_distill_840.pth', classifier=('head', 'head_dist')), } class SequentialTuple(nn.Sequential): """ This module exists to work around torchscript typing issues list -> list""" def __init__(self, *args): super(SequentialTuple, self).__init__(*args) def forward(self, x: Tuple[torch.Tensor, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: for module in self: x = module(x) return x class Transformer(nn.Module): def __init__( self, base_dim, depth, heads, mlp_ratio, pool=None, drop_rate=.0, attn_drop_rate=.0, drop_path_prob=None): super(Transformer, self).__init__() self.layers = nn.ModuleList([]) embed_dim = base_dim * heads self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=heads, mlp_ratio=mlp_ratio, qkv_bias=True, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=drop_path_prob[i], norm_layer=partial(nn.LayerNorm, eps=1e-6) ) for i in range(depth)]) self.pool = pool def forward(self, x: Tuple[torch.Tensor, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: x, cls_tokens = x B, C, H, W = x.shape token_length = cls_tokens.shape[1] x = x.flatten(2).transpose(1, 2) x = torch.cat((cls_tokens, x), dim=1) x = self.blocks(x) cls_tokens = x[:, :token_length] x = x[:, token_length:] x = x.transpose(1, 2).reshape(B, C, H, W) if self.pool is not None: x, cls_tokens = self.pool(x, cls_tokens) return x, cls_tokens class ConvHeadPooling(nn.Module): def __init__(self, in_feature, out_feature, stride, padding_mode='zeros'): super(ConvHeadPooling, self).__init__() self.conv = nn.Conv2d( in_feature, out_feature, kernel_size=stride + 1, padding=stride // 2, stride=stride, padding_mode=padding_mode, groups=in_feature) self.fc = nn.Linear(in_feature, out_feature) def forward(self, x, cls_token) -> Tuple[torch.Tensor, torch.Tensor]: x = self.conv(x) cls_token = self.fc(cls_token) return x, cls_token class ConvEmbedding(nn.Module): def __init__(self, in_channels, out_channels, patch_size, stride, padding): super(ConvEmbedding, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, kernel_size=patch_size, stride=stride, padding=padding, bias=True) def forward(self, x): x = self.conv(x) return x class PoolingVisionTransformer(nn.Module): """ Pooling-based Vision Transformer A PyTorch implement of 'Rethinking Spatial Dimensions of Vision Transformers' - https://arxiv.org/abs/2103.16302 """ def __init__(self, img_size, patch_size, stride, base_dims, depth, heads, mlp_ratio, num_classes=1000, in_chans=3, distilled=False, attn_drop_rate=.0, drop_rate=.0, drop_path_rate=.0): super(PoolingVisionTransformer, self).__init__() padding = 0 img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) height = math.floor((img_size[0] + 2 * padding - patch_size[0]) / stride + 1) width = math.floor((img_size[1] + 2 * padding - patch_size[1]) / stride + 1) self.base_dims = base_dims self.heads = heads self.num_classes = num_classes self.num_tokens = 2 if distilled else 1 self.patch_size = patch_size self.pos_embed = nn.Parameter(torch.randn(1, base_dims[0] * heads[0], height, width)) self.patch_embed = ConvEmbedding(in_chans, base_dims[0] * heads[0], patch_size, stride, padding) self.cls_token = nn.Parameter(torch.randn(1, self.num_tokens, base_dims[0] * heads[0])) self.pos_drop = nn.Dropout(p=drop_rate) transformers = [] # stochastic depth decay rule dpr = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(depth)).split(depth)] for stage in range(len(depth)): pool = None if stage < len(heads) - 1: pool = ConvHeadPooling( base_dims[stage] * heads[stage], base_dims[stage + 1] * heads[stage + 1], stride=2) transformers += [Transformer( base_dims[stage], depth[stage], heads[stage], mlp_ratio, pool=pool, drop_rate=drop_rate, attn_drop_rate=attn_drop_rate, drop_path_prob=dpr[stage]) ] self.transformers = SequentialTuple(*transformers) self.norm = nn.LayerNorm(base_dims[-1] * heads[-1], eps=1e-6) self.num_features = self.embed_dim = base_dims[-1] * heads[-1] # Classifier head self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() self.head_dist = None if distilled: self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity() trunc_normal_(self.pos_embed, std=.02) trunc_normal_(self.cls_token, std=.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'} def get_classifier(self): if self.head_dist is not None: return self.head, self.head_dist else: return self.head def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() if self.head_dist is not None: self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x): x = self.patch_embed(x) x = self.pos_drop(x + self.pos_embed) cls_tokens = self.cls_token.expand(x.shape[0], -1, -1) x, cls_tokens = self.transformers((x, cls_tokens)) cls_tokens = self.norm(cls_tokens) if self.head_dist is not None: return cls_tokens[:, 0], cls_tokens[:, 1] else: return cls_tokens[:, 0] def forward(self, x): x = self.forward_features(x) if self.head_dist is not None: x, x_dist = self.head(x[0]), self.head_dist(x[1]) # x must be a tuple if self.training and not torch.jit.is_scripting(): return x, x_dist else: return (x + x_dist) / 2 else: return self.head(x) def checkpoint_filter_fn(state_dict, model): """ preprocess checkpoints """ out_dict = {} p_blocks = re.compile(r'pools\.(\d)\.') for k, v in state_dict.items(): # FIXME need to update resize for PiT impl # if k == 'pos_embed' and v.shape != model.pos_embed.shape: # # To resize pos embedding when using model at different size from pretrained weights # v = resize_pos_embed(v, model.pos_embed) k = p_blocks.sub(lambda exp: f'transformers.{int(exp.group(1))}.pool.', k) out_dict[k] = v return out_dict def _create_pit(variant, pretrained=False, **kwargs): if kwargs.get('features_only', None): raise RuntimeError('features_only not implemented for Vision Transformer models.') model = build_model_with_cfg( PoolingVisionTransformer, variant, pretrained, default_cfg=default_cfgs[variant], pretrained_filter_fn=checkpoint_filter_fn, **kwargs) return model @register_model def pit_b_224(pretrained, **kwargs):
@register_model def pit_s_224(pretrained, **kwargs): model_kwargs = dict( patch_size=16, stride=8, base_dims=[48, 48, 48], depth=[2, 6, 4], heads=[3, 6, 12], mlp_ratio=4, **kwargs ) return _create_pit('pit_s_224', pretrained, **model_kwargs) @register_model def pit_xs_224(pretrained, **kwargs): model_kwargs = dict( patch_size=16, stride=8, base_dims=[48, 48, 48], depth=[2, 6, 4], heads=[2, 4, 8], mlp_ratio=4, **kwargs ) return _create_pit('pit_xs_224', pretrained, **model_kwargs) @register_model def pit_ti_224(pretrained, **kwargs): model_kwargs = dict( patch_size=16, stride=8, base_dims=[32, 32, 32], depth=[2, 6, 4], heads=[2, 4, 8], mlp_ratio=4, **kwargs ) return _create_pit('pit_ti_224', pretrained, **model_kwargs) @register_model def pit_b_distilled_224(pretrained, **kwargs): model_kwargs = dict( patch_size=14, stride=7, base_dims=[64, 64, 64], depth=[3, 6, 4], heads=[4, 8, 16], mlp_ratio=4, distilled=True, **kwargs ) return _create_pit('pit_b_distilled_224', pretrained, **model_kwargs) @register_model def pit_s_distilled_224(pretrained, **kwargs): model_kwargs = dict( patch_size=16, stride=8, base_dims=[48, 48, 48], depth=[2, 6, 4], heads=[3, 6, 12], mlp_ratio=4, distilled=True, **kwargs ) return _create_pit('pit_s_distilled_224', pretrained, **model_kwargs) @register_model def pit_xs_distilled_224(pretrained, **kwargs): model_kwargs = dict( patch_size=16, stride=8, base_dims=[48, 48, 48], depth=[2, 6, 4], heads=[2, 4, 8], mlp_ratio=4, distilled=True, **kwargs ) return _create_pit('pit_xs_distilled_224', pretrained, **model_kwargs) @register_model def pit_ti_distilled_224(pretrained, **kwargs): model_kwargs = dict( patch_size=16, stride=8, base_dims=[32, 32, 32], depth=[2, 6, 4], heads=[2, 4, 8], mlp_ratio=4, distilled=True, **kwargs ) return _create_pit('pit_ti_distilled_224', pretrained, **model_kwargs)
model_kwargs = dict( patch_size=14, stride=7, base_dims=[64, 64, 64], depth=[3, 6, 4], heads=[4, 8, 16], mlp_ratio=4, **kwargs ) return _create_pit('pit_b_224', pretrained, **model_kwargs)
index.d.ts
import BScroll from '@better-scroll/core'; import MouseWheel from '@better-scroll/mouse-wheel'; import ObserveDom from '@better-scroll/observe-dom'; import PullDownRefresh from '@better-scroll/pull-down';
import Wheel from '@better-scroll/wheel'; import Zoom from '@better-scroll/zoom'; import NestedScroll from '@better-scroll/nested-scroll'; import InfinityScroll from '@better-scroll/infinity'; import Movable from '@better-scroll/movable'; import ObserveImage from '@better-scroll/observe-image'; import Indicators from '@better-scroll/indicators'; export { createBScroll, BScrollInstance, Options, CustomOptions, TranslaterPoint, MountedBScrollHTMLElement, Behavior, Boundary, CustomAPI } from '@better-scroll/core'; export { MouseWheel, ObserveDom, PullDownRefresh, PullUpLoad, ScrollBar, Slide, Wheel, Zoom, NestedScroll, InfinityScroll, Movable, ObserveImage, Indicators }; export default BScroll;
import PullUpLoad from '@better-scroll/pull-up'; import ScrollBar from '@better-scroll/scroll-bar'; import Slide from '@better-scroll/slide';
utils.py
def write_qs(qs):
def write_ans(ans): with open("ans.txt", "w") as f: for i in ans: f.write(i + "\n") def read_qs(): with open("qs.txt", "r") as f: qs = f.readlines() qs = [i.rstrip("\n") for i in qs] return qs def read_ans(): with open("ans.txt", "r") as f: ans = f.readlines() ans = [i.rstrip("\n") for i in ans] return ans if __name__ == "__main__": from data import training_qs, answers write_qs(training_qs) qs = read_qs() write_ans(answers) ans = read_ans() assert(len(qs) == len(ans)) assert(qs == training_qs) assert(ans == answers)
with open("qs.txt", "w") as f: for i in qs: f.write(i + "\n")
IMPORTAMBIENTE.py
''' ARQUIVO PARA IMPORTAR OS AMBIENTES DOS SERVIDORES OSB: COLOCAR A LISTA DE SERVIDORES (XLSX) COM OS CAMPOS [SIAPE - AMBIENTE - SETOR EXERCÍCIO] ''' import os import pandas as pd from SQL import sqlexecute from MENSAGEM import mensagemErro, mensagemInformacao def i
): ''' FUNÇÃO IMPORTAR AMBIENTE E EXERCÍCIO DOS SERVIDORES PARA O BANCO DE DADOS ENTRA PLANILHA DOS SERVIDORES DO SISTEMA INTEGRADO (RELATÓRIO) SAI BANCO DE DADOS ATUALIZADO COM AMBIENTE E EXERCÍCIO DOS SERVIDORES ''' listdir = os.listdir('DADOS_EXTRATOR\\') if 'servidores.xlsx' in listdir: xls = 'DADOS_EXTRATOR\\servidores.xlsx' folha = 'Servidores' arq = pd.read_excel(xls, folha) dados = arq[['Siape', 'Ambiente', 'Exercício']] dados = dados[dados['Siape'].notnull()] dados['Siape'] = dados['Siape'].apply(lambda x: str(x).rjust(7, '0')) dados = dados.dropna(thresh=2) dados = dados.fillna('null') dados = dados[dados['Siape'].duplicated() == False] sql = '''delete from ts_sis_ambientes;''' sqlexecute(sql) sql = '''INSERT INTO ts_sis_ambientes\n(GR_MATRICULA, AMBIENTE, EXERCICIO)\nvalues\n''' lx = '' for i in dados.values: if len(i[0]) == 7: lx = '''( '{0}', '{1}', '{2}' ),\n'''.format(i[0], i[1], i[2]) sql += lx sql = sql[:-2] + ';' sql = sql.replace('\'null\'', 'null') sqlexecute(sql) mensagemInformacao('Importação do AMBIENTE concluída.') else: mensagemErro('Arquivo "servidores.xlsx" não encontrado. (AMBIENTE)')
mportarAmbienteServidores(
groups.go
package main import ( "fmt" "strconv" "strings" "github.com/tobischo/gokeepasslib" ) func listGroups(g *gokeepasslib.Group) []string { var groups = make([]string, 0) groups = append(groups, g.Name) for _, group := range g.Groups { subGroups := listGroups(&group) for i, val := range subGroups { subGroups[i] = fmt.Sprintf("%s/%s", g.Name, val) } groups = append(groups, subGroups...) } return groups } func readGroup(selectors []string, g *gokeepasslib.Group) (*gokeepasslib.Group, error)
func searchGroups(selectors []string, g *gokeepasslib.Group) []string { groups := listGroups(g) selector := strings.ToLower(strings.Join(selectors, "/")) var selectedGroups = make([]string, 0) for _, group := range groups { if strings.Contains(strings.ToLower(group), selector) { selectedGroups = append(selectedGroups, group) } } return selectedGroups }
{ if len(selectors) == 1 { if g.Name == selectors[0] { return g, nil } } else { for i, group := range g.Groups { if group.Name == selectors[1] { return readGroup(selectors[1:], &g.Groups[i]) } } } groups := searchGroups(selectors, g) if len(groups) < 1 { return nil, fmt.Errorf("No group found") } for i, group := range groups { fmt.Printf("%3d %s\n", i, group) } selection, err := readString("Selection: ") if err != nil { return nil, err } index, err := strconv.Atoi(selection) if err != nil { return nil, err } return readGroup(strings.Split(groups[index], "/"), g) return nil, fmt.Errorf("Failed to locate group at selector") }
rexgridtable.min.js
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).rexgridtable=e()}(this,function(){"use strict";function u(t){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function
(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function m(t,e,i){return e&&n(t.prototype,e),i&&n(t,i),t}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&s(t,e)}function b(t){return(b=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function s(t,e){return(s=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function k(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function C(n){var s=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(t){return!1}}();return function(){var t,e=b(n);if(s){var i=b(this).constructor;t=Reflect.construct(e,arguments,i)}else t=e.apply(this,arguments);return function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return k(t)}(this,t)}}function l(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=b(t)););return t}function S(t,e,i){return(S="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,i){var n=l(t,e);if(n){var s=Object.getOwnPropertyDescriptor(n,e);return s.get?s.get.call(i):s.value}})(t,e,i||t)}function r(t,e,i,n){return(r="undefined"!=typeof Reflect&&Reflect.set?Reflect.set:function(t,e,i,n){var s,r,o,h,a=l(t,e);if(a){if((s=Object.getOwnPropertyDescriptor(a,e)).set)return s.set.call(n,i),!0;if(!s.writable)return!1}if(s=Object.getOwnPropertyDescriptor(n,e)){if(!s.writable)return!1;s.value=i,Object.defineProperty(n,e,s)}else h=i,(o=e)in(r=n)?Object.defineProperty(r,o,{value:h,enumerable:!0,configurable:!0,writable:!0}):r[o]=h;return!0})(t,e,i,n)}function e(t,e,i,n,s){if(!r(t,e,i,n||t)&&s)throw new Error("failed to set property");return i}function o(t){return function(t){if(Array.isArray(t))return h(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(!t)return;if("string"==typeof t)return h(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);"Object"===i&&t.constructor&&(i=t.constructor.name);if("Map"===i||"Set"===i)return Array.from(t);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return h(t,e)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,n=new Array(e);i<e;i++)n[i]=t[i];return n}var t=Phaser.GameObjects.Zone,a=Phaser.Utils.Array.Add,c=Phaser.Utils.Array.Remove,d=function(){i(h,t);var o=C(h);function h(t,e,i,n,s){var r;return y(this,h),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=1),void 0===s&&(s=1),(r=o.call(this,t,e,i,n,s)).children=[],r}return m(h,[{key:"destroy",value:function(t){if(this.scene){if(t)for(var e,i=this.children.length-1;0<=i;i--)(e=this.children[i]).parentContainer||e.displayList||e.destroy(t);this.clear(!t),S(b(h.prototype),"destroy",this).call(this,t)}}},{key:"contains",value:function(t){return-1!==this.children.indexOf(t)}},{key:"add",value:function(t){var e=this;return a(this.children,t,0,function(t){t.once("destroy",e.onChildDestroy,e)},this),this}},{key:"remove",value:function(t,e){var i=this;return c(this.children,t,function(t){t.off("destroy",i.onChildDestroy,i),e&&t.destroy()}),this}},{key:"onChildDestroy",value:function(t){this.remove(t,!1)}},{key:"clear",value:function(t){for(var e,i=0,n=this.children.length;i<n;i++)(e=this.children[i]).off("destroy",this.onChildDestroy,this),t&&e.destroy();return this.children.length=0,this}}]),h}(),v=Phaser.GameObjects.Components;Phaser.Class.mixin(d,[v.Alpha,v.Flip]);function p(t){var e;return t.hasOwnProperty("rexContainer")&&(e=t.rexContainer.parent),e}function f(e){if(!e.hasOwnProperty("rexContainer")){var t={parent:null,self:null,x:0,y:0,rotation:0,scaleX:0,scaleY:0,flipX:!1,flipY:!1,alpha:0,visible:!0,active:!0};Object.defineProperty(t,"angle",{get:function(){return M(this.rotation)},set:function(t){this.rotation=T(t)}}),Object.defineProperty(t,"displayWidth",{get:function(){return e.width*this.scaleX},set:function(t){this.scaleX=t/e.width}}),Object.defineProperty(t,"displayHeight",{get:function(){return e.height*this.scaleY},set:function(t){this.scaleY=t/e.height}}),e.rexContainer=t}return e.rexContainer}function g(t){return this.setParent(t),this.resetChildState(t).updateChildVisible(t).updateChildActive(t).updateChildScrollFactor(t).updateChildMask(t),_.call(this,t),this}function w(t){this.setParent(t);var e=f(t);return e.x=t.x,e.y=t.y,e.rotation=t.rotation,e.scaleX=t.scaleX,e.scaleY=t.scaleY,e.flipX=t.flipX,e.flipY=t.flipY,e.alpha=t.alpha,e.visible=t.visible,e.active=t.active,this.updateChildPosition(t).updateChildAlpha(t).updateChildVisible(t).updateChildActive(t).updateChildScrollFactor(t).updateChildMask(t),_.call(this,t),this}function x(t,e){return t===e?1:t/e}function O(t,e){if(0===t.length)return t;void 0===e&&(e=!1);var i=t[0].scene.sys.displayList;return i.depthSort(),e?t.sort(function(t,e){return i.getIndex(e)-i.getIndex(t)}):t.sort(function(t,e){return i.getIndex(t)-i.getIndex(e)}),t}function P(t){return"[object Array]"===Object.prototype.toString.call(t)}function E(t){var e=this.getAllChildren([this]);return O(e),t.add(e),this}var T=Phaser.Math.DegToRad,M=Phaser.Math.RadToDeg,D={setParent:function(t,e){void 0===e&&(e=this);var i=f(t);return e?(i.parent=e,i.self=t):(i.parent=null,i.self=null),this},getParent:function(t){return void 0===t&&(t=this),p(t)},getTopmostParent:function(t){return void 0===t&&(t=this),function(t){for(var e=p(t);e;)e=p(t=e);return t}(t)}},_=d.prototype.add,Y={add:function(t){return Array.isArray(t)?this.addMultiple(t):g.call(this,t),this},addMultiple:function(t){for(var e=0,i=t.length;e<i;e++)g.call(this,t[e]);return this},addLocal:function(t){return Array.isArray(t)?this.addMultiple(t):w.call(this,t),this},addLocalMultiple:function(t){for(var e=0,i=t.length;e<i;e++)w.call(this,t[e]);return this}},R=d.prototype.remove,X=d.prototype.clear,V={remove:function(t,e){return p(t)!==this||(this.setParent(t,null),R.call(this,t,e)),this},clear:function(t){for(var e=0,i=this.children.length;e<i;e++)this.setParent(this.children[e],null);return X.call(this,t),this}},z={getLocalState:function(t){return f(t)},resetChildState:function(t){return this.resetChildPositionState(t).resetChildVisibleState(t).resetChildAlphaState(t).resetChildActiveState(t),this},resetChildrenState:function(t){for(var e=0,i=t.length;e<i;e++)this.resetChildState(t[e]);return this},syncProperties:function(){return this.syncPosition().syncVisible().syncAlpha().syncActive().syncScrollFactor().syncMask(),this}},I=Phaser.Math.RotateAround,A={worldToLocal:function(t){return t.x-=this.x,t.y-=this.y,I(t,0,0,-this.rotation),t.x/=this.scaleX,t.y/=this.scaleY,t.x*=this.flipX?-1:1,t.y*=this.flipY?-1:1,t},localToWorld:function(t){return t.x*=this.flipX?-1:1,t.y*=this.flipY?-1:1,t.x*=this.scaleX,t.y*=this.scaleY,I(t,0,0,this.rotation),t.x+=this.x,t.y+=this.y,t}},j={updateChildPosition:function(t){t.isRexContainerLite&&(t.syncChildrenEnable=!1);var e=f(t),i=e.parent;return t.x=e.x,t.y=e.y,i.localToWorld(t),t.scaleX=e.scaleX*i.scaleX,t.scaleY=e.scaleY*i.scaleY,void 0!==t.flipX&&(t.flipX=i.flipX?!e.flipX:e.flipX,t.flipY=i.flipY?!e.flipY:e.flipY),t.rotation=e.rotation+i.rotation,t.isRexContainerLite&&(t.syncChildrenEnable=!0,t.syncPosition()),this},syncPosition:function(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildPosition,this),this},resetChildPositionState:function(t){var e=f(t),i=e.parent;return e.x=t.x,e.y=t.y,i.worldToLocal(e),e.scaleX=x(t.scaleX,i.scaleX),e.scaleY=x(t.scaleY,i.scaleY),void 0!==t.flipX&&(e.flipX=t.flipX,e.flipY=t.flipY),e.rotation=t.rotation-i.rotation,this},setChildPosition:function(t,e,i){return t.x=e,t.y=i,this.resetChildPositionState(t),this},setChildLocalPosition:function(t,e,i){var n=f(t);return n.x=e,n.y=i,this.updateChildPosition(t),this},resetLocalPositionState:function(){var t=f(this).parent;return t&&t.resetChildPositionState(this),this}},H={updateChildRotation:function(t){var e=f(t),i=e.parent;return t.rotation=i.rotation+e.rotation,this},syncRotation:function(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildRotation,this),this},resetChildRotationState:function(t){var e=f(t),i=e.parent;return e.rotation=t.rotation-i.rotation,this},setChildRotation:function(t,e){return t.rotation=e,this.resetChildRotationState(t),this},setChildAngle:function(t,e){return t.angle=e,this.resetChildRotationState(t),this},setChildLocalRotation:function(t,e){return f(t).rotation=e,this.updateChildRotation(t),this},resetLocalRotationState:function(){var t=f(this).parent;return t&&t.resetChildRotationState(this),this}},L={updateChildScale:function(t){var e=f(t),i=e.parent;return t.scaleX=i.scaleX*e.scaleX,t.scaleY=i.scaleY*e.scaleY,this},syncScale:function(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildScale,this),this},resetChildScaleState:function(t){var e=f(t),i=e.parent;return e.scaleX=x(t.scaleX,i.scaleX),e.scaleY=x(t.scaleY,i.scaleY),this},setChildScale:function(t,e,i){return void 0===i&&(i=e),t.scaleX=e,t.scaleY=i,this.resetChildScaleState(t),this},setChildLocalScale:function(t,e,i){void 0===i&&(i=e);var n=f(t);return n.scaleX=e,n.scaleY=i,this.updateChildScale(t),this},setChildDisplaySize:function(t,e,i){return t.setDisplaySize(e,i),this.resetChildScaleState(t),this},resetLocalScaleState:function(){var t=f(this).parent;return t&&t.resetChildScaleState(this),this}},W={updateChildVisible:function(t){var e=f(t),i=e.parent,n=!e.hasOwnProperty("maskVisible")||e.maskVisible;return t.visible=i.visible&&e.visible&&n,this},syncVisible:function(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildVisible,this),this},resetChildVisibleState:function(t){var e=f(t);return e.hasOwnProperty("maskVisible")&&delete e.maskVisible,e.visible=t.visible,this},setChildVisible:function(t,e){return this.setChildLocalVisible(t,e),this},setChildLocalVisible:function(t,e){return void 0===e&&(e=!0),f(t).visible=e,this.updateChildVisible(t),this},setChildMaskVisible:function(t,e){return void 0===e&&(e=!0),f(t).maskVisible=e,this.updateChildVisible(t),this},resetLocalVisibleState:function(){var t=f(this).parent;return t&&t.resetChildVisibleState(this),this}},N={updateChildAlpha:function(t){var e=f(t),i=e.parent;return t.alpha=i.alpha*e.alpha,this},syncAlpha:function(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildAlpha,this),this},resetChildAlphaState:function(t){var e=f(t),i=e.parent;return e.alpha=x(t.alpha,i.alpha),this},setChildAlpha:function(t,e){return t.alpha=e,this.resetChildAlphaState(t),this},setChildLocalAlpha:function(t,e){return f(t).alpha=e,this.updateChildAlpha(t),this},resetLocalAlphaState:function(){var t=f(this).parent;return t&&t.resetChildAlphaState(this),this}},F={updateChildActive:function(t){var e=f(t),i=e.parent;return t.active=i.active&&e.active,this},syncActive:function(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildActive,this),this},resetChildActiveState:function(t){return f(t).active=t.active,this},setChildActive:function(t,e){return t.active=e,this.resetChildActiveState(t),this},setChildLocalActive:function(t,e){return void 0===e&&(e=!0),f(t).active=e,this.updateChildActive(t),this},resetLocalActiveState:function(){var t=f(this).parent;return t&&t.resetChildActiveState(this),this}},G={updateChildScrollFactor:function(t){var e=f(t).parent;return t.setScrollFactor(e.scrollFactorX,e.scrollFactorY),this},syncScrollFactor:function(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildScrollFactor,this),this}},B={updateChildMask:function(t){return null==this.mask||(this.mask.hasOwnProperty("geometryMask")?this.mask.geometryMask:this.mask.bitmapMask)!==t&&(t.mask=this.mask),this},syncMask:function(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildMask,this),this},setMask:function(t){return this.mask=t,this},clearMask:function(t){return void 0===t&&(t=!1),t&&this.mask&&this.mask.destroy(),this.mask=null,this}},U={setDepth:function(t,e){if(this.depth=t,!e&&this.children)for(var i=this.getAllChildren(),n=0,s=i.length;n<s;n++)i[n].depth=t;return this},swapDepth:function(t){var e=this.depth,i=t.depth;return this.setDepth(i),t.setDepth(e),this},incDepth:function(t){if(this.depth+=t,this.children)for(var e=this.getAllChildren(),i=0,n=e.length;i<n;i++)e[i].depth+=t;return this},moveDepthBelow:function(t){var e=t.scene.children,i=this.getAllChildren([this]);O(i);for(var n=0,s=i.length;n<s;n++){var r=i[n];if(e.exists(r)){e.moveBelow(t,r);break}}return this},moveDepthAbove:function(t){var e=t.scene.children,i=this.getAllChildren([this]);O(i,!0);for(var n=0,s=i.length;n<s;n++){var r=i[n];if(e.exists(r)){e.moveAbove(t,r);break}}return this}},J=Phaser.Utils.Array,Z={getChildren:function(t){if(t)for(var e=0,i=this.children.length;e<i;e++)t.push(this.children[e]);else t=this.children;return t},getAllChildren:function(t){void 0===t&&(t=[]);for(var e,i=this.children,n=0,s=i.length;n<s;n++){if(e=i[n],t.push(e),e.hasOwnProperty("isRexContainerLite"))t.push.apply(t,o(e.getAllChildren()))}return t},getAllVisibleChildren:function(t){void 0===t&&(t=[]);for(var e,i=this.children,n=0,s=i.length;n<s;n++){if((e=i[n]).visible)if(t.push(e),e.hasOwnProperty("isRexContainerLite"))t.push.apply(t,o(e.getAllVisibleChildren()))}return t},contains:function(t){var e=p(t);return!!e&&(e===this||this.contains(e))},getByName:function(t,e){if(e){for(var i,n,s=[this];s.length;)for(var r=0,o=(i=s.shift()).children.length;r<o;r++){if((n=i.children[r]).name===t)return n;n.isRexContainerLite&&s.push(n)}return null}return J.GetFirst(this.children,"name",t)},getRandom:function(t,e){return J.GetRandom(this.children,t,e)},getFirst:function(t,e,i,n){return J.GetFirstElement(this.children,t,e,i,n)},getAll:function(t,e,i,n){return J.GetAll(this.children,t,e,i,n)},count:function(t,e,i,n){return J.CountAllMatching(this.children,t,e,i,n)},swap:function(t,e){return J.Swap(this.children,t,e),this},setAll:function(t,e,i,n){return J.SetAll(this.children,t,e,i,n),this}},K={tweenChild:function(t){var e=t.targets;P(e)||(e=[e]);for(var r,i,n=[],s=0,o=e.length;s<o;s++)(i=e[s]).hasOwnProperty("rexContainer")&&(r=i.scene,n.push(i.rexContainer));if(r){t.targets=n;var h=r.tweens.add(t);return h.on("update",function(t,e,i){if(i.parent){var n=i.parent,s=i.self;switch(e){case"x":case"y":n.updateChildPosition(s);break;case"angle":case"rotation":n.updateChildRotation(s);break;case"scaleX":case"scaleY":case"displayWidth":case"displayHeight":n.updateChildScale(s);break;case"alpha":n.updateChildAlpha(s)}}else r.tweens.remove(t)}),h}},tween:function(t){var e=this.scene;return t.targets||(t.targets=this),e.tweens.add(t)}},q={addToLayer:E,addToContainer:E},$=Phaser.Math.RotateAround,Q={changeOrigin:function(t,e){this.syncChildrenEnable=!1,function(t,e,i){void 0===i&&(i=e);var n={x:(e-t.originX)*t.displayWidth,y:(i-t.originY)*t.displayHeight};$(n,0,0,t.rotation),t.originX=e,t.originY=i,t.x=t.x+n.x,t.y=t.y+n.y}(this,t,e),this.syncChildrenEnable=!0;for(var i=this.getAllChildren(),n=0,s=i.length;n<s;n++)this.resetChildPositionState(i[n]);return this}};Object.assign(Q,D,Y,V,z,A,j,H,L,W,N,F,G,B,U,Z,K,q);var tt=function(){i(a,d);var h=C(a);function a(t,e,i,n,s,r){var o;return y(this,a),(o=h.call(this,t,e,i,n,s)).type="rexContainerLite",o.isRexContainerLite=!0,o.syncChildrenEnable=!0,o._active=!0,o._mask=null,o._scrollFactorX=1,o._scrollFactorY=1,r&&o.add(r),o}return m(a,[{key:"destroy",value:function(t){this.scene&&(this.syncChildrenEnable=!1,S(b(a.prototype),"destroy",this).call(this,t))}},{key:"resize",value:function(t,e){return this.setSize(t,e),this}},{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.syncPosition())}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.syncPosition())}},{key:"rotation",get:function(){return S(b(a.prototype),"rotation",this)},set:function(t){this.rotation!==t&&(e(b(a.prototype),"rotation",t,this,!0),this.syncPosition())}},{key:"scaleX",get:function(){return S(b(a.prototype),"scaleX",this)},set:function(t){this.scaleX!==t&&(e(b(a.prototype),"scaleX",t,this,!0),this.syncPosition())}},{key:"scaleY",get:function(){return S(b(a.prototype),"scaleY",this)},set:function(t){this.scaleY!==t&&(e(b(a.prototype),"scaleY",t,this,!0),this.syncPosition())}},{key:"flipX",get:function(){return S(b(a.prototype),"flipX",this)},set:function(t){S(b(a.prototype),"flipX",this)!==t&&(e(b(a.prototype),"flipX",t,this,!0),this.syncPosition())}},{key:"flipY",get:function(){return S(b(a.prototype),"flipY",this)},set:function(t){S(b(a.prototype),"flipY",this)!==t&&(e(b(a.prototype),"flipY",t,this,!0),this.syncPosition())}},{key:"visible",get:function(){return S(b(a.prototype),"visible",this)},set:function(t){S(b(a.prototype),"visible",this)!==t&&(e(b(a.prototype),"visible",t,this,!0),this.syncVisible())}},{key:"alpha",get:function(){return S(b(a.prototype),"alpha",this)},set:function(t){S(b(a.prototype),"alpha",this)!==t&&(e(b(a.prototype),"alpha",t,this,!0),this.syncAlpha())}},{key:"active",get:function(){return this._active},set:function(t){this._active!==t&&(this._active=t,this.syncActive())}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask!==t&&(this._mask=t,this.syncMask())}},{key:"scrollFactorX",get:function(){return this._scrollFactorX},set:function(t){this._scrollFactorX!==t&&(this._scrollFactorX=t,this.syncScrollFactor())}},{key:"scrollFactorY",get:function(){return this._scrollFactorY},set:function(t){this._scrollFactorY!==t&&(this._scrollFactorY=t,this.syncScrollFactor())}},{key:"list",get:function(){return this.children}}],[{key:"GetParent",value:function(t){return p(t)}}]),a}();Object.assign(tt.prototype,Q);function et(t){return t.hasOwnProperty("rexSizer")||(t.rexSizer={}),t.rexSizer}function it(){}var nt,st=Phaser.Display.Align,rt={center:st.CENTER,left:st.LEFT_CENTER,right:st.RIGHT_CENTER,top:st.TOP_CENTER,bottom:st.BOTTOM_CENTER,"left-top":st.TOP_LEFT,"left-center":st.LEFT_CENTER,"left-bottom":st.BOTTOM_LEFT,"center-top":st.TOP_CENTER,"center-center":st.CENTER,"center-bottom":st.BOTTOM_CENTER,"right-top":st.TOP_RIGHT,"right-center":st.RIGHT_CENTER,"right-bottom":st.BOTTOM_RIGHT},ot=new Phaser.GameObjects.Zone({sys:{queueDepthSort:it,events:{once:it}}},0,0,1,1);ot.setOrigin(0);function ht(t){return void 0!==t.displayWidth?t.displayWidth:t.width}function at(t){return void 0!==t.displayHeight?t.displayHeight:t.height}function lt(t){var e=at(t);return t.y+e-e*t.originY}function ut(t){var e=ht(t);return t.x-e*t.originX+.5*e}function ct(t,e){var i=at(t);return t.y=e-i+i*t.originY,t}function dt(t,e){var i=ht(t),n=i*t.originX;return t.x=e+n-.5*i,t}function vt(t){var e=ht(t);return t.x-e*t.originX}function pt(t,e){var i=ht(t);return t.x=e+i*t.originX,t}function ft(t){var e=ht(t);return t.x+e-e*t.originX}function gt(t,e){var i=ht(t);return t.x=e-i+i*t.originX,t}function yt(t,e){var i=at(t),n=i*t.originY;return t.y=e+n-.5*i,t}function mt(t){var e=at(t);return t.y-e*t.originY+.5*e}function bt(t){var e=at(t);return t.y-e*t.originY}function kt(t,e){var i=at(t);return t.y=e+i*t.originY,t}var Ct=0,St=1,wt=2,xt=4,Ot=6,Pt=8,Et=10,Tt=12,Mt=[];Mt[11]=function(t,e,i,n){return void 0===i&&(i=0),void 0===n&&(n=0),dt(t,ut(e)+i),ct(t,lt(e)+n),t},Mt[Et]=function(t,e,i,n){return void 0===i&&(i=0),void 0===n&&(n=0),pt(t,vt(e)-i),ct(t,lt(e)+n),t},Mt[Tt]=function(t,e,i,n){return void 0===i&&(i=0),void 0===n&&(n=0),gt(t,ft(e)+i),ct(t,lt(e)+n),t},Mt[Ot]=function(t,e,i,n){var s,r,o;return void 0===i&&(i=0),void 0===n&&(n=0),s=t,r=ut(e)+i,o=mt(e)+n,dt(s,r),yt(s,o),t},Mt[xt]=function(t,e,i,n){return void 0===i&&(i=0),void 0===n&&(n=0),pt(t,vt(e)-i),yt(t,mt(e)+n),t},Mt[Pt]=function(t,e,i,n){return void 0===i&&(i=0),void 0===n&&(n=0),gt(t,ft(e)+i),yt(t,mt(e)+n),t},Mt[St]=function(t,e,i,n){return void 0===i&&(i=0),void 0===n&&(n=0),dt(t,ut(e)+i),kt(t,bt(e)-n),t},Mt[Ct]=function(t,e,i,n){return void 0===i&&(i=0),void 0===n&&(n=0),pt(t,vt(e)-i),kt(t,bt(e)-n),t},Mt[wt]=function(t,e,i,n){return void 0===i&&(i=0),void 0===n&&(n=0),gt(t,ft(e)+i),kt(t,bt(e)-n),t};function Dt(t,e,i,n,s){return Mt[i](t,e,n,s)}function _t(t,e,i,n,s,r){ot.setPosition(e,i).setSize(n,s),Dt(t,ot,r)}function Yt(t,e){return void 0===e&&(e={}),"number"==typeof t?(e.left=t,e.right=t,e.top=t,e.bottom=t):(e.left=Bt(t,"left",0),e.right=Bt(t,"right",0),e.top=Bt(t,"top",0),e.bottom=Bt(t,"bottom",0)),e}function Rt(t){return Ut.call(this,t),this.sizerEventsEnable&&(t.emit("sizer.add",t,this),this.emit("add",t,this)),this}function Xt(t,e){return void 0===this.childrenMap&&(this.childrenMap={}),this.childrenMap[t]=e,this}function Vt(t,e){return void 0===e?t:t[e]}function zt(t,e,i){var n=u(e);"string"===n?t[e]=i:"number"===n?(t.left=e,t.right=e,t.top=e,t.bottom=e):(t.left=qt(e,"left",0),t.right=qt(e,"right",0),t.top=qt(e,"top",0),t.bottom=qt(e,"bottom",0))}function It(t){var e=Math.max(this.childrenWidth,this.minWidth);return void 0===t&&(t=e),t}function At(t){var e=Math.max(this.childrenHeight,this.minHeight);return void 0===t&&(t=e),t}function jt(){this._childrenWidth=void 0,this._childrenHeight=void 0;for(var t,e=this.getChildrenSizers(),i=0,n=e.length;i<n;i++)(t=e[i]).ignoreLayout||t.preLayout()}function Ht(t){return t instanceof ee}function Lt(t){return null==t||"object"!==u(t)?null:Ht(t)?t:t.scene&&Ht(t.scene)?t.scene:t.parent&&t.parent.scene&&Ht(t.parent.scene)?t.parent.scene:void 0}var Wt=Phaser.Utils.Objects.GetValue,Nt=Phaser.GameObjects.Group,Ft=function(t){return t.add.text(0,0,"")},Gt=new Phaser.Geom.Rectangle,Bt=Phaser.Utils.Objects.GetValue,Ut=tt.prototype.add,Jt=tt.prototype.add,Zt={pin:function(t){return Jt.call(this,t),this},addBackground:function(t,e,i){return void 0===this.backgroundChildren&&(this.backgroundChildren=[]),"string"==typeof e&&(i=e,e=void 0),void 0===e&&(e=0),Rt.call(this,t),this.backgroundChildren.push(t),this.getSizerConfig(t).padding=Yt(e),void 0!==i&&this.addChildrenMap(i,t),this},isBackground:function(t){return void 0!==this.backgroundChildren&&-1!==this.backgroundChildren.indexOf(t)}},Kt=/(\S+)\[(\d+)\]/i,qt=Phaser.Utils.Objects.GetValue,$t={getInnerPadding:function(t){return Vt(this.space,t)},setInnerPadding:function(t,e){return zt(this.space,t,e),this},getOutterPadding:function(t){return Vt(this.getSizerConfig(this).padding,t)},setOuterPadding:function(t,e){return zt(this.getSizerConfig(this).padding,t,e),this},getChildOutterPadding:function(t,e){return"string"==typeof t&&(t=this.getElement(t)),Vt(this.getSizerConfig(t).padding,e)},setChildOuterPadding:function(t,e,i){return"string"==typeof t&&(t=this.getElement(t)),zt(this.getSizerConfig(t).padding,e,i),this}},Qt={getShownChildren:function(t){void 0===t&&(t=[]);for(var e,i=this.children,n=0,s=i.length;n<s;n++)(e=i[n]).rexSizer&&e.rexSizer.hidden||t.push(e);return t},getAllShownChildren:function(t){void 0===t&&(t=[]);for(var e,i=this.children,n=0,s=i.length;n<s;n++){if(!(e=i[n]).rexSizer||!e.rexSizer.hidden)if(t.push(e),e.hasOwnProperty("isRexContainerLite"))t.push.apply(t,o(e.getAllShownChildren()))}return t}},te={setEventEmitter:function(t,e){return void 0===e&&(e=Phaser.Events.EventEmitter),this._privateEE=!0===t||void 0===t,this._eventEmitter=this._privateEE?new e:t,this},destroyEventEmitter:function(){return this._eventEmitter&&this._privateEE&&this._eventEmitter.shutdown(),this},getEventEmitter:function(){return this._eventEmitter},on:function(){return this._eventEmitter&&this._eventEmitter.on.apply(this._eventEmitter,arguments),this},once:function(){return this._eventEmitter&&this._eventEmitter.once.apply(this._eventEmitter,arguments),this},off:function(){return this._eventEmitter&&this._eventEmitter.off.apply(this._eventEmitter,arguments),this},emit:function(t){return this._eventEmitter&&t&&this._eventEmitter.emit.apply(this._eventEmitter,arguments),this},addListener:function(){return this._eventEmitter&&this._eventEmitter.addListener.apply(this._eventEmitter,arguments),this},removeListener:function(){return this._eventEmitter&&this._eventEmitter.removeListener.apply(this._eventEmitter,arguments),this},removeAllListeners:function(){return this._eventEmitter&&this._eventEmitter.removeAllListeners.apply(this._eventEmitter,arguments),this},listenerCount:function(){return this._eventEmitter?this._eventEmitter.listenerCount.apply(this._eventEmitter,arguments):0},listeners:function(){return this._eventEmitter?this._eventEmitter.listeners.apply(this._eventEmitter,arguments):[]},eventNames:function(){return this._eventEmitter?this._eventEmitter.eventNames.apply(this._eventEmitter,arguments):[]}},ee=Phaser.Scene,ie=Phaser.Utils.Objects.GetValue,ne=function(){function i(t,e){y(this,i),this.parent=t,this.scene=Lt(t),this.isShutdown=!1,this.setEventEmitter(ie(e,"eventEmitter",!0)),this.parent&&this.parent===this.scene?this.scene.events.once("shutdown",this.onSceneDestroy,this):this.parent&&this.parent.once&&this.parent.once("destroy",this.onParentDestroy,this)}return m(i,[{key:"shutdown",value:function(){this.isShutdown||(this.parent&&this.parent===this.scene?this.scene.events.off("shutdown",this.onSceneDestroy,this):this.parent&&this.parent.once&&this.parent.off("destroy",this.onParentDestroy,this),this.destroyEventEmitter(),this.parent=void 0,this.scene=void 0,this.isShutdown=!0)}},{key:"destroy",value:function(t){this.shutdown(t)}},{key:"onSceneDestroy",value:function(){this.destroy(!0)}},{key:"onParentDestroy",value:function(t,e){this.destroy(e)}}]),i}();Object.assign(ne.prototype,te);var se=Phaser.Geom.Rectangle;Phaser.Scale.Center;function re(t){return i=t,n="complete",new Promise(function(t,e){i.once(n,function(){t()})});var i,n}function oe(e,t){t.completeEventName=void 0,t.on("complete",function(){t.completeEventName&&(e.emit(t.completeEventName,e),t.completeEventName=void 0)}),t.on("update",function(){var t=e.getParentSizer();t&&t.resetChildPositionState(e)})}function he(e,t){t.completeEventName=void 0,t.on("complete",function(){t.completeEventName&&(e.emit(t.completeEventName,e),t.completeEventName=void 0)}),t.on("update",function(){var t=e.getParentSizer();t&&t.resetChildAlphaState(e)})}function ae(t,e){if("number"==typeof t)return t;var i=t[0],n=parseFloat(t.substr(2));switch(i){case"+":return e+n;case"-":return e-n;case"*":return e*n;case"/":return e/n}}function le(e,t){t.completeEventName=void 0,t.on("complete",function(){t.completeEventName&&(e.emit(t.completeEventName,e),t.completeEventName=void 0)}),t.on("update",function(){var t=e.getParentSizer();t&&t.resetChildPositionState(e)})}function ue(t,e,i,n,s){return!(!t||!t.getBounds)&&(!(n&&!n(t,e,i))&&(!!(ri=t.getBounds(ri)).contains(e,i)&&!(s&&!s(t,e,i))))}function ce(t,e,i,n,s){return ue(t,e,i,oi(n),hi(s))}function de(t){return!(t.rexSizer&&t.rexSizer.hidden)}function ve(t,e,i){!t||void 0===e&&void 0===i||(t.resize?(void 0===e&&(e=t.width),void 0===i&&(i=t.height),t.resize(e,i)):(void 0!==e&&(t.displayWidth=e),void 0!==i&&(t.displayHeight=i)))}function pe(t){var e,i;this.sizerEventsEnable&&(e=t,void 0===(i=this.getChildPrevState(t))?i={}:!0===i&&(i=ai),i.x=e.x,i.y=e.y,i.scaleX=e.scaleX,i.scaleY=e.scaleY,i.width=e.width,i.height=e.height,i.displayWidth=e.displayWidth,i.displayHeight=e.displayHeight,this.layoutedChildren.push(t))}function fe(t,e,i,n,s,r,o,h){_t(t,e,i,n,s,r),void 0!==o&&(t.x+=o),void 0!==h&&(t.y+=h),this.resetChildPositionState(t),this.sizerEventsEnable&&t.emit("sizer.postlayout",t,this)}var ge=new se,ye=function(){i(s,ne);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,{eventEmitter:!1})).viewport=void 0,i.resetFromJSON(e),i.boot(),i}return m(s,[{key:"resetFromJSON",value:function(t){var e,i,n,s,r,o,h,a;void 0===t&&(t={}),void 0!==t.x?(e=null,i=t.x):void 0!==t.left?(e=0,i=t.left):void 0!==t.right?(e=1,i=t.right):void 0!==t.centerX&&(e=.5,i=t.centerX),void 0!==t.y?(n=null,s=t.y):void 0!==t.top?(n=0,s=t.top):void 0!==t.bottom?(n=1,s=t.bottom):void 0!==t.centerY&&(n=.5,s=t.centerY),void 0!==i&&(i=i.replace("left","0%").replace("right","100%").replace("center","50%").split("%"),r=parseFloat(i[0])/100,o=""===i[1]?0:parseFloat(i[1])),void 0!==s&&(s=s.replace("top","0%").replace("bottom","100%").replace("center","50%").split("%"),h=parseFloat(s[0])/100,a=""===s[1]?0:parseFloat(s[1]));var l,u,c=t.width;void 0!==c&&(c=c.split("%"),l=parseFloat(c[0])/100,u=""===c[1]?0:parseFloat(c[1]));var d,v,p=t.height;void 0!==p&&(p=p.split("%"),d=parseFloat(p[0])/100,v=""===p[1]?0:parseFloat(p[1])),this.setAlign(e,n),this.setPercentage(r,h),this.setOffset(o,a),this.setSizePercentage(l,d),this.setSizePadding(u,v);var f=t.onResizeCallback,g=t.onResizeCallbackScope;void 0!==f&&this.setResizeCallback(f,g);var y=t.onUpdateViewportCallback,m=t.onUpdateViewportCallbackScope;return void 0!==y&&this.setUpdateViewportCallback(y,m),this}},{key:"boot",value:function(){this.scene.scale.on("resize",this.anchor,this),this.anchor()}},{key:"shutdown",value:function(t){this.isShutdown||(this.scene.scale.off("resize",this.anchor,this),this.viewport=void 0,this.onUpdateViewportCallback=void 0,this.onUpdateViewportCallbackScope=void 0,this.onResizeCallback=void 0,this.onResizeCallbackScope=void 0,S(b(s.prototype),"shutdown",this).call(this,t))}},{key:"setAlign",value:function(t,e){return this.alignX=t,this.alignY=e,this}},{key:"setPercentage",value:function(t,e){return this.percentageX=t,this.percentageY=e,this}},{key:"setOffset",value:function(t,e){return this.offsetX=t,this.offsetY=e,this}},{key:"setSizePercentage",value:function(t,e){return this.percentageWidth=t,this.percentageHeight=e,this}},{key:"setSizePadding",value:function(t,e){return this.paddingWidth=t,this.paddingHeight=e,this}},{key:"setResizeCallback",value:function(t,e){return this.onResizeCallback=t,this.onResizeCallbackScope=e,this}},{key:"setUpdateViewportCallback",value:function(t,e){return this.onUpdateViewportCallback=t,this.onUpdateViewportCallbackScope=e,this}},{key:"anchor",value:function(){return this.updateViewport(),this.updateSize(),this.updatePosition(),this}},{key:"updateSize",value:function(){var t=this.onResizeCallback,e=this.onResizeCallbackScope,i=this.anchorWidth,n=this.anchorHeight;if((void 0!==i||void 0!==n)&&t){var s=this.parent;void 0===i&&(i=s.width),void 0===n&&(n=s.height),e?t.call(e,i,n,s,this):t(i,n,s,this)}}},{key:"updatePosition",value:function(){var t=this.parent;return null===this.alignX?t.x=this.anchorX:void 0!==this.alignX&&(t.x=this.anchorX+t.displayWidth*(t.originX-this.alignX)),null===this.alignY?t.y=this.anchorY:void 0!==this.alignY&&(t.y=this.anchorY+t.displayHeight*(t.originY-this.alignY)),this}},{key:"anchorX",get:function(){return this.viewport.x+this.viewport.width*this.percentageX+this.offsetX}},{key:"anchorY",get:function(){return this.viewport.y+this.viewport.height*this.percentageY+this.offsetY}},{key:"anchorWidth",get:function(){if(void 0!==this.percentageWidth)return this.viewport.width*this.percentageWidth+this.paddingWidth}},{key:"anchorHeight",get:function(){if(void 0!==this.percentageHeight)return this.viewport.height*this.percentageHeight+this.paddingHeight}},{key:"updateViewport",value:function(){this.viewport=function(t,e){void 0===e?e=new se:!0===e&&(e=ge);var i,n,s=t.scale,r=s.baseSize,o=s.parentSize,h=s.canvasBounds,a=s.displayScale,l=0<=h.x?0:-(h.x*a.x),u=0<=h.y?0:-(h.y*a.y);return i=o.width>=h.width?r.width:r.width-(h.width-o.width)*a.x,n=o.height>=h.height?r.height:r.height-(h.height-o.height)*a.y,e.setTo(l,u,i,n),e}(this.scene,!this.viewport||this.viewport);var t=this.onUpdateViewportCallback,e=this.onUpdateViewportCallbackScope;t&&(e?t.call(e,this.viewport,this.parent,this):t(this.viewport,this.parent,this))}}]),s}(),me=Phaser.Utils.Objects.GetValue,be=function(){i(s,ne);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,e))._isRunning=!1,i.isPaused=!1,i.tickingState=!1,i.setTickingMode(me(e,"tickingMode",1)),i}return m(s,[{key:"boot",value:function(){2!==this.tickingMode||this.tickingState||this.startTicking()}},{key:"shutdown",value:function(t){this.isShutdown||(this.stop(),this.tickingState&&this.stopTicking(),S(b(s.prototype),"shutdown",this).call(this,t))}},{key:"setTickingMode",value:function(t){"string"==typeof t&&(t=ke[t]),this.tickingMode=t}},{key:"startTicking",value:function(){this.tickingState=!0}},{key:"stopTicking",value:function(){this.tickingState=!1}},{key:"isRunning",get:function(){return this._isRunning},set:function(t){this._isRunning!==t&&(this._isRunning=t,1===this.tickingMode&&t!=this.tickingState&&(t?this.startTicking():this.stopTicking()))}},{key:"start",value:function(){return this.isPaused=!1,this.isRunning=!0,this}},{key:"pause",value:function(){return this.isRunning&&(this.isPaused=!0,this.isRunning=!1),this}},{key:"resume",value:function(){return this.isPaused&&(this.isRunning=!0),this}},{key:"stop",value:function(){return this.isPaused=!1,this.isRunning=!1,this}},{key:"complete",value:function(){this.isPaused=!1,this.isRunning=!1,this.emit("complete",this.parent,this)}}]),s}(),ke={no:0,lazy:1,always:2},Ce=function(){i(e,be);var t=C(e);function e(){return y(this,e),t.apply(this,arguments)}return m(e,[{key:"startTicking",value:function(){S(b(e.prototype),"startTicking",this).call(this),this.scene.events.on("update",this.update,this)}},{key:"stopTicking",value:function(){S(b(e.prototype),"stopTicking",this).call(this),this.scene&&this.scene.events.off("update",this.update,this)}}]),e}(),Se=Phaser.Utils.Objects.GetValue,we=Phaser.Math.Clamp,xe=function(){function e(t){y(this,e),this.resetFromJSON(t)}return m(e,[{key:"resetFromJSON",value:function(t){this.state=Se(t,"state",Oe),this.timeScale=Se(t,"timeScale",1),this.delay=Se(t,"delay",0),this.repeat=Se(t,"repeat",0),this.repeatCounter=Se(t,"repeatCounter",0),this.duration=Se(t,"duration",0),this.nowTime=Se(t,"nowTime",0),this.justRestart=Se(t,"justRestart",!1)}},{key:"toJSON",value:function(){return{state:this.state,timeScale:this.timeScale,delay:this.delay,repeat:this.repeat,repeatCounter:this.repeatCounter,duration:this.duration,nowTime:this.nowTime,justRestart:this.justRestart}}},{key:"destroy",value:function(){}},{key:"setTimeScale",value:function(t){return this.timeScale=t,this}},{key:"setDelay",value:function(t){return void 0===t&&(t=0),this.delay=t,this}},{key:"setDuration",value:function(t){return this.duration=t,this}},{key:"setRepeat",value:function(t){return this.repeat=t,this}},{key:"setRepeatInfinity",value:function(){return this.repeat=-1,this}},{key:"start",value:function(){return this.nowTime=0<this.delay?-this.delay:0,this.state=0<=this.nowTime?Ee:Pe,this.repeatCounter=0,this}},{key:"stop",value:function(){return this.state=Oe,this}},{key:"update",value:function(t,e){this.state!==Oe&&this.state!==Te&&0!==e&&0!==this.timeScale&&(this.nowTime+=e*this.timeScale,this.state=0<=this.nowTime?Ee:Pe,this.justRestart=!1,this.nowTime>=this.duration&&(-1===this.repeat||this.repeatCounter<this.repeat?(this.repeatCounter++,this.justRestart=!0,this.nowTime-=this.duration):(this.nowTime=this.duration,this.state=Te)))}},{key:"t",get:function(){var t;switch(this.state){case Oe:case Pe:t=0;break;case Ee:t=this.nowTime/this.duration;break;case Te:t=1}return we(t,0,1)},set:function(t){(t=we(t,-1,1))<0?(this.state=Pe,this.nowTime=-this.delay*t):(this.state=Ee,this.nowTime=this.duration*t,1===t&&0!==this.repeat&&this.repeatCounter++)}},{key:"isIdle",get:function(){return this.state===Oe}},{key:"isDelay",get:function(){return this.state===Pe}},{key:"isCountDown",get:function(){return this.state===Ee}},{key:"isRunning",get:function(){return this.state===Pe||this.state===Ee}},{key:"isDone",get:function(){return this.state===Te}},{key:"isOddIteration",get:function(){return 1==(1&this.repeatCounter)}},{key:"isEvenIteration",get:function(){return 0==(1&this.repeatCounter)}}]),e}(),Oe=0,Pe=1,Ee=2,Te=-1,Me=function(){i(s,Ce);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,e)).timer=new xe,i}return m(s,[{key:"shutdown",value:function(t){this.isShutdown||(S(b(s.prototype),"shutdown",this).call(this,t),this.timer.destroy(),this.timer=void 0)}},{key:"start",value:function(){return this.timer.start(),S(b(s.prototype),"start",this).call(this),this}},{key:"stop",value:function(){return this.timer.stop(),S(b(s.prototype),"stop",this).call(this),this}},{key:"complete",value:function(){return this.timer.stop(),S(b(s.prototype),"complete",this).call(this),this}}]),s}(),De=Phaser.Utils.Objects.GetValue,_e=Phaser.Utils.Objects.GetAdvancedValue,Ye=Phaser.Tweens.Builders.GetEaseFunction,Re=function(){i(e,Me);var t=C(e);function e(){return y(this,e),t.apply(this,arguments)}return m(e,[{key:"resetFromJSON",value:function(t){return this.timer.resetFromJSON(De(t,"timer")),this.setEnable(De(t,"enable",!0)),this.setDelay(_e(t,"delay",0)),this.setDuration(_e(t,"duration",1e3)),this.setEase(De(t,"ease","Linear")),this.setRepeat(De(t,"repeat",0)),this}},{key:"setEnable",value:function(t){return null==t&&(t=!0),this.enable=t,this}},{key:"setDelay",value:function(t){return this.delay=t,this}},{key:"setDuration",value:function(t){return this.duration=t,this}},{key:"setEase",value:function(t){return void 0===t&&(t="Linear"),this.ease=t,this.easeFn=Ye(t),this}},{key:"setRepeat",value:function(t){return this.repeat=t,this}},{key:"start",value:function(){return this.timer.isRunning||S(b(e.prototype),"start",this).call(this),this}},{key:"restart",value:function(){return this.timer.stop(),this.start.apply(this,arguments),this}},{key:"update",value:function(t,e){if(!this.isRunning||!this.enable)return this;var i=this.parent;if(!i.active)return this;var n=this.timer;return n.update(t,e),n.isDelay||this.updateGameObject(i,n),this.emit("update",i,this),n.isDone&&this.complete(),this}},{key:"updateGameObject",value:function(){}}]),e}(),Xe=Phaser.Utils.Objects.GetValue,Ve=Phaser.Utils.Objects.GetAdvancedValue,ze=Phaser.Math.Linear,Ie=function(){i(s,Re);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,e)).scaleStart={},i.scaleEnd={},i.resetFromJSON(e),i.boot(),i}return m(s,[{key:"resetFromJSON",value:function(t){return S(b(s.prototype),"resetFromJSON",this).call(this,t),this.setMode(Xe(t,"mode",0)),this.setScaleRange(Ve(t,"start",void 0),Ve(t,"end",0)),this}},{key:"setMode",value:function(t){return"string"==typeof t&&(t=Ae[t]),this.mode=t,this}},{key:"setScaleRange",value:function(t,e){return"number"==typeof t?(this.startX=t,this.startY=t):(this.startX=Ve(t,"x",this.parent.scaleX),this.startY=Ve(t,"y",this.parent.scaleY)),"number"==typeof e?(this.endX=e,this.endY=e):(this.endX=Ve(e,"x",void 0),this.endY=Ve(e,"y",void 0)),this.hasScaleX=void 0!==this.startX&&void 0!==this.endX,this.hasScaleY=void 0!==this.startY&&void 0!==this.endY,this}},{key:"start",value:function(){if(this.timer.isRunning)return this;var t=this.parent;return this.hasScaleX&&(t.scaleX=this.startX),this.hasScaleY&&(t.scaleY=this.startY),this.timer.setDelay(this.delay).setDuration(this.duration).setRepeat(2===this.mode?-1:0),S(b(s.prototype),"start",this).call(this),this}},{key:"updateGameObject",value:function(t,e){var i=e.t;e.isOddIteration&&(i=1-i),i=this.easeFn(i),this.hasScaleX&&(t.scaleX=ze(this.startX,this.endX,i)),this.hasScaleY&&(t.scaleY=ze(this.startY,this.endY,i))}},{key:"complete",value:function(){return S(b(s.prototype),"complete",this).call(this),1===this.mode&&this.parent.destroy(),this}}]),s}(),Ae={stop:0,destroy:1,yoyo:2},je=Phaser.Utils.Objects.IsPlainObject,He={popUp:function(t,e,i){if(je(t)){var n=t;t=n.duration,e=n.orientation,i=n.ease}var s=void 0===this._scale;return this._scale=function(t,e,i,n,s){var r;switch(i){case 0:case"x":r={x:0};break;case 1:case"y":r={y:0};break;default:r=0}var o={mode:0,start:r,end:1,duration:e,ease:void 0===n?"Cubic":n};return void 0===s?s=new Ie(t,o):s.resetFromJSON(o),s.restart(),s}(this,t,e,i,this._scale),s&&oe(this,this._scale),this._scale.completeEventName="popup.complete",this},popUpPromise:function(t,e,i){return this.popUp(t,e,i),re(this._scale)},scaleDownDestroy:function(t,e,i,n){if(je(t)){var s=t;t=s.duration,e=s.orientation,i=s.ease,n=s.destroy}var r=void 0===this._scale;return this._scale=function(t,e,i,n,s,r){s instanceof Ie&&(r=s,s=void 0),void 0===s&&(s=!0);var o={};switch(o.mode=s?1:0,i){case 0:case"x":o.end={x:0};break;case 1:case"y":o.end={y:0};break;default:o.end=0}return o.duration=e,o.ease=void 0===n?"Linear":n,void 0===r?r=new Ie(t,o):r.resetFromJSON(o),r.restart(),r}(this,t,e,i,n,this._scale),r&&oe(this,this._scale),this._scale.completeEventName="scaledown.complete",this},scaleDownDestroyPromise:function(t,e,i,n){return this.scaleDownDestroy(t,e,i,n),re(this._scale)},scaleDown:function(t,e,i){return this.scaleDownDestroy(t,e,i,!1),this},scaleDownPromise:function(t,e,i){return this.scaleDown(t,e,i),re(this._scale)}},Le=Phaser.Utils.Objects.GetValue,We=Phaser.Utils.Objects.GetAdvancedValue,Ne=Phaser.Math.Linear,Fe=function(){i(s,Re);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,e)).resetFromJSON(e),i.boot(),i}return m(s,[{key:"resetFromJSON",value:function(t){return S(b(s.prototype),"resetFromJSON",this).call(this,t),this.setMode(Le(t,"mode",0)),this.setAlphaRange(We(t,"start",this.parent.alpha),We(t,"end",0)),this}},{key:"setMode",value:function(t){return"string"==typeof t&&(t=Ge[t]),this.mode=t,this}},{key:"setAlphaRange",value:function(t,e){return this.alphaStart=t,this.alphaEnd=e,this}},{key:"start",value:function(){return this.timer.isRunning||(this.parent.setAlpha(this.alphaStart),this.timer.setDelay(this.delay).setDuration(this.duration).setRepeat(2===this.mode?-1:0),S(b(s.prototype),"start",this).call(this)),this}},{key:"updateGameObject",value:function(t,e){var i=e.t;e.isOddIteration&&(i=1-i),t.alpha=Ne(this.alphaStart,this.alphaEnd,i)}},{key:"complete",value:function(){return S(b(s.prototype),"complete",this).call(this),1===this.mode&&this.parent.destroy(),this}}]),s}(),Ge={stop:0,destroy:1,yoyo:2},Be=Phaser.Utils.Objects.IsPlainObject,Ue=Phaser.Utils.Objects.IsPlainObject,Je={fadeIn:function(t,e){Ue(t)&&(t=t.duration);var i=void 0===this._fade;return this._fade=function(t,e,i,n){var s,r;r=Be(i)?(s=i.start,i.end):i,void 0===s&&(s=0),void 0===r&&(r=1);var o={mode:0,start:s,end:r,duration:e};return void 0===n?n=new Fe(t,o):n.resetFromJSON(o),n.restart(),n}(this,t,e,this._fade),i&&he(this,this._fade),this._fade.completeEventName="fadein.complete",this},fadeInPromoise:function(t,e){return this.fadeIn(t,e),re(this._fade)},fadeOutDestroy:function(t,e){if(Ue(t)){var i=t;t=i.duration,e=i.destroy}var n=void 0===this._fade;return this._fade=function(t,e,i,n){i instanceof Fe&&(n=i,i=void 0),void 0===i&&(i=!0);var s={mode:i?1:0,end:0,duration:e};return void 0===n?n=new Fe(t,s):n.resetFromJSON(s),n.restart(),n}(this,t,e,this._fade),n&&he(this,this._fade),this._fade.completeEventName="fadeout.complete",this},fadeOutDestroyPromise:function(t,e){return this.fadeOutDestroy(t,e),re(this._fade)},fadeOut:function(t){return this.fadeOutDestroy(t,!1),this},fadeOutPromise:function(t){return this.fadeOut(t),re(this._fade)}},Ze=Phaser.Utils.Objects.GetValue,Ke=Phaser.Utils.Objects.GetAdvancedValue,qe=Phaser.Math.Linear,$e=function(){i(s,Re);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,e)).resetFromJSON(e),i.boot(),i}return m(s,[{key:"resetFromJSON",value:function(t){if(S(b(s.prototype),"resetFromJSON",this).call(this,t),this.setMode(Ze(t,"mode",0)),t&&(t.hasOwnProperty("x")||t.hasOwnProperty("y"))){var e=Ke(t,"x",void 0),i=Ke(t,"y",void 0);this.setTargetPosition(e,i)}else this.setTargetPosition(t);return this}},{key:"setMode",value:function(t){return"string"==typeof t&&(t=Qe[t]),this.mode=t,this}},{key:"setTargetPosition",value:function(t,e){if("number"==typeof t||"number"==typeof e)this.startX=this.parent.x,this.startY=this.parent.y,this.endX=t,this.endY=e;else{var i=t;this.startX=Ke(i,"startX",void 0),this.startY=Ke(i,"startY",void 0),this.endX=Ke(i,"endX",void 0),this.endY=Ke(i,"endY",void 0)}return this.hasMoveX=void 0!==this.startX&&void 0!==this.endX,this.hasMoveY=void 0!==this.startY&&void 0!==this.endY,this}},{key:"start",value:function(){if(this.timer.isRunning)return this;var t=this.parent;return this.hasMoveX&&(t.x=this.startX),this.hasMoveY&&(t.y=this.startY),this.timer.setDelay(this.delay).setDuration(this.duration).setRepeat(2===this.mode?-1:0),S(b(s.prototype),"start",this).call(this),this}},{key:"updateGameObject",value:function(t,e){var i=e.t;e.isOddIteration&&(i=1-i),i=this.easeFn(i),this.hasMoveX&&(t.x=qe(this.startX,this.endX,i)),this.hasMoveY&&(t.y=qe(this.startY,this.endY,i))}},{key:"complete",value:function(){return S(b(s.prototype),"complete",this).call(this),1===this.mode&&this.parent.destroy(),this}}]),s}(),Qe={stop:0,destroy:1,yoyo:2},ti=Phaser.Utils.Objects.IsPlainObject,ei=Phaser.Math.Distance.Between,ii={moveFrom:function(t,e,i,n,s){if(ti(t)){var r=t;e=r.x,i=r.y,t=r.hasOwnProperty("speed")?1e3*ei(e,i,this.x,this.y)/r.speed:r.duration,n=r.ease}var o=void 0===this._easeMove;return this._easeMove=function(t,e,i,n,s,r,o){r instanceof $e&&(o=r,r=void 0),void 0===r&&(r=!1);var h={};return h.mode=r?1:0,void 0!==i&&(h.startX=ae(i,t.x),h.endX=t.x),void 0!==n&&(h.startY=ae(n,t.y),h.endY=t.y),h.duration=e,h.ease=void 0===s?"Linear":s,void 0===o?o=new $e(t,h):o.resetFromJSON(h),o.restart(),o}(this,t,e,i,n,s,this._easeMove),o&&le(this,this._easeMove),this._easeMove.completeEventName="movefrom.complete",this},moveFromPromise:function(t,e,i,n,s){return this.moveFrom(t,e,i,n,s),re(this._easeMove)},moveFromDestroy:function(t,e,i,n){return this.moveFrom(t,e,i,n,!0),this},moveFromDestroyPromise:function(t,e,i,n){return this.moveFromDestroy(t,e,i,n),re(this._easeMove)},moveTo:function(t,e,i,n,s){if(ti(t)){var r=t;e=r.x,i=r.y,t=r.hasOwnProperty("speed")?1e3*ei(e,i,this.x,this.y)/r.speed:r.duration,n=r.ease}var o=void 0===this._easeMove;return this._easeMove=function(t,e,i,n,s,r,o){r instanceof $e&&(o=r,r=void 0),void 0===r&&(r=!1);var h={};return h.mode=r?1:0,void 0!==i&&(h.startX=t.x,h.endX=ae(i,t.x)),void 0!==n&&(h.startY=t.y,h.endY=ae(n,t.y)),h.duration=e,h.ease=void 0===s?"Linear":s,void 0===o?o=new $e(t,h):o.resetFromJSON(h),o.restart(),o}(this,t,e,i,n,s,this._easeMove),o&&le(this,this._easeMove),this._easeMove.completeEventName="moveto.complete",this},moveToPromise:function(t,e,i,n,s){return this.moveTo(t,e,i,n,s),re(this._easeMove)},moveToDestroy:function(t,e,i,n){return this.moveTo(t,e,i,n,!0),this},moveToDestroyPromise:function(t,e,i,n){return this.moveToDestroy(t,e,i,n,!0),re(this._easeMove)}},ni=function(t,e){t&&(et(t).hidden=e,t.rexContainer.parent.setChildVisible(t,!e))},si={show:function(t){return void 0===t&&(t=this),ni(t,!1),this},hide:function(t){return void 0===t&&(t=this),ni(t,!0),this},isShow:function(t){return void 0===t&&(t=this),!!(e=t)&&!et(e).hidden;var e}},ri=void 0,oi=function(n){return n?function(t,e,i){return!!de(t)&&(n(t,e,i),!0)}:de},hi=function(t){return t},ai={},li=Phaser.Display.Align.CENTER,ui=Phaser.Utils.Objects.GetValue,ci=function(){i(s,ne);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,e))._enable=void 0,t.setInteractive(ui(e,"inputConfig",void 0)),i.resetFromJSON(e),i.boot(),i}return m(s,[{key:"resetFromJSON",value:function(t){return this.pointer=void 0,this.lastClickTime=void 0,this.setEnable(ui(t,"enable",!0)),this.setMode(ui(t,"mode",1)),this.setClickInterval(ui(t,"clickInterval",100)),this.setDragThreshold(ui(t,"threshold",void 0)),this}},{key:"boot",value:function(){var t=this.parent;t.on("pointerdown",this.onPress,this),t.on("pointerup",this.onRelease,this),t.on("pointerout",this.onPointOut,this),t.on("pointermove",this.onMove,this)}},{key:"shutdown",value:function(t){this.isShutdown||(this.pointer=null,S(b(s.prototype),"shutdown",this).call(this,t))}},{key:"enable",get:function(){return this._enable},set:function(t){if(this._enable!==t){t||this.cancel();var e=(this._enable=t)?"enable":"disable";this.emit(e,this,this.parent)}}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"toggleEnable",value:function(){return this.setEnable(!this.enable),this}},{key:"setMode",value:function(t){return"string"==typeof t&&(t=di[t]),this.mode=t,this}},{key:"setClickInterval",value:function(t){return this.clickInterval=t,this}},{key:"setDragThreshold",value:function(t){return this.dragThreshold=t,this}},{key:"onPress",value:function(t,e,i,n){void 0===this.pointer&&(this.pointer=t,0===this.mode&&this.click(t.downTime,t,n))}},{key:"onRelease",value:function(t,e,i,n){this.pointer===t&&(1===this.mode&&this.click(t.upTime,t,n),this.pointer=void 0)}},{key:"onPointOut",value:function(t){this.pointer===t&&this.cancel()}},{key:"onMove",value:function(t){this.pointer===t&&void 0!==this.dragThreshold&&t.getDistance()>=this.dragThreshold&&this.cancel()}},{key:"click",value:function(t,e,i){if(!this.enable)return this;if(void 0===t)return this.emit("click",this,this.parent,e,i),this;this.pointer=void 0;var n=this.lastClickTime;return void 0!==n&&t-n<=this.clickInterval||(this.lastClickTime=t,this.emit("click",this,this.parent,e,i)),this}},{key:"cancel",value:function(){return this.pointer=void 0,this}}]),s}(),di={press:0,pointerdown:0,release:1,pointerup:1},vi={onClick:function(t,e,i){return t&&(void 0===this._click&&(this._click=new ci(this,i)),this._click.on("click",t,e)),this},offClick:function(t,e){return void 0===this._click||this._click.off("click",t,e),this},enableClick:function(t){return void 0===this._click||this._click.setEnable(t),this},disableClick:function(){return void 0===this._click||this._click.setEnable(!1),this}},pi={getSizerConfig:et,getChildPrevState:function(t){var e=et(t);return e.hasOwnProperty("prevState")||(e.prevState={}),e.prevState},pushIntoBounds:function(t){return void 0===t&&(t=function(t,e){void 0===e&&(void 0===nt&&(nt=new Phaser.Geom.Rectangle),e=nt);var i=t.game.config;return e.setTo(0,0,i.width,i.height),e}(this.scene)),this.left=Math.max(this.left,t.left),this.right=Math.min(this.right,t.right),this.top=Math.max(this.top,t.top),this.bottom=Math.min(this.bottom,t.bottom),this},drawBounds:function(t,e){var i,n,s,r,o=t.scene;if("number"==typeof e)i=e;else{i=Wt(e,"color",16777215);var h=Wt(e,"name",!1);h&&(n=Wt(h,"createTextCallback",Ft),s=Wt(h,"createTextCallbackScope",void 0),"string"==typeof(r=Wt(h,"align","left-top"))&&(r=rt[r]))}if(n&&!t.children){t.children=new Nt(o),t.once("destroy",function(t,e){t.children.destroy(!e),t.children=void 0});var a=t.clear.bind(t);t.clear=function(){a(),t.children.clear(!1,!0)}}for(var l,u,c=this.getAllShownChildren([this]),d=0,v=c.length;d<v;d++)(l=c[d]).getBounds&&(i&&t.lineStyle(1,i).strokeRectShape(l.getBounds(Gt)),l.name&&n&&(u=s?n.call(s,o):n(o))&&(u.setText(l.name),t.children.add(u),_t(u,Gt.x,Gt.y,Gt.width,Gt.height,r)));return this},resolveWidth:It,resolveChildrenWidth:function(t){var e,i;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(i=this.getExpandedChildWidth(e,t),i=e.resolveWidth(i),e.resolveChildrenWidth(i))},resolveHeight:At,getChildWidth:function(t){return t.isRexSizer?Math.max(t.minWidth,t.childrenWidth):void 0!==t.minWidth?t.minWidth:ht(t)},getChildHeight:function(t){return t.isRexSizer?Math.max(t.minHeight,t.childrenHeight):void 0!==t.minHeight?t.minHeight:at(t)},getExpandedChildWidth:function(t,e){return e},getExpandedChildHeight:function(t,e){return e},getChildrenWidth:function(){return 0},getChildrenHeight:function(){return 0},addChildrenMap:Xt,addElement:Xt,getElement:function(t,e){if("string"==typeof t&&(t=t.split(".")),0!==t.length){var i=t.shift(),n=null;if("#"===i.charAt(0))i=i.substring(1),n=this.getByName(i,e);else if(-1===i.indexOf("["))this.childrenMap&&(n=this.childrenMap[i]);else{var s=i.match(Kt);if(null!=s&&this.childrenMap){var r=this.childrenMap[s[1]];r&&(n=r[s[2]])}}return 0===t.length?n:n&&n.childrenMap?n.getElement(t):null}},getAllChildrenSizers:function(t){void 0===t&&(t=[]);for(var e=t.length,i=this.getChildrenSizers(t),n=t.length,s=e;s<n;s++)i[s].getAllChildrenSizers(t);return t},getChildrenSizers:function(t){return void 0===t&&(t=[]),t},preLayout:jt,layout:function(){return this.runLayout(),this},runLayout:function(t,e,i){if(this.ignoreLayout)return this;var n=!t;return n&&this.preLayout(),e=this.resolveWidth(e),n&&(this.resolveChildrenWidth(e),this.runWidthWrap(e)),i=this.resolveHeight(i),this.resize(e,i),this.sizerEventsEnable&&void 0===this.layoutedChildren&&(this.layoutedChildren=[]),this.layoutChildren(),this.layoutBackgrounds(),this.sizerEventsEnable&&(this.emit("postlayout",this.layoutedChildren,this),this.layoutedChildren.length=0),this.postLayout()},layoutChildren:function(){},runWidthWrap:function(t){var e,i;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||(void 0===(i=this.getExpandedChildWidth(e,t))&&(i=this.resolveWidth(i)),e.runWidthWrap&&e.runWidthWrap(i));return this},layoutBackgrounds:function(){if(void 0!==this.backgroundChildren)for(var t,e,i,n,s,r,o,h=this.backgroundChildren,a=this.left,l=this.top,u=this.width,c=this.height,d=0,v=h.length;d<v;d++)(e=(t=h[d]).rexSizer).hidden||(i=e.padding,pe.call(this,t),n=a+i.left,s=l+i.top,r=u-i.left-i.right,o=c-i.top-i.bottom,ve(t,r,o),fe.call(this,t,n,s,r,o,li))},postLayout:function(){return this._anchor&&this._anchor.updatePosition(),this},setAnchor:function(t){void 0===t&&(t={});var n=t.hasOwnProperty("width"),s=t.hasOwnProperty("height"),e=t.hasOwnProperty("onResizeCallback");return!n&&!s||e||(t.onResizeCallback=function(t,e,i){n&&i.setMinWidth(t),s&&i.setMinHeight(e),i.layout()}),void 0===this._anchor?this._anchor=new ye(this,t):this._anchor.resetFromJSON(t),this},isInTouching:function(t,e){return void 0===e&&(e=this),function(t,e,i,n){if(e)return ue(t,e.x,e.y,i,n);for(var s=t.scene.input.manager,r=s.pointersTotal,o=s.pointers,h=0;h<r;h++)if(e=o[h],ue(t,e.x,e.y,i,n))return!0;return!1}(e,t)},pointToChild:function(t,e,i,n,s){var r;if((r=i)&&"function"==typeof r||(s=i,n=i=void 0),void 0===s&&(s=this.sizerChildren?this.sizerChildren:this.children),P(s)){for(var o,h=0,a=s.length;h<a;h++)if(o=s[h],ce(o,t,e,i,n))return o}else for(var l in s)if(o=s[l],ce(o,t,e,i,n))return o;return null},setDraggable:function(s,t){var e=u(s);return"string"===e?s=this.getElement(s):void 0!==s&&"object"==e||(t=s,s=this),void 0===t&&(t=!0),s.input&&s.input.hasOwnProperty("draggable")?s.input.draggable=t:t&&(s.setInteractive(),s.scene.input.setDraggable(s),s.on("drag",function(t,e,i){var n=this.getTopmostSizer();n.x+=e-s.x,n.y+=i-s.y},this)),this},broadcastEvent:function(){for(var t=this.getAllChildren([this]),e=0,i=t.length;e<i;e++){var n=t[e];n.emit.apply(n,arguments)}return this}};Object.assign(pi,$t,Zt,{getParentSizer:function(t){return this.getParent(t)},getTopmostSizer:function(t){return this.getTopmostParent(t)}},He,Je,ii,vi,si,Qt);var fi=Phaser.Utils.Objects.GetValue,gi=function(){i(l,tt);var a=C(l);function l(t,e,i,n,s,r){var o;y(this,l),(o=a.call(this,t,e,i,2,2)).isRexSizer=!0,o.setMinSize(n,s),o.setName(fi(r,"name","")),o.rexSizer={},o.space={},o.backgroundChildren=void 0,o.sizerChildren=void 0,o.layoutedChildren=void 0;var h=fi(r,"anchor",void 0);return h&&o.setAnchor(h),o.setInnerPadding(fi(r,"space",0)),o.setDraggable(fi(r,"draggable",!1)),o.setSizerEventsEnable(fi(r,"sizerEvents",!1)),o.setDirty(!0),o}return m(l,[{key:"destroy",value:function(t){if(this.scene){if(t)for(var e=this.getAllChildrenSizers([this]),i=0,n=e.length;i<n;i++)e[i].sizerEventsEnable=!1;S(b(l.prototype),"destroy",this).call(this,t),this.backgroundChildren=void 0,this.sizerChildren=void 0,this.childrenMap=void 0,this.space=void 0,this.rexSizer=void 0,this.layoutedChildren=void 0}}},{key:"setMinSize",value:function(t,e){return this.setMinWidth(t).setMinHeight(e),this}},{key:"setMinWidth",value:function(t){return null==t&&(t=0),this.minWidth=t,this}},{key:"setMinHeight",value:function(t){return null==t&&(t=0),this.minHeight=t,this}},{key:"setDirty",value:function(t){return void 0===t&&(t=!0),this.dirty=t,this}},{key:"setSizerEventsEnable",value:function(t){return void 0===t&&(t=!0),this.sizerEventsEnable=t,this}},{key:"ignoreLayout",get:function(){return this.rexSizer.hidden||!this.dirty}},{key:"childrenWidth",get:function(){return void 0===this._childrenWidth&&(this._childrenWidth=this.getChildrenWidth()),this._childrenWidth}},{key:"childrenHeight",get:function(){return void 0===this._childrenHeight&&(this._childrenHeight=this.getChildrenHeight()),this._childrenHeight}},{key:"left",get:function(){return this.x-ht(this)*this.originX},set:function(t){this.x+=t-this.left}},{key:"alignLeft",value:function(t){return this.left=t,this}},{key:"right",get:function(){return this.left+ht(this)},set:function(t){this.x+=t-this.right}},{key:"alignRight",value:function(t){return this.right=t,this}},{key:"centerX",get:function(){return this.left+ht(this)/2},set:function(t){this.x+=t-this.centerX}},{key:"alignCenterX",value:function(t){return this.centerX=t,this}},{key:"top",get:function(){return this.y-at(this)*this.originY},set:function(t){this.y+=t-this.top}},{key:"alignTop",value:function(t){return this.top=t,this}},{key:"bottom",get:function(){return this.top+at(this)},set:function(t){this.y+=t-this.bottom}},{key:"alignBottom",value:function(t){return this.bottom=t,this}},{key:"centerY",get:function(){return this.top+at(this)/2},set:function(t){this.y+=t-this.centerY}},{key:"alignCenterY",value:function(t){return this.centerY=t,this}},{key:"innerLeft",get:function(){return this.left+this.space.left}},{key:"innerRight",get:function(){return this.right-this.space.right}},{key:"innerTop",get:function(){return this.top+this.space.top}},{key:"innerBottom",get:function(){return this.bottom-this.space.bottom}},{key:"innerWidth",get:function(){return this.width-this.space.left-this.space.right}},{key:"innerHeight",get:function(){return this.height-this.space.top-this.space.bottom}},{key:"minInnerWidth",get:function(){var t=this.minWidth-this.space.left-this.space.right;return Math.max(t,0)}},{key:"minInnerHeight",get:function(){var t=this.minHeight-this.space.top-this.space.bottom;return Math.max(t,0)}}]),l}();Object.assign(gi.prototype,pi);function yi(t,e,i,n,s,r,o,h){Rt.call(this,t);var a=u(e);if(null===e)return this;if("number"!==a)if("string"===a)e=Si[e];else if(bi(e)){var l;e=ki(l=e,"proportion",0),i=ki(l,"align",Ci),n=ki(l,"padding",0),s=ki(l,"expand",!1),r=ki(l,"key",void 0),o=ki(l,"index",void 0),t.isRexSizer||(h=0===this.orientation?ki(l,"minWidth",void 0):ki(l,"minHeight",void 0))}return"string"==typeof i&&(i=rt[i]),void 0===e&&(e=0),void 0===i&&(i=Ci),void 0===n&&(n=0),void 0===s&&(s=!1),t.isRexSizer||void 0!==h||(h=0===this.orientation?t._minWidth:t._minHeight),(l=this.getSizerConfig(t)).proportion=e,l.align=i,l.padding=Yt(n),l.expand=s,void 0===o||o>=this.sizerChildren.length?this.sizerChildren.push(t):this.sizerChildren.splice(o,0,t),!t.isRexSizer&&0<e&&(0===this.orientation?(t.minWidth=void 0===h?ht(t):h,t.minHeight=void 0):(t.minWidth=void 0,t.minHeight=void 0===h?at(t):h)),void 0!==r&&this.addChildrenMap(r,t),this}var mi=Phaser.GameObjects.Zone,bi=Phaser.Utils.Objects.IsPlainObject,ki=Phaser.Utils.Objects.GetValue,Ci=Phaser.Display.Align.CENTER,Si={min:0,full:-1},wi={add:yi,addSpace:function(t){return this.insertSpace(void 0,t),this},insertSpace:function(t,e){var i,n;return void 0===e&&(e=1),yi.call(this,(i=this.scene,(n=new mi(i,0,0,1,1)).isRexSpace=!0,n),{proportion:e,minWidth:0,minHeight:0,index:t}),this},insert:function(t,e,i,n,s,r,o){return yi.call(this,e,i,n,s,r,o,t),this}},xi=Phaser.Utils.Array.Remove,Oi=tt.prototype.remove,Pi=tt.prototype.clear,Ei=Phaser.Utils.Array.Remove,Ti={remove:function(t,e){return this.getParentSizer(t)!==this||(Ei(this.sizerChildren,t),function(t,e){return this.isBackground(t)&&xi(this.backgroundChildren,t),Oi.call(this,t,e),!e&&this.sizerEventsEnable&&(t.emit("sizer.remove",t,this),this.emit("remove",t,this)),this}.call(this,t,e)),this},removeAll:function(t){for(var e=this.sizerChildren.length-1;0<=e;e--)this.remove(this.sizerChildren[e],t);return this},clear:function(t){return this.sizerChildren.length=0,function(t){this.backgroundChildren&&(this.backgroundChildren.length=0);var e,i=!t&&this.sizerEventsEnable;if(i&&(e=this.getChildren([])),Pi.call(this,t),i)for(var n,s=0,r=e.length;s<r;s++)(n=e[s]).emit("sizer.remove",n,this),this.emit("remove",n,this);return this}.call(this,t),this}},Mi={getChildrenWidth:function(t){if(this.rexSizer.hidden)return 0;void 0===t&&(t=!0);var e,i,n,s=0,r=this.sizerChildren;if(0===this.orientation)for(var o=0,h=r.length;o<h;o++)(e=r[o]).rexSizer.hidden||(n=0===e.rexSizer.proportion||t&&0<e.rexSizer.proportion?this.getChildWidth(e):0,n+=(i=e.rexSizer.padding).left+i.right,0<o&&(n+=this.space.item),s+=n);else for(o=0,h=r.length;o<h;o++)(e=r[o]).hasOwnProperty("rexSizer")&&(e.rexSizer.hidden||(i=e.rexSizer.padding,n=this.getChildWidth(e)+i.left+i.right,s=Math.max(n,s)));return s+this.space.left+this.space.right},getChildrenHeight:function(t){if(this.rexSizer.hidden)return 0;void 0===t&&(t=!0);var e,i,n,s=0,r=this.sizerChildren;if(0===this.orientation)for(var o=0,h=r.length;o<h;o++)(e=r[o]).rexSizer.hidden||(i=e.rexSizer.padding,n=this.getChildHeight(e)+i.top+i.bottom,s=Math.max(n,s));else for(o=0,h=r.length;o<h;o++)(e=r[o]).hasOwnProperty("rexSizer")&&(e.rexSizer.hidden||(i=e.rexSizer.padding,n=0===e.rexSizer.proportion||t&&0<e.rexSizer.proportion?this.getChildHeight(e):0,n+=i.top+i.bottom,0<o&&(n+=this.space.item),s+=n));return s+this.space.top+this.space.bottom},getExpandedChildWidth:function(t,e){var i;void 0===e&&(e=this.width);var n=t.rexSizer,s=n.padding;0===this.orientation?0<n.proportion&&0<this.proportionLength&&(i=n.proportion*this.proportionLength):n.expand&&(i=e-this.space.left-this.space.right-s.left-s.right);return i},getExpandedChildHeight:function(t,e){var i;void 0===e&&(e=this.height);var n=t.rexSizer,s=n.padding;0===this.orientation?n.expand&&(i=e-this.space.top-this.space.bottom-s.top-s.bottom):0<n.proportion&&0<this.proportionLength&&(i=n.proportion*this.proportionLength);return i},getChildrenSizers:function(t){void 0===t&&(t=[]);for(var e,i=this.sizerChildren,n=0,s=i.length;n<s;n++)(e=i[n]).isRexSizer&&t.push(e);return t},preLayout:function(){return this._childrenProportion=void 0,this.proportionLength=void 0,jt.call(this),this},layoutChildren:function(){for(var t,e,i,n,s,r,o,h,a,l,u,c=this.sizerChildren,d=this.innerLeft,v=this.innerTop,p=this.innerWidth,f=this.innerHeight,g=d,y=v,m=0,b=c.length;m<b;m++)(t=c[m]).rexSizer.hidden||(i=(e=t.rexSizer).padding,pe.call(this,t),h=this.getExpandedChildWidth(t),a=this.getExpandedChildHeight(t),t.isRexSizer?(t.runLayout(this,h,a),u=this,(l=t).width<l.childrenWidth&&console.warn("Layout width error: Parent=".concat(u.constructor.name,", Child=").concat(l.constructor.name)),l.height<l.childrenHeight&&console.warn("Layout height error: Parent=".concat(u.constructor.name,", Child=").concat(l.constructor.name))):ve(t,h,a),void 0===h&&(h=ht(t)),void 0===a&&(a=at(t)),o=0===this.orientation?(n=g+i.left,r=0===e.proportion||0===this.proportionLength?h:e.proportion*this.proportionLength,s=y+i.top,f-i.top-i.bottom):(n=g+i.left,r=p-i.left-i.right,s=y+i.top,0===e.proportion||0===this.proportionLength?a:e.proportion*this.proportionLength),fe.call(this,t,n,s,r,o,e.align),0===this.orientation?g+=r+i.left+i.right+this.space.item:y+=o+i.top+i.bottom+this.space.item)},resolveWidth:function(t){t=It.call(this,t);if(void 0===this.proportionLength&&0===this.orientation){var e=t-this.childrenWidth;0<e?(e=t-this.getChildrenWidth(!1),this.proportionLength=e/this.childrenProportion):this.proportionLength=0}return t},resolveHeight:function(t,e){e=At.call(this,t,e);if(void 0===this.proportionLength&&1===this.orientation){var i=e-this.childrenHeight;0<i?(i=e-this.getChildrenHeight(!1),this.proportionLength=i/this.childrenProportion):this.proportionLength=0}return e}};Object.assign(Mi,wi,Ti);var Di={x:0,h:0,horizontal:0,"left-to-right":0,y:1,v:1,vertical:1,"top-to-bottom":1},_i=Phaser.Utils.Objects.IsPlainObject,Yi=Phaser.Utils.Objects.GetValue,Ri=function(){i(l,gi);var a=C(l);function l(t,e,i,n,s,r,o){var h;return y(this,l),_i(e)?(e=Yi(o=e,"x",0),i=Yi(o,"y",0),n=Yi(o,"width",void 0),s=Yi(o,"height",void 0),r=Yi(o,"orientation",0)):_i(n)?(n=Yi(o=n,"width",void 0),s=Yi(o,"height",void 0),r=Yi(o,"orientation",0)):_i(r)&&(r=Yi(o=r,"orientation",0)),void 0===r&&(r=0),(h=a.call(this,t,e,i,n,s,o)).type="rexSizer",h.sizerChildren=[],h.setOrientation(r),h.setItemSpacing(Yi(o,"space.item",0)),h.addChildrenMap("items",h.sizerChildren),h}return m(l,[{key:"setOrientation",value:function(t){var e;return this.orientation=("string"==typeof(e=t)&&(e=Di[e]),e),this}},{key:"setItemSpacing",value:function(t){return this.space.item=t,this}},{key:"childrenProportion",get:function(){return void 0===this._childrenProportion&&(this._childrenProportion=function(){for(var t,e,i=0,n=this.sizerChildren,s=0,r=n.length;s<r;s++)(t=n[s]).rexSizer.hidden||0<(e=t.rexSizer.proportion)&&(i+=e);return i}.call(this)),this._childrenProportion}}]),l}();Object.assign(Ri.prototype,Mi);function Xi(t){var e=Hi(t,"scrollMode",0);return"string"==typeof e&&(e=ji[e]),e}function Vi(t,e,i){var n,s,r;return t.y===e.y?(n=Math.min(t.x,e.x),s=Math.max(t.x,e.x),r=Li(i.x,n,s)):t.x===e.x&&(n=Math.min(t.y,e.y),s=Math.max(t.y,e.y),r=Li(i.y,n,s)),r}function zi(t,e,i){this.enable&&(Wi.x=e,Wi.y=i,this.value=Vi(this.getStartPoint(),this.getEndPoint(),Wi))}function Ii(t){if(this.enable&&t.isDown){Ni.x=t.worldX,Ni.y=t.worldY;var e=Vi(this.getStartPoint(),this.getEndPoint(),Ni);this.stopEaseValue(),0===this.easeValueDuration||Math.abs(this.value-e)<.1?this.value=e:this.easeValueTo(e)}}function Ai(t,e){void 0===e&&(e=Fi);var i=this.childrenMap.thumb,n=i.x,s=i.y;return _t(i,this.innerLeft,this.innerTop,this.innerWidth,this.innerHeight,t),e.x=i.x,e.y=i.y,i.x=n,i.y=s,e}var ji={v:0,vertical:0,h:1,horizontal:1},Hi=Phaser.Utils.Objects.GetValue,Li=Phaser.Math.Percent,Wi={},Ni={},Fi={},Gi=Phaser.Display.Align.LEFT_CENTER,Bi=Phaser.Display.Align.TOP_CENTER,Ui={},Ji=Phaser.Display.Align.RIGHT_CENTER,Zi=Phaser.Display.Align.BOTTOM_CENTER,Ki={},qi=Phaser.Math.Linear,$i={},Qi=Phaser.Display.Align.LEFT_CENTER,tn=Phaser.Display.Align.TOP_CENTER,en=Phaser.Utils.Objects.GetValue,nn=Phaser.Math.Linear,sn=function(){i(s,Re);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,e)).resetFromJSON(),i.boot(),i}return m(s,[{key:"start",value:function(t){if(this.timer.isRunning)return this;var e=this.parent;this.propertyKey=en(t,"key","value");var i=e[this.propertyKey];return this.fromValue=en(t,"from",i),this.toValue=en(t,"to",i),this.setEase(en(t,"ease",this.ease)),this.setDuration(en(t,"duration",this.duration)),this.timer.setDuration(this.duration),e[this.propertyKey]=this.fromValue,S(b(s.prototype),"start",this).call(this),this}},{key:"updateGameObject",value:function(t,e){var i=e.t;i=this.easeFn(i),t[this.propertyKey]=nn(this.fromValue,this.toValue,i)}}]),s}(),rn={setEaseValuePropName:function(t){return this.easeValuePropName=t,this},setEaseValueDuration:function(t){return this.easeValueDuration=t,this},setEaseValueFunction:function(t){return this.easeFunction=t,this},stopEaseValue:function(){return this.easeValueTask&&this.easeValueTask.stop(),this},easeValueTo:function(t,e,i){return null==t||(void 0!==e&&(t=Percent(t,e,i)),void 0===this.easeValueTask&&(this.easeValueTask=new sn(this,{eventEmitter:null})),this.easeValueTask.restart({key:this.easeValuePropName,to:t,duration:this.easeValueDuration,ease:this.easeFunction})),this}},on=Phaser.Utils.Objects.GetValue,hn=Phaser.Math.Clamp,an=Phaser.Math.Linear,ln=Phaser.Math.Percent,un=Phaser.Math.Snap.To,cn=function(){i(c,Ri);var u=C(c);function c(t,e){var i;y(this,c),(i=u.call(this,t,e)).type="rexSlider",i.eventEmitter=on(e,"eventEmitter",k(i));var n=on(e,"background",void 0),s=on(e,"track",void 0),r=on(e,"indicator",void 0),o=on(e,"thumb",void 0);n&&i.addBackground(n),s&&i.add(s,{proportion:1,expand:!0,minWidth:0,minHeight:0}),r&&i.pin(r),o&&i.pin(o);var h=on(e,"input",0);switch("string"==typeof h&&(h=dn[h]),h){case 0:o&&(o.setInteractive(),i.scene.input.setDraggable(o),o.on("drag",zi,k(i)));break;case 1:i.setInteractive().on("pointerdown",Ii,k(i)).on("pointermove",Ii,k(i))}i.addChildrenMap("background",n),i.addChildrenMap("track",s),i.addChildrenMap("indicator",r),i.addChildrenMap("thumb",o);var a=on(e,"valuechangeCallback",null);if(null!==a){var l=on(e,"valuechangeCallbackScope",void 0);i.eventEmitter.on("valuechange",a,l)}return i.setEnable(on(e,"enable",void 0)),i.setGap(on(e,"gap",void 0)),i.setValue(on(e,"value",0),on(e,"min",void 0),on(e,"max",void 0)),i.setEaseValuePropName("value").setEaseValueDuration(on(e,"easeValue.duration",0)).setEaseValueFunction(on(e,"easeValue.ease","Linear")),i}return m(c,[{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"setGap",value:function(t){return this.gap=t,this}},{key:"value",get:function(){return this._value},set:function(t){void 0!==this.gap&&(t=un(t,this.gap));var e=this._value;this._value=hn(t,0,1),e!==this._value&&(this.updateThumb(this._value),this.updateIndicator(this._value),this.eventEmitter.emit("valuechange",this._value,e,this.eventEmitter))}},{key:"setValue",value:function(t,e,i){return null==t||(void 0!==e&&(t=ln(t,e,i)),this.value=t),this}},{key:"addValue",value:function(t,e,i){return void 0!==e&&(t=ln(t,e,i)),this.value+=t,this}},{key:"getValue",value:function(t,e){var i=this.value;return void 0!==t&&(i=an(t,e,i)),i}},{key:"runLayout",value:function(t,e,i){return this.ignoreLayout||(S(b(c.prototype),"runLayout",this).call(this,t,e,i),this.updateThumb(),this.updateIndicator()),this}}]),c}(),dn={pan:0,drag:0,click:1,none:-1},vn={getStartPoint:function(t){if(void 0===t&&(t=Ui),this.childrenMap.thumb){var e=0===this.orientation?Gi:Bi;Ai.call(this,e,t)}else 0===this.orientation?(t.x=this.innerLeft+1,t.y=this.centerY):(t.x=this.centerX,t.y=this.innerTop+1);return t},getEndPoint:function(t){if(void 0===t&&(t=Ki),this.childrenMap.thumb){var e=0===this.orientation?Ji:Zi;Ai.call(this,e,t)}else 0===this.orientation?(t.x=this.innerRight-1,t.y=this.centerY):(t.x=this.centerX,t.y=this.innerBottom-1);return t},updateThumb:function(t){var e,i,n,s,r=this.childrenMap.thumb;return void 0===r||(void 0===t&&(t=this.value),e=t,i=this.getStartPoint(),n=this.getEndPoint(),void 0===(s=r)&&(s=$i),s.x=qi(i.x,n.x,e),s.y=qi(i.y,n.y,e),this.resetChildPositionState(r)),this},updateIndicator:function(t){var e,i,n=this.childrenMap.indicator;if(void 0===n)return this;void 0===t&&(t=this.value);var s=this.childrenMap.thumb;if(s)if(0===this.orientation){var r=ht(s);e=s.x-r*s.originX+r-this.left}else{var o=at(s);i=s.y-o*s.originY+o-this.top}else 0===this.orientation?e=this.width*t:i=this.height*t;ve(n,e,i);var h=0===this.orientation?Qi:tn;Dt(n,this,h),this.resetChildPositionState(n)}};Object.assign(cn.prototype,vn,rn);function pn(t,e,i){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return t[e];if(-1===e.indexOf("."))return i;for(var n=e.split("."),s=t,r=i,o=0;o<n.length;o++){if(!s.hasOwnProperty(n[o])){r=i;break}r=s[n[o]],s=s[n[o]]}return r}return i}var fn=function(){function o(t){y(this,o);var e=pn(t,"states",void 0);e&&this.addStates(e);var i=pn(t,"extend",void 0);if(i)for(var n in i)this.hasOwnProperty(n)&&void 0!==this[n]||(this[n]=i[n]);var s=pn(t,"eventEmitter",void 0),r=pn(t,"EventEmitterClass",void 0);this.setEventEmitter(s,r),this._stateLock=!1,this.resetFromJSON(t)}return m(o,[{key:"shutdown",value:function(){this.destroyEventEmitter()}},{key:"destroy",value:function(){this.shutdown()}},{key:"resetFromJSON",value:function(t){this.setEnable(pn(t,"enable",!0)),this.start(pn(t,"start",void 0));var e=pn(t,"init",void 0);return e&&e.call(this),this}},{key:"toJSON",value:function(){return{curState:this.state,prevState:this.prevState,enable:this.enable,start:this._start}}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"toggleEnable",value:function(){return this.setEnable(!this.enable),this}},{key:"state",get:function(){return this._state},set:function(t){if(this.enable&&!this._stateLock&&this._state!==t){if(this._prevState=this._state,this._state=t,this._stateLock=!0,this.emit("statechange",this),null!=this._prevState){var e="exit_"+this._prevState,i=this[e];i&&i.call(this),this.emit(e,this)}if(this._stateLock=!1,null!=this._state){var n="enter_"+this._state,s=this[n];s&&s.call(this),this.emit(n,this)}}}},{key:"prevState",get:function(){return this._prevState}},{key:"start",value:function(t){return this._start=t,this._prevState=void 0,this._state=t,this}},{key:"goto",value:function(t){return null!=t&&(this.state=t),this}},{key:"next",value:function(){var t,e=this["next_"+this.state];return e&&(t="string"==typeof e?e:e.call(this)),this.goto(t),this}},{key:"addState",value:function(t,e){var i=pn(e,"next",void 0);i&&(this["next_"+t]=i);var n=pn(e,"exit",void 0);n&&(this["exit_"+t]=n);var s=pn(e,"enter",void 0);return s&&(this["enter_"+t]=s),this}},{key:"addStates",value:function(t){for(var e in t)this.addState(e,t[e]);return this}},{key:"update",value:function(t,e,i){void 0===i&&(i="update");var n=this[i+"_"+this.state];n&&n.call(this,t,e)}},{key:"preupdate",value:function(t,e){this.update(t,e,"preupdate")}},{key:"postupdate",value:function(t,e){this.update(t,e,"postupdate")}}]),o}();Object.assign(fn.prototype,te);var gn=function(){i(s,fn);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,e)).parent=t,i.init(),i}return m(s,[{key:"init",value:function(){this.start("IDLE")}},{key:"next_IDLE",value:function(){var t,e=this.parent;return e.dragState.isDown&&(t=0===e.dragThreshold?"DRAG":"DRAGBEGIN"),t}},{key:"update_IDLE",value:function(){this.next()}},{key:"next_DRAGBEGIN",value:function(){var t=this.parent,e=t.dragState;return e.isDown?e.pointer.getDistance()>=t.dragThreshold?"DRAG":"DRAGBEGIN":"IDLE"}},{key:"update_DRAGBEGIN",value:function(){this.next()}},{key:"next_DRAG",value:function(){var t,e=this.parent;return e.dragState.isUp&&(t=e.outOfBounds?"BACK":e.slidingEnable?"SLIDE":"IDLE"),t}},{key:"update_DRAG",value:function(){var t=this.parent;t.dragState.justMoved&&t.dragging(),this.next()}},{key:"next_SLIDE",value:function(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isSliding||(t="IDLE"),t}},{key:"enter_SLIDE",value:function(){this.parent.onSliding()}},{key:"exit_SLIDE",value:function(){this.parent.stop()}},{key:"update_SLIDE",value:function(t,e){this.parent.sliding(t,e),this.next()}},{key:"next_BACK",value:function(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isPullBack||(t="IDLE"),t}},{key:"enter_BACK",value:function(){this.parent.onPullBack()}},{key:"exit_BACK",value:function(){this.parent.stop()}},{key:"update_BACK",value:function(t,e){this.parent.pullBack(t,e),this.next()}}]),s}(),yn=Phaser.Utils.Objects.GetValue,mn=Phaser.Math.Distance.Between,bn=function(){i(s,ne);var n=C(s);function s(t,e){var i;return y(this,s),(i=n.call(this,t,e))._enable=void 0,t.setInteractive(yn(e,"inputConfig",void 0)),i.resetFromJSON(e),i.boot(),i}return m(s,[{key:"resetFromJSON",value:function(t){return this.pointer=void 0,this.isInTouched=!1,this.holdStartTime=void 0,this.x=void 0,this.y=void 0,this.preX=void 0,this.preY=void 0,this.localX=void 0,this.localY=void 0,this.justMoved=!1,this.setEnable(yn(t,"enable",!0)),this.holdThreshold=yn(t,"holdThreshold",50),this}},{key:"boot",value:function(){this.parent.on("pointerdown",this.onPointIn,this),this.parent.on("pointerup",this.onPointOut,this),this.parent.on("pointerout",this.onPointOut,this),this.parent.on("pointermove",this.onPointerMove,this),this.scene.events.on("preupdate",this.preupdate,this)}},{key:"shutdown",value:function(t){this.isShutdown||(this.scene.events.off("preupdate",this.preupdate,this),this.pointer=void 0,S(b(s.prototype),"shutdown",this).call(this,t))}},{key:"enable",get:function(){return this._enable},set:function(t){this._enable!==t&&(t||(this.isInTouched=!1,this.pointer=void 0),this._enable=t)}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"toggleEnable",value:function(){return this.setEnable(!this.enable),this}},{key:"isDown",get:function(){return this.pointer&&this.pointer.isDown}},{key:"isUp",get:function(){return!this.isDown}},{key:"dx",get:function(){return this.x-this.preX}},{key:"dy",get:function(){return this.y-this.preY}},{key:"dt",get:function(){return this.scene.sys.game.loop.delta}},{key:"speed",get:function(){return this.x===this.preX&&this.y===this.preY?0:mn(this.preX,this.preY,this.x,this.y)/(.001*this.dt)}},{key:"speedX",get:function(){return this.dx/(.001*this.dt)}},{key:"speedY",get:function(){return this.dy/(.001*this.dt)}},{key:"onPointIn",value:function(t,e,i){this.enable&&t.isDown&&void 0===this.pointer&&(this.pointer=t,this.localX=e,this.localY=i)}},{key:"onPointOut",value:function(t){this.enable&&this.pointer===t&&(this.pointer=void 0)}},{key:"onPointerMove",value:function(t,e,i){this.enable&&t.isDown&&this.pointer===t&&(this.localX=e,this.localY=i)}},{key:"preupdate",value:function(t){if(this.enable){var e=this.pointer;this.justMoved=!1,e&&!this.isInTouched?(this.x=e.x,this.y=e.y,this.preX=e.x,this.preY=e.y,this.isInTouched=!0,this.holdStartTime=void 0,this.emit("touchstart",e,this.localX,this.localY)):e&&this.isInTouched?this.x===e.x&&this.y===e.y?void 0===this.holdStartTime?this.holdStartTime=t:t-this.holdStartTime>this.holdThreshold&&(this.preX=this.x,this.preY=this.y):(this.preX=this.x,this.preY=this.y,this.x=e.x,this.y=e.y,this.holdStartTime=void 0,this.justMoved=!0,this.emit("touchmove",e,this.localX,this.localY)):!e&&this.isInTouched&&(this.isInTouched=!1,this.holdStartTime=void 0,this.emit("touchend",e))}}}]),s}(),kn=Phaser.Utils.Objects.GetValue,Cn=function(){function e(t){y(this,e),this.resetFromJSON(t)}return m(e,[{key:"resetFromJSON",value:function(t){return this.setValue(kn(t,"value",0)),this.setSpeed(kn(t,"speed",0)),this.setAcceleration(kn(t,"acceleration",0)),this}},{key:"reset",value:function(){this.setValue(0),this.setSpeed(0),this.setAcceleration(0)}},{key:"setValue",value:function(t){return this.value=t,this}},{key:"setSpeed",value:function(t){return this.speed=t,this}},{key:"setAcceleration",value:function(t){return this.acceleration=t,this}},{key:"updateSpeed",value:function(t){return 0!==this.acceleration&&(this.speed+=this.acceleration*t,this.speed<0&&(this.speed=0)),this}},{key:"getDeltaValue",value:function(t){return this.updateSpeed(t),this.speed<=0?0:this.speed*t}},{key:"update",value:function(t){return this.updateSpeed(t),0<this.speed&&(this.value+=this.getDeltaValue(t)),this}},{key:"isMoving",get:function(){return 0<this.speed}}]),e}(),Sn=function(){function t(){y(this,t),this.value,this.dir,this.movement=new Cn}return m(t,[{key:"init",value:function(t,e,i,n,s){return this.value=t,this.end=s,this.dir=void 0!==s?t<s:e,this.movement.setSpeed(i).setAcceleration(-n),this}},{key:"stop",value:function(){this.movement.reset()}},{key:"update",value:function(t){var e=this.movement.getDeltaValue(t);return this.dir||(e=-e),void 0===this.end?this.value+=e:0===e?this.value=this.end:(this.value+=e,this.dir?this.value>this.end&&(this.value=this.end):this.value<this.end&&(this.value=this.end)),this}},{key:"isMoving",get:function(){return this.movement.isMoving}}]),t}(),wn=Phaser.Utils.Objects.GetValue,xn=Phaser.Math.Clamp,On=function(){i(l,ne);var a=C(l);function l(t,e){var i;y(this,l),i=a.call(this,t,e);var n=wn(e,"enable",!0),s={enable:n,eventEmitter:!1};i._state=new gn(k(i),s);var r={inputConfig:wn(e,"inputConfig",void 0),enable:n,eventEmitter:!1};i.dragState=new bn(t,r),i._enable=void 0,i._value=void 0,i._slowDown=new Sn;var o=wn(e,"valuechangeCallback",null);if(null!==o){var h=wn(e,"valuechangeCallbackScope",void 0);i.on("valuechange",o,h)}if(null!==(o=wn(e,"overmaxCallback",null))){h=wn(e,"overmaxCallbackScope",void 0);i.on("overmax",o,h)}if(null!==(o=wn(e,"overminCallback",null))){h=wn(e,"overminCallbackScope",void 0);i.on("overmin",o,h)}return i.resetFromJSON(e),i.boot(),i}return m(l,[{key:"resetFromJSON",value:function(t){this.setOrientationMode(wn(t,"orientation",0)),this.setDragThreshold(wn(t,"threshold",10)),this.setSlidingDeceleration(wn(t,"slidingDeceleration",5e3)),this.setBackDeceleration(wn(t,"backDeceleration",2e3));var e=wn(t,"bounds",void 0);return e?this.setBounds(e):this.setBounds(wn(t,"max",0),wn(t,"min",0)),this.setValue(wn(t,"value",this.maxValue||0)),this.setEnable(wn(t,"enable",!0)),this}},{key:"boot",value:function(){this.scene.events.on("update",this._state.update,this._state)}},{key:"shutdown",value:function(t){this.isShutdown||(this.scene.events.off("update",this._state.update,this._state),this._state.destroy(t),this.dragState.destroy(t),this._state=void 0,this.dragState=void 0,S(b(l.prototype),"shutdown",this).call(this,t))}},{key:"enable",get:function(){return this._enable},set:function(t){if(this._enable!==t)return this._enable=t,this._state.setEnable(t),this.dragState.setEnable(t),this}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"toggleEnable",value:function(){return this.setEnable(!this.enable),this}},{key:"setOrientationMode",value:function(t){return"string"==typeof t&&(t=Pn[t]),this.orientationMode=t,this}},{key:"setDragThreshold",value:function(t){return this.dragThreshold=t,this}},{key:"setSlidingDeceleration",value:function(t){return this.slidingDeceleration=t,this}},{key:"setBackDeceleration",value:function(t){return this.backDeceleration=t,this}},{key:"setBounds",value:function(t,e){if(Array.isArray(t)){var i=t;t=i[0],e=i[1]}return t<e?(this.minValue=t,this.maxValue=e):(this.minValue=e,this.maxValue=t),this}},{key:"value",get:function(){return this._value},set:function(t){if(t!==this._value){var e=this._value,i=this.overMax(t),n=this.overMin(t);i&&this.emit("overmax",t,e),n&&this.emit("overmin",t,e),this.backEnable||(i&&(t=this.maxValue),n&&(t=this.minValue)),this._value=t,this.emit("valuechange",t,e)}}},{key:"setValue",value:function(t,e){return void 0===e&&(e=!1),e&&(t=xn(t,this.minValue,this.maxValue)),this.value=t,this}},{key:"addValue",value:function(t,e){return this.setValue(this.value+t,e),this}},{key:"state",get:function(){return this._state.state}},{key:"isDragging",get:function(){return this.dragState.isInTouched}},{key:"outOfMaxBound",get:function(){return this.overMax(this.value)}},{key:"outOfMinBound",get:function(){return this.overMin(this.value)}},{key:"outOfBounds",get:function(){return this.outOfMinBound||this.outOfMaxBound}},{key:"overMax",value:function(t){return null!=this.maxValue&&t>this.maxValue}},{key:"overMin",value:function(t){return null!=this.minValue&&t<this.minValue}},{key:"backEnable",get:function(){return"number"==typeof this.backDeceleration}},{key:"isPullBack",get:function(){return this._slowDown.isMoving}},{key:"slidingEnable",get:function(){return"number"==typeof this.slidingDeceleration}},{key:"isSliding",get:function(){return this._slowDown.isMoving}},{key:"dragDelta",get:function(){return 0===this.orientationMode?this.dragState.dy:1===this.orientationMode?this.dragState.dx:0}},{key:"dragSpeed",get:function(){return 0===this.orientationMode?this.dragState.speedY:1===this.orientationMode?this.dragState.speedX:0}},{key:"dragging",value:function(){this.value+=this.dragDelta}},{key:"onSliding",value:function(){var t=this.value,e=this.dragSpeed;if(0===e)return this._slowDown.stop(),void this._state.next();var i=this.slidingDeceleration;this._slowDown.init(t,0<e,Math.abs(e),i)}},{key:"sliding",value:function(t,e){e*=.001;var i=this._slowDown.update(e).value;this.overMax(i)?(this.value=this.maxValue,this._slowDown.stop()):this.overMin(i)?(this.value=this.minValue,this._slowDown.stop()):this.value=i}},{key:"onPullBack",value:function(){var t=this.value,e=this.outOfMinBound?this.minValue:this.maxValue,i=Math.abs(e-t),n=this.backDeceleration,s=Math.sqrt(2*n*i);this._slowDown.init(t,void 0,s,n,e)}},{key:"pullBack",value:function(t,e){e*=.001,this.value=this._slowDown.update(e).value,this._slowDown.isMoving||this._state.next()}},{key:"stop",value:function(){this._slowDown.stop()}}]),l}(),Pn={y:0,v:0,vertical:0,x:1,h:1,horizontal:1},En=Phaser.Utils.Objects.GetValue,Tn=function(){i(s,ne);var n=C(s);function s(t,e){var i;(y(this,s),(i=n.call(this,t,e)).parent!==i.scene?i.focusMode=En(e,"focus",!1):i.focusMode=!1,i.setSpeed(En(e,"speed",.1)),i.setEnable(En(e,"enable",!0)),i.focusMode)?(t=i.parent).setInteractive(En(e,"inputConfig",void 0)).on("wheel",function(t,e,i,n,s){this.enable&&this.scroll(i)},k(i)):i.scene.input.on("wheel",i.onSceneScroll,k(i));return i}return m(s,[{key:"destroy",value:function(){this.focusMode||this.scene.input.off("wheel",this.onSceneScroll,this)}},{key:"onSceneScroll",value:function(t,e,i,n){this.enable&&this.scroll(n)}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"setSpeed",value:function(t){return this.speed=t,this}},{key:"scroll",value:function(t){t*=this.speed,this.emit("scroll",t,this.parent,this)}}]),s}(),Mn=Phaser.Utils.Objects.GetValue,Dn={right:0,left:1,bottom:0,top:1},_n=Phaser.Utils.Objects.GetValue,Yn=Phaser.Math.Clamp,Rn=function(){i(p,Ri);var v=C(p);function p(t,e){var i;y(this,p),void 0===e&&(e={});var n=Xi(e);e.orientation=0===n?1:0,(i=v.call(this,t,e)).type=_n(e,"type","rexScrollable");var s=_n(e,"background",void 0),r=function(t){var e,i=this.scene,n=Xi(t),s=new Ri(i,{orientation:n}),r=Mn(t,"child.gameObject",void 0),o=Mn(t,"slider",void 0),h=Mn(o,"position",0);"string"==typeof h&&(h=Dn[h]);var a,l,u=0===h,c=Mn(t,"scroller",!0),d=Mn(t,"mouseWheelScroller",!1);if(r){var v=Mn(t,"space.child",0),p={};if(this.childMargin={},"number"!=typeof v){var f=v;0===n?(p.left=Mn(f,"left",0),p.right=Mn(f,"right",0),this.childMargin.top=Mn(f,"top",0),this.childMargin.bottom=Mn(f,"bottom",0)):(p.top=Mn(f,"top",0),p.bottom=Mn(f,"bottom",0),this.childMargin.top=Mn(f,"left",0),this.childMargin.bottom=Mn(f,"right",0))}else o&&(p=0===n?u?{right:v}:{left:v}:u?{bottom:v}:{top:v}),this.childMargin.top=0,this.childMargin.bottom=0;o&&(!0===o&&(o={}),o.orientation=0===s.orientation?1:0,e=new cn(i,o)),c&&(!0===c&&(c={}),c.orientation=n,a=new On(r,c)),d&&(l=new Tn(r,d)),e&&!u&&s.add(e,{proportion:0,align:"center",expand:!0});var g=Mn(t,"child.proportion",1),y=Mn(t,"child.expand",!0);s.add(r,{proportion:g,align:"center",padding:p,expand:y}),e&&u&&s.add(e,{proportion:0,align:"center",expand:!0})}return e&&e.on("valuechange",function(t){this.t=t,this.emit("scroll",this)},this),a&&a.on("valuechange",function(t){this.childOY=t,this.emit("scroll",this)},this),l&&l.on("scroll",function(t){this.addChildOY(-t,!0)},this),this.addChildrenMap("child",r),this.addChildrenMap("slider",e),this.addChildrenMap("scroller",a),this.addChildrenMap("mouseWheelScroller",l),s}.call(k(i),e),o=_n(e,"header",void 0),h=_n(e,"footer",void 0);if(s&&i.addBackground(s),o){var a=_n(e,"align.header","center"),l=_n(e,"space.header",0);c=0===n?{bottom:l}:{right:l};var u=_n(e,"expand.header",!0);i.add(o,0,a,c,u)}if(r&&i.add(r,1,"center",0,!0),h){a=_n(e,"align.footer","center");var c,d=_n(e,"space.footer",0);c=0===n?{top:d}:{left:d};u=_n(e,"expand.footer",!0);i.add(h,0,a,c,u)}return i.addChildrenMap("background",s),i.addChildrenMap("header",o),i.addChildrenMap("footer",h),i}return m(p,[{key:"runLayout",value:function(t,e,i){return this.ignoreLayout||(S(b(p.prototype),"runLayout",this).call(this,t,e,i),this.resizeController()),this}},{key:"t",get:function(){var t=this.childrenMap.child.t,e=this.childMargin;if(0!==e.top||0!==e.bottom){var i=this.childrenMap.child,n=i.topChildOY-i.bottomChildOY,s=n+e.top+e.bottom;t=(n*t+e.top)/s}return t},set:function(t){var e=this.childMargin;if(0!==e.top||0!==e.bottom){var i=this.childrenMap.child,n=i.topChildOY-i.bottomChildOY;t=((n+e.top+e.bottom)*t-e.top)/n}this.childrenMap.child.t=t,this.updateController()}},{key:"childOY",get:function(){return this.childrenMap.child.childOY},set:function(t){this.childrenMap.child.childOY=t,this.updateController()}},{key:"topChildOY",get:function(){return this.childrenMap.child.topChildOY+this.childMargin.top}},{key:"bottomChildOY",get:function(){return this.childrenMap.child.bottomChildOY-this.childMargin.bottom}},{key:"isOverflow",get:function(){var t=this.childrenMap.child;return t.topChildOY!==t.bottomChildOY}},{key:"setChildOY",value:function(t,e){return void 0===e&&(e=!1),e&&(t=Yn(t,this.bottomChildOY,this.topChildOY)),this.childOY=t,this}},{key:"addChildOY",value:function(t,e){return this.setChildOY(this.childOY+t,e),this}},{key:"setT",value:function(t,e){return void 0===e&&(e=!1),e&&(t=Yn(t,0,1)),this.t=t,this}},{key:"addT",value:function(t,e){return this.setT(this.t+t,e),this}},{key:"scrollToTop",value:function(){return this.t=0,this}},{key:"scrollToBottom",value:function(){return this.t=1,this}},{key:"sliderEnable",get:function(){var t=this.childrenMap.slider;return!!t&&t.enable},set:function(t){var e=this.childrenMap.slider;e&&e.setEnable(t)}},{key:"setSliderEnable",value:function(t){return void 0===t&&(t=!0),this.sliderEnable=t,this}},{key:"scrollerEnable",get:function(){var t=this.childrenMap.scroller;return!!t&&t.enable},set:function(t){var e=this.childrenMap.scroller;e&&e.setEnable(t)}},{key:"setScrollerEnable",value:function(t){return void 0===t&&(t=!0),this.scrollerEnable=t,this}},{key:"mouseWheelScrollerEnable",get:function(){var t=this.childrenMap.mouseWheelScroller;return!!t&&t.enable},set:function(t){var e=this.childrenMap.mouseWheelScrollerEnable;e&&e.setEnable(t)}},{key:"setMouseWheelScrollerEnable",value:function(t){return void 0===t&&(t=!0),this.mouseWheelScrollerEnable=t,this}}]),p}(),Xn={resizeController:function(){var t=this.topChildOY,e=this.bottomChildOY,i=this.childrenMap.scroller,n=this.childrenMap.slider;return i&&i.setBounds(e,t),n&&n.setEnable(e!==t),this.updateController(),this},updateController:function(){var t=this.childrenMap.scroller,e=this.childrenMap.slider;t&&t.setValue(this.childOY),e&&e.setValue(this.t)}};Object.assign(Rn.prototype,Xn);function Vn(t){if(Array.isArray(t))t.length=0;else for(var e in t)delete t[e]}var zn={enableData:function(){return void 0===this.data&&(this.data={}),this},getData:function(t,e){return this.enableData(),void 0===t?this.data:pn(this.data,t,e)},setData:function(t,e){if(this.enableData(),1===arguments.length){var i=t;for(t in i)this.data[t]=i[t]}else this.data[t]=e;return this},incData:function(t,e,i){return void 0===i&&(i=0),this.enableData(),this.setData(t,this.getData(t,i)+e),this},mulData:function(t,e,i){return void 0===i&&(i=0),this.enableData(),this.setData(t,this.getData(t,i)*e),this},clearData:function(){return this.data&&Vn(this.data),this},resetData:function(t){if(this.clearData(),t)for(var e in this.enableData(),t)this.data[e]=t[e];return this},cloneData:function(){return this.data?function(t,e){var i=Array.isArray(t);if(void 0===e?e=i?[]:{}:Vn(e),i){e.length=t.length;for(var n=0,s=t.length;n<s;n++)e[n]=t[n]}else for(var r in t)e[r]=t[r];return e}(this.data):{}}},In=function(){function i(t,e){y(this,i),this.container=null,this._deltaHeight=0,this.setParent(t)}return m(i,[{key:"setParent",value:function(t){this.parent=t,this.parentContainer=t.getParentContainer()}},{key:"destroy",value:function(t){void 0===t&&(t=!1),t||this.destroyContainer(),this.deltaHeight=0,this.data=void 0,this.container=null,this.parent=void 0,this.parentContainer=void 0}},{key:"table",get:function(){return this.parent}},{key:"scrollMode",get:function(){return this.parentContainer.scrollMode}},{key:"colIndx",get:function(){return this.parent.cellIndxeToColIndex(this.index)}},{key:"rowIndx",get:function(){return this.parent.cellIndxeToRowIndex(this.index)}},{key:"getContainer",value:function(){return this.container}},{key:"setContainer",value:function(t){return t?(this.container&&this.container.destroy(),this.container=t,this.parentContainer.add(t)):this.destroyContainer(),this}},{key:"destroyContainer",value:function(){return this.container&&(this.container.destroy(),this.container=null),this}},{key:"popContainer",value:function(){if(this.container){var t=this.container;return this.container=null,this.parentContainer.remove(t),t}return null}},{key:"setXY",value:function(t,e){return this.container&&this.parentContainer.setChildLocalPosition(this.container,t,e),this}},{key:"deltaHeight",get:function(){return this._deltaHeight},set:function(t){null==t&&(t=0);var e=this.parent;0===this._deltaHeight&&0!==t?e.nonZeroDeltaHeightCount++:0!==this._deltaHeight&&0===t&&e.nonZeroDeltaHeightCount--;var i=this._deltaHeight!==t;if(this._deltaHeight=t,i){var n=0===this.scrollMode?"cellheightchange":"cellwidthchange";this.parentContainer.emit(n,this,this.container,this.parentContainer)}}},{key:"deltaWidth",get:function(){return this.deltaHeight},set:function(t){this.deltaHeight=t}},{key:"setDeltaHeight",value:function(t){return this.deltaHeight=t,this}},{key:"setDeltaWidth",value:function(t){return this.deltaHeight=t,this}},{key:"height",get:function(){return 0===this.scrollMode?this.deltaHeight+this.parent.defaultCellHeight:this.parent.defaultCellWidth},set:function(t){1!==this.scrollMode&&this.setDeltaHeight(t-this.parent.defaultCellHeight)}},{key:"setHeight",value:function(t){return this.height=t,this}},{key:"width",get:function(){return 0===this.scrollMode?this.parent.defaultCellWidth:this.deltaHeight+this.parent.defaultCellHeight},set:function(t){0!==this.scrollMode&&this.setDeltaHeight(t-this.parent.defaultCellHeight)}},{key:"setWidth",value:function(t){return this.width=t,this}},{key:"scene",get:function(){return this.parentContainer.scene}}]),i}();Object.assign(In.prototype,zn);function An(t,e,i,n,s){switch(this.clear().fillStyle(16777215),this.shape){case 1:var r=Math.min(t,e)/2;this.fillCircle(-t*(n-.5),-e*(s-.5),r+i);break;default:this.fillRect(-t*n-i,-e*s-i,t+2*i,e+2*i)}}function jn(t){return t.hasOwnProperty("geometryMask")?t.geometryMask:t.bitmapMask}function Hn(t){if(this.emit("cellinvisible",t),this.cellContainersPool){var e=t.popContainer();e&&this.cellContainersPool.killAndHide(e)}t.destroyContainer()}function Ln(){var t=this.preVisibleCells,e=this.visibleCells;t.iterate(function(t){e.contains(t)||Hn.call(this,t)},this)}function Wn(t){var e,i=null;(e=t.getContainer())?(i=e,t.popContainer()):this.cellContainersPool&&null!==(i=this.cellContainersPool.getFirstDead())&&i.setActive(!0).setVisible(!0),this.emit("cellvisible",t,i,this),this.cellContainersPool&&((e=t.getContainer())?null===i?this.cellContainersPool.add(e):i!==e&&(this.cellContainersPool.add(e),this.cellContainersPool.killAndHide(i)):null!==i&&this.cellContainersPool.killAndHide(i))}function Nn(t,e){e-=this.y+this.topLeftY,t-=this.x+this.topLeftX;var i=this.tableOY-(0===this.scrollMode?e:t),n=this.tableOX-(0===this.scrollMode?t:e),s=this.table,r=s.heightToRowIndex(-i),o=s.widthToColIndex(-n),h=s.colRowToCellIndex(o,r);return null!==h&&this.isCellVisible(h)?h:null}var Fn=function(){function t(){y(this,t),this.items=[]}return m(t,[{key:"destroy",value:function(){this.clear(),this.items=void 0}},{key:"pop",value:function(){return 0<this.items.length?this.items.pop():null}},{key:"push",value:function(t){return this.items.push(t),this}},{key:"pushMultiple",value:function(t){return this.items.push.apply(this.items,t),t.length=0,this}},{key:"clear",value:function(){return this.items.length=0,this}}]),t}(),Gn=Phaser.Utils.Objects.GetValue,Bn=Phaser.Utils.Array.SpliceOne,Un=function(){function i(t,e){y(this,i),this.parent=t,this.cells=[],this.cellPool=new Fn,this.resetFromJSON(e)}return m(i,[{key:"resetFromJSON",value:function(t){return this.colCount=void 0,this._nonZeroDeltaHeightCount=0,this.resetTotalRowsHeight(),this.setDefaultCellHeight(Gn(t,"cellHeight",30)),this.setDefaultCellWidth(Gn(t,"cellWidth",30)),this.initCells(Gn(t,"cellsCount",0)),this.setColumnCount(Gn(t,"columns",1)),this}},{key:"destroy",value:function(){this.cellPool.destroy(),this.cells=void 0,this.parent=void 0}},{key:"nonZeroDeltaHeightCount",get:function(){return this._nonZeroDeltaHeightCount},set:function(t){this._nonZeroDeltaHeightCount!==t&&(this._nonZeroDeltaHeightCount=t,this.resetTotalRowsHeight())}},{key:"defaultCellHeightMode",get:function(){return 0===this.nonZeroDeltaHeightCount}},{key:"setDefaultCellHeight",value:function(t){return this.defaultCellHeight=t,this}},{key:"setDefaultCellWidth",value:function(t){return this.defaultCellWidth=t,this}},{key:"initCells",value:function(t){var e=this.cells;e.length=t;for(var i=0;i<t;i++)e[i]=null;return this}},{key:"insertNewCells",value:function(t,e){var i=this.cells;if(t===i.length){var n=t+e;i.legth=n;for(var s=t;s<n;s++)i[s]=null}else{var r,o=[];o.length=e;for(s=0;s<e;s++)o[s]=null;(r=this.cells).splice.apply(r,[t,0].concat(o))}return this.resetTotalRowsHeight(),this}},{key:"removeCells",value:function(t,e){for(var i=t+e,n=t;n<i;n++)this.freeCell(n);return i===this.cells.length?this.cells.length=t:(1===e?Bn(this.cells,t):this.cells.splice(t,e),this.buildCellIndex(t)),this.resetTotalRowsHeight(),this}},{key:"setColumnCount",value:function(t){return this.colCount=t,this.resetTotalRowsHeight(),this}},{key:"rowCount",get:function(){return Math.ceil(this.cells.length/this.colCount)}},{key:"cellsCount",get:function(){return this.cells.length}},{key:"isValidCellIdx",value:function(t){return 0<=t&&t<this.cells.length}},{key:"heightToRowIndex",value:function(t,e){if(this.defaultCellHeightMode){var i=t/this.defaultCellHeight;return i=e?Math.ceil(i):Math.floor(i)}var n,s=this.rowCount,r=t;for(i=0;;){if(n=0<=i&&i<s,!(0<(r-=this.getRowHeight(i))&&n)){if(0===r)return i;if(e){var o=i;(n=0<=(i+=1)&&i<s)||(i=o)}return i}i+=1}}},{key:"widthToColIndex",value:function(t,e){var i=t/this.defaultCellWidth;return i=e?Math.ceil(i):Math.floor(i)}},{key:"colRowToCellIndex",value:function(t,e){return t>=this.colCount?null:e*this.colCount+t}},{key:"rowIndexToHeight",value:function(t,e){if(this.defaultCellHeightMode)return(e-t+1)*this.defaultCellHeight;for(var i=0,n=t;n<=e;n++)i+=this.getRowHeight(n);return i}},{key:"colIndexToWidth",value:function(t,e){return(e-t+1)*this.defaultCellWidth}},{key:"getRowHeight",value:function(t){var e=this.colCount;if(e<=1)return this.getCellHeight(this.colRowToCellIndex(0,t));for(var i,n=0,s=0;s<e;s++)n<(i=this.getCellHeight(this.colRowToCellIndex(s,t)))&&(n=i);return n}},{key:"getColWidth",value:function(){return this.defaultCellWidth}},{key:"getCellHeight",value:function(t){if(!this.isValidCellIdx(t))return 0;var e;if(this.defaultCellHeightMode)e=this.defaultCellHeight;else{var i=this.getCell(t,!1),n=i?i.deltaHeight:0;e=this.defaultCellHeight+n}return e}},{key:"resetTotalRowsHeight",value:function(){this._totalRowsHeight=null}},{key:"totalRowsHeight",get:function(){return null===this._totalRowsHeight&&(this._totalRowsHeight=this.rowIndexToHeight(0,this.rowCount-1)),this._totalRowsHeight}},{key:"totalColumnWidth",get:function(){return this.colCount*this.defaultCellWidth}},{key:"cellIndxeToColIndex",value:function(t){return t%this.colCount}},{key:"cellIndxeToRowIndex",value:function(t){return Math.floor(t/this.colCount)}},{key:"getCell",value:function(t,e){if(!this.isValidCellIdx(t))return null;if(void 0===e&&(e=!0),null===this.cells[t]&&e){var i=this.newCell(t);this.cells[t]=i}return this.cells[t]}},{key:"newCell",value:function(t){var e=this.cellPool.pop();return null===e?e=new In(this):e.setParent(this),e.index=t,e}},{key:"buildCellIndex",value:function(t){void 0===t&&(t=0);for(var e,i=this.cells,n=t,s=i.length;n<s;n++)(e=i[n])&&(e.index=n);return this}},{key:"getParentContainer",value:function(){return this.parent}},{key:"freeCell",value:function(t){return"number"==typeof t&&(t=this.cells[t]),t&&(t.destroy(),this.cellPool.push(t)),this}}]),i}(),Jn=Phaser.GameObjects.Graphics,Zn=function(){i(r,Jn);var s=C(r);function r(t,e,i){var n;return y(this,r),void 0===e&&(e=0),"string"==typeof e&&(e=Kn[e]),void 0===i&&(i=0),(n=s.call(this,t.scene)).parent=t,n.shape=e,n.padding=i,n.setPosition().resize().setVisible(!1),n}return m(r,[{key:"destroy",value:function(){return this.parent=void 0,S(b(r.prototype),"destroy",this).call(this),this}},{key:"setPosition",value:function(t,e){var i=this.parent;return void 0===t&&(t=i.x),void 0===e&&(e=i.y),S(b(r.prototype),"setPosition",this).call(this,t,e),this}},{key:"resize",value:function(t,e,i){var n=this.parent;return void 0===t&&(t=n.width),void 0===e&&(e=n.height),void 0===i&&(i=this.padding),this.widthSave===t&&this.heightSave===e&&this.paddingSave===i||(this.widthSave=t,this.heightSave=e,this.paddingSave=i,this.originXSave=n.originX,this.originYSave=n.originY,An.call(this,t,e,i,n.originX,n.originY)),this}},{key:"setOrigin",value:function(t,e){void 0===e&&(e=t);var i=this.parent;return void 0===t&&(t=i.originX),void 0===e&&(e=i.originY),this.originXSave===t&&this.originYSave===e||(this.originXSave=t,this.originYSave=e,An.call(this,this.widthSave,this.heightSave,this.paddingSave,t,e)),this}}]),r}(),Kn={rectangle:0,circle:1},qn=Phaser.Geom.Intersects.RectangleToRectangle,$n=Phaser.Geom.Rectangle.Overlaps,Qn=function(t){for(;;){var e=t.rexContainer;if(e){if(e.visible){var i=e.parent;if(i){t=i;continue}return!0}return!1}return t.visible}},ts=function(t,e){var i=0,n=e.top,s=e.bottom,r=e.left,o=e.right;return i+=t.contains(r,n)?1:0,i+=t.contains(r,s)?1:0,i+=t.contains(o,n)?1:0,i+=t.contains(o,s)?1:0},es=function(t,e){t.setChildMaskVisible(e,!0),e.clearMask&&e.clearMask()},is=function(t,e,i){t.setChildMaskVisible(e,!0),e.setMask&&e.setMask(i)},ns=function(t,e){t.setChildMaskVisible(e,!1),e.clearMask&&e.clearMask()},ss=function(t){var e=0===this.scrollMode?this.topLeftX:this.topLeftY;return this.tableOX+this.table.colIndexToWidth(0,t-1)+e},rs=function(t){var e=0===this.scrollMode?this.topLeftY:this.topLeftX;return this.tableOY+this.table.rowIndexToHeight(0,t-1)+e},os=function(){var t=this.preVisibleCells;this.preVisibleCells=this.visibleCells,this.visibleCells=t,this.visibleCells.clear()},hs=Phaser.Math.Clamp,as={setTableOY:function(t){var e=this.table,i=this.topTableOY,n=this.bottomTableOY,s=t>this.topTableOY,r=t<this.bottomTableOY;this.clampTableOXY&&(e.rowCount<e.heightToRowIndex(this.instHeight,!0)?t=0:s?t=i:r&&(t=n));return this._tableOY!==t&&(this._tableOY=t),s&&(this.execeedTopState||this.emit("execeedtop",this,t,i)),this.execeedTopState=s,r&&(this.execeedBottomState||this.emit("execeedbottom",this,t,n)),this.execeedBottomState=r,this},setTableOX:function(t){var e=this.table,i=this.leftTableOX,n=this.rightTableOX,s=t>this.leftTableOX,r=t<this.rightTableOX;this.clampTableOXY&&(e.colCount<e.widthToColIndex(this.instWidth,!0)?t=0:s?t=i:r&&(t=n));return this._tableOX!==t&&(this._tableOX=t),s&&(this.execeedLeftState||this.emit("execeedleft",this,t,i)),this.execeedLeftState=s,r&&(this.execeedRightState||this.emit("execeedright",this,t,n)),this.execeedRightState=r,this},maskCells:function(){if(!this.cellsMask)return this;if(!this.maskCellsFlag)return this;if(0===this.alpha||!this.visible)return this;for(var t,e=[],i=this.visibleCells.entries,n=0,s=i.length;n<s;n++)(t=i[n].getContainer())&&(t.hasOwnProperty("isRexContainerLite")?t.getAllChildren(e):e.push(t));return function(t,e,i){if(e){void 0===i&&(i=t.getAllChildren());for(var n,s,r=t.getBounds(),o=jn(e),h=0,a=i.length;h<a;h++)if(!(n=i[h]).hasOwnProperty("isRexContainerLite")&&n!==o&&Qn(n))if(n.getBounds)switch(s=n.getBounds(s),ts(r,s)){case 4:es(t,n);break;case 0:qn(r,s)||$n(r,s)?is(t,n,e):ns(t,n);break;default:is(t,n,e)}else is(t,n,e)}}(this,this.cellsMask,e),0===this.maskUpdateMode&&(this.maskCellsFlag=!1),this},updateTable:function(t){return void 0===t&&(t=!1),t&&(os.call(this),Ln.call(this)),os.call(this),function(){if(0!==this.cellsCount){var t=this.table,e=t.heightToRowIndex(-this.tableOY);e<=0&&(e=0);var i=e,n=t.widthToColIndex(-this.tableOX);n<=0&&(n=0);for(var s=n,r=t.colRowToCellIndex(s,i),o=this.bottomBound,h=this.rightBound,a=t.cellsCount-1,l=t.colCount-1,u=ss.call(this,s),c=u,d=rs.call(this,i);d<o&&r<=a;){if(this.table.isValidCellIdx(r)){var v=t.getCell(r,!0);this.visibleCells.set(v),this.preVisibleCells.contains(v)||Wn.call(this,v),0===this.scrollMode?v.setXY(c,d):v.setXY(d,c)}c<h&&s<l?(c+=t.getColWidth(s),s+=1):(c=u,d+=t.getRowHeight(i),s=n,i+=1),r=t.colRowToCellIndex(s,i)}}}.call(this),Ln.call(this),this.maskCellsFlag=!0,this},isCellVisible:function(t){var e=this.table.getCell(t,!1);return e&&this.visibleCells.contains(e)},pointToCellIndex:Nn,pointToCellContainer:function(t,e){var i=Nn.call(this,t,e);if(null!==i)return this.getCellContainer(i)},eachVisibleCell:function(t,e){return this.visibleCells.each(t,e),this},iterateVisibleCell:function(t,e){return this.visibleCells.iterate(t,e),this},eachCell:function(t,e){return this.table.cells.slice().forEach(t,e),this},iterateCell:function(t,e){return this.table.cells.forEach(t,e),this},setCellsCount:function(t){var e=this.cellsCount;return e===t||(t<e?this.removeCells(t,e-t):this.insertNewCells(e,t-e)),this},insertNewCells:function(t,e){return"object"===u(t)&&(t=t.index),void 0===e&&(e=1),e<=0||(t=hs(t,0,this.cellsCount),this.table.insertNewCells(t,e)),this},removeCells:function(t,e){if("object"===u(t)&&(t=t.index),void 0===e&&(e=1),t<0&&(e+=t,t=0),e<=0)return this;if(t>this.cellsCount)return this;for(var i,n=t,s=t+e;n<s;n++)(i=this.getCell(n,!1))&&(this.visibleCells.contains(i)&&(Hn.call(this,i),this.visibleCells.delete(i)),this.preVisibleCells.delete(i));return this.table.removeCells(t,e),this},setColumnCount:function(t){return this.table.colCount===t||this.table.setColumnCount(t),this},setGridSize:function(t,e){return this.setCellsCount(t*e),this.table.setColumnCount(t),this},updateVisibleCell:function(t){var e=this.table.getCell(t,!1);return e&&e.container&&Wn.call(this,e),this}},ls=Phaser.GameObjects.Group;Phaser.GameObjects.Components;var us=Phaser.Structs.Set,cs=Phaser.Utils.Objects.GetValue,ds=function(){i(v,tt);var d=C(v);function v(t,e,i,n,s,r){var o;y(this,v),void 0===r&&(r={}),(o=d.call(this,t,e,i,n,s)).type="rexGridTable",o._tableOX=0,o._tableOY=0,o.visibleCells=new us,o.preVisibleCells=new us,o.execeedTopState=!1,o.execeedBottomState=!1,o.execeedLeftState=!1,o.execeedRightState=!1,cs(r,"reuseCellContainer",!1)&&(o.cellContainersPool=new ls(t));var h=cs(r,"cellVisibleCallback",null);if(null!==h){var a=cs(r,"cellVisibleCallbackScope",void 0);o.on("cellvisible",h,a)}if(null!==(h=cs(r,"cellInvisibleCallback",null))){a=cs(r,"cellInvisibleCallbackScope",void 0);o.on("cellinvisible",h,a)}if(o.setCellsMask(cs(r,"mask",!0)),o.setScrollMode(cs(r,"scrollMode",0)),o.setClampMode(cs(r,"clamplTableOXY",!0)),0===o.scrollMode){var l=cs(r,"cellWidth",void 0);if(o.expandCellSize=void 0===l,void 0===l){var u=cs(r,"columns",1);r.cellWidth=o.width/u}}else{l=cs(r,"cellHeight",void 0);var c=cs(r,"cellWidth",void 0);o.expandCellSize=void 0===l,r.cellWidth=l,r.cellHeight=c}return o.table=new Un(k(o),r),o.updateTable(),o}return m(v,[{key:"destroy",value:function(t){this.scene&&(this.cellsMask&&(this.scene.game.events.off("poststep",this.maskCells,this),this.cellsMask.destroy(),this.cellsMask=void 0),this.table.destroy(t),this.table=void 0,this.cellContainersPool&&(this.cellContainersPool.destroy(!0),this.cellContainersPool=void 0),S(b(v.prototype),"destroy",this).call(this,t))}},{key:"setScrollMode",value:function(t){return"string"==typeof t&&(t=ps[t.toLowerCase()]),this.scrollMode=t,this}},{key:"setClampMode",value:function(t){return void 0===t&&(t=!0),this.clampTableOXY=t,this}},{key:"tableOY",get:function(){return this._tableOY},set:function(t){this.setTableOY(t).updateTable()}},{key:"tableOX",get:function(){return this._tableOX},set:function(t){this.setTableOX(t).updateTable()}},{key:"setTableOXY",value:function(t,e){return this.setTableOY(e).setTableOX(t),this}},{key:"addTableOY",value:function(t){return this.setTableOY(this.tableOY+t),this}},{key:"addTableOX",value:function(t){return this.setTableOX(this.tableOX+t),this}},{key:"addTableOXY",value:function(t,e){return this.addTableOY(e).addTableOX(t),this}},{key:"setTableOYByPercentage",value:function(t){return this.setTableOY(-this.tableVisibleHeight*t),this}},{key:"getTableOYPercentage",value:function(){var t=this.tableVisibleHeight;return 0===t?0:this.tableOY/-t}},{key:"t",get:function(){return this.getTableOYPercentage()},set:function(t){this.setTableOYByPercentage(t).updateTable()}},{key:"getCell",value:function(t){return this.table.getCell(t,!0)}},{key:"getCellContainer",value:function(t){var e,i=this.table.getCell(t,!1);return i&&(e=i.getContainer()),e}},{key:"cellsCount",get:function(){return this.table.cellsCount}},{key:"columnCount",get:function(){return this.table.colCount}},{key:"setCellHeight",value:function(t,e){return("number"==typeof t?this.table.getCell(t,!0):t).height=e,this}},{key:"setCellWidth",value:function(t,e){return("number"==typeof t?this.table.getCell(t,!0):t).width=e,this}},{key:"setCellsMask",value:function(t){var e,i,n;if(!0===t?(e=!0,n=i=0):!1===t?e=!1:(e=cs(t,"mask",!0),i=cs(t,"padding",0),n=cs(t,"updateMode",0)),this.maskCellsFlag=!0,this.maskUpdateMode=n,e){var s=new Zn(this,0,i);this.cellsMask=s.createGeometryMask(),this.add(s),"string"==typeof n&&(n=fs[n]),this.scene.game.events.on("poststep",this.maskCells,this)}return this}},{key:"instHeight",get:function(){return 0===this.scrollMode?this.height:this.width}},{key:"instWidth",get:function(){return 0===this.scrollMode?this.width:this.height}},{key:"tableHeight",get:function(){return this.table.totalRowsHeight}},{key:"tableWidth",get:function(){return this.table.totalColumnWidth}},{key:"topTableOY",get:function(){return 0}},{key:"bottomTableOY",get:function(){return-this.tableVisibleHeight}},{key:"leftTableOX",get:function(){return 0}},{key:"rightTableOX",get:function(){return-this.tableVisibleWidth}},{key:"tableVisibleHeight",get:function(){var t=this.tableHeight,e=this.instHeight;return e<t?t-e:0}},{key:"tableVisibleWidth",get:function(){var t=this.tableWidth,e=this.instWidth;return e<t?t-e:0}},{key:"bottomLeftY",get:function(){return-(this.displayHeight*this.originY)+this.displayHeight}},{key:"topRightX",get:function(){return-(this.displayWidth*this.originX)+this.displayWidth}},{key:"topLeftX",get:function(){return-(this.displayWidth*this.originX)}},{key:"topLeftY",get:function(){return-(this.displayHeight*this.originY)}},{key:"bottomBound",get:function(){return 0===this.scrollMode?this.bottomLeftY:this.topRightX}},{key:"rightBound",get:function(){return 0===this.scrollMode?this.topRightX:this.bottomLeftY}},{key:"resize",value:function(t,e){return this.width===t&&this.height===e||(S(b(v.prototype),"resize",this).call(this,t,e),this.cellsMask&&ve(jn(this.cellsMask),t,e),this.expandCellSize&&this.table.setDefaultCellWidth(this.instWidth/this.table.colCount),this.updateTable(!0)),this}}]),v}();Object.assign(ds.prototype,as);function vs(t,e,i,n,s,r){var o;if(null!=(o=void 0===s?n:i.pointToCellIndex(n,s))){var h=i.getCellContainer(o);h&&t.emit(e,h,o,r)}}var ps={v:0,vertical:0,h:1,horizontal:1},fs={update:0,everyTick:1},gs=function(t){var e=this.childrenMap.child,i=e.pointToCellIndex(t.x,t.y);if(i!==e.input.lastOverCellIndex){var n=e.input.lastOverCellIndex;e.input.lastOverCellIndex=i,vs(this.eventEmitter,"cell.out",e,n,void 0,t),vs(this.eventEmitter,"cell.over",e,i,void 0,t)}},ys=function(t){var e=this.childrenMap.child,i=e.input.lastOverCellIndex;e.input.lastOverCellIndex=void 0,vs(this.eventEmitter,"cell.out",e,i,void 0,t)},ms=Phaser.Utils.Objects.GetValue,bs=Phaser.Utils.Objects.GetValue,ks=function(){i(r,be);var s=C(r);function r(t,e){var i;y(this,r);var n=Lt(t);return n===t&&(t=void 0),((i=s.call(this,n,e)).gameObject=t)&&t.setInteractive(bs(e,"inputConfig",void 0)),i._enable=void 0,i.resetFromJSON(e),i.boot(),i}return m(r,[{key:"resetFromJSON",value:function(t){return this.setEnable(bs(t,"enable",!0)),this.setDetectBounds(),void 0===this.gameObject?this.setDetectBounds(bs(t,"bounds",void 0)):this.setDetectBounds(),this.tracerState=Cs,this.pointer=void 0,this.lastPointer=void 0,this.movedState=!1,this.isTouchingAnyObject=!1,this}},{key:"boot",value:function(){S(b(r.prototype),"boot",this).call(this),this.gameObject?this.gameObject.on("pointerdown",this.onPointerDown,this):this.scene.input.on("pointerdown",this.onPointerDown,this),this.scene.input.on("pointerup",this.onPointerUp,this),this.scene.input.on("pointermove",this.onPointerMove,this),this.scene.events.once("shutdown",this.destroy,this)}},{key:"shutdown",value:function(t){this.scene&&(this.gameObject||this.scene.input.off("pointerdown",this.onPointerDown,this),this.scene.input.off("pointerup",this.onPointerUp,this),this.scene.input.off("pointermove",this.onPointerMove,this),this.scene.events.off("shutdown",this.destroy,this),this.gameObject=void 0,this.bounds=void 0,this.pointer=void 0,this.lastPointer=void 0,this.movedState=!1,S(b(r.prototype),"shutdown",this).call(this,t))}},{key:"enable",get:function(){return this._enable},set:function(t){if(this._enable!==t)return t||this.dragCancel(),this._enable=t,this}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"setDetectBounds",value:function(t){return this.bounds=t,this}},{key:"toggleEnable",value:function(){return this.setEnable(!this.enable),this}},{key:"onPointerDown",value:function(t,e){this.enable&&void 0===this.pointer&&(this.bounds&&!this.bounds.contains(t.x,t.y)||this.pointer===t||(this.pointer=t,this.lastPointer=t,this.movedState=!1,this.tracerState=Ss,void 0===this.gameObject&&(this.isTouchingAnyObject=0<e.length),this.onDragStart()))}},{key:"onPointerUp",value:function(t){this.enable&&(this.bounds&&!this.bounds.contains(t.x,t.y)||this.pointer!==t||(this.pointer=void 0,this.movedState=!1,this.tracerState=Cs,this.onDragEnd()))}},{key:"onPointerMove",value:function(t){if(this.enable&&t.isDown){var e=!this.bounds||this.bounds.contains(t.x,t.y),i=this.pointer===t;!i&&e||(i&&!e?this.onPointerUp(t):(this.movedState||(this.movedState=t.x!==t.downX||t.y!==t.downY),this.movedState&&this.onDrag()))}}},{key:"dragCancel",value:function(){return this.tracerState===Ss&&this.onDragEnd(),this.pointer=void 0,this.tracerState=Cs,this}},{key:"onDragStart",value:function(){this.emit("dragstart",this)}},{key:"onDragEnd",value:function(){this.emit("dragend",this)}},{key:"onDrag",value:function(){this.emit("drag",this)}},{key:"preUpdate",value:function(){}},{key:"postUpdate",value:function(){}},{key:"startTicking",value:function(){S(b(r.prototype),"startTicking",this).call(this),this.scene.events.on("preupdate",this.preUpdate,this),this.scene.events.on("postupdate",this.postUpdate,this)}},{key:"stopTicking",value:function(){S(b(r.prototype),"stopTicking",this).call(this),this.scene&&(this.scene.events.off("preupdate",this.preUpdate,this),this.scene.events.off("postupdate",this.postUpdate,this))}},{key:"setRecongizedStateObject",value:function(t){return this.recongizedState=t,this}},{key:"state",get:function(){return this.recongizedState.state},set:function(t){this.recongizedState.state=t}},{key:"cancel",value:function(){return this.state=ws,this}}]),r}(),Cs=0,Ss=1,ws="IDLE",xs=Phaser.Utils.Objects.GetValue,Os=Phaser.Math.Distance.Between,Ps=function(){i(o,ks);var r=C(o);function o(t,e){var i;y(this,o);var n=k(i=r.call(this,t,e)),s={states:{IDLE:{enter:function(){n.stop(),n.tapsCount=0,n.x=0,n.y=0,n.worldX=0,n.worldY=0},exit:function(){var t=n.lastPointer;n.x=t.x,n.y=t.y,n.worldX=t.worldX,n.worldY=t.worldY}},BEGIN:{enter:function(){n.start(),n.tapsCount=0,n.emit("tappingstart",n,n.gameObject,n.lastPointer)}},RECOGNIZED:{enter:function(){n.start(),n.emit("tap",n,n.gameObject,n.lastPointer),n.emit("".concat(n.tapsCount,"tap"),n,n.gameObject,n.lastPointer)}}},init:function(){this.state=Es},eventEmitter:!1};return i.setRecongizedStateObject(new fn(s)),i}return m(o,[{key:"resetFromJSON",value:function(t){S(b(o.prototype),"resetFromJSON",this).call(this,t),this.setHoldTime(xs(t,"time",250)),this.setTapInterval(xs(t,"tapInterval",200)),this.setDragThreshold(xs(t,"threshold",9)),this.setTapOffset(xs(t,"tapOffset",10));var e=xs(t,"taps",void 0);return void 0!==e?this.setTaps(e):(this.setMaxTaps(xs(t,"maxTaps",void 0)),this.setMinTaps(xs(t,"minTaps",void 0))),this}},{key:"onDragStart",value:function(){switch(this.state){case Es:this.state=Ts;break;case Ts:var t=this.lastPointer;Os(t.upX,t.upY,t.x,t.y)>this.tapOffset&&(this.state=Ms,this.state=Ts);break;case Ms:this.state=Ts}}},{key:"onDragEnd",value:function(){this.state===Ts&&(this.tapsCount++,this.emit("tapping",this,this.gameObject,this.lastPointer),void 0!==this.maxTaps&&this.tapsCount===this.maxTaps&&(this.state=Ms))}},{key:"onDrag",value:function(){this.state!==Es&&this.pointer.getDistance()>this.dragThreshold&&(this.state=Es)}},{key:"preUpdate",value:function(t){if(this.isRunning&&this.enable&&this.state===Ts){var e=this.lastPointer;if(e.isDown)t-e.downTime>this.holdTime&&(this.state=Es);else t-e.upTime>this.tapInterval&&(void 0===this.minTaps||this.tapsCount>=this.minTaps?this.state=Ms:this.state=Es)}}},{key:"postUpdate",value:function(){this.isRunning&&this.enable&&this.state===Ms&&(this.state=Es)}},{key:"isTapped",get:function(){return this.state===Ms}},{key:"setHoldTime",value:function(t){return this.holdTime=t,this}},{key:"setTapInterval",value:function(t){return this.tapInterval=t,this}},{key:"setDragThreshold",value:function(t){return this.dragThreshold=t,this}},{key:"setTapOffset",value:function(t){return this.tapOffset=t,this}},{key:"setMaxTaps",value:function(t){return this.maxTaps=t,this}},{key:"setMinTaps",value:function(t){return this.minTaps=t,this}},{key:"setTaps",value:function(t,e){return void 0===e&&(e=t),this.setMinTaps(t).setMaxTaps(e),this}}]),o}(),Es="IDLE",Ts="BEGIN",Ms="RECOGNIZED",Ds=Phaser.Utils.Objects.GetValue,_s=function(){i(o,ks);var r=C(o);function o(t,e){var i;y(this,o);var n=k(i=r.call(this,t,e)),s={states:{IDLE:{enter:function(){n.x=0,n.y=0,n.worldX=0,n.worldY=0},exit:function(){var t=n.lastPointer;n.x=t.x,n.y=t.y,n.worldX=t.worldX,n.worldY=t.worldY}},BEGIN:{enter:function(){n.start()},exit:function(){n.stop()}},RECOGNIZED:{enter:function(){n.emit("pressstart",n,n.gameObject,n.lastPointer)},exit:function(){n.emit("pressend",n,n.gameObject,n.lastPointer)}}},init:function(){this.state=Ys},eventEmitter:!1};return i.setRecongizedStateObject(new fn(s)),i}return m(o,[{key:"resetFromJSON",value:function(t){return S(b(o.prototype),"resetFromJSON",this).call(this,t),this.setDragThreshold(Ds(t,"threshold",9)),this.setHoldTime(Ds(t,"time",251)),this}},{key:"onDragStart",value:function(){this.state=Rs,0===this.holdTime&&(this.state=Xs)}},{key:"onDragEnd",value:function(){this.state=Ys}},{key:"onDrag",value:function(){this.state!==Ys&&this.pointer.getDistance()>this.dragThreshold&&(this.state=Ys)}},{key:"preUpdate",value:function(t){this.isRunning&&this.enable&&this.state===Rs&&t-this.pointer.downTime>=this.holdTime&&(this.state=Xs)}},{key:"isPressed",get:function(){return this.state===Xs}},{key:"setHoldTime",value:function(t){return this.holdTime=t,this}},{key:"setDragThreshold",value:function(t){return this.dragThreshold=t,this}}]),o}(),Ys="IDLE",Rs="BEGIN",Xs="RECOGNIZED";Phaser.Utils.Objects.GetValue;var Vs=Phaser.Math.Distance.Between,zs=Phaser.Math.Angle.Between,Is={getDt:function(){return this.scene.sys.game.loop.delta},getVelocity:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Vs(e.x,e.y,t.x,t.y)/(.001*this.getDt())},getVelocityX:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Math.abs(t.x-e.x)/(.001*this.getDt())},getVelocityY:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Math.abs(t.y-e.y)/(.001*this.getDt())},getVelocityAngle:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return zs(e.x,e.y,t.x,t.y)}},As={"up&down":0,"left&right":1,"4dir":2,"8dir":3},js={},Hs=Phaser.Utils.Objects.GetValue,Ls=Phaser.Math.RadToDeg,Ws=function(){i(o,ks);var r=C(o);function o(t,e){var i;y(this,o);var n=k(i=r.call(this,t,e)),s={states:{IDLE:{enter:function(){n.x=0,n.y=0,n.worldX=0,n.worldY=0},exit:function(){var t=n.lastPointer;n.x=t.x,n.y=t.y,n.worldX=t.worldX,n.worldY=t.worldY}},BEGIN:{enter:function(){n.validDrag=!1}},RECOGNIZED:{enter:function(){n.start(),n.updateDirectionStates(),n.emit("swipe",n,n.gameObject,n.lastPointer)},exit:function(){n.stop(),n.clearDirectionStates()}}},init:function(){this.state=Ns},eventEmitter:!1};return i.setRecongizedStateObject(new fn(s)),i.clearDirectionStates(),i}return m(o,[{key:"resetFromJSON",value:function(t){return S(b(o.prototype),"resetFromJSON",this).call(this,t),this.setDragThreshold(Hs(t,"threshold",10)),this.setVelocityThreshold(Hs(t,"velocityThreshold",1e3)),this.setDirectionMode(Hs(t,"dir","8dir")),this}},{key:"onDragStart",value:function(){this.state=Fs}},{key:"onDragEnd",value:function(){this.state=Ns}},{key:"onDrag",value:function(){this.state===Fs&&(this.validDrag||(this.validDrag=0===this.dragThreshold||this.pointer.getDistance()>=this.dragThreshold),this.validDrag&&this.dragVelocity>this.velocityThreshold&&(this.state=Gs))}},{key:"postUpdate",value:function(){this.isRunning&&this.enable&&this.state===Gs&&(this.state=Ns)}},{key:"isSwiped",get:function(){return this.state===Gs}},{key:"dragVelocity",get:function(){var t;switch(this.dirMode){case 0:t=this.getVelocityY();break;case 1:t=this.getVelocityX();break;default:t=this.getVelocity()}return t}},{key:"setDragThreshold",value:function(t){return this.dragThreshold=t,this}},{key:"setVelocityThreshold",value:function(t){return this.velocityThreshold=t,this}},{key:"setDirectionMode",value:function(t){return"string"==typeof t&&(t=As[t]),this.dirMode=t,this}},{key:"updateDirectionStates",value:function(){return function(t,e,i){switch(void 0===i?i={}:!0===i&&(i=js),i.left=!1,i.right=!1,i.up=!1,i.down=!1,t=(t+360)%360,e){case 0:t<180?i.down=!0:i.up=!0;break;case 1:90<t&&t<=270?i.left=!0:i.right=!0;break;case 2:45<t&&t<=135?i.down=!0:135<t&&t<=225?i.left=!0:225<t&&t<=315?i.up=!0:i.right=!0;break;case 3:22.5<t&&t<=67.5?(i.down=!0,i.right=!0):67.5<t&&t<=112.5?i.down=!0:112.5<t&&t<=157.5?(i.down=!0,i.left=!0):157.5<t&&t<=202.5?i.left=!0:202.5<t&&t<=247.5?(i.left=!0,i.up=!0):247.5<t&&t<=292.5?i.up=!0:(292.5<t&&t<=337.5&&(i.up=!0),i.right=!0)}}(Ls(this.getVelocityAngle()),this.dirMode,this),this}},{key:"clearDirectionStates",value:function(){return this.left=!1,this.right=!1,this.up=!1,this.down=!1,this}}]),o}();Object.assign(Ws.prototype,Is);var Ns="IDLE",Fs="BEGIN",Gs="RECOGNIZED",Bs=Phaser.Utils.Objects.GetValue,Us=Phaser.Utils.Array.SpliceOne,Js=Phaser.Math.Distance.Between,Zs=Phaser.Math.Angle.Between,Ks=function(){function n(t,e){y(this,n);var i=t.input.manager.pointersTotal-1;i<2&&t.input.addPointer(2-i),this.scene=t,this.setEventEmitter(Bs(e,"eventEmitter",void 0)),this._enable=void 0,this.pointers=[],this.movedState={},this.resetFromJSON(e),this.boot()}return m(n,[{key:"resetFromJSON",value:function(t){return this.setEnable(Bs(t,"enable",!0)),this.bounds=Bs(t,"bounds",void 0),this.tracerState=$s,this.pointers.length=0,Vn(this.movedState),this}},{key:"boot",value:function(){this.scene.input.on("pointerdown",this.onPointerDown,this),this.scene.input.on("pointerup",this.onPointerUp,this),this.scene.input.on("pointermove",this.onPointerMove,this),this.scene.events.once("shutdown",this.destroy,this)}},{key:"shutdown",value:function(){this.scene&&(this.destroyEventEmitter(),this.pointers.length=0,Vn(this.movedState),this.scene.input.off("pointerdown",this.onPointerDown,this),this.scene.input.off("pointerup",this.onPointerUp,this),this.scene.input.off("pointermove",this.onPointerMove,this),this.scene.events.off("shutdown",this.destroy,this),this.scene=void 0)}},{key:"destroy",value:function(){this.shutdown()}},{key:"enable",get:function(){return this._enable},set:function(t){if(this._enable!==t)return t||this.dragCancel(),this._enable=t,this}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"toggleEnable",value:function(){return this.setEnable(!this.enable),this}},{key:"onPointerDown",value:function(t){if(this.enable&&(2!==this.pointers.length&&(!this.bounds||this.bounds.contains(t.x,t.y))&&-1===this.pointers.indexOf(t)))switch(this.movedState[t.id]=!1,this.pointers.push(t),this.tracerState){case $s:this.tracerState=Qs,this.onDrag1Start();break;case Qs:this.tracerState=tr,this.onDrag2Start()}}},{key:"onPointerUp",value:function(t){if(this.enable&&(!this.bounds||this.bounds.contains(t.x,t.y))){var e=this.pointers.indexOf(t);if(-1!==e)switch(delete this.movedState[t.id],Us(this.pointers,e),this.tracerState){case Qs:this.tracerState=$s,this.onDrag1End();break;case tr:this.tracerState=Qs,this.onDrag2End(),this.onDrag1Start()}}}},{key:"onPointerMove",value:function(t){if(this.enable&&t.isDown){var e=!this.bounds||this.bounds.contains(t.x,t.y),i=-1!==this.pointers.indexOf(t);if(i||!e)if(i&&!e)this.onPointerUp(t);else if(this.movedState[t.id]||(this.movedState[t.id]=t.x!==t.downX||t.y!==t.downY),this.movedState[t.id])switch(this.tracerState){case Qs:this.onDrag1();break;case tr:this.onDrag2()}}}},{key:"dragCancel",value:function(){return this.tracerState===tr&&this.onDrag2End(),this.pointers.length=0,Vn(this.movedState),this.tracerState=$s,this}},{key:"onDrag1Start",value:function(){this.emit("drag1start",this)}},{key:"onDrag1End",value:function(){this.emit("drag1end",this)}},{key:"onDrag1",value:function(){this.emit("drag1",this)}},{key:"onDrag2Start",value:function(){this.emit("drag2start",this)}},{key:"onDrag2End",value:function(){this.emit("drag2end",this)}},{key:"onDrag2",value:function(){this.emit("drag2",this)}},{key:"distanceBetween",get:function(){if(this.tracerState!==tr)return 0;var t=this.pointers[0],e=this.pointers[1];return Js(t.x,t.y,e.x,e.y)}},{key:"angleBetween",get:function(){if(this.tracerState!==tr)return 0;var t=this.pointers[0],e=this.pointers[1];return Zs(t.x,t.y,e.x,e.y)}},{key:"drag1Vector",get:function(){var t=this.pointers[0];if(t&&this.movedState[t.id]){var e=t.position,i=t.prevPosition;qs.x=e.x-i.x,qs.y=e.y-i.y}else qs.x=0,qs.y=0;return qs}},{key:"centerX",get:function(){if(this.tracerState!==tr)return 0;var t=this.pointers[0].position,e=this.pointers[1].position;return(t.x+e.x)/2}},{key:"centerY",get:function(){if(this.tracerState!==tr)return 0;var t=this.pointers[0].position,e=this.pointers[1].position;return(t.y+e.y)/2}},{key:"prevCenterX",get:function(){if(this.tracerState!==tr)return 0;var t=this.movedState[this.pointers[0].id]?this.pointers[0].prevPosition:this.pointers[0].position,e=this.movedState[this.pointers[1].id]?this.pointers[1].prevPosition:this.pointers[1].position;return(t.x+e.x)/2}},{key:"prevCenterY",get:function(){if(this.tracerState!==tr)return 0;var t=this.movedState[this.pointers[0].id]?this.pointers[0].prevPosition:this.pointers[0].position,e=this.movedState[this.pointers[1].id]?this.pointers[1].prevPosition:this.pointers[1].position;return(t.y+e.y)/2}},{key:"movementCenterX",get:function(){return this.centerX-this.prevCenterX}},{key:"movementCenterY",get:function(){return this.centerY-this.prevCenterY}},{key:"setRecongizedStateObject",value:function(t){return this.recongizedState=t,this}},{key:"state",get:function(){return this.recongizedState.state},set:function(t){this.recongizedState.state=t}},{key:"cancel",value:function(){return this.state=er,this}}]),n}();Object.assign(Ks.prototype,te);var qs={},$s=0,Qs=1,tr=2,er="IDLE";Phaser.Utils.Objects.GetValue;function ir(t,e,i,n){return nr(t,e,i,n),t.rotation+=n,t}var nr=Phaser.Math.RotateAround,sr={},rr=Phaser.Utils.Objects.GetValue,or=Phaser.Math.Angle.WrapDegrees,hr=Phaser.Math.Angle.ShortestBetween,ar=Phaser.Math.RadToDeg,lr=Phaser.Math.DegToRad,ur=function(){i(o,Ks);var r=C(o);function o(t,e){var i;y(this,o);var n=k(i=r.call(this,t,e)),s={states:{IDLE:{enter:function(){n.prevAngle=void 0,n.angle=0}},BEGIN:{},RECOGNIZED:{enter:function(){n.emit("rotatestart",n)},exit:function(){n.emit("rotateend",n)}}},init:function(){this.state=vr},eventEmitter:!1};return i.setRecongizedStateObject(new fn(s)),i}return m(o,[{key:"resetFromJSON",value:function(t){return S(b(o.prototype),"resetFromJSON",this).call(this,t),this.setDragThreshold(rr(t,"threshold",0)),this}},{key:"onDrag2Start",value:function(){this.prevAngle=or(ar(this.angleBetween)),this.state=pr,0===this.dragThreshold&&(this.state=fr)}},{key:"onDrag2End",value:function(){this.state=vr}},{key:"onDrag2",value:function(){switch(this.state){case pr:if(this.pointers[0].getDistance()>=this.dragThreshold&&this.pointers[1].getDistance()>=this.dragThreshold){var t=or(ar(this.angleBetween));this.angle=hr(this.prevAngle,t),this.prevAngle=t,this.state=fr}break;case fr:t=or(ar(this.angleBetween));this.angle=hr(this.prevAngle,t),this.prevAngle=t,this.emit("rotate",this)}}},{key:"isRotated",get:function(){return this.state===fr}},{key:"rotation",get:function(){return lr(this.angle)}},{key:"setDragThreshold",value:function(t){return this.dragThreshold=t,this}}]),o}(),cr={spinObject:function(t,e){if(!this.isRotation)return this;void 0===e&&(e=this.pointers[0].camera);var i=this.movementCenterX,n=this.movementCenterY;e.getWorldPoint(this.centerX,this.centerY,sr);var s=sr.x,r=sr.y,o=this.rotation;if(Array.isArray(t))for(var h=t,a=0,l=h.length;a<l;a++)(t=h[a]).x+=i,t.y+=n,ir(t,s,r,o);else t.x+=i,t.y+=n,ir(t,s,r,o);return this}};Object.assign(ur.prototype,cr);function dr(t,e){t.setInteractive(),function(e){e.on("pointerdown",function(t){vs(this.eventEmitter,"cell.down",e,t.x,t.y,t)},this).on("pointerup",function(t){vs(this.eventEmitter,"cell.up",e,t.x,t.y,t)},this)}.call(this,t,e),function(t){t.on("pointermove",gs,this).on("pointerover",gs,this).on("pointerout",ys,this)}.call(this,t,e),function(t,e){var i=ms(e,"button",void 0);!1!==i&&(void 0===i&&(i={}),i.threshold=10,t._click=new ci(t,i),t._click.on("click",function(t,e,i){vs(this.eventEmitter,"cell.click",e,i.x,i.y,i)},this))}.call(this,t,e),function(t,e){var i=gr(e,"tap",void 0);!1!==i&&(t._tap=new Ps(t,i),t._tap.on("tap",function(t,e,i){var n="cell.".concat(t.tapsCount,"tap");vs(this.eventEmitter,n,t.gameObject,t.x,t.y,i)},this))}.call(this,t,e),function(n,t){var e=yr(t,"press",void 0);!1!==e&&(n._press=new _s(n,e),n._press.on("pressstart",function(t,e,i){vs(this.eventEmitter,"cell.pressstart",n,t.x,t.y,i)},this).on("pressend",function(t,e,i){vs(this.eventEmitter,"cell.pressend",n,t.x,t.y,i)},this))}.call(this,t,e),function(s,t){var e=mr(t,"swipe",void 0);!1!==e&&(void 0===e&&(e={}),e.dir="4dir",s._swipe=new Ws(s,e),s._swipe.on("swipe",function(t,e,i){var n=t.left?"left":t.right?"right":t.up?"up":"down";vs(this.eventEmitter,"cell.swipe".concat(n),s,t.x,t.y,i)},this))}.call(this,t,e)}var vr="IDLE",pr="BEGIN",fr="RECOGNIZED",gr=Phaser.Utils.Objects.GetValue,yr=Phaser.Utils.Objects.GetValue,mr=Phaser.Utils.Objects.GetValue,br=Phaser.Utils.Objects.GetValue,kr=function(){i(g,Rn);var f=C(g);function g(t,e){var i;y(this,g),void 0===e&&(e={});var n=Xi(e),s=br(e,"table",void 0);void 0===s&&(s={}),s.scrollMode=n,s.clamplTableOXY=br(e,"clamplChildOY",!1);var r,o,h,a=br(s,"width",void 0),l=br(s,"height",void 0),u=new ds(t,0,0,a,l,s);t.add.existing(u),o=0===n?(r=void 0===a?1:0,void 0===l):(r=void 0===l?1:0,void 0===a),h=u,Object.defineProperty(h,"childOY",{configurable:!0,get:function(){return h.tableOY},set:function(t){h.tableOY=t}}),Object.defineProperty(h,"topChildOY",{get:function(){return h.topTableOY}}),Object.defineProperty(h,"bottomChildOY",{get:function(){return h.bottomTableOY}}),e.type="rexGridTable",e.child={gameObject:u,proportion:r,expand:o};var c=br(e,"space",void 0);c&&(c.child=c.table),(i=f.call(this,t,e)).addChildrenMap("table",u),i.eventEmitter=br(e,"eventEmitter",k(i));var d=br(e,"createCellContainerCallback",it),v=br(e,"createCellContainerCallbackScope",void 0);i.setCreateCellContainerCallback(d,v),function(t){t.on("cellvisible",function(t,e,i){var n=this.createCellContainerCallback,s=this.createCellContainerCallbackScope;t.item=this.items[t.index],(e=s?n.call(s,t,e,i):n(t,e,i))&&(e.setOrigin&&e.setOrigin(0),e.isRexSizer&&e.layout()),t.item=void 0,t.setContainer(e)},this)}.call(k(i),u),i.resizeControllerFlag=!1;var p=0===n?"cellheightchange":"cellwidthchange";return u.on(p,function(){this.resizeControllerFlag=!0},k(i)),br(s,"interactive",!0)&&dr.call(k(i),u,s),i.setItems(br(e,"items",[])),t.game.events.on("poststep",i.onPostStep,k(i)),i}return m(g,[{key:"destroy",value:function(t){this.scene&&(this.scene.game.events.off("poststep",this.onPostStep,this),S(b(g.prototype),"destroy",this).call(this,t))}},{key:"setCreateCellContainerCallback",value:function(t,e){return this.createCellContainerCallback=t,this.createCellContainerCallbackScope=e,this}},{key:"refresh",value:function(){return this.setItems(this.items),this}},{key:"getCell",value:function(t){return this.childrenMap.child.getCell(t)}},{key:"getCellContainer",value:function(t){return this.childrenMap.child.getCellContainer(t)}},{key:"updateVisibleCell",value:function(t){return this.childrenMap.child.updateVisibleCell(t)}},{key:"onPostStep",value:function(){this.resizeControllerFlag&&(this.resizeController(),this.resizeControllerFlag=!1)}}]),g}(),Cr={setItems:function(t){void 0===t?this.items.length=0:this.items=t;var e=this.childrenMap.child;return e.setCellsCount(this.items.length),e.updateTable(!0),this.resizeController(),this}};return Object.assign(kr.prototype,Cr),kr});
y
lib.rs
#![doc = "generated by AutoRust 0.1.0"] #[cfg(feature = "package-2021-06-01")]
mod package_2021_06_01; #[cfg(feature = "package-2021-06-01")] pub use package_2021_06_01::{models, operations, API_VERSION}; #[cfg(feature = "package-2021-01-01-preview")] mod package_2021_01_01_preview; #[cfg(feature = "package-2021-01-01-preview")] pub use package_2021_01_01_preview::{models, operations, API_VERSION}; #[cfg(feature = "package-2020-07-17-preview")] mod package_2020_07_17_preview; #[cfg(feature = "package-2020-07-17-preview")] pub use package_2020_07_17_preview::{models, operations, API_VERSION}; #[cfg(feature = "package-2020-03-20")] mod package_2020_03_20; use azure_core::setters; #[cfg(feature = "package-2020-03-20")] pub use package_2020_03_20::{models, operations, API_VERSION}; pub fn config( http_client: std::sync::Arc<std::boxed::Box<dyn azure_core::HttpClient>>, token_credential: Box<dyn azure_core::TokenCredential>, ) -> OperationConfigBuilder { OperationConfigBuilder { api_version: None, http_client, base_path: None, token_credential, token_credential_resource: None, } } pub struct OperationConfigBuilder { api_version: Option<String>, http_client: std::sync::Arc<std::boxed::Box<dyn azure_core::HttpClient>>, base_path: Option<String>, token_credential: Box<dyn azure_core::TokenCredential>, token_credential_resource: Option<String>, } impl OperationConfigBuilder { setters! { api_version : String => Some (api_version) , base_path : String => Some (base_path) , token_credential_resource : String => Some (token_credential_resource) , } pub fn build(self) -> OperationConfig { OperationConfig { api_version: self.api_version.unwrap_or(API_VERSION.to_owned()), http_client: self.http_client, base_path: self.base_path.unwrap_or("https://management.azure.com".to_owned()), token_credential: Some(self.token_credential), token_credential_resource: self.token_credential_resource.unwrap_or("https://management.azure.com/".to_owned()), } } } pub struct OperationConfig { api_version: String, http_client: std::sync::Arc<std::boxed::Box<dyn azure_core::HttpClient>>, base_path: String, token_credential: Option<Box<dyn azure_core::TokenCredential>>, token_credential_resource: String, } impl OperationConfig { pub fn api_version(&self) -> &str { self.api_version.as_str() } pub fn http_client(&self) -> &dyn azure_core::HttpClient { self.http_client.as_ref().as_ref() } pub fn base_path(&self) -> &str { self.base_path.as_str() } pub fn token_credential(&self) -> Option<&dyn azure_core::TokenCredential> { self.token_credential.as_deref() } pub fn token_credential_resource(&self) -> &str { self.token_credential_resource.as_str() } }
generic.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Definition of generic operator strategy.""" # pylint: disable=invalid-name,unused-argument import logging import re from tvm import topi, _ffi, te, ir from tvm.topi.utils import get_const_int, get_const_float, get_const_tuple, get_float_tuple from tvm.target import generic_func, override_native_generic_func from .. import op as _op logger = logging.getLogger("strategy") def naive_schedule(_, outs, target): """Return the naive default schedule""" if "gpu" in target.keys: # For GPU, we at least need thread binding to make a valid schedule. # So the naive schedule cannot be compiled. raise RuntimeError( "Cannot compile for GPU targets if no tuned schedule is found. " "Please see the warning messages above for more information about the failed workloads." ) return te.create_schedule(outs[-1].op) def wrap_topi_schedule(topi_schedule): """Wrap TOPI schedule which doesn't use attrs""" def wrapper(attrs, outs, target): with target: return topi_schedule(outs) return wrapper def get_conv2d_in_channels(data_shape, data_layout): """Get conv2d input channels""" data_shape = get_const_tuple(data_shape) if len(data_shape) == 4: idx = data_layout.find("C") assert idx >= 0, "Invalid conv2d data layout {}".format(data_layout) return data_shape[idx] if re.match(r"NCHW\d*c", data_layout): # NCHW[8]c return data_shape[1] * data_shape[4] raise ValueError("Unknown conv2d data layout {}".format(data_layout)) def get_conv2d_out_channels(kernel_shape, kernel_layout): """Get conv2d output channels""" kernel_shape = get_const_tuple(kernel_shape) if len(kernel_shape) == 4: idx = kernel_layout.find("O") assert idx >= 0, "Invalid conv2d kernel layout {}".format(kernel_layout) return kernel_shape[idx] if re.match(r"OIHW\d*i\d*o", kernel_layout): return kernel_shape[0] * kernel_shape[5] if re.match(r"OIHW\d*o", kernel_layout): return kernel_shape[0] * kernel_shape[4] raise ValueError("Unknown conv2d kernel layout {}".format(kernel_layout)) def is_depthwise_conv2d(data_shape, data_layout, kernel_shape, kernel_layout, groups): ic = get_conv2d_in_channels(data_shape, data_layout) oc = get_conv2d_out_channels(kernel_shape, kernel_layout) return ic == oc == groups @generic_func def schedule_injective(attrs, outs, target): """Schedule injective ops""" with target: return topi.generic.schedule_injective(outs) @generic_func def schedule_reduce(attrs, outs, target): """Schedule reduction ops""" with target: return topi.generic.schedule_reduce(outs) _op._schedule_injective = schedule_injective _op._schedule_reduce = schedule_reduce # concatenate @generic_func def schedule_concatenate(attrs, outs, target): """Schedule concatenate op""" with target: return topi.generic.schedule_injective(outs) # pool @generic_func def schedule_pool(attrs, outs, target): """Schedule pooling ops""" with target: return topi.generic.schedule_pool(outs, attrs.layout) # pool_grad @generic_func def schedule_pool_grad(attrs, outs, target): """Schedule pooling gradient ops""" with target: return topi.generic.schedule_pool_grad(outs) # adaptive pool @generic_func def schedule_adaptive_pool(attrs, outs, target): """Schedule adaptive pooling ops""" with target: return topi.generic.schedule_adaptive_pool(outs) # softmax def wrap_compute_softmax(topi_compute): """Wrap softmax topi compute""" def _compute_softmax(attrs, inputs, out_type): axis = attrs.get_int("axis") return [topi_compute(inputs[0], axis)] return _compute_softmax @override_native_generic_func("softmax_strategy") def softmax_strategy(attrs, inputs, out_type, target): """softmax generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_softmax(topi.nn.softmax), wrap_topi_schedule(topi.generic.schedule_softmax), name="softmax.generic", ) return strategy # log_softmax @generic_func def schedule_log_softmax(attrs, outs, target): """Schedule log_softmax op""" with target: return topi.generic.schedule_softmax(outs) # lrn @generic_func def schedule_lrn(attrs, outs, target): """Schedule LRN op""" with target: return topi.generic.schedule_lrn(outs) # bitpack @generic_func def schedule_bitpack(attrs, outs, target): """Schedule bitpack""" with target: return topi.generic.schedule_bitpack(outs) get_auto_scheduler_rewritten_layout = _ffi.get_global_func( "relay.attrs.get_auto_scheduler_rewritten_layout" ) # conv2d def wrap_compute_conv2d( topi_compute, need_data_layout=False, need_out_layout=False, has_groups=False, need_auto_scheduler_layout=False, ): """Wrap conv2d topi compute""" def _compute_conv2d(attrs, inputs, out_type): padding = get_const_tuple(attrs.padding) strides = get_const_tuple(attrs.strides) dilation = get_const_tuple(attrs.dilation) data_layout = attrs.get_str("data_layout") out_layout = attrs.get_str("out_layout") out_dtype = attrs.out_dtype auto_scheduler_rewritten_layout = get_auto_scheduler_rewritten_layout(attrs) out_dtype = inputs[0].dtype if out_dtype in ("same", "") else out_dtype args = [inputs[0], inputs[1], strides, padding, dilation] if has_groups: args.append(attrs.groups) if need_data_layout: args.append(data_layout) if need_out_layout: args.append(out_layout) args.append(out_dtype) if need_auto_scheduler_layout: args.append(auto_scheduler_rewritten_layout) return [topi_compute(*args)] return _compute_conv2d @override_native_generic_func("conv2d_strategy") def conv2d_strategy(attrs, inputs, out_type, target): """conv2d generic strategy""" logger.warning("conv2d is not optimized for this platform.") strategy = _op.OpStrategy() data, kernel = inputs dilation = get_const_tuple(attrs.dilation) groups = attrs.groups layout = attrs.data_layout kernel_layout = attrs.kernel_layout (dilation_h, dilation_w) = dilation if dilation_h < 1 or dilation_w < 1: raise ValueError("dilation should be positive value") if groups == 1: if layout == "NCHW": assert kernel_layout == "OIHW" strategy.add_implementation( wrap_compute_conv2d(topi.nn.conv2d_nchw), wrap_topi_schedule(topi.generic.schedule_conv2d_nchw), name="conv2d_nchw.generic", ) elif layout == "NHWC": assert kernel_layout == "HWIO" strategy.add_implementation( wrap_compute_conv2d(topi.nn.conv2d_nhwc), wrap_topi_schedule(topi.generic.schedule_conv2d_nhwc), name="conv2d_nhwc.generic", ) elif layout == "HWCN": assert kernel_layout == "HWIO" strategy.add_implementation( wrap_compute_conv2d(topi.nn.conv2d_hwcn), wrap_topi_schedule(topi.generic.schedule_conv2d_hwcn), name="conv2d_hwcn.generic", ) else: raise RuntimeError("Unsupported conv2d layout {}".format(layout)) elif is_depthwise_conv2d(data.shape, layout, kernel.shape, kernel_layout, groups): if layout == "NCHW": assert kernel_layout == "OIHW" strategy.add_implementation( wrap_compute_conv2d(topi.nn.depthwise_conv2d_nchw), wrap_topi_schedule(topi.generic.schedule_depthwise_conv2d_nchw), name="depthwise_conv2d_nchw.generic", ) elif layout == "NHWC": assert kernel_layout == "HWOI" strategy.add_implementation( wrap_compute_conv2d(topi.nn.depthwise_conv2d_nhwc), wrap_topi_schedule(topi.generic.schedule_depthwise_conv2d_nhwc), name="depthwise_conv2d_nhwc.generic", ) else: raise RuntimeError("Unsupported depthwise_conv2d layout {}".format(layout)) else: # group_conv2d if layout == "NCHW": assert kernel_layout == "OIHW" strategy.add_implementation( wrap_compute_conv2d(topi.nn.group_conv2d_nchw, has_groups=True), wrap_topi_schedule(topi.generic.schedule_group_conv2d_nchw), name="group_conv2d_nchw.generic", ) elif layout == "NHWC": assert kernel_layout == "HWIO" strategy.add_implementation( wrap_compute_conv2d(topi.nn.group_conv2d_nhwc, has_groups=True), wrap_topi_schedule(topi.generic.schedule_group_conv2d_nhwc), name="group_conv2d_nhwc.generic", ) else: raise RuntimeError("Unsupported group_conv2d layout {}".format(layout)) return strategy # conv2d_NCHWc @override_native_generic_func("conv2d_NCHWc_strategy") def conv2d_NCHWc_strategy(attrs, inputs, out_type, target): """conv2d_NCHWc generic strategy""" logger.warning("conv2d_NCHWc is not optimized for this platform.") strategy = _op.OpStrategy() if inputs[0].dtype == "int8" or inputs[0].dtype == "uint8": strategy.add_implementation( wrap_compute_conv2d(topi.nn.conv2d_NCHWc_int8, True, True), wrap_topi_schedule(topi.generic.schedule_conv2d_NCHWc_int8), name="conv2d_NCHWc_int8.generic", ) else: strategy.add_implementation( wrap_compute_conv2d(topi.nn.conv2d_NCHWc, True, True), wrap_topi_schedule(topi.generic.schedule_conv2d_NCHWc), name="conv2d_NCHWc.generic", ) return strategy # depthwise_conv2d_NCHWc @override_native_generic_func("depthwise_conv2d_NCHWc_strategy") def depthwise_conv2d_NCHWc_strategy(attrs, inputs, out_type, target): """depthwise_conv2d generic strategy""" logger.warning("depthwise_conv2d_NCHWc is not optimized for this platform.") strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_conv2d(topi.nn.depthwise_conv2d_NCHWc, True, True), wrap_topi_schedule(topi.generic.schedule_depthwise_conv2d_NCHWc), name="depthwise_conv2d_NCHWc.generic", ) return strategy # conv2d_winograd_without_weight_transform @override_native_generic_func("conv2d_winograd_without_weight_transform_strategy") def conv2d_winograd_without_weight_transfrom_strategy(attrs, inputs, out_type, target): """conv2d_winograd_without_weight_transfrom generic strategy""" raise ValueError("No generic implemenation for conv2d_winograd_without_weight_transform") # conv2d_gemm_without_weight_transform @override_native_generic_func("conv2d_gemm_without_weight_transform_strategy") def conv2d_gemm_without_weight_transform_strategy(attrs, inputs, out_type, target): """conv2d_gemm_without_weight_transfrom generic strategy""" raise ValueError("No generic implemenation for conv2d_gemm_without_weight_transform") # conv2d_winograd_weight_transform @generic_func def schedule_conv2d_winograd_weight_transform(attrs, outs, target): """Schedule conv2d_winograd_weight_transform""" with target: return topi.generic.schedule_conv2d_winograd_weight_transform(outs) # conv2d_winograd_nnpack_weight_transform @generic_func def schedule_conv2d_winograd_nnpack_weight_transform(attrs, outs, target): """Schedule conv2d_winograd_nnpack_weight_transform""" with target: return topi.generic.schedule_conv2d_winograd_nnpack_weight_transform(outs) # conv2d_gemm_weight_transform @generic_func def schedule_conv2d_gemm_weight_transform(attrs, outs, target): """Schedule conv2d_gemm_weight_transform""" with target: return topi.generic.schedule_conv2d_gemm_weight_transform(outs) # deformable_conv2d def wrap_compute_deformable_conv2d(topi_compute): """wrap deformable_conv2d topi compute""" def _compute_deformable_conv2d(attrs, inputs, out_dtype): padding = get_const_tuple(attrs.padding) strides = get_const_tuple(attrs.strides) dilation = get_const_tuple(attrs.dilation) deformable_groups = attrs.deformable_groups groups = attrs.groups out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype in ("same", "") else out_dtype out = topi_compute( inputs[0], inputs[1], inputs[2], strides, padding, dilation, deformable_groups, groups, out_dtype, ) return [out] return _compute_deformable_conv2d @override_native_generic_func("deformable_conv2d_strategy") def deformable_conv2d_strategy(attrs, inputs, out_type, target): """deformable_conv2d generic strategy""" layout = attrs.data_layout strategy = _op.OpStrategy() if layout == "NCHW": strategy.add_implementation( wrap_compute_deformable_conv2d(topi.nn.deformable_conv2d_nchw), wrap_topi_schedule(topi.generic.schedule_deformable_conv2d_nchw), name="deformable_conv2d_nchw.generic", ) elif layout == "NHWC": # This implementation should never be picked by autotvm strategy.add_implementation( wrap_compute_deformable_conv2d(topi.nn.deformable_conv2d_nhwc), naive_schedule, name="deformable_conv2d_nhwc.generic", ) else: raise RuntimeError("Layout %s is not supported in deformable conv2d" % layout) return strategy # conv2d_transpose def wrap_compute_conv2d_transpose(topi_compute): """wrap conv2d_transpose topi compute""" def compute_conv2d_transpose(attrs, inputs, out_dtype): """Compute definition of conv2d_transpose""" padding = get_const_tuple(attrs.padding) strides = get_const_tuple(attrs.strides) out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype in ("same", "") else out_dtype output_padding = get_const_tuple(attrs.output_padding) out = topi_compute(inputs[0], inputs[1], strides, padding, out_dtype, output_padding) return [out] return compute_conv2d_transpose @override_native_generic_func("conv2d_transpose_strategy") def conv2d_transpose_strategy(attrs, inputs, out_type, target): """conv2d_transpose generic strategy""" logger.warning("conv2d_transpose is not optimized for this platform.") layout = attrs.data_layout dilation = get_const_tuple(attrs.dilation) groups = attrs.groups assert layout == "NCHW", "only support nchw for now" assert dilation == (1, 1), "not support dilate now" assert groups == 1, "only support groups == 1 for now" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_conv2d_transpose(topi.nn.conv2d_transpose_nchw), wrap_topi_schedule(topi.generic.schedule_conv2d_transpose_nchw), name="conv2d_transpose_nchw.generic", ) return strategy # conv3d_transpose def wrap_compute_conv3d_transpose(topi_compute): """wrap conv3d_transpose topi compute""" def compute_conv3d_transpose(attrs, inputs, out_dtype): """Compute definition of conv3d_transpose""" padding = get_const_tuple(attrs.padding) strides = get_const_tuple(attrs.strides) output_padding = get_const_tuple(attrs.output_padding) out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype in ("same", "") else out_dtype out = topi_compute(inputs[0], inputs[1], strides, padding, out_dtype, output_padding) return [out] return compute_conv3d_transpose @override_native_generic_func("conv3d_transpose_strategy") def conv3d_transpose_strategy(attrs, inputs, out_type, target): """conv3d_transpose generic strategy""" logger.warning("conv3d_transpose is not optimized for this platform.") layout = attrs.data_layout dilation = get_const_tuple(attrs.dilation) groups = attrs.groups assert layout == "NCDHW", "only support ncdhw for now" assert dilation == (1, 1, 1), "not support dilate now" assert groups == 1, "only support groups == 1 for now" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_conv3d_transpose(topi.nn.conv3d_transpose_ncdhw), wrap_topi_schedule(topi.generic.schedule_conv3d_transpose_ncdhw), name="conv3d_transpose_ncdhw.generic", ) return strategy # conv3d def wrap_compute_conv3d(topi_compute, need_layout=False): """wrap conv3d topi compute""" def _compute_conv3d(attrs, inputs, out_type): padding = get_const_tuple(attrs.padding) strides = get_const_tuple(attrs.strides) dilation = get_const_tuple(attrs.dilation) groups = attrs.groups layout = attrs.data_layout out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype in ("same", "") else out_dtype (dilation_d, dilation_h, dilation_w) = dilation if dilation_d < 1 or dilation_h < 1 or dilation_w < 1: raise ValueError("Dilation should be positive value") if groups != 1: raise ValueError("Not support arbitrary group number for conv3d") if need_layout: out = topi_compute(inputs[0], inputs[1], strides, padding, dilation, layout, out_dtype) else: out = topi_compute(inputs[0], inputs[1], strides, padding, dilation, out_dtype) return [out] return _compute_conv3d @override_native_generic_func("conv3d_strategy") def conv3d_strategy(attrs, inputs, out_type, target): """conv3d generic strategy""" logger.warning("conv3d is not optimized for this platform.") strategy = _op.OpStrategy() layout = attrs.data_layout if layout == "NCDHW": strategy.add_implementation( wrap_compute_conv3d(topi.nn.conv3d_ncdhw), wrap_topi_schedule(topi.generic.schedule_conv3d_ncdhw), name="conv3d_ncdhw.generic", ) elif layout == "NDHWC": strategy.add_implementation( wrap_compute_conv3d(topi.nn.conv3d_ndhwc), wrap_topi_schedule(topi.generic.schedule_conv3d_ndhwc), name="conv3d_ndhwc.generic", ) else: raise ValueError("Not support this layout {} yet".format(layout)) return strategy # conv3d_winograd_without_weight_transform @override_native_generic_func("conv3d_winograd_without_weight_transform_strategy") def conv3d_winograd_without_weight_transfrom_strategy(attrs, inputs, out_type, target): """conv3d_winograd_without_weight_transfrom generic strategy""" raise ValueError("No generic implemenation for conv3d_winograd_without_weight_transform") # conv3d_winograd_weight_transform @generic_func def schedule_conv3d_winograd_weight_transform(attrs, outs, target): """Schedule conv3d_winograd_weight_transform""" with target: return topi.generic.schedule_conv3d_winograd_weight_transform(outs) # conv1d def wrap_compute_conv1d(topi_compute): """wrap conv1d topi compute""" def _compute_conv1d(attrs, inputs, out_type): """Compute definition of conv1d""" strides = get_const_tuple(attrs.strides) padding = get_const_tuple(attrs.padding) dilation = get_const_tuple(attrs.dilation) out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype in ("same", "") else out_dtype return [topi_compute(inputs[0], inputs[1], strides, padding, dilation, out_dtype)] return _compute_conv1d @override_native_generic_func("conv1d_strategy") def conv1d_strategy(attrs, inputs, out_type, target): """conv1d generic strategy""" logger.warning("conv1d is not optimized for this platform.") layout = attrs.data_layout dilation = get_const_tuple(attrs.dilation) if dilation[0] < 1: raise ValueError("dilation should be a positive value") strategy = _op.OpStrategy() if layout == "NCW": strategy.add_implementation( wrap_compute_conv1d(topi.nn.conv1d_ncw), wrap_topi_schedule(topi.generic.schedule_conv1d_ncw), name="conv1d_ncw.generic", ) elif layout == "NWC": strategy.add_implementation( wrap_compute_conv1d(topi.nn.conv1d_nwc), wrap_topi_schedule(topi.generic.schedule_conv1d_nwc), name="conv1d_nwc.generic", ) else: raise ValueError("Unsupported conv1d layout {}".format(layout)) return strategy # conv1d_transpose def wrap_compute_conv1d_transpose(topi_compute): """wrap conv1d_transpose topi compute""" def _compute_conv1d_tranpsoe(attrs, inputs, out_type): padding = get_const_tuple(attrs.padding) strides = get_const_tuple(attrs.strides) out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype in ("same", "") else out_dtype output_padding = get_const_tuple(attrs.output_padding) out = topi_compute(inputs[0], inputs[1], strides, padding, out_dtype, output_padding) return [out] return _compute_conv1d_tranpsoe @override_native_generic_func("conv1d_transpose_strategy") def conv1d_transpose_strategy(attrs, inputs, out_type, target): """conv1d_transpose generic strategy""" logger.warning("conv1d_transpose is not optimized for this platform.") strategy = _op.OpStrategy() layout = attrs.data_layout dilation = get_const_tuple(attrs.dilation) groups = attrs.groups assert layout == "NCW", "conv1d_transpose ncw only supported" assert dilation == (1,), "conv1d_transpose dilation is not supported" assert groups == 1, "conv1d_transpose groups == 1 only supported" strategy.add_implementation( wrap_compute_conv1d_transpose(topi.nn.conv1d_transpose_ncw), wrap_topi_schedule(topi.generic.schedule_conv1d_transpose_ncw), name="conv1d_transpose_ncw.generic", ) return strategy # dilation2d def wrap_compute_dilation2d(topi_compute, need_data_layout=False): """Wrap dilation2d topi compute""" def _compute_dilation2d(attrs, inputs, out_type): padding = get_const_tuple(attrs.padding) strides = get_const_tuple(attrs.strides) dilations = get_const_tuple(attrs.dilations) data_layout = attrs.get_str("data_layout") out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype in ("same", "") else out_dtype args = [inputs[0], inputs[1], strides, padding, dilations] if need_data_layout: args.append(data_layout) args.append(out_dtype) return [topi_compute(*args)] return _compute_dilation2d @override_native_generic_func("dilation2d_strategy") def dilation2d_strategy(attrs, inputs, out_type, target): """dilation2d_strategy generic strategy""" logger.warning("dilation2d_strategy is not optimized for this platform.") strategy = _op.OpStrategy() dilations = get_const_tuple(attrs.dilations) layout = attrs.data_layout kernel_layout = attrs.kernel_layout assert layout in ["NCHW", "NHWC"] (dilation_h, dilation_w) = dilations if dilation_h < 1 or dilation_w < 1: raise ValueError("dilation should be positive value") if layout == "NCHW": assert kernel_layout == "IHW" strategy.add_implementation( wrap_compute_dilation2d(topi.image.dilation2d_nchw), wrap_topi_schedule(topi.generic.schedule_dilation2d_nchw), name="dilation2d_nchw.generic", ) elif layout == "NHWC": assert kernel_layout == "HWI" strategy.add_implementation( wrap_compute_dilation2d(topi.image.dilation2d_nhwc), wrap_topi_schedule(topi.generic.schedule_dilation2d_nhwc), name="dilation2d_nhwc.generic", ) else: raise RuntimeError("Unsupported dilation2d layout {}".format(layout)) return strategy # dense def wrap_compute_dense(topi_compute): """wrap dense topi compute""" def _compute_dense(attrs, inputs, out_type): """Compute definition of dense""" out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype == "" else out_dtype return [topi_compute(inputs[0], inputs[1], None, out_dtype)] return _compute_dense @override_native_generic_func("dense_strategy") def dense_strategy(attrs, inputs, out_type, target): """dense generic strategy""" logger.warning("dense is not optimized for this platform.") strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_dense(topi.nn.dense), wrap_topi_schedule(topi.generic.schedule_dense), name="dense.generic", ) return strategy # batch_matmul def wrap_compute_batch_matmul(topi_compute): """wrap batch_matmul topi compute""" def _compute_batch_matmul(attrs, inputs, out_type): return [topi_compute(inputs[0], inputs[1], out_type.shape)] return _compute_batch_matmul @override_native_generic_func("batch_matmul_strategy") def batch_matmul_strategy(attrs, inputs, out_type, target): """batch_matmul generic strategy""" logger.warning("batch_matmul is not optimized for this platform.") strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_batch_matmul(topi.nn.batch_matmul), wrap_topi_schedule(topi.generic.schedule_batch_matmul), name="batch_matmul.generic", ) return strategy # sparse dense def wrap_compute_sparse_dense(topi_compute): """wrap sparse dense topi compute""" def _compute_sparse_dense(attrs, inputs, out_type): return [topi_compute(inputs[0], inputs[1], inputs[2], inputs[3], attrs["sparse_lhs"])] return _compute_sparse_dense @override_native_generic_func("sparse_dense_strategy") def sparse_dense_strategy(attrs, inputs, out_type, target): """sparse dense generic strategy""" logger.warning("sparse dense is not optimized for this platform.") strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_sparse_dense(topi.nn.sparse_dense), wrap_topi_schedule(topi.generic.schedule_sparse_dense), name="sparse_dense.generic", ) return strategy @override_native_generic_func("sparse_dense_padded_strategy") def sparse_dense_padded_strategy(attrs, inputs, out_type, target): """sparse dense padded generic strategy""" raise NotImplementedError("sparse_dense_padded is only implemented for cuda") # sparse_transpose @generic_func def schedule_sparse_transpose(attrs, outs, target): """schedule sparse_transpose""" with target: return topi.generic.schedule_sparse_transpose(outs) # argsort def wrap_compute_argsort(topi_compute): """Wrap argsort topi compute""" def _compute_argsort(attrs, inputs, _): axis = get_const_int(attrs.axis) is_ascend = bool(get_const_int(attrs.is_ascend)) dtype = attrs.dtype return [topi_compute(inputs[0], axis=axis, is_ascend=is_ascend, dtype=dtype)] return _compute_argsort @override_native_generic_func("argsort_strategy") def argsort_strategy(attrs, inputs, out_type, target): """argsort generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_argsort(topi.argsort), wrap_topi_schedule(topi.generic.schedule_argsort), name="argsort.generic", ) return strategy # topk def wrap_compute_topk(topi_compute): """Wrap topk compute""" def _compute_topk(attrs, inputs, out_type): if attrs.k is not None: k = attrs.k else: k = inputs[1] axis = get_const_int(attrs.axis) ret_type = attrs.ret_type is_ascend = bool(get_const_int(attrs.is_ascend)) dtype = attrs.dtype out = topi_compute(inputs[0], k, axis, ret_type, is_ascend, dtype) out = out if isinstance(out, list) else [out] return out return _compute_topk @override_native_generic_func("topk_strategy") def topk_strategy(attrs, inputs, out_type, target): """topk generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_topk(topi.topk), wrap_topi_schedule(topi.generic.schedule_topk), name="topk.generic", ) return strategy # multibox_prior def wrap_compute_multibox_prior(topi_compute): """Wrap multibox_prior compute""" def _compute_multibox_prior(attrs, inputs, _): """Compute definition of multibox_prior""" sizes = get_float_tuple(attrs.sizes) ratios = get_float_tuple(attrs.ratios) steps = get_float_tuple(attrs.steps) offsets = get_float_tuple(attrs.offsets) clip = bool(get_const_int(attrs.clip)) return [topi_compute(inputs[0], sizes, ratios, steps, offsets, clip)] return _compute_multibox_prior @override_native_generic_func("multibox_prior_strategy") def multibox_prior_strategy(attrs, inputs, out_type, target): """multibox_prior generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_multibox_prior(topi.vision.ssd.multibox_prior), wrap_topi_schedule(topi.generic.schedule_multibox_prior), name="multibox_prior.generic", ) return strategy # multibox_transform_loc def wrap_compute_multibox_transform_loc(topi_compute): """Wrap multibox_transform_loc compute""" def _compute_multibox_transform_loc(attrs, inputs, _): """Compute definition of multibox_detection""" clip = bool(get_const_int(attrs.clip)) threshold = get_const_float(attrs.threshold) variances = get_float_tuple(attrs.variances) return topi_compute(inputs[0], inputs[1], inputs[2], clip, threshold, variances) return _compute_multibox_transform_loc @override_native_generic_func("multibox_transform_loc_strategy") def multibox_transform_loc_strategy(attrs, inputs, out_type, target): """schedule multibox_transform_loc""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_multibox_transform_loc(topi.vision.ssd.multibox_transform_loc), wrap_topi_schedule(topi.generic.schedule_multibox_transform_loc), name="multibox_transform_loc.generic", ) return strategy # get_valid_counts def wrap_compute_get_valid_counts(topi_compute): """wrap get_valid_counts topi compute""" def _compute_get_valid_counts(attrs, inputs, out_type): score_threshold = inputs[1] id_index = get_const_int(attrs.id_index) score_index = get_const_int(attrs.score_index) if attrs.score_threshold is not None: score_threshold = get_const_float(attrs.score_threshold) return topi_compute(inputs[0], score_threshold, id_index, score_index) return _compute_get_valid_counts @override_native_generic_func("get_valid_counts_strategy") def get_valid_counts_strategy(attrs, inputs, out_type, target): """get_valid_counts generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_get_valid_counts(topi.vision.get_valid_counts), wrap_topi_schedule(topi.generic.schedule_get_valid_counts), name="get_valid_counts.generic", ) return strategy # non-maximum suppression def wrap_compute_nms(topi_compute): """wrap nms topi compute""" def _compute_nms(attrs, inputs, out_type): max_output_size = inputs[3] iou_threshold = inputs[4] if attrs.max_output_size is not None: max_output_size = attrs.max_output_size if attrs.iou_threshold is not None: iou_threshold = get_const_float(attrs.iou_threshold) return_indices = bool(get_const_int(attrs.return_indices)) force_suppress = bool(get_const_int(attrs.force_suppress)) top_k = get_const_int(attrs.top_k) coord_start = get_const_int(attrs.coord_start) score_index = get_const_int(attrs.score_index) id_index = get_const_int(attrs.id_index) invalid_to_bottom = bool(get_const_int(attrs.invalid_to_bottom)) if return_indices: return topi_compute( inputs[0], inputs[1], inputs[2], max_output_size, iou_threshold, force_suppress, top_k, coord_start, score_index, id_index, return_indices, invalid_to_bottom, ) return [ topi_compute( inputs[0], inputs[1], inputs[2], max_output_size, iou_threshold, force_suppress, top_k, coord_start, score_index, id_index, return_indices, invalid_to_bottom, ) ] return _compute_nms @override_native_generic_func("non_max_suppression_strategy") def nms_strategy(attrs, inputs, out_type, target): """nms generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_nms(topi.vision.non_max_suppression), wrap_topi_schedule(topi.generic.schedule_nms), name="nms.generic", ) return strategy # roi_align def wrap_compute_roi_align(topi_compute): """wrap roi_align topi compute""" def _compute_roi_align(attrs, inputs, out_type): assert attrs.layout == "NCHW" pooled_size = get_const_tuple(attrs.pooled_size) return [ topi_compute( inputs[0], inputs[1], pooled_size=pooled_size, spatial_scale=attrs.spatial_scale, sample_ratio=attrs.sample_ratio, ) ] return _compute_roi_align @override_native_generic_func("roi_align_strategy") def roi_align_strategy(attrs, inputs, out_type, target): """roi_align generic strategy""" strategy = _op.OpStrategy() layout = attrs.layout assert layout == "NCHW", "only support nchw for now" strategy.add_implementation( wrap_compute_roi_align(topi.vision.rcnn.roi_align_nchw), wrap_topi_schedule(topi.generic.schedule_roi_align), name="roi_align.generic", ) return strategy # roi_pool @generic_func def schedule_roi_pool(attrs, outs, target): """schedule roi_pool""" with target: return topi.generic.schedule_roi_pool(outs) # proposal def wrap_compute_proposal(topi_compute): """wrap proposal topi compute""" def _compute_proposal(attrs, inputs, out_type): scales = get_float_tuple(attrs.scales) ratios = get_float_tuple(attrs.ratios) feature_stride = attrs.feature_stride threshold = attrs.threshold rpn_pre_nms_top_n = attrs.rpn_pre_nms_top_n rpn_post_nms_top_n = attrs.rpn_post_nms_top_n rpn_min_size = attrs.rpn_min_size iou_loss = bool(get_const_int(attrs.iou_loss)) return [ topi_compute( inputs[0], inputs[1], inputs[2], scales, ratios, feature_stride, threshold, rpn_pre_nms_top_n, rpn_post_nms_top_n, rpn_min_size, iou_loss, ) ] return _compute_proposal @override_native_generic_func("proposal_strategy") def proposal_strategy(attrs, inputs, out_type, target): """proposal generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_proposal(topi.vision.rcnn.proposal), wrap_topi_schedule(topi.generic.schedule_proposal), name="proposal.generic", ) return strategy # scatter @override_native_generic_func("scatter_strategy")
strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_scatter(topi.scatter), wrap_topi_schedule(topi.generic.schedule_scatter), name="scatter.generic", ) return strategy def wrap_compute_scatter(topi_compute): """Wrap scatter topi compute""" def _compute_scatter(attrs, inputs, _): return [topi_compute(inputs[0], inputs[1], inputs[2], axis=attrs.axis)] return _compute_scatter @override_native_generic_func("scatter_add_strategy") def scatter_add_strategy(attrs, outs, out_type, target): strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_scatter(topi.scatter_add), wrap_topi_schedule(topi.generic.schedule_scatter), name="scatter_add.generic", ) return strategy # scatter_nd @override_native_generic_func("scatter_nd_strategy") def scatter_nd_strategy(attrs, inputs, out_type, target): """scatter_nd generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_scatter_nd(topi.scatter_nd), wrap_topi_schedule(topi.generic.schedule_extern), name="scatter_nd.generic", ) return strategy def wrap_compute_scatter_nd(topi_compute): """Wrap scatter_nd topi compute""" def _compute_scatter_nd(attrs, inputs, _): return [topi_compute(inputs[0], inputs[1], attrs.out_shape)] return _compute_scatter_nd # bitserial_conv2d def wrap_compute_bitserial_conv2d(topi_compute): """wrap bitserial_conv2d topi compute""" def compute_bitserial_conv2d(attrs, inputs, out_dtype): """Compute definition for bitserial conv2d.""" padding = get_const_tuple(attrs.padding) strides = get_const_tuple(attrs.strides) activation_bits = attrs.activation_bits weight_bits = attrs.weight_bits pack_dtype = attrs.pack_dtype out_dtype = attrs.out_dtype unipolar = attrs.unipolar return [ topi_compute( inputs[0], inputs[1], strides, padding, activation_bits, weight_bits, pack_dtype, out_dtype, unipolar, ) ] return compute_bitserial_conv2d @override_native_generic_func("bitserial_conv2d_strategy") def bitserial_conv2d_strategy(attrs, inputs, out_type, target): """bitserial_conv2d generic strategy""" logger.warning("bitserial_conv2d is not optimized for this platform.") strategy = _op.OpStrategy() layout = attrs.data_layout if layout == "NCHW": strategy.add_implementation( wrap_compute_bitserial_conv2d(topi.nn.bitserial_conv2d_nchw), wrap_topi_schedule(topi.generic.schedule_bitserial_conv2d_nchw), name="bitserial_conv2d_nchw.generic", ) elif layout == "NHWC": strategy.add_implementation( wrap_compute_bitserial_conv2d(topi.nn.bitserial_conv2d_nhwc), wrap_topi_schedule(topi.generic.schedule_bitserial_conv2d_nhwc), name="bitserial_conv2d_nhwc.generic", ) else: raise ValueError("Data layout {} not supported.".format(layout)) return strategy # bitserial_dense def wrap_compute_bitserial_dense(topi_compute): """wrap bitserial_dense topi compute""" def compute_bitserial_dense(attrs, inputs, out_type): """Compute definition of bitserial dense""" data_bits = attrs.data_bits weight_bits = attrs.weight_bits pack_dtype = attrs.pack_dtype out_dtype = attrs.out_dtype out_dtype = inputs[0].dtype if out_dtype == "" else out_dtype unipolar = attrs.unipolar return [ topi_compute( inputs[0], inputs[1], data_bits, weight_bits, pack_dtype, out_dtype, unipolar ) ] return compute_bitserial_dense @override_native_generic_func("bitserial_dense_strategy") def bitserial_dense_strategy(attrs, inputs, out_type, target): """bitserial_dense generic strategy""" logger.warning("bitserial_dense is not optimized for this platform.") strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_bitserial_dense(topi.nn.bitserial_dense), wrap_topi_schedule(topi.generic.schedule_bitserial_dense), name="bitserial_dense.generic", ) return strategy # correlation def wrap_compute_correlation(topi_compute): """wrap correlation topi compute""" def _compute_correlation(attrs, inputs, out_type): kernel_size = attrs.kernel_size max_displacement = attrs.max_displacement stride1 = attrs.stride1 stride2 = attrs.stride2 padding = get_const_tuple(attrs.padding) is_multiply = attrs.is_multiply return [ topi_compute( inputs[0], inputs[1], kernel_size, max_displacement, stride1, stride2, padding, is_multiply, ) ] return _compute_correlation @override_native_generic_func("correlation_strategy") def correlation_strategy(attrs, inputs, out_type, target): """correlation generic strategy""" logger.warning("correlation is not optimized for this platform.") layout = attrs.layout assert layout == "NCHW", "Only support NCHW layout" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_correlation(topi.nn.correlation_nchw), wrap_topi_schedule(topi.generic.schedule_correlation_nchw), name="correlation.generic", ) return strategy # argwhere def wrap_compute_argwhere(topi_compute): """wrap argwhere topi compute""" def _compute_argwhere(attrs, inputs, out_type): output_shape = [] for s in out_type.shape: if hasattr(s, "value"): output_shape.append(s) else: output_shape.append(te.var("any_dim", "int32")) new_output_type = ir.TensorType(output_shape, "int32") return [topi_compute(new_output_type, inputs[0])] return _compute_argwhere @override_native_generic_func("argwhere_strategy") def argwhere_strategy(attrs, inputs, out_type, target): """argwhere generic strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_argwhere(topi.argwhere), wrap_topi_schedule(topi.generic.schedule_argwhere), name="argwhere.generic", ) return strategy
def scatter_strategy(attrs, outs, out_type, target):
main.rs
use hello_macro::HelloMacro; struct Pancakes; impl HelloMacro for Pancakes { fn
() { println!("Hello, Macro! My name is Pancakes!"); } } fn main() { Pancakes::hello_macro(); }
hello_macro
logic.rs
use chrono::{DateTime, Utc}; use uuid::Uuid; use super::{FromStr, HashMap, MatchCondition, Types}; pub(crate) fn read_match_args(chars: &mut std::str::Chars) -> Result<Vec<MatchCondition>, String> { let base = chars .skip_while(|c| c == &'(' || c.is_whitespace()) .take_while(|c| c != &')') .collect::<String>() .trim() .to_string(); let mut conditions: Vec<MatchCondition> = Vec::new(); base.split(',') .filter(|l| !l.is_empty()) .map(|l| { let k = l .split(' ') .filter(|f| !f.is_empty()) .collect::<Vec<&str>>(); let mut c = k[2].chars(); match k.get(1) { Some(&"==") => Ok(MatchCondition::Eq( k[0].to_string(), parse_value( c.next() .ok_or_else(|| String::from("Not able to parse match argument"))?, &mut c, )?, )), Some(&"!=") => Ok(MatchCondition::NotEq( k[0].to_string(), parse_value( c.next() .ok_or_else(|| String::from("Not able to parse match argument"))?, &mut c, )?, )), Some(&">=") => Ok(MatchCondition::GEq( k[0].to_string(), parse_value( c.next() .ok_or_else(|| String::from("Not able to parse match argument"))?, &mut c, )?, )), Some(&"<=") => Ok(MatchCondition::LEq( k[0].to_string(), parse_value( c.next() .ok_or_else(|| String::from("Not able to parse match argument"))?, &mut c, )?, )), Some(&">") => Ok(MatchCondition::G( k[0].to_string(), parse_value( c.next() .ok_or_else(|| String::from("Not able to parse match argument"))?, &mut c, )?, )), Some(&"<") => Ok(MatchCondition::L( k[0].to_string(), parse_value( c.next() .ok_or_else(|| String::from("Not able to parse match argument"))?, &mut c, )?, )), _ => Err(String::from("Unidentified Match Condition")), } }) .try_for_each(|e: Result<MatchCondition, String>| { conditions.push(e?); Ok::<(), String>(()) })?; Ok(conditions) } pub(crate) fn read_map(chars: &mut std::str::Chars) -> Result<HashMap<String, Types>, String> { let mut res: HashMap<String, Types> = HashMap::new(); let mut key: Option<String> = None; let mut val: Option<Types> = None; loop { match chars.next() { Some(' ') => (), Some('{') => break, _ => { return Err(String::from( "Entity map should start with `{` and end with `}`", )) } } } loop { match chars.next() { Some('}') => return Ok(res), Some('{') => { if key.is_some() { val = Some(Types::Map(read_inner_map(chars)?)); } else { return Err(String::from("Key must be an alphanumeric value")); } } Some('[') => { if key.is_some() { val = Some(Types::Vector(read_vec(chars)?)); } else { return Err(String::from("Key must be an alphanumeric value")); } } Some(c) if !c.is_whitespace() && c != ',' => { if key.is_some() { val = Some(parse_value(c, chars)?); } else { key = Some(parse_key(c, chars)); } } Some(c) if c.is_whitespace() || c == ',' => (), _ => return Err(String::from("Entity HashMap could not be created")), } if key.is_some() && val.is_some() { res.insert(key.unwrap().to_string(), val.unwrap()); key = None; val = None; } } } pub(crate) fn read_map_as_str( chars: &mut std::str::Chars, ) -> Result<HashMap<String, String>, String>
pub(crate) fn read_inner_map( chars: &mut std::str::Chars, ) -> Result<HashMap<String, Types>, String> { let mut res: HashMap<String, Types> = HashMap::new(); let mut key: Option<String> = None; let mut val: Option<Types> = None; loop { match chars.next() { Some('}') => return Ok(res), Some('{') => { if key.is_some() { val = Some(Types::Map(read_inner_map(chars)?)); } else { return Err(String::from("Key must be an alphanumeric value")); } } Some('[') => { if key.is_some() { val = Some(Types::Vector(read_vec(chars)?)); } else { return Err(String::from("Key must be an alphanumeric value")); } } Some(c) if !c.is_whitespace() && c != ',' => { if key.is_some() { val = Some(parse_value(c, chars)?); } else { key = Some(parse_key(c, chars)); } } Some(c) if c.is_whitespace() || c == ',' => (), _ => return Err(String::from("Entity HashMap could not be created")), } if key.is_some() && val.is_some() { res.insert(key.unwrap().to_string(), val.unwrap()); key = None; val = None; } } } fn read_vec(chars: &mut std::str::Chars) -> Result<Vec<Types>, String> { let mut res: Vec<Types> = vec![]; loop { match chars.next() { Some(']') => return Ok(res), Some('[') => res.push(Types::Vector(read_vec(chars)?)), Some('{') => res.push(Types::Map(read_inner_map(chars)?)), Some(c) if !c.is_whitespace() && c != ',' => { res.push(parse_value(c, chars)?); } Some(c) if c.is_whitespace() || c == ',' => (), err => return Err(format!("{:?} could not be parsed at char", err)), } } } pub(crate) fn read_select_args(chars: &mut std::str::Chars) -> Result<Vec<String>, String> { let mut res = Vec::new(); if chars.next() != Some('{') { return Err(String::from( "SELECT arguments set should start with `#{` and end with `}`", )); } loop { match chars.next() { Some('}') => return Ok(res), Some(c) if !c.is_whitespace() && c != ',' => { let key_rest = chars .take_while(|c| c.is_alphanumeric() || c == &'_') .collect::<String>(); let key = format!("{}{}", c, key_rest); res.push(key); } Some(c) if c.is_whitespace() || c == ',' => (), err => return Err(format!("{:?} could not be parsed at char", err)), } } } pub(crate) fn read_args(chars: &mut std::str::Chars) -> Result<Vec<String>, String> { let mut res = Vec::new(); if chars.next() != Some('{') { return Err(String::from( "Arguments set should start with `#{` and end with `}`", )); } loop { match chars.next() { Some('}') => return Ok(res), Some(c) if !c.is_whitespace() && c != ',' => { let key_rest = chars .skip_while(|c| c.is_whitespace()) .take_while(|c| c.is_alphanumeric() || c == &'_') .collect::<String>() .trim() .to_owned(); let key = format!("{}{}", c, key_rest); res.push(key); } Some(c) if c.is_whitespace() || c == ',' => (), err => return Err(format!("{:?} could not be parsed at char", err)), } } } pub(crate) fn parse_key(c: char, chars: &mut std::str::Chars) -> String { let key_rest = chars .take_while(|c| c.is_alphanumeric() || c == &'_') .collect::<String>(); format!("{}{}", c, key_rest) } pub fn parse_value(c: char, chars: &mut std::str::Chars) -> Result<Types, String> { if c == '"' { return read_str(chars); } let value = format!( "{}{}", c, chars .take_while(|c| !c.is_whitespace() && c != &',') .collect::<String>() ); if value.ends_with('P') && value[..value.len() - 1].parse::<f64>().is_ok() { Ok(Types::Precise(value[..value.len() - 1].to_string())) } else if value.parse::<isize>().is_ok() { Ok(Types::Integer(value.parse().unwrap())) } else if value.parse::<f64>().is_ok() { Ok(Types::Float(value.parse().unwrap())) } else if uuid::Uuid::from_str(&value).is_ok() { Ok(Types::Uuid(uuid::Uuid::from_str(&value).unwrap())) } else if value.parse::<bool>().is_ok() { Ok(Types::Boolean(value.parse().unwrap())) } else if &value.to_lowercase() == "nil" { Ok(Types::Nil) } else if value.starts_with('\'') && value.ends_with('\'') && value.len() == 3 { Ok(Types::Char(value.chars().nth(1).unwrap())) } else if value.parse::<DateTime<Utc>>().is_ok() { Ok(Types::DateTime(value.parse::<DateTime<Utc>>().unwrap())) } else { Err(format!("Value Type could not be created from {}", value)) } } pub(crate) fn parse_str_value(c: char, chars: &mut std::str::Chars) -> String { format!( "{}{}", c, chars .take_while(|c| !c.is_whitespace() && c != &',') .collect::<String>() ) .replace('\"', "") } pub(crate) fn read_str(chars: &mut std::str::Chars) -> Result<Types, String> { let result = chars.try_fold((false, String::new()), |(last_was_escape, mut s), c| { if last_was_escape { // Supported escape characters, per https://github.com/edn-format/edn#strings match c { 't' => s.push('\t'), 'r' => s.push('\r'), 'n' => s.push('\n'), '\\' => s.push('\\'), '\"' => s.push('\"'), _ => return Err(Err(format!("Invalid escape sequence \\{}", c))), }; Ok((false, s)) } else if c == '\"' { // Unescaped quote means we're done Err(Ok(s)) } else if c == '\\' { Ok((true, s)) } else { s.push(c); Ok((false, s)) } }); match result { // An Ok means we actually finished parsing *without* seeing the end of the string, so that's // an error. Ok(_) => Err("Unterminated string".to_string()), Err(Err(e)) => Err(e), Err(Ok(string)) => Ok(Types::String(string)), } } pub(crate) fn read_uuids(chars: &mut std::str::Chars) -> Result<Vec<Uuid>, String> { let mut uuids = Vec::new(); let mut uuid = String::new(); loop { match chars.next() { Some(' ') | Some('#') | Some('{') => (), Some(l) if l.is_alphanumeric() => uuid.push(l), Some(dash) if dash == '-' => uuid.push(dash), Some(',') => { uuids.push(Uuid::from_str(&uuid).map_err(|e| { format!("Couldn't creat an Uuid from {:?}. Error {:?}", uuid, e) })?); uuid = String::new(); } Some('}') => return Ok(uuids), _ => { return Err(String::from( "Uuids in `IDS IN` are reuired to be inside a `#{` and `}`", )) } } } } // UNSAFE pub(crate) fn integer_decode(val: f64) -> u64 { val.to_bits() }
{ let mut res: HashMap<String, String> = HashMap::new(); let mut key: Option<String> = None; let mut val: Option<String> = None; loop { match chars.next() { Some(' ') => (), Some('{') => break, _ => { return Err(String::from( "Entity map should start with `{` and end with `}`", )) } } } loop { match chars.next() { Some('}') => return Ok(res), Some(c) if !c.is_whitespace() && c != ',' => { if key.is_some() { val = Some(parse_str_value(c, chars)); } else { key = Some(parse_key(c, chars)); } } Some(c) if c.is_whitespace() || c == ',' => (), _ => return Err(String::from("Entity HashMap could not be created")), } if key.is_some() && val.is_some() { res.insert(key.unwrap().to_string(), val.unwrap()); key = None; val = None; } } }
removeAttributeFiltersHandler.ts
// (C) 2021 GoodData Corporation import { call, put, select } from "redux-saga/effects"; import { SagaIterator } from "redux-saga"; import { batchActions } from "redux-batched-actions"; import difference from "lodash/difference"; import partition from "lodash/partition"; import { RemoveAttributeFilters } from "../../../commands/filters"; import { invalidArgumentsProvided } from "../../../events/general"; import { attributeFilterRemoved } from "../../../events/filters"; import { filterContextActions } from "../../../store/filterContext"; import { selectFilterContextAttributeFilters } from "../../../store/filterContext/filterContextSelectors"; import { DashboardContext } from "../../../types/commonTypes"; import { dispatchFilterContextChanged } from "../common"; import { dispatchDashboardEvent } from "../../../store/_infra/eventDispatcher"; import { layoutActions } from "../../../store/layout"; export function* removeAttributeFiltersHandler( ctx: DashboardContext, cmd: RemoveAttributeFilters, ): SagaIterator<void> { const { filterLocalIds } = cmd.payload; const allFilters: ReturnType<typeof selectFilterContextAttributeFilters> = yield select( selectFilterContextAttributeFilters, ); const [removedFilters, survivingFilters] = partition(allFilters, (item) => filterLocalIds.includes(item.attributeFilter.localIdentifier!), ); const invalidLocalIds = difference( filterLocalIds, allFilters.map((filter) => filter.attributeFilter.localIdentifier), ); if (invalidLocalIds.length) { throw invalidArgumentsProvided( ctx, cmd, `Invalid filterLocalIds provided. These ids were not found: ${invalidLocalIds.join(", ")}.`, ); } for (const removedFilter of removedFilters) { const affectedChildren = survivingFilters.filter((item) => item.attributeFilter.filterElementsBy?.some((parent) => filterLocalIds.includes(parent.filterLocalIdentifier), ), ); const batch = batchActions([ // remove filter from parents and keep track of the affected filters ...affectedChildren.map(({ attributeFilter }) => filterContextActions.setAttributeFilterParents({ filterLocalId: attributeFilter.localIdentifier!, parentFilters: attributeFilter.filterElementsBy!.filter( (parent) => parent.filterLocalIdentifier !== removedFilter?.attributeFilter.localIdentifier, ), }), ), // remove filter itself filterContextActions.removeAttributeFilter({
}), // remove filter's display form metadata object filterContextActions.removeAttributeFilterDisplayForms(removedFilter.attributeFilter.displayForm), // house-keeping: ensure the removed attribute filter disappears from widget ignore lists layoutActions.removeIgnoredAttributeFilter({ displayFormRefs: [removedFilter.attributeFilter.displayForm], }), ]); yield put(batch); yield dispatchDashboardEvent( attributeFilterRemoved(ctx, removedFilter!, affectedChildren, cmd.correlationId), ); } yield call(dispatchFilterContextChanged, ctx, cmd); }
filterLocalId: removedFilter.attributeFilter.localIdentifier!,
index.d.ts
declare namespace ModbusRTU { interface IModbusRTU { new(port?: any): IModbusRTU; open(callback: Function): void; close(callback: Function): void; writeFC1(address: number, dataAddress: number, length: number, next: NodeStyleCallback<ReadCoilResult>): void; writeFC2(address: number, dataAddress: number, length: number, next: NodeStyleCallback<ReadCoilResult>): void; writeFC3(address: number, dataAddress: number, length: number, next: NodeStyleCallback<ReadRegisterResult>): void; writeFC4(address: number, dataAddress: number, length: number, next: NodeStyleCallback<ReadRegisterResult>): void; writeFC5(address: number, dataAddress: number, state: boolean, next: NodeStyleCallback<WriteCoilResult>): void; writeFC6(address: number, dataAddress: number, value: number, next: NodeStyleCallback<WriteRegisterResult>): void; writeFC15(address: number, dataAddress: number, states: Array<boolean>, next: NodeStyleCallback<WriteMultipleResult>): void; writeFC16(address: number, dataAddress: number, values: Array<number>, next: NodeStyleCallback<WriteMultipleResult>): void; // Connection shorthand API connectRTU(path: string, options: SerialPortOptions, next: Function): void; connectRTU(path: string, options: SerialPortOptions): Promise<void>; connectTCP(ip: string, options: TcpPortOptions, next: Function): void; connectTCP(ip: string, options: TcpPortOptions): Promise<void>; connectTcpRTUBuffered(ip: string, options: TcpRTUPortOptions, next: Function): void; connectTcpRTUBuffered(ip: string, options: TcpRTUPortOptions): Promise<void>; connectTelnet(ip: string, options: TelnetPortOptions, next: Function): void; connectTelnet(ip: string, options: TelnetPortOptions): Promise<void>; connectC701(ip: string, options: C701PortOptions, next: Function): void; connectC701(ip: string, options: C701PortOptions): Promise<void>; connectRTUBuffered(path: string, options: SerialPortOptions, next: Function): void; connectRTUBuffered(path: string, options: SerialPortOptions): Promise<void>; connectAsciiSerial(path: string, options: SerialPortOptions, next: Function): void; connectAsciiSerial(path: string, options: SerialPortOptions): Promise<void>; // Promise API setID(id: number): void; getID(): number; setTimeout(duration: number): void; getTimeout(): number; readCoils(dataAddress: number, length: number): Promise<ReadCoilResult>; readDiscreteInputs(dataAddress: number, length: number): Promise<ReadCoilResult>; readHoldingRegisters(dataAddress: number, length: number): Promise<ReadRegisterResult>; readInputRegisters(dataAddress: number, length: number): Promise<ReadRegisterResult>; writeCoil(dataAddress: number, state: boolean): Promise<WriteCoilResult>; writeCoils(dataAddress: number, states: Array<boolean>): Promise<WriteMultipleResult>; writeRegister(dataAddress: number, value: number): Promise<WriteRegisterResult>; writeRegisters(dataAddress: number, values: Array<number>): Promise<WriteMultipleResult>; // 16 } interface NodeStyleCallback<T> { (err: NodeJS.ErrnoException, param: T): void; } interface ReadCoilResult { data: Array<boolean>; buffer: Buffer; } interface ReadRegisterResult { data: Array<number>; buffer: Buffer; } interface WriteCoilResult { address: number; state: boolean; } interface WriteRegisterResult { address: number; value: number; } interface WriteMultipleResult { address: number; length: number; } interface SerialPortOptions { baudRate?: number; dataBits?: number;
stopBits?: number; parity?: 'none' | 'even' | 'mark' | 'odd' | 'space'; rtscts?: boolean; xon?: boolean; xoff?: boolean; xany?: boolean; flowControl?: boolean | Array<string>; bufferSize?: number; parser?: any; platformOptions?: SerialPortUnixPlatformOptions; } interface SerialPortUnixPlatformOptions { vmin?: number; vtime?: number; } interface TcpPortOptions { port?: number; } interface TcpRTUPortOptions { port?: number; } interface TelnetPortOptions { port?: number; } interface C701PortOptions { port?: number; } } declare var ModbusRTU: ModbusRTU.IModbusRTU; export = ModbusRTU ;
mod.rs
//! Rustdoc's HTML rendering module. //! //! This modules contains the bulk of the logic necessary for rendering a //! rustdoc `clean::Crate` instance to a set of static HTML pages. This //! rendering process is largely driven by the `format!` syntax extension to //! perform all I/O into files and streams. //! //! The rendering process is largely driven by the `Context` and `Cache` //! structures. The cache is pre-populated by crawling the crate in question, //! and then it is shared among the various rendering threads. The cache is meant //! to be a fairly large structure not implementing `Clone` (because it's shared //! among threads). The context, however, should be a lightweight structure. This //! is cloned per-thread and contains information about what is currently being //! rendered. //! //! In order to speed up rendering (mostly because of markdown rendering), the //! rendering process has been parallelized. This parallelization is only //! exposed through the `crate` method on the context, and then also from the //! fact that the shared cache is stored in TLS (and must be accessed as such). //! //! In addition to rendering the crate itself, this module is also responsible //! for creating the corresponding search index and source file renderings. //! These threads are not parallelized (they haven't been a bottleneck yet), and //! both occur before the crate is rendered. crate mod cache; #[cfg(test)] mod tests; mod context; mod print_item; mod span_map; mod templates; mod write_shared; crate use context::*; crate use span_map::{collect_spans_and_sources, LinkFromSrc}; use std::collections::VecDeque; use std::default::Default; use std::fmt; use std::fs; use std::iter::Peekable; use std::path::PathBuf; use std::str; use std::string::ToString; use rustc_ast_pretty::pprust; use rustc_attr::{ConstStability, Deprecation, StabilityLevel}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::CtorKind; use rustc_hir::def_id::DefId; use rustc_hir::Mutability; use rustc_middle::middle::stability; use rustc_middle::ty::TyCtxt; use rustc_span::{ symbol::{kw, sym, Symbol}, BytePos, FileName, RealFileName, }; use serde::ser::SerializeSeq; use serde::{Serialize, Serializer}; use crate::clean::{self, ItemId, RenderedLink, SelfTy}; use crate::docfs::PathError; use crate::error::Error; use crate::formats::cache::Cache; use crate::formats::item_type::ItemType; use crate::formats::{AssocItemRender, Impl, RenderMode}; use crate::html::escape::Escape; use crate::html::format::{ href, print_abi_with_space, print_constness_with_space, print_default_space, print_generic_bounds, print_where_clause, Buffer, HrefError, PrintWithSpace, }; use crate::html::highlight; use crate::html::markdown::{HeadingOffset, Markdown, MarkdownHtml, MarkdownSummaryLine}; use crate::html::sources; use crate::scrape_examples::CallData; use crate::try_none; /// A pair of name and its optional document. crate type NameDoc = (String, Option<String>); crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ { crate::html::format::display_fn(move |f| { if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) } }) } // Helper structs for rendering items/sidebars and carrying along contextual // information /// Struct representing one entry in the JS search index. These are all emitted /// by hand to a large JS file at the end of cache-creation. #[derive(Debug)] crate struct IndexItem { crate ty: ItemType, crate name: String, crate path: String, crate desc: String, crate parent: Option<DefId>, crate parent_idx: Option<usize>, crate search_type: Option<IndexItemFunctionType>, crate aliases: Box<[String]>, } /// A type used for the search index. #[derive(Debug)] crate struct RenderType { name: Option<String>, generics: Option<Vec<TypeWithKind>>, } /// Full type of functions/methods in the search index. #[derive(Debug)] crate struct IndexItemFunctionType { inputs: Vec<TypeWithKind>, output: Option<Vec<TypeWithKind>>, } impl Serialize for IndexItemFunctionType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { // If we couldn't figure out a type, just write `null`. let mut iter = self.inputs.iter(); if match self.output { Some(ref output) => iter.chain(output.iter()).any(|i| i.ty.name.is_none()), None => iter.any(|i| i.ty.name.is_none()), } { serializer.serialize_none() } else { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element(&self.inputs)?; if let Some(output) = &self.output { if output.len() > 1 { seq.serialize_element(&output)?; } else { seq.serialize_element(&output[0])?; } } seq.end() } } } #[derive(Debug)] crate struct TypeWithKind { ty: RenderType, kind: ItemType, } impl From<(RenderType, ItemType)> for TypeWithKind { fn from(x: (RenderType, ItemType)) -> TypeWithKind { TypeWithKind { ty: x.0, kind: x.1 } } } impl Serialize for TypeWithKind { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element(&self.ty.name)?; seq.serialize_element(&self.kind)?; if let Some(generics) = &self.ty.generics { seq.serialize_element(generics)?; } seq.end() } } #[derive(Debug, Clone)] crate struct StylePath { /// The path to the theme crate path: PathBuf, /// What the `disabled` attribute should be set to in the HTML tag crate disabled: bool, } fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) { if let Some(l) = cx.src_href(item) { write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l) } } #[derive(Debug, Eq, PartialEq, Hash)] struct ItemEntry { url: String, name: String, } impl ItemEntry { fn new(mut url: String, name: String) -> ItemEntry { while url.starts_with('/') { url.remove(0); } ItemEntry { url, name } } } impl ItemEntry { crate fn print(&self) -> impl fmt::Display + '_ { crate::html::format::display_fn(move |f| { write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name)) }) } } impl PartialOrd for ItemEntry { fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for ItemEntry { fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering { self.name.cmp(&other.name) } } #[derive(Debug)] struct AllTypes { structs: FxHashSet<ItemEntry>, enums: FxHashSet<ItemEntry>, unions: FxHashSet<ItemEntry>, primitives: FxHashSet<ItemEntry>, traits: FxHashSet<ItemEntry>, macros: FxHashSet<ItemEntry>, functions: FxHashSet<ItemEntry>, typedefs: FxHashSet<ItemEntry>, opaque_tys: FxHashSet<ItemEntry>, statics: FxHashSet<ItemEntry>, constants: FxHashSet<ItemEntry>, attributes: FxHashSet<ItemEntry>, derives: FxHashSet<ItemEntry>, trait_aliases: FxHashSet<ItemEntry>, } impl AllTypes { fn new() -> AllTypes { let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default()); AllTypes { structs: new_set(100), enums: new_set(100), unions: new_set(100), primitives: new_set(26), traits: new_set(100), macros: new_set(100), functions: new_set(100), typedefs: new_set(100), opaque_tys: new_set(100), statics: new_set(100), constants: new_set(100), attributes: new_set(100), derives: new_set(100), trait_aliases: new_set(100), } } fn append(&mut self, item_name: String, item_type: &ItemType) { let mut url: Vec<_> = item_name.split("::").skip(1).collect(); if let Some(name) = url.pop() { let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name); url.push(name); let name = url.join("::"); match *item_type { ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)), ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)), ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)), ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)), ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)), ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)), ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)), ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)), ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)), ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)), ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)), ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)), ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)), ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)), _ => true, }; } } } impl AllTypes { fn print(self, f: &mut Buffer) { fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) { if !e.is_empty() { let mut e: Vec<&ItemEntry> = e.iter().collect(); e.sort(); write!( f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title.replace(' ', "-"), // IDs cannot contain whitespaces. title, class ); for s in e.iter() { write!(f, "<li>{}</li>", s.print()); } f.write_str("</ul>"); } } f.write_str( "<h1 class=\"fqn\">\ <span class=\"in-band\">List of all items</span>\ <span class=\"out-of-band\">\ <span id=\"render-detail\">\ <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \ title=\"collapse all docs\">\ [<span class=\"inner\">&#x2212;</span>]\ </a>\ </span> </span> </h1>", ); // Note: print_entries does not escape the title, because we know the current set of titles // doesn't require escaping. print_entries(f, &self.structs, "Structs", "structs"); print_entries(f, &self.enums, "Enums", "enums"); print_entries(f, &self.unions, "Unions", "unions"); print_entries(f, &self.primitives, "Primitives", "primitives"); print_entries(f, &self.traits, "Traits", "traits"); print_entries(f, &self.macros, "Macros", "macros"); print_entries(f, &self.attributes, "Attribute Macros", "attributes"); print_entries(f, &self.derives, "Derive Macros", "derives"); print_entries(f, &self.functions, "Functions", "functions"); print_entries(f, &self.typedefs, "Typedefs", "typedefs"); print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases"); print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types"); print_entries(f, &self.statics, "Statics", "statics"); print_entries(f, &self.constants, "Constants", "constants") } } #[derive(Debug)] enum Setting { Section { description: &'static str, sub_settings: Vec<Setting>, }, Toggle { js_data_name: &'static str, description: &'static str, default_value: bool, }, Select { js_data_name: &'static str, description: &'static str, default_value: &'static str, options: Vec<(String, String)>, }, } impl Setting { fn display(&self, root_path: &str, suffix: &str) -> String { match *self { Setting::Section { description, ref sub_settings } => format!( "<div class=\"setting-line\">\ <div class=\"title\">{}</div>\ <div class=\"sub-settings\">{}</div> </div>", description, sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>() ), Setting::Toggle { js_data_name, description, default_value } => format!( "<div class=\"setting-line\">\ <label class=\"toggle\">\ <input type=\"checkbox\" id=\"{}\" {}>\ <span class=\"slider\"></span>\ </label>\ <div>{}</div>\ </div>", js_data_name, if default_value { " checked" } else { "" }, description, ), Setting::Select { js_data_name, description, default_value, ref options } => format!( "<div class=\"setting-line\">\ <div>{}</div>\ <label class=\"select-wrapper\">\ <select id=\"{}\" autocomplete=\"off\">{}</select>\ <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\ </label>\ </div>", description, js_data_name, options .iter() .map(|opt| format!( "<option value=\"{}\" {}>{}</option>", opt.0, if opt.0 == default_value { "selected" } else { "" }, opt.1, )) .collect::<String>(), root_path, suffix, ), } } } impl From<(&'static str, &'static str, bool)> for Setting { fn from(values: (&'static str, &'static str, bool)) -> Setting { Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 } } } impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting { fn from(values: (&'static str, Vec<T>)) -> Setting { Setting::Section { description: values.0, sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(), } } } fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> { let theme_names: Vec<(String, String)> = themes .iter() .map(|entry| { let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path) .to_string(); Ok((theme.clone(), theme)) }) .collect::<Result<_, Error>>()?; // (id, explanation, default value) let settings: &[Setting] = &[ ( "Theme preferences", vec![ Setting::from(("use-system-theme", "Use system theme", true)), Setting::Select { js_data_name: "preferred-dark-theme", description: "Preferred dark theme", default_value: "dark", options: theme_names.clone(), }, Setting::Select { js_data_name: "preferred-light-theme", description: "Preferred light theme", default_value: "light", options: theme_names, }, ], ) .into(), ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(), ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(), ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false) .into(), ("go-to-only-result", "Directly go to item in search if there is only one result", false) .into(), ("line-numbers", "Show line numbers on code examples", false).into(), ("disable-shortcuts", "Disable keyboard shortcuts", false).into(), ]; Ok(format!( "<h1 class=\"fqn\">\ <span class=\"in-band\">Rustdoc settings</span>\ </h1>\ <div class=\"settings\">{}</div>\ <script src=\"{}settings{}.js\"></script>", settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(), root_path, suffix )) } fn document( w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>, heading_offset: HeadingOffset, ) { if let Some(ref name) = item.name { info!("Documenting {}", name); } document_item_info(w, cx, item, parent); if parent.is_none() { document_full_collapsible(w, item, cx, heading_offset); } else { document_full(w, item, cx, heading_offset); } } /// Render md_text as markdown. fn render_markdown( w: &mut Buffer, cx: &Context<'_>, md_text: &str, links: Vec<RenderedLink>, heading_offset: HeadingOffset, ) { let mut ids = cx.id_map.borrow_mut(); write!( w, "<div class=\"docblock\">{}</div>", Markdown { content: md_text, links: &links, ids: &mut ids, error_codes: cx.shared.codes, edition: cx.shared.edition(), playground: &cx.shared.playground, heading_offset, } .into_string() ) } /// Writes a documentation block containing only the first paragraph of the documentation. If the /// docs are longer, a "Read more" link is appended to the end. fn document_short( w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, link: AssocItemLink<'_>, parent: &clean::Item, show_def_docs: bool, ) { document_item_info(w, cx, item, Some(parent)); if !show_def_docs { return; } if let Some(s) = item.doc_value() { let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string(); if s.contains('\n') { let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx)); if let Some(idx) = summary_html.rfind("</p>") { summary_html.insert_str(idx, &link); } else { summary_html.push_str(&link); } } write!(w, "<div class='docblock'>{}</div>", summary_html,); } } fn document_full_collapsible( w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, heading_offset: HeadingOffset, ) { document_full_inner(w, item, cx, true, heading_offset); } fn document_full( w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, heading_offset: HeadingOffset, ) { document_full_inner(w, item, cx, false, heading_offset); } fn document_full_inner( w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, is_collapsible: bool, heading_offset: HeadingOffset, ) { if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) { debug!("Doc block: =====\n{}\n=====", s); if is_collapsible { w.write_str( "<details class=\"rustdoc-toggle top-doc\" open>\ <summary class=\"hideme\">\ <span>Expand description</span>\ </summary>", ); render_markdown(w, cx, &s, item.links(cx), heading_offset); w.write_str("</details>"); } else { render_markdown(w, cx, &s, item.links(cx), heading_offset); } } let kind = match &*item.kind { clean::ItemKind::StrippedItem(box kind) | kind => kind, }; if let clean::ItemKind::FunctionItem(..) | clean::ItemKind::MethodItem(..) = kind { render_call_locations(w, cx, item); } } /// Add extra information about an item such as: /// /// * Stability /// * Deprecated /// * Required features (through the `doc_cfg` feature) fn document_item_info( w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>, ) { let item_infos = short_item_info(item, cx, parent); if !item_infos.is_empty() { w.write_str("<div class=\"item-info\">"); for info in item_infos { w.write_str(&info); } w.write_str("</div>"); } } fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> { let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) { (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg), (cfg, _) => cfg.as_deref().cloned(), }; debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg); Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html())) } /// Render the stability, deprecation and portability information that is displayed at the top of /// the item's documentation. fn short_item_info( item: &clean::Item, cx: &Context<'_>, parent: Option<&clean::Item>, ) -> Vec<String> { let mut extra_info = vec![]; let error_codes = cx.shared.codes; if let Some(depr @ Deprecation { note, since, is_since_rustc_version: _, suggestion: _ }) = item.deprecation(cx.tcx()) { // We display deprecation messages for #[deprecated] and #[rustc_deprecated] // but only display the future-deprecation messages for #[rustc_deprecated]. let mut message = if let Some(since) = since { let since = &since.as_str(); if !stability::deprecation_in_effect(&depr) { if *since == "TBD" { String::from("Deprecating in a future Rust version") } else { format!("Deprecating in {}", Escape(since)) } } else { format!("Deprecated since {}", Escape(since)) } } else { String::from("Deprecated") }; if let Some(note) = note { let note = note.as_str(); let mut ids = cx.id_map.borrow_mut(); let html = MarkdownHtml( &note, &mut ids, error_codes, cx.shared.edition(), &cx.shared.playground, ); message.push_str(&format!(": {}", html.into_string())); } extra_info.push(format!( "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>", message, )); } // Render unstable items. But don't render "rustc_private" crates (internal compiler crates). // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere. if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item .stability(cx.tcx()) .as_ref() .filter(|stab| stab.feature != sym::rustc_private) .map(|stab| (stab.level, stab.feature)) { let mut message = "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned(); let mut feature = format!("<code>{}</code>", Escape(&feature.as_str())); if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) { feature.push_str(&format!( "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>", url = url, issue = issue )); } message.push_str(&format!(" ({})", feature)); if let Some(unstable_reason) = reason { let mut ids = cx.id_map.borrow_mut(); message = format!( "<details><summary>{}</summary>{}</details>", message, MarkdownHtml( &unstable_reason.as_str(), &mut ids, error_codes, cx.shared.edition(), &cx.shared.playground, ) .into_string() ); } extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message)); } if let Some(portability) = portability(item, parent) { extra_info.push(portability); } extra_info } // Render the list of items inside one of the sections "Trait Implementations", // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages). fn render_impls(cx: &Context<'_>, w: &mut Buffer, impls: &[&&Impl], containing_item: &clean::Item) { let tcx = cx.tcx(); let mut rendered_impls = impls .iter() .map(|i| { let did = i.trait_did().unwrap(); let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx); let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods); let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() }; render_impl( &mut buffer, cx, i, containing_item, assoc_link, RenderMode::Normal, None, &[], ImplRenderingParameters { show_def_docs: true, is_on_foreign_type: false, show_default_items: true, show_non_assoc_items: true, toggle_open_by_default: true, }, ); buffer.into_inner() }) .collect::<Vec<_>>(); rendered_impls.sort(); w.write_str(&rendered_impls.join("")); } fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String { use crate::formats::item_type::ItemType::*; let name = it.name.as_ref().unwrap(); let ty = match it.type_() { Typedef | AssocType => AssocType, s => s, }; let anchor = format!("#{}.{}", ty, name); match link { AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id), AssocItemLink::Anchor(None) => anchor, AssocItemLink::GotoSource(did, _) => { href(did.expect_def_id(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor) } } } fn assoc_const( w: &mut Buffer, it: &clean::Item, ty: &clean::Type, _default: Option<&String>, link: AssocItemLink<'_>, extra: &str, cx: &Context<'_>, ) { write!( w, "{}{}const <a href=\"{}\" class=\"constant\">{}</a>: {}", extra, it.visibility.print_with_space(it.def_id, cx), naive_assoc_href(it, link, cx), it.name.as_ref().unwrap(), ty.print(cx) ); } fn assoc_type( w: &mut Buffer, it: &clean::Item, bounds: &[clean::GenericBound], default: Option<&clean::Type>, link: AssocItemLink<'_>, extra: &str, cx: &Context<'_>, ) { write!( w, "{}type <a href=\"{}\" class=\"type\">{}</a>", extra, naive_assoc_href(it, link, cx), it.name.as_ref().unwrap() ); if !bounds.is_empty() { write!(w, ": {}", print_generic_bounds(bounds, cx)) } if let Some(default) = default { write!(w, " = {}", default.print(cx)) } } fn render_stability_since_raw( w: &mut Buffer, ver: Option<&str>, const_stability: Option<&ConstStability>, containing_ver: Option<&str>, containing_const_ver: Option<&str>, ) { let ver = ver.filter(|inner| !inner.is_empty()); match (ver, const_stability) { // stable and const stable (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. })) if Some(since.as_str()).as_deref() != containing_const_ver => { write!( w, "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>", v, since ); } // stable and const unstable ( Some(v), Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }), ) => { write!( w, "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ", v ); if let Some(n) = issue { write!( w, "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>", n, feature ); } else { write!(w, "unstable"); } write!(w, ")</span>"); } // stable (Some(v), _) if ver != containing_ver => { write!( w, "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>", v ); } _ => {} } } fn render_assoc_item( w: &mut Buffer, item: &clean::Item, link: AssocItemLink<'_>, parent: ItemType, cx: &Context<'_>, ) { fn method( w: &mut Buffer, meth: &clean::Item, header: hir::FnHeader, g: &clean::Generics, d: &clean::FnDecl, link: AssocItemLink<'_>, parent: ItemType, cx: &Context<'_>, ) { let name = meth.name.as_ref().unwrap(); let href = match link { AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)), AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)), AssocItemLink::GotoSource(did, provided_methods) => { // We're creating a link from an impl-item to the corresponding // trait-item and need to map the anchored type accordingly. let ty = if provided_methods.contains(name) { ItemType::Method } else { ItemType::TyMethod }; match (href(did.expect_def_id(), cx), ty) { (Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)), (Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None, (Err(_), ty) => Some(format!("#{}.{}", ty, name)), } } }; let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string(); let constness = print_constness_with_space(&header.constness, meth.const_stability(cx.tcx())); let asyncness = header.asyncness.print_with_space(); let unsafety = header.unsafety.print_with_space(); let defaultness = print_default_space(meth.is_default()); let abi = print_abi_with_space(header.abi).to_string(); // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`. let generics_len = format!("{:#}", g.print(cx)).len(); let mut header_len = "fn ".len() + vis.len() + constness.len() + asyncness.len() + unsafety.len() + defaultness.len() + abi.len() + name.as_str().len() + generics_len; let (indent, indent_str, end_newline) = if parent == ItemType::Trait { header_len += 4; let indent_str = " "; render_attributes_in_pre(w, meth, indent_str); (4, indent_str, false) } else { render_attributes_in_code(w, meth); (0, "", true) }; w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len()); write!( w, "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\ {generics}{decl}{notable_traits}{where_clause}", indent = indent_str, vis = vis, constness = constness, asyncness = asyncness, unsafety = unsafety, defaultness = defaultness, abi = abi, // links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()), name = name, generics = g.print(cx), decl = d.full_print(header_len, indent, header.asyncness, cx), notable_traits = notable_traits_decl(d, cx), where_clause = print_where_clause(g, cx, indent, end_newline), ) } match *item.kind { clean::StrippedItem(..) => {} clean::TyMethodItem(ref m) => { method(w, item, m.header, &m.generics, &m.decl, link, parent, cx) } clean::MethodItem(ref m, _) => { method(w, item, m.header, &m.generics, &m.decl, link, parent, cx) } clean::AssocConstItem(ref ty, ref default) => assoc_const( w, item, ty, default.as_ref(), link, if parent == ItemType::Trait { " " } else { "" }, cx, ), clean::AssocTypeItem(ref bounds, ref default) => assoc_type( w, item, bounds, default.as_ref(), link, if parent == ItemType::Trait { " " } else { "" }, cx, ), _ => panic!("render_assoc_item called on non-associated-item"), } } const ALLOWED_ATTRIBUTES: &[Symbol] = &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive]; fn attrib
clean::Item) -> Vec<String> { it.attrs .other_attrs .iter() .filter_map(|attr| { if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) { Some(pprust::attribute_to_string(attr).replace("\n", "").replace(" ", " ")) } else { None } }) .collect() } // When an attribute is rendered inside a `<pre>` tag, it is formatted using // a whitespace prefix and newline. fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) { for a in attributes(it) { writeln!(w, "{}{}", prefix, a); } } // When an attribute is rendered inside a <code> tag, it is formatted using // a div to produce a newline after it. fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) { for a in attributes(it) { write!(w, "<div class=\"code-attribute\">{}</div>", a); } } #[derive(Copy, Clone)] enum AssocItemLink<'a> { Anchor(Option<&'a str>), GotoSource(ItemId, &'a FxHashSet<Symbol>), } impl<'a> AssocItemLink<'a> { fn anchor(&self, id: &'a str) -> Self { match *self { AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(id)), ref other => *other, } } } fn render_assoc_items( w: &mut Buffer, cx: &Context<'_>, containing_item: &clean::Item, it: DefId, what: AssocItemRender<'_>, ) { let mut derefs = FxHashSet::default(); derefs.insert(it); render_assoc_items_inner(w, cx, containing_item, it, what, &mut derefs) } fn render_assoc_items_inner( w: &mut Buffer, cx: &Context<'_>, containing_item: &clean::Item, it: DefId, what: AssocItemRender<'_>, derefs: &mut FxHashSet<DefId>, ) { info!("Documenting associated items of {:?}", containing_item.name); let cache = cx.cache(); let v = match cache.impls.get(&it) { Some(v) => v, None => return, }; let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none()); if !non_trait.is_empty() { let mut tmp_buf = Buffer::empty_from(w); let render_mode = match what { AssocItemRender::All => { tmp_buf.write_str( "<h2 id=\"implementations\" class=\"small-section-header\">\ Implementations<a href=\"#implementations\" class=\"anchor\"></a>\ </h2>", ); RenderMode::Normal } AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => { let id = cx.derive_id(small_url_encode(format!("deref-methods-{:#}", type_.print(cx)))); if let Some(def_id) = type_.def_id(cx.cache()) { cx.deref_id_map.borrow_mut().insert(def_id, id.clone()); } write!( tmp_buf, "<h2 id=\"{id}\" class=\"small-section-header\">\ <span>Methods from {trait_}&lt;Target = {type_}&gt;</span>\ <a href=\"#{id}\" class=\"anchor\"></a>\ </h2>", id = id, trait_ = trait_.print(cx), type_ = type_.print(cx), ); RenderMode::ForDeref { mut_: deref_mut_ } } }; let mut impls_buf = Buffer::empty_from(w); for i in &non_trait { render_impl( &mut impls_buf, cx, i, containing_item, AssocItemLink::Anchor(None), render_mode, None, &[], ImplRenderingParameters { show_def_docs: true, is_on_foreign_type: false, show_default_items: true, show_non_assoc_items: true, toggle_open_by_default: true, }, ); } if !impls_buf.is_empty() { w.push_buffer(tmp_buf); w.push_buffer(impls_buf); } } if !traits.is_empty() { let deref_impl = traits.iter().find(|t| t.trait_did() == cx.tcx().lang_items().deref_trait()); if let Some(impl_) = deref_impl { let has_deref_mut = traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait()); render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, derefs); } // If we were already one level into rendering deref methods, we don't want to render // anything after recursing into any further deref methods above. if let AssocItemRender::DerefFor { .. } = what { return; } let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits.iter().partition(|t| t.inner_impl().synthetic); let (blanket_impl, concrete): (Vec<&&Impl>, _) = concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some()); let mut impls = Buffer::empty_from(w); render_impls(cx, &mut impls, &concrete, containing_item); let impls = impls.into_inner(); if !impls.is_empty() { write!( w, "<h2 id=\"trait-implementations\" class=\"small-section-header\">\ Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\ </h2>\ <div id=\"trait-implementations-list\">{}</div>", impls ); } if !synthetic.is_empty() { w.write_str( "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\ Auto Trait Implementations\ <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\ </h2>\ <div id=\"synthetic-implementations-list\">", ); render_impls(cx, w, &synthetic, containing_item); w.write_str("</div>"); } if !blanket_impl.is_empty() { w.write_str( "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\ Blanket Implementations\ <a href=\"#blanket-implementations\" class=\"anchor\"></a>\ </h2>\ <div id=\"blanket-implementations-list\">", ); render_impls(cx, w, &blanket_impl, containing_item); w.write_str("</div>"); } } } fn render_deref_methods( w: &mut Buffer, cx: &Context<'_>, impl_: &Impl, container_item: &clean::Item, deref_mut: bool, derefs: &mut FxHashSet<DefId>, ) { let cache = cx.cache(); let deref_type = impl_.inner_impl().trait_.as_ref().unwrap(); let (target, real_target) = impl_ .inner_impl() .items .iter() .find_map(|item| match *item.kind { clean::TypedefItem(ref t, true) => Some(match *t { clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_), _ => (&t.type_, &t.type_), }), _ => None, }) .expect("Expected associated type binding"); debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target); let what = AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut }; if let Some(did) = target.def_id(cache) { if let Some(type_did) = impl_.inner_impl().for_.def_id(cache) { // `impl Deref<Target = S> for S` if did == type_did || !derefs.insert(did) { // Avoid infinite cycles return; } } render_assoc_items_inner(w, cx, container_item, did, what, derefs); } else { if let Some(prim) = target.primitive_type() { if let Some(&did) = cache.primitive_locations.get(&prim) { render_assoc_items_inner(w, cx, container_item, did, what, derefs); } } } } fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool { let self_type_opt = match *item.kind { clean::MethodItem(ref method, _) => method.decl.self_type(), clean::TyMethodItem(ref method) => method.decl.self_type(), _ => None, }; if let Some(self_ty) = self_type_opt { let (by_mut_ref, by_box, by_value) = match self_ty { SelfTy::SelfBorrowed(_, mutability) | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => { (mutability == Mutability::Mut, false, false) } SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => { (false, Some(did) == tcx.lang_items().owned_box(), false) } SelfTy::SelfValue => (false, false, true), _ => (false, false, false), }; (deref_mut_ || !by_mut_ref) && !by_box && !by_value } else { false } } fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String { let mut out = Buffer::html(); if let Some(did) = decl.output.as_return().and_then(|t| t.def_id(cx.cache())) { if let Some(impls) = cx.cache().impls.get(&did) { for i in impls { let impl_ = i.inner_impl(); if let Some(trait_) = &impl_.trait_ { let trait_did = trait_.def_id(); if cx.cache().traits.get(&trait_did).map_or(false, |t| t.is_notable) { if out.is_empty() { write!( &mut out, "<div class=\"notable\">Notable traits for {}</div>\ <code class=\"content\">", impl_.for_.print(cx) ); } //use the "where" class here to make it small write!( &mut out, "<span class=\"where fmt-newline\">{}</span>", impl_.print(false, cx) ); for it in &impl_.items { if let clean::TypedefItem(ref tydef, _) = *it.kind { out.push_str("<span class=\"where fmt-newline\"> "); let empty_set = FxHashSet::default(); let src_link = AssocItemLink::GotoSource(trait_did.into(), &empty_set); assoc_type(&mut out, it, &[], Some(&tydef.type_), src_link, "", cx); out.push_str(";</span>"); } } } } } } } if !out.is_empty() { out.insert_str( 0, "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\ <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">", ); out.push_str("</code></span></div></span></span>"); } out.into_inner() } #[derive(Clone, Copy, Debug)] struct ImplRenderingParameters { show_def_docs: bool, is_on_foreign_type: bool, show_default_items: bool, /// Whether or not to show methods. show_non_assoc_items: bool, toggle_open_by_default: bool, } fn render_impl( w: &mut Buffer, cx: &Context<'_>, i: &Impl, parent: &clean::Item, link: AssocItemLink<'_>, render_mode: RenderMode, use_absolute: Option<bool>, aliases: &[String], rendering_params: ImplRenderingParameters, ) { let cache = cx.cache(); let traits = &cache.traits; let trait_ = i.trait_did().map(|did| &traits[&did]); let mut close_tags = String::new(); // For trait implementations, the `interesting` output contains all methods that have doc // comments, and the `boring` output contains all methods that do not. The distinction is // used to allow hiding the boring methods. // `containing_item` is used for rendering stability info. If the parent is a trait impl, // `containing_item` will the grandparent, since trait impls can't have stability attached. fn doc_impl_item( boring: &mut Buffer, interesting: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: &clean::Item, containing_item: &clean::Item, link: AssocItemLink<'_>, render_mode: RenderMode, is_default_item: bool, trait_: Option<&clean::Trait>, rendering_params: ImplRenderingParameters, ) { let item_type = item.type_(); let name = item.name.as_ref().unwrap(); let render_method_item = rendering_params.show_non_assoc_items && match render_mode { RenderMode::Normal => true, RenderMode::ForDeref { mut_: deref_mut_ } => { should_render_item(item, deref_mut_, cx.tcx()) } }; let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" }; let mut doc_buffer = Buffer::empty_from(boring); let mut info_buffer = Buffer::empty_from(boring); let mut short_documented = true; if render_method_item { if !is_default_item { if let Some(t) = trait_ { // The trait item may have been stripped so we might not // find any documentation or stability for it. if let Some(it) = t.items.iter().find(|i| i.name == item.name) { // We need the stability of the item from the trait // because impls can't have a stability. if item.doc_value().is_some() { document_item_info(&mut info_buffer, cx, it, Some(parent)); document_full(&mut doc_buffer, item, cx, HeadingOffset::H5); short_documented = false; } else { // In case the item isn't documented, // provide short documentation from the trait. document_short( &mut doc_buffer, it, cx, link, parent, rendering_params.show_def_docs, ); } } } else { document_item_info(&mut info_buffer, cx, item, Some(parent)); if rendering_params.show_def_docs { document_full(&mut doc_buffer, item, cx, HeadingOffset::H5); short_documented = false; } } } else { document_short( &mut doc_buffer, item, cx, link, parent, rendering_params.show_def_docs, ); } } let w = if short_documented && trait_.is_some() { interesting } else { boring }; let toggled = !doc_buffer.is_empty(); if toggled { let method_toggle_class = if item_type == ItemType::Method { " method-toggle" } else { "" }; write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class); } match *item.kind { clean::MethodItem(..) | clean::TyMethodItem(_) => { // Only render when the method is not static or we allow static methods if render_method_item { let id = cx.derive_id(format!("{}.{}", item_type, name)); let source_id = trait_ .and_then(|trait_| { trait_.items.iter().find(|item| { item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false) }) }) .map(|item| format!("{}.{}", item.type_(), name)); write!( w, "<div id=\"{}\" class=\"{}{} has-srclink\">", id, item_type, in_trait_class, ); render_rightside(w, cx, item, containing_item); write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id); w.write_str("<h4 class=\"code-header\">"); render_assoc_item( w, item, link.anchor(source_id.as_ref().unwrap_or(&id)), ItemType::Impl, cx, ); w.write_str("</h4>"); w.write_str("</div>"); } } clean::TypedefItem(ref tydef, _) => { let source_id = format!("{}.{}", ItemType::AssocType, name); let id = cx.derive_id(source_id.clone()); write!( w, "<div id=\"{}\" class=\"{}{} has-srclink\">", id, item_type, in_trait_class ); write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id); w.write_str("<h4 class=\"code-header\">"); assoc_type( w, item, &Vec::new(), Some(&tydef.type_), link.anchor(if trait_.is_some() { &source_id } else { &id }), "", cx, ); w.write_str("</h4>"); w.write_str("</div>"); } clean::AssocConstItem(ref ty, ref default) => { let source_id = format!("{}.{}", item_type, name); let id = cx.derive_id(source_id.clone()); write!( w, "<div id=\"{}\" class=\"{}{} has-srclink\">", id, item_type, in_trait_class ); render_rightside(w, cx, item, containing_item); write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id); w.write_str("<h4 class=\"code-header\">"); assoc_const( w, item, ty, default.as_ref(), link.anchor(if trait_.is_some() { &source_id } else { &id }), "", cx, ); w.write_str("</h4>"); w.write_str("</div>"); } clean::AssocTypeItem(ref bounds, ref default) => { let source_id = format!("{}.{}", item_type, name); let id = cx.derive_id(source_id.clone()); write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,); write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id); w.write_str("<h4 class=\"code-header\">"); assoc_type( w, item, bounds, default.as_ref(), link.anchor(if trait_.is_some() { &source_id } else { &id }), "", cx, ); w.write_str("</h4>"); w.write_str("</div>"); } clean::StrippedItem(..) => return, _ => panic!("can't make docs for trait item with name {:?}", item.name), } w.push_buffer(info_buffer); if toggled { w.write_str("</summary>"); w.push_buffer(doc_buffer); w.push_str("</details>"); } } let mut impl_items = Buffer::empty_from(w); let mut default_impl_items = Buffer::empty_from(w); for trait_item in &i.inner_impl().items { doc_impl_item( &mut default_impl_items, &mut impl_items, cx, trait_item, if trait_.is_some() { &i.impl_item } else { parent }, parent, link, render_mode, false, trait_.map(|t| &t.trait_), rendering_params, ); } fn render_default_items( boring: &mut Buffer, interesting: &mut Buffer, cx: &Context<'_>, t: &clean::Trait, i: &clean::Impl, parent: &clean::Item, containing_item: &clean::Item, render_mode: RenderMode, rendering_params: ImplRenderingParameters, ) { for trait_item in &t.items { let n = trait_item.name; if i.items.iter().any(|m| m.name == n) { continue; } let did = i.trait_.as_ref().unwrap().def_id(); let provided_methods = i.provided_trait_methods(cx.tcx()); let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods); doc_impl_item( boring, interesting, cx, trait_item, parent, containing_item, assoc_link, render_mode, true, Some(t), rendering_params, ); } } // If we've implemented a trait, then also emit documentation for all // default items which weren't overridden in the implementation block. // We don't emit documentation for default items if they appear in the // Implementations on Foreign Types or Implementors sections. if rendering_params.show_default_items { if let Some(t) = trait_ { render_default_items( &mut default_impl_items, &mut impl_items, cx, &t.trait_, i.inner_impl(), &i.impl_item, parent, render_mode, rendering_params, ); } } if render_mode == RenderMode::Normal { let toggled = !(impl_items.is_empty() && default_impl_items.is_empty()); if toggled { close_tags.insert_str(0, "</details>"); write!( w, "<details class=\"rustdoc-toggle implementors-toggle\"{}>", if rendering_params.toggle_open_by_default { " open" } else { "" } ); write!(w, "<summary>") } render_impl_summary( w, cx, i, parent, parent, rendering_params.show_def_docs, use_absolute, rendering_params.is_on_foreign_type, aliases, ); if toggled { write!(w, "</summary>") } if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) { let mut ids = cx.id_map.borrow_mut(); write!( w, "<div class=\"docblock\">{}</div>", Markdown { content: &*dox, links: &i.impl_item.links(cx), ids: &mut ids, error_codes: cx.shared.codes, edition: cx.shared.edition(), playground: &cx.shared.playground, heading_offset: HeadingOffset::H4 } .into_string() ); } } if !default_impl_items.is_empty() || !impl_items.is_empty() { w.write_str("<div class=\"impl-items\">"); w.push_buffer(default_impl_items); w.push_buffer(impl_items); close_tags.insert_str(0, "</div>"); } w.write_str(&close_tags); } // Render the items that appear on the right side of methods, impls, and // associated types. For example "1.0.0 (const: 1.39.0) [src]". fn render_rightside( w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, containing_item: &clean::Item, ) { let tcx = cx.tcx(); write!(w, "<div class=\"rightside\">"); render_stability_since_raw( w, item.stable_since(tcx).as_deref(), item.const_stability(tcx), containing_item.stable_since(tcx).as_deref(), containing_item.const_stable_since(tcx).as_deref(), ); write_srclink(cx, item, w); w.write_str("</div>"); } pub(crate) fn render_impl_summary( w: &mut Buffer, cx: &Context<'_>, i: &Impl, parent: &clean::Item, containing_item: &clean::Item, show_def_docs: bool, use_absolute: Option<bool>, is_on_foreign_type: bool, // This argument is used to reference same type with different paths to avoid duplication // in documentation pages for trait with automatic implementations like "Send" and "Sync". aliases: &[String], ) { let id = cx.derive_id(match i.inner_impl().trait_ { Some(ref t) => { if is_on_foreign_type { get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx) } else { format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx)))) } } None => "impl".to_string(), }); let aliases = if aliases.is_empty() { String::new() } else { format!(" data-aliases=\"{}\"", aliases.join(",")) }; write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases); render_rightside(w, cx, &i.impl_item, containing_item); write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id); write!(w, "<h3 class=\"code-header in-band\">"); if let Some(use_absolute) = use_absolute { write!(w, "{}", i.inner_impl().print(use_absolute, cx)); if show_def_docs { for it in &i.inner_impl().items { if let clean::TypedefItem(ref tydef, _) = *it.kind { w.write_str("<span class=\"where fmt-newline\"> "); assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx); w.write_str(";</span>"); } } } } else { write!(w, "{}", i.inner_impl().print(false, cx)); } write!(w, "</h3>"); let is_trait = i.inner_impl().trait_.is_some(); if is_trait { if let Some(portability) = portability(&i.impl_item, Some(parent)) { write!(w, "<div class=\"item-info\">{}</div>", portability); } } w.write_str("</div>"); } fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) { let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 }; if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union() || it.is_enum() || it.is_mod() || it.is_typedef() { write!( buffer, "<h2 class=\"location\">{}{}</h2>", match *it.kind { clean::StructItem(..) => "Struct ", clean::TraitItem(..) => "Trait ", clean::PrimitiveItem(..) => "Primitive Type ", clean::UnionItem(..) => "Union ", clean::EnumItem(..) => "Enum ", clean::TypedefItem(..) => "Type Definition ", clean::ForeignTypeItem => "Foreign Type ", clean::ModuleItem(..) => if it.is_crate() { "Crate " } else { "Module " }, _ => "", }, it.name.as_ref().unwrap() ); } if it.is_crate() { if let Some(ref version) = cx.cache().crate_version { write!( buffer, "<div class=\"block version\">\ <div class=\"narrow-helper\"></div>\ <p>Version {}</p>\ </div>", Escape(version), ); } } buffer.write_str("<div class=\"sidebar-elems\">"); if it.is_crate() { write!( buffer, "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>", it.name.as_ref().expect("crates always have a name"), ); } match *it.kind { clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s), clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t), clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it), clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u), clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e), clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it), clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items), clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it), _ => {} } // The sidebar is designed to display sibling functions, modules and // other miscellaneous information. since there are lots of sibling // items (and that causes quadratic growth in large modules), // we refactor common parts into a shared JavaScript file per module. // still, we don't move everything into JS because we want to preserve // as much HTML as possible in order to allow non-JS-enabled browsers // to navigate the documentation (though slightly inefficiently). if !it.is_mod() { buffer.write_str("<h2 class=\"location\">Other items in<br>"); for (i, name) in cx.current.iter().take(parentlen).enumerate() { if i > 0 { buffer.write_str("::<wbr>"); } write!( buffer, "<a href=\"{}index.html\">{}</a>", &cx.root_path()[..(cx.current.len() - i - 1) * 3], *name ); } buffer.write_str("</h2>"); } // Sidebar refers to the enclosing module, not this module. let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" }; write!( buffer, "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\ </div>", name = it.name.unwrap_or(kw::Empty), ty = it.type_(), path = relpath ); write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath); // Closes sidebar-elems div. buffer.write_str("</div>"); } fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String { if used_links.insert(url.clone()) { return url; } let mut add = 1; while !used_links.insert(format!("{}-{}", url, add)) { add += 1; } format!("{}-{}", url, add) } struct SidebarLink { name: Symbol, url: String, } impl fmt::Display for SidebarLink { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "<a href=\"#{}\">{}</a>", self.url, self.name) } } impl PartialEq for SidebarLink { fn eq(&self, other: &Self) -> bool { self.url == other.url } } impl Eq for SidebarLink {} impl PartialOrd for SidebarLink { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for SidebarLink { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.url.cmp(&other.url) } } fn get_methods( i: &clean::Impl, for_deref: bool, used_links: &mut FxHashSet<String>, deref_mut: bool, tcx: TyCtxt<'_>, ) -> Vec<SidebarLink> { i.items .iter() .filter_map(|item| match item.name { Some(name) if !name.is_empty() && item.is_method() => { if !for_deref || should_render_item(item, deref_mut, tcx) { Some(SidebarLink { name, url: get_next_url(used_links, format!("method.{}", name)), }) } else { None } } _ => None, }) .collect::<Vec<_>>() } fn get_associated_constants( i: &clean::Impl, used_links: &mut FxHashSet<String>, ) -> Vec<SidebarLink> { i.items .iter() .filter_map(|item| match item.name { Some(name) if !name.is_empty() && item.is_associated_const() => Some(SidebarLink { name, url: get_next_url(used_links, format!("associatedconstant.{}", name)), }), _ => None, }) .collect::<Vec<_>>() } // The point is to url encode any potential character from a type with genericity. fn small_url_encode(s: String) -> String { let mut st = String::new(); let mut last_match = 0; for (idx, c) in s.char_indices() { let escaped = match c { '<' => "%3C", '>' => "%3E", ' ' => "%20", '?' => "%3F", '\'' => "%27", '&' => "%26", ',' => "%2C", ':' => "%3A", ';' => "%3B", '[' => "%5B", ']' => "%5D", '"' => "%22", _ => continue, }; st += &s[last_match..idx]; st += escaped; // NOTE: we only expect single byte characters here - which is fine as long as we // only match single byte characters last_match = idx + 1; } if last_match != 0 { st += &s[last_match..]; st } else { s } } fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) { let did = it.def_id.expect_def_id(); let cache = cx.cache(); if let Some(v) = cache.impls.get(&did) { let mut used_links = FxHashSet::default(); { let used_links_bor = &mut used_links; let mut assoc_consts = v .iter() .flat_map(|i| get_associated_constants(i.inner_impl(), used_links_bor)) .collect::<Vec<_>>(); if !assoc_consts.is_empty() { // We want links' order to be reproducible so we don't use unstable sort. assoc_consts.sort(); out.push_str( "<h3 class=\"sidebar-title\">\ <a href=\"#implementations\">Associated Constants</a>\ </h3>\ <div class=\"sidebar-links\">", ); for line in assoc_consts { write!(out, "{}", line); } out.push_str("</div>"); } let mut methods = v .iter() .filter(|i| i.inner_impl().trait_.is_none()) .flat_map(|i| get_methods(i.inner_impl(), false, used_links_bor, false, cx.tcx())) .collect::<Vec<_>>(); if !methods.is_empty() { // We want links' order to be reproducible so we don't use unstable sort. methods.sort(); out.push_str( "<h3 class=\"sidebar-title\"><a href=\"#implementations\">Methods</a></h3>\ <div class=\"sidebar-links\">", ); for line in methods { write!(out, "{}", line); } out.push_str("</div>"); } } if v.iter().any(|i| i.inner_impl().trait_.is_some()) { if let Some(impl_) = v.iter().find(|i| i.trait_did() == cx.tcx().lang_items().deref_trait()) { let mut derefs = FxHashSet::default(); derefs.insert(did); sidebar_deref_methods(cx, out, impl_, v, &mut derefs); } let format_impls = |impls: Vec<&Impl>| { let mut links = FxHashSet::default(); let mut ret = impls .iter() .filter_map(|it| { if let Some(ref i) = it.inner_impl().trait_ { let i_display = format!("{:#}", i.print(cx)); let out = Escape(&i_display); let encoded = small_url_encode(format!("{:#}", i.print(cx))); let generated = format!( "<a href=\"#impl-{}\">{}{}</a>", encoded, if it.inner_impl().negative_polarity { "!" } else { "" }, out ); if links.insert(generated.clone()) { Some(generated) } else { None } } else { None } }) .collect::<Vec<String>>(); ret.sort(); ret }; let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| { out.push_str("<div class=\"sidebar-links\">"); for link in links { out.push_str(&link); } out.push_str("</div>"); }; let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic); let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete .into_iter() .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some()); let concrete_format = format_impls(concrete); let synthetic_format = format_impls(synthetic); let blanket_format = format_impls(blanket_impl); if !concrete_format.is_empty() { out.push_str( "<h3 class=\"sidebar-title\"><a href=\"#trait-implementations\">\ Trait Implementations</a></h3>", ); write_sidebar_links(out, concrete_format); } if !synthetic_format.is_empty() { out.push_str( "<h3 class=\"sidebar-title\"><a href=\"#synthetic-implementations\">\ Auto Trait Implementations</a></h3>", ); write_sidebar_links(out, synthetic_format); } if !blanket_format.is_empty() { out.push_str( "<h3 class=\"sidebar-title\"><a href=\"#blanket-implementations\">\ Blanket Implementations</a></h3>", ); write_sidebar_links(out, blanket_format); } } } } fn sidebar_deref_methods( cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &[Impl], derefs: &mut FxHashSet<DefId>, ) { let c = cx.cache(); debug!("found Deref: {:?}", impl_); if let Some((target, real_target)) = impl_.inner_impl().items.iter().find_map(|item| match *item.kind { clean::TypedefItem(ref t, true) => Some(match *t { clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_), _ => (&t.type_, &t.type_), }), _ => None, }) { debug!("found target, real_target: {:?} {:?}", target, real_target); if let Some(did) = target.def_id(c) { if let Some(type_did) = impl_.inner_impl().for_.def_id(c) { // `impl Deref<Target = S> for S` if did == type_did || !derefs.insert(did) { // Avoid infinite cycles return; } } } let deref_mut = v.iter().any(|i| i.trait_did() == cx.tcx().lang_items().deref_mut_trait()); let inner_impl = target .def_id(c) .or_else(|| { target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned()) }) .and_then(|did| c.impls.get(&did)); if let Some(impls) = inner_impl { debug!("found inner_impl: {:?}", impls); let mut used_links = FxHashSet::default(); let mut ret = impls .iter() .filter(|i| i.inner_impl().trait_.is_none()) .flat_map(|i| { get_methods(i.inner_impl(), true, &mut used_links, deref_mut, cx.tcx()) }) .collect::<Vec<_>>(); if !ret.is_empty() { let map; let id = if let Some(target_def_id) = real_target.def_id(c) { map = cx.deref_id_map.borrow(); map.get(&target_def_id).expect("Deref section without derived id") } else { "deref-methods" }; write!( out, "<h3 class=\"sidebar-title\"><a href=\"#{}\">Methods from {}&lt;Target={}&gt;</a></h3>", id, Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))), Escape(&format!("{:#}", real_target.print(cx))), ); // We want links' order to be reproducible so we don't use unstable sort. ret.sort(); out.push_str("<div class=\"sidebar-links\">"); for link in ret { write!(out, "{}", link); } out.push_str("</div>"); } } // Recurse into any further impls that might exist for `target` if let Some(target_did) = target.def_id_no_primitives() { if let Some(target_impls) = c.impls.get(&target_did) { if let Some(target_deref_impl) = target_impls.iter().find(|i| { i.inner_impl() .trait_ .as_ref() .map(|t| Some(t.def_id()) == cx.tcx().lang_items().deref_trait()) .unwrap_or(false) }) { sidebar_deref_methods(cx, out, target_deref_impl, target_impls, derefs); } } } } } fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) { let mut sidebar = Buffer::new(); let fields = get_struct_fields_name(&s.fields); if !fields.is_empty() { if let CtorKind::Fictive = s.struct_type { sidebar.push_str( "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\ <div class=\"sidebar-links\">", ); for field in fields { sidebar.push_str(&field); } sidebar.push_str("</div>"); } else if let CtorKind::Fn = s.struct_type { sidebar .push_str("<h3 class=\"sidebar-title\"><a href=\"#fields\">Tuple Fields</a></h3>"); } } sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn get_id_for_impl_on_foreign_type( for_: &clean::Type, trait_: &clean::Path, cx: &Context<'_>, ) -> String { small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx))) } fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> { match *item.kind { clean::ItemKind::ImplItem(ref i) => { i.trait_.as_ref().map(|trait_| { // Alternative format produces no URLs, // so this parameter does nothing. ( format!("{:#}", i.for_.print(cx)), get_id_for_impl_on_foreign_type(&i.for_, trait_, cx), ) }) } _ => None, } } fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) { buf.write_str("<div class=\"block items\">"); fn print_sidebar_section( out: &mut Buffer, items: &[clean::Item], before: &str, filter: impl Fn(&clean::Item) -> bool, write: impl Fn(&mut Buffer, &str), after: &str, ) { let mut items = items .iter() .filter_map(|m| match m.name { Some(ref name) if filter(m) => Some(name.as_str()), _ => None, }) .collect::<Vec<_>>(); if !items.is_empty() { items.sort_unstable(); out.push_str(before); for item in items.into_iter() { write(out, &item); } out.push_str(after); } } print_sidebar_section( buf, &t.items, "<h3 class=\"sidebar-title\"><a href=\"#associated-types\">\ Associated Types</a></h3><div class=\"sidebar-links\">", |m| m.is_associated_type(), |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym), "</div>", ); print_sidebar_section( buf, &t.items, "<h3 class=\"sidebar-title\"><a href=\"#associated-const\">\ Associated Constants</a></h3><div class=\"sidebar-links\">", |m| m.is_associated_const(), |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym), "</div>", ); print_sidebar_section( buf, &t.items, "<h3 class=\"sidebar-title\"><a href=\"#required-methods\">\ Required Methods</a></h3><div class=\"sidebar-links\">", |m| m.is_ty_method(), |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym), "</div>", ); print_sidebar_section( buf, &t.items, "<h3 class=\"sidebar-title\"><a href=\"#provided-methods\">\ Provided Methods</a></h3><div class=\"sidebar-links\">", |m| m.is_method(), |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym), "</div>", ); let cache = cx.cache(); if let Some(implementors) = cache.implementors.get(&it.def_id.expect_def_id()) { let mut res = implementors .iter() .filter(|i| { i.inner_impl().for_.def_id(cache).map_or(false, |d| !cache.paths.contains_key(&d)) }) .filter_map(|i| extract_for_impl_name(&i.impl_item, cx)) .collect::<Vec<_>>(); if !res.is_empty() { res.sort(); buf.push_str( "<h3 class=\"sidebar-title\"><a href=\"#foreign-impls\">\ Implementations on Foreign Types</a></h3>\ <div class=\"sidebar-links\">", ); for (name, id) in res.into_iter() { write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name)); } buf.push_str("</div>"); } } sidebar_assoc_items(cx, buf, it); buf.push_str("<h3 class=\"sidebar-title\"><a href=\"#implementors\">Implementors</a></h3>"); if t.is_auto { buf.push_str( "<h3 class=\"sidebar-title\"><a \ href=\"#synthetic-implementors\">Auto Implementors</a></h3>", ); } buf.push_str("</div>") } fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) { let mut sidebar = Buffer::new(); sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) { let mut sidebar = Buffer::new(); sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> { let mut fields = fields .iter() .filter(|f| matches!(*f.kind, clean::StructFieldItem(..))) .filter_map(|f| { f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name)) }) .collect::<Vec<_>>(); fields.sort(); fields } fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) { let mut sidebar = Buffer::new(); let fields = get_struct_fields_name(&u.fields); if !fields.is_empty() { sidebar.push_str( "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\ <div class=\"sidebar-links\">", ); for field in fields { sidebar.push_str(&field); } sidebar.push_str("</div>"); } sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) { let mut sidebar = Buffer::new(); let mut variants = e .variants .iter() .filter_map(|v| { v.name .as_ref() .map(|name| format!("<a href=\"#variant.{name}\">{name}</a>", name = name)) }) .collect::<Vec<_>>(); if !variants.is_empty() { variants.sort_unstable(); sidebar.push_str(&format!( "<h3 class=\"sidebar-title\"><a href=\"#variants\">Variants</a></h3>\ <div class=\"sidebar-links\">{}</div>", variants.join(""), )); } sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) { match ty { ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"), ItemType::Module => ("modules", "Modules"), ItemType::Struct => ("structs", "Structs"), ItemType::Union => ("unions", "Unions"), ItemType::Enum => ("enums", "Enums"), ItemType::Function => ("functions", "Functions"), ItemType::Typedef => ("types", "Type Definitions"), ItemType::Static => ("statics", "Statics"), ItemType::Constant => ("constants", "Constants"), ItemType::Trait => ("traits", "Traits"), ItemType::Impl => ("impls", "Implementations"), ItemType::TyMethod => ("tymethods", "Type Methods"), ItemType::Method => ("methods", "Methods"), ItemType::StructField => ("fields", "Struct Fields"), ItemType::Variant => ("variants", "Variants"), ItemType::Macro => ("macros", "Macros"), ItemType::Primitive => ("primitives", "Primitive Types"), ItemType::AssocType => ("associated-types", "Associated Types"), ItemType::AssocConst => ("associated-consts", "Associated Constants"), ItemType::ForeignType => ("foreign-types", "Foreign Types"), ItemType::Keyword => ("keywords", "Keywords"), ItemType::OpaqueTy => ("opaque-types", "Opaque Types"), ItemType::ProcAttribute => ("attributes", "Attribute Macros"), ItemType::ProcDerive => ("derives", "Derive Macros"), ItemType::TraitAlias => ("trait-aliases", "Trait aliases"), ItemType::Generic => unreachable!(), } } fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) { let mut sidebar = String::new(); // Re-exports are handled a bit differently because they can be extern crates or imports. if items.iter().any(|it| { it.name.is_some() && (it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())) }) { let (id, name) = item_ty_to_strs(ItemType::Import); sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name)); } // ordering taken from item_module, reorder, where it prioritized elements in a certain order // to print its headings for &myty in &[ ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct, ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait, ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl, ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant, ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType, ItemType::Keyword, ] { if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) { let (id, name) = item_ty_to_strs(myty); sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name)); } } if !sidebar.is_empty() { write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar); } } fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) { let mut sidebar = Buffer::new(); sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang"; /// Returns a list of all paths used in the type. /// This is used to help deduplicate imported impls /// for reexported types. If any of the contained /// types are re-exported, we don't use the corresponding /// entry from the js file, as inlining will have already /// picked up the impl fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> { let mut out = Vec::new(); let mut visited = FxHashSet::default(); let mut work = VecDeque::new(); let mut process_path = |did: DefId| { let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone()); let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern); if let Some(path) = fqp { out.push(path.join("::")); } }; work.push_back(first_ty); while let Some(ty) = work.pop_front() { if !visited.insert(ty.clone()) { continue; } match ty { clean::Type::ResolvedPath { did, .. } => process_path(did), clean::Type::Tuple(tys) => { work.extend(tys.into_iter()); } clean::Type::Slice(ty) => { work.push_back(*ty); } clean::Type::Array(ty, _) => { work.push_back(*ty); } clean::Type::RawPointer(_, ty) => { work.push_back(*ty); } clean::Type::BorrowedRef { type_, .. } => { work.push_back(*type_); } clean::Type::QPath { self_type, trait_, .. } => { work.push_back(*self_type); process_path(trait_.def_id()); } _ => {} } } out } const MAX_FULL_EXAMPLES: usize = 5; const NUM_VISIBLE_LINES: usize = 10; /// Generates the HTML for example call locations generated via the --scrape-examples flag. fn render_call_locations(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item) { let tcx = cx.tcx(); let def_id = item.def_id.expect_def_id(); let key = tcx.def_path_hash(def_id); let call_locations = match cx.shared.call_locations.get(&key) { Some(call_locations) => call_locations, _ => { return; } }; // Generate a unique ID so users can link to this section for a given method let id = cx.id_map.borrow_mut().derive("scraped-examples"); write!( w, "<div class=\"docblock scraped-example-list\">\ <span></span>\ <h5 id=\"{id}\" class=\"section-header\">\ <a href=\"#{id}\">Examples found in repository</a>\ </h5>", id = id ); // Generate the HTML for a single example, being the title and code block let write_example = |w: &mut Buffer, (path, call_data): (&PathBuf, &CallData)| -> bool { let contents = match fs::read_to_string(&path) { Ok(contents) => contents, Err(err) => { let span = item.span(tcx).inner(); tcx.sess .span_err(span, &format!("failed to read file {}: {}", path.display(), err)); return false; } }; // To reduce file sizes, we only want to embed the source code needed to understand the example, not // the entire file. So we find the smallest byte range that covers all items enclosing examples. assert!(!call_data.locations.is_empty()); let min_loc = call_data.locations.iter().min_by_key(|loc| loc.enclosing_item.byte_span.0).unwrap(); let byte_min = min_loc.enclosing_item.byte_span.0; let line_min = min_loc.enclosing_item.line_span.0; let max_loc = call_data.locations.iter().max_by_key(|loc| loc.enclosing_item.byte_span.1).unwrap(); let byte_max = max_loc.enclosing_item.byte_span.1; let line_max = max_loc.enclosing_item.line_span.1; // The output code is limited to that byte range. let contents_subset = &contents[(byte_min as usize)..(byte_max as usize)]; // The call locations need to be updated to reflect that the size of the program has changed. // Specifically, the ranges are all subtracted by `byte_min` since that's the new zero point. let (mut byte_ranges, line_ranges): (Vec<_>, Vec<_>) = call_data .locations .iter() .map(|loc| { let (byte_lo, byte_hi) = loc.call_expr.byte_span; let (line_lo, line_hi) = loc.call_expr.line_span; let byte_range = (byte_lo - byte_min, byte_hi - byte_min); let line_range = (line_lo - line_min, line_hi - line_min); let (anchor, line_title) = if line_lo == line_hi { (format!("{}", line_lo + 1), format!("line {}", line_lo + 1)) } else { ( format!("{}-{}", line_lo + 1, line_hi + 1), format!("lines {}-{}", line_lo + 1, line_hi + 1), ) }; let line_url = format!("{}{}#{}", cx.root_path(), call_data.url, anchor); (byte_range, (line_range, line_url, line_title)) }) .unzip(); let (_, init_url, init_title) = &line_ranges[0]; let needs_expansion = line_max - line_min > NUM_VISIBLE_LINES; let locations_encoded = serde_json::to_string(&line_ranges).unwrap(); write!( w, "<div class=\"scraped-example {expanded_cls}\" data-locs=\"{locations}\">\ <div class=\"scraped-example-title\">\ {name} (<a href=\"{url}\">{title}</a>)\ </div>\ <div class=\"code-wrapper\">", expanded_cls = if needs_expansion { "" } else { "expanded" }, name = call_data.display_name, url = init_url, title = init_title, // The locations are encoded as a data attribute, so they can be read // later by the JS for interactions. locations = Escape(&locations_encoded) ); if line_ranges.len() > 1 { write!(w, r#"<span class="prev">&pr;</span> <span class="next">&sc;</span>"#); } if needs_expansion { write!(w, r#"<span class="expand">&varr;</span>"#); } // Look for the example file in the source map if it exists, otherwise return a dummy span let file_span = (|| { let source_map = tcx.sess.source_map(); let crate_src = tcx.sess.local_crate_source_file.as_ref()?; let abs_crate_src = crate_src.canonicalize().ok()?; let crate_root = abs_crate_src.parent()?.parent()?; let rel_path = path.strip_prefix(crate_root).ok()?; let files = source_map.files(); let file = files.iter().find(|file| match &file.name { FileName::Real(RealFileName::LocalPath(other_path)) => rel_path == other_path, _ => false, })?; Some(rustc_span::Span::with_root_ctxt( file.start_pos + BytePos(byte_min), file.start_pos + BytePos(byte_max), )) })() .unwrap_or(rustc_span::DUMMY_SP); // The root path is the inverse of Context::current let root_path = vec!["../"; cx.current.len() - 1].join(""); let mut decoration_info = FxHashMap::default(); decoration_info.insert("highlight focus", vec![byte_ranges.remove(0)]); decoration_info.insert("highlight", byte_ranges); sources::print_src( w, contents_subset, call_data.edition, file_span, cx, &root_path, Some(highlight::DecorationInfo(decoration_info)), sources::SourceContext::Embedded { offset: line_min }, ); write!(w, "</div></div>"); true }; // The call locations are output in sequence, so that sequence needs to be determined. // Ideally the most "relevant" examples would be shown first, but there's no general algorithm // for determining relevance. Instead, we prefer the smallest examples being likely the easiest to // understand at a glance. let ordered_locations = { let sort_criterion = |(_, call_data): &(_, &CallData)| { // Use the first location because that's what the user will see initially let (lo, hi) = call_data.locations[0].enclosing_item.byte_span; hi - lo }; let mut locs = call_locations.into_iter().collect::<Vec<_>>(); locs.sort_by_key(sort_criterion); locs }; let mut it = ordered_locations.into_iter().peekable(); // An example may fail to write if its source can't be read for some reason, so this method // continues iterating until a write suceeds let write_and_skip_failure = |w: &mut Buffer, it: &mut Peekable<_>| { while let Some(example) = it.next() { if write_example(&mut *w, example) { break; } } }; // Write just one example that's visible by default in the method's description. write_and_skip_failure(w, &mut it); // Then add the remaining examples in a hidden section. if it.peek().is_some() { write!( w, "<details class=\"rustdoc-toggle more-examples-toggle\">\ <summary class=\"hideme\">\ <span>More examples</span>\ </summary>\ <div class=\"more-scraped-examples\">\ <div class=\"toggle-line\"><div class=\"toggle-line-inner\"></div></div>\ <div class=\"more-scraped-examples-inner\">" ); // Only generate inline code for MAX_FULL_EXAMPLES number of examples. Otherwise we could // make the page arbitrarily huge! for _ in 0..MAX_FULL_EXAMPLES { write_and_skip_failure(w, &mut it); } // For the remaining examples, generate a <ul> containing links to the source files. if it.peek().is_some() { write!(w, r#"<div class="example-links">Additional examples can be found in:<br><ul>"#); it.for_each(|(_, call_data)| { write!( w, r#"<li><a href="{root}{url}">{name}</a></li>"#, root = cx.root_path(), url = call_data.url, name = call_data.display_name ); }); write!(w, "</ul></div>"); } write!(w, "</div></div></details>"); } write!(w, "</div>"); }
utes(it: &
memcache.py
# -*- test-case-name: twisted.test.test_memcache -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Memcache client protocol. Memcached is a caching server, storing data in the form of pairs key/value, and memcache is the protocol to talk with it. To connect to a server, create a factory for L{MemCacheProtocol}:: from twisted.internet import reactor, protocol from twisted.protocols.memcache import MemCacheProtocol, DEFAULT_PORT d = protocol.ClientCreator(reactor, MemCacheProtocol ).connectTCP("localhost", DEFAULT_PORT) def doSomething(proto): # Here you call the memcache operations return proto.set("mykey", "a lot of data") d.addCallback(doSomething) reactor.run() All the operations of the memcache protocol are present, but L{MemCacheProtocol.set} and L{MemCacheProtocol.get} are the more important. See U{http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt} for more information about the protocol. """ from collections import deque from twisted.protocols.basic import LineReceiver from twisted.protocols.policies import TimeoutMixin from twisted.internet.defer import Deferred, fail, TimeoutError from twisted.python import log from twisted.python.compat import ( intToBytes, iteritems, nativeString, networkString) DEFAULT_PORT = 11211 class NoSuchCommand(Exception): """ Exception raised when a non existent command is called. """ class ClientError(Exception): """ Error caused by an invalid client call. """ class ServerError(Exception): """ Problem happening on the server. """ class Command: """ Wrap a client action into an object, that holds the values used in the protocol. @ivar _deferred: the L{Deferred} object that will be fired when the result arrives. @type _deferred: L{Deferred} @ivar command: name of the command sent to the server. @type command: L{bytes} """ def __init__(self, command, **kwargs): """ Create a command. @param command: the name of the command. @type command: L{bytes} @param kwargs: this values will be stored as attributes of the object for future use """ self.command = command self._deferred = Deferred() for k, v in kwargs.items(): setattr(self, k, v) def success(self, value): """ Shortcut method to fire the underlying deferred. """ self._deferred.callback(value) def fail(self, error): """ Make the underlying deferred fails. """ self._deferred.errback(error) class MemCacheProtocol(LineReceiver, TimeoutMixin): """ MemCache protocol: connect to a memcached server to store/retrieve values. @ivar persistentTimeOut: the timeout period used to wait for a response. @type persistentTimeOut: L{int} @ivar _current: current list of requests waiting for an answer from the server. @type _current: L{deque} of L{Command} @ivar _lenExpected: amount of data expected in raw mode, when reading for a value. @type _lenExpected: L{int} @ivar _getBuffer: current buffer of data, used to store temporary data when reading in raw mode. @type _getBuffer: L{list} @ivar _bufferLength: the total amount of bytes in C{_getBuffer}. @type _bufferLength: L{int} @ivar _disconnected: indicate if the connectionLost has been called or not. @type _disconnected: L{bool} """ MAX_KEY_LENGTH = 250 _disconnected = False def __init__(self, timeOut=60): """ Create the protocol. @param timeOut: the timeout to wait before detecting that the connection is dead and close it. It's expressed in seconds. @type timeOut: L{int} """ self._current = deque() self._lenExpected = None self._getBuffer = None self._bufferLength = None self.persistentTimeOut = self.timeOut = timeOut def _cancelCommands(self, reason): """ Cancel all the outstanding commands, making them fail with C{reason}. """ while self._current: cmd = self._current.popleft() cmd.fail(reason) def timeoutConnection(self): """ Close the connection in case of timeout. """ self._cancelCommands(TimeoutError("Connection timeout")) self.transport.loseConnection() def connectionLost(self, reason): """ Cause any outstanding commands to fail. """ self._disconnected = True self._cancelCommands(reason) LineReceiver.connectionLost(self, reason) def sendLine(self, line): """ Override sendLine to add a timeout to response. """ if not self._current: self.setTimeout(self.persistentTimeOut) LineReceiver.sendLine(self, line) def rawDataReceived(self, data): """ Collect data for a get. """ self.resetTimeout() self._getBuffer.append(data) self._bufferLength += len(data) if self._bufferLength >= self._lenExpected + 2:
val = buf self._lenExpected = None self._getBuffer = None self._bufferLength = None cmd = self._current[0] if cmd.multiple: flags, cas = cmd.values[cmd.currentKey] cmd.values[cmd.currentKey] = (flags, cas, val) else: cmd.value = val self.setLineMode(rem) def cmd_STORED(self): """ Manage a success response to a set operation. """ self._current.popleft().success(True) def cmd_NOT_STORED(self): """ Manage a specific 'not stored' response to a set operation: this is not an error, but some condition wasn't met. """ self._current.popleft().success(False) def cmd_END(self): """ This the end token to a get or a stat operation. """ cmd = self._current.popleft() if cmd.command == b"get": if cmd.multiple: values = {key: val[::2] for key, val in iteritems(cmd.values)} cmd.success(values) else: cmd.success((cmd.flags, cmd.value)) elif cmd.command == b"gets": if cmd.multiple: cmd.success(cmd.values) else: cmd.success((cmd.flags, cmd.cas, cmd.value)) elif cmd.command == b"stats": cmd.success(cmd.values) else: raise RuntimeError( "Unexpected END response to %s command" % (nativeString(cmd.command),)) def cmd_NOT_FOUND(self): """ Manage error response for incr/decr/delete. """ self._current.popleft().success(False) def cmd_VALUE(self, line): """ Prepare the reading a value after a get. """ cmd = self._current[0] if cmd.command == b"get": key, flags, length = line.split() cas = b"" else: key, flags, length, cas = line.split() self._lenExpected = int(length) self._getBuffer = [] self._bufferLength = 0 if cmd.multiple: if key not in cmd.keys: raise RuntimeError("Unexpected commands answer.") cmd.currentKey = key cmd.values[key] = [int(flags), cas] else: if cmd.key != key: raise RuntimeError("Unexpected commands answer.") cmd.flags = int(flags) cmd.cas = cas self.setRawMode() def cmd_STAT(self, line): """ Reception of one stat line. """ cmd = self._current[0] key, val = line.split(b" ", 1) cmd.values[key] = val def cmd_VERSION(self, versionData): """ Read version token. """ self._current.popleft().success(versionData) def cmd_ERROR(self): """ A non-existent command has been sent. """ log.err("Non-existent command sent.") cmd = self._current.popleft() cmd.fail(NoSuchCommand()) def cmd_CLIENT_ERROR(self, errText): """ An invalid input as been sent. """ errText = repr(errText) log.err("Invalid input: " + errText) cmd = self._current.popleft() cmd.fail(ClientError(errText)) def cmd_SERVER_ERROR(self, errText): """ An error has happened server-side. """ errText = repr(errText) log.err("Server error: " + errText) cmd = self._current.popleft() cmd.fail(ServerError(errText)) def cmd_DELETED(self): """ A delete command has completed successfully. """ self._current.popleft().success(True) def cmd_OK(self): """ The last command has been completed. """ self._current.popleft().success(True) def cmd_EXISTS(self): """ A C{checkAndSet} update has failed. """ self._current.popleft().success(False) def lineReceived(self, line): """ Receive line commands from the server. """ self.resetTimeout() token = line.split(b" ", 1)[0] # First manage standard commands without space cmd = getattr(self, "cmd_" + nativeString(token), None) if cmd is not None: args = line.split(b" ", 1)[1:] if args: cmd(args[0]) else: cmd() else: # Then manage commands with space in it line = line.replace(b" ", b"_") cmd = getattr(self, "cmd_" + nativeString(line), None) if cmd is not None: cmd() else: # Increment/Decrement response cmd = self._current.popleft() val = int(line) cmd.success(val) if not self._current: # No pending request, remove timeout self.setTimeout(None) def increment(self, key, val=1): """ Increment the value of C{key} by given value (default to 1). C{key} must be consistent with an int. Return the new value. @param key: the key to modify. @type key: L{bytes} @param val: the value to increment. @type val: L{int} @return: a deferred with will be called back with the new value associated with the key (after the increment). @rtype: L{Deferred} """ return self._incrdecr(b"incr", key, val) def decrement(self, key, val=1): """ Decrement the value of C{key} by given value (default to 1). C{key} must be consistent with an int. Return the new value, coerced to 0 if negative. @param key: the key to modify. @type key: L{bytes} @param val: the value to decrement. @type val: L{int} @return: a deferred with will be called back with the new value associated with the key (after the decrement). @rtype: L{Deferred} """ return self._incrdecr(b"decr", key, val) def _incrdecr(self, cmd, key, val): """ Internal wrapper for incr/decr. """ if self._disconnected: return fail(RuntimeError("not connected")) if not isinstance(key, bytes): return fail(ClientError( "Invalid type for key: %s, expecting bytes" % (type(key),))) if len(key) > self.MAX_KEY_LENGTH: return fail(ClientError("Key too long")) fullcmd = b" ".join([cmd, key, intToBytes(int(val))]) self.sendLine(fullcmd) cmdObj = Command(cmd, key=key) self._current.append(cmdObj) return cmdObj._deferred def replace(self, key, val, flags=0, expireTime=0): """ Replace the given C{key}. It must already exist in the server. @param key: the key to replace. @type key: L{bytes} @param val: the new value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded, and C{False} with the key didn't previously exist. @rtype: L{Deferred} """ return self._set(b"replace", key, val, flags, expireTime, b"") def add(self, key, val, flags=0, expireTime=0): """ Add the given C{key}. It must not exist in the server. @param key: the key to add. @type key: L{bytes} @param val: the value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded, and C{False} with the key already exists. @rtype: L{Deferred} """ return self._set(b"add", key, val, flags, expireTime, b"") def set(self, key, val, flags=0, expireTime=0): """ Set the given C{key}. @param key: the key to set. @type key: L{bytes} @param val: the value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded. @rtype: L{Deferred} """ return self._set(b"set", key, val, flags, expireTime, b"") def checkAndSet(self, key, val, cas, flags=0, expireTime=0): """ Change the content of C{key} only if the C{cas} value matches the current one associated with the key. Use this to store a value which hasn't been modified since last time you fetched it. @param key: The key to set. @type key: L{bytes} @param val: The value associated with the key. @type val: L{bytes} @param cas: Unique 64-bit value returned by previous call of C{get}. @type cas: L{bytes} @param flags: The flags to store with the key. @type flags: L{int} @param expireTime: If different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred} """ return self._set(b"cas", key, val, flags, expireTime, cas) def _set(self, cmd, key, val, flags, expireTime, cas): """ Internal wrapper for setting values. """ if self._disconnected: return fail(RuntimeError("not connected")) if not isinstance(key, bytes): return fail(ClientError( "Invalid type for key: %s, expecting bytes" % (type(key),))) if len(key) > self.MAX_KEY_LENGTH: return fail(ClientError("Key too long")) if not isinstance(val, bytes): return fail(ClientError( "Invalid type for value: %s, expecting bytes" % (type(val),))) if cas: cas = b" " + cas length = len(val) fullcmd = b" ".join([ cmd, key, networkString("%d %d %d" % (flags, expireTime, length))]) + cas self.sendLine(fullcmd) self.sendLine(val) cmdObj = Command(cmd, key=key, flags=flags, length=length) self._current.append(cmdObj) return cmdObj._deferred def append(self, key, val): """ Append given data to the value of an existing key. @param key: The key to modify. @type key: L{bytes} @param val: The value to append to the current value associated with the key. @type val: L{bytes} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred} """ # Even if flags and expTime values are ignored, we have to pass them return self._set(b"append", key, val, 0, 0, b"") def prepend(self, key, val): """ Prepend given data to the value of an existing key. @param key: The key to modify. @type key: L{bytes} @param val: The value to prepend to the current value associated with the key. @type val: L{bytes} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred} """ # Even if flags and expTime values are ignored, we have to pass them return self._set(b"prepend", key, val, 0, 0, b"") def get(self, key, withIdentifier=False): """ Get the given C{key}. It doesn't support multiple keys. If C{withIdentifier} is set to C{True}, the command issued is a C{gets}, that will return the current identifier associated with the value. This identifier has to be used when issuing C{checkAndSet} update later, using the corresponding method. @param key: The key to retrieve. @type key: L{bytes} @param withIdentifier: If set to C{True}, retrieve the current identifier along with the value and the flags. @type withIdentifier: L{bool} @return: A deferred that will fire with the tuple (flags, value) if C{withIdentifier} is C{False}, or (flags, cas identifier, value) if C{True}. If the server indicates there is no value associated with C{key}, the returned value will be L{None} and the returned flags will be C{0}. @rtype: L{Deferred} """ return self._get([key], withIdentifier, False) def getMultiple(self, keys, withIdentifier=False): """ Get the given list of C{keys}. If C{withIdentifier} is set to C{True}, the command issued is a C{gets}, that will return the identifiers associated with each values. This identifier has to be used when issuing C{checkAndSet} update later, using the corresponding method. @param keys: The keys to retrieve. @type keys: L{list} of L{bytes} @param withIdentifier: If set to C{True}, retrieve the identifiers along with the values and the flags. @type withIdentifier: L{bool} @return: A deferred that will fire with a dictionary with the elements of C{keys} as keys and the tuples (flags, value) as values if C{withIdentifier} is C{False}, or (flags, cas identifier, value) if C{True}. If the server indicates there is no value associated with C{key}, the returned values will be L{None} and the returned flags will be C{0}. @rtype: L{Deferred} @since: 9.0 """ return self._get(keys, withIdentifier, True) def _get(self, keys, withIdentifier, multiple): """ Helper method for C{get} and C{getMultiple}. """ keys = list(keys) if self._disconnected: return fail(RuntimeError("not connected")) for key in keys: if not isinstance(key, bytes): return fail(ClientError( "Invalid type for key: %s, expecting bytes" % (type(key),))) if len(key) > self.MAX_KEY_LENGTH: return fail(ClientError("Key too long")) if withIdentifier: cmd = b"gets" else: cmd = b"get" fullcmd = b" ".join([cmd] + keys) self.sendLine(fullcmd) if multiple: values = dict([(key, (0, b"", None)) for key in keys]) cmdObj = Command(cmd, keys=keys, values=values, multiple=True) else: cmdObj = Command(cmd, key=keys[0], value=None, flags=0, cas=b"", multiple=False) self._current.append(cmdObj) return cmdObj._deferred def stats(self, arg=None): """ Get some stats from the server. It will be available as a dict. @param arg: An optional additional string which will be sent along with the I{stats} command. The interpretation of this value by the server is left undefined by the memcache protocol specification. @type arg: L{None} or L{bytes} @return: a deferred that will fire with a L{dict} of the available statistics. @rtype: L{Deferred} """ if arg: cmd = b"stats " + arg else: cmd = b"stats" if self._disconnected: return fail(RuntimeError("not connected")) self.sendLine(cmd) cmdObj = Command(b"stats", values={}) self._current.append(cmdObj) return cmdObj._deferred def version(self): """ Get the version of the server. @return: a deferred that will fire with the string value of the version. @rtype: L{Deferred} """ if self._disconnected: return fail(RuntimeError("not connected")) self.sendLine(b"version") cmdObj = Command(b"version") self._current.append(cmdObj) return cmdObj._deferred def delete(self, key): """ Delete an existing C{key}. @param key: the key to delete. @type key: L{bytes} @return: a deferred that will be called back with C{True} if the key was successfully deleted, or C{False} if not. @rtype: L{Deferred} """ if self._disconnected: return fail(RuntimeError("not connected")) if not isinstance(key, bytes): return fail(ClientError( "Invalid type for key: %s, expecting bytes" % (type(key),))) self.sendLine(b"delete " + key) cmdObj = Command(b"delete", key=key) self._current.append(cmdObj) return cmdObj._deferred def flushAll(self): """ Flush all cached values. @return: a deferred that will be called back with C{True} when the operation has succeeded. @rtype: L{Deferred} """ if self._disconnected: return fail(RuntimeError("not connected")) self.sendLine(b"flush_all") cmdObj = Command(b"flush_all") self._current.append(cmdObj) return cmdObj._deferred __all__ = ["MemCacheProtocol", "DEFAULT_PORT", "NoSuchCommand", "ClientError", "ServerError"]
data = b"".join(self._getBuffer) buf = data[:self._lenExpected] rem = data[self._lenExpected + 2:]
parseip.go
package netutil import ( "errors" "fmt" "net" "net/http" "strconv" "strings" ) // returns IP address func ParseRemoteAddress(remote_addr string) (net.IP, error)
func ParseRemoteAddressFromRequest(req *http.Request) (net.IP, error) { return ParseRemoteAddress(req.RemoteAddr) }
{ index := strings.LastIndexByte(remote_addr, ':') if index == -1 { return nil, errors.New("invalid request address (no colon)") } _, err := strconv.ParseUint(remote_addr[index+1:], 10, 16) if err != nil { return nil, err } var ip net.IP if remote_addr[0] == '[' && remote_addr[index-1] == ']' { ip = net.ParseIP(remote_addr[1 : index-1]) if ip == nil { return nil, fmt.Errorf("invalid request address (invalid IP in '%s')", remote_addr) } if strings.Contains(remote_addr[1:index-1], ".") { return nil, fmt.Errorf("IP address was expected to be IPv6, but was IPv4") } } else { ip = net.ParseIP(remote_addr[:index]) if ip == nil { return nil, fmt.Errorf("invalid request address (invalid IP in '%s')", remote_addr) } if strings.Contains(remote_addr[:index], ":") { return nil, fmt.Errorf("IP address was expected to be IPv4, but was IPv6") } } return ip, nil }
parquet_read_parallel.rs
use crossbeam_channel::unbounded; use std::fs::File; use std::sync::Arc; use std::thread; use std::time::SystemTime; use arrow2::{array::Array, compute::cast::cast, error::Result, io::parquet::read}; fn parallel_read(path: &str) -> Result<Vec<Box<dyn Array>>> { // prepare a channel to send serialized records from threads let (tx, rx) = unbounded(); let mut file = File::open(path)?; let file_metadata = read::read_metadata(&mut file)?; let arrow_schema = Arc::new(read::get_schema(&file_metadata)?); let file_metadata = Arc::new(file_metadata); let start = SystemTime::now(); // spawn a thread to produce `Vec<CompressedPage>` (IO bounded) let producer_metadata = file_metadata.clone(); let child = thread::spawn(move || { for column in 0..producer_metadata.schema().num_columns() { for row_group in 0..producer_metadata.row_groups.len() { let start = SystemTime::now(); println!("produce start: {} {}", column, row_group); let pages = read::get_page_iterator(&producer_metadata, row_group, column, &mut file) .unwrap() .collect::<Vec<_>>(); println!( "produce end - {:?}: {} {}", start.elapsed().unwrap(), column, row_group ); tx.send((column, row_group, pages)).unwrap(); } } }); let mut children = Vec::new(); // use 3 consumers of to decompress, decode and deserialize. for _ in 0..3 { let rx_consumer = rx.clone(); let metadata_consumer = file_metadata.clone(); let arrow_schema_consumer = arrow_schema.clone(); let child = thread::spawn(move || { let (column, row_group, iter) = rx_consumer.recv().unwrap(); let start = SystemTime::now(); println!("consumer start - {} {}", column, row_group); let metadata = metadata_consumer.row_groups[row_group].column(column); let array = read::page_iter_to_array(iter.into_iter(), metadata).unwrap(); println!( "consumer end - {:?}: {} {}", start.elapsed().unwrap(), column, row_group ); cast( array.as_ref(), arrow_schema_consumer.field(column).data_type(), ) }); children.push(child); } child.join().expect("child thread panicked"); let arrays = children .into_iter() .map(|x| x.join().unwrap()) .collect::<Result<Vec<_>>>()?; println!("Finished - {:?}", start.elapsed().unwrap()); Ok(arrays) } fn main() -> Result<()>
{ use std::env; let args: Vec<String> = env::args().collect(); let file_path = &args[1]; let arrays = parallel_read(file_path)?; for array in arrays { println!("{}", array) } Ok(()) }
registration_flow.py
# coding: utf-8 """ Ory Kratos Welcome to the ORY Kratos HTTP API documentation! # noqa: E501 The version of the OpenAPI document: v0.5.4-alpha.1 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from ory_kratos_client.configuration import Configuration class RegistrationFlow(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'active': 'str', 'expires_at': 'datetime', 'id': 'str', 'issued_at': 'datetime', 'messages': 'list[Message]', 'methods': 'dict(str, RegistrationFlowMethod)', 'request_url': 'str', 'type': 'str' } attribute_map = { 'active': 'active', 'expires_at': 'expires_at', 'id': 'id', 'issued_at': 'issued_at', 'messages': 'messages', 'methods': 'methods', 'request_url': 'request_url', 'type': 'type' } def __init__(self, active=None, expires_at=None, id=None, issued_at=None, messages=None, methods=None, request_url=None, type=None, local_vars_configuration=None): # noqa: E501 """RegistrationFlow - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._active = None self._expires_at = None self._id = None self._issued_at = None self._messages = None self._methods = None self._request_url = None self._type = None self.discriminator = None if active is not None: self.active = active self.expires_at = expires_at self.id = id self.issued_at = issued_at if messages is not None: self.messages = messages self.methods = methods self.request_url = request_url if type is not None: self.type = type @property def active(self): """Gets the active of this RegistrationFlow. # noqa: E501 and so on. # noqa: E501 :return: The active of this RegistrationFlow. # noqa: E501 :rtype: str """ return self._active @active.setter def active(self, active): """Sets the active of this RegistrationFlow. and so on. # noqa: E501 :param active: The active of this RegistrationFlow. # noqa: E501 :type: str """ self._active = active @property def expires_at(self): """Gets the expires_at of this RegistrationFlow. # noqa: E501 ExpiresAt is the time (UTC) when the flow expires. If the user still wishes to log in, a new flow has to be initiated. # noqa: E501 :return: The expires_at of this RegistrationFlow. # noqa: E501 :rtype: datetime """ return self._expires_at @expires_at.setter def expires_at(self, expires_at): """Sets the expires_at of this RegistrationFlow. ExpiresAt is the time (UTC) when the flow expires. If the user still wishes to log in, a new flow has to be initiated. # noqa: E501 :param expires_at: The expires_at of this RegistrationFlow. # noqa: E501 :type: datetime """ if self.local_vars_configuration.client_side_validation and expires_at is None: # noqa: E501 raise ValueError("Invalid value for `expires_at`, must not be `None`") # noqa: E501 self._expires_at = expires_at @property def id(self): """Gets the id of this RegistrationFlow. # noqa: E501 :return: The id of this RegistrationFlow. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this RegistrationFlow. :param id: The id of this RegistrationFlow. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and id is None: # noqa: E501 raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def issued_at(self): """Gets the issued_at of this RegistrationFlow. # noqa: E501 IssuedAt is the time (UTC) when the flow occurred. # noqa: E501 :return: The issued_at of this RegistrationFlow. # noqa: E501 :rtype: datetime """ return self._issued_at @issued_at.setter def issued_at(self, issued_at): """Sets the issued_at of this RegistrationFlow. IssuedAt is the time (UTC) when the flow occurred. # noqa: E501 :param issued_at: The issued_at of this RegistrationFlow. # noqa: E501 :type: datetime """ if self.local_vars_configuration.client_side_validation and issued_at is None: # noqa: E501 raise ValueError("Invalid value for `issued_at`, must not be `None`") # noqa: E501 self._issued_at = issued_at @property def
(self): """Gets the messages of this RegistrationFlow. # noqa: E501 :return: The messages of this RegistrationFlow. # noqa: E501 :rtype: list[Message] """ return self._messages @messages.setter def messages(self, messages): """Sets the messages of this RegistrationFlow. :param messages: The messages of this RegistrationFlow. # noqa: E501 :type: list[Message] """ self._messages = messages @property def methods(self): """Gets the methods of this RegistrationFlow. # noqa: E501 Methods contains context for all enabled registration methods. If a registration flow has been processed, but for example the password is incorrect, this will contain error messages. # noqa: E501 :return: The methods of this RegistrationFlow. # noqa: E501 :rtype: dict(str, RegistrationFlowMethod) """ return self._methods @methods.setter def methods(self, methods): """Sets the methods of this RegistrationFlow. Methods contains context for all enabled registration methods. If a registration flow has been processed, but for example the password is incorrect, this will contain error messages. # noqa: E501 :param methods: The methods of this RegistrationFlow. # noqa: E501 :type: dict(str, RegistrationFlowMethod) """ if self.local_vars_configuration.client_side_validation and methods is None: # noqa: E501 raise ValueError("Invalid value for `methods`, must not be `None`") # noqa: E501 self._methods = methods @property def request_url(self): """Gets the request_url of this RegistrationFlow. # noqa: E501 RequestURL is the initial URL that was requested from ORY Kratos. It can be used to forward information contained in the URL's path or query for example. # noqa: E501 :return: The request_url of this RegistrationFlow. # noqa: E501 :rtype: str """ return self._request_url @request_url.setter def request_url(self, request_url): """Sets the request_url of this RegistrationFlow. RequestURL is the initial URL that was requested from ORY Kratos. It can be used to forward information contained in the URL's path or query for example. # noqa: E501 :param request_url: The request_url of this RegistrationFlow. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and request_url is None: # noqa: E501 raise ValueError("Invalid value for `request_url`, must not be `None`") # noqa: E501 self._request_url = request_url @property def type(self): """Gets the type of this RegistrationFlow. # noqa: E501 The flow type can either be `api` or `browser`. # noqa: E501 :return: The type of this RegistrationFlow. # noqa: E501 :rtype: str """ return self._type @type.setter def type(self, type): """Sets the type of this RegistrationFlow. The flow type can either be `api` or `browser`. # noqa: E501 :param type: The type of this RegistrationFlow. # noqa: E501 :type: str """ self._type = type def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RegistrationFlow): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, RegistrationFlow): return True return self.to_dict() != other.to_dict()
messages
disclosure.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-disclosure', templateUrl: './disclosure.component.html', styleUrls: ['./disclosure.component.css'] }) export class
implements OnInit { constructor() { } ngOnInit() { } }
DisclosureComponent
tisane_multifg.py
description = 'frequency counter, fg1 and fg2' excludes = ['frequency'] # group = 'lowlevel' tango_base = 'tango://sans1hw.sans1.frm2:10000/sans1/tisane' ARMING_STRING_FC = ( ':FUNC "FREQ";' ':CALC:AVER 1;' ':CALC:SMO:RESP FAST;' ':CALC:SMO 1;' ':INP:COUP AC;' ':INP:FILT 0;' ':INP:IMP +1.00000000E+006;' ':INP:LEV -1.80000000E+000;' ':INP:LEV:REL +50;'
':INP:LEV:AUTO 0;' ':INP:NREJ 1;' ':INP:PROB +1;' ':INP:RANG +5.00000000E+000;' ':INP:SLOP POS;' ':MMEM:CDIR "INT:\\";' ':OUTP:POL NORM;' ':OUTP 0;' ':SAMP:COUN +1;' ':FREQ:GATE:POL NEG;' ':FREQ:GATE:SOUR TIME;' ':FREQ:GATE:TIME +1.00000000000000E-001;' ':TRIG:COUN +1;' ':TRIG:DEL +0.00000000000000E+000;' ':TRIG:SLOP NEG;' ':TRIG:SOUR IMM;' ) ARMING_STRING = ( '*RST;' ':SOUR1:FUNC:SHAP SQU;' ':SOUR1:FREQ 5;' ':SOUR1:VOLT 2.4;' ':SOUR1:VOLT:UNIT VPP;' ':SOUR1:VOLT:OFFS 1.3;' ':SOUR1:FUNCtion:SQU:DCYCle 50;' ':SOUR1:AM:STATe OFF;' ':SOUR1:SWEep:STATe OFF;' ':SOUR1:BURSt:MODE TRIG;' ':OUTP1:LOAD 50;' ':OUTP1:POL NORM;' ':TRIG1:SOUR EXT;' ':SOUR1:BURSt:NCYCles 9.9E37;' ':SOUR2:FUNC:SHAP SQU;' ':SOUR2:FREQ 10;' ':SOUR2:VOLT 5;' ':SOUR2:VOLT:UNIT VPP;' ':SOUR2:VOLT:OFFS 1.3;' ':SOUR2:FUNCtion:SQU:DCYCle 50;' ':SOUR2:AM:STATe OFF;' ':SOUR2:SWEep:STATe OFF;' ':SOUR2:BURSt:MODE TRIG;' ':OUTP2:LOAD 50;' ':OUTP2:POL NORM;' ':TRIG2:SOUR EXT;' ':SOUR2:BURSt:NCYCles 9.9E37;' ':SOUR1:BURSt:STATe ON;' ':SOUR2:BURSt:STATe ON;' ':OUTP1 ON;' ':OUTP2 ON;' ) OFF_STRING = ( ':OUTP1 OFF;' ':OUTP2 OFF;' ':SOUR1:BURSt:STATe OFF;' ':SOUR2:BURSt:STATe OFF;' ) devices = dict( tisane_fc = device('nicos.devices.entangle.Sensor', description = "Frequency counter for chopper signal", tangodevice = "%s/fc1_frequency" % tango_base, unit = "Hz", pollinterval = 1, fmtstr = '%.6f', ), tisane_fc_trigger = device('nicos_mlz.devices.io_trigger.Trigger', description = "String blasting device", tangodevice = "%s/fc1_io" % tango_base, lowlevel = True, safesetting = 'idle', strings = {'idle' : '', 'arm' : ARMING_STRING_FC, } ), # tisane_fg1_sample = device('nicos_mlz.sans1.devices.tisane.Burst', # description = "Signal-generator for sample tisane signal", # tangodevice = "%s_multifg/ch1_burst" % tango_base, # frequency = 1000, # amplitude = 2.5, # offset = 1.3, # shape = 'square', # duty = 50, # mapping = dict(On = 1, Off = 0), # ), # tisane_fg2_det = device('nicos_mlz.sans1.devices.tisane.Burst', # description = "Signal-generator for detector tisane signal", # tangodevice = "%s_multifg/ch2_burst" % tango_base, # frequency = 1000, # amplitude = 5.0, # offset = 1.3, # shape = 'square', # duty = 50, # mapping = dict(On = 1, Off = 0), # ), tisane_fg_multi = device('nicos_mlz.devices.io_trigger.Trigger', description = "String blasting device", tangodevice = "%s_multifg/io" % tango_base, safesetting = 'idle', strings = {'idle' : '', 'arm' : ARMING_STRING, 'off' : OFF_STRING, } ), )
test_xlsx_model.py
# # coding=utf-8 import unittest import sys import os from io import open import openpyxl as xl from pptx_template.xlsx_model import _build_tsv, _format_cell_value, generate_whole_model class Cell: def __init__(self, value, number_format): self.value = value self.number_format = number_format def _to_cells(list_of_list): return [[Cell(value, '') for value in list] for list in list_of_list] class MyTest(unittest.TestCase): def test_build_tsv(self): tsv = _build_tsv([_to_cells([["Year","A","B"],["2016",100,200]])]) self.assertEqual([["Year","A","B"],["2016",100,200]], tsv) def test_build_tsv_tranapose(self): tsv = _build_tsv([_to_cells([["Year","A","B"],["2016",100,200]])], transpose=True) self.assertEqual([["Year","2016"],["A",100],["B",200]], tsv) def test_build_tsv_side_by_side(self): tsv = _build_tsv([_to_cells([["Year","A"],["2016",100]]), _to_cells([["B"],[200]])], side_by_side=True) self.assertEqual([["Year","A","B"],["2016",100,200]], tsv) def test_format_cell_value(self): self.assertEqual(123.45678, _format_cell_value(Cell(123.45678, ''))) self.assertEqual("123", _format_cell_value(Cell(123.45678, '0'))) self.assertEqual("123.46", _format_cell_value(Cell(123.45678, '0.00')))
def test_generate_whole_model(self): def read_expect(name): file_name = os.path.join(os.path.dirname(__file__), 'data2', name) f = open(file_name, mode = 'r', encoding = 'utf-8') result = f.read() f.close() return result xls_file = os.path.join(os.path.dirname(__file__), 'data2', 'in.xlsx') slides = generate_whole_model(xls_file, {}) self.assertEqual(u'Hello!', slides['p01']['greeting']['en']) self.assertEqual(u'こんにちは!', slides['p01']['greeting']['ja']) self.assertEqual([ ['Season', u'売り上げ', u'利益', u'利益率'], [u'春', 100, 50, 0.5], [u'夏', 110, 60, 0.5], [u'秋', 120, 70, 0.5], [u'冬', 130, 0, 0.6], ], slides['p02']['array']) self.assertEqual(read_expect('p02-normal.tsv'), slides['p02']['normal']['tsv_body']) self.assertEqual(read_expect('p02-transpose.tsv'), slides['p02']['transpose']['tsv_body']) self.assertEqual(read_expect('p02-sidebyside.tsv'), slides['p02']['sidebyside']['tsv_body']) if __name__ == '__main__': unittest.main()
self.assertEqual("123.5", _format_cell_value(Cell(123.45678, '0.0_'))) self.assertEqual("12345.7%", _format_cell_value(Cell(123.45678, '0.0%_'))) self.assertEqual("12345%", _format_cell_value(Cell(123.45678, '0%_')))
lib.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { core::cmp::{self, Ord, Ordering}, itertools, log::*, std::{convert::TryFrom, fmt, iter}, thiserror::Error, }; /// A child moniker locally identifies a child component instance using the name assigned by /// its parent and its collection (if present). It is a building block for more complex monikers. /// /// Display notation: "[collection:]name:instance_id". #[derive(Eq, PartialEq, Debug, Clone, Hash)] pub struct ChildMoniker { name: String, collection: Option<String>, instance: InstanceId, rep: String, } pub type InstanceId = u32; impl ChildMoniker { pub fn new(name: String, collection: Option<String>, instance: InstanceId) -> Self { assert!(!name.is_empty()); let rep = if let Some(c) = collection.as_ref() { assert!(!c.is_empty()); format!("{}:{}:{}", c, name, instance) } else { format!("{}:{}", name, instance) }; Self { name, collection, instance, rep } } /// Parses an `ChildMoniker` from a string. /// /// Input strings should be of the format `<name>(:<collection>)?:<instance_id>`, e.g. `foo:42` /// or `biz:foo:42`. fn parse(rep: &str) -> Result<Self, MonikerError> { let parts: Vec<_> = rep.split(":").collect(); let invalid = || MonikerError::invalid_moniker(rep); // An instanced moniker is either just a name (static instance), or // collection:name:instance_id. if parts.len() != 2 && parts.len() != 3 { return Err(invalid()); } for p in parts.iter() { if p.is_empty() { return Err(invalid()); } } let (name, coll, instance) = match parts.len() == 3 { true => { let name = parts[1].to_string(); let coll = parts[0].to_string(); let instance: InstanceId = match parts[2].parse() { Ok(i) => i, _ => { return Err(invalid()); } }; (name, Some(coll), instance) } false => { let instance: InstanceId = match parts[1].parse() { Ok(i) => i, _ => { return Err(invalid()); } }; (parts[0].to_string(), None, instance) } }; Ok(Self::new(name, coll, instance)) } /// Converts this instanced moniker to a regular child moniker by stripping the instance id. pub fn to_partial(&self) -> PartialMoniker { PartialMoniker::new(self.name.clone(), self.collection.clone()) } /// Converts this child moniker to an instanced moniker. pub fn from_partial(m: &PartialMoniker, instance: InstanceId) -> Self { Self::new(m.name.clone(), m.collection.clone(), instance) } pub fn name(&self) -> &str { &self.name } pub fn collection(&self) -> Option<&str> { self.collection.as_ref().map(|s| &**s) } pub fn instance(&self) -> InstanceId { self.instance } pub fn as_str(&self) -> &str { &self.rep } } impl From<&str> for ChildMoniker { fn from(rep: &str) -> Self { ChildMoniker::parse(rep).expect(&format!("instanced moniker failed to parse: {}", rep)) } } impl Ord for ChildMoniker { fn cmp(&self, other: &Self) -> Ordering { (&self.collection, &self.name, &self.instance).cmp(&( &other.collection, &other.name, &other.instance, )) } } impl PartialOrd for ChildMoniker { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl fmt::Display for ChildMoniker { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.as_str()) } } /// A variant of child moniker that does not distinguish between instances /// /// Display notation: "name[:collection]". #[derive(Eq, PartialEq, Debug, Clone, Hash)] pub struct PartialMoniker { name: String, collection: Option<String>, rep: String, } impl PartialMoniker { pub fn new(name: String, collection: Option<String>) -> Self { assert!(!name.is_empty()); let rep = if let Some(c) = collection.as_ref() { assert!(!c.is_empty()); format!("{}:{}", c, name) } else { name.clone() }; PartialMoniker { name, collection, rep } } /// Parses a `PartialMoniker` from a string. /// /// Input strings should be of the format `<name>(:<collection>)?`, e.g. `foo` or `biz:foo`. fn
(rep: &str) -> Result<Self, MonikerError> { let mut parts = rep.split(":").fuse(); let invalid = || MonikerError::invalid_moniker(rep); let first = parts.next().ok_or_else(invalid)?; let second = parts.next(); if parts.next().is_some() || first.len() == 0 || second.map_or(false, |s| s.len() == 0) { return Err(invalid()); } let (name, coll) = match second { Some(s) => (s, Some(first.to_string())), None => (first, None), }; Ok(PartialMoniker::new(name.to_string(), coll)) } pub fn name(&self) -> &str { &self.name } pub fn collection(&self) -> Option<&str> { self.collection.as_ref().map(|s| &**s) } pub fn as_str(&self) -> &str { &self.rep } } impl From<&str> for PartialMoniker { fn from(rep: &str) -> Self { PartialMoniker::parse(rep).expect(&format!("child moniker failed to parse: {}", rep)) } } impl Ord for PartialMoniker { fn cmp(&self, other: &Self) -> Ordering { (&self.collection, &self.name).cmp(&(&other.collection, &other.name)) } } impl PartialOrd for PartialMoniker { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl fmt::Display for PartialMoniker { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.as_str()) } } /// An absolute moniker describes the identity of a component instance in terms of its path /// relative to the root of the component instance tree. /// /// A root moniker is a moniker with an empty path. /// /// Absolute monikers are only used internally within the component manager. Externally, /// components are referenced by encoded relative moniker so as to minimize the amount of /// information which is disclosed about the overall structure of the component instance tree. /// /// Display notation: "/", "/name1:1", "/name1:1/name2:2", ... #[derive(Eq, PartialEq, Debug, Clone, Hash)] pub struct AbsoluteMoniker { path: Vec<ChildMoniker>, } impl AbsoluteMoniker { pub fn new(path: Vec<ChildMoniker>) -> AbsoluteMoniker { AbsoluteMoniker { path } } fn parse(path: &Vec<&str>) -> Result<Self, MonikerError> { let path: Result<Vec<ChildMoniker>, MonikerError> = path.iter().map(|x| ChildMoniker::parse(x)).collect(); Ok(AbsoluteMoniker::new(path?)) } /// Parse the given string as an absolute moniker. The string should be a '/' delimited series /// of child monikers without any instance identifiers, e.g. "/", or "/name1/name2" or /// "/name1:collection1". // TODO(fxbug.dev/49968): Remove instance ID 0 assumption when removing instance IDs from // AbsoluteMoniker/ChildMoniker (and rename to parse_str + add From<&str> impl). pub fn parse_string_without_instances(input: &str) -> Result<Self, MonikerError> { if input.chars().nth(0) != Some('/') { return Err(MonikerError::invalid_moniker(input)); } if input == "/" { return Ok(Self::root()); } let path = input[1..] .split('/') .map(PartialMoniker::parse) .map(|p| p.map(|ok_p| ChildMoniker::from_partial(&ok_p, 0))) .collect::<Result<_, MonikerError>>()?; Ok(Self::new(path)) } // Serializes absolute moniker into its string format, omitting instance ids. // // This method is the inverse of `parse_string_without_instances()`. pub fn to_string_without_instances(&self) -> String { format!( "/{}", itertools::join( (&self.path) .into_iter() .map(|segment: &ChildMoniker| segment.to_partial().as_str().to_string()), "/" ) ) } /// Given an absolute moniker realm `start`, and a relative moniker from `start` to an `end` /// realm, returns the absolute moniker of the `end` realm. /// /// If an absolute moniker cannot be computed, then a MonikerError::InvalidMoniker error is /// returned. /// /// Example: /// /// a /// / \ /// b c /// / /// d /// /// Given: /// `start` = /a/c /// `start_to_end` (c -> d) = .\c/b/d /// Returns: /// /a/b/d pub fn from_relative( start: &AbsoluteMoniker, start_to_end: &RelativeMoniker, ) -> Result<AbsoluteMoniker, MonikerError> { // Verify that `start.path`'s tail is of `start_to_end.up_path`. if start_to_end.up_path.len() > start.path.len() || !start_to_end.up_path.iter().eq(start .path .iter() .rev() .take(start_to_end.up_path.len())) { return Err(MonikerError::invalid_moniker(format!("{}", start))); } Ok(AbsoluteMoniker::new( start .path .iter() .take(start.path.len() - start_to_end.up_path.len()) // remove the first `start_to_end.up_path` elements from `from` .chain(start_to_end.down_path.iter()) // append the `start_to_end.down_path` elements .cloned() .collect(), )) } pub fn path(&self) -> &Vec<ChildMoniker> { &self.path } /// Indicates whether `other` is contained within the realm specified by /// this AbsoluteMoniker. pub fn contains_in_realm(&self, other: &AbsoluteMoniker) -> bool { if other.path.len() < self.path.len() { return false; } self.path.iter().enumerate().all(|item| *item.1 == other.path[item.0]) } pub fn root() -> AbsoluteMoniker { AbsoluteMoniker { path: vec![] } } pub fn leaf(&self) -> Option<&ChildMoniker> { self.path.last() } pub fn is_root(&self) -> bool { self.path.is_empty() } pub fn parent(&self) -> Option<AbsoluteMoniker> { if self.is_root() { None } else { let l = self.path.len() - 1; Some(AbsoluteMoniker { path: self.path[..l].to_vec() }) } } pub fn child(&self, child: ChildMoniker) -> AbsoluteMoniker { let mut path = self.path.clone(); path.push(child); AbsoluteMoniker { path } } } impl From<Vec<&str>> for AbsoluteMoniker { fn from(rep: Vec<&str>) -> Self { AbsoluteMoniker::parse(&rep) .expect(&format!("absolute moniker failed to parse: {:?}", &rep)) } } impl cmp::Ord for AbsoluteMoniker { fn cmp(&self, other: &Self) -> cmp::Ordering { let min_size = cmp::min(self.path.len(), other.path.len()); for i in 0..min_size { if self.path[i] < other.path[i] { return cmp::Ordering::Less; } else if self.path[i] > other.path[i] { return cmp::Ordering::Greater; } } if self.path.len() > other.path.len() { return cmp::Ordering::Greater; } else if self.path.len() < other.path.len() { return cmp::Ordering::Less; } return cmp::Ordering::Equal; } } impl PartialOrd for AbsoluteMoniker { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl fmt::Display for AbsoluteMoniker { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.path.is_empty() { write!(f, "/")?; } else { for segment in &self.path { write!(f, "/{}", segment.as_str())? } } Ok(()) } } /// One of: /// - An absolute moniker /// - A marker representing component manager's realm #[derive(Eq, PartialEq, Debug, Clone, Hash)] pub enum ExtendedMoniker { ComponentInstance(AbsoluteMoniker), ComponentManager, } /// The string representation of ExtendedMoniker::ComponentManager const EXTENDED_MONIKER_COMPONENT_MANAGER_STR: &'static str = "<component_manager>"; impl ExtendedMoniker { pub fn parse_string_without_instances(rep: &str) -> Result<Self, MonikerError> { if rep == EXTENDED_MONIKER_COMPONENT_MANAGER_STR { Ok(ExtendedMoniker::ComponentManager) } else { Ok(ExtendedMoniker::ComponentInstance(AbsoluteMoniker::parse_string_without_instances( rep, )?)) } } } impl fmt::Display for ExtendedMoniker { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::ComponentInstance(m) => { write!(f, "{}", m)?; } Self::ComponentManager => { write!(f, "{}", EXTENDED_MONIKER_COMPONENT_MANAGER_STR)?; } } Ok(()) } } /// A relative moniker describes the identity of a component instance in terms of its path /// relative to another (unspecified) component in the component instance tree. /// /// A self-reference moniker is a moniker with both empty "up" and "down" paths. /// /// Relative monikers consist of two paths called "up" and "down". /// - The "up" path describes a sequence of child-to-parent traversals heading towards the root of /// the component instance tree. /// - The "down" path describes a sequence of parent-to-child traversals heading towards a /// different component instance in the tree. /// /// These paths are minimal: no suffix segments of the "up" path can be a prefix segments of the /// "down" path. All such common segments must be elided as part of canonicalizing the relative /// moniker prior to construction. /// /// Naming child monikers along both the "upwards" and "downwards" paths provides a strong /// guarantee that relative monikers are only meaningful when interpreted within isomorphic /// component instance subtrees. (Compare with relative filesystem path notations which use ".." /// to perform upwards traversal and offer correspondingly weaker guarantees.) /// /// For example, if two sibling component instances named "A" and "B" both possess relative /// monikers for another component instance named "C", then A's moniker for C and B's moniker /// for C will be distinct. /// /// Display notation: ".", "./down1", ".\up1/down1", ".\up1\up2/down1", ... #[derive(Eq, PartialEq, Debug, Clone)] pub struct RelativeMoniker { up_path: Vec<ChildMoniker>, down_path: Vec<ChildMoniker>, } impl RelativeMoniker { pub fn new(up_path: Vec<ChildMoniker>, down_path: Vec<ChildMoniker>) -> RelativeMoniker { RelativeMoniker { up_path, down_path } } pub fn from_absolute(from: &AbsoluteMoniker, to: &AbsoluteMoniker) -> RelativeMoniker { let mut from_path = from.path().iter().peekable(); let mut to_path = to.path().iter().peekable(); while from_path.peek().is_some() && from_path.peek() == to_path.peek() { from_path.next(); to_path.next(); } let mut res = RelativeMoniker { up_path: from_path.cloned().collect(), down_path: to_path.cloned().collect(), }; res.up_path.reverse(); res } pub fn up_path(&self) -> &Vec<ChildMoniker> { &self.up_path } pub fn down_path(&self) -> &Vec<ChildMoniker> { &self.down_path } pub fn is_self(&self) -> bool { self.up_path.is_empty() && self.down_path.is_empty() } pub fn to_string_without_instances(&self) -> String { let mut res = ".".to_string(); for (segment, leading_char) in self .up_path .iter() .zip(iter::repeat("\\")) .chain(self.down_path.iter().zip(iter::repeat("/"))) { res.push_str(leading_char); res.push_str(segment.name()); if let Some(collection) = segment.collection() { res.push_str(":"); res.push_str(collection); } } res } /// Parses n `RelativeMoniker` from a string. /// /// Input strings should be of the format /// `.(\<name>(:<collection>)?:<instance_id>)*(/<name>(:<collection>)?:<instance_id>)*`, such /// as `.\foo:42/bar:12/baz:54` or `./biz:foo:42`. fn parse(rep: &str) -> Result<Self, MonikerError> { if rep.chars().nth(0) != Some('.') { return Err(MonikerError::invalid_moniker(rep)); } let stripped_input = rep.strip_prefix(".").unwrap(); let mut up_vs_down = stripped_input.splitn(2, '/'); let set_one = up_vs_down.next().unwrap(); let set_two = up_vs_down.next(); let up_string = set_one.strip_prefix("\\").unwrap_or(set_one); let down_string = set_two.unwrap_or(""); if up_string == "" && down_string == "" { return Ok(Self::new(vec![], vec![])); } if down_string.contains("\\") { return Err(MonikerError::invalid_moniker(rep)); } let up_path; if up_string == "" { up_path = vec![]; } else { up_path = up_string .split("\\") .map(ChildMoniker::parse) .collect::<Result<Vec<ChildMoniker>, MonikerError>>()?; } let down_path; if down_string == "" { down_path = vec![]; } else { down_path = down_string .split("/") .map(ChildMoniker::parse) .collect::<Result<Vec<ChildMoniker>, MonikerError>>()?; } Ok(RelativeMoniker { up_path, down_path }) } } impl fmt::Display for RelativeMoniker { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, ".")?; for segment in &self.up_path { write!(f, "\\{}", segment)? } for segment in &self.down_path { write!(f, "/{}", segment)? } Ok(()) } } impl TryFrom<&str> for RelativeMoniker { type Error = MonikerError; fn try_from(input: &str) -> Result<Self, MonikerError> { RelativeMoniker::parse(input) } } /// Errors produced by `MonikerEnvironment`. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum MonikerError { #[error("invalid moniker: {}", rep)] InvalidMoniker { rep: String }, } impl MonikerError { pub fn invalid_moniker(rep: impl Into<String>) -> MonikerError { MonikerError::InvalidMoniker { rep: rep.into() } } } #[cfg(test)] mod tests { use {super::*, anyhow::Error, std::convert::TryInto}; #[test] fn child_monikers() { let m = ChildMoniker::new("test".to_string(), None, 42); assert_eq!("test", m.name()); assert_eq!(None, m.collection()); assert_eq!(42, m.instance()); assert_eq!("test:42", m.as_str()); assert_eq!("test:42", format!("{}", m)); assert_eq!(m, ChildMoniker::from("test:42")); assert_eq!("test", m.to_partial().as_str()); assert_eq!(m, ChildMoniker::from_partial(&"test".into(), 42)); let m = ChildMoniker::new("test".to_string(), Some("coll".to_string()), 42); assert_eq!("test", m.name()); assert_eq!(Some("coll"), m.collection()); assert_eq!(42, m.instance()); assert_eq!("coll:test:42", m.as_str()); assert_eq!("coll:test:42", format!("{}", m)); assert_eq!(m, ChildMoniker::from("coll:test:42")); assert_eq!("coll:test", m.to_partial().as_str()); assert_eq!(m, ChildMoniker::from_partial(&"coll:test".into(), 42)); assert!(ChildMoniker::parse("").is_err(), "cannot be empty"); assert!(ChildMoniker::parse(":").is_err(), "cannot be empty with colon"); assert!(ChildMoniker::parse("::").is_err(), "cannot be empty with double colon"); assert!(ChildMoniker::parse("f:").is_err(), "second part cannot be empty with colon"); assert!(ChildMoniker::parse(":1").is_err(), "first part cannot be empty with colon"); assert!(ChildMoniker::parse("f:f:").is_err(), "third part cannot be empty with colon"); assert!(ChildMoniker::parse("f::1").is_err(), "second part cannot be empty with colon"); assert!(ChildMoniker::parse(":f:1").is_err(), "first part cannot be empty with colon"); assert!(ChildMoniker::parse("f:f:1:1").is_err(), "more than three colons not allowed"); assert!(ChildMoniker::parse("f:f").is_err(), "second part must be int"); assert!(ChildMoniker::parse("f:f:f").is_err(), "third part must be int"); } #[test] fn child_moniker_compare() { let a = ChildMoniker::new("a".to_string(), None, 1); let a2 = ChildMoniker::new("a".to_string(), None, 2); let aa = ChildMoniker::new("a".to_string(), Some("a".to_string()), 1); let aa2 = ChildMoniker::new("a".to_string(), Some("a".to_string()), 2); let ab = ChildMoniker::new("a".to_string(), Some("b".to_string()), 1); let ba = ChildMoniker::new("b".to_string(), Some("a".to_string()), 1); let bb = ChildMoniker::new("b".to_string(), Some("b".to_string()), 1); let aa_same = ChildMoniker::new("a".to_string(), Some("a".to_string()), 1); assert_eq!(Ordering::Less, a.cmp(&a2)); assert_eq!(Ordering::Greater, a2.cmp(&a)); assert_eq!(Ordering::Less, a2.cmp(&aa)); assert_eq!(Ordering::Greater, aa.cmp(&a2)); assert_eq!(Ordering::Less, a.cmp(&ab)); assert_eq!(Ordering::Greater, ab.cmp(&a)); assert_eq!(Ordering::Less, a.cmp(&ba)); assert_eq!(Ordering::Greater, ba.cmp(&a)); assert_eq!(Ordering::Less, a.cmp(&bb)); assert_eq!(Ordering::Greater, bb.cmp(&a)); assert_eq!(Ordering::Less, aa.cmp(&aa2)); assert_eq!(Ordering::Greater, aa2.cmp(&aa)); assert_eq!(Ordering::Less, aa.cmp(&ab)); assert_eq!(Ordering::Greater, ab.cmp(&aa)); assert_eq!(Ordering::Less, aa.cmp(&ba)); assert_eq!(Ordering::Greater, ba.cmp(&aa)); assert_eq!(Ordering::Less, aa.cmp(&bb)); assert_eq!(Ordering::Greater, bb.cmp(&aa)); assert_eq!(Ordering::Equal, aa.cmp(&aa_same)); assert_eq!(Ordering::Equal, aa_same.cmp(&aa)); assert_eq!(Ordering::Greater, ab.cmp(&ba)); assert_eq!(Ordering::Less, ba.cmp(&ab)); assert_eq!(Ordering::Less, ab.cmp(&bb)); assert_eq!(Ordering::Greater, bb.cmp(&ab)); assert_eq!(Ordering::Less, ba.cmp(&bb)); assert_eq!(Ordering::Greater, bb.cmp(&ba)); } #[test] fn partial_monikers() { let m = PartialMoniker::new("test".to_string(), None); assert_eq!("test", m.name()); assert_eq!(None, m.collection()); assert_eq!("test", m.as_str()); assert_eq!("test", format!("{}", m)); assert_eq!(m, PartialMoniker::from("test")); let m = PartialMoniker::new("test".to_string(), Some("coll".to_string())); assert_eq!("test", m.name()); assert_eq!(Some("coll"), m.collection()); assert_eq!("coll:test", m.as_str()); assert_eq!("coll:test", format!("{}", m)); assert_eq!(m, PartialMoniker::from("coll:test")); assert!(PartialMoniker::parse("").is_err(), "cannot be empty"); assert!(PartialMoniker::parse(":").is_err(), "cannot be empty with colon"); assert!(PartialMoniker::parse("f:").is_err(), "second part cannot be empty with colon"); assert!(PartialMoniker::parse(":f").is_err(), "first part cannot be empty with colon"); assert!(PartialMoniker::parse("f:f:f").is_err(), "multiple colons not allowed"); } #[test] fn partial_moniker_compare() { let a = PartialMoniker::new("a".to_string(), None); let aa = PartialMoniker::new("a".to_string(), Some("a".to_string())); let ab = PartialMoniker::new("a".to_string(), Some("b".to_string())); let ba = PartialMoniker::new("b".to_string(), Some("a".to_string())); let bb = PartialMoniker::new("b".to_string(), Some("b".to_string())); let aa_same = PartialMoniker::new("a".to_string(), Some("a".to_string())); assert_eq!(Ordering::Less, a.cmp(&aa)); assert_eq!(Ordering::Greater, aa.cmp(&a)); assert_eq!(Ordering::Less, a.cmp(&ab)); assert_eq!(Ordering::Greater, ab.cmp(&a)); assert_eq!(Ordering::Less, a.cmp(&ba)); assert_eq!(Ordering::Greater, ba.cmp(&a)); assert_eq!(Ordering::Less, a.cmp(&bb)); assert_eq!(Ordering::Greater, bb.cmp(&a)); assert_eq!(Ordering::Less, aa.cmp(&ab)); assert_eq!(Ordering::Greater, ab.cmp(&aa)); assert_eq!(Ordering::Less, aa.cmp(&ba)); assert_eq!(Ordering::Greater, ba.cmp(&aa)); assert_eq!(Ordering::Less, aa.cmp(&bb)); assert_eq!(Ordering::Greater, bb.cmp(&aa)); assert_eq!(Ordering::Equal, aa.cmp(&aa_same)); assert_eq!(Ordering::Equal, aa_same.cmp(&aa)); assert_eq!(Ordering::Greater, ab.cmp(&ba)); assert_eq!(Ordering::Less, ba.cmp(&ab)); assert_eq!(Ordering::Less, ab.cmp(&bb)); assert_eq!(Ordering::Greater, bb.cmp(&ab)); assert_eq!(Ordering::Less, ba.cmp(&bb)); assert_eq!(Ordering::Greater, bb.cmp(&ba)); } #[test] fn absolute_monikers() { let root = AbsoluteMoniker::root(); assert_eq!(true, root.is_root()); assert_eq!("/", format!("{}", root)); assert_eq!(root, AbsoluteMoniker::from(vec![])); let m = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), Some("coll".to_string()), 2), ]); assert_eq!(false, m.is_root()); assert_eq!("/a:1/coll:b:2", format!("{}", m)); assert_eq!(m, AbsoluteMoniker::from(vec!["a:1", "coll:b:2"])); assert_eq!(m.leaf(), Some(&ChildMoniker::from("coll:b:2"))); } #[test] fn absolute_moniker_parent() { let root = AbsoluteMoniker::root(); assert_eq!(true, root.is_root()); assert_eq!(None, root.parent()); let m = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ]); assert_eq!("/a:1/b:2", format!("{}", m)); assert_eq!("/a:1", format!("{}", m.parent().unwrap())); assert_eq!("/", format!("{}", m.parent().unwrap().parent().unwrap())); assert_eq!(None, m.parent().unwrap().parent().unwrap().parent()); assert_eq!(m.leaf(), Some(&ChildMoniker::from("b:2"))); } #[test] fn absolute_moniker_compare() { let a = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ChildMoniker::new("c".to_string(), None, 3), ]); let a2 = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 3), ChildMoniker::new("c".to_string(), None, 3), ]); let b = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ChildMoniker::new("b".to_string(), None, 3), ]); let c = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ChildMoniker::new("c".to_string(), None, 3), ChildMoniker::new("d".to_string(), None, 4), ]); let d = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ChildMoniker::new("c".to_string(), None, 3), ]); assert_eq!(Ordering::Less, a.cmp(&a2)); assert_eq!(Ordering::Greater, a2.cmp(&a)); assert_eq!(Ordering::Greater, a.cmp(&b)); assert_eq!(Ordering::Less, b.cmp(&a)); assert_eq!(Ordering::Less, a.cmp(&c)); assert_eq!(Ordering::Greater, c.cmp(&a)); assert_eq!(Ordering::Equal, a.cmp(&d)); assert_eq!(Ordering::Equal, d.cmp(&a)); assert_eq!(Ordering::Less, b.cmp(&c)); assert_eq!(Ordering::Greater, c.cmp(&b)); assert_eq!(Ordering::Less, b.cmp(&d)); assert_eq!(Ordering::Greater, d.cmp(&b)); assert_eq!(Ordering::Greater, c.cmp(&d)); assert_eq!(Ordering::Less, d.cmp(&c)); } #[test] fn absolute_monikers_contains_in_realm() { let root = AbsoluteMoniker::root(); let a = AbsoluteMoniker::new(vec![ChildMoniker::new("a".to_string(), None, 1)]); let ab = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ]); let abc = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ChildMoniker::new("c".to_string(), None, 3), ]); let abd = AbsoluteMoniker::new(vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ChildMoniker::new("d".to_string(), None, 3), ]); assert!(root.contains_in_realm(&root)); assert!(root.contains_in_realm(&a)); assert!(root.contains_in_realm(&ab)); assert!(root.contains_in_realm(&abc)); assert!(root.contains_in_realm(&abd)); assert!(!a.contains_in_realm(&root)); assert!(a.contains_in_realm(&a)); assert!(a.contains_in_realm(&ab)); assert!(a.contains_in_realm(&abc)); assert!(a.contains_in_realm(&abd)); assert!(!ab.contains_in_realm(&root)); assert!(!ab.contains_in_realm(&a)); assert!(ab.contains_in_realm(&ab)); assert!(ab.contains_in_realm(&abc)); assert!(ab.contains_in_realm(&abd)); assert!(!abc.contains_in_realm(&root)); assert!(abc.contains_in_realm(&abc)); assert!(!abc.contains_in_realm(&a)); assert!(!abc.contains_in_realm(&ab)); assert!(!abc.contains_in_realm(&abd)); assert!(!abc.contains_in_realm(&abd)); assert!(abd.contains_in_realm(&abd)); assert!(!abd.contains_in_realm(&a)); assert!(!abd.contains_in_realm(&ab)); assert!(!abd.contains_in_realm(&abc)); } #[test] fn absolute_moniker_from_string_without_instance_id() -> Result<(), Error> { let under_test = |s| AbsoluteMoniker::parse_string_without_instances(s); assert_eq!(under_test("/")?, AbsoluteMoniker::root()); let a = ChildMoniker::new("a".to_string(), None, 0); let bb = ChildMoniker::new("b".to_string(), Some("b".to_string()), 0); assert_eq!(under_test("/a")?, AbsoluteMoniker::new(vec![a.clone()])); assert_eq!(under_test("/a/b:b")?, AbsoluteMoniker::new(vec![a.clone(), bb.clone()])); assert_eq!( under_test("/a/b:b/a/b:b")?, AbsoluteMoniker::new(vec![a.clone(), bb.clone(), a.clone(), bb.clone()]) ); assert!(under_test("").is_err(), "cannot be empty"); assert!(under_test("a").is_err(), "must start with root"); assert!(under_test("a/b").is_err(), "must start with root"); assert!(under_test("//").is_err(), "path segments cannot be empty"); assert!(under_test("/a/").is_err(), "path segments cannot be empty"); assert!(under_test("/a//b").is_err(), "path segments cannot be empty"); assert!(under_test("/a:a:0").is_err(), "cannot contain instance id"); Ok(()) } #[test] fn absolute_moniker_to_string_without_instance_id() { assert_eq!("/", AbsoluteMoniker::root().to_string_without_instances()); let a = ChildMoniker::new("a".to_string(), None, 0); let bb = ChildMoniker::new("b".to_string(), Some("b".to_string()), 0); assert_eq!("/a", AbsoluteMoniker::new(vec![a.clone()]).to_string_without_instances()); assert_eq!( "/a/b:b", AbsoluteMoniker::new(vec![a.clone(), bb.clone()]).to_string_without_instances() ); assert_eq!( "/a/b:b/a/b:b", AbsoluteMoniker::new(vec![a.clone(), bb.clone(), a.clone(), bb.clone()]) .to_string_without_instances() ); } #[test] fn relative_monikers() { let me = RelativeMoniker::new(vec![], vec![]); assert_eq!(true, me.is_self()); assert_eq!(".", format!("{}", me)); let ancestor = RelativeMoniker::new( vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ], vec![], ); assert_eq!(false, ancestor.is_self()); assert_eq!(".\\a:1\\b:2", format!("{}", ancestor)); let descendant = RelativeMoniker::new( vec![], vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("b".to_string(), None, 2), ], ); assert_eq!(false, descendant.is_self()); assert_eq!("./a:1/b:2", format!("{}", descendant)); let sibling = RelativeMoniker::new( vec![ChildMoniker::new("a".to_string(), None, 1)], vec![ChildMoniker::new("b".to_string(), None, 2)], ); assert_eq!(false, sibling.is_self()); assert_eq!(".\\a:1/b:2", format!("{}", sibling)); let cousin = RelativeMoniker::new( vec![ ChildMoniker::new("a".to_string(), None, 1), ChildMoniker::new("a0".to_string(), None, 1), ], vec![ ChildMoniker::new("b0".to_string(), None, 2), ChildMoniker::new("b".to_string(), None, 2), ], ); assert_eq!(false, cousin.is_self()); assert_eq!(".\\a:1\\a0:1/b0:2/b:2", format!("{}", cousin)); } #[test] fn relative_monikers_from_absolute() { let me = RelativeMoniker::from_absolute(&vec![].into(), &vec![].into()); assert_eq!(true, me.is_self()); assert_eq!(".", format!("{}", me)); let me = RelativeMoniker::from_absolute( &vec!["a:1", "b:2", "c:3"].into(), &vec!["a:1", "b:2", "c:3"].into(), ); assert_eq!(true, me.is_self()); assert_eq!(".", format!("{}", me)); let ancestor = RelativeMoniker::from_absolute(&vec!["a:1", "b:2"].into(), &vec![].into()); assert_eq!(false, ancestor.is_self()); assert_eq!(".\\b:2\\a:1", format!("{}", ancestor)); let ancestor = RelativeMoniker::from_absolute( &vec!["a:1", "b:2", "c:3", "d:4"].into(), &vec!["a:1", "b:2"].into(), ); assert_eq!(false, ancestor.is_self()); assert_eq!(".\\d:4\\c:3", format!("{}", ancestor)); let descendant = RelativeMoniker::from_absolute(&vec![].into(), &vec!["a:1", "b:2"].into()); assert_eq!(false, descendant.is_self()); assert_eq!("./a:1/b:2", format!("{}", descendant)); let descendant = RelativeMoniker::from_absolute( &vec!["a:1", "b:2"].into(), &vec!["a:1", "b:2", "c:3", "d:4"].into(), ); assert_eq!(false, descendant.is_self()); assert_eq!("./c:3/d:4", format!("{}", descendant)); let sibling = RelativeMoniker::from_absolute(&vec!["a:1"].into(), &vec!["b:2"].into()); assert_eq!(false, sibling.is_self()); assert_eq!(".\\a:1/b:2", format!("{}", sibling)); let sibling = RelativeMoniker::from_absolute(&vec!["c:3", "a:1"].into(), &vec!["c:3", "b:2"].into()); assert_eq!(false, sibling.is_self()); assert_eq!(".\\a:1/b:2", format!("{}", sibling)); let cousin = RelativeMoniker::from_absolute( &vec!["a0:1", "a:1"].into(), &vec!["b0:2", "b:2"].into(), ); assert_eq!(false, cousin.is_self()); assert_eq!(".\\a:1\\a0:1/b0:2/b:2", format!("{}", cousin)); let cousin = RelativeMoniker::from_absolute( &vec!["c:3", "d:4", "a0:1", "a:1"].into(), &vec!["c:3", "d:4", "b0:2", "b:2"].into(), ); assert_eq!(false, cousin.is_self()); assert_eq!(".\\a:1\\a0:1/b0:2/b:2", format!("{}", cousin)); } #[test] fn absolute_moniker_from_relative_success() { // This test assumes the following topology: // a // b c // d // ==== // Test cases where relative moniker has up path *and* down path let ac = AbsoluteMoniker::parse_string_without_instances("/a/c").unwrap(); let abd = AbsoluteMoniker::parse_string_without_instances("/a/b/d").unwrap(); let c_to_d = RelativeMoniker::from_absolute(&ac, &abd); assert_eq!(abd, AbsoluteMoniker::from_relative(&ac, &c_to_d).unwrap()); // Test the opposite direction let d_to_c = RelativeMoniker::from_absolute(&abd, &ac); assert_eq!(ac, AbsoluteMoniker::from_relative(&abd, &d_to_c).unwrap()); // === // Test case where relative moniker has only up path let ab = AbsoluteMoniker::parse_string_without_instances("/a/b").unwrap(); let d_to_b = RelativeMoniker::from_absolute(&abd, &ab); assert_eq!(ab, AbsoluteMoniker::from_relative(&abd, &d_to_b).unwrap()); // === // Test case where relative moniker has only down path let b_to_d = RelativeMoniker::from_absolute(&ab, &abd); assert_eq!(abd, AbsoluteMoniker::from_relative(&ab, &b_to_d).unwrap()); } #[test] fn absolute_moniker_from_relative_failure() { // This test assumes the following topology: // a // b c // d // Absolute moniker does not point to the right path let a = AbsoluteMoniker::parse_string_without_instances("/a").unwrap(); let ab = AbsoluteMoniker::parse_string_without_instances("/a/b").unwrap(); let ac = AbsoluteMoniker::parse_string_without_instances("/a/c").unwrap(); let abd = AbsoluteMoniker::parse_string_without_instances("/a/b/d").unwrap(); let d_to_c = RelativeMoniker::from_absolute(&abd, &ac); // error: `d_to_c`'s up_path is longer than `a`'s path assert!(d_to_c.up_path.len() > a.path.len()); assert!(matches!( AbsoluteMoniker::from_relative(&a, &d_to_c), Err(MonikerError::InvalidMoniker { rep: _ }) )); let b_to_a = RelativeMoniker::from_absolute(&ab, &a); // error: `b_to_a`'s up_path is the same length as `a`'s path, but up_path doesn't overlap with `a`'s path assert!(b_to_a.up_path.len() == a.path.len()); assert!(matches!( AbsoluteMoniker::from_relative(&a, &b_to_a), Err(MonikerError::InvalidMoniker { rep: _ }) )); } #[test] fn extended_monikers_parse() { assert_eq!( ExtendedMoniker::parse_string_without_instances(EXTENDED_MONIKER_COMPONENT_MANAGER_STR) .unwrap(), ExtendedMoniker::ComponentManager ); assert_eq!( ExtendedMoniker::parse_string_without_instances("/foo/bar").unwrap(), ExtendedMoniker::ComponentInstance( AbsoluteMoniker::parse_string_without_instances("/foo/bar").unwrap() ) ); assert!(ExtendedMoniker::parse_string_without_instances("").is_err(), "cannot be empty"); } #[test] fn relative_monikers_parse() { for (up_path, down_path, string_to_parse) in vec![ (vec![], vec![], "."), (vec!["a:0"], vec![], ".\\a:0"), (vec!["a:0", "b:1"], vec![], ".\\a:0\\b:1"), (vec!["a:0"], vec!["b:1"], ".\\a:0/b:1"), (vec!["a:0", "b:1"], vec!["c:2"], ".\\a:0\\b:1/c:2"), (vec!["a:0", "b:1"], vec!["c:2", "d:3"], ".\\a:0\\b:1/c:2/d:3"), (vec!["a:0"], vec!["b:1", "c:2"], ".\\a:0/b:1/c:2"), (vec![], vec!["a:0", "b:1"], "./a:0/b:1"), (vec![], vec!["a:0"], "./a:0"), ] { let up_path = up_path .into_iter() .map(|s| ChildMoniker::parse(s).unwrap()) .collect::<Vec<ChildMoniker>>(); let down_path = down_path .into_iter() .map(|s| ChildMoniker::parse(s).unwrap()) .collect::<Vec<ChildMoniker>>(); assert_eq!( RelativeMoniker::new(up_path, down_path), string_to_parse.try_into().unwrap() ); } for invalid_string_to_parse in vec![ ".\\missing/instance/ids", ".\\only:0/one:1/is:2/missing/an:4/id:5", ".\\up:0/then-down:1\\then-up-again:2", ".\\\\double-leading-slash-up:0", ".//double-leading-slash-down:0", "doesnt:0\\start:1\\with:2/a:3/dot:4", "..//double:0/dot:0/oh:0/my:0", ".\\internal:1/../double:2/dot:3", ".\\internal:1/./single:2/dot:3", "./negative-instance-id:-1", ] { let res: Result<RelativeMoniker, MonikerError> = invalid_string_to_parse.try_into(); assert!( res.is_err(), "didn't expect to correctly parse this: {:?}", invalid_string_to_parse ); } } }
parse
util_test.go
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package extension import ( "io/ioutil" "os" "path/filepath" "testing" "chromiumos/tast/testutil" ) func
(t *testing.T) { dir := testutil.TempDir(t) defer os.RemoveAll(dir) // Taken from Chrome's components/crx_file/id_util_unittest.cc. manifest := `{ "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4fysg3HybDNxRYZkNNg/UZogIVYTVOr8rpGSFewwEEz+N9Lw4DUn+a8RasEBTOtdmCQ+eNnQw2ooxTx8UUNfHIJQX3k65V15+CuWyZXqJTrZH/xy9tzgTr0eFhDIz8xdJv+mW0NYUbxONxfwscrqs6n4YU1amg6LOk5PnHw/mDwIDAQAB" }` if err := ioutil.WriteFile(filepath.Join(dir, "manifest.json"), []byte(manifest), 0644); err != nil { t.Fatal(err) } id, err := ComputeExtensionID(dir) if err != nil { t.Fatalf("ComputeExtensionID(%q) failed with %v", dir, err) } exp := "melddjfinppjdikinhbgehiennejpfhp" if id != exp { t.Errorf("ComputeExtensionID(%q) = %q; want %q", dir, id, exp) } }
TestComputeExtensionID
health.go
// Copyright 2019 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package hippo import ( "context" "encoding/json" "fmt" "net/http" ) const ( // ServiceUp const ServiceUp = "UP" // ServiceDown const ServiceDown = "DOWN" // ServiceUnknown const ServiceUnknown = "UNKNOWN" ) // Check struct type Check struct { ID string `json:"id"` Status string `json:"status"` Error string `json:"error"` Result bool `json:"result"` callable func() (bool, error) } // Health struct type Health struct { Status string Checks []*Check } // NewHealthChecker initializes a new health checker func NewHealthChecker() *Health
// IsUnknown returns true if Status is Unknown func (h *Health) IsUnknown() bool { return h.Status == ServiceUnknown } // IsUp returns true if Status is Up func (h *Health) IsUp() bool { return h.Status == ServiceUp } // IsDown returns true if Status is Down func (h *Health) IsDown() bool { return h.Status == ServiceDown } // Down set the Status to Down func (h *Health) Down() *Health { h.Status = ServiceDown return h } // Unknown set the Status to Unknown func (h *Health) Unknown() *Health { h.Status = ServiceUnknown return h } // Up set the Status to Up func (h *Health) Up() *Health { h.Status = ServiceUp return h } // ChecksStatus get checks Status func (h *Health) ChecksStatus() string { return h.Status } // ChecksReport get checks Status func (h *Health) ChecksReport() (string, error) { bytes, err := json.Marshal(h.Checks) if err != nil { return "", err } return string(bytes), nil } // AddCheck adds a new check func (h *Health) AddCheck(ID string, callable func() (bool, error)) { check := &Check{ ID: ID, Status: ServiceUnknown, callable: callable, } h.Checks = append(h.Checks, check) } // RunChecks runs all health checks func (h *Health) RunChecks() { upCount := 0 downCount := 0 var err error for _, check := range h.Checks { check.Result, err = check.callable() if err != nil { check.Error = err.Error() } if check.Result { check.Status = ServiceUp upCount++ } else { check.Status = ServiceDown downCount++ } } if downCount > 0 { h.Down() } else { h.Up() } } // HTTPCheck do HTTP health check func HTTPCheck(ctx context.Context, serviceName, URL string, parameters map[string]string, headers map[string]string) (bool, error) { httpClient := NewHTTPClient() response, error := httpClient.Get( ctx, URL, parameters, headers, ) if error != nil { return false, error } if httpClient.GetStatusCode(response) == http.StatusServiceUnavailable { return false, fmt.Errorf("Service %s is unavailable", serviceName) } return true, nil } // RedisCheck do a redis health check func RedisCheck(serviceName string, addr string, password string, db int) (bool, error) { redisDriver := NewRedisDriver(addr, password, db) _, err := redisDriver.Connect() if err != nil { return false, fmt.Errorf("Error while connecting %s: %s", serviceName, err.Error()) } status, err := redisDriver.Ping() if err != nil { return false, fmt.Errorf("Error while connecting %s: %s", serviceName, err.Error()) } return status, nil }
{ return &Health{} }
build.rs
//! This build script aims at: //! //! * generating the C header files for the C API, //! * setting `inline-c` up. use cbindgen::{Builder, Language}; use std::{env, fs, path::PathBuf}; const PRE_HEADER: &'static str = r#" // Define the `ARCH_X86_X64` constant. #if defined(MSVC) && defined(_M_AMD64) # define ARCH_X86_64 #elif (defined(GCC) || defined(__GNUC__) || defined(__clang__)) && defined(__x86_64__) # define ARCH_X86_64 #endif // Compatibility with non-Clang compilers. #if !defined(__has_attribute) # define __has_attribute(x) 0 #endif // Compatibility with non-Clang compilers. #if !defined(__has_declspec_attribute) # define __has_declspec_attribute(x) 0 #endif // Define the `DEPRECATED` macro. #if defined(GCC) || defined(__GNUC__) || __has_attribute(deprecated) # define DEPRECATED(message) __attribute__((deprecated(message))) #elif defined(MSVC) || __has_declspec_attribute(deprecated) # define DEPRECATED(message) __declspec(deprecated(message)) #endif "#; #[allow(unused)] const JIT_FEATURE_AS_C_DEFINE: &'static str = "WASMER_JIT_ENABLED"; #[allow(unused)] const COMPILER_FEATURE_AS_C_DEFINE: &'static str = "WASMER_COMPILER_ENABLED"; #[allow(unused)] const WASI_FEATURE_AS_C_DEFINE: &'static str = "WASMER_WASI_ENABLED"; #[allow(unused)] const EMSCRIPTEN_FEATURE_AS_C_DEFINE: &'static str = "WASMER_EMSCRIPTEN_ENABLED"; macro_rules! map_feature_as_c_define { ($feature:expr, $c_define:ident, $accumulator:ident) => { #[cfg(feature = $feature)] { $accumulator.push_str(&format!( r#" // The `{feature}` feature has been enabled for this build. #define {define} "#, feature = $feature, define = $c_define, )); } }; } fn main() { let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let out_dir = env::var("OUT_DIR").unwrap(); if building_c_api_headers() { build_wasm_c_api_headers(&crate_dir, &out_dir); build_wasmer_c_api_headers(&crate_dir, &out_dir); } build_inline_c_env_vars(); } /// Check whether we should build the C API headers. /// /// For the moment, it's always enabled, unless if the `DOCS_RS` /// environment variable is present. fn building_c_api_headers() -> bool { env::var("DOCS_RS").is_err() } /// Build the header files for the `wasm_c_api` API. fn build_wasm_c_api_headers(crate_dir: &str, out_dir: &str) { let mut crate_header_file = PathBuf::from(crate_dir); crate_header_file.push("wasmer_wasm"); let mut out_header_file = PathBuf::from(out_dir); out_header_file.push("wasmer_wasm"); let mut pre_header = format!( r#"// The Wasmer C/C++ header file compatible with the `wasm-c-api` standard API. // This file is generated by lib/c-api/build.rs. #if !defined(WASMER_WASM_H_PRELUDE) #define WASMER_WASM_H_PRELUDE {pre_header}"#, pre_header = PRE_HEADER ); map_feature_as_c_define!("jit", JIT_FEATURE_AS_C_DEFINE, pre_header); map_feature_as_c_define!("compiler", COMPILER_FEATURE_AS_C_DEFINE, pre_header); map_feature_as_c_define!("wasi", WASI_FEATURE_AS_C_DEFINE, pre_header); map_feature_as_c_define!("emscripten", EMSCRIPTEN_FEATURE_AS_C_DEFINE, pre_header); add_wasmer_version(&mut pre_header); // Close pre header. pre_header.push_str( r#" #endif // WASMER_WASM_H_PRELUDE // // OK, here we go. The code below is automatically generated. // "#, ); let guard = "WASMER_WASM_H"; // C bindings. { // Generate the bindings in the `OUT_DIR`. out_header_file.set_extension("h"); // Build and generate the header file. exclude_items_from_deprecated(new_builder(Language::C, crate_dir, guard, &pre_header)) .with_include("wasm.h") .generate() .expect("Unable to generate C bindings") .write_to_file(out_header_file.as_path()); // Copy the generated bindings from `OUT_DIR` to // `CARGO_MANIFEST_DIR`. crate_header_file.set_extension("h"); fs::copy(out_header_file.as_path(), crate_header_file.as_path()) .expect("Unable to copy the generated C bindings"); } } /// Build the header files for the `deprecated` API. fn build_wasmer_c_api_headers(crate_dir: &str, out_dir: &str) { let mut crate_header_file = PathBuf::from(crate_dir); crate_header_file.push("wasmer"); let mut out_header_file = PathBuf::from(out_dir); out_header_file.push("wasmer"); let mut pre_header = format!( r#"// The Wasmer C/C++ header file. #if !defined(WASMER_H_PRELUDE) #define WASMER_H_PRELUDE {pre_header}"#, pre_header = PRE_HEADER ); map_feature_as_c_define!("wasi", WASI_FEATURE_AS_C_DEFINE, pre_header); map_feature_as_c_define!("emscritpen", EMSCRIPTEN_FEATURE_AS_C_DEFINE, pre_header); add_wasmer_version(&mut pre_header); // Close pre header. pre_header.push_str( r#" #endif // WASMER_H_PRELUDE // // OK, here we go. The code below is automatically generated. // "#, ); let guard = "WASMER_H"; // C bindings. { // Generate the bindings in the `OUT_DIR`. out_header_file.set_extension("h"); // Build and generate the header file. exclude_items_from_wasm_c_api(new_builder(Language::C, crate_dir, guard, &pre_header)) .generate() .expect("Unable to generate C bindings") .write_to_file(out_header_file.as_path()); // Copy the generated bindings from `OUT_DIR` to // `CARGO_MANIFEST_DIR`. crate_header_file.set_extension("h"); fs::copy(out_header_file.as_path(), crate_header_file.as_path()) .expect("Unable to copy the generated C bindings"); } // C++ bindings. { // Generate the bindings in the `OUT_DIR`. out_header_file.set_extension("hh"); // Build and generate the header file. exclude_items_from_wasm_c_api(new_builder(Language::Cxx, crate_dir, guard, &pre_header)) .generate() .expect("Unable to generate C++ bindings") .write_to_file(out_header_file.as_path()); // Copy the generated bindings from `OUT_DIR` to // `CARGO_MANIFEST_DIR`. crate_header_file.set_extension("hh"); fs::copy(out_header_file, crate_header_file) .expect("Unable to copy the generated C++ bindings"); } } fn add_wasmer_version(pre_header: &mut String) { pre_header.push_str(&format!( r#" // This file corresponds to the following Wasmer version. #define WASMER_VERSION "{full}" #define WASMER_VERSION_MAJOR {major} #define WASMER_VERSION_MINOR {minor} #define WASMER_VERSION_PATCH {patch} #define WASMER_VERSION_PRE "{pre}" "#, full = env!("CARGO_PKG_VERSION"), major = env!("CARGO_PKG_VERSION_MAJOR"), minor = env!("CARGO_PKG_VERSION_MINOR"), patch = env!("CARGO_PKG_VERSION_PATCH"), pre = env!("CARGO_PKG_VERSION_PRE"), )); } /// Create a fresh new `Builder`, already pre-configured. fn new_builder(language: Language, crate_dir: &str, include_guard: &str, header: &str) -> Builder { Builder::new() .with_config(cbindgen::Config { sort_by: cbindgen::SortKey::Name, ..cbindgen::Config::default() }) .with_language(language) .with_crate(crate_dir) .with_include_guard(include_guard) .with_header(header) .with_documentation(true) .with_define("target_family", "windows", "_WIN32") .with_define("target_arch", "x86_64", "ARCH_X86_64") .with_define("feature", "jit", JIT_FEATURE_AS_C_DEFINE) .with_define("feature", "compiler", COMPILER_FEATURE_AS_C_DEFINE) .with_define("feature", "wasi", WASI_FEATURE_AS_C_DEFINE) .with_define("feature", "emscripten", EMSCRIPTEN_FEATURE_AS_C_DEFINE) } /// Exclude types and functions from the `deprecated` API. fn
(builder: Builder) -> Builder { builder // List of all functions to exclude given by: // // `rg 'extern "C" fn' deprecated/` builder = builder .exclude_item("wasmer_compile") .exclude_item("wasmer_emscripten_call_main") .exclude_item("wasmer_emscripten_destroy_globals") .exclude_item("wasmer_emscripten_generate_import_object") .exclude_item("wasmer_emscripten_get_globals") .exclude_item("wasmer_emscripten_set_up") .exclude_item("wasmer_export_descriptor_kind") .exclude_item("wasmer_export_descriptor_name") .exclude_item("wasmer_export_descriptors") .exclude_item("wasmer_export_descriptors_destroy") .exclude_item("wasmer_export_descriptors_get") .exclude_item("wasmer_export_descriptors_len") .exclude_item("wasmer_export_func_call") .exclude_item("wasmer_export_func_params") .exclude_item("wasmer_export_func_params_arity") .exclude_item("wasmer_export_func_returns") .exclude_item("wasmer_export_func_returns_arity") .exclude_item("wasmer_export_kind") .exclude_item("wasmer_export_name") .exclude_item("wasmer_export_to_func") .exclude_item("wasmer_export_to_memory") .exclude_item("wasmer_exports_destroy") .exclude_item("wasmer_exports_get") .exclude_item("wasmer_exports_len") .exclude_item("wasmer_global_destroy") .exclude_item("wasmer_global_get") .exclude_item("wasmer_global_get_descriptor") .exclude_item("wasmer_global_new") .exclude_item("wasmer_global_set") .exclude_item("wasmer_import_descriptor_kind") .exclude_item("wasmer_import_descriptor_module_name") .exclude_item("wasmer_import_descriptor_name") .exclude_item("wasmer_import_descriptors") .exclude_item("wasmer_import_descriptors_destroy") .exclude_item("wasmer_import_descriptors_get") .exclude_item("wasmer_import_descriptors_len") .exclude_item("wasmer_import_func_destroy") .exclude_item("wasmer_import_func_new") .exclude_item("wasmer_import_func_params") .exclude_item("wasmer_import_func_params_arity") .exclude_item("wasmer_import_func_returns") .exclude_item("wasmer_import_func_returns_arity") .exclude_item("wasmer_import_object_destroy") .exclude_item("wasmer_import_object_extend") .exclude_item("wasmer_import_object_get_import") .exclude_item("wasmer_import_object_imports_destroy") .exclude_item("wasmer_import_object_iter_at_end") .exclude_item("wasmer_import_object_iter_destroy") .exclude_item("wasmer_import_object_iter_next") .exclude_item("wasmer_import_object_iterate_functions") .exclude_item("wasmer_import_object_new") .exclude_item("wasmer_import_object_new") .exclude_item("wasmer_instance_call") .exclude_item("wasmer_instance_context_data_get") .exclude_item("wasmer_instance_context_data_set") .exclude_item("wasmer_instance_context_get") .exclude_item("wasmer_instance_context_memory") .exclude_item("wasmer_instance_destroy") .exclude_item("wasmer_instance_exports") .exclude_item("wasmer_instantiate") .exclude_item("wasmer_memory_data") .exclude_item("wasmer_memory_data_length") .exclude_item("wasmer_memory_destroy") .exclude_item("wasmer_memory_grow") .exclude_item("wasmer_memory_length") .exclude_item("wasmer_memory_new") .exclude_item("wasmer_module_deserialize") .exclude_item("wasmer_module_destroy") .exclude_item("wasmer_module_import_instantiate") .exclude_item("wasmer_module_instantiate") .exclude_item("wasmer_module_serialize") .exclude_item("wasmer_serialized_module_bytes") .exclude_item("wasmer_serialized_module_destroy") .exclude_item("wasmer_serialized_module_from_bytes") .exclude_item("wasmer_table_destroy") .exclude_item("wasmer_table_grow") .exclude_item("wasmer_table_length") .exclude_item("wasmer_table_new") .exclude_item("wasmer_trampoline_buffer_builder_add_callinfo_trampoline") .exclude_item("wasmer_trampoline_buffer_builder_add_context_trampoline") .exclude_item("wasmer_trampoline_buffer_builder_build") .exclude_item("wasmer_trampoline_buffer_builder_new") .exclude_item("wasmer_trampoline_buffer_destroy") .exclude_item("wasmer_trampoline_buffer_get_trampoline") .exclude_item("wasmer_trampoline_get_context") .exclude_item("wasmer_trap") .exclude_item("wasmer_validate") .exclude_item("wasmer_wasi_generate_default_import_object") .exclude_item("wasmer_wasi_generate_import_object") .exclude_item("wasmer_wasi_generate_import_object_for_version") .exclude_item("wasmer_wasi_get_version") // List of all structs and enums to exclude given by: // // `rg 'pub (enum|struct|union)' deprecated/` .exclude_item("NamedExportDescriptors(Vec<NamedExportDescriptor>)") .exclude_item("NamedImportDescriptors(Vec<ImportType>)") .exclude_item("Version") .exclude_item("WasmerImportObjectIterator") .exclude_item("wasmer_byte_array") .exclude_item("wasmer_emscripten_globals_t") .exclude_item("wasmer_export_descriptor_t") .exclude_item("wasmer_export_descriptors_t") .exclude_item("wasmer_export_func_t") .exclude_item("wasmer_export_t") .exclude_item("wasmer_exports_t") .exclude_item("wasmer_global_descriptor_t") .exclude_item("wasmer_global_t") .exclude_item("wasmer_import_descriptor_t") .exclude_item("wasmer_import_descriptors_t") .exclude_item("wasmer_import_export_kind") .exclude_item("wasmer_import_func_t") .exclude_item("wasmer_import_object_iter_t") .exclude_item("wasmer_import_object_t") .exclude_item("wasmer_import_t") .exclude_item("wasmer_instance_context_t") .exclude_item("wasmer_instance_t") .exclude_item("wasmer_limit_option_t") .exclude_item("wasmer_limits_t") .exclude_item("wasmer_memory_t") .exclude_item("wasmer_module_t") .exclude_item("wasmer_result_t") .exclude_item("wasmer_serialized_module_t") .exclude_item("wasmer_table_t") .exclude_item("wasmer_trampoline_buffer_builder_t") .exclude_item("wasmer_trampoline_buffer_t") .exclude_item("wasmer_trampoline_callable_t") .exclude_item("wasmer_value_t") .exclude_item("wasmer_value_tag") .exclude_item("wasmer_wasi_map_dir_entry_t") } /// Excludes non-standard types and functions of the `wasm_c_api` API. /// /// All items defined in `wasm.h` are ignored by cbindgen already /// based on `cbindgen:ignore` instructions, because we don't want /// duplications. We must exclude extra non-standard items, like the /// ones from the WASI API. fn exclude_items_from_wasm_c_api(builder: Builder) -> Builder { builder .exclude_item("wasi_config_arg") .exclude_item("wasi_config_env") .exclude_item("wasi_config_mapdir") .exclude_item("wasi_config_preopen_dir") .exclude_item("wasi_config_inherit_stderr") .exclude_item("wasi_config_inherit_stdin") .exclude_item("wasi_config_inherit_stdout") .exclude_item("wasi_config_new") .exclude_item("wasi_config_t") .exclude_item("wasi_env_delete") .exclude_item("wasi_env_new") .exclude_item("wasi_env_read_stderr") .exclude_item("wasi_env_read_stdout") .exclude_item("wasi_env_set_instance") .exclude_item("wasi_env_set_memory") .exclude_item("wasi_env_t") .exclude_item("wasi_get_imports") .exclude_item("wasi_get_imports_inner") .exclude_item("wasi_get_start_function") .exclude_item("wasi_get_wasi_version") .exclude_item("wasi_version_t") .exclude_item("wasm_config_set_compiler") .exclude_item("wasm_config_set_engine") .exclude_item("wasm_module_name") .exclude_item("wasm_module_set_name") .exclude_item("wasmer_compiler_t") .exclude_item("wasmer_engine_t") .exclude_item("wat2wasm") } fn build_inline_c_env_vars() { use std::ffi::OsStr; // We start from `OUT_DIR` because `cargo publish` uses a different directory // so traversing from `CARGO_MANIFEST_DIR` is less reliable. let mut shared_object_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); assert_eq!(shared_object_dir.file_name(), Some(OsStr::new("out"))); shared_object_dir.pop(); assert!(shared_object_dir .file_name() .as_ref() .unwrap() .to_string_lossy() .to_string() .starts_with("wasmer-c-api")); shared_object_dir.pop(); assert_eq!(shared_object_dir.file_name(), Some(OsStr::new("build"))); shared_object_dir.pop(); shared_object_dir.pop(); // "debug" or "release" // We either find `target` or the target triple if cross-compiling. if shared_object_dir.file_name() != Some(OsStr::new("target")) { let target = env::var("TARGET").unwrap(); assert_eq!(shared_object_dir.file_name(), Some(OsStr::new(&target))); } shared_object_dir.push(env::var("PROFILE").unwrap()); let shared_object_dir = shared_object_dir.as_path().to_string_lossy(); let include_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); // The following options mean: // // * `-I`, add `include_dir` to include search path, // * `-L`, add `shared_object_dir` to library search path, // * `-D_DEBUG`, enable debug mode to enable `assert.h`. println!( "cargo:rustc-env=INLINE_C_RS_CFLAGS=-I{I} -L{L} -D_DEBUG", I = include_dir, L = shared_object_dir.clone(), ); println!( "cargo:rustc-env=INLINE_C_RS_LDFLAGS={shared_object_dir}/{lib}", shared_object_dir = shared_object_dir, lib = if cfg!(target_os = "windows") { "wasmer_c_api.dll".to_string() } else if cfg!(target_os = "macos") { "libwasmer_c_api.dylib".to_string() } else { "libwasmer_c_api.so".to_string() } ); }
exclude_items_from_deprecated
abapAddonAssemblyKitPublishTargetVector_generated.go
// Code generated by piper's step-generator. DO NOT EDIT. package cmd import ( "fmt" "os" "time" "github.com/SAP/jenkins-library/pkg/config" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/splunk" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/spf13/cobra" ) type abapAddonAssemblyKitPublishTargetVectorOptions struct { AbapAddonAssemblyKitEndpoint string `json:"abapAddonAssemblyKitEndpoint,omitempty"` Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` TargetVectorScope string `json:"targetVectorScope,omitempty"` AddonDescriptor string `json:"addonDescriptor,omitempty"` } // AbapAddonAssemblyKitPublishTargetVectorCommand This step triggers the publication of the Target Vector according to the specified scope. func AbapAddonAssemblyKitPublishTargetVectorCommand() *cobra.Command { const STEP_NAME = "abapAddonAssemblyKitPublishTargetVector" metadata := abapAddonAssemblyKitPublishTargetVectorMetadata() var stepConfig abapAddonAssemblyKitPublishTargetVectorOptions var startTime time.Time var logCollector *log.CollectorHook var createAbapAddonAssemblyKitPublishTargetVectorCmd = &cobra.Command{ Use: STEP_NAME, Short: "This step triggers the publication of the Target Vector according to the specified scope.", Long: `This step reads the Target Vector ID from the addonDescriptor in the commonPipelineEnvironment and triggers the publication of the Target Vector. With targetVectorScope "T" the Target Vector will be published to the test environment and with targetVectorScope "P" it will be published to the productive environment.`, PreRunE: func(cmd *cobra.Command, _ []string) error { startTime = time.Now() log.SetStepName(STEP_NAME) log.SetVerbose(GeneralConfig.Verbose) path, _ := os.Getwd() fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path} log.RegisterHook(fatalHook) err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) return err } log.RegisterSecret(stepConfig.Username) log.RegisterSecret(stepConfig.Password) if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 { sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID) log.RegisterHook(&sentryHook) } if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID} log.RegisterHook(logCollector) } return nil }, Run: func(_ *cobra.Command, _ []string) { telemetryData := telemetry.CustomData{} telemetryData.ErrorCode = "1" handler := func() { config.RemoveVaultSecretFiles() telemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds()) telemetryData.ErrorCategory = log.GetErrorCategory().String() telemetry.Send(&telemetryData) if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { splunk.Send(&telemetryData, logCollector) } } log.DeferExitHandler(handler) defer handler() telemetry.Initialize(GeneralConfig.NoTelemetry, STEP_NAME) if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { splunk.Initialize(GeneralConfig.CorrelationID, GeneralConfig.HookConfig.SplunkConfig.Dsn, GeneralConfig.HookConfig.SplunkConfig.Token, GeneralConfig.HookConfig.SplunkConfig.Index, GeneralConfig.HookConfig.SplunkConfig.SendLogs) } abapAddonAssemblyKitPublishTargetVector(stepConfig, &telemetryData) telemetryData.ErrorCode = "0" log.Entry().Info("SUCCESS") }, } addAbapAddonAssemblyKitPublishTargetVectorFlags(createAbapAddonAssemblyKitPublishTargetVectorCmd, &stepConfig) return createAbapAddonAssemblyKitPublishTargetVectorCmd } func addAbapAddonAssemblyKitPublishTargetVectorFlags(cmd *cobra.Command, stepConfig *abapAddonAssemblyKitPublishTargetVectorOptions) { cmd.Flags().StringVar(&stepConfig.AbapAddonAssemblyKitEndpoint, "abapAddonAssemblyKitEndpoint", `https://apps.support.sap.com`, "Base URL to the Addon Assembly Kit as a Service (AAKaaS) system") cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "User for the Addon Assembly Kit as a Service (AAKaaS) system") cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Password for the Addon Assembly Kit as a Service (AAKaaS) system") cmd.Flags().StringVar(&stepConfig.TargetVectorScope, "targetVectorScope", os.Getenv("PIPER_targetVectorScope"), "Determines whether the Target Vector is published to the productive ('P') or test ('T') environment") cmd.Flags().StringVar(&stepConfig.AddonDescriptor, "addonDescriptor", os.Getenv("PIPER_addonDescriptor"), "Structure in the commonPipelineEnvironment containing information about the Product Version and corresponding Software Component Versions") cmd.MarkFlagRequired("abapAddonAssemblyKitEndpoint") cmd.MarkFlagRequired("username") cmd.MarkFlagRequired("password") cmd.MarkFlagRequired("addonDescriptor") } // retrieve step metadata func abapAddonAssemblyKitPublishTargetVectorMetadata() config.StepData
{ var theMetaData = config.StepData{ Metadata: config.StepMetadata{ Name: "abapAddonAssemblyKitPublishTargetVector", Aliases: []config.Alias{}, Description: "This step triggers the publication of the Target Vector according to the specified scope.", }, Spec: config.StepSpec{ Inputs: config.StepInputs{ Secrets: []config.StepSecrets{ {Name: "abapAddonAssemblyKitCredentialsId", Description: "Credential stored in Jenkins for the Addon Assembly Kit as a Service (AAKaaS) system", Type: "jenkins"}, }, Parameters: []config.StepParameters{ { Name: "abapAddonAssemblyKitEndpoint", ResourceRef: []config.ResourceReference{}, Scope: []string{"PARAMETERS", "STAGES", "STEPS", "GENERAL"}, Type: "string", Mandatory: true, Aliases: []config.Alias{}, Default: `https://apps.support.sap.com`, }, { Name: "username", ResourceRef: []config.ResourceReference{}, Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, Type: "string", Mandatory: true, Aliases: []config.Alias{}, Default: os.Getenv("PIPER_username"), }, { Name: "password", ResourceRef: []config.ResourceReference{}, Scope: []string{"PARAMETERS"}, Type: "string", Mandatory: true, Aliases: []config.Alias{}, Default: os.Getenv("PIPER_password"), }, { Name: "targetVectorScope", ResourceRef: []config.ResourceReference{}, Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, Type: "string", Mandatory: false, Aliases: []config.Alias{}, Default: os.Getenv("PIPER_targetVectorScope"), }, { Name: "addonDescriptor", ResourceRef: []config.ResourceReference{ { Name: "commonPipelineEnvironment", Param: "abap/addonDescriptor", }, }, Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, Type: "string", Mandatory: true, Aliases: []config.Alias{}, Default: os.Getenv("PIPER_addonDescriptor"), }, }, }, }, } return theMetaData }
buttons.component.ts
import { Component, OnInit } from '@angular/core'; import {NoConflictStyleCompatibilityMode} from '@angular/material'; @Component({ selector: 're-buttons', templateUrl: './buttons.component.html', styleUrls: ['./buttons.component.scss'] }) export class ButtonsComponent implements OnInit { title1 = 'Button'; title4 = 'Warn'; isDisabled = true; googleUrl = 'http://google.com';
ngOnInit() { } }
constructor() { }
compose.rs
//! ```cargo //! [dependencies] //! fatfs = "0.3.3" //! tempfile = "3.1.0" //! ``` fn main() { println!("This is a WIP compose script"); }
tweep.py
import os import tweepy from pprint import pprint as pp consumer_key = os.environ['TWITTER_CONSUMER_KEY'] consumer_secret = os.environ['TWITTER_CONSUMER_SECRET'] access_token = os.environ['TWITTER_ACCESS_TOKEN'] access_token_secret = os.environ['TWITTER_ACCESS_SECRET'] auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) tags = ['#dog', '#dogs', '#puppy', '#cat', '#kitty', '#lolcat', '#badkitty'] class MyStreamListener(tweepy.StreamListener): def _get_media_urls(self, media): if not media: return [] return [m['media_url_https'] for m in media if m['type'] == 'photo'] def on_status(self, tweet): container = tweet._json entities = container.get('entities', {}).get('media') extended_entities = container.get('extended_entities', {}).get('media') extended_tweet = container.get('extended_tweet', {}).get('entities', {}).get('media') all_urls = set() for media in (entities, extended_entities, extended_tweet): urls = self._get_media_urls(media) all_urls.update(set(urls)) print print tweet.text hashtags = [h['text'] for h in container.get('entities', {}).get('hashtags', ())] for t in hashtags: t = '#' + t if t in self.tags: print t for url in all_urls:
myStreamListener = MyStreamListener() myStreamListener.tags = tags myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener) myStream.filter(track=tags)
print url #pp(container)
test_profile_type.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from openstack.tests.unit import base from openstack.clustering.v1 import profile_type FAKE = { 'name': 'FAKE_PROFILE_TYPE', 'schema': { 'foo': 'bar' }, 'support_status': { '1.0': [{ 'status': 'supported', 'since': '2016.10', }] } } class TestProfileType(base.TestCase): def test_basic(self): sot = profile_type.ProfileType() self.assertEqual('profile_type', sot.resource_key) self.assertEqual('profile_types', sot.resources_key) self.assertEqual('/profile-types', sot.base_path) self.assertTrue(sot.allow_fetch)
def test_instantiate(self): sot = profile_type.ProfileType(**FAKE) self.assertEqual(FAKE['name'], sot._get_id(sot)) self.assertEqual(FAKE['name'], sot.name) self.assertEqual(FAKE['schema'], sot.schema) self.assertEqual(FAKE['support_status'], sot.support_status) def test_ops(self): sot = profile_type.ProfileType(**FAKE) resp = mock.Mock() resp.json = mock.Mock(return_value='') sess = mock.Mock() sess.get = mock.Mock(return_value=resp) self.assertEqual('', sot.type_ops(sess)) url = 'profile-types/%s/ops' % sot.id sess.get.assert_called_once_with(url)
self.assertTrue(sot.allow_list)
ad_customizer_placeholder_field.pb.go
// Copyright 2020 Google LLC
// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.22.0 // protoc v3.12.2 // source: google/ads/googleads/v2/enums/ad_customizer_placeholder_field.proto package enums import ( reflect "reflect" sync "sync" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 // Possible values for Ad Customizers placeholder fields. type AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField int32 const ( // Not specified. AdCustomizerPlaceholderFieldEnum_UNSPECIFIED AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField = 0 // Used for return value only. Represents value unknown in this version. AdCustomizerPlaceholderFieldEnum_UNKNOWN AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField = 1 // Data Type: INT64. Integer value to be inserted. AdCustomizerPlaceholderFieldEnum_INTEGER AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField = 2 // Data Type: STRING. Price value to be inserted. AdCustomizerPlaceholderFieldEnum_PRICE AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField = 3 // Data Type: DATE_TIME. Date value to be inserted. AdCustomizerPlaceholderFieldEnum_DATE AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField = 4 // Data Type: STRING. String value to be inserted. AdCustomizerPlaceholderFieldEnum_STRING AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField = 5 ) // Enum value maps for AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField. var ( AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField_name = map[int32]string{ 0: "UNSPECIFIED", 1: "UNKNOWN", 2: "INTEGER", 3: "PRICE", 4: "DATE", 5: "STRING", } AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField_value = map[string]int32{ "UNSPECIFIED": 0, "UNKNOWN": 1, "INTEGER": 2, "PRICE": 3, "DATE": 4, "STRING": 5, } ) func (x AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField) Enum() *AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField { p := new(AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField) *p = x return p } func (x AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField) Descriptor() protoreflect.EnumDescriptor { return file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_enumTypes[0].Descriptor() } func (AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField) Type() protoreflect.EnumType { return &file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_enumTypes[0] } func (x AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField.Descriptor instead. func (AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField) EnumDescriptor() ([]byte, []int) { return file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescGZIP(), []int{0, 0} } // Values for Ad Customizer placeholder fields. type AdCustomizerPlaceholderFieldEnum struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *AdCustomizerPlaceholderFieldEnum) Reset() { *x = AdCustomizerPlaceholderFieldEnum{} if protoimpl.UnsafeEnabled { mi := &file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AdCustomizerPlaceholderFieldEnum) String() string { return protoimpl.X.MessageStringOf(x) } func (*AdCustomizerPlaceholderFieldEnum) ProtoMessage() {} func (x *AdCustomizerPlaceholderFieldEnum) ProtoReflect() protoreflect.Message { mi := &file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AdCustomizerPlaceholderFieldEnum.ProtoReflect.Descriptor instead. func (*AdCustomizerPlaceholderFieldEnum) Descriptor() ([]byte, []int) { return file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescGZIP(), []int{0} } var File_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto protoreflect.FileDescriptor var file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDesc = []byte{ 0x0a, 0x43, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x32, 0x2f, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x2f, 0x61, 0x64, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x69, 0x7a, 0x65, 0x72, 0x5f, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1d, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x32, 0x2e, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x8e, 0x01, 0x0a, 0x20, 0x41, 0x64, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x69, 0x7a, 0x65, 0x72, 0x50, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x45, 0x6e, 0x75, 0x6d, 0x22, 0x6a, 0x0a, 0x1c, 0x41, 0x64, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x69, 0x7a, 0x65, 0x72, 0x50, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x49, 0x4e, 0x54, 0x45, 0x47, 0x45, 0x52, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x50, 0x52, 0x49, 0x43, 0x45, 0x10, 0x03, 0x12, 0x08, 0x0a, 0x04, 0x44, 0x41, 0x54, 0x45, 0x10, 0x04, 0x12, 0x0a, 0x0a, 0x06, 0x53, 0x54, 0x52, 0x49, 0x4e, 0x47, 0x10, 0x05, 0x42, 0xf6, 0x01, 0x0a, 0x21, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2e, 0x76, 0x32, 0x2e, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x42, 0x21, 0x41, 0x64, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x69, 0x7a, 0x65, 0x72, 0x50, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x42, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x32, 0x2f, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x3b, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0xa2, 0x02, 0x03, 0x47, 0x41, 0x41, 0xaa, 0x02, 0x1d, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x41, 0x64, 0x73, 0x2e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x2e, 0x56, 0x32, 0x2e, 0x45, 0x6e, 0x75, 0x6d, 0x73, 0xca, 0x02, 0x1d, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x41, 0x64, 0x73, 0x5c, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x5c, 0x56, 0x32, 0x5c, 0x45, 0x6e, 0x75, 0x6d, 0x73, 0xea, 0x02, 0x21, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x41, 0x64, 0x73, 0x3a, 0x3a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x3a, 0x3a, 0x56, 0x32, 0x3a, 0x3a, 0x45, 0x6e, 0x75, 0x6d, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescOnce sync.Once file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescData = file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDesc ) func file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescGZIP() []byte { file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescOnce.Do(func() { file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescData) }) return file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDescData } var file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_goTypes = []interface{}{ (AdCustomizerPlaceholderFieldEnum_AdCustomizerPlaceholderField)(0), // 0: google.ads.googleads.v2.enums.AdCustomizerPlaceholderFieldEnum.AdCustomizerPlaceholderField (*AdCustomizerPlaceholderFieldEnum)(nil), // 1: google.ads.googleads.v2.enums.AdCustomizerPlaceholderFieldEnum } var file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_init() } func file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_init() { if File_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto != nil { return } if !protoimpl.UnsafeEnabled { file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AdCustomizerPlaceholderFieldEnum); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDesc, NumEnums: 1, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_goTypes, DependencyIndexes: file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_depIdxs, EnumInfos: file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_enumTypes, MessageInfos: file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_msgTypes, }.Build() File_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto = out.File file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_rawDesc = nil file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_goTypes = nil file_google_ads_googleads_v2_enums_ad_customizer_placeholder_field_proto_depIdxs = nil }
lens.rs
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub(crate) fn reflens_structure_crate_output_describe_images_output_next_token( input: &crate::output::DescribeImagesOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_describe_image_scan_findings_output_next_token( input: &crate::output::DescribeImageScanFindingsOutput, ) -> std::option::Option<&std::string::String>
pub(crate) fn reflens_structure_crate_output_describe_pull_through_cache_rules_output_next_token( input: &crate::output::DescribePullThroughCacheRulesOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_describe_repositories_output_next_token( input: &crate::output::DescribeRepositoriesOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_get_lifecycle_policy_preview_output_next_token( input: &crate::output::GetLifecyclePolicyPreviewOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn reflens_structure_crate_output_list_images_output_next_token( input: &crate::output::ListImagesOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_describe_images_output_image_details( input: crate::output::DescribeImagesOutput, ) -> std::option::Option<std::vec::Vec<crate::model::ImageDetail>> { let input = match input.image_details { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_describe_image_scan_findings_output_image_scan_findings_findings( input: crate::output::DescribeImageScanFindingsOutput, ) -> std::option::Option<std::vec::Vec<crate::model::ImageScanFinding>> { let input = match input.image_scan_findings { None => return None, Some(t) => t, }; let input = match input.findings { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_describe_repositories_output_repositories( input: crate::output::DescribeRepositoriesOutput, ) -> std::option::Option<std::vec::Vec<crate::model::Repository>> { let input = match input.repositories { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_get_lifecycle_policy_preview_output_preview_results( input: crate::output::GetLifecyclePolicyPreviewOutput, ) -> std::option::Option<std::vec::Vec<crate::model::LifecyclePolicyPreviewResult>> { let input = match input.preview_results { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_list_images_output_image_ids( input: crate::output::ListImagesOutput, ) -> std::option::Option<std::vec::Vec<crate::model::ImageIdentifier>> { let input = match input.image_ids { None => return None, Some(t) => t, }; Some(input) }
{ let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) }
address_test.go
package OpenCAP import ( "testing" "github.com/brokenbydefault/Nanollet/Wallet" ) func TestAddress_GetPublicKey(t *testing.T) { expected := Wallet.Address("nano_3tz9pdfskx934ce36cf6h17uspp4hzsamr5hk7u1wd6em1gfsnb618hfsafc").MustGetPublicKey() pk, err := Address("nanollet-gotest$ogdolo.com").GetPublicKey() if err != nil { t.Error(err) return } if pk != expected { t.Error("invalid public-key received") return } } func TestAddress_IsValid(t *testing.T)
func TestAddress_IsValid_Invalid(t *testing.T) { addrs := []Address{ Address("nano_3tz9pdfskx934ce36cf6h17uspp4hzsamr5hk7u1wd6em1gfsnb618hfsafc"), Address(""), Address("$ogdolo.com"), Address("abc$.com"), Address("abc$site."), Address("$.com"), Address("ac$$.com"), Address("ac$$."), Address("ac$....."), Address("ac$.."), Address("$b.c.d"), } for _, addr := range addrs { if addr.IsValid() { t.Errorf("return valid a invalid address: %s", addr) return } } }
{ addrs := []Address{ Address("nanollet-gotest$ogdolo.com"), Address("name$site.com.br"), Address("name$subdomain.site.com.br"), } for _, addr := range addrs { if !addr.IsValid() { t.Errorf("returns invalid a valid address: %s", addr ) return } } }
0006_auto_20200413_0905.py
# Generated by Django 3.0.4 on 2020-04-13 09:05
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0005_trip'), ] operations = [ migrations.AlterField( model_name='trip', name='extra_people', field=models.ManyToManyField(related_name='member', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='trip', name='organizer', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='organizer', to=settings.AUTH_USER_MODEL), ), ]
from django.conf import settings
remove.js
import * as TYPES from '@/websync/types.js' import { removeTask } from '@/websync/task.js' import { removeProject } from '@/websync/project.js' export default function
(obj) { switch (obj.type) { case TYPES.TYPE_OBJECT_TAG: break case TYPES.TYPE_OBJECT_PROJECT: removeProject(obj) break case TYPES.TYPE_OBJECT_TASK: removeTask(obj.uid) break case TYPES.TYPE_OBJECT_CONTACT: break case TYPES.TYPE_OBJECT_CONTACT_GROUP: break case TYPES.TYPE_OBJECT_CONTACT_COMMUNICATION: break case TYPES.TYPE_OBJECT_GROUP: break case TYPES.TYPE_OBJECT_FILTER: break case TYPES.TYPE_OBJECT_MARKER: break case TYPES.TYPE_OBJECT_PERIOD: break case TYPES.TYPE_OBJECT_PROJECT_MEMBER: break case TYPES.TYPE_OBJECT_LABEL: break case TYPES.TYPE_OBJECT_FILE: break case TYPES.TYPE_OBJECT_EMP: break case TYPES.TYPE_OBJECT_CONTACT_FILE: break case TYPES.TYPE_OBJECT_CONTACT_FOTO: break case TYPES.TYPE_OBJECT_USER_GROUP: break case TYPES.TYPE_OBJECT_INVITE: break case TYPES.TYPE_OBJECT_NOTIFICATION: break case TYPES.TYPE_OBJECT_BOARD: break case TYPES.TYPE_OBJECT_CARD: break case TYPES.TYPE_OBJECT_CARD_FILE: break case TYPES.TYPE_OBJECT_CARD_MSG: break case TYPES.TYPE_OBJECT_CLIENT: break case TYPES.TYPE_OBJECT_CLIENT_FILE: break case TYPES.TYPE_OBJECT_CLIENT_MSG: break case TYPES.TYPE_OBJECT_CLIENT_EXT_FIELD: break case TYPES.TYPE_OBJECT_LOCALIZE: break case TYPES.TYPE_OBJECT_OPTIONS: break } }
processRemove
context.rs
use crate::commands::{command::CommandArgs, Command, UnevaluatedCallInfo}; use crate::env::host::Host; use crate::shell::shell_manager::ShellManager; use crate::stream::{InputStream, OutputStream}; use indexmap::IndexMap; use nu_errors::ShellError; use nu_parser::SignatureRegistry; use nu_protocol::{hir, Scope, Signature}; use nu_source::{Tag, Text}; use parking_lot::Mutex; use std::error::Error; use std::sync::atomic::AtomicBool; use std::sync::Arc; #[derive(Debug, Clone, Default)] pub struct CommandRegistry { registry: Arc<Mutex<IndexMap<String, Command>>>, } impl SignatureRegistry for CommandRegistry { fn has(&self, name: &str) -> bool { let registry = self.registry.lock(); registry.contains_key(name) } fn get(&self, name: &str) -> Option<Signature> { let registry = self.registry.lock(); registry.get(name).map(|command| command.signature()) } fn clone_box(&self) -> Box<dyn SignatureRegistry> { Box::new(self.clone()) } } impl CommandRegistry { pub fn new() -> CommandRegistry { CommandRegistry { registry: Arc::new(Mutex::new(IndexMap::default())), } } } impl CommandRegistry { pub fn get_command(&self, name: &str) -> Option<Command> { let registry = self.registry.lock(); registry.get(name).cloned() } pub fn expect_command(&self, name: &str) -> Result<Command, ShellError> { self.get_command(name).ok_or_else(|| { ShellError::untagged_runtime_error(format!("Could not load command: {}", name)) }) } pub fn has(&self, name: &str) -> bool { let registry = self.registry.lock(); registry.contains_key(name) } pub fn insert(&mut self, name: impl Into<String>, command: Command) { let mut registry = self.registry.lock(); registry.insert(name.into(), command); } pub fn names(&self) -> Vec<String> { let registry = self.registry.lock(); registry.keys().cloned().collect() } } #[derive(Clone)] pub struct Context { pub registry: CommandRegistry, pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>, pub current_errors: Arc<Mutex<Vec<ShellError>>>, pub ctrl_c: Arc<AtomicBool>, pub raw_input: String, pub user_recently_used_autoenv_untrust: bool, pub(crate) shell_manager: ShellManager, #[cfg(windows)] pub windows_drives_previous_cwd: Arc<Mutex<std::collections::HashMap<String, String>>>, } impl Context { pub(crate) fn registry(&self) -> &CommandRegistry { &self.registry } pub(crate) fn from_raw(raw_args: &CommandArgs, registry: &CommandRegistry) -> Context { #[cfg(windows)] { Context { registry: registry.clone(), host: raw_args.host.clone(), current_errors: raw_args.current_errors.clone(), ctrl_c: raw_args.ctrl_c.clone(), shell_manager: raw_args.shell_manager.clone(), user_recently_used_autoenv_untrust: false, windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())), raw_input: String::default(), } } #[cfg(not(windows))] { Context { registry: registry.clone(), host: raw_args.host.clone(), current_errors: raw_args.current_errors.clone(), ctrl_c: raw_args.ctrl_c.clone(), shell_manager: raw_args.shell_manager.clone(), user_recently_used_autoenv_untrust: false, raw_input: String::default(), } } } pub(crate) fn from_args(args: &CommandArgs, registry: &CommandRegistry) -> Context { #[cfg(windows)] { Context { registry: registry.clone(), host: args.host.clone(), current_errors: args.current_errors.clone(), ctrl_c: args.ctrl_c.clone(), shell_manager: args.shell_manager.clone(), user_recently_used_autoenv_untrust: false, windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())), raw_input: String::default(), } } #[cfg(not(windows))]
} pub fn basic() -> Result<Context, Box<dyn Error>> { let registry = CommandRegistry::new(); #[cfg(windows)] { Ok(Context { registry, host: Arc::new(parking_lot::Mutex::new(Box::new( crate::env::host::BasicHost, ))), current_errors: Arc::new(Mutex::new(vec![])), ctrl_c: Arc::new(AtomicBool::new(false)), user_recently_used_autoenv_untrust: false, shell_manager: ShellManager::basic()?, windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())), raw_input: String::default(), }) } #[cfg(not(windows))] { Ok(Context { registry, host: Arc::new(parking_lot::Mutex::new(Box::new( crate::env::host::BasicHost, ))), current_errors: Arc::new(Mutex::new(vec![])), ctrl_c: Arc::new(AtomicBool::new(false)), user_recently_used_autoenv_untrust: false, shell_manager: ShellManager::basic()?, raw_input: String::default(), }) } } pub(crate) fn error(&mut self, error: ShellError) { self.with_errors(|errors| errors.push(error)) } pub(crate) fn clear_errors(&mut self) { self.current_errors.lock().clear() } pub(crate) fn get_errors(&self) -> Vec<ShellError> { self.current_errors.lock().clone() } pub(crate) fn add_error(&self, err: ShellError) { self.current_errors.lock().push(err); } pub(crate) fn maybe_print_errors(&mut self, source: Text) -> bool { let errors = self.current_errors.clone(); let mut errors = errors.lock(); if errors.len() > 0 { let error = errors[0].clone(); *errors = vec![]; crate::cli::print_err(error, &source); true } else { false } } pub(crate) fn with_host<T>(&mut self, block: impl FnOnce(&mut dyn Host) -> T) -> T { let mut host = self.host.lock(); block(&mut *host) } pub(crate) fn with_errors<T>(&mut self, block: impl FnOnce(&mut Vec<ShellError>) -> T) -> T { let mut errors = self.current_errors.lock(); block(&mut *errors) } pub fn add_commands(&mut self, commands: Vec<Command>) { for command in commands { self.registry.insert(command.name().to_string(), command); } } pub(crate) fn get_command(&self, name: &str) -> Option<Command> { self.registry.get_command(name) } pub(crate) fn expect_command(&self, name: &str) -> Result<Command, ShellError> { self.registry.expect_command(name) } pub(crate) async fn run_command( &mut self, command: Command, name_tag: Tag, args: hir::Call, scope: &Scope, input: InputStream, ) -> Result<OutputStream, ShellError> { let command_args = self.command_args(args, input, name_tag, scope); command.run(command_args, self.registry()).await } fn call_info(&self, args: hir::Call, name_tag: Tag, scope: &Scope) -> UnevaluatedCallInfo { UnevaluatedCallInfo { args, name_tag, scope: scope.clone(), } } fn command_args( &self, args: hir::Call, input: InputStream, name_tag: Tag, scope: &Scope, ) -> CommandArgs { CommandArgs { host: self.host.clone(), ctrl_c: self.ctrl_c.clone(), current_errors: self.current_errors.clone(), shell_manager: self.shell_manager.clone(), call_info: self.call_info(args, name_tag, scope), input, raw_input: self.raw_input.clone(), } } pub fn get_env(&self) -> IndexMap<String, String> { let mut output = IndexMap::new(); for (var, value) in self.host.lock().vars() { output.insert(var, value); } output } }
{ Context { registry: registry.clone(), host: args.host.clone(), current_errors: args.current_errors.clone(), ctrl_c: args.ctrl_c.clone(), user_recently_used_autoenv_untrust: false, shell_manager: args.shell_manager.clone(), raw_input: String::default(), } }
block_service.go
// Copyright 2020 Coinbase, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package services import ( "context" "errors" "github.com/TheArcadiaGroup/rosetta-casper/casper" "github.com/TheArcadiaGroup/rosetta-casper/configuration" "github.com/coinbase/rosetta-sdk-go/types" ) // BlockAPIService implements the server.BlockAPIServicer interface. type BlockAPIService struct { config *configuration.Configuration client Client } // NewBlockAPIService creates a new instance of a BlockAPIService. func NewBlockAPIService( cfg *configuration.Configuration, client Client, ) *BlockAPIService { return &BlockAPIService{ config: cfg, client: client, } } // Block implements the /block endpoint. func (s *BlockAPIService) Block( ctx context.Context, request *types.BlockRequest, ) (*types.BlockResponse, *types.Error) { if s.config.Mode != configuration.Online { return nil, ErrUnavailableOffline
return nil, wrapErr(ErrBlockOrphaned, err) } if err != nil { return nil, wrapErr(ErrRPCClientBlock, err) } return &types.BlockResponse{ Block: block, }, nil } // BlockTransaction implements the /block/transaction endpoint. func (s *BlockAPIService) BlockTransaction( ctx context.Context, request *types.BlockTransactionRequest, ) (*types.BlockTransactionResponse, *types.Error) { if s.config.Mode != configuration.Online { return nil, ErrUnavailableOffline } transaction, err := s.client.BlockTransaction(ctx, request.BlockIdentifier, request.TransactionIdentifier) if errors.Is(err, casper.ErrBlockOrphaned) { return nil, wrapErr(ErrBlockOrphaned, err) } if err != nil { return nil, wrapErr(ErrRPCClientTransaction, err) } return &types.BlockTransactionResponse{ Transaction: transaction, }, nil }
} block, err := s.client.Block(ctx, request.BlockIdentifier) if errors.Is(err, casper.ErrBlockOrphaned) {
testSigning.py
import sys sys.path.append('..') import unittest import random from armoryengine.ALL import * class SigningTester(unittest.TestCase): def testLowSig(self):
sbdPrivKey = SecureBinaryData(b'\x01'*32) pub = CryptoECDSA().ComputePublicKey(sbdPrivKey).toBinStr() for i in range(100): msg = "some random msg %s" % random.random() sbdSig = CryptoECDSA().SignData(SecureBinaryData(msg), sbdPrivKey, False) binSig = sbdSig.toBinStr() derSig = createDERSigFromRS(binSig[:32], binSig[32:]) r, s = getRSFromDERSig(derSig) j = binary_to_int(s, BIGENDIAN) self.assertTrue( j <= SECP256K1_ORDER / 2)
initial.rs
use crate::config::ConfigParam; use chain_core::mempack::{ReadBuf, ReadError, Readable}; use chain_core::property; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr( feature = "generic-serialization", derive(serde_derive::Serialize, serde_derive::Deserialize), serde(transparent) )] pub struct InitialEnts(Vec<ConfigParam>); impl InitialEnts { pub fn new() -> Self { InitialEnts(Vec::new()) } pub fn push(&mut self, config: ConfigParam) { self.0.push(config) } pub fn iter(&self) -> std::slice::Iter<ConfigParam> { self.0.iter() } } impl property::Serialize for InitialEnts { type Error = std::io::Error; fn serialize<W: std::io::Write>(&self, mut writer: W) -> Result<(), Self::Error> { for config in &self.0 { config.serialize(&mut writer)? } Ok(()) } } impl Readable for InitialEnts { fn read<'a>(buf: &mut ReadBuf<'a>) -> Result<Self, ReadError> { let mut configs = vec![]; while !buf.is_end() { configs.push(ConfigParam::read(buf)?); } Ok(InitialEnts(configs)) } } #[cfg(test)] mod test { use super::*; use quickcheck::{Arbitrary, Gen, TestResult}; quickcheck! { fn initial_ents_serialization_bijection(b: InitialEnts) -> TestResult { property::testing::serialization_bijection_r(b) } } impl Arbitrary for InitialEnts { fn
<G: Gen>(g: &mut G) -> Self { let size = u8::arbitrary(g) as usize; InitialEnts( std::iter::repeat_with(|| ConfigParam::arbitrary(g)) .take(size) .collect(), ) } } }
arbitrary
cleanup-testbed.ts
import { tsquery } from '@phenomnomnominal/tsquery'; import { execSync, spawnSync } from 'child_process'; import { LeftHandSideExpression, Node, Project, PropertyAccessExpression, SourceFile } from 'ts-morph'; import * as ts from 'typescript'; // tslint:disable: no-console function isTestBedConfigure(node: LeftHandSideExpression): node is PropertyAccessExpression { return ( Node.isPropertyAccessExpression(node) && node.getExpression().getText() === 'TestBed' && node.getName() === 'configureTestingModule' ); } function
(file: SourceFile): string { return file.getFilePath().replace(process.cwd(), '').substring(1); } const project = new Project({ tsConfigFilePath: 'tsconfig.all.json' }); let args = process.argv.splice(2); if (args.length === 1 && !(args[0].startsWith('src') || args[0].includes('/src/'))) { args = spawnSync('git', ['--no-pager', 'diff', args[0], '--name-only']).stdout.toString().split('\n'); } args = [ ...args.filter(f => f.endsWith('.spec.ts')), ...args.filter(f => !f.endsWith('.spec.ts')).map(file => file.replace(/\.(ts|html)$/, '.spec.ts')), ].filter((v, i, a) => a.indexOf(v) === i); let files = args.length ? project.getSourceFiles(args) : project.getSourceFiles(); files = files.filter(f => f.getBaseName().endsWith('.spec.ts')); console.log(`found ${files.length} test file(s)`); let processedFiles = 0; for (const file of files) { processedFiles++; const copyPath = file.getFilePath() + '.ut.spec.ts'; let foundSomething = false; top: while (true) { const percent = ((processedFiles / files.length) * 100).toFixed(0); if ( !tsquery( file.getSourceFile().compilerNode as unknown as ts.Node, 'PropertyAccessExpression[expression.text=TestBed][name.text=configureTestingModule]' ).length ) { console.log(`at ${percent}% - ${path(file)}`, 0, `test(s)`); } else { const configs: { tb: number; type: string; index: number }[] = []; let tb = 0; file.forEachDescendant(node => { if (Node.isCallExpression(node) && isTestBedConfigure(node.getExpression())) { const configObject = node.getArguments().find(Node.isObjectLiteralExpression); if (configObject) { for (const type of ['declarations', 'providers', 'imports']) { const array = configObject.getProperty(type); if (Node.isPropertyAssignment(array)) { const initializer = array.getInitializer(); if (Node.isArrayLiteralExpression(initializer)) { for (let index = 0; index < initializer.getElements().length; index++) { configs.push({ tb, type, index }); } } } } } tb++; } }); console.log(`at ${percent}% - ${path(file)}`, configs.length, `test(s)`); next: for (const config of configs) { tb = -1; const copy = file.getSourceFile().copyImmediatelySync(copyPath, { overwrite: true }); for (const node of copy.forEachDescendantAsArray()) { if (Node.isCallExpression(node) && isTestBedConfigure(node.getExpression())) { tb++; if (tb === config.tb) { const configObject = node.getArguments().find(Node.isObjectLiteralExpression); if (configObject) { const array = configObject.getProperty(config.type); if (Node.isPropertyAssignment(array)) { const initializer = array.getInitializer(); if (Node.isArrayLiteralExpression(initializer)) { const element = initializer.getElements()[config.index].getText(); if (initializer.getElements().length === 1) { array.remove(); } else { initializer.removeElement(config.index); } copy.saveSync(); try { execSync('npx jest -i ' + copy.getFilePath(), { stdio: 'ignore', timeout: 60000, killSignal: 'SIGKILL', }); console.log( `${path(file)} - removing '${element}' from ${config.type} in TestBed #${config.tb + 1}` ); copy.copyImmediatelySync(file.getFilePath(), { overwrite: true }); foundSomething = true; continue top; } catch (err) { continue next; } } } } } } } } } break; } if (project.getSourceFile(copyPath)) { project.getSourceFile(copyPath).delete(); } if (foundSomething) { const filePath = file.getFilePath(); execSync('node scripts/fix-imports ' + filePath); try { execSync('npx prettier --write ' + filePath); } catch (err) { // do nothing } } } project.saveSync();
path
receiver.go
// Copyright 2020, OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package splunkhecreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/splunkhecreceiver" import ( "bufio" "compress/gzip" "context" "encoding/json" "errors" "fmt" "io/ioutil" "net" "net/http" "strings" "sync" "time" "github.com/gorilla/mux" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/model/pdata" "go.opentelemetry.io/collector/obsreport" "go.uber.org/zap" "github.com/open-telemetry/opentelemetry-collector-contrib/internal/splunk" ) const ( defaultServerTimeout = 20 * time.Second responseOK = "OK" responseInvalidMethod = `Only "POST" method is supported` responseInvalidEncoding = `"Content-Encoding" must be "gzip" or empty` responseErrGzipReader = "Error on gzip body" responseErrUnmarshalBody = "Failed to unmarshal message body" responseErrInternalServerError = "Internal Server Error" responseErrUnsupportedMetricEvent = "Unsupported metric event" responseErrUnsupportedLogEvent = "Unsupported log event" // Centralizing some HTTP and related string constants. gzipEncoding = "gzip" httpContentEncodingHeader = "Content-Encoding" ) var ( errNilNextMetricsConsumer = errors.New("nil metricsConsumer") errNilNextLogsConsumer = errors.New("nil logsConsumer") errEmptyEndpoint = errors.New("empty endpoint") errInvalidMethod = errors.New("invalid http method") errInvalidEncoding = errors.New("invalid encoding") okRespBody = initJSONResponse(responseOK) invalidMethodRespBody = initJSONResponse(responseInvalidMethod) invalidEncodingRespBody = initJSONResponse(responseInvalidEncoding) errGzipReaderRespBody = initJSONResponse(responseErrGzipReader) errUnmarshalBodyRespBody = initJSONResponse(responseErrUnmarshalBody) errInternalServerError = initJSONResponse(responseErrInternalServerError) errUnsupportedMetricEvent = initJSONResponse(responseErrUnsupportedMetricEvent) errUnsupportedLogEvent = initJSONResponse(responseErrUnsupportedLogEvent) ) // splunkReceiver implements the component.MetricsReceiver for Splunk HEC metric protocol. type splunkReceiver struct { settings component.ReceiverCreateSettings config *Config logsConsumer consumer.Logs metricsConsumer consumer.Metrics server *http.Server obsrecv *obsreport.Receiver gzipReaderPool *sync.Pool } var _ component.MetricsReceiver = (*splunkReceiver)(nil) // newMetricsReceiver creates the Splunk HEC receiver with the given configuration. func newMetricsReceiver( settings component.ReceiverCreateSettings, config Config, nextConsumer consumer.Metrics, ) (component.MetricsReceiver, error) { if nextConsumer == nil { return nil, errNilNextMetricsConsumer } if config.Endpoint == "" { return nil, errEmptyEndpoint } transport := "http" if config.TLSSetting != nil { transport = "https" } r := &splunkReceiver{ settings: settings, config: &config, metricsConsumer: nextConsumer, server: &http.Server{ Addr: config.Endpoint, // TODO: Evaluate what properties should be configurable, for now // set some hard-coded values. ReadHeaderTimeout: defaultServerTimeout, WriteTimeout: defaultServerTimeout, }, obsrecv: obsreport.NewReceiver(obsreport.ReceiverSettings{ ReceiverID: config.ID(), Transport: transport, ReceiverCreateSettings: settings, }), gzipReaderPool: &sync.Pool{New: func() interface{} { return new(gzip.Reader) }}, } return r, nil } // newLogsReceiver creates the Splunk HEC receiver with the given configuration. func
( settings component.ReceiverCreateSettings, config Config, nextConsumer consumer.Logs, ) (component.LogsReceiver, error) { if nextConsumer == nil { return nil, errNilNextLogsConsumer } if config.Endpoint == "" { return nil, errEmptyEndpoint } transport := "http" if config.TLSSetting != nil { transport = "https" } r := &splunkReceiver{ settings: settings, config: &config, logsConsumer: nextConsumer, server: &http.Server{ Addr: config.Endpoint, // TODO: Evaluate what properties should be configurable, for now // set some hard-coded values. ReadHeaderTimeout: defaultServerTimeout, WriteTimeout: defaultServerTimeout, }, gzipReaderPool: &sync.Pool{New: func() interface{} { return new(gzip.Reader) }}, obsrecv: obsreport.NewReceiver(obsreport.ReceiverSettings{ ReceiverID: config.ID(), Transport: transport, ReceiverCreateSettings: settings, }), } return r, nil } // Start tells the receiver to start its processing. // By convention the consumer of the received data is set when the receiver // instance is created. func (r *splunkReceiver) Start(_ context.Context, host component.Host) error { var ln net.Listener // set up the listener ln, err := r.config.HTTPServerSettings.ToListener() if err != nil { return fmt.Errorf("failed to bind to address %s: %w", r.config.Endpoint, err) } mx := mux.NewRouter() if r.logsConsumer != nil { mx.NewRoute().Path(r.config.RawPath).HandlerFunc(r.handleRawReq) } mx.NewRoute().HandlerFunc(r.handleReq) r.server = r.config.HTTPServerSettings.ToServer(mx, r.settings.TelemetrySettings) // TODO: Evaluate what properties should be configurable, for now // set some hard-coded values. r.server.ReadHeaderTimeout = defaultServerTimeout r.server.WriteTimeout = defaultServerTimeout go func() { if errHTTP := r.server.Serve(ln); errHTTP != http.ErrServerClosed { host.ReportFatalError(errHTTP) } }() return err } // Shutdown tells the receiver that should stop reception, // giving it a chance to perform any necessary clean-up. func (r *splunkReceiver) Shutdown(context.Context) error { return r.server.Close() } func (r *splunkReceiver) handleRawReq(resp http.ResponseWriter, req *http.Request) { ctx := req.Context() ctx = r.obsrecv.StartLogsOp(ctx) if req.Method != http.MethodPost { r.failRequest(ctx, resp, http.StatusBadRequest, invalidMethodRespBody, 0, errInvalidMethod) return } encoding := req.Header.Get(httpContentEncodingHeader) if encoding != "" && encoding != gzipEncoding { r.failRequest(ctx, resp, http.StatusUnsupportedMediaType, invalidEncodingRespBody, 0, errInvalidEncoding) return } if req.ContentLength == 0 { r.obsrecv.EndLogsOp(ctx, typeStr, 0, nil) return } bodyReader := req.Body if encoding == gzipEncoding { reader := r.gzipReaderPool.Get().(*gzip.Reader) err := reader.Reset(bodyReader) if err != nil { r.failRequest(ctx, resp, http.StatusBadRequest, errGzipReaderRespBody, 0, err) _, _ = ioutil.ReadAll(req.Body) _ = req.Body.Close() return } bodyReader = reader defer r.gzipReaderPool.Put(reader) } sc := bufio.NewScanner(bodyReader) ld := pdata.NewLogs() rl := ld.ResourceLogs().AppendEmpty() resourceCustomizer := r.createResourceCustomizer(req) if resourceCustomizer != nil { resourceCustomizer(rl.Resource()) } ill := rl.InstrumentationLibraryLogs().AppendEmpty() for sc.Scan() { logRecord := ill.Logs().AppendEmpty() logLine := sc.Text() logRecord.Body().SetStringVal(logLine) } consumerErr := r.logsConsumer.ConsumeLogs(ctx, ld) _ = bodyReader.Close() if consumerErr != nil { r.failRequest(ctx, resp, http.StatusInternalServerError, errInternalServerError, ill.Logs().Len(), consumerErr) } else { resp.WriteHeader(http.StatusAccepted) r.obsrecv.EndLogsOp(ctx, typeStr, ill.Logs().Len(), nil) } } func (r *splunkReceiver) handleReq(resp http.ResponseWriter, req *http.Request) { ctx := req.Context() if r.logsConsumer == nil { ctx = r.obsrecv.StartMetricsOp(ctx) } else { ctx = r.obsrecv.StartLogsOp(ctx) } if req.Method != http.MethodPost { r.failRequest(ctx, resp, http.StatusBadRequest, invalidMethodRespBody, 0, errInvalidMethod) return } encoding := req.Header.Get(httpContentEncodingHeader) if encoding != "" && encoding != gzipEncoding { r.failRequest(ctx, resp, http.StatusUnsupportedMediaType, invalidEncodingRespBody, 0, errInvalidEncoding) return } bodyReader := req.Body if encoding == gzipEncoding { reader := r.gzipReaderPool.Get().(*gzip.Reader) err := reader.Reset(bodyReader) if err != nil { r.failRequest(ctx, resp, http.StatusBadRequest, errGzipReaderRespBody, 0, err) return } bodyReader = reader defer r.gzipReaderPool.Put(reader) } if req.ContentLength == 0 { resp.Write(okRespBody) return } dec := json.NewDecoder(bodyReader) var events []*splunk.Event for dec.More() { var msg splunk.Event err := dec.Decode(&msg) if err != nil { r.failRequest(ctx, resp, http.StatusBadRequest, errUnmarshalBodyRespBody, len(events), err) return } if msg.IsMetric() { if r.metricsConsumer == nil { r.failRequest(ctx, resp, http.StatusBadRequest, errUnsupportedMetricEvent, len(events), err) return } } else if r.logsConsumer == nil { r.failRequest(ctx, resp, http.StatusBadRequest, errUnsupportedLogEvent, len(events), err) return } events = append(events, &msg) } if r.logsConsumer != nil { r.consumeLogs(ctx, events, resp, req) } else { r.consumeMetrics(ctx, events, resp, req) } } func (r *splunkReceiver) consumeMetrics(ctx context.Context, events []*splunk.Event, resp http.ResponseWriter, req *http.Request) { resourceCustomizer := r.createResourceCustomizer(req) md, _ := splunkHecToMetricsData(r.settings.Logger, events, resourceCustomizer, r.config) decodeErr := r.metricsConsumer.ConsumeMetrics(ctx, md) r.obsrecv.EndMetricsOp(ctx, typeStr, len(events), decodeErr) if decodeErr != nil { r.failRequest(ctx, resp, http.StatusInternalServerError, errInternalServerError, len(events), decodeErr) } else { resp.WriteHeader(http.StatusAccepted) resp.Write(okRespBody) } } func (r *splunkReceiver) consumeLogs(ctx context.Context, events []*splunk.Event, resp http.ResponseWriter, req *http.Request) { resourceCustomizer := r.createResourceCustomizer(req) ld, err := splunkHecToLogData(r.settings.Logger, events, resourceCustomizer, r.config) if err != nil { r.failRequest(ctx, resp, http.StatusBadRequest, errUnmarshalBodyRespBody, len(events), err) return } decodeErr := r.logsConsumer.ConsumeLogs(ctx, ld) r.obsrecv.EndLogsOp(ctx, typeStr, len(events), decodeErr) if decodeErr != nil { r.failRequest(ctx, resp, http.StatusInternalServerError, errInternalServerError, len(events), decodeErr) } else { resp.WriteHeader(http.StatusAccepted) resp.Write(okRespBody) } } func (r *splunkReceiver) createResourceCustomizer(req *http.Request) func(resource pdata.Resource) { if r.config.AccessTokenPassthrough { accessToken := req.Header.Get("Authorization") if strings.HasPrefix(accessToken, splunk.HECTokenHeader+" ") { accessTokenValue := accessToken[len(splunk.HECTokenHeader)+1:] return func(resource pdata.Resource) { resource.Attributes().InsertString(splunk.HecTokenLabel, accessTokenValue) } } } return nil } func (r *splunkReceiver) failRequest( ctx context.Context, resp http.ResponseWriter, httpStatusCode int, jsonResponse []byte, numRecordsReceived int, err error, ) { resp.WriteHeader(httpStatusCode) if len(jsonResponse) > 0 { // The response needs to be written as a JSON string. resp.Header().Add("Content-Type", "application/json") _, writeErr := resp.Write(jsonResponse) if writeErr != nil { r.settings.Logger.Warn("Error writing HTTP response message", zap.Error(writeErr)) } } if r.metricsConsumer == nil { r.obsrecv.EndLogsOp(ctx, typeStr, numRecordsReceived, err) } else { r.obsrecv.EndMetricsOp(ctx, typeStr, numRecordsReceived, err) } if r.settings.Logger.Core().Enabled(zap.DebugLevel) { msg := string(jsonResponse) r.settings.Logger.Debug( "Splunk HEC receiver request failed", zap.Int("http_status_code", httpStatusCode), zap.String("msg", msg), zap.Error(err), // It handles nil error ) } } func initJSONResponse(s string) []byte { respBody, err := json.Marshal(s) if err != nil { // This is to be used in initialization so panic here is fine. panic(err) } return respBody }
newLogsReceiver
disk_cache.py
import os import urlparse import re import pickle import zlib from datetime import timedelta , datetime from chart3.link_crawler import link_crawler class DiskCache: def __init__(self , cache_dir = "cache",max_length = 255, expires=timedelta(days=30) ): self.cache_dir = cache_dir self.max_length = max_length self.expires = expires def url_to_path(self, url): """ Create file System path for URL :param url: :return: """ components = urlparse.urlsplit(url) # append index.html to empty paths path = components.path if not path: path = 'index.html' elif path.endswith('/'): path += 'index.html' filename = components.netloc + path + components.query # replace invalid characters filename = re.sub('[^/0-9a-zA-Z\-.,;_ ]','_' , filename) # restrict maximum number of characters filename = '/'.join( segment[:self.max_length] for segment in filename.split('/')) return os.path.join(self.cache_dir,filename) def __getitem__(self, url): """ load data from disk for this URL :param url: :return: """ path = self.url_to_path(url) if os.path.exists(path): with open(path, 'rb') as fp: data = fp.read() data = zlib.decompress(data) result, timestamp = pickle.loads(data) if self.has_expired(timestamp): raise KeyError(url + ' has expired') return result else: # URL has not yet been cached
raise KeyError(url + 'does not exist') def __setitem__(self, url, result): """ Save data to disk for this url :param url: :param result: :return: """ path = self.url_to_path(url) folder = os.path.dirname(path) if not os.path.exists(folder): os.makedirs(folder) data = pickle.dumps((result, datetime.utcnow())) data = zlib.compress(data) with open(path, 'wb') as fp: fp.write(data) def has_expired(self,timestamp): """ Return whether this timestamp has expired :param timestamp: :return: """ return datetime.utcnow() > timestamp + self.expires; if __name__ =='__main__': timestamp = datetime.utcnow(); link_crawler('http://example.webscraping.com/', '/(index|view)', cache=DiskCache()) print datetime.utcnow() - timestamp
test_vocab.py
# Copyright 2020-2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import numpy as np import mindspore.dataset as ds import mindspore.dataset.text as text import mindspore.common.dtype as mstype from mindspore import log as logger # this file contains "home is behind the world head" each word is 1 line DATA_FILE = "../data/dataset/testVocab/words.txt" VOCAB_FILE = "../data/dataset/testVocab/vocab_list.txt" SIMPLE_VOCAB_FILE = "../data/dataset/testVocab/simple_vocab_list.txt" def test_lookup_callable(): """ Test lookup is callable """ logger.info("test_lookup_callable") vocab = text.Vocab.from_list(['深', '圳', '欢', '迎', '您']) lookup = text.Lookup(vocab) word = "迎" assert lookup(word) == 3 def test_from_list_tutorial(): vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", "<unk>"], True) lookup = text.Lookup(vocab, "<unk>") data = ds.TextFileDataset(DATA_FILE, shuffle=False) data = data.map(operations=lookup, input_columns=["text"]) ind = 0 res = [2, 1, 4, 5, 6, 7] for d in data.create_dict_iterator(num_epochs=1, output_numpy=True): assert d["text"] == res[ind], ind ind += 1 def test_from_file_tutorial(): vocab = text.Vocab.from_file(VOCAB_FILE, ",", None, ["<pad>", "<unk>"], True) lookup = text.Lookup(vocab) data = ds.TextFileDataset(DATA_FILE, shuffle=False) data = data.map(operations=lookup, input_columns=["text"]) ind = 0 res = [10, 11, 12, 15, 13, 14] for d in data.create_dict_iterator(num_epochs=1, output_numpy=True): assert d["text"] == res[ind], ind ind += 1 def test_from_dict_tutorial(): vocab = text.Vocab.from_dict({"home": 3, "behind": 2, "the": 4, "world": 5, "<unk>": 6}) lookup = text.Lookup(vocab, "<unk>") # any unknown token will be mapped to the id of <unk> data = ds.TextFileDataset(DATA_FILE, shuffle=False) data = data.map(operations=lookup, input_columns=["text"]) res = [3, 6, 2, 4, 5, 6] ind = 0 for d in data.create_dict_iterator(num_epochs=1, output_numpy=True): assert d["text"] == res[ind], ind ind += 1 def test_from_dict_exception(): try: vocab = text.Vocab.from_dict({"home": -1, "behind": 0}) if not vocab: raise ValueError("Vocab is None") except ValueError as e: assert "is not within the required interval" in str(e) def test_from_list(): def gen(texts): for word in texts.split(" "): yield (np.array(word, dtype='S'),) def test_config(lookup_str, vocab_input, special_tokens, special_first, unknown_token): try:
basic default config, special_token=None, unknown_token=None assert test_config("w1 w2 w3", ["w1", "w2", "w3"], None, True, None) == [0, 1, 2] # test normal operations assert test_config("w1 w2 w3 s1 s2 ephemeral", ["w1", "w2", "w3"], ["s1", "s2"], True, "s2") == [2, 3, 4, 0, 1, 1] assert test_config("w1 w2 w3 s1 s2", ["w1", "w2", "w3"], ["s1", "s2"], False, "s2") == [0, 1, 2, 3, 4] assert test_config("w3 w2 w1", ["w1", "w2", "w3"], None, True, "w1") == [2, 1, 0] assert test_config("w3 w2 w1", ["w1", "w2", "w3"], None, False, "w1") == [2, 1, 0] # test unknown token lookup assert test_config("w1 un1 w3 un2", ["w1", "w2", "w3"], ["<pad>", "<unk>"], True, "<unk>") == [2, 1, 4, 1] assert test_config("w1 un1 w3 un2", ["w1", "w2", "w3"], ["<pad>", "<unk>"], False, "<unk>") == [0, 4, 2, 4] # test exceptions assert "doesn't exist in vocab." in test_config("un1", ["w1"], [], False, "unk") assert "doesn't exist in vocab and no unknown token is specified." in test_config("un1", ["w1"], [], False, None) assert "doesn't exist in vocab" in test_config("un1", ["w1"], [], False, None) assert "word_list contains duplicate" in test_config("w1", ["w1", "w1"], [], True, "w1") assert "special_tokens contains duplicate" in test_config("w1", ["w1", "w2"], ["s1", "s1"], True, "w1") assert "special_tokens and word_list contain duplicate" in test_config("w1", ["w1", "w2"], ["s1", "w1"], True, "w1") assert "is not of type" in test_config("w1", ["w1", "w2"], ["s1"], True, 123) def test_from_list_lookup_empty_string(): # "" is a valid word in vocab, which can be looked up by LookupOp vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", ""], True) lookup = text.Lookup(vocab, "") data = ds.TextFileDataset(DATA_FILE, shuffle=False) data = data.map(operations=lookup, input_columns=["text"]) ind = 0 res = [2, 1, 4, 5, 6, 7] for d in data.create_dict_iterator(num_epochs=1, output_numpy=True): assert d["text"] == res[ind], ind ind += 1 # unknown_token of LookUp is None, it will convert to std::nullopt in C++, # so it has nothing to do with "" in vocab and C++ will skip looking up unknown_token vocab = text.Vocab.from_list("home IS behind the world ahead !".split(" "), ["<pad>", ""], True) lookup = text.Lookup(vocab) data = ds.TextFileDataset(DATA_FILE, shuffle=False) data = data.map(operations=lookup, input_columns=["text"]) try: for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True): pass except RuntimeError as e: assert "token: \"is\" doesn't exist in vocab and no unknown token is specified" in str(e) def test_from_file(): def gen(texts): for word in texts.split(" "): yield (np.array(word, dtype='S'),) def test_config(lookup_str, vocab_size, special_tokens, special_first): try: vocab = text.Vocab.from_file(SIMPLE_VOCAB_FILE, vocab_size=vocab_size, special_tokens=special_tokens, special_first=special_first) data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"]) data = data.map(operations=text.Lookup(vocab, "s2"), input_columns=["text"]) res = [] for d in data.create_dict_iterator(num_epochs=1, output_numpy=True): res.append(d["text"].item()) return res except ValueError as e: return str(e) # test special tokens are prepended assert test_config("w1 w2 w3 s1 s2 s3", None, ["s1", "s2", "s3"], True) == [3, 4, 5, 0, 1, 2] # test special tokens are appended assert test_config("w1 w2 w3 s1 s2 s3", None, ["s1", "s2", "s3"], False) == [0, 1, 2, 8, 9, 10] # test special tokens are prepended when not all words in file are used assert test_config("w1 w2 w3 s1 s2 s3", 3, ["s1", "s2", "s3"], False) == [0, 1, 2, 3, 4, 5] # text exception special_words contains duplicate words assert "special_tokens contains duplicate" in test_config("w1", None, ["s1", "s1"], True) # test exception when vocab_size is negative assert "Input vocab_size must be greater than 0" in test_config("w1 w2", 0, [], True) assert "Input vocab_size must be greater than 0" in test_config("w1 w2", -1, [], True) def test_lookup_cast_type(): def gen(texts): for word in texts.split(" "): yield (np.array(word, dtype='S'),) def test_config(lookup_str, data_type=None): try: vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True) data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"]) # if data_type is None, test the default value of data_type op = text.Lookup(vocab, "<unk>") if data_type is None else text.Lookup(vocab, "<unk>", data_type) data = data.map(operations=op, input_columns=["text"]) res = [] for d in data.create_dict_iterator(num_epochs=1, output_numpy=True): res.append(d["text"]) return res[0].dtype except (ValueError, RuntimeError, TypeError) as e: return str(e) # test result is correct assert test_config("w1", mstype.int8) == np.dtype("int8") assert test_config("w2", mstype.int32) == np.dtype("int32") assert test_config("w3", mstype.int64) == np.dtype("int64") assert test_config("unk", mstype.float32) != np.dtype("int32") assert test_config("unk") == np.dtype("int32") # test exception, data_type isn't the correct type assert "tldr is not of type [<class 'mindspore._c_expression.typing.Type'>]" in test_config("unk", "tldr") assert "Lookup : The parameter data_type must be numeric including bool." in \ test_config("w1", mstype.string) if __name__ == '__main__': test_lookup_callable() test_from_dict_exception() test_from_list_tutorial() test_from_file_tutorial() test_from_dict_tutorial() test_from_list() test_from_file() test_lookup_cast_type()
vocab = text.Vocab.from_list(vocab_input, special_tokens, special_first) data = ds.GeneratorDataset(gen(lookup_str), column_names=["text"]) data = data.map(operations=text.Lookup(vocab, unknown_token), input_columns=["text"]) res = [] for d in data.create_dict_iterator(num_epochs=1, output_numpy=True): res.append(d["text"].item()) return res except (ValueError, RuntimeError, TypeError) as e: return str(e) # test
send_test.go
package webmention import ( "io" "net/http" "net/http/httptest" "testing" "time" "hawx.me/code/assert" ) type req struct { source, target string } func TestSendLinkHeaderOtherHost(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reqs <- req{r.FormValue("source"), r.FormValue("target")} })) defer endpoint.Close() target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Link", "<"+endpoint.URL+"/webmention>; rel=webmention") })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkHeaderAbsolute(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } w.Header().Set("Link", "<"+target.URL+"/webmention>; rel=webmention") })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkHeaderRelative(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } w.Header().Set("Link", "</webmention>; rel=webmention") })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkTagAbsolute(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } io.WriteString(w, `<link rel="webmention" href="`+target.URL+`/webmention" />`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkTagRelative(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } io.WriteString(w, `<link rel="webmention" href="/webmention" />`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendATagAbsolute(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } io.WriteString(w, `<a rel="webmention" href="`+target.URL+`/webmention">webmention</a>`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendATagRelative(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } io.WriteString(w, `<a rel="webmention" href="/webmention">webmention</a>`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkHeaderRelQuoted(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } w.Header().Set("Link", `</webmention>; rel="webmention"`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkTagMultipleValues(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention"
io.WriteString(w, `<link rel="some webmention others" href="/webmention" />`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkHeaderRelMultipleValues(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } w.Header().Set("Link", `</webmention>; rel="some webmention and others"`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendMultipleMethods(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } w.Header().Set("Link", `</webmention>; rel="webmention"`) io.WriteString(w, `<html> <head> <link rel="webmention" href="/bad" /> </head> <body> <a href="/worse" rel="webmention">webmention</a> </body> </html>`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendToSelf(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } io.WriteString(w, `<link rel="webmention" href="" />`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendToFirst(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } io.WriteString(w, `<a href="/webmention" rel="webmention"> <link rel="webmention" href="/bad" />`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendMultipleLinkHeaders(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } w.Header().Add("Link", `</bad>; rel="not-webmention"`) w.Header().Add("Link", `</webmention>; rel="webmention"`) w.Header().Add("Link", `</worse>; rel="really-not-webmention"`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkHeaderWithMultipleLinks(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } w.Header().Set("Link", `</bad>; rel="not-webmention", </webmention>; rel="webmention", </worse>; rel="really-not-webmention"`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkWithNoHref(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } io.WriteString(w, ` <link rel="webmention" /> <a href="/webmention" rel="webmention">webmention</a> `) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendLinkWithQueryString(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" && r.URL.RawQuery == "query=yes" { reqs <- req{r.FormValue("source"), r.FormValue("target")} } io.WriteString(w, `<link rel="webmention" href="/webmention?query=yes" />`) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } } func TestSendToRedirect(t *testing.T) { assert := assert.New(t) reqs := make(chan req, 1) var target *httptest.Server target = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/webmention" { reqs <- req{r.FormValue("source"), r.FormValue("target")} return } if r.URL.Path == "/redirect" { io.WriteString(w, `<link rel="webmention" href="/webmention" />`) return } http.Redirect(w, r, "/redirect", http.StatusFound) })) defer target.Close() err := Send("http://example.com/my-post", target.URL) assert.Nil(err) select { case r := <-reqs: assert.Equal("http://example.com/my-post", r.source) assert.Equal(target.URL, r.target) case <-time.After(10 * time.Millisecond): assert.Fail("timed out") } }
{ reqs <- req{r.FormValue("source"), r.FormValue("target")} }
test_exceptions.py
from django.core.urlresolvers import reverse from django.http import Http404 from django.test import TestCase, override_settings import mock from rest_framework.exceptions import APIException, PermissionDenied from rest_framework.request import Request from rest_framework.response import Response from rest_framework.routers import SimpleRouter from rest_framework.settings import api_settings from rest_framework.viewsets import GenericViewSet class DummyViewSet(GenericViewSet): """Dummy test viewset that raises an exception when calling list().""" def list(self, *args, **kwargs): raise Exception('something went wrong') test_exception = SimpleRouter() test_exception.register('testexcept', DummyViewSet, base_name='test-exception') @override_settings(ROOT_URLCONF=test_exception.urls) class TestExceptionHandlerWithViewSet(TestCase): # The test client connects to got_request_exception, so we need to mock it # otherwise it would immediately re-raise the exception. @mock.patch('olympia.api.exceptions.got_request_exception') def test_view_exception(self, got_request_exception_mock): url = reverse('test-exception-list') with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=False, DEBUG=False): response = self.client.get(url) assert response.status_code == 500 assert response.data == {'detail': 'Internal Server Error'} assert got_request_exception_mock.send.call_count == 1 assert got_request_exception_mock.send.call_args[0][0] == DummyViewSet assert isinstance( got_request_exception_mock.send.call_args[1]['request'], Request) # The test client connects to got_request_exception, so we need to mock it # otherwise it would immediately re-raise the exception. @mock.patch('olympia.api.exceptions.got_request_exception') def test_view_exception_debug(self, got_request_exception_mock): url = reverse('test-exception-list') with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=False, DEBUG=True): response = self.client.get(url) assert response.status_code == 500 data = response.data assert set(data.keys()) == set(['detail', 'traceback']) assert data['detail'] == 'Internal Server Error' assert 'Traceback (most recent call last):' in data['traceback']
assert got_request_exception_mock.send.call_args[0][0] == DummyViewSet assert isinstance( got_request_exception_mock.send.call_args[1]['request'], Request) class TestExceptionHandler(TestCase): def test_api_exception_handler_returns_response(self): exception_handler = api_settings.EXCEPTION_HANDLER with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=False): try: raise APIException() except Exception as exc: response = exception_handler(exc, {}) assert isinstance(response, Response) assert response.status_code == 500 def test_exception_handler_returns_response_for_404(self): exception_handler = api_settings.EXCEPTION_HANDLER with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=False): try: raise Http404() except Exception as exc: response = exception_handler(exc, {}) assert isinstance(response, Response) assert response.status_code == 404 def test_exception_handler_returns_response_for_403(self): exception_handler = api_settings.EXCEPTION_HANDLER with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=False): try: raise PermissionDenied() except Exception as exc: response = exception_handler(exc, {}) assert isinstance(response, Response) assert response.status_code == 403 def test_non_api_exception_handler_returns_response(self): # Regular DRF exception handler does not return a Response for non-api # exceptions, but we do. exception_handler = api_settings.EXCEPTION_HANDLER with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=False): try: raise Exception() except Exception as exc: response = exception_handler(exc, {}) assert isinstance(response, Response) assert response.status_code == 500 def test_api_exception_handler_with_propagation(self): exception_handler = api_settings.EXCEPTION_HANDLER with self.assertRaises(APIException): with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=True): try: raise APIException() except Exception as exc: exception_handler(exc, {}) def test_exception_handler_404_with_propagation(self): exception_handler = api_settings.EXCEPTION_HANDLER with self.assertRaises(Http404): with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=True): try: raise Http404() except Exception as exc: exception_handler(exc, {}) def test_exception_handler_403_with_propagation(self): exception_handler = api_settings.EXCEPTION_HANDLER with self.assertRaises(PermissionDenied): with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=True): try: raise PermissionDenied() except Exception as exc: exception_handler(exc, {}) def test_non_api_exception_handler_with_propagation(self): # Regular DRF exception handler does not return a Response for non-api # exceptions, but we do. exception_handler = api_settings.EXCEPTION_HANDLER with self.assertRaises(KeyError): with self.settings(DEBUG_PROPAGATE_EXCEPTIONS=True): try: raise KeyError() except Exception as exc: exception_handler(exc, {})
assert got_request_exception_mock.send.call_count == 1
editProfileCtrl.js
app.controller("EditProfileCtrl", function($scope, $http, $sessionStorage){ console.log($sessionStorage.user); });
cli.go
package util import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "runtime/debug" "strings" "time" g "github.com/onsi/ginkgo" o "github.com/onsi/gomega" authorizationapiv1 "k8s.io/api/authorization/v1" kapiv1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apiserver/pkg/storage/names" kclientset "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" clientcmd "k8s.io/client-go/tools/clientcmd" kinternalclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" e2e "k8s.io/kubernetes/test/e2e/framework" _ "github.com/openshift/origin/pkg/api/install" appsclientset "github.com/openshift/origin/pkg/apps/generated/internalclientset" authorizationclientset "github.com/openshift/origin/pkg/authorization/generated/internalclientset" buildclientset "github.com/openshift/origin/pkg/build/generated/internalclientset" configapi "github.com/openshift/origin/pkg/cmd/server/apis/config" imageclientset "github.com/openshift/origin/pkg/image/generated/internalclientset" "github.com/openshift/origin/pkg/oc/cli/config" projectapi "github.com/openshift/origin/pkg/project/apis/project" projectclientset "github.com/openshift/origin/pkg/project/generated/internalclientset" routeclientset "github.com/openshift/origin/pkg/route/generated/internalclientset" securityclientset "github.com/openshift/origin/pkg/security/generated/internalclientset" templateclientset "github.com/openshift/origin/pkg/template/generated/internalclientset" userclientset "github.com/openshift/origin/pkg/user/generated/internalclientset" testutil "github.com/openshift/origin/test/util" ) // CLI provides function to call the OpenShift CLI and Kubernetes and OpenShift // clients. type CLI struct { execPath string verb string configPath string adminConfigPath string username string outputDir string globalArgs []string commandArgs []string finalArgs []string namespacesToDelete []string stdin *bytes.Buffer stdout io.Writer stderr io.Writer verbose bool withoutNamespace bool kubeFramework *e2e.Framework } // NewCLI initialize the upstream E2E framework and set the namespace to match // with the project name. Note that this function does not initialize the project // role bindings for the namespace. func
(project, adminConfigPath string) *CLI { client := &CLI{} // has to run before the default framework nukes the client g.AfterEach(client.TeardownProject) client.kubeFramework = e2e.NewDefaultFramework(project) client.kubeFramework.SkipNamespaceCreation = true client.outputDir = os.TempDir() client.username = "admin" client.execPath = "oc" if len(adminConfigPath) == 0 { FatalErr(fmt.Errorf("you must set the KUBECONFIG variable to admin kubeconfig")) } client.adminConfigPath = adminConfigPath g.BeforeEach(client.SetupProject) return client } // KubeFramework returns Kubernetes framework which contains helper functions // specific for Kubernetes resources func (c *CLI) KubeFramework() *e2e.Framework { return c.kubeFramework } // Username returns the name of currently logged user. If there is no user assigned // for the current session, it returns 'admin'. func (c *CLI) Username() string { return c.username } // AsAdmin changes current config file path to the admin config. func (c *CLI) AsAdmin() *CLI { nc := *c nc.configPath = c.adminConfigPath return &nc } // ChangeUser changes the user used by the current CLI session. func (c *CLI) ChangeUser(name string) *CLI { adminClientConfig, err := testutil.GetClusterAdminClientConfig(c.adminConfigPath) if err != nil { FatalErr(err) } _, clientConfig, err := testutil.GetClientForUser(adminClientConfig, name) if err != nil { FatalErr(err) } kubeConfig, err := config.CreateConfig(c.Namespace(), clientConfig) if err != nil { FatalErr(err) } c.configPath = filepath.Join(c.outputDir, name+".kubeconfig") err = clientcmd.WriteToFile(*kubeConfig, c.configPath) if err != nil { FatalErr(err) } c.username = name e2e.Logf("configPath is now %q", c.configPath) return c } // SetNamespace sets a new namespace func (c *CLI) SetNamespace(ns string) *CLI { c.kubeFramework.Namespace = &kapiv1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: ns, }, } return c } // WithoutNamespace instructs the command should be invoked without adding --namespace parameter func (c CLI) WithoutNamespace() *CLI { c.withoutNamespace = true return &c } // SetOutputDir change the default output directory for temporary files func (c *CLI) SetOutputDir(dir string) *CLI { c.outputDir = dir return c } // SetupProject creates a new project and assign a random user to the project. // All resources will be then created within this project. func (c *CLI) SetupProject() { newNamespace := names.SimpleNameGenerator.GenerateName(fmt.Sprintf("e2e-test-%s-", c.kubeFramework.BaseName)) c.SetNamespace(newNamespace).ChangeUser(fmt.Sprintf("%s-user", newNamespace)) e2e.Logf("The user is now %q", c.Username()) e2e.Logf("Creating project %q", newNamespace) _, err := c.ProjectClient().Project().ProjectRequests().Create(&projectapi.ProjectRequest{ ObjectMeta: metav1.ObjectMeta{Name: newNamespace}, }) o.Expect(err).NotTo(o.HaveOccurred()) // TODO: remove when https://github.com/kubernetes/kubernetes/pull/62606 merges and is in origin c.namespacesToDelete = append(c.namespacesToDelete, newNamespace) e2e.Logf("Waiting on permissions in project %q ...", newNamespace) err = WaitForSelfSAR(1*time.Second, 60*time.Second, c.KubeClient(), authorizationapiv1.SelfSubjectAccessReviewSpec{ ResourceAttributes: &authorizationapiv1.ResourceAttributes{ Namespace: newNamespace, Verb: "create", Group: "", Resource: "pods", }, }) o.Expect(err).NotTo(o.HaveOccurred()) } // TeardownProject removes projects created by this test. func (c *CLI) TeardownProject() { if len(c.namespacesToDelete) > 0 { timeout := e2e.DefaultNamespaceDeletionTimeout if c.kubeFramework.NamespaceDeletionTimeout != 0 { timeout = c.kubeFramework.NamespaceDeletionTimeout } e2e.DeleteNamespaces(c.kubeFramework.ClientSet, c.namespacesToDelete, nil) e2e.WaitForNamespacesDeleted(c.kubeFramework.ClientSet, c.namespacesToDelete, timeout) } } // Verbose turns on printing verbose messages when executing OpenShift commands func (c *CLI) Verbose() *CLI { c.verbose = true return c } func (c *CLI) AppsClient() appsclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } client, err := appsclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AuthorizationClient() authorizationclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } client, err := authorizationclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) BuildClient() buildclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } client, err := buildclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) ImageClient() imageclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } client, err := imageclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) ProjectClient() projectclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } client, err := projectclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) RouteClient() routeclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } client, err := routeclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } // Client provides an OpenShift client for the current user. If the user is not // set, then it provides client for the cluster admin user func (c *CLI) TemplateClient() templateclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } client, err := templateclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) UserClient() userclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } client, err := userclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AdminAppsClient() appsclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := appsclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AdminAuthorizationClient() authorizationclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := authorizationclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AdminBuildClient() buildclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := buildclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AdminImageClient() imageclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := imageclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AdminProjectClient() projectclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := projectclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AdminRouteClient() routeclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := routeclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } // AdminClient provides an OpenShift client for the cluster admin user. func (c *CLI) AdminTemplateClient() templateclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := templateclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AdminUserClient() userclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := userclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } func (c *CLI) AdminSecurityClient() securityclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } client, err := securityclientset.NewForConfig(clientConfig) if err != nil { FatalErr(err) } return client } // KubeClient provides a Kubernetes client for the current namespace func (c *CLI) KubeClient() kclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } return kclientset.NewForConfigOrDie(clientConfig) } // KubeClient provides a Kubernetes client for the current namespace func (c *CLI) InternalKubeClient() kinternalclientset.Interface { clientConfig, err := configapi.GetClientConfig(c.configPath, nil) if err != nil { FatalErr(err) } return kinternalclientset.NewForConfigOrDie(clientConfig) } // AdminKubeClient provides a Kubernetes client for the cluster admin user. func (c *CLI) AdminKubeClient() kclientset.Interface { return kclientset.NewForConfigOrDie(c.AdminConfig()) } // AdminKubeClient provides a Kubernetes client for the cluster admin user. func (c *CLI) InternalAdminKubeClient() kinternalclientset.Interface { return kinternalclientset.NewForConfigOrDie(c.AdminConfig()) } func (c *CLI) AdminConfig() *restclient.Config { clientConfig, err := configapi.GetClientConfig(c.adminConfigPath, nil) if err != nil { FatalErr(err) } return clientConfig } // Namespace returns the name of the namespace used in the current test case. // If the namespace is not set, an empty string is returned. func (c *CLI) Namespace() string { if c.kubeFramework.Namespace == nil { return "" } return c.kubeFramework.Namespace.Name } // setOutput allows to override the default command output func (c *CLI) setOutput(out io.Writer) *CLI { c.stdout = out return c } // Run executes given OpenShift CLI command verb (iow. "oc <verb>"). // This function also override the default 'stdout' to redirect all output // to a buffer and prepare the global flags such as namespace and config path. func (c *CLI) Run(commands ...string) *CLI { in, out, errout := &bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{} nc := &CLI{ execPath: c.execPath, verb: commands[0], kubeFramework: c.KubeFramework(), adminConfigPath: c.adminConfigPath, configPath: c.configPath, username: c.username, outputDir: c.outputDir, globalArgs: append(commands, []string{ fmt.Sprintf("--config=%s", c.configPath), }...), } if !c.withoutNamespace { nc.globalArgs = append(nc.globalArgs, fmt.Sprintf("--namespace=%s", c.Namespace())) } nc.stdin, nc.stdout, nc.stderr = in, out, errout return nc.setOutput(c.stdout) } // Template sets a Go template for the OpenShift CLI command. // This is equivalent of running "oc get foo -o template --template='{{ .spec }}'" func (c *CLI) Template(t string) *CLI { if c.verb != "get" { FatalErr("Cannot use Template() for non-get verbs.") } templateArgs := []string{"--output=template", fmt.Sprintf("--template=%s", t)} commandArgs := append(c.commandArgs, templateArgs...) c.finalArgs = append(c.globalArgs, commandArgs...) return c } // InputString adds expected input to the command func (c *CLI) InputString(input string) *CLI { c.stdin.WriteString(input) return c } // Args sets the additional arguments for the OpenShift CLI command func (c *CLI) Args(args ...string) *CLI { c.commandArgs = args c.finalArgs = append(c.globalArgs, c.commandArgs...) return c } func (c *CLI) printCmd() string { return strings.Join(c.finalArgs, " ") } type ExitError struct { Cmd string StdErr string *exec.ExitError } // Output executes the command and returns stdout/stderr combined into one string func (c *CLI) Output() (string, error) { if c.verbose { fmt.Printf("DEBUG: oc %s\n", c.printCmd()) } cmd := exec.Command(c.execPath, c.finalArgs...) cmd.Stdin = c.stdin e2e.Logf("Running '%s %s'", c.execPath, strings.Join(c.finalArgs, " ")) out, err := cmd.CombinedOutput() trimmed := strings.TrimSpace(string(out)) switch err.(type) { case nil: c.stdout = bytes.NewBuffer(out) return trimmed, nil case *exec.ExitError: e2e.Logf("Error running %v:\n%s", cmd, trimmed) return trimmed, &ExitError{ExitError: err.(*exec.ExitError), Cmd: c.execPath + " " + strings.Join(c.finalArgs, " "), StdErr: trimmed} default: FatalErr(fmt.Errorf("unable to execute %q: %v", c.execPath, err)) // unreachable code return "", nil } } // Outputs executes the command and returns the stdout/stderr output as separate strings func (c *CLI) Outputs() (string, string, error) { if c.verbose { fmt.Printf("DEBUG: oc %s\n", c.printCmd()) } cmd := exec.Command(c.execPath, c.finalArgs...) cmd.Stdin = c.stdin e2e.Logf("Running '%s %s'", c.execPath, strings.Join(c.finalArgs, " ")) //out, err := cmd.CombinedOutput() var stdErrBuff, stdOutBuff bytes.Buffer cmd.Stdout = &stdOutBuff cmd.Stderr = &stdErrBuff err := cmd.Run() stdOutBytes := stdOutBuff.Bytes() stdErrBytes := stdErrBuff.Bytes() stdOut := strings.TrimSpace(string(stdOutBytes)) stdErr := strings.TrimSpace(string(stdErrBytes)) switch err.(type) { case nil: c.stdout = bytes.NewBuffer(stdOutBytes) c.stderr = bytes.NewBuffer(stdErrBytes) return stdOut, stdErr, nil case *exec.ExitError: e2e.Logf("Error running %v:\nStdOut>\n%s\nStdErr>\n%s\n", cmd, stdOut, stdErr) return stdOut, stdErr, err default: FatalErr(fmt.Errorf("unable to execute %q: %v", c.execPath, err)) // unreachable code return "", "", nil } } // Background executes the command in the background and returns the Cmd object // which may be killed later via cmd.Process.Kill(). It also returns buffers // holding the stdout & stderr of the command, which may be read from only after // calling cmd.Wait(). func (c *CLI) Background() (*exec.Cmd, *bytes.Buffer, *bytes.Buffer, error) { if c.verbose { fmt.Printf("DEBUG: oc %s\n", c.printCmd()) } cmd := exec.Command(c.execPath, c.finalArgs...) cmd.Stdin = c.stdin var stdout, stderr bytes.Buffer cmd.Stdout = bufio.NewWriter(&stdout) cmd.Stderr = bufio.NewWriter(&stderr) e2e.Logf("Running '%s %s'", c.execPath, strings.Join(c.finalArgs, " ")) err := cmd.Start() return cmd, &stdout, &stderr, err } // BackgroundRC executes the command in the background and returns the Cmd // object which may be killed later via cmd.Process.Kill(). It returns a // ReadCloser for stdout. If in doubt, use Background(). Consult the os/exec // documentation. func (c *CLI) BackgroundRC() (*exec.Cmd, io.ReadCloser, error) { if c.verbose { fmt.Printf("DEBUG: oc %s\n", c.printCmd()) } cmd := exec.Command(c.execPath, c.finalArgs...) cmd.Stdin = c.stdin stdout, err := cmd.StdoutPipe() if err != nil { return nil, nil, err } e2e.Logf("Running '%s %s'", c.execPath, strings.Join(c.finalArgs, " ")) err = cmd.Start() return cmd, stdout, err } // Stdout returns the current stdout writer func (c *CLI) Stdout() io.Writer { return c.stdout } // OutputToFile executes the command and store output to a file func (c *CLI) OutputToFile(filename string) (string, error) { content, err := c.Output() if err != nil { return "", err } path := filepath.Join(c.outputDir, c.Namespace()+"-"+filename) return path, ioutil.WriteFile(path, []byte(content), 0644) } // Execute executes the current command and return error if the execution failed // This function will set the default output to Ginkgo writer. func (c *CLI) Execute() error { out, err := c.Output() if _, err := io.Copy(g.GinkgoWriter, strings.NewReader(out+"\n")); err != nil { fmt.Fprintln(os.Stderr, "ERROR: Unable to copy the output to ginkgo writer") } os.Stdout.Sync() return err } // FatalErr exits the test in case a fatal error has occurred. func FatalErr(msg interface{}) { // the path that leads to this being called isn't always clear... fmt.Fprintln(g.GinkgoWriter, string(debug.Stack())) e2e.Failf("%v", msg) }
NewCLI
read_zip.rs
use crate::{ reader::{ArchiveReader, ArchiveReaderResult}, Archive, Error, }; use ara::ReadAt; use async_trait::async_trait; use std::io::Cursor; #[async_trait] pub trait AsyncReadZip { async fn read_zip(&self) -> Result<Archive, Error>; } #[async_trait] impl<T> AsyncReadZip for T where T: ReadAt, { async fn read_zip(&self) -> Result<Archive, Error>
}
{ let mut buf = vec![0u8; 1024]; let mut ar = ArchiveReader::new(self.len()); let archive = loop { if let Some(offset) = ar.wants_read() { let n = self.read_at(offset, &mut buf[..]).await?; let mut cursor = Cursor::new(&buf[..n]); ar.read(&mut cursor)?; } match ar.process()? { ArchiveReaderResult::Continue => continue, ArchiveReaderResult::Done(archive) => break archive, } }; Ok(archive) }
config.go
package update import ( "github.com/devspace-cloud/devspace/pkg/devspace/config/configutil" "github.com/devspace-cloud/devspace/pkg/util/log" "github.com/spf13/cobra" )
// newConfigCmd creates a new command func newConfigCmd() *cobra.Command { cmd := &configCmd{} configCmd := &cobra.Command{ Use: "config", Short: "Converts the active config to the current config version", Long: ` ####################################################### ############### devspace update config ################ ####################################################### Updates the currently active config to the newest config version Note: This does not upgrade the overwrite configs ####################################################### `, Args: cobra.NoArgs, Run: cmd.RunConfig, } return configCmd } // RunConfig executes the functionality "devspace update config" func (cmd *configCmd) RunConfig(cobraCmd *cobra.Command, args []string) { // Set config root configExists, err := configutil.SetDevSpaceRoot() if err != nil { log.Fatal(err) } if !configExists { log.Fatal("Couldn't find a DevSpace configuration. Please run `devspace init`") } // Get config configutil.GetConfigWithoutDefaults(false) // Save it err = configutil.SaveLoadedConfig() if err != nil { log.Fatalf("Error saving config: %v", err) } log.Infof("Successfully converted base config to current version") }
// configCmd holds the cmd flags type configCmd struct{}
serialize.js
module.exports = serializeElement function serializeElement(elem) { var strings = [] var tagname = elem.tagName if (elem.namespaceURI === "http://www.w3.org/1999/xhtml") { tagname = tagname.toLowerCase() } strings.push("<" + tagname + properties(elem) + datasetify(elem) + ">") if (elem.textContent) { strings.push(elem.textContent) } elem.childNodes.forEach(function (node) { strings.push(node.toString()) }) strings.push("</" + tagname + ">") return strings.join("") } function isProperty(elem, key) { var type = typeof elem[key] if (key === "style" && Object.keys(elem.style).length > 0) { return true } return elem.hasOwnProperty(key) && (type === "string" || type === "boolean" || type === "number") && key !== "nodeName" && key !== "className" && key !== "tagName" && key !== "textContent" && key !== "namespaceURI" } function stylify(styles) { var attr = "" Object.keys(styles).forEach(function (key) { var value = styles[key] attr += key + ":" + value + ";" }) return attr } function datasetify(elem) { var ds = elem.dataset var props = [] for (var key in ds) { props.push({ name: "data-" + key, value: ds[key] }) } return props.length ? stringify(props) : "" } function
(list) { var attributes = [] list.forEach(function (tuple) { var name = tuple.name var value = tuple.value if (name === "style") { value = stylify(value) } attributes.push(name + "=" + "\"" + value + "\"") }) return attributes.length ? " " + attributes.join(" ") : "" } function properties(elem) { var props = [] for (var key in elem) { if (isProperty(elem, key)) { props.push({ name: key, value: elem[key] }) } } for (var ns in elem._attributes) { for (var attribute in elem._attributes[ns]) { var name = (ns !== "null" ? ns + ":" : "") + attribute props.push({ name: name, value: elem._attributes[ns][attribute] }) } } if (elem.className) { props.push({ name: "class", value: elem.className }) } return props.length ? stringify(props) : "" }
stringify
virtualmachineimagetemplates.go
package virtualmachineimagebuilder // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // VirtualMachineImageTemplatesClient is the azure Virtual Machine Image Builder Client type VirtualMachineImageTemplatesClient struct { BaseClient } // NewVirtualMachineImageTemplatesClient creates an instance of the VirtualMachineImageTemplatesClient client. func NewVirtualMachineImageTemplatesClient(subscriptionID string) VirtualMachineImageTemplatesClient { return NewVirtualMachineImageTemplatesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewVirtualMachineImageTemplatesClientWithBaseURI creates an instance of the VirtualMachineImageTemplatesClient // client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI // (sovereign clouds, Azure stack). func NewVirtualMachineImageTemplatesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineImageTemplatesClient { return VirtualMachineImageTemplatesClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate create or update a virtual machine image template // Parameters: // parameters - parameters supplied to the CreateImageTemplate operation // resourceGroupName - the name of the resource group. // imageTemplateName - the name of the image Template func (client VirtualMachineImageTemplatesClient) CreateOrUpdate(ctx context.Context, parameters ImageTemplate, resourceGroupName string, imageTemplateName string) (result VirtualMachineImageTemplatesCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.CreateOrUpdate") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.ImageTemplateProperties", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.ImageTemplateProperties.Source", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.ImageTemplateProperties.Distribute", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.ImageTemplateProperties.BuildTimeoutInMinutes", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.ImageTemplateProperties.BuildTimeoutInMinutes", Name: validation.InclusiveMaximum, Rule: int64(960), Chain: nil}, {Target: "parameters.ImageTemplateProperties.BuildTimeoutInMinutes", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, }}, }}}}, {TargetValue: imageTemplateName, Constraints: []validation.Constraint{{Target: "imageTemplateName", Name: validation.Pattern, Rule: `^[A-Za-z0-9-_.]{1,64}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "CreateOrUpdate", err.Error()) } req, err := client.CreateOrUpdatePreparer(ctx, parameters, resourceGroupName, imageTemplateName) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client VirtualMachineImageTemplatesClient) CreateOrUpdatePreparer(ctx context.Context, parameters ImageTemplate, resourceGroupName string, imageTemplateName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "imageTemplateName": autorest.Encode("path", imageTemplateName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VirtualMachineImages/imageTemplates/{imageTemplateName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) }
var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) CreateOrUpdateResponder(resp *http.Response) (result ImageTemplate, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete delete a virtual machine image template // Parameters: // resourceGroupName - the name of the resource group. // imageTemplateName - the name of the image Template func (client VirtualMachineImageTemplatesClient) Delete(ctx context.Context, resourceGroupName string, imageTemplateName string) (result VirtualMachineImageTemplatesDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: imageTemplateName, Constraints: []validation.Constraint{{Target: "imageTemplateName", Name: validation.Pattern, Rule: `^[A-Za-z0-9-_.]{1,64}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Delete", err.Error()) } req, err := client.DeletePreparer(ctx, resourceGroupName, imageTemplateName) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client VirtualMachineImageTemplatesClient) DeletePreparer(ctx context.Context, resourceGroupName string, imageTemplateName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "imageTemplateName": autorest.Encode("path", imageTemplateName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VirtualMachineImages/imageTemplates/{imageTemplateName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) DeleteSender(req *http.Request) (future VirtualMachineImageTemplatesDeleteFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get get information about a virtual machine image template // Parameters: // resourceGroupName - the name of the resource group. // imageTemplateName - the name of the image Template func (client VirtualMachineImageTemplatesClient) Get(ctx context.Context, resourceGroupName string, imageTemplateName string) (result ImageTemplate, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: imageTemplateName, Constraints: []validation.Constraint{{Target: "imageTemplateName", Name: validation.Pattern, Rule: `^[A-Za-z0-9-_.]{1,64}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, imageTemplateName) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client VirtualMachineImageTemplatesClient) GetPreparer(ctx context.Context, resourceGroupName string, imageTemplateName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "imageTemplateName": autorest.Encode("path", imageTemplateName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VirtualMachineImages/imageTemplates/{imageTemplateName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) GetResponder(resp *http.Response) (result ImageTemplate, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // GetRunOutput get the specified run output for the specified image template resource // Parameters: // resourceGroupName - the name of the resource group. // imageTemplateName - the name of the image Template // runOutputName - the name of the run output func (client VirtualMachineImageTemplatesClient) GetRunOutput(ctx context.Context, resourceGroupName string, imageTemplateName string, runOutputName string) (result RunOutput, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.GetRunOutput") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: imageTemplateName, Constraints: []validation.Constraint{{Target: "imageTemplateName", Name: validation.Pattern, Rule: `^[A-Za-z0-9-_.]{1,64}$`, Chain: nil}}}, {TargetValue: runOutputName, Constraints: []validation.Constraint{{Target: "runOutputName", Name: validation.Pattern, Rule: `^[A-Za-z0-9-_.]{1,64}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "GetRunOutput", err.Error()) } req, err := client.GetRunOutputPreparer(ctx, resourceGroupName, imageTemplateName, runOutputName) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "GetRunOutput", nil, "Failure preparing request") return } resp, err := client.GetRunOutputSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "GetRunOutput", resp, "Failure sending request") return } result, err = client.GetRunOutputResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "GetRunOutput", resp, "Failure responding to request") } return } // GetRunOutputPreparer prepares the GetRunOutput request. func (client VirtualMachineImageTemplatesClient) GetRunOutputPreparer(ctx context.Context, resourceGroupName string, imageTemplateName string, runOutputName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "imageTemplateName": autorest.Encode("path", imageTemplateName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "runOutputName": autorest.Encode("path", runOutputName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VirtualMachineImages/imageTemplates/{imageTemplateName}/runOutputs/{runOutputName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetRunOutputSender sends the GetRunOutput request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) GetRunOutputSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetRunOutputResponder handles the response to the GetRunOutput request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) GetRunOutputResponder(resp *http.Response) (result RunOutput, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets information about the VM image templates associated with the subscription. func (client VirtualMachineImageTemplatesClient) List(ctx context.Context) (result ImageTemplateListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.List") defer func() { sc := -1 if result.itlr.Response.Response != nil { sc = result.itlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.itlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "List", resp, "Failure sending request") return } result.itlr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client VirtualMachineImageTemplatesClient) ListPreparer(ctx context.Context) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.VirtualMachineImages/imageTemplates", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) ListResponder(resp *http.Response) (result ImageTemplateListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client VirtualMachineImageTemplatesClient) listNextResults(ctx context.Context, lastResults ImageTemplateListResult) (result ImageTemplateListResult, err error) { req, err := lastResults.imageTemplateListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client VirtualMachineImageTemplatesClient) ListComplete(ctx context.Context) (result ImageTemplateListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx) return } // ListByResourceGroup gets information about the VM image templates associated with the specified resource group. // Parameters: // resourceGroupName - the name of the resource group. func (client VirtualMachineImageTemplatesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ImageTemplateListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.ListByResourceGroup") defer func() { sc := -1 if result.itlr.Response.Response != nil { sc = result.itlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listByResourceGroupNextResults req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "ListByResourceGroup", nil, "Failure preparing request") return } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.itlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "ListByResourceGroup", resp, "Failure sending request") return } result.itlr, err = client.ListByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "ListByResourceGroup", resp, "Failure responding to request") } return } // ListByResourceGroupPreparer prepares the ListByResourceGroup request. func (client VirtualMachineImageTemplatesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VirtualMachineImages/imageTemplates", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) ListByResourceGroupResponder(resp *http.Response) (result ImageTemplateListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByResourceGroupNextResults retrieves the next set of results, if any. func (client VirtualMachineImageTemplatesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ImageTemplateListResult) (result ImageTemplateListResult, err error) { req, err := lastResults.imageTemplateListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") } result, err = client.ListByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") } return } // ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. func (client VirtualMachineImageTemplatesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ImageTemplateListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.ListByResourceGroup") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) return } // ListRunOutputs list all run outputs for the specified Image Template resource // Parameters: // resourceGroupName - the name of the resource group. // imageTemplateName - the name of the image Template func (client VirtualMachineImageTemplatesClient) ListRunOutputs(ctx context.Context, resourceGroupName string, imageTemplateName string) (result RunOutputCollectionPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.ListRunOutputs") defer func() { sc := -1 if result.roc.Response.Response != nil { sc = result.roc.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: imageTemplateName, Constraints: []validation.Constraint{{Target: "imageTemplateName", Name: validation.Pattern, Rule: `^[A-Za-z0-9-_.]{1,64}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "ListRunOutputs", err.Error()) } result.fn = client.listRunOutputsNextResults req, err := client.ListRunOutputsPreparer(ctx, resourceGroupName, imageTemplateName) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "ListRunOutputs", nil, "Failure preparing request") return } resp, err := client.ListRunOutputsSender(req) if err != nil { result.roc.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "ListRunOutputs", resp, "Failure sending request") return } result.roc, err = client.ListRunOutputsResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "ListRunOutputs", resp, "Failure responding to request") } return } // ListRunOutputsPreparer prepares the ListRunOutputs request. func (client VirtualMachineImageTemplatesClient) ListRunOutputsPreparer(ctx context.Context, resourceGroupName string, imageTemplateName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "imageTemplateName": autorest.Encode("path", imageTemplateName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VirtualMachineImages/imageTemplates/{imageTemplateName}/runOutputs", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListRunOutputsSender sends the ListRunOutputs request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) ListRunOutputsSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListRunOutputsResponder handles the response to the ListRunOutputs request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) ListRunOutputsResponder(resp *http.Response) (result RunOutputCollection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listRunOutputsNextResults retrieves the next set of results, if any. func (client VirtualMachineImageTemplatesClient) listRunOutputsNextResults(ctx context.Context, lastResults RunOutputCollection) (result RunOutputCollection, err error) { req, err := lastResults.runOutputCollectionPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listRunOutputsNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListRunOutputsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listRunOutputsNextResults", resp, "Failure sending next results request") } result, err = client.ListRunOutputsResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "listRunOutputsNextResults", resp, "Failure responding to next results request") } return } // ListRunOutputsComplete enumerates all values, automatically crossing page boundaries as required. func (client VirtualMachineImageTemplatesClient) ListRunOutputsComplete(ctx context.Context, resourceGroupName string, imageTemplateName string) (result RunOutputCollectionIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.ListRunOutputs") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListRunOutputs(ctx, resourceGroupName, imageTemplateName) return } // Run create artifacts from a existing image template // Parameters: // resourceGroupName - the name of the resource group. // imageTemplateName - the name of the image Template func (client VirtualMachineImageTemplatesClient) Run(ctx context.Context, resourceGroupName string, imageTemplateName string) (result VirtualMachineImageTemplatesRunFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.Run") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: imageTemplateName, Constraints: []validation.Constraint{{Target: "imageTemplateName", Name: validation.Pattern, Rule: `^[A-Za-z0-9-_.]{1,64}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Run", err.Error()) } req, err := client.RunPreparer(ctx, resourceGroupName, imageTemplateName) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Run", nil, "Failure preparing request") return } result, err = client.RunSender(req) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Run", result.Response(), "Failure sending request") return } return } // RunPreparer prepares the Run request. func (client VirtualMachineImageTemplatesClient) RunPreparer(ctx context.Context, resourceGroupName string, imageTemplateName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "imageTemplateName": autorest.Encode("path", imageTemplateName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VirtualMachineImages/imageTemplates/{imageTemplateName}/run", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RunSender sends the Run request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) RunSender(req *http.Request) (future VirtualMachineImageTemplatesRunFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // RunResponder handles the response to the Run request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) RunResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Update update the tags for this Virtual Machine Image Template // Parameters: // parameters - additional parameters for Image Template update. // resourceGroupName - the name of the resource group. // imageTemplateName - the name of the image Template func (client VirtualMachineImageTemplatesClient) Update(ctx context.Context, parameters ImageTemplateUpdateParameters, resourceGroupName string, imageTemplateName string) (result VirtualMachineImageTemplatesUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineImageTemplatesClient.Update") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: imageTemplateName, Constraints: []validation.Constraint{{Target: "imageTemplateName", Name: validation.Pattern, Rule: `^[A-Za-z0-9-_.]{1,64}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Update", err.Error()) } req, err := client.UpdatePreparer(ctx, parameters, resourceGroupName, imageTemplateName) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Update", nil, "Failure preparing request") return } result, err = client.UpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "virtualmachineimagebuilder.VirtualMachineImageTemplatesClient", "Update", result.Response(), "Failure sending request") return } return } // UpdatePreparer prepares the Update request. func (client VirtualMachineImageTemplatesClient) UpdatePreparer(ctx context.Context, parameters ImageTemplateUpdateParameters, resourceGroupName string, imageTemplateName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "imageTemplateName": autorest.Encode("path", imageTemplateName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-05-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VirtualMachineImages/imageTemplates/{imageTemplateName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) UpdateSender(req *http.Request) (future VirtualMachineImageTemplatesUpdateFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client VirtualMachineImageTemplatesClient) UpdateResponder(resp *http.Response) (result ImageTemplate, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImageTemplatesClient) CreateOrUpdateSender(req *http.Request) (future VirtualMachineImageTemplatesCreateOrUpdateFuture, err error) {
constant.js
var keyup = "keyup"; var change = "change"; var MODELFLAG_PICKED = 1 << 1; var MODELFLAG_HIDDEN = 1 << 2; var MODELFLAG_LOCKED = 1 << 3; var MODELFLAG_FORCE_UPDATE = 1 << 4; function ArrayPushIfNotHas(arr, element) { if (arr && element && arr.indexOf(element) == -1) { arr.push(element); return true; } else return false; } function getParameterByName(name) { if (!location || !location.search) return undefined; return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null; } //# sourceURL=file://ui/global/constant.js
var click = "click"; var keydown = "keydown"; var keypress = "keypress";
hb16cfg4.rs
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::HB16CFG4 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = "Possible values of the field `EPI_HB16CFG4_MODE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG4_MODER { #[doc = "ADMUX - AD\\[15:0\\]"] EPI_HB16CFG4_MODE_ADMUX, #[doc = "ADNONMUX - D\\[15:0\\]"] EPI_HB16CFG4_MODE_AD, #[doc = r"Reserved"] _Reserved(u8), } impl EPI_HB16CFG4_MODER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_ADMUX => 0, EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_AD => 1, EPI_HB16CFG4_MODER::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EPI_HB16CFG4_MODER { match value { 0 => EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_ADMUX, 1 => EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_AD, i => EPI_HB16CFG4_MODER::_Reserved(i), } } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_MODE_ADMUX`"] #[inline(always)] pub fn is_epi_hb16cfg4_mode_admux(&self) -> bool { *self == EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_ADMUX } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_MODE_AD`"] #[inline(always)] pub fn is_epi_hb16cfg4_mode_ad(&self) -> bool { *self == EPI_HB16CFG4_MODER::EPI_HB16CFG4_MODE_AD } } #[doc = "Values that can be written to the field `EPI_HB16CFG4_MODE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG4_MODEW { #[doc = "ADMUX - AD\\[15:0\\]"] EPI_HB16CFG4_MODE_ADMUX, #[doc = "ADNONMUX - D\\[15:0\\]"] EPI_HB16CFG4_MODE_AD, } impl EPI_HB16CFG4_MODEW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EPI_HB16CFG4_MODEW::EPI_HB16CFG4_MODE_ADMUX => 0, EPI_HB16CFG4_MODEW::EPI_HB16CFG4_MODE_AD => 1, } } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_MODEW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_MODEW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EPI_HB16CFG4_MODEW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "ADMUX - AD\\[15:0\\]"] #[inline(always)] pub fn epi_hb16cfg4_mode_admux(self) -> &'a mut W { self.variant(EPI_HB16CFG4_MODEW::EPI_HB16CFG4_MODE_ADMUX) } #[doc = "ADNONMUX - D\\[15:0\\]"] #[inline(always)] pub fn epi_hb16cfg4_mode_ad(self) -> &'a mut W { self.variant(EPI_HB16CFG4_MODEW::EPI_HB16CFG4_MODE_AD) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 0); self.w.bits |= ((value as u32) & 3) << 0; self.w } } #[doc = "Possible values of the field `EPI_HB16CFG4_RDWS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG4_RDWSR { #[doc = "Active RDn is 2 EPI clocks"] EPI_HB16CFG4_RDWS_2, #[doc = "Active RDn is 4 EPI clocks"] EPI_HB16CFG4_RDWS_4, #[doc = "Active RDn is 6 EPI clocks"] EPI_HB16CFG4_RDWS_6, #[doc = "Active RDn is 8 EPI clocks"] EPI_HB16CFG4_RDWS_8, } impl EPI_HB16CFG4_RDWSR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_2 => 0, EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_4 => 1, EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_6 => 2, EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_8 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EPI_HB16CFG4_RDWSR { match value { 0 => EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_2, 1 => EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_4, 2 => EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_6, 3 => EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_RDWS_2`"] #[inline(always)] pub fn is_epi_hb16cfg4_rdws_2(&self) -> bool { *self == EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_2 } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_RDWS_4`"] #[inline(always)] pub fn is_epi_hb16cfg4_rdws_4(&self) -> bool { *self == EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_4 } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_RDWS_6`"] #[inline(always)] pub fn is_epi_hb16cfg4_rdws_6(&self) -> bool { *self == EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_6 } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_RDWS_8`"] #[inline(always)] pub fn is_epi_hb16cfg4_rdws_8(&self) -> bool { *self == EPI_HB16CFG4_RDWSR::EPI_HB16CFG4_RDWS_8 } } #[doc = "Values that can be written to the field `EPI_HB16CFG4_RDWS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG4_RDWSW { #[doc = "Active RDn is 2 EPI clocks"] EPI_HB16CFG4_RDWS_2, #[doc = "Active RDn is 4 EPI clocks"] EPI_HB16CFG4_RDWS_4, #[doc = "Active RDn is 6 EPI clocks"] EPI_HB16CFG4_RDWS_6, #[doc = "Active RDn is 8 EPI clocks"] EPI_HB16CFG4_RDWS_8, } impl EPI_HB16CFG4_RDWSW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_2 => 0, EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_4 => 1, EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_6 => 2, EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_8 => 3, } } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_RDWSW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_RDWSW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EPI_HB16CFG4_RDWSW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Active RDn is 2 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg4_rdws_2(self) -> &'a mut W { self.variant(EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_2) } #[doc = "Active RDn is 4 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg4_rdws_4(self) -> &'a mut W { self.variant(EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_4) } #[doc = "Active RDn is 6 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg4_rdws_6(self) -> &'a mut W { self.variant(EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_6) } #[doc = "Active RDn is 8 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg4_rdws_8(self) -> &'a mut W { self.variant(EPI_HB16CFG4_RDWSW::EPI_HB16CFG4_RDWS_8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 4); self.w.bits |= ((value as u32) & 3) << 4; self.w } } #[doc = "Possible values of the field `EPI_HB16CFG4_WRWS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG4_WRWSR { #[doc = "Active WRn is 2 EPI clocks"] EPI_HB16CFG4_WRWS_2, #[doc = "Active WRn is 4 EPI clocks"] EPI_HB16CFG4_WRWS_4, #[doc = "Active WRn is 6 EPI clocks"] EPI_HB16CFG4_WRWS_6, #[doc = "Active WRn is 8 EPI clocks"] EPI_HB16CFG4_WRWS_8, } impl EPI_HB16CFG4_WRWSR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_2 => 0, EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_4 => 1, EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_6 => 2, EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_8 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EPI_HB16CFG4_WRWSR { match value { 0 => EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_2, 1 => EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_4, 2 => EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_6, 3 => EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_WRWS_2`"] #[inline(always)] pub fn is_epi_hb16cfg4_wrws_2(&self) -> bool { *self == EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_2 } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_WRWS_4`"] #[inline(always)] pub fn is_epi_hb16cfg4_wrws_4(&self) -> bool { *self == EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_4 } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_WRWS_6`"] #[inline(always)] pub fn is_epi_hb16cfg4_wrws_6(&self) -> bool { *self == EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_6 } #[doc = "Checks if the value of the field is `EPI_HB16CFG4_WRWS_8`"] #[inline(always)] pub fn is_epi_hb16cfg4_wrws_8(&self) -> bool { *self == EPI_HB16CFG4_WRWSR::EPI_HB16CFG4_WRWS_8 } } #[doc = "Values that can be written to the field `EPI_HB16CFG4_WRWS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16CFG4_WRWSW { #[doc = "Active WRn is 2 EPI clocks"] EPI_HB16CFG4_WRWS_2, #[doc = "Active WRn is 4 EPI clocks"] EPI_HB16CFG4_WRWS_4, #[doc = "Active WRn is 6 EPI clocks"] EPI_HB16CFG4_WRWS_6, #[doc = "Active WRn is 8 EPI clocks"] EPI_HB16CFG4_WRWS_8, } impl EPI_HB16CFG4_WRWSW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_2 => 0, EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_4 => 1, EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_6 => 2, EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_8 => 3, } } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_WRWSW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_WRWSW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EPI_HB16CFG4_WRWSW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Active WRn is 2 EPI clocks"]
self.variant(EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_2) } #[doc = "Active WRn is 4 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg4_wrws_4(self) -> &'a mut W { self.variant(EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_4) } #[doc = "Active WRn is 6 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg4_wrws_6(self) -> &'a mut W { self.variant(EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_6) } #[doc = "Active WRn is 8 EPI clocks"] #[inline(always)] pub fn epi_hb16cfg4_wrws_8(self) -> &'a mut W { self.variant(EPI_HB16CFG4_WRWSW::EPI_HB16CFG4_WRWS_8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 6); self.w.bits |= ((value as u32) & 3) << 6; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG4_BURSTR { bits: bool, } impl EPI_HB16CFG4_BURSTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_BURSTW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_BURSTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 16); self.w.bits |= ((value as u32) & 1) << 16; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG4_RDCRER { bits: bool, } impl EPI_HB16CFG4_RDCRER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_RDCREW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_RDCREW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 17); self.w.bits |= ((value as u32) & 1) << 17; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG4_WRCRER { bits: bool, } impl EPI_HB16CFG4_WRCRER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_WRCREW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_WRCREW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 18); self.w.bits |= ((value as u32) & 1) << 18; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG4_ALEHIGHR { bits: bool, } impl EPI_HB16CFG4_ALEHIGHR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_ALEHIGHW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_ALEHIGHW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 19); self.w.bits |= ((value as u32) & 1) << 19; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG4_RDHIGHR { bits: bool, } impl EPI_HB16CFG4_RDHIGHR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_RDHIGHW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_RDHIGHW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 20); self.w.bits |= ((value as u32) & 1) << 20; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16CFG4_WRHIGHR { bits: bool, } impl EPI_HB16CFG4_WRHIGHR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16CFG4_WRHIGHW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16CFG4_WRHIGHW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 21); self.w.bits |= ((value as u32) & 1) << 21; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:1 - CS3n Host Bus Sub-Mode"] #[inline(always)] pub fn epi_hb16cfg4_mode(&self) -> EPI_HB16CFG4_MODER { EPI_HB16CFG4_MODER::_from(((self.bits >> 0) & 3) as u8) } #[doc = "Bits 4:5 - CS3n Read Wait States"] #[inline(always)] pub fn epi_hb16cfg4_rdws(&self) -> EPI_HB16CFG4_RDWSR { EPI_HB16CFG4_RDWSR::_from(((self.bits >> 4) & 3) as u8) } #[doc = "Bits 6:7 - CS3n Write Wait States"] #[inline(always)] pub fn epi_hb16cfg4_wrws(&self) -> EPI_HB16CFG4_WRWSR { EPI_HB16CFG4_WRWSR::_from(((self.bits >> 6) & 3) as u8) } #[doc = "Bit 16 - CS3n Burst Mode"] #[inline(always)] pub fn epi_hb16cfg4_burst(&self) -> EPI_HB16CFG4_BURSTR { let bits = ((self.bits >> 16) & 1) != 0; EPI_HB16CFG4_BURSTR { bits } } #[doc = "Bit 17 - CS3n PSRAM Configuration Register Read"] #[inline(always)] pub fn epi_hb16cfg4_rdcre(&self) -> EPI_HB16CFG4_RDCRER { let bits = ((self.bits >> 17) & 1) != 0; EPI_HB16CFG4_RDCRER { bits } } #[doc = "Bit 18 - CS3n PSRAM Configuration Register Write"] #[inline(always)] pub fn epi_hb16cfg4_wrcre(&self) -> EPI_HB16CFG4_WRCRER { let bits = ((self.bits >> 18) & 1) != 0; EPI_HB16CFG4_WRCRER { bits } } #[doc = "Bit 19 - CS3n ALE Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg4_alehigh(&self) -> EPI_HB16CFG4_ALEHIGHR { let bits = ((self.bits >> 19) & 1) != 0; EPI_HB16CFG4_ALEHIGHR { bits } } #[doc = "Bit 20 - CS3n READ Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg4_rdhigh(&self) -> EPI_HB16CFG4_RDHIGHR { let bits = ((self.bits >> 20) & 1) != 0; EPI_HB16CFG4_RDHIGHR { bits } } #[doc = "Bit 21 - CS3n WRITE Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg4_wrhigh(&self) -> EPI_HB16CFG4_WRHIGHR { let bits = ((self.bits >> 21) & 1) != 0; EPI_HB16CFG4_WRHIGHR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:1 - CS3n Host Bus Sub-Mode"] #[inline(always)] pub fn epi_hb16cfg4_mode(&mut self) -> _EPI_HB16CFG4_MODEW { _EPI_HB16CFG4_MODEW { w: self } } #[doc = "Bits 4:5 - CS3n Read Wait States"] #[inline(always)] pub fn epi_hb16cfg4_rdws(&mut self) -> _EPI_HB16CFG4_RDWSW { _EPI_HB16CFG4_RDWSW { w: self } } #[doc = "Bits 6:7 - CS3n Write Wait States"] #[inline(always)] pub fn epi_hb16cfg4_wrws(&mut self) -> _EPI_HB16CFG4_WRWSW { _EPI_HB16CFG4_WRWSW { w: self } } #[doc = "Bit 16 - CS3n Burst Mode"] #[inline(always)] pub fn epi_hb16cfg4_burst(&mut self) -> _EPI_HB16CFG4_BURSTW { _EPI_HB16CFG4_BURSTW { w: self } } #[doc = "Bit 17 - CS3n PSRAM Configuration Register Read"] #[inline(always)] pub fn epi_hb16cfg4_rdcre(&mut self) -> _EPI_HB16CFG4_RDCREW { _EPI_HB16CFG4_RDCREW { w: self } } #[doc = "Bit 18 - CS3n PSRAM Configuration Register Write"] #[inline(always)] pub fn epi_hb16cfg4_wrcre(&mut self) -> _EPI_HB16CFG4_WRCREW { _EPI_HB16CFG4_WRCREW { w: self } } #[doc = "Bit 19 - CS3n ALE Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg4_alehigh(&mut self) -> _EPI_HB16CFG4_ALEHIGHW { _EPI_HB16CFG4_ALEHIGHW { w: self } } #[doc = "Bit 20 - CS3n READ Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg4_rdhigh(&mut self) -> _EPI_HB16CFG4_RDHIGHW { _EPI_HB16CFG4_RDHIGHW { w: self } } #[doc = "Bit 21 - CS3n WRITE Strobe Polarity"] #[inline(always)] pub fn epi_hb16cfg4_wrhigh(&mut self) -> _EPI_HB16CFG4_WRHIGHW { _EPI_HB16CFG4_WRHIGHW { w: self } } }
#[inline(always)] pub fn epi_hb16cfg4_wrws_2(self) -> &'a mut W {
WarningIcon.js
import _mergeJSXProps from "babel-helper-vue-jsx-merge-props"; export default { name: 'WarningIcon', props: {}, functional: true, render: function render(h, ctx) { var attrs = ctx.data.attrs || {}; ctx.data.attrs = attrs;
xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 18" }, "class": "c-ficon c-ficon--warning" }, ctx.data]), [h("path", { attrs: { "fill-rule": "evenodd", d: "M19.8 15.3c.6 1-.2 2.5-1.5 2.5H1.7c-1.3 0-2.1-1.4-1.5-2.5L8.6.8a1.7 1.7 0 012.8 0l8.4 14.5zm-9.8-3a1.6 1.6 0 100 3.2 1.6 1.6 0 000-3.2zM8.5 6.5l.2 4.8a.4.4 0 00.5.4h1.6a.4.4 0 00.5-.4l.2-4.8a.4.4 0 00-.4-.4H8.9c-.2 0-.4.2-.4.5z" } })]); } };
return h("svg", _mergeJSXProps([{ attrs: {
_routes_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class RoutesOperations: """RoutesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2017_06_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _delete_initial( self, resource_group_name: str, route_table_name: str, route_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-06-01" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore async def begin_delete( self, resource_group_name: str, route_table_name: str, route_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes the specified route from a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, route_table_name=route_table_name, route_name=route_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore async def get( self, resource_group_name: str, route_table_name: str, route_name: str, **kwargs ) -> "models.Route": """Gets the specified route from a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Route, or the result of cls(response) :rtype: ~azure.mgmt.network.v2017_06_01.models.Route :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.Route"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-06-01" accept = "application/json, text/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Route', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, route_table_name: str, route_name: str, route_parameters: "models.Route", **kwargs ) -> "models.Route": cls = kwargs.pop('cls', None) # type: ClsType["models.Route"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-06-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json, text/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(route_parameters, 'Route') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('Route', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('Route', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, route_table_name: str, route_name: str, route_parameters: "models.Route", **kwargs ) -> AsyncLROPoller["models.Route"]: """Creates or updates a route in the specified route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :param route_parameters: Parameters supplied to the create or update route operation. :type route_parameters: ~azure.mgmt.network.v2017_06_01.models.Route :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either Route or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2017_06_01.models.Route] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["models.Route"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, route_table_name=route_table_name, route_name=route_name, route_parameters=route_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('Route', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} # type: ignore def list( self, resource_group_name: str, route_table_name: str, **kwargs ) -> AsyncIterable["models.RouteListResult"]: """Gets all routes in a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either RouteListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2017_06_01.models.RouteListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.RouteListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-06-01" accept = "application/json, text/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('RouteListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None):
return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes'} # type: ignore
request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response
package.py
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class
(MakefilePackage): """DPDK is a set of libraries and drivers for fast packet processing. It supports many processor architectures and both FreeBSD and Linux.""" homepage = "https://github.com/DPDK/dpdk" url = "https://github.com/DPDK/dpdk/archive/v19.11.tar.gz" version('20.02', sha256='29e56ea8e47e30110ecb881fa5a37125a865dd2d45b61f68e93e334caaab16b7') version('19.11', sha256='ce1befb20a5e5c5399b326a39cfa23314a5229c0ced2553f53b09b1ae630706b') version('19.08', sha256='1ceff1a6f4f8d5f6f62c1682097249227ac5225ccd9638e0af09f5411c681038') version('19.05', sha256='5fea95cb726e6adaa506dab330e79563ccd4dacf03f126c826aabdced605d32b') version('19.02', sha256='04885d32c86fff5aefcfffdb8257fed405233602dbcd22f8298be13c2e285a50') conflicts('target=aarch64:', msg='DPDK is not supported on aarch64.') depends_on('numactl') def build(self, spec, prefix): make('defconfig') make() def install(self, spec, prefix): install_tree('.', prefix)
Dpdk
real_facts.py
import random from ansible.module_utils.basic import AnsibleModule ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: real_facts short_description: A module that dishes out the true facts. version_added: "2.8" description: - "A module that dishes out the true facts." options: name: default: Jane Doe author: - David Newswanger (@newswangerd) ''' EXAMPLES = ''' # Pass in a message - name: Test with a message real_facts: name: David Newswanger ''' RETURN = ''' fact: description: Actual facts type: str sample: Jane Doe is a smart cookie. ''' FACTS = [ "{name} is looking great today!", "{name} is a smart cookie.", "I’d choose {name}'s company over pizza anytime." ] def run_module(): # define available arguments/parameters a user can pass to the module module_args = dict( name=dict(type='str', default='Jane Doe'), ) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) result = dict( changed=False, fact='' )
) if module.check_mode: return result module.exit_json(**result) def main(): run_module() if __name__ == '__main__': main()
result['fact'] = random.choice(FACTS).format( name=module.params['name']
globvars.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: globvars.py # Author: Yuxin Wu <[email protected]> import six import argparse __all__ = ['globalns', 'use_global_argument'] if six.PY2: class NS: pass else: import types NS = types.SimpleNamespace globalns = NS() def
(args): """ Add the content of :class:`argparse.Namespace` to globalns. Args: args (argparse.Namespace): arguments """ assert isinstance(args, argparse.Namespace), type(args) for k, v in six.iteritems(vars(args)): setattr(globalns, k, v)
use_global_argument